diff --git a/README.md b/README.md index 786f6bfc3d..5986602286 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ A gamepad is recommended ([Controls](#controls)). The game folder is never modif | **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 | | **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`) | +| **DirectStorage** | ✅ | the console's DirectStorage queues: file and memory sources, queued event notifications, 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`) | @@ -176,6 +176,7 @@ A **gamepad is recommended**: console games are made for one, and their menus an - **Gamepad:** any controller Windows sees through XInput (Xbox controllers, wired or wireless) is the game's gamepad – buttons, sticks, triggers and rumble. It can be plugged in or out while the game runs. + GameInput keeps half a second of recent state changes so titles can read inputs between frames. - **PlayStation controllers** (DualShock 4 wired or over Bluetooth, DualSense wired) are the gamepad when no XInput controller is connected – buttons, sticks and triggers, no rumble or light bar. `XCL_PLAYSTATION_PAD=0` turns this off. @@ -232,6 +233,20 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder
Switches, caches, logs and the files XCL writes +- When a game folder contains a `shaders.rpf` shader pack or loose `.dxbc` files under + `shaders/`, XCL shows shader preparation in the game window before executing title code. + The same window then presents the game. The percentage counts + processed records. The timer counts seconds since one finished (or preparation started); + five seconds without progress counts as a stall, and the window shows when the last one ended. + XCL prepares supported shader stages and compute pipelines, including + split pieces and their whole fallback. Graphics pipelines are created during play the first + time; the ones a run used are recorded with their state (`used-graphics-pipelines.bin` beside + the shader cache, at most `XCL_GFX_RECORDS_MB`, default 64) and built before the title starts + on the next launch, with their driver blobs kept, so the title makes them from those in + milliseconds. `XCL_PREPARE_GRAPHICS=0` leaves that pass out. Later launches reuse matching cache entries. + If a preparation worker fails, XCL retries its batch once after the other workers finish. + Closing the window cancels the launch. A compiler or driver failure stops it and reports + the cause. Null-renderer runs skip shader preparation. With presentation disabled, the gate runs without a window. - **`--pipelines` size cap**: a compute program whose DXIL is over 8 MiB and that has no saved blob is left to the runtime instead of being compiled in the pass — those compiles take tens of minutes and gigabytes and stopped the pass on the biggest programs. `XCL_PIPELINE_MAX_KB` @@ -277,6 +292,8 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder `XCL_PSO_TRACE=1` logs every driver compile. A huge compute program the driver refuses is logged with the driver's verdict (`the driver refused the compute PSO of record HASH … with 0x…`): its dispatches are skipped. +- XCL records pipeline keys associated with driver crashes in `driver-crashes.txt` beside the + DXIL cache. Later runs skip those pipelines. Delete the file to retry them. - With `XCL_DRED=1`, a D3D12 device removal logs GPU breadcrumbs in `xcl.log`. XCL examines up to 4,096 command lists and reports up to 64 unfinished lists, starting with those on which the GPU completed at least one operation. For each, it names the translated diff --git a/crates/xcl/Cargo.toml b/crates/xcl/Cargo.toml index c3b23a1b8b..08bd049d19 100644 --- a/crates/xcl/Cargo.toml +++ b/crates/xcl/Cargo.toml @@ -44,6 +44,7 @@ features = [ version = "0.61" features = [ "Win32_Foundation", + "Win32_Graphics_Gdi", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_Debug", diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 2d431e5a47..cc844d570c 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -62,6 +62,9 @@ pub fn set_title_filter(f: usize) -> usize { } unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i32 { + // a crash inside the driver's compiler: the pipeline it was given is noted first, so the next + // run does not end at it too + crate::hle::d3d12x::driver_crash::on_crash(); crate::hle::d3d12x::real::log_device_removed(); if !info.is_null() && !(*info).ExceptionRecord.is_null() { let rec = &*(*info).ExceptionRecord; @@ -109,6 +112,9 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i modules::describe_address(addr) ); crate::xlog_error!("{msg}"); + // XCL's queues and the last GPU-side events (`d3d12x::flight`): a title that ends itself + // after its own GPU watchdog fired shows here which queue had stopped + crate::hle::d3d12x::flight::dump("crash"); crate::report::write_final(Some(msg)); crate::log::flush(); } @@ -682,7 +688,7 @@ pub fn dump_threads() { ok }; if got { - let frames: Vec = unwind(&mut c.0, 14).into_iter().map(modules::describe_address).collect(); + let frames: Vec = unwind(&mut c.0, 40).into_iter().map(modules::describe_address).collect(); lines.push(format!("thread {} '{}': {}", te.th32ThreadID, thread_name(h), frames.join(" < "))); } CloseHandle(h); 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 b5d615a297..bb6cdb6137 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -1,14 +1,201 @@ //! 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, LOOP_BUDGET, VAR_BUDGET, VAR_BUDGET_OWNER, VAR_BUDGET_TOTAL, 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, 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.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" { + 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); + // 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 || (o.output && (cond_write || rmw_dst)) { + u |= 1u128 << r; + } + } + if o.output && !cond_write { + for r in v..(v + def_n).min(106) { + def |= 1u128 << r; + } + } + } + (u, def) +} + +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], wave64); + u |= iu & !d; + d |= id; + } + if let Term::Cond(ci, ..) = blk.term { + let (iu, _) = inst_sreg_scc_use_def(&cfg.insts[ci], wave64); + 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,96 +204,452 @@ 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. -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 = 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 } } /// Whether a program takes the form by itself: large, mostly repeated blocks, small tables. -pub fn wanted(cfg: &Cfg, p: &Plan, tables: usize) -> bool { - let insts = |n: usize| cfg.blocks[p.order[n]].insts.len(); - let all: usize = (0..p.order.len()).map(insts).sum(); +pub fn wanted(cfg: &Cfg, p: &Plan) -> bool { + 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(); - large(cfg) && once * 10 < all * 3 && p.words() <= tables + large(cfg) && once * 10 < all * 3 && p.words() <= MAX_TABLE_WORDS } +/// 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 a program is large enough for `wanted` to be asked. 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; +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, 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; + if (live_out[idx] & clobber) == 0 { + let new_len = blk.insts.len() - 3; + blk.insts.truncate(new_len); + } + } + } + // 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]; + } + } + _ => {} } - }; - 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); + order = new_order; + mblocks = new_mblocks; + } + + let final_live_out = if allow_split { + compute_live_out(cfg, &mblocks, end_live, lw.wave64) + } else { + vec![ALL_SGPRS_MASK | SCC_LIVE_BIT; mblocks.len()] + }; + + // a loop head's guard names its loop region and what an iteration spends (`loop_cost`): + // heads of two regions, or of two costs, are two classes + let loops = crate::gpu::recomp::loop_ranges(&cfg.insts); + let regions = crate::gpu::recomp::budget_regions(&loops); + 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 region = if blk.is_header { + let pc = cfg.blocks[order[n]].pc; + let cost = crate::gpu::recomp::loop_cost(&loops, pc) as u64; + crate::gpu::recomp::budget_region(®ions, pc).unwrap_or(0) as u64 + ((cost - 1) << 32) + } else { + 0 + }; + let mut key = vec![blk.is_header as u64 + region, 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)); + } + 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 }); + } + } + 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) } @@ -120,12 +663,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) } @@ -209,10 +752,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; @@ -221,10 +767,50 @@ 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)); + let loops = crate::gpu::recomp::loop_ranges(&cfg.insts); + let regions = crate::gpu::recomp::budget_regions(&loops); + let owner = if regions.is_empty() { None } else { Some((slot(lw, VAR_BUDGET_OWNER), slot(lw, VAR_BUDGET_TOTAL))) }; lw.s.m.set_block(head); let b = lw.s.m.load(at, 4); let w = lw.c(width); @@ -243,12 +829,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)) }; @@ -285,11 +920,24 @@ 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]) { - // a loop head spends the loop budget - let left = lw.s.m.load(budget, 4); - let none = lw.cmpc(Pred::Eq, left, 0); + let blk = &p.mblocks[r]; + if blk.is_header { + // a loop head spends the loop budget (of its region: the recompiler's `loop_guard`) + let region = owner.zip(crate::gpu::recomp::budget_region(®ions, cfg.blocks[p.order[r]].pc)); + // (1 for a short loop: the guard's instructions are then what they always were) + let cost = crate::gpu::recomp::loop_cost(&loops, cfg.blocks[p.order[r]].pc); + let mut left = lw.s.m.load(budget, 4); + if let Some(((own_at, total_at), reg)) = region { + let own = lw.s.m.load(own_at, 4); + let other = lw.cmpc(Pred::Ne, own, reg); + left = lw.selc(other, LOOP_BUDGET * crate::gpu::recomp::LOOP_BUDGETS_PER_REGION, left); + let rv = lw.c(reg); + lw.s.m.store(own_at, rv, 4); + let total = lw.s.m.load(total_at, 4); + let spent = if cost == 1 { lw.cmpc(Pred::Eq, total, 0) } else { lw.cmpc(Pred::ULt, total, cost) }; + left = lw.selc(spent, 0, left); + } + let none = if cost == 1 { lw.cmpc(Pred::Eq, left, 0) } else { lw.cmpc(Pred::ULt, left, cost) }; let (out, body) = (lw.block(Some(1)), lw.block(Some(1))); lw.cond_br(none, out, body); lw.s.m.set_block(out); @@ -297,13 +945,22 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block lw.s.m.store(to, end, 4); lw.s.m.br(target_latch); lw.s.m.set_block(body); - let one = lw.c(1); + let one = lw.c(cost); let l = lw.sub(left, one); lw.s.m.store(budget, l, 4); + if let Some(((_, total_at), _)) = region { + let total = lw.s.m.load(total_at, 4); + let t = lw.sub(total, one); + lw.s.m.store(total_at, t, 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, @@ -312,7 +969,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); } @@ -351,3 +1012,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)); + } +} diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index 7602b5da43..8f3a36ff24 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -49,7 +49,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"); } } @@ -102,6 +106,73 @@ fn gpu_compact_form_spends_the_loop_budget_as_the_plain_form() { assert_eq!(&c.sgpr[..2], &p.sgpr[..2]); } +/// In both of the direct translator's forms an iteration of a long loop spends more of the loop +/// budget (`recomp::loop_cost`): a loop of 80 instructions (320 B) that never ends runs half the +/// budget's iterations, as on the HLSL path +/// (`recomp::tests::gpu_an_endless_long_loop_stops_after_the_budget_by_its_cost`). +#[test] +fn gpu_an_endless_long_loop_stops_after_the_budget_by_its_cost_in_both_forms() { + 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 o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; + let i = |nm: &str, e: &str, f: &[(&str, u64)], lit: Option| encode(nm, e, f, lit).unwrap_or_else(|x| panic!("{nm}: {x}")); + let mut v = Vec::new(); + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)], None)); + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + for _ in 0..77 { + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 129)], None)); + } + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None)); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFB0)], None)); + v.extend(i("S_ENDPGM", "ENC_SOPP", &[], None)); + for compact in [true, false] { + let k = translate_full_as(&v, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}")); + let r = runner::run_with_statics(&k.dxil, &KernelState::default(), &[], &[], &[], &k.static_samplers).expect("GPU run"); + assert_eq!(r.sgpr[0], (1 << 16) / 2, "compact {compact}"); + } +} + +/// The direct translator's forms give each loop region its own budget as the HLSL path does +/// (`recomp::tests::gpu_a_loop_after_a_spin_to_the_budget_still_runs`). +#[test] +fn gpu_a_loop_after_a_spin_to_the_budget_still_runs_in_both_forms() { + 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 o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; + for (spin, n, nested) in [(0x10000, 3, false), (0xFFF0, 1000, false), (0x10000, 3, true)] { + let i = |nm: &str, e: &str, f: &[(&str, u64)], lit: Option| encode(nm, e, f, lit).unwrap_or_else(|x| panic!("{nm}: {x}")); + // a spin of `spin` tries (in an outer loop that runs once when `nested`), a loop of `n`, + // then s2 = 7 (as `recomp::tests::spin_then_loop`) + let mut v = Vec::new(); + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)], None)); + if nested { + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 3), ("SSRC1", 129)], None)); + } + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 255)], Some(spin))); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None)); + if nested { + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 3), ("SSRC1", 129)], None)); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF9)], None)); + } + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)], None)); + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None)); + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 255)], Some(n))); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None)); + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 135)], None)); + v.extend(i("S_ENDPGM", "ENC_SOPP", &[], None)); + for compact in [true, false] { + let k = translate_full_as(&v, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}")); + let r = runner::run_with_statics(&k.dxil, &KernelState::default(), &[], &[], &[], &k.static_samplers).expect("GPU run"); + assert_eq!(&r.sgpr[..3], &[spin, n, 7], "spin {spin:#x}, loop {n}, nested {nested}, compact {compact}"); + } + } +} + fn early_outs(copies: usize) -> Vec { let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); let mut v = Vec::new(); @@ -169,7 +240,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)])); @@ -177,50 +257,23 @@ 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::plan(&cfg, &lw).unwrap(); - assert!(p.inline && p.words() > 8192 && p.words() <= 12288); - assert!(super::compact::wanted(&cfg, &p, super::compact::TABLE_WORDS_WAVE32)); + assert!(p.inline && p.order.len() > 16384 && p.words() <= 12288); + assert!(super::compact::wanted(&cfg, &p)); 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 7492f54b9c..164a8e97dd 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -133,6 +133,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(); @@ -153,6 +154,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 } } @@ -181,7 +307,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)])); } @@ -204,7 +330,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()); @@ -254,6 +380,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; @@ -429,12 +556,12 @@ 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"); if crate::gpu::recomp::dxc::location().is_ok() { - super::coverage::translate_mode(&code, &Mode::Pixel(psi), ko, true).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); + super::coverage::translate_mode(&code, &Mode::Pixel(psi), ko, true, &[]).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); } } @@ -613,6 +740,44 @@ fn window_at_lowers_to_32bit_carry_without_int64() { } } +#[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", 20)], 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 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), + ("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"); + 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}; @@ -633,6 +798,89 @@ fn dot8_u32_u4_unclamped_lowers_to_dot4_add_u8_packed() { assert!(!dis_clamped.contains("dot4AddPacked"), "clamped dot8 should stay 64-bit saturating:\n{dis_clamped}"); } +#[test] +fn s_barrier_emits_all_sync_when_shader_writes_uav_or_uses_glc() { + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + + // Pure ALU + s_barrier keeps GROUP_SYNC (mode 9 = SYNC_THREAD_GROUP | TGSM_FENCE). + let lds_only = prog(&[ + ("S_BARRIER", "ENC_SOPP", &[], None), + ]); + let dxil_lds = translate(&lds_only, ko).expect("lds-only barrier translates"); + super::validate::validate(&dxil_lds).expect("lds-only validates"); + if let Ok(dis) = super::validate::disassemble(&dxil_lds) { + assert!(dis.contains("dx.op.barrier(i32 80, i32 9)"), "expected GROUP_SYNC (9):\n{dis}"); + assert!(!dis.contains("dx.op.barrier(i32 80, i32 11)"), "unexpected ALL_SYNC (11):\n{dis}"); + } + + // Shader with a global store upgrades s_barrier to ALL_SYNC (mode 11 = GROUP_SYNC | UAV_FENCE_GLOBAL). + let with_store = prog(&[ + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 1), ("SADDR", 0x7D), ("OFFSET", 0)], None), + ("S_BARRIER", "ENC_SOPP", &[], None), + ]); + let dxil_store = translate(&with_store, ko).expect("store + barrier translates"); + super::validate::validate(&dxil_store).expect("store + barrier validates"); + if let Ok(dis) = super::validate::disassemble(&dxil_store) { + assert!(dis.contains("dx.op.barrier(i32 80, i32 11)"), "expected ALL_SYNC (11):\n{dis}"); + } + + // Shader with a GLC=1 load also upgrades s_barrier to ALL_SYNC (mode 11). + let with_glc = prog(&[ + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("SADDR", 0x7D), ("OFFSET", 0), ("GLC", 1)], None), + ("S_BARRIER", "ENC_SOPP", &[], None), + ]); + let dxil_glc = translate(&with_glc, ko).expect("glc load + barrier translates"); + super::validate::validate(&dxil_glc).expect("glc load + barrier validates"); + if let Ok(dis) = super::validate::disassemble(&dxil_glc) { + assert!(dis.contains("dx.op.barrier(i32 80, i32 11)"), "expected ALL_SYNC (11) for GLC load:\n{dis}"); + } +} + +/// A console PS with DB_SHADER_CONTROL.DEPTH_BEFORE_SHADER (`PsInterface::early_depth`) gets +/// `[earlydepthstencil]` on the HLSL path and the ForceEarlyDepthStencil shader flag (bit 3) on +/// both paths, also when it exports depth; without it, neither. +#[test] +fn early_depth_pixel_shaders_test_depth_first_on_both_paths() { + use crate::gpu::recomp::{dxc, runner, translate, Mode, Options, PsInterface}; + if dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + // the shader flags of the entry (`!{i32 0, i64 , ...}`) + let early_flag = |c: &[u8]| { + let dis = super::validate::disassemble(c).unwrap_or_else(|e| panic!("{e}")); + dis.match_indices("!{i32 0, i64 ").any(|(i, m)| { + let n: String = dis[i + m.len()..].chars().take_while(char::is_ascii_digit).collect(); + n.parse::().is_ok_and(|f| f & 8 != 0) + }) + }; + let color = ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 4), ("VSRC2", 4), ("VSRC3", 4), ("DONE", 1), ("VM", 1)][..], None); + let target = sig("SV_Target", 0, 64, 3, 0, 0xF); + let cases = [ + ("color", prog(&[("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 242)], None), color]), vec![target.clone()]), + ( + "color and depth", + prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 240)], None), + ("EXP", "ENC_EXP", &[("TGT", 8), ("EN", 0x1), ("VSRC0", 4), ("VSRC1", 4), ("VSRC2", 4), ("VSRC3", 4)], None), + color, + ]), + vec![target, sig("SV_Depth", 0, 65, 3, u32::MAX, 0x1)], + ), + ]; + let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + for (name, code, outputs) in &cases { + for early_depth in [false, true] { + let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: outputs.clone(), input_ena: 0x2, attrs: None, early_depth }; + let t = translate(code, &Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }).unwrap(); + assert_eq!(t.hlsl.contains("[earlydepthstencil]\nXclOut main("), early_depth, "{name}, early {early_depth}: HLSL\n{}", t.hlsl); + let hlsl = dxc::compile(&t.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{name}, early {early_depth}: {e}\n{}", t.hlsl)); + assert_eq!(early_flag(&hlsl), early_depth, "{name}, early {early_depth}: HLSL path's shader flags"); + let direct = super::kernel::translate_pixel(code, ko, &psi).unwrap_or_else(|e| panic!("{name}, early {early_depth}: {}", &e[..e.len().min(800)])); + assert_eq!(early_flag(&direct.dxil), early_depth, "{name}, early {early_depth}: direct path's shader flags"); + } + } +} + #[test] fn raw_loads_in_root_windows_are_branchless() { let loads = prog(&[ @@ -680,13 +928,25 @@ 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"); super::validate::validate(&ps_k.dxil).expect("pixel shader validates"); if let Ok(dis) = super::validate::disassemble(&ps_k.dxil) { let body = dis.split("define void @main()").nth(1).and_then(|s| s.split("\n}\n").next()).expect("main body"); - assert!(body.contains("switch i32"), "pixel shader multi-window loads must keep switch:\n{dis}"); + assert!(body.contains("switch i32"), "pixel shader root-UAV loads must keep switch:\n{dis}"); + } + let ps_flat = super::kernel::translate_pixel( + &ps_code, + KernelOptions { wave64: false, split: false, mem_windows: 4 | crate::gpu::recomp::HEAP_WINDOWS | crate::gpu::recomp::HEAP_FLAT, sampler_base: 0 }, + &psi, + ) + .expect("pixel shader heap-flat load translates"); + super::validate::validate(&ps_flat.dxil).expect("pixel shader heap-flat validates"); + if let Ok(dis) = super::validate::disassemble(&ps_flat.dxil) { + let body = dis.split("define void @main()").nth(1).and_then(|s| s.split("\n}\n").next()).expect("main body"); + assert!(!body.contains("switch i32"), "pixel shader heap-flat loads must not emit switch:\n{dis}"); } } @@ -717,7 +977,6 @@ fn raw_loads_in_root_windows_respect_exec_and_bounds() { let arena = crate::gpu::uma::Uma::with_windows(4, 1 << 20).expect("4 UMA windows"); let ws: [u64; 4] = std::array::from_fn(|k| arena.window(k).0 as u64); let word = |a: u64| unsafe { &mut *(a as *mut u32) }; - // Non-zero canary at offset 0 of every window so leaked unselected reads fail immediately. for (k, &wk) in ws.iter().enumerate() { *word(wk) = 0xBAD0_0000 | k as u32; *word(wk + 0x1000) = 0xA000_0000 | (k as u32 * 0x11); @@ -754,7 +1013,6 @@ fn raw_loads_in_root_windows_respect_exec_and_bounds() { r[5] = 0xDEAD_0000; continue; } - // Dynamic window choices: 0, 1, 2, 3, w>=4, 0xFFFF_FFFF, hi==0 (-> w0), carry w0->w1. match slot { 0..=3 => { r[2] = (ws[slot] + 0x1000) as u32; @@ -783,7 +1041,6 @@ fn raw_loads_in_root_windows_respect_exec_and_bounds() { 7 => { r[2] = 0x1000; r[3] = hi(ws[0]); - // 0xFFFF_FFF8 + OFFSET 16 carries from window 0 into window 1 at byte offset 8. r[4] = 0xFFFF_FFF8; r[5] = hi(ws[0]); } @@ -831,3 +1088,117 @@ 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"); +} + +/// Constant data after the program (`kernel::translate_entry_rodata`), as the HLSL kernel's +/// `gpu_loads_read_the_constant_data_after_the_program`: `s_getpc_b64` plus the compiler's +/// offset is its address, and `s_load` / `global_load` (with windows `s_buffer_load` too) read +/// it from the module's table – with one window, two windows (switch) and heap windows, where +/// window 0 holds other bytes at the table's offset. Any other address still reads the memory. +#[test] +fn gpu_direct_loads_read_the_constant_data_after_the_program() { + use super::kernel::{translate_entry_rodata, Entry}; + use crate::gpu::recomp::{runner, HEAP_WINDOWS}; + let body = |table: u32| { + prog(&[ + ("S_GETPC_B64", "ENC_SOP1", &[("SDST", 0)], None), // s[0:1] = 4 + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 255)], Some(table.wrapping_sub(4))), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 128)], None), + ("GLOBAL_LOAD_DWORDX3", "ENC_FLAT_GLBL", &[("VDST", 5), ("ADDR", 10), ("SADDR", 0), ("OFFSET", 0)], None), + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 0), ("OFFSET", 4), ("SOFFSET", 125)], None), + ("S_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 0), ("OFFSET", 8), ("SOFFSET", 125)], None), + // memory, not the data: v[12:13] and s[2:3] + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 8), ("ADDR", 12), ("SADDR", 0x7D), ("OFFSET", 0)], None), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 28), ("SBASE", 1), ("OFFSET", 0), ("SOFFSET", 125)], None), + // the V# s[4:7] + ("S_BUFFER_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 30), ("SBASE", 2), ("OFFSET", 4), ("SOFFSET", 125)], None), + ]) + }; + // as in retail data: program, guard s_endpgm, block (u32 N, N dwords, s_endpgm) + let block = body(0).len() as u32 + 4; + let code = body(block + 4); + let table: Vec = (0..8).map(|i| 0x7AB1_E000 + i).collect(); + let mut data = vec![table.len() as u32]; + data.extend(&table); + data.push(0xBF81_0000); + let rodata = vec![(block, data)]; + let split = runner::split_wave64(); + let direct = |windows: u32, rodata: &[(u32, Vec)]| { + let o = KernelOptions { wave64: true, split, mem_windows: windows, sampler_base: 0 }; + translate_entry_rodata(&code, o, Entry::Kernel, rodata).unwrap_or_else(|e| panic!("windows {windows:#x}: {}", &e[..e.len().min(800)])) + }; + // (translations are validated in test builds) + let one = direct(1, &rodata).dxil; + assert_eq!(direct(1, &[]).dxil, translate(&code, KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }).unwrap(), "no data, no table"); + assert_ne!(one, direct(1, &[]).dxil); + match (runner::adapter(), runner::wave64_programs_supported()) { + (Ok(_), Ok(true)) => {} + (a, w) => return runner::skip_test(if a.is_err() || w.is_err() { "no GPU" } else { "no wave64" }), + } + let check = |r: &runner::KernelResult, buffer: [u32; 2], what: &str| { + assert_eq!(r.sgpr[20], table[1], "{what}: s_load_dword of the table"); + assert_eq!(r.sgpr[24..28], table[2..6], "{what}: s_load_dwordx4 of the table"); + assert_eq!(r.sgpr[28..30], [4242, 4343], "{what}: s_load from memory"); + assert_eq!(r.sgpr[30..32], buffer, "{what}: s_buffer_load"); + for l in 0..64usize { + let k = l % 6; + assert_eq!(r.vgpr[l][5..8], table[k..k + 3], "{what}, lane {l}: three dwords of the table from {k}"); + assert_eq!(r.vgpr[l][8], 7000 + l as u32, "{what}, lane {l}: memory outside the data"); + } + }; + // one window: nothing of the code is in the memory (and a V# is always memory) + let mut st = runner::KernelState::default(); + st.sgpr[2] = 0x900; + st.sgpr[4..7].copy_from_slice(&[0x900, 0, 64]); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[10] = 4 * (l as u32 % 6); + r[12] = 0x800 + 4 * l as u32; + } + let mut mem = vec![0u32; 1024]; + mem[0x240..0x243].copy_from_slice(&[4242, 4343, 4444]); + for l in 0..64 { + mem[0x200 + l] = 7000 + l as u32; + } + check(&runner::run(&one, &st, &mem).unwrap(), [4343, 4444], "one window"); + // several windows: a code address is in none of them, and window 0 holds other bytes at + // the table's offset; the V# is on the table + let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap(); + let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64); + let word = |a: u64| unsafe { &mut *(a as *mut u32) }; + for k in 0..16u64 { + *word(w0 + block as u64 + 4 * k) = 0xBAD0_0000 + k as u32; + } + *word(w1 + 0x900) = 4242; + *word(w1 + 0x904) = 4343; + st.sgpr[2..4].copy_from_slice(&[(w1 + 0x900) as u32, (w1 >> 32) as u32]); + st.sgpr[4..7].copy_from_slice(&[block + 4, crate::gpu::recomp::CODE_ADDRESS_HI, 64]); + for (l, r) in st.vgpr.iter_mut().enumerate() { + *word(w1 + 0x800 + 4 * l as u64) = 7000 + l as u32; + r[12] = (w1 + 0x800 + 4 * l as u64) as u32; + r[13] = (w1 >> 32) as u32; + } + for (windows, what) in [(2, "two windows"), (2 | HEAP_WINDOWS, "heap windows")] { + check(&runner::run_in_arena(&direct(windows, &rodata).dxil, &st, &arena).unwrap(), [table[1], table[2]], what); + } +} diff --git a/crates/xcl/src/gpu/dxil/coverage.rs b/crates/xcl/src/gpu/dxil/coverage.rs index 4ac26cb707..f9a463308d 100644 --- a/crates/xcl/src/gpu/dxil/coverage.rs +++ b/crates/xcl/src/gpu/dxil/coverage.rs @@ -246,14 +246,15 @@ pub fn percentiles(v: &[u64]) -> (u64, u64, u64) { /// One program through the direct translator for `mode`. Panics (outside the translator's /// own thread) come back as `"panic: …"`; `validate` runs DXC's validator on the result -/// (the translator itself only validates in debug / test builds). -pub fn translate_mode(code: &[u8], mode: &Mode, o: KernelOptions, validate: bool) -> Result, String> { +/// (the translator itself only validates in debug / test builds). `rodata`: the constant data +/// after the program (`xbox::Fssm::rodata`). +pub fn translate_mode(code: &[u8], mode: &Mode, o: KernelOptions, validate: bool, rodata: &[(u32, Vec)]) -> Result, String> { let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match mode { - Mode::Kernel => kernel::translate_full(code, o), - Mode::Compute(cs) => kernel::translate_compute(code, o, cs), - Mode::Vertex(vs) => kernel::translate_vertex(code, KernelOptions { split: false, ..o }, vs), - Mode::Pixel(ps) => kernel::translate_pixel(code, KernelOptions { split: false, ..o }, ps), - Mode::Mesh(ms) => kernel::translate_mesh(code, o, ms), + Mode::Kernel => kernel::translate_entry_rodata(code, o, kernel::Entry::Kernel, rodata), + Mode::Compute(cs) => kernel::translate_entry_rodata(code, o, kernel::Entry::Compute(cs.clone()), rodata), + Mode::Vertex(vs) => kernel::translate_entry_rodata(code, KernelOptions { split: false, ..o }, kernel::Entry::Vertex(vs.clone()), rodata), + Mode::Pixel(ps) => kernel::translate_entry_rodata(code, KernelOptions { split: false, ..o }, kernel::Entry::Pixel(ps.clone()), rodata), + Mode::Mesh(ms) => kernel::translate_entry_rodata(code, o, kernel::Entry::Mesh(ms.clone()), rodata), Mode::Geometry(g) => kernel::translate_geometry(code, o, g), })); let k = match r { @@ -405,7 +406,7 @@ mod tests { let mut r = Report::default(); for (name, code, mode) in [("ok", ok.clone(), Mode::Kernel), ("gs", ok, Mode::Geometry(Default::default()))] { let t0 = std::time::Instant::now(); - let res = translate_mode(&code, &mode, o, false).map(|d| d.len()); + let res = translate_mode(&code, &mode, o, false, &[]).map(|d| d.len()); r.add(name, &Sample { stage: stage_name(&mode), result: res, time: t0.elapsed(), hlsl_size: None }); } assert_eq!(r.stages["kernel"].translated, 1, "{}", r.text(5)); 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 6ef85ad800..f7f2579ab0 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -13,7 +13,7 @@ use std::collections::{BTreeSet, HashMap}; use super::cfg::{Cfg, Term}; use super::container::Stage; -use super::lower::{ComputeInit, Init, Lw, Partner, VAR_BUDGET, VAR_SCC, VAR_VGPR}; +use super::lower::{ComputeInit, Init, Lw, Partner, LOOP_BUDGET, VAR_BUDGET, VAR_BUDGET_OWNER, VAR_BUDGET_TOTAL, VAR_SCC, VAR_VGPR}; use super::module::{Block, Pred, Value}; use super::shader::{RawUav, Shader}; use super::ssa::Ssa; @@ -38,7 +38,7 @@ pub struct KernelOptions { /// identity (`recomp::pso`): bump it when `pso::direct_compute` / `direct_graphics` change the /// containers. An edit of `gpu/dxil` needs no bump, `XCL_DIRECT_DXIL_SOURCE_ID` is its hash /// (the `gpu/dxil` sources are not in build.rs's translator source hash). -pub const TRANSLATOR_VERSION: u32 = 9; +pub const TRANSLATOR_VERSION: u32 = 11; /// `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. @@ -74,6 +74,55 @@ 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 being held back (`XCL_RT_GATE=hold`) with their outputs never written: +/// 707 of the 1 073 programs a retail title's hold leaves out write memory that later passes and +/// the CPU read (screen-probe ray lists, ray-traced resolves, particle collisions). Traversal +/// loops end at the root, so no BVH is read and none can keep the GPU busy. +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` (all its +/// loops together; `lower::LOOP_BUDGET` for every other program). With every ray missing their +/// traversal ends at once, and what else loops in them runs a few dozen rounds; but the device +/// hung (a TDR, 2 s into a retail title's world) the first time they all ran at 65 536 a lane. +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 + } +} + /// `XCL_DIRECT_COMPACT`: `1` forces the compact form, `0` forbids it, unset leaves it to `compact::wanted`. pub fn compact_mode() -> Option { match std::env::var("XCL_DIRECT_COMPACT").as_deref() { @@ -91,39 +140,39 @@ 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 /// group of 21 triangles into `res` (the recompiler's `Mode::Geometry`). Always wave64. pub fn translate_geometry(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. @@ -139,13 +188,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 { - let tables = if wave32_only { super::compact::TABLE_WORDS_WAVE32 } else { super::compact::TABLE_WORDS }; - translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None, tables) +/// `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( @@ -154,15 +202,43 @@ fn translate_entry( entry: Entry, compact: Option, nest: Option, - tables: usize, +) -> Result { + 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`). +pub fn translate_entry_rodata(code: &[u8], o: KernelOptions, entry: Entry, rodata: &[(u32, Vec)]) -> Result { + 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( + code: &[u8], + o: KernelOptions, + entry: Entry, + compact: Option, + nest: Option, + rodata: Vec<(u32, Vec)>, ) -> Result { // 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(); + // (a test's `RT_ALL_MISS_FOR_TEST`, and `with_rt_program`, go along to the translator's thread) + #[cfg(test)] + let rt_all_miss = RT_ALL_MISS_FOR_TEST.with(|c| c.get()); + let rt_program = RT_PROGRAM.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, tables)) + .spawn(move || { + #[cfg(test)] + RT_ALL_MISS_FOR_TEST.with(|c| c.set(rt_all_miss)); + RT_PROGRAM.with(|c| c.set(rt_program)); + translate_on_this_thread(&code, o, entry, compact, nest, rodata) + }) .map_err(|e| format!("translator thread: {e}"))? .join() .map_err(|e| { @@ -178,7 +254,7 @@ fn translate_entry( 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)); @@ -192,7 +268,7 @@ fn translate_on_this_thread( entry: Entry, compact: Option, nest: Option, - tables: usize, + rodata: Vec<(u32, Vec)>, ) -> Result { let geo = match &entry { Entry::Geometry(g) => Some(g.clone()), @@ -203,16 +279,19 @@ 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 mut lw = Lw::new(&cfg.insts, &leaders, o, &entry); + lw.rodata = rodata; let uses_lds = lw.lds.is_some(); let res = lw.res; let io = lw.init.io.expect("the I/O buffer"); let mut split_tid = None; + // a compute program: whether this group runs (`compute_init`: not past a folded dispatch's count) + let mut group_runs = None; let numthreads = match &entry { Entry::Kernel => { lw.setup_lanes(); @@ -226,7 +305,7 @@ fn translate_on_this_thread( Entry::Compute(cs) => { let (tid, gtid) = lw.setup_lanes_compute(cs.threads, uses_lds); if split && !uses_lds && cs.threads == [64, 1, 1] { split_tid = Some(tid); } - compute_init(&mut lw, cs, tid, gtid); + group_runs = Some(compute_init(&mut lw, cs, tid, gtid)); cs.threads } Entry::Mesh(ms) => { @@ -279,7 +358,7 @@ fn translate_on_this_thread( } let plan = if (compute || kernel) && compact.unwrap_or_else(|| super::compact::large(&cfg)) { super::compact::plan(&cfg, &lw) } else { None }; - let plan = plan.filter(|p| compact.unwrap_or_else(|| super::compact::wanted(&cfg, p, tables))); + let plan = plan.filter(|p| compact.unwrap_or_else(|| super::compact::wanted(&cfg, p))); if let Some(p) = &plan { crate::xlog_info!("[SHADER] direct DXIL compact form: {} blocks of {} kinds", p.order.len(), p.rep.len()); } @@ -318,6 +397,8 @@ fn translate_on_this_thread( } let h0 = if plan.is_some() { lw.block(None) } else { head(&mut lw, entry) }; let exit = lw.block(None); + // where `Block(0)` goes + let mut first = h0; if gs_only { // the GS alone: in the lower hardware wave only let gate = lw.block(Some(1)); @@ -325,12 +406,21 @@ fn translate_on_this_thread( lw.s.m.set_block(gate); let up = lw.upper; lw.cond_br(up, exit, h0); + first = gate; + } else if let Some(runs) = group_runs { + // a folded dispatch's groups past the console's count leave at once (the whole group: + // no barrier waits on them) + let gate = lw.block(Some(1)); + lw.edge(Block(0), gate); + lw.s.m.set_block(gate); + lw.cond_br(runs, h0, exit); + first = gate; } else { lw.edge(Block(0), h0); } let switch = if two_phase { Some(lw.block(None)) } else { None }; - // scalar loads the program repeats keep their first values (compute programs and kernels: - // the other stages enter their code by edges the CFG does not hold) + // scalar loads the program repeats keep their first values (compute, vertex, pixel and + // kernel: geometry enters its GS blocks by edges the CFG does not hold) let reloads = if follow_loads { super::reload::analyze(&cfg) } else { Default::default() }; let mut gs_entry: Option = None; if let Some(p) = &plan { @@ -339,6 +429,14 @@ fn translate_on_this_thread( None => super::compact::emit(&mut lw, &cfg, p, h0, exit)?, } } + // Per-region loop budgets target compute spin-wait passes (PR #2793); keep graphics/mesh + // stages on the single-budget CFG so AMD LLPC does not trip on multi-PHI mesh loop headers. + let loops = crate::gpu::recomp::loop_ranges(&cfg.insts); + let regions = if compute || kernel { + crate::gpu::recomp::budget_regions(&loops) + } else { + Vec::new() + }; for &b in cfg.rpo.iter().filter(|_| plan.is_none()) { let h = head(&mut lw, b); lw.s.m.set_block(h); @@ -354,15 +452,34 @@ fn translate_on_this_thread( } let end = if es_block { switch.unwrap() } else { exit }; if cfg.headers.contains(&b) { - // a lane's loop iterations are capped (the recompiler's LOOP_GUARD) - let left = lw.rd(VAR_BUDGET); - let none = lw.cmpc(Pred::Eq, left, 0); + // a lane's loop iterations are capped (the recompiler's LOOP_GUARD / loop_guard) + let region = crate::gpu::recomp::budget_region(®ions, cfg.blocks[b].pc); + // an iteration of a long loop spends more than 1 (the recompiler's `loop_cost`); + // with 1 the guard is the instructions it always was + let cost = crate::gpu::recomp::loop_cost(&loops, cfg.blocks[b].pc); + let mut left = lw.rd(VAR_BUDGET); + if let Some(r) = region { + let own = lw.rd(VAR_BUDGET_OWNER); + let other = lw.cmpc(Pred::Ne, own, r); + left = lw.selc(other, LOOP_BUDGET * crate::gpu::recomp::LOOP_BUDGETS_PER_REGION, left); + let rv = lw.c(r); + lw.wr(VAR_BUDGET_OWNER, rv); + let total = lw.rd(VAR_BUDGET_TOTAL); + let spent = if cost == 1 { lw.cmpc(Pred::Eq, total, 0) } else { lw.cmpc(Pred::ULt, total, cost) }; + left = lw.selc(spent, 0, left); + } + let none = if cost == 1 { lw.cmpc(Pred::Eq, left, 0) } else { lw.cmpc(Pred::ULt, left, cost) }; let cont = lw.block(Some(1)); lw.cond_br(none, end, cont); lw.s.m.set_block(cont); - let one = lw.c(1); + let one = lw.c(cost); let l = lw.sub(left, one); lw.wr(VAR_BUDGET, l); + if region.is_some() { + let total = lw.rd(VAR_BUDGET_TOTAL); + let t = lw.sub(total, one); + lw.wr(VAR_BUDGET_TOTAL, t); + } } for &i in &cfg.blocks[b].insts { lw.reload = reloads.get(b, i); @@ -437,7 +554,7 @@ fn translate_on_this_thread( } lw.s.m.ret(); lw.s.m.set_block(Block(0)); - lw.s.m.br(h0); + lw.s.m.br(first); let hw = if split || !o.wave64 { 32 } else { 64 }; let limit = if compute && (!split || split_tid.is_some()) { dispatch_piece_limit() } else { 0 }; lw.finish_dispatch(numthreads, hw, limit, split_tid) @@ -513,8 +630,11 @@ 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(), + rodata_table: None, fmt_desc_cache: HashMap::new(), fmt_comp1_cache: HashMap::new(), reload: None, @@ -529,7 +649,19 @@ 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| { + 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(), + compact_blk_pc: None, + compact_lit: None, xs: None, xw: None, xc: None, @@ -546,6 +678,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, @@ -580,7 +713,7 @@ impl Lw { slot = slot.max(w); } } - lw.static_samplers = crate::gpu::recomp::constant_samplers(insts, leaders); + lw.static_samplers = crate::gpu::recomp::constant_samplers(insts, leaders, matches!(entry, Entry::Vertex(_) | Entry::Pixel(_))); let group_threads: Option = match entry { Entry::Vertex(_) | Entry::Pixel(_) => None, Entry::Kernel => None, @@ -594,6 +727,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 { + lw.ps_masks = crate::gpu::recomp::ps_masks::forms(insts); + } lw.setup_storage(uses_lds, if split { slot } else { 1 }); if let (Some(t), true) = (group_threads, split) { lw.partner = match t { @@ -620,11 +756,15 @@ 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(); - 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 { self.s.try_finish(numthreads, Some(hw)) @@ -714,12 +854,28 @@ fn store_registers(lw: &mut Lw, res: super::shader::RawUav) { /// The compute entry's fixed registers (the HLSL compute mode's prologue): group ids /// after the user SGPRs, TG_SIZE, SCC = 0, EXEC = the wave's threads, v0..v2 = thread id. -pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) { +/// Returns whether this group runs: a dispatch folded into Y (`recomp::IO_GROUP_LIMIT` in `io` +/// not 0, the console's group count in X) takes its group in X from both ids, and the groups +/// past that count do not run. +pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) -> Value { + let io = lw.init.io.expect("the I/O buffer"); + let o = lw.c((crate::gpu::recomp::IO_GROUP_LIMIT * 4) as u32); + let limit = lw.s.raw_load(io, o, 1)[0]; + let (gx, gy) = (lw.s.group_id(0), lw.s.group_id(1)); + let k = lw.c(crate::gpu::recomp::FOLD_X); + let rows = lw.mul(gy, k); + let flat = lw.add(gx, rows); + let folded = lw.cmpc(Pred::Ne, limit, 0); + let zero = lw.c(0); + let ids = [lw.sel(folded, flat, gx), lw.sel(folded, zero, gy)]; + let inside = lw.cmp(Pred::ULt, flat, limit); + let t = lw.b(true); + let runs = lw.sel(folded, inside, t); let mut sgpr = HashMap::new(); let mut next = cs.user_sgprs; for k in 0..3 { if cs.tgid[k] { - let g = lw.s.group_id(k as u32); + let g = if k < 2 { ids[k] } else { lw.s.group_id(2) }; sgpr.insert(next, g); next += 1; } @@ -735,7 +891,6 @@ pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) let v = lw.or(w, i); sgpr.insert(next, v); } - let zero = lw.c(0); sgpr.insert(VAR_SCC, zero); let (lo, hi) = entry_exec(lw, total, tid); sgpr.insert(126, lo); @@ -747,6 +902,7 @@ pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) } } lw.init.compute = Some(ComputeInit { sgpr, vgpr, zero }); + runs } /// The mesh entry's registers (the HLSL mesh mode's prologue): SGPRs from `io` with the @@ -786,7 +942,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, outputs: ms.outputs.clone() }); + lw.mesh = Some(super::lower::MeshCtx { rec, vtx, prm, 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 4ee59b5cc8..3cf1b61601 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -180,6 +180,19 @@ impl Lw { /// This lane's bit of the mask (lo, hi), cached per block. pub fn lanebit(&mut self, lo: Value, hi: Value) -> Value { + 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; @@ -190,6 +203,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); @@ -459,6 +480,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 @@ -626,6 +674,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)] @@ -643,7 +729,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`, @@ -711,8 +797,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()); @@ -722,7 +808,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 5034d31903..ec46ce1c76 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -34,6 +34,10 @@ pub const VAR_XDEAD: u32 = VAR_BUDGET + 4; pub const VAR_IMG_WRITE: u32 = VAR_BUDGET + 8; /// loop iterations a lane may run (the recompiler's `xcl_budget`) pub const LOOP_BUDGET: u32 = 1 << 16; +/// the loop region whose budget [`VAR_BUDGET`] holds (the recompiler's `xcl_bown`, `budget_region`) +pub const VAR_BUDGET_OWNER: u32 = VAR_BUDGET + 7; +/// iterations left to all the regions together (the recompiler's `xcl_btotal`) +pub const VAR_BUDGET_TOTAL: u32 = VAR_BUDGET + 24; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Dst { @@ -65,6 +69,8 @@ pub struct MeshCtx { pub vtx: Value, pub prm: 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. @@ -113,12 +119,15 @@ 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 == VAR_BUDGET_TOTAL { + return s.m.i32c(LOOP_BUDGET * crate::gpu::recomp::LOOP_BUDGETS_IN_ALL); } if var == super::lower_round::VAR_F32_MODE { return s.m.i32c(super::lower_round::MODE_INIT); } - if var == VAR_FP16_RM || var == VAR_WIN || var == VAR_XK || var == VAR_XDEAD || (VAR_IMG_WRITE..VAR_IMG_WRITE + 16).contains(&var) { + if var == VAR_FP16_RM || var == VAR_BUDGET_OWNER || var == VAR_WIN || var == VAR_XK || var == VAR_XDEAD || (VAR_IMG_WRITE..VAR_IMG_WRITE + 16).contains(&var) { return s.m.i32c(0); } if var >= super::lower_mem::VAR_TMP { @@ -187,9 +196,16 @@ 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, + /// constant data after the program in the code region (`recomp::Options::rodata`: + /// (address from the program's start, dwords)) and its table, created on first use + /// (`rodata_loads`) + pub rodata: Vec<(u32, Vec)>, + pub rodata_table: Option, /// cached decoded format descriptors hoisted to `d3`'s defining block pub fmt_desc_cache: HashMap<(Value, Option), super::lower_mem::FmtDesc>, /// cached single-component format decode parameters hoisted to `d3`'s defining block @@ -216,10 +232,18 @@ 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` 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)>, @@ -250,6 +274,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, @@ -685,6 +711,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), @@ -708,7 +738,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), @@ -732,9 +762,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)), @@ -751,7 +781,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); @@ -760,7 +790,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), } } @@ -1016,7 +1046,12 @@ impl Lw { fn sopp(&mut self, d: &Decoded, name: &str) -> LResult<()> { match name { "s_barrier" => { - 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); Ok(()) } "s_round_mode" => { @@ -1305,8 +1340,17 @@ impl Lw { return err(d, "indirect branch"); } if name == "s_getpc_b64" { - let pc = d.pc + d.len as u64; - let (lo, hi) = (self.c(pc as u32), self.c(0)); + // 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 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 hi = self.c(code_hi); self.write64(&dst, lo, hi); return 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..e8fb2ae53b 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); } } @@ -401,11 +409,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) }; diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index c366666fd9..db79242c50 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,11 @@ 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 128 B Box32 + // node (`full + 111`) fall within valid UMA windows so out-of-window / null BVH + // roots never read `[0; 28]` or straddle into an unmapped 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 +970,19 @@ 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 w = self.rd(super::lower::VAR_WIN); + let w_ok = self.cmpc(Pred::ULt, w, self.mems.len() as u32); + // Check end of 112-byte Box32 node (`full + 111`) stays in-window as well. + 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, w_ok); + let ok2 = self.land(same_hi, non_null); + bvh_valid = self.land(ok1, ok2); } let ty = self.andc(node, 7); let sort = { @@ -946,8 +990,15 @@ impl Lw { self.nz(s) }; let act = self.act(); + let guard = self.land(act, bvh_valid); let out = [self.tmp_var(), self.tmp_var(), self.tmp_var(), self.tmp_var()]; - self.guarded(act, &mut |lw| { + // Default to all-miss (`u32::MAX`) for active lanes whose BVH node address was + // null/out-of-window so traversal exits immediately instead of looping on zeroes. + let ones = self.c(u32::MAX); + for (c, _) in out.iter().enumerate() { + self.write32(&super::lower::Dst::V(vdata + c as u64), ones); + } + self.guarded(guard, &mut |lw| { lw.bvh_intersect(ty, a, extent, origin, dir, inv, sort, out)?; for (c, &t) in out.iter().enumerate() { let v = lw.rd(t); diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index cc7cd0116a..60eaab5916 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -318,9 +318,9 @@ impl Lw { /// `(aligned_byte_offset, component_mask)` pairs). For non-graphics stages with root UAV /// windows (`self.heap_mem.is_none() && self.gfx.is_none()`), emits branchless straight-line /// loads reading offset `0` on unselected windows / inactive lanes and merging with `select`, - /// eliminating per-load `switch` / guard CFGs and `phi` nodes while preserving `#1693` - /// semantics (out-of-range windows and inactive lanes yield `0`). Graphics stages (`VS`/`PS`) - /// keep the `switch` form so non-coherent root UAV loads are not serialized in one basic block. + /// eliminating per-load `switch` / guard CFGs and `phi` nodes while preserving out-of-range + /// and inactive-lane zero semantics. Graphics stages (`VS`/`PS`) keep the `switch` form for + /// root UAVs; heap-window stages delegate to `with_mem_i32s` (`heap_flat` when enabled). pub(crate) fn with_mem_raw_loads( &mut self, mut guard: Option, @@ -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) @@ -1167,6 +1189,9 @@ impl Lw { let base = self.add(d0, off); let base_aligned = self.andc(base, !3); let raw = self.mem_ld_chunks(base_aligned, count); + // (a V# on the constant data in the code: only with windows, where its high + // dword tells it from the title's memory) + let raw = if self.windowed() { self.rodata_loads(base_aligned, raw) } else { raw }; let z = self.c(0); (0..count) .map(|i| { @@ -1193,7 +1218,9 @@ impl Lw { let a = self.add(b, k); let a = self.add(a, soff); let base_aligned = self.andc(a, !3); - self.mem_ld_chunks(base_aligned, count) + let raw = self.mem_ld_chunks(base_aligned, count); + // (constant data in the code) + self.rodata_loads(base_aligned, raw) }; let coherent = ["GLC", "DLC"].iter().any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(1)); if self.split && coherent { @@ -1251,18 +1278,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 { @@ -1901,16 +1939,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(); @@ -2025,6 +2071,13 @@ impl Lw { } else { let vd = Self::fv(d, "VDST"); let loaded = self.mem_ld_n(Some(act), a, count as u32); + // (constant data in the code) + let loaded = if self.rodata.is_empty() { + loaded + } else { + let a = self.andc(a, !3); + self.rodata_loads(a, loaded) + }; for i in 0..count { self.write32(&Dst::V(vd + i), loaded[i as usize]); } @@ -2425,8 +2478,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); @@ -2535,13 +2593,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 08e15a5580..c57ccb28c4 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)] @@ -991,7 +992,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(()); @@ -1040,16 +1041,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); @@ -1241,6 +1245,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 +1300,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 { @@ -1324,8 +1358,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), @@ -1428,3 +1485,110 @@ 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"); + } +} 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/lower_window.rs b/crates/xcl/src/gpu/dxil/lower_window.rs index 1f41e5817d..4ab2f70b16 100644 --- a/crates/xcl/src/gpu/dxil/lower_window.rs +++ b/crates/xcl/src/gpu/dxil/lower_window.rs @@ -151,6 +151,76 @@ impl Lw { self.wr(VAR_WIN, w); } + /// `Lw::rodata` (the HLSL kernel's `xcl_gload`): the dwords `vals` a load read from memory + /// at `a`, `a + 4`.. (`a` dword-aligned), with those at a code address inside one of the + /// program's constant data blocks replaced by the block's dword. A code address has the + /// high dword `CODE_ADDRESS_HI` with several windows (`s_getpc_b64`; the window of the + /// access was just selected: `VAR_WIN`) and is the program's offset with one. `vals` as + /// they are without data. + pub(crate) fn rodata_loads(&mut self, a: Value, vals: Vec) -> Vec { + let total: usize = self.rodata.iter().map(|b| b.1.len()).sum(); + if total == 0 { + return vals; + } + let table = match self.rodata_table { + Some(g) => g, + None => { + let words: Vec = self.rodata.iter().flat_map(|b| b.1.iter().copied()).collect(); + let words: Vec = words.into_iter().map(|w| self.s.m.i32c(w)).collect(); + let i32 = self.s.m.i32(); + let at = self.s.m.array(total as u64, i32); + let init = self.s.m.aggregate(at, &words); + let g = self.s.m.global("xcl_rodata", at, 0, Some(init), true, 4); + self.rodata_table = Some(g); + g + } + }; + let code = if self.windowed() { + let w = self.rd(VAR_WIN); + let base = self.uma_base(); + let hi = self.c(crate::gpu::recomp::CODE_ADDRESS_HI); + let cw = self.sub(hi, base); + Some(self.cmp(Pred::Eq, w, cw)) + } else { + None + }; + // per block: `a`'s offset in it, its dword's index in the table, the block's bytes + let mut first = 0u32; + let mut blocks = Vec::new(); + for (at, len) in self.rodata.iter().map(|b| (b.0, b.1.len() as u32)).filter(|b| b.1 > 0).collect::>() { + let k = self.c(at); + let off = self.sub(a, k); + let q = self.lshrc(off, 2); + let q = self.addc(q, first); + blocks.push((off, q, 4 * len)); + first += len; + } + let z = self.c(0); + vals.into_iter() + .enumerate() + .map(|(i, v)| { + let i = i as u32; + let (mut inside, mut idx) = (None, z); + for &(off, q, bytes) in &blocks { + let (o, q) = if i == 0 { (off, q) } else { (self.addc(off, 4 * i), self.addc(q, i)) }; + let c = self.cmpc(Pred::ULt, o, bytes); + idx = self.sel(c, q, idx); + inside = Some(match inside { + Some(x) => self.or(x, c), + None => c, + }); + } + let mut inside = inside.expect("a block"); + if let Some(cw) = code { + inside = self.and(inside, cw); + } + let p = self.s.m.gep(table, &[z, idx]); + let t = self.s.m.load(p, 4); + self.sel(inside, t, v) + }) + .collect() + } + /// The window of a buffer access: V# base `d1[15:0]:d0` plus `adds` (the stride bits /// `d1[29:16]` are not part of the address). pub fn buffer_window(&mut self, d0: Value, d1: Value, adds: &[Ea], write: bool) { diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index d72ef6fc38..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)] @@ -417,6 +420,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) @@ -458,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. @@ -507,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, } @@ -827,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); + } + } } } } @@ -876,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; @@ -897,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 @@ -952,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, &[]), @@ -972,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(); @@ -1012,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; } @@ -1174,6 +1255,7 @@ impl Module { fn write_inst( &self, w: &mut BitWriter, + ab: &FuncAbbrevs, i: usize, inst_id: u64, abs: &dyn Fn(Value) -> u64, @@ -1199,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); @@ -1222,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)] @@ -1253,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 { @@ -1274,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, } @@ -1333,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; @@ -1361,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 @@ -1416,11 +1573,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 { @@ -1452,6 +1612,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 { @@ -1465,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 5e867f55a0..1603f8b5ff 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -99,7 +99,20 @@ impl Module { match op { 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::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, } @@ -423,44 +436,12 @@ impl Module { idom } - /// 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. - 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(); - // 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; - } - // unreachable blocks: emptied (the writer drops them) - let mut reach = vec![false; self.blocks.len()]; - for &b in &order { - reach[b as usize] = true; - } - for (b, r) in reach.iter().enumerate() { - if !r { - self.blocks[b].clear(); - } - } - 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 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") { + /// 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 &b in order { for &i in &self.blocks[b as usize] { let i = i as usize; if repl[i].is_some() { @@ -471,7 +452,7 @@ impl Module { let mut same: Option = None; let mut trivial = true; for &(v, _) in inc { - let v = resolve(&mut repl, v); + let v = resolve(repl, v); if v == me || Some(v) == same { continue; } @@ -491,218 +472,825 @@ impl Module { break; } } + } - // 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); + /// 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 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), + 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()] + } + + 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; + } + // 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; } - 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), - }; + 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; + } + 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; } - Step::Enter(b) => b, + 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 }; - 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) { - 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(); - } + 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; } } - self.insts[i].op = op; } - for &c in kids[b].iter().rev() { - stack.push(Step::Enter(c)); + if let Some(t) = term { + self.blocks[0].push(t); } + if !changed { + break; + } + any_changed = true; } - // 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; + any_changed + } + + /// 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; + } + } + } + } + if !any_alloca { + return false; + } + // 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; } - 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 { + }), + } + } + } + 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; + } + 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); + changed = true; continue; } - if same.is_some() { - trivial = false; - break; - } - same = Some(v); } - if let (true, Some(v)) = (trivial, same) { - repl[i] = Some(v); + 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); } + _ => {} } - if !changed { - break; + } + } + + // 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; + } + } } } } - // phis may name values defined later (back edges): resolve once more - for &b in &order { + + if changed { + for &b in order { + self.blocks[b as usize].retain(|&i| !dead_store[i as usize]); + } + } + 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; - self.insts[i].op.map_operands(|v| resolve(&mut repl, v)); + 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 + } - // 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 { + /// 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] { - 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); + 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; + } + } + 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; } - 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); + 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); + } + } + } + _ => {} + } + } + + 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); + } + _ => {} } - for b in &mut self.blocks { - b.retain(|&i| live[i as usize]); + 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; } - 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; + 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()]; + for &b in &order { + reach[b as usize] = true; + } + for (b, r) in reach.iter().enumerate() { + if !r && !self.blocks[b].is_empty() { + self.blocks[b].clear(); + iter_changed = true; + } + } + 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 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); + } + + // 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; + } + } + + // 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); + } + } + } + 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; + } + for &c in kids[b].iter().rev() { + stack.push(Step::Enter(c)); } - if !changed { - break; + } + 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)); } } - if phi_changed { + // 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("mask") && self.narrow_raw_buffer_loads(&order) { + iter_changed = true; + } + + 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; + } } } @@ -1400,4 +1988,309 @@ 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"); + } + + #[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"); + } + + #[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 f14751b43b..89718e8ad5 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -87,10 +87,11 @@ 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`. A fresh + /// dispatch can assign a different physical wave to a group; `wave_lane_index` (or `split_tid`) + /// identifies each thread's continuation slot cleanly. + 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; } @@ -146,11 +147,11 @@ impl Shader { } } 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(); @@ -268,7 +269,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) } @@ -804,7 +805,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 = chain.expect("split the synthetic program"); @@ -886,7 +887,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| { @@ -936,7 +937,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); } @@ -1053,7 +1054,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).expect("split branch fixture"); + let chain = lw.s.split_compute(geometry, split.then_some(tid), 32, 64).expect("split branch fixture"); assert!(chain.pieces.len() >= 3); let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); crate::gpu::dxil::validate::validate(&whole).expect("valid unsplit fixture"); @@ -1081,4 +1082,44 @@ mod tests { } } + #[test] + fn dispatch_chain_native_wave64_splits_with_wavesize_64() { + let geometry = [64, 1, 1]; + let options = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let cs = CsInterface { threads: geometry, ..Default::default() }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let mem = lw.mems[0]; + let offset = lw.shlc(tid, 2); + let mut val = lw.s.raw_load(mem, offset, 1)[0]; + let k = lw.c(33); + for step in 0..3u32 { + for i in 1..=12u32 { + let c = lw.c(step * 100 + i); + val = lw.xor(val, c); + val = lw.mul(val, k); + } + if step < 2 { + let next = lw.s.m.new_block(); + let alt = lw.s.m.new_block(); + let width = lw.s.wave_lane_count(); + let taken = lw.cmp(Pred::ULt, tid, width); + lw.s.m.cond_br(taken, next, alt); + lw.s.m.set_block(alt); + let alt_val = lw.addc(val, 1); + lw.s.raw_store(mem, offset, &[alt_val]); + lw.s.m.br(next); + lw.s.m.set_block(next); + } + } + lw.s.raw_store(mem, offset, &[val]); + lw.s.m.ret(); + lw.s.m.optimize(); + let chain = lw.s.split_compute(geometry, None, 64, 48).expect("native wave64 [64,1,1] splits cleanly"); + assert!(chain.pieces.len() >= 2); + assert_eq!(chain.dwords_per_group % 64, 0); + if let Ok(dis) = crate::gpu::dxil::validate::disassemble(&chain.pieces[0]) { + assert!(dis.contains("WaveSize=64"), "split piece must keep WaveSize=64:\n{dis}"); + } + } } 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. diff --git a/crates/xcl/src/gpu/dxil/prelude.rs b/crates/xcl/src/gpu/dxil/prelude.rs index 7a5e5b65c4..0fcaa1bda9 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); @@ -731,6 +763,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 46a06c63d4..e9a2cedadc 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 }; 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); diff --git a/crates/xcl/src/gpu/effects.rs b/crates/xcl/src/gpu/effects.rs index 4fe79eb859..baf9cf7d62 100644 --- a/crates/xcl/src/gpu/effects.rs +++ b/crates/xcl/src/gpu/effects.rs @@ -17,6 +17,8 @@ pub struct Effects { pub memory: bool, /// image stores and image atomics pub images: bool, + /// ray-tracing BVH intersection instructions (`IMAGE_BVH_INTERSECT_RAY` / `IMAGE_BVH64_INTERSECT_RAY`) + pub bvh_intersect: bool, /// instructions in the program pub instructions: usize, } @@ -63,7 +65,10 @@ pub fn of(code: &[u8]) -> Option { let n = d.inst.name; let writes = n.contains("_STORE") || n.contains("_ATOMIC"); match d.enc.name { - "ENC_MIMG" => e.images |= writes, + "ENC_MIMG" => { + e.images |= writes; + e.bvh_intersect |= n == "IMAGE_BVH_INTERSECT_RAY" || n == "IMAGE_BVH64_INTERSECT_RAY"; + } "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" | "ENC_SMEM" => e.memory |= writes, // LDS is the group's own and gone after it; the global data share is not "ENC_DS" => { @@ -104,6 +109,54 @@ pub fn big_and_image_only(blob: &[u8]) -> bool { code.len() >= BIG_CODE && of(&code).is_some_and(|e| !e.memory) } +/// Console RDNA2 code bytes (16 KiB, ~4 000 instructions, ~200+ KiB DXIL) from which a compute +/// shader is treated as heavyweight for worker-gated compilation so title threads never compile +/// large compute shaders ungated (and `xcl-pso-pre-*` never speculatively preloads them). +pub const HEAVY_CODE: usize = 16 << 10; + +/// Fast ASCII substring scan over a raw console shader container (`PRIV`/`ILDN`/metadata) to +/// recognize known RT companion shader families without touching any `build.rs`-hashed translator +/// sources. +pub fn container_contains_ascii_any(blob: &[u8], needles: &[&[u8]]) -> bool { + needles.iter().any(|needle| !needle.is_empty() && blob.windows(needle.len()).any(|w| w == *needle)) +} + +/// Length in bytes of the compute program's RDNA2 code (`None` if not a valid console CS). +pub fn compute_code_len(blob: &[u8]) -> Option { + compute_code(blob).map(|c| c.len()) +} + +/// Whether raw RDNA2 compute machine code `code` contains `IMAGE_BVH_INTERSECT_RAY` or +/// `IMAGE_BVH64_INTERSECT_RAY`. Unlike [`of`], this does not bail out on indirect branches +/// (`s_setpc_b64` / `s_swappc_b64` switch tables or subroutines), which large RT shaders use. +pub fn code_uses_bvh_intersect(code: &[u8]) -> bool { + let mut off = 0; + let mut ended = false; + while off + 4 <= code.len() { + let Ok(d) = rdna2::decode(&code[off..], off as u64) else { + if ended { + break; + } + return false; + }; + if ended && d.inst.name == "S_CODE_END" { + break; + } + if d.enc.name == "ENC_MIMG" && (d.inst.name == "IMAGE_BVH_INTERSECT_RAY" || d.inst.name == "IMAGE_BVH64_INTERSECT_RAY") { + return true; + } + off += d.len; + ended |= d.inst.flags & rdna2::F_TERMINATOR != 0; + } + false +} + +/// Whether the compute shader `blob` issues `IMAGE_BVH_INTERSECT_RAY` or `IMAGE_BVH64_INTERSECT_RAY`. +pub fn uses_bvh_intersect(blob: &[u8]) -> bool { + let Some(code) = compute_code(blob) else { return false }; + code_uses_bvh_intersect(&code) +} + #[cfg(test)] mod tests { use super::*; @@ -121,8 +174,19 @@ mod tests { fn images_and_memory_are_told_apart() { // loads of either kind write nothing let load: (&str, &str, &[(&str, u64)]) = ("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("SRSRC", 2)]); - assert_eq!(of(&asm(&[MOV, IMAGE_LOAD, load, END])), Some(Effects { memory: false, images: false, instructions: 4 })); - assert_eq!(of(&asm(&[MOV, IMAGE_STORE, END])), Some(Effects { memory: false, images: true, instructions: 3 })); + assert_eq!(of(&asm(&[MOV, IMAGE_LOAD, load, END])), Some(Effects { memory: false, images: false, bvh_intersect: false, instructions: 4 })); + assert_eq!(of(&asm(&[MOV, IMAGE_STORE, END])), Some(Effects { memory: false, images: true, bvh_intersect: false, instructions: 3 })); + let bvh: (&str, &str, &[(&str, u64)]) = ("IMAGE_BVH64_INTERSECT_RAY", "ENC_MIMG", &[("DMASK", 15), ("VADDR", 0), ("VDATA", 4), ("SRSRC", 2)]); + assert_eq!(of(&asm(&[bvh, END])).map(|e| (e.memory, e.images, e.bvh_intersect)), Some((false, false, true))); + assert!(code_uses_bvh_intersect(&asm(&[bvh, END]))); + // Indirect jump (`s_setpc_b64`) makes conservative `of()` return None, yet BVH detection + // must still recognize `IMAGE_BVH64_INTERSECT_RAY` so large RT shaders are classified as BVH. + let indirect: (&str, &str, &[(&str, u64)]) = ("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 2)]); + let rt_with_indirect = asm(&[indirect, bvh, END]); + assert_eq!(of(&rt_with_indirect), None); + assert!(code_uses_bvh_intersect(&rt_with_indirect)); + assert!(container_contains_ascii_any(b"\0\x01CS_ScreenProbes_ActivateRays\0", &[b"RaytracingResolve", b"ScreenProbes_ActivateRays"])); + assert!(!container_contains_ascii_any(b"\0\x01CS_DepthPyramid\0", &[b"RaytracingResolve", b"ScreenProbes_ActivateRays"])); let image_atomic: (&str, &str, &[(&str, u64)]) = ("IMAGE_ATOMIC_ADD", "ENC_MIMG", &[("DMASK", 1), ("VADDR", 0), ("VDATA", 4), ("SRSRC", 2)]); assert_eq!(of(&asm(&[image_atomic, END])).map(|e| (e.memory, e.images)), Some((false, true))); // every way into memory another pass or an indirect call reads @@ -148,12 +212,12 @@ mod tests { // a branch can jump past an early s_endpgm: a store after it is the program's (were it // constant data instead, taking it for a store only makes binds wait, as before) let store: (&str, &str, &[(&str, u64)]) = ("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("SRSRC", 2)]); - assert_eq!(of(&asm(&[IMAGE_STORE, END, store, END])), Some(Effects { memory: true, images: true, instructions: 4 })); + assert_eq!(of(&asm(&[IMAGE_STORE, END, store, END])), Some(Effects { memory: true, images: true, bvh_intersect: false, instructions: 4 })); // what does not decode after the end is trailing data let mut code = asm(&[IMAGE_STORE, END]); code.extend_from_slice(&[0xff; 8]); if rdna2::decode(&[0xff; 8], 0).is_err() { - assert_eq!(of(&code), Some(Effects { memory: false, images: true, instructions: 2 })); + assert_eq!(of(&code), Some(Effects { memory: false, images: true, bvh_intersect: false, instructions: 2 })); } } @@ -198,7 +262,7 @@ mod tests { assert_eq!(of(&asm(&[IMAGE_STORE])), None); let mut saved = asm(&[IMAGE_STORE, ("S_ENDPGM_SAVED", "ENC_SOPP", &[])]); saved.extend_from_slice(&[0xff; 8]); - assert_eq!(of(&saved), Some(Effects { memory: false, images: true, instructions: 2 })); + assert_eq!(of(&saved), Some(Effects { memory: false, images: true, instructions: 2, bvh_intersect: false })); } #[test] @@ -222,7 +286,7 @@ mod tests { END, ("S_CODE_END", "ENC_SOPP", &[]), ]); - assert_eq!(of(&far_ok), Some(Effects { memory: false, images: true, instructions: 7 })); + assert_eq!(of(&far_ok), Some(Effects { memory: false, images: true, instructions: 7, bvh_intersect: false })); // resolved far jump whose target lands past the decoded slice still fails closed let far_oob = asm(&[ diff --git a/crates/xcl/src/gpu/rdna2.rs b/crates/xcl/src/gpu/rdna2.rs index 45430f355a..202aa941cc 100644 --- a/crates/xcl/src/gpu/rdna2.rs +++ b/crates/xcl/src/gpu/rdna2.rs @@ -222,9 +222,14 @@ pub fn decode(code: &[u8], pc: u64) -> Result { && o.field.and_then(|f| field_value(enc, &base_words, f)) == Some(255) }); // VALU: the literal is fetched whenever a source field selects it, even one the - // opcode does not read – console compilers hide the shader hash in v_nop literals + // opcode does not read – console compilers hide the shader hash in v_nop literals. + // Skip fields whose operand definition is a non-source index (e.g. VOP3 v_interp_* + // SRC0 = OPR_ATTR, where attr63.w encodes 0xFF == 255). if !has_literal && is_valu(enc) { - has_literal = ["SRC0", "SRC1", "SRC2"].iter().any(|f| field_value(enc, &base_words, f) == Some(255)); + has_literal = ["SRC0", "SRC1", "SRC2"].iter().any(|f| { + !ienc.operands.iter().any(|o| !o.implicit && o.field == Some(*f) && !is_src_type(o.ty)) + && field_value(enc, &base_words, f) == Some(255) + }); } } if has_literal { @@ -1291,4 +1296,28 @@ mod tests { assert!(total > 2500 && modified > 250, "the SDWA tests are not all there: {total} lines, {modified} with source or output modifiers"); assert!(wrong.is_empty(), "{} of {total} SDWA lines differ from LLVM's, the first: {:?}", wrong.len(), &wrong[..wrong.len().min(8)]); } + + #[test] + fn vop3_interp_attr63_w_does_not_consume_literal() { + // VOP3 v_interp_p1ll_f16 / v_interp_p2_f16 encode (high<<8)|(chan<<6)|attr in SRC0. + // attr63.w (high=0, chan=3, attr=63) yields SRC0 == 0xFF == 255, which is OPR_ATTR + // rather than a 32-bit inline literal. + for name in ["V_INTERP_P1LL_F16", "V_INTERP_P2_F16"] { + let mut bytes = encode(name, "ENC_VOP3", &[("VDST", 1), ("SRC0", 0xFF), ("SRC1", 256), ("SRC2", 257)], None).unwrap(); + assert_eq!(bytes.len(), 8); + bytes.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let d = decode(&bytes, 0).unwrap(); + assert_eq!(d.inst.name, name); + assert_eq!(d.len, 8, "{name} attr63.w must not consume a 32-bit literal"); + assert_eq!(d.literal, None); + let next = decode(&bytes[d.len..], d.len as u64).unwrap(); + assert_eq!(next.inst.name, "S_ENDPGM"); + } + // Console compilers still hide shader hashes in v_nop with SRC0 == 255. + let vnop = encode("V_NOP", "ENC_VOP1", &[("SRC0", 255)], Some(0x1234_5678)).unwrap(); + let d = decode(&vnop, 0).unwrap(); + assert_eq!(d.inst.name, "V_NOP"); + assert_eq!(d.len, 8); + assert_eq!(d.literal, Some(0x1234_5678)); + } } diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 379bd8518f..444915d8ba 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -9,11 +9,11 @@ //! kept for `report.json` ([`toolchain`]). use std::cell::RefCell; -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, OnceLock, Weak}; +use std::sync::{Arc, Condvar, Mutex, OnceLock, Weak}; use windows::core::{Interface, GUID, HRESULT, PCWSTR}; use windows::Win32::Graphics::Direct3D::Dxc::{ @@ -205,6 +205,14 @@ pub fn toolchain() -> Toolchain { mod version_tests { use super::*; + #[test] + fn an_empty_blob_with_a_null_pointer_reads_as_no_bytes() { + assert!(unsafe { bytes_at(std::ptr::null(), 0) }.is_empty()); + assert!(unsafe { bytes_at(std::ptr::null(), 16) }.is_empty()); + let data = [1u8, 2, 3]; + assert_eq!(unsafe { bytes_at(data.as_ptr(), data.len()) }, &data); + } + #[test] fn versions_parse_and_compare_as_numbers() { assert_eq!(parse_version("10.0.26100.0"), Some([10, 0, 26100, 0])); @@ -389,8 +397,6 @@ struct Job { profile: String, extra: Vec, reply: std::sync::mpsc::Sender, String>>, - /// one of the title's threads waits for it - wanted: Wanted, } /// Whether one of the title's threads waits for a compile (asked again while it is held back). @@ -400,6 +406,136 @@ pub type Wanted = Box bool + Send>; /// 0.1 – 0.7 GB). const WANTED_AT_ONCE: usize = 6; +/// Workers kept free of background compiles while a title is running so a compile that a +/// title thread waits for (`wanted`) starts immediately instead of queueing behind slow +/// background DXC compiles (#1164). Offline tools (`boot().is_none()`) use every worker. +fn wanted_reserve(total: usize) -> usize { + if total <= 1 { + 0 + } else { + (total / 3).clamp(1, 4).min(total - 1) + } +} + +struct Queued { + job: J, + wanted: Wanted, +} + +struct QueueState { + items: VecDeque>, + bg_active: usize, + total_workers: usize, + closed: bool, +} + +/// Priority job queue for the DXC worker pool: wanted jobs are dequeued ahead of background +/// jobs and bypass the background concurrency cap (`bg_limit`), while background jobs leave +/// `wanted_reserve(total_workers)` workers free whenever `reserve_for_wanted()` is true. +struct Queue { + state: Mutex>, + cv: Condvar, + reserve_for_wanted: fn() -> bool, +} + +struct BgSlot<'a, J>(&'a Queue); + +impl Drop for BgSlot<'_, J> { + fn drop(&mut self) { + let mut s = self.0.state.lock().unwrap_or_else(|e| e.into_inner()); + s.bg_active = s.bg_active.saturating_sub(1); + let has_work = !s.items.is_empty(); + let done = s.closed && !has_work; + drop(s); + if done { + self.0.cv.notify_all(); + } else if has_work { + self.0.cv.notify_one(); + } + } +} + +impl Queue { + fn new(total_workers: usize, reserve_for_wanted: fn() -> bool) -> Self { + Self { + state: Mutex::new(QueueState { + items: VecDeque::new(), + bg_active: 0, + total_workers: total_workers.max(1), + closed: false, + }), + cv: Condvar::new(), + reserve_for_wanted, + } + } + + fn bg_limit(&self, total_workers: usize) -> usize { + let reserve = if (self.reserve_for_wanted)() { wanted_reserve(total_workers) } else { 0 }; + total_workers.saturating_sub(reserve).max(1) + } + + fn push(&self, job: J, wanted: Wanted) -> Result<(), &'static str> { + let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if s.closed { + return Err("DXC: no compile threads"); + } + let wake = (wanted)() || s.bg_active < self.bg_limit(s.total_workers); + s.items.push_back(Queued { job, wanted }); + drop(s); + if wake { + self.cv.notify_one(); + } + Ok(()) + } + + /// Wake waiting workers after an already-queued job's `wanted` predicate flips to true. + fn notify_wanted(&self) { + // Acquire and release the mutex so a worker between evaluating `wanted` and entering + // `cv.wait` cannot miss this notification. + let _g = self.state.lock().unwrap_or_else(|e| e.into_inner()); + drop(_g); + self.cv.notify_all(); + } + + /// Wait for the next runnable job. Returns `None` once closed and drained. + fn pop(&self) -> Option<(J, Wanted, Option>)> { + let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(pos) = s.items.iter().position(|q| (q.wanted)()) { + let q = s.items.remove(pos).unwrap(); + let notify_close = s.closed && s.items.is_empty(); + drop(s); + if notify_close { + self.cv.notify_all(); + } + return Some((q.job, q.wanted, None)); + } + let limit = self.bg_limit(s.total_workers); + if s.bg_active < limit { + if let Some(q) = s.items.pop_front() { + s.bg_active += 1; + let notify_close = s.closed && s.items.is_empty(); + drop(s); + if notify_close { + self.cv.notify_all(); + } + return Some((q.job, q.wanted, Some(BgSlot(self)))); + } + } + if s.closed && s.items.is_empty() { + return None; + } + s = self.cv.wait(s).unwrap_or_else(|e| e.into_inner()); + } + } + + #[cfg(test)] + fn close(&self) { + self.state.lock().unwrap_or_else(|e| e.into_inner()).closed = true; + self.cv.notify_all(); + } +} + /// Compile threads (DXC workers, and the PSO workers of `pso_async` that feed them): every core /// but one, `XCL_DXC_THREADS` to choose. Memory is what `wait_for_memory` watches: a retail /// pack's biggest translations take ~0.7 GB in DXC (a typical one 0.1–0.3 GB). The cap used @@ -463,36 +599,59 @@ pub fn wait_for_memory(wanted: &Wanted) -> MemorySlot { } } +static POOL: OnceLock>> = OnceLock::new(); + +/// Wake the DXC worker pool after a queued compile becomes wanted by a title thread. +/// Does nothing if the pool has not been started yet. +pub fn notify_wanted() { + if let Some(q) = POOL.get() { + q.notify_wanted(); + } +} + /// DXC workers (`compile_threads`, each with its own compiler and a `DXC_STACK` stack), started /// on first use; callers wait for their job. -fn pool() -> &'static std::sync::Mutex> { - static POOL: OnceLock>> = OnceLock::new(); +fn pool() -> &'static Arc> { POOL.get_or_init(|| { - let (tx, rx) = std::sync::mpsc::channel::(); - let rx = std::sync::Arc::new(std::sync::Mutex::new(rx)); - for k in 0..compile_threads() { - let rx = rx.clone(); - let _ = std::thread::Builder::new().name(format!("xcl-dxc-{k}")).stack_size(DXC_STACK).spawn(move || loop { - let job = match rx.lock().unwrap().recv() { - Ok(j) => j, - Err(_) => return, - }; - let _slot = wait_for_memory(&job.wanted); - let extra: Vec<&str> = job.extra.iter().map(|s| s.as_str()).collect(); - let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| compile_here(&job.src, &job.entry, &job.profile, &extra))) - .unwrap_or_else(|_| Err("DXC: panic in the compile thread".into())); - let _ = job.reply.send(r); - }); + let n = compile_threads(); + let q = Arc::new(Queue::::new(n, || crate::state::boot().is_some())); + let mut spawned = 0usize; + for k in 0..n { + let q = q.clone(); + if std::thread::Builder::new() + .name(format!("xcl-dxc-{k}")) + .stack_size(DXC_STACK) + .spawn(move || { + while let Some((job, wanted, _bg)) = q.pop() { + let _slot = wait_for_memory(&wanted); + let extra: Vec<&str> = job.extra.iter().map(|s| s.as_str()).collect(); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| compile_here(&job.src, &job.entry, &job.profile, &extra))) + .unwrap_or_else(|_| Err("DXC: panic in the compile thread".into())); + let _ = job.reply.send(r); + } + }) + .is_ok() + { + spawned += 1; + } + } + { + let mut s = q.state.lock().unwrap_or_else(|e| e.into_inner()); + if spawned == 0 { + s.closed = true; + } else { + s.total_workers = spawned; + } } - std::sync::Mutex::new(tx) + q }) } /// Compile HLSL to signed DXIL. `profile` e.g. "cs_6_6"; `extra` are dxc arguments. pub fn compile(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { let (reply, rx) = std::sync::mpsc::channel(); - let job = Job { src: src.into(), entry: entry.into(), profile: profile.into(), extra: extra.iter().map(|s| s.to_string()).collect(), reply, wanted: crate::hle::d3d12x::pso_async::wanted_here() }; - pool().lock().unwrap().send(job).map_err(|_| "DXC: no compile threads".to_string())?; + let job = Job { src: src.into(), entry: entry.into(), profile: profile.into(), extra: extra.iter().map(|s| s.to_string()).collect(), reply }; + pool().push(job, crate::hle::d3d12x::pso_async::wanted_here()).map_err(str::to_string)?; rx.recv().map_err(|_| "DXC: the compile thread exited".to_string())? } @@ -607,7 +766,7 @@ unsafe fn output(status: windows::core::Result, errors: windows::core:: let msg = errors .ok() .map(|b| { - let s = std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()); + let s = bytes_at(b.GetBufferPointer() as *const u8, b.GetBufferSize()); String::from_utf8_lossy(s).trim_end_matches('\0').to_string() }) .unwrap_or_default(); @@ -619,7 +778,15 @@ unsafe fn output(status: windows::core::Result, errors: windows::core:: return Err(format!("dxc: {msg}")); } let blob = result.map_err(|e| format!("{e}"))?; - Ok(std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec()) + Ok(bytes_at(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec()) +} + +unsafe fn bytes_at<'a>(p: *const u8, n: usize) -> &'a [u8] { + if p.is_null() || n == 0 { + &[] + } else { + std::slice::from_raw_parts(p, n) + } } fn compile_whole(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { @@ -1096,6 +1263,16 @@ pub fn in_cached_only() -> bool { } pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec, bool), String> { + // LOCAL EXPERIMENT: XCL_LOOP_FOR= XCL_LOOP_N=: the loop budget of that program alone + let patched; + let src = match (std::env::var("XCL_LOOP_FOR"), std::env::var("XCL_LOOP_N")) { + (Ok(t), Ok(n)) if !t.is_empty() && src.contains(&t) => { + patched = src.replacen("static uint xcl_budget = 1u << 16;", &format!("static uint xcl_budget = {n}u;"), 1); + crate::xlog_info!("[SHADER] loop budget {n} for a program of {} B HLSL ({entry}, {profile})", src.len()); + &patched[..] + } + _ => src, + }; compile_cached_in(&cache_dir(), src, entry, profile) } @@ -1518,6 +1695,194 @@ mod cache_tests { } } +#[cfg(test)] +mod pool_tests { + use super::*; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Barrier; + use std::time::Duration; + + fn run_pool(q: Arc>, workers: usize, work: impl Fn(J) + Send + Sync + 'static) -> Vec> { + let work = Arc::new(work); + (0..workers) + .map(|_| { + let (q, work) = (q.clone(), work.clone()); + std::thread::spawn(move || { + while let Some((job, _wanted, _bg)) = q.pop() { + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| work(job))); + } + }) + }) + .collect() + } + + #[test] + fn wanted_reserve_scales_with_worker_count() { + assert_eq!(wanted_reserve(1), 0); + assert_eq!(wanted_reserve(2), 1); + assert_eq!(wanted_reserve(3), 1); + assert_eq!(wanted_reserve(4), 1); + assert_eq!(wanted_reserve(6), 2); + assert_eq!(wanted_reserve(11), 3); + assert_eq!(wanted_reserve(15), 4); + assert_eq!(wanted_reserve(24), 4); + for total in 1..=32 { + let r = wanted_reserve(total); + assert!(r < total, "total={total} reserve={r} must leave >=1 background worker"); + if total >= 2 { + assert!((1..=4).contains(&r), "total={total} reserve={r}"); + } + } + } + + #[test] + fn wanted_job_jumps_ahead_of_queued_background_jobs() { + let q = Queue::<&'static str>::new(1, || true); + q.push("bg-1", Box::new(|| false)).unwrap(); + q.push("bg-2", Box::new(|| false)).unwrap(); + q.push("wanted-1", Box::new(|| true)).unwrap(); + q.push("bg-3", Box::new(|| false)).unwrap(); + q.push("wanted-2", Box::new(|| true)).unwrap(); + q.close(); + + let mut order = Vec::new(); + while let Some((name, _w, _bg)) = q.pop() { + order.push(name); + } + assert_eq!(order, ["wanted-1", "wanted-2", "bg-1", "bg-2", "bg-3"]); + } + + #[test] + fn wanted_job_runs_immediately_while_background_workers_are_saturated() { + // 4 workers, title running -> 3 background slots, 1 reserved for wanted jobs. + let q = Arc::new(Queue::>::new(4, || true)); + let (started_tx, started_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + let release_rx = Arc::new(Mutex::new(release_rx)); + let handles = run_pool(q.clone(), 4, |f| f()); + + // Saturate all 3 background slots with blocked jobs, plus 2 extra queued background jobs. + for i in 0..5 { + let (stx, rrx) = (started_tx.clone(), release_rx.clone()); + q.push( + Box::new(move || { + let _ = stx.send(i); + let _ = rrx.lock().unwrap().recv(); + }), + Box::new(|| false), + ) + .unwrap(); + } + for _ in 0..3 { + started_rx.recv_timeout(Duration::from_secs(2)).expect("background job started"); + } + // The 4th worker must stay reserved rather than picking up the 4th background job. + assert!(started_rx.recv_timeout(Duration::from_millis(40)).is_err(), "reserved worker took a background job"); + + // A wanted job starts and finishes right away on the reserved worker. + let (done_tx, done_rx) = std::sync::mpsc::channel(); + q.push(Box::new(move || done_tx.send("wanted-ok").unwrap()), Box::new(|| true)).unwrap(); + assert_eq!(done_rx.recv_timeout(Duration::from_secs(2)).expect("wanted job ran immediately"), "wanted-ok"); + + for _ in 0..5 { + release_tx.send(()).unwrap(); + } + q.close(); + for h in handles { + h.join().unwrap(); + } + } + + #[test] + fn queued_background_job_promoted_to_wanted_wakes_reserved_worker() { + let q = Arc::new(Queue::>::new(4, || true)); + let (started_tx, started_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + let release_rx = Arc::new(Mutex::new(release_rx)); + let handles = run_pool(q.clone(), 4, |f| f()); + + for i in 0..3 { + let (stx, rrx) = (started_tx.clone(), release_rx.clone()); + q.push( + Box::new(move || { + let _ = stx.send(i); + let _ = rrx.lock().unwrap().recv(); + }), + Box::new(|| false), + ) + .unwrap(); + } + for _ in 0..3 { + started_rx.recv_timeout(Duration::from_secs(2)).expect("background worker saturated"); + } + + // Queue a 4th job initially unwanted; it must wait while all 3 background slots are full. + let promoted = Arc::new(AtomicBool::new(false)); + let p_check = promoted.clone(); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + q.push( + Box::new(move || done_tx.send("promoted-ok").unwrap()), + Box::new(move || p_check.load(Ordering::Acquire)), + ) + .unwrap(); + assert!(done_rx.recv_timeout(Duration::from_millis(40)).is_err(), "unwanted job bypassed bg limit"); + + // Title binds the pipeline -> wanted flips true and wakes the reserved worker. + promoted.store(true, Ordering::Release); + q.notify_wanted(); + assert_eq!(done_rx.recv_timeout(Duration::from_secs(2)).expect("promoted job woke reserved worker"), "promoted-ok"); + + for _ in 0..3 { + release_tx.send(()).unwrap(); + } + q.close(); + for h in handles { + h.join().unwrap(); + } + } + + #[test] + fn offline_mode_uses_all_workers_for_background_jobs() { + let q = Arc::new(Queue::>::new(4, || false)); + let all_four = Arc::new(Barrier::new(4)); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let handles = run_pool(q.clone(), 4, |f| f()); + + for i in 0..4 { + let (b, tx) = (all_four.clone(), done_tx.clone()); + q.push( + Box::new(move || { + b.wait(); + tx.send(i).unwrap(); + }), + Box::new(|| false), + ) + .unwrap(); + } + for _ in 0..4 { + done_rx.recv_timeout(Duration::from_secs(2)).expect("all 4 offline workers ran concurrently"); + } + q.close(); + for h in handles { + h.join().unwrap(); + } + } + + #[test] + fn bg_slot_recovers_after_worker_panic() { + let q = Arc::new(Queue::>::new(2, || true)); + let handles = run_pool(q.clone(), 2, |f| f()); + q.push(Box::new(|| panic!("simulated compiler panic")), Box::new(|| false)).unwrap(); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + q.push(Box::new(move || done_tx.send("after-panic").unwrap()), Box::new(|| false)).unwrap(); + assert_eq!(done_rx.recv_timeout(Duration::from_secs(2)).expect("bg slot released after panic"), "after-panic"); + q.close(); + for h in handles { + h.join().unwrap(); + } + } +} + /// `src` compiled whole and linked with its memory accessors, whatever their number, with the /// seconds each took. #[cfg(test)] diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 2f817a809f..379d4e014a 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}; @@ -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, @@ -72,12 +71,32 @@ 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`) pub coherent_mem: 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 @@ -613,7 +632,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(), @@ -624,6 +643,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, } @@ -645,6 +665,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 { @@ -971,7 +992,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, }; @@ -1300,28 +1321,37 @@ 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}();")); } 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 { @@ -1597,9 +1627,11 @@ impl Em { return Err("indirect branch"); } if name == "s_getpc_b64" { - // the code region is addressed from 0 in this model + // the code region is addressed from 0 in this model – with constant data after the + // program and several memory windows, above them all (`rodata_loader`) let pc = d.pc + d.len as u64; - self.write64(&dst, &hex(pc as u32), "0u"); + let hi = if self.opt.rodata.is_empty() || self.opt.mem_windows <= 1 { "0u".to_string() } else { hex(super::CODE_ADDRESS_HI) }; + self.write64(&dst, &hex(pc as u32), &hi); return Ok(()); } if matches!(name, "s_bitset0_b64" | "s_bitset1_b64") { @@ -1882,7 +1914,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") { @@ -1963,18 +2003,20 @@ impl Em { } else { self.line(&format!("uint {t}_a = ({b} + {} + {soff}) & ~3u;", hex(imm))); } + // (with constant data in the code, which `s_load` reads too: `rodata_loader`) + let load = if self.opt.rodata.is_empty() { "mem.Load" } else { "xcl_gload" }; match count { 1 => { - self.line(&format!("uint {t}_0 = mem.Load({t}_a);")); + self.line(&format!("uint {t}_0 = {load}({t}_a);")); vals.push(format!("{t}_0")); } 2 => { - self.line(&format!("uint2 {t}_g0 = mem.Load2({t}_a);")); + self.line(&format!("uint2 {t}_g0 = {load}2({t}_a);")); vals.extend([format!("{t}_g0.x"), format!("{t}_g0.y")]); } _ => { for g in 0..count / 4 { - self.line(&format!("uint4 {t}_g{g} = mem.Load4({t}_a + {}u);", 16 * g)); + self.line(&format!("uint4 {t}_g{g} = {load}4({t}_a + {}u);", 16 * g)); vals.extend(["x", "y", "z", "w"].iter().map(|c| format!("{t}_g{g}.{c}"))); } } @@ -2325,18 +2367,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};")); } @@ -2387,15 +2437,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!("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!("res.Store((xcl_vtx + {}u) * 4u, {v});", 4 * (j + 1) + c)); } } } @@ -2436,10 +2490,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" => { @@ -4422,19 +4487,26 @@ impl Em { st.push(format!("mem.Store(({t}_a + {}u) & ~3u, {v});", 4 * i)); } else { let v = self.vreg(f("VDST") + i); - st.push(format!("{v} = mem.Load(({t}_a + {}u) & ~3u);", 4 * i)); + // (with constant data in the code: `rodata_loader`) + let load = if self.opt.rodata.is_empty() { "mem.Load" } else { "xcl_gload" }; + st.push(format!("{v} = {load}(({t}_a + {}u) & ~3u);", 4 * i)); } } self.line(&format!("if ({act}) {{ {} }}", st.join(" "))); 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(); @@ -4845,6 +4917,7 @@ impl Em { } else { h.push_str(LOADX4_ONE_WINDOW); } + h.push_str(&rodata_loader(&self.opt.rodata, windows > 1)); for (i, (_, cmp)) in self.static_used.iter().enumerate() { let k = self.opt.static_sampler_base as usize + i; let ty = if *cmp { "SamplerComparisonState" } else { "SamplerState" }; @@ -5023,12 +5096,20 @@ impl Em { h.push_str(" lane_id = WaveGetLaneIndex();\n"); } load_sgprs(&mut h); + // a folded dispatch (`IO_GROUP_LIMIT`): the console's group in X, the groups + // past its count left out (the whole group returns) + let _ = writeln!( + h, + " uint3 xcl_gid = gid;\n {{\n uint xcl_gl = io.Load({}u);\n if (xcl_gl != 0u) {{\n uint xcl_f = gid.x + gid.y * {}u;\n if (xcl_f >= xcl_gl) return;\n xcl_gid = uint3(xcl_f, 0u, gid.z);\n }}\n }}", + super::IO_GROUP_LIMIT * 4, + super::FOLD_X + ); // system SGPRs after the user data: enabled group ids, then TG_SIZE let mut next = cs.user_sgprs as u64; for (k, c) in ["x", "y", "z"].iter().enumerate() { if cs.tgid[k] { if sg.contains(&next) { - let _ = writeln!(h, " {} = gid.{c};", sname(next).unwrap()); + let _ = writeln!(h, " {} = xcl_gid.{c};", sname(next).unwrap()); } next += 1; } @@ -5246,7 +5327,9 @@ impl Em { // 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()); @@ -5273,7 +5356,13 @@ impl Em { 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"); } @@ -5733,6 +5822,34 @@ fn float_minmax_mem(min: bool, x2: bool, a: &str, v: &str, old: &str, t: &str) - /// Placeholder where the memory window accessors go (after the `mem` declarations). const MEM_ACCESSORS_HERE: &str = "//XCL_MEM_ACCESSORS\n"; +/// `Options::rodata`: the program's constant data as an array of the shader, and the dword +/// loads of `s_load` and FLAT / GLOBAL instructions that read it – a code address +/// (`s_getpc_b64` plus the compiler's offset: `CODE_ADDRESS_HI` with several memory windows, +/// the program's offset with one) inside one of the blocks gives the block's dword, any other +/// address the memory's. Nothing without data. +fn rodata_loader(rodata: &[(u32, Vec)], windows: bool) -> String { + let total: usize = rodata.iter().map(|b| b.1.len()).sum(); + if total == 0 { + return String::new(); + } + let words: Vec = rodata.iter().flat_map(|b| b.1.iter()).map(|w| format!("0x{w:08X}u")).collect(); + let mut s = format!("static const uint xcl_rodata[{total}] = {{ {} }};\nuint xcl_gload(uint a) {{\n", words.join(", ")); + let w0 = if windows { format!("xcl_w == {:#X}u - xcl_uma_base && ", super::CODE_ADDRESS_HI) } else { String::new() }; + let mut first = 0usize; + let mut inside = Vec::new(); + for (at, block) in rodata.iter().filter(|b| !b.1.is_empty()) { + let _ = writeln!(s, " [branch] if ({w0}a - {at}u < {}u) {{ return xcl_rodata[{first}u + ((a - {at}u) >> 2)]; }}", 4 * block.len()); + inside.push(format!("a - {at}u < {}u", 4 * block.len())); + first += block.len(); + } + s.push_str(" return mem.Load(a);\n}\n"); + // several dwords from `a` (`s_load_dwordx2` and up): one look at the address for all of them + let inside = format!("{w0}({})", inside.join(" || ")); + let _ = writeln!(s, "uint2 xcl_gload2(uint a) {{ [branch] if ({inside}) {{ return uint2(xcl_gload(a), xcl_gload(a + 4u)); }} return mem.Load2(a); }}"); + let _ = writeln!(s, "uint4 xcl_gload4(uint a) {{ [branch] if ({inside}) {{ return uint4(xcl_gload(a), xcl_gload(a + 4u), xcl_gload(a + 8u), xcl_gload(a + 12u)); }} return mem.Load4(a); }}"); + s +} + /// Four dwords at four addresses (scalar buffer loads with their bounds checks); with several /// windows `mem_accessors` defines it, with one switch for all four. const LOADX4_ONE_WINDOW: &str = "uint4 xcl_loadx4(uint4 a) { return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); }\n"; @@ -5832,14 +5949,16 @@ 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 - // does what the switch's `default` does - let _ = writeln!(s, "#define XCL_MW {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex({}u + xcl_w)]", super::MEM_HEAP_BASE); - let _ = writeln!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] if (xcl_w >= {windows}u) {{ return uint4(0u, 0u, 0u, 0u); }} XCL_MW; return uint4(m.Load(a.x), m.Load(a.y), m.Load(a.z), m.Load(a.w)); }}"); - for (ret, name, params, args, def) in mem_methods() { + // takes the null view at MEM_HEAP_NULL, which does what the switch's `default` does. No + // branch: a guard gives each access two paths, exploding basic blocks and handle PHIs in + // large HLSL pixel shaders and causing drivers to stall or reject them (#1695). + let null = super::MEM_HEAP_NULL - super::MEM_HEAP_BASE; + let index = if windows >= null { format!("min(xcl_w, {null}u)") } else { format!("select(xcl_w < {windows}u, xcl_w, {null}u)") }; + let _ = writeln!(s, "#define XCL_MW {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex({}u + {index})]", super::MEM_HEAP_BASE); + let _ = writeln!(s, "uint4 xcl_loadx4(uint4 a) {{ XCL_MW; return uint4(m.Load(a.x), m.Load(a.y), m.Load(a.z), m.Load(a.w)); }}"); + for (ret, name, params, args, _) in mem_methods() { let r = if ret == "void" { "" } else { "return " }; - // (the switch's `break` leaves the accessor) - let outside = def.replace("break;", "return;"); - let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ [branch] if (xcl_w >= {windows}u) {{ {outside} }} XCL_MW; {r}m.{name}({args}); }}"); + let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ XCL_MW; {r}m.{name}({args}); }}"); } return s; } @@ -6431,6 +6550,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); 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/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 0d86a1607e..54df58357a 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -1304,12 +1304,15 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s prev = c; } } - // compute: every lane that runs is in EXEC, and nothing is stored at the end – the skip and - // store blocks are left unreachable (a bare `ret`) + // compute: every lane that runs is in EXEC, and nothing is stored at the end – the store + // blocks are left unreachable, and the skip block (a bare `ret`) takes the groups past a + // folded dispatch's count if kernel { preds[skip] = vec![0]; preds[sstore] = vec![exit]; preds[vstore] = vec![exit, sstore]; + } else if matches!(stage, Stage::Compute(_)) { + preds[skip] = vec![0]; } preds[exit] = kernel.then_some(skip).into_iter().chain(ends.iter().map(|&b| tail[b])).collect(); for i in 0..count { @@ -1402,11 +1405,25 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s } Stage::Compute(cs) => { let (flat, tid) = l.ir.compute_ids(cs.threads); + // a dispatch folded into Y (`IO_GROUP_LIMIT` not 0: the console's group count in X): + // the group in X from both ids, the groups past the count leave at once + let a = l.ir.int(super::IO_GROUP_LIMIT as u32); + let limit = l.ir.io_load(a); + let (gx, gy) = (l.ir.group_id(0), l.ir.group_id(1)); + let k = l.ir.int(super::FOLD_X); + let rows = l.ir.bin(Bin::Mul, gy, k); + let group = l.ir.bin(Bin::Add, gx, rows); + let z = l.ir.int(0); + let folded = l.ir.icmp(Cmp::Ne, limit, z); + let ids = [l.ir.select(folded, group, gx), l.ir.select(folded, z, gy)]; + let inside = l.ir.icmp(Cmp::Ult, group, limit); + let t = l.ir.boolean(true); + let runs = l.ir.select(folded, inside, t); // system SGPRs after the user data: the enabled group ids, then TG_SIZE let mut next = cs.user_sgprs as u8; for k in 0..3 { if cs.tgid[k as usize] { - let g = l.ir.group_id(k); + let g = if k < 2 { ids[k as usize] } else { l.ir.group_id(k) }; l.write_num(0, next, g); next += 1; } @@ -1436,7 +1453,7 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s // every lane that runs is in EXEC let t = l.ir.boolean(true); l.write_bit(0, EXEC, t); - l.ir.br(blk(0)); + l.ir.br_if(runs, blk(0), skip); l.ir.at(skip); l.ssa.seal(&mut l.ir, skip); l.ir.ret(); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 528493d6e5..6cdfe0835c 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; @@ -81,10 +82,19 @@ mod link_tests; /// (`console_heap::null_views`). pub const MEM_HEAP_BASE: u32 = 4; +/// The null raw UAV after the windows' views: an `xcl_w` outside the windows takes it (reads 0, +/// stores and atomics dropped, atomics return 0: the switch's `default`). +pub const MEM_HEAP_NULL: u32 = MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32; + /// Flag in a memory-windows count (`pso::mem_windows`, the translation caches' keys): /// `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 (it uses `MEM_HEAP_NULL` unconditionally). +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 +129,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 +163,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 +177,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 @@ -204,6 +219,19 @@ pub const GS_PRIMS_PER_GROUP: u32 = 21; pub const IO_GS_PRIMS: usize = 110; pub const IO_GS_VERTICES: usize = 111; pub const IO_UMA_BASE_HI: usize = 112; +/// io slot (trap-temp range) of a compute dispatch whose groups were folded: the console's group +/// count in X, 0 when not folded. The console takes up to 2^32 - 1 groups a dimension, D3D12 +/// 65 535 - a dispatch of more in X (and 1 in Y) runs as 65 535 x ceil(n / 65 535) groups, and +/// the translated program takes `gid.x + gid.y * 65 535` as its group in X, leaving out the +/// groups at or past `n`. +pub const IO_GROUP_LIMIT: usize = 113; +/// Groups a folded dispatch has in X. +pub const FOLD_X: u32 = 65_535; +/// High dword `s_getpc_b64` gives a program that has constant data in its code region +/// (`Options::rodata`) and several memory windows: its code addresses are then above every +/// address a title can have (user space ends at 0x7FFF_FFFF_FFFF), so a load from the data is +/// told from a load of the title's memory at the same low dword (descriptor tables in window 0). +pub const CODE_ADDRESS_HI: u32 = 0xC0DE; impl GsInterface { /// bytes of one ES vertex in LDS (ESGS item: 16 per ES output register) @@ -230,6 +258,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, } } } @@ -367,6 +396,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 @@ -374,6 +416,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())); @@ -384,20 +431,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 { @@ -406,14 +468,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 { @@ -434,7 +560,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), } } @@ -442,7 +571,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(), } } @@ -471,7 +600,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() })), @@ -491,6 +622,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, @@ -521,18 +653,25 @@ pub struct Options { /// every access from the high address bits pub mem_windows: u32, /// with `mem_windows` > 1: reach window k through descriptor `MEM_HEAP_BASE + k` of the - /// shader-visible heap (a raw UAV of the window, `ResourceDescriptorHeap`) – one access per - /// site instead of a `switch` over the root UAVs `mem`, `mem1`.., which inlines every - /// access once per window (HANDOFF: twice the DXC + driver time with 4 windows) + /// shader-visible heap (a raw UAV of the window, `ResourceDescriptorHeap`; `MEM_HEAP_NULL` + /// outside the windows) – one access per site, with no branch, instead of a `switch` over the + /// root UAVs `mem`, `mem1`.., which inlines every access once per window (HANDOFF: twice the + /// DXC + driver time with 4 windows) pub heap_windows: bool, /// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`: /// always the guarded block chain) pub structured: bool, + /// constant data the console compiler put in the code region after the program + /// (`xbox::Fssm::rodata`): (address from the program's start, dwords). The program finds + /// it with `s_getpc_b64` and reads it with `s_load` / `global_load`; the title's memory does + /// not hold the code, so a load at a code address in one of these ranges takes the dwords + /// from the shader (`CODE_ADDRESS_HI`) + pub rodata: Vec<(u32, Vec)>, } impl Default for Options { fn default() -> Self { - Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true } + Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true, rodata: Vec::new() } } } @@ -565,6 +704,8 @@ struct Ctx<'a> { starts: &'a BTreeSet, leaders: &'a [u64], loops: &'a [(u64, u64)], + /// [`budget_regions`] + regions: &'a [(u64, u64)], /// every branch: (address of the branch, target) edges: &'a [(u64, u64)], /// split wave64 geometry mode: the ES's s_setpc ends the ES phase and `gs_start` is the GS @@ -647,6 +788,74 @@ impl Conts { /// leaves at its next iteration and the program runs to its end. const LOOP_GUARD: &str = "if (xcl_budget == 0u) break; xcl_budget--;"; +/// A program with two or more loop regions gives each this many budgets of iterations +/// ([`loop_guard`]): a title's own spin capped at one budget (0x10000 tries) must fit, also +/// when it sits in an outer loop whose head spends from the same count. +pub(crate) const LOOP_BUDGETS_PER_REGION: u32 = 2; +/// ... and all of its regions together at most this many. +pub(crate) const LOOP_BUDGETS_IN_ALL: u32 = 4; + +/// The outermost of [`loop_ranges`]: the program's loop regions, in order. Control only moves +/// forward from one to the next (a jump back into an earlier one would make them one range). +/// Empty for a program with fewer than two, whose guards stay [`LOOP_GUARD`]. +pub(crate) fn budget_regions(loops: &[(u64, u64)]) -> Vec<(u64, u64)> { + let outer: Vec<(u64, u64)> = loops.iter().copied().filter(|&(a, b)| !loops.iter().any(|&(c, d)| (c, d) != (a, b) && c <= a && b <= d)).collect(); + if outer.len() < 2 { + Vec::new() + } else { + outer + } +} + +/// The region ([`budget_regions`]) of the loop headed at `head`, numbered from 1. +pub(crate) fn budget_region(regions: &[(u64, u64)], head: u64) -> Option { + regions.iter().position(|&(a, b)| a <= head && head < b).map(|k| k as u32 + 1) +} + +/// An iteration of a loop spends one of the loop budget for every this many bytes of the loop's +/// code ([`loop_cost`]) ... +pub(crate) const LOOP_COST_BYTES: u64 = 128; +/// ... and at most this many: the longest loop still gets 256 iterations of one budget. +pub(crate) const LOOP_COST_MOST: u32 = 256; + +/// What an iteration of the loop headed at `head` spends of the loop budget: 1 for a short +/// loop, more for a long one (the innermost of `loops` that holds `head`, a unit for every +/// [`LOOP_COST_BYTES`] of it). The budget counts iterations, and what an iteration costs the GPU +/// grows with the loop: a retail program's 9 KB loop nest, given what made every one of its +/// loops run on, spent its 131 072 iterations in one group of 64 lanes for more than 20 s, and +/// the driver was reset. With the cost that nest stops after 1 771 iterations. A loop shorter +/// than twice the unit costs 1, and its guard is what it was. A ray-tracing program's budget is +/// small already (`dxil::kernel::RT_LOOP_BUDGET`): its loops cost 1. +pub(crate) fn loop_cost(loops: &[(u64, u64)], head: u64) -> u32 { + if crate::gpu::dxil::kernel::loop_budget() == crate::gpu::dxil::kernel::RT_LOOP_BUDGET { + return 1; + } + let innermost = loops.iter().filter(|&&(a, b)| a <= head && head < b).map(|&(a, b)| b - a).min(); + innermost.map_or(1, |len| (len / LOOP_COST_BYTES).clamp(1, LOOP_COST_MOST as u64) as u32) +} + +/// The guard of the loop headed at `head`. In a program with loop regions, each region starts +/// with [`LOOP_BUDGETS_PER_REGION`] budgets, and `xcl_btotal` keeps all of them to +/// [`LOOP_BUDGETS_IN_ALL`]: a title's own spin that gives up after 0x10000 tries, the budget, +/// otherwise left every loop after it without an iteration (a retail FSR pass then published a +/// flag made from a register its main loop never set, and the pass waiting on that flag spun +/// 260 ms a frame). +/// An iteration spends [`loop_cost`] of them (of `loops`, the ranges the loops are emitted from). +fn loop_guard(regions: &[(u64, u64)], loops: &[(u64, u64)], head: u64) -> String { + match (budget_region(regions, head), loop_cost(loops, head)) { + (Some(r), 1) => format!( + "if (xcl_bown != {r}u) {{ xcl_bown = {r}u; xcl_budget = {}u; }} if (xcl_budget == 0u || xcl_btotal == 0u) break; xcl_budget--; xcl_btotal--;", + LOOP_BUDGETS_PER_REGION << 16 + ), + (Some(r), k) => format!( + "if (xcl_bown != {r}u) {{ xcl_bown = {r}u; xcl_budget = {}u; }} if (xcl_budget < {k}u || xcl_btotal < {k}u) break; xcl_budget -= {k}u; xcl_btotal -= {k}u;", + LOOP_BUDGETS_PER_REGION << 16 + ), + (None, 1) => LOOP_GUARD.to_string(), + (None, k) => format!("if (xcl_budget < {k}u) break; xcl_budget -= {k}u;"), + } +} + /// Structured code longer than this many bytes per byte of program falls back to the `pc` form. /// Each guard of the structured form lists every pending skip flag, so it grows with the /// square of the flags: one retail program made 455 B per byte (148 MB, 14 MB as `pc` blocks), @@ -656,7 +865,7 @@ const STRUCTURED_BYTES_PER_CODE_BYTE: usize = 128; /// The loops the translator emits: ranges spanned by backward jumps (far jumps included), /// partly overlapping ones merged until they nest, sorted. `x64_masks` uses them for the /// exits through `LOOP_GUARD`. -pub(super) fn loop_ranges(insts: &[Decoded]) -> Vec<(u64, u64)> { +pub(crate) fn loop_ranges(insts: &[Decoded]) -> Vec<(u64, u64)> { let mut loops: Vec<(u64, u64)> = Vec::new(); for d in insts { if let Some(t) = rdna2::branch_target(d) { @@ -1098,7 +1307,7 @@ fn emit_structured( } let raised: BTreeSet = match it { Item::Loop { a, b, latch, entry } => { - body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {LOOP_GUARD}\n")); + body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {}\n", loop_guard(c.regions, c.loops, a))); let (lcont, lin) = if entry.is_none() { (cont.enter(Some(a)), &inner) } else { (cont.enter(None), &none) }; let mut r = emit_structured(c, em, body, entry.unwrap_or(a), latch, None, nest + 1, &lcont, lin, d + 1, blocks, flags); for &t in &r { @@ -1219,7 +1428,7 @@ fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, d let start = c.leaders[i]; let inner = c.loops.iter().filter(|&&(a, b)| a == start && b <= hi && (a, b) != (lo, hi)).max_by_key(|x| x.1).copied(); if let Some((a, b)) = inner { - body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {LOOP_GUARD}\n")); + body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {}\n", loop_guard(c.regions, c.loops, a))); emit_range(c, em, body, a, b, depth + 1, blocks, flags); body.push_str(&format!("{pad}}}\n")); i = c.leaders.partition_point(|&l| l < b); @@ -1425,47 +1634,115 @@ fn scalar_constant(d: &Decoded, code: u64) -> Option { } /// S# built from constants in the code – how the console compiler places the static -/// samplers of a root signature: for each MIMG instruction whose four sampler SGPRs were all -/// set by s_mov / s_movk / s_brev with constants earlier in its block, those words. -pub(crate) fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet) -> BTreeMap { - let mut known: std::collections::HashMap = std::collections::HashMap::new(); - let mut out = BTreeMap::new(); - for d in insts { - if leaders.contains(&d.pc) { - known.clear(); - } - let f = |n: &str| rdna2::field_value(d.enc, &d.words, n); - if d.enc.name == "ENC_MIMG" { - if let Some(s) = f("SSAMP").map(|v| v * rdna2::register_scale("SSAMP")) { - if let (Some(a), Some(b), Some(c), Some(e)) = (known.get(&s), known.get(&(s + 1)), known.get(&(s + 2)), known.get(&(s + 3))) { - out.insert(d.pc, [*a, *b, *c, *e]); +/// samplers of a root signature: for each MIMG instruction whose four sampler SGPRs hold +/// constants set by s_mov / s_movk / s_brev on every path that reaches it, those words. +/// +/// The constants are followed through the program's branches (the compiler sets an S# before a +/// loop or an `if` and samples inside it): a register is a constant at a block's start when +/// every block that leads there leaves it with the same one. A program with a branch whose +/// target is not known is read block by block, as nothing is known at a block's start then. +/// +/// `follow`: the stages that draw (vertex and pixel programs). The other programs are read +/// block by block as before: on a retail title, compute programs read this way gave garbage +/// counts to `ExecuteIndirect` (2 055 in 75 s, none before) and the device hung. +pub(crate) fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet, follow: bool) -> BTreeMap { + type Known = std::collections::HashMap; + // one block's instructions on `known`; the S# of its MIMG instructions into `out` + fn run(block: &[Decoded], known: &mut Known, mut out: Option<&mut BTreeMap>) { + for d in block { + let f = |n: &str| rdna2::field_value(d.enc, &d.words, n); + if d.enc.name == "ENC_MIMG" { + if let (Some(out), Some(s)) = (out.as_deref_mut(), f("SSAMP").map(|v| v * rdna2::register_scale("SSAMP"))) { + if let (Some(a), Some(b), Some(c), Some(e)) = (known.get(&s), known.get(&(s + 1)), known.get(&(s + 2)), known.get(&(s + 3))) { + out.insert(d.pc, [*a, *b, *c, *e]); + } } } - } - let set: Vec<(u64, u32)> = match d.inst.name { - "S_MOV_B32" => f("SDST").zip(f("SSRC0").and_then(|c| scalar_constant(d, c))).map(|(r, v)| vec![(r, v)]).unwrap_or_default(), - "S_MOVK_I32" => f("SDST").zip(f("SIMM16")).map(|(r, v)| vec![(r, v as u16 as i16 as i32 as u32)]).unwrap_or_default(), - // a constant with only high bits set, as the compiler writes it: `s_brev_b32 s66, 40` - "S_BREV_B32" => f("SDST").zip(f("SSRC0").and_then(|c| scalar_constant(d, c))).map(|(r, v)| vec![(r, v.reverse_bits())]).unwrap_or_default(), - // 64-bit moves of inline integers (sign-extended): S# words that are 0 / -1 - "S_MOV_B64" => match (f("SDST"), f("SSRC0")) { - (Some(r), Some(c @ 128..=208)) => { - let v = scalar_constant(d, c).unwrap() as i32 as i64; - vec![(r, v as u32), (r + 1, (v >> 32) as u32)] - } + let set: Vec<(u64, u32)> = match d.inst.name { + "S_MOV_B32" => f("SDST").zip(f("SSRC0").and_then(|c| scalar_constant(d, c))).map(|(r, v)| vec![(r, v)]).unwrap_or_default(), + "S_MOVK_I32" => f("SDST").zip(f("SIMM16")).map(|(r, v)| vec![(r, v as u16 as i16 as i32 as u32)]).unwrap_or_default(), + // a constant with only high bits set, as the compiler writes it: `s_brev_b32 s66, 40` + "S_BREV_B32" => f("SDST").zip(f("SSRC0").and_then(|c| scalar_constant(d, c))).map(|(r, v)| vec![(r, v.reverse_bits())]).unwrap_or_default(), + // 64-bit moves of inline integers (sign-extended): S# words that are 0 / -1 + "S_MOV_B64" => match (f("SDST"), f("SSRC0")) { + (Some(r), Some(c @ 128..=208)) => { + let v = scalar_constant(d, c).unwrap() as i32 as i64; + vec![(r, v as u32), (r + 1, (v >> 32) as u32)] + } + _ => Vec::new(), + }, _ => Vec::new(), - }, - _ => Vec::new(), - }; - for w in rdna2::sgpr_uses(d).1 { - known.remove(&w); + }; + for w in rdna2::sgpr_uses(d).1 { + known.remove(&w); + } + for (r, v) in set { + if r < 106 { + known.insert(r, v); + } + } } - for (r, v) in set { - if r < 106 { - known.insert(r, v); + } + // the blocks, in address order + let mut starts: Vec = insts.iter().enumerate().filter(|(i, d)| *i == 0 || leaders.contains(&d.pc)).map(|(i, _)| i).collect(); + starts.push(insts.len()); + let blocks: Vec<&[Decoded]> = starts.windows(2).map(|w| &insts[w[0]..w[1]]).filter(|b| !b.is_empty()).collect(); + let at: std::collections::HashMap = blocks.iter().enumerate().map(|(k, b)| (b[0].pc, k)).collect(); + // where each block goes on; None: somewhere that is not known + let next: Option>> = blocks + .iter() + .enumerate() + .map(|(k, b)| { + let d = b.last().unwrap(); + let after = (k + 1 < blocks.len()).then_some(k + 1); + Some(match (rdna2::branch_target(d), d.inst.name) { + (Some(t), n) if n.starts_with("S_CBRANCH") => after.into_iter().chain([*at.get(&t)?]).collect(), + (Some(t), "S_BRANCH" | "S_SETPC_B64") => vec![*at.get(&t)?], + (Some(_), _) => return None, + (None, "S_ENDPGM") => Vec::new(), + (None, _) if d.inst.flags & rdna2::F_TERMINATOR != 0 => return None, + _ => after.into_iter().collect(), + }) + }) + .collect(); + let mut out = BTreeMap::new(); + let Some(next) = next.filter(|_| follow) else { + for b in &blocks { + run(b, &mut Known::new(), Some(&mut out)); + } + return out; + }; + // what is known at each block's start (None: not reached yet): what every way in agrees on + let mut start: Vec> = vec![None; blocks.len()]; + let mut work: Vec = Vec::new(); + if !blocks.is_empty() { + start[0] = Some(Known::new()); + work.push(0); + } + while let Some(k) = work.pop() { + let mut known = start[k].clone().unwrap_or_default(); + run(blocks[k], &mut known, None); + for &n in &next[k] { + let changed = match &mut start[n] { + slot @ None => { + *slot = Some(known.clone()); + true + } + Some(have) => { + let before = have.len(); + have.retain(|r, v| known.get(r) == Some(v)); + have.len() != before + } + }; + if changed { + work.push(n); } } } + for (k, b) in blocks.iter().enumerate() { + // (a block nothing leads to: nothing known at its start) + run(b, &mut start[k].clone().unwrap_or_default(), Some(&mut out)); + } out } @@ -1501,7 +1778,7 @@ 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() }; + normalized = Options { mem_windows: opt.mem_windows & !(HEAP_WINDOWS | HEAP_FLAT), heap_windows: true, ..opt.clone() }; &normalized } else { opt @@ -1549,14 +1826,14 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { let mut em = emit::Em::new(opt.clone()); em.coherent_mem = matches!(opt.mode, Mode::Compute(_)) && needs_coherent_mem(&insts); em.configure_round_modes(&insts, branches == 0); - em.static_ss = constant_samplers(&insts, &leaders); + em.static_ss = constant_samplers(&insts, &leaders, matches!(opt.mode, Mode::Vertex(_) | Mode::Pixel(_))); // split wave64: masks only read lane by lane skip the halves' exchange (geometry mode // 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 @@ -1597,13 +1874,20 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // (optimising one big dispatcher loop took minutes on large retail programs). let leaders: Vec = leaders.into_iter().filter(|l| starts.contains(l)).collect(); let loops = loop_ranges(&insts); + // Per-region loop budgets target compute spin-wait passes (PR #2793); keep graphics/mesh + // stages on the single-budget CFG. + let regions = if matches!(opt.mode, Mode::Compute(_) | Mode::Kernel) { + budget_regions(&loops) + } else { + Vec::new() + }; let edges: Vec<(u64, u64)> = insts.iter().filter_map(|d| rdna2::branch_target(d).map(|t| (d.pc, t))).collect(); let phase_split = gs_jump.is_some_and(|t| t.is_some()) && opt.split_wave64 && opt.wave64; - let ctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &loops, edges: &edges, phase_split, memo: Default::default() }; + let ctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &loops, regions: ®ions, edges: &edges, phase_split, memo: Default::default() }; let mut flags = BTreeSet::new(); let mut code = String::new(); let nested = nested_loop_ranges(&insts); - let sctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &nested, edges: &edges, phase_split, memo: Default::default() }; + let sctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &nested, regions: ®ions, edges: &edges, phase_split, memo: Default::default() }; if gs_jump.is_none() && opt.structured && std::env::var_os("XCL_RECOMP_NO_STRUCTURED").is_none() && structurable(&sctx, 0, u64::MAX).is_some() { // structured control flow: plain if / loops, no block dispatch on `pc` (much // smaller for DXC and the driver on big programs) @@ -1619,6 +1903,9 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { } emit_range(&ctx, &mut em, &mut code, 0, u64::MAX, 1, &mut blocks, &mut flags); } + if !regions.is_empty() { + body.push_str(&format!(" uint xcl_bown = 0u;\n uint xcl_btotal = {}u;\n", LOOP_BUDGETS_IN_ALL << 16)); + } for &t in &flags { body.push_str(&format!(" bool {} = false;\n", skip_flag(t))); } @@ -1664,6 +1951,114 @@ mod attribute_tests { assert_eq!(ps_attribute_slot(&ps, 1, 0), Some(1)); } + /// DB_SHADER_CONTROL follows SPI_PS_INPUT_ENA in the input table: DEPTH_BEFORE_SHADER (bit + /// 12) makes a PS early-depth; other bits (Z export, kill, the ordered-section bit 16) do not. + #[test] + fn ps_depth_before_shader_from_the_input_table() { + let early = |sub: u32, control: u32, valid: bool| { + let base = if sub == 5 { 0x130 } else { 0x138 }; + let mut data = vec![0u8; 0x400]; + data[0x10..0x14].copy_from_slice(&sub.to_le_bytes()); + data[base..base + 8].copy_from_slice(&[6, 1, 0xF, 0, 0, 0, 1, 2]); + data[base + 0x100] = if valid { 1 } else { 33 }; + data[base + 0x110] = 2; + data[base + 0x114..base + 0x118].copy_from_slice(&control.to_le_bytes()); + assert_eq!(ps_shader_control(&data), Some(control)); + let f = super::super::xbox::Fssm { data, stages: vec![super::super::xbox::HwStage { offset: 0, hw: 5, api: 1 }], ..Default::default() }; + let sh = super::super::xbox::XboxShader { stage: "PS".into(), ..Default::default() }; + let Some(Mode::Pixel(ps)) = interface(&[], &sh, &f) else { panic!("not a PS") }; + ps.early_depth + }; + for sub in [5, 6] { + assert!(early(sub, DEPTH_BEFORE_SHADER, true), "sub-version {sub}"); + assert!(early(sub, DEPTH_BEFORE_SHADER | 1 << 16 | 0x41, true), "sub-version {sub}, with other bits"); + assert!(!early(sub, 1 << 16 | 0x41, true), "sub-version {sub}, without the bit"); + // no input table found: the layout is not known, the bit not trusted + assert!(!early(sub, DEPTH_BEFORE_SHADER, false), "sub-version {sub}, no table"); + } + } + + /// A signature with float16 elements (component type 6) between float ones, in the shapes a + /// retail title's PS / MS pack: r7 holds two elements, r9 a single component. + fn f16_sig() -> Vec { + let e = |name: &str, index: u32, ct: u32, register: u32, mask: u8| SigElement { component_type: ct, mask, ..input(name, index, register, mask) }; + let mut pos = input("SV_Position", 0, 0, 0); + pos.system_value = 1; + vec![ + pos, + e("COLOR", 0, 6, 1, 0xF), + e("COLOR", 1, 6, 2, 0xF), + e("TEXCOORD", 0, 3, 3, 0x3), + e("TEXCOORD", 1, 6, 4, 0x7), + e("TEXCOORD", 4, 6, 5, 0xF), + e("TEXCOORD", 3, 3, 6, 0xF), + e("TEXCOORD", 7, 6, 7, 0x3), + e("TEXCOORD", 8, 6, 7, 0xC), + e("TEXCOORD", 9, 6, 8, 0x7), + e("TEXCOORD", 14, 6, 9, 0x1), + ] + } + + /// Float16 interpolants packed two per dword and two registers per attribute (the record + /// shapes of a retail title's PS, FSSM sub-version 6): the table parses, each (dword, half) + /// names its element and component, the second register is found where the record does not + /// name it, and the attributes after a pair keep their registers. + #[test] + fn f16_packed_attributes() { + let sig = f16_sig(); + let mut f = vec![0u8; 0x400]; + f[0x10] = 6; + // PS input records: [6, reg, 3, attr, 0, reg2, packed register, 0x1a]; attr 4 repeats + // its own register (the second one is r8); attr 5 is a single float16 (0x0a) + let recs: [[u8; 8]; 6] = [[6, 1, 3, 0, 0, 2, 1, 26], [6, 3, 3, 1, 0, 0, 2, 2], [6, 4, 3, 2, 0, 5, 3, 26], [6, 6, 15, 3, 0, 0, 4, 2], [6, 7, 3, 4, 0, 7, 5, 26], [6, 9, 1, 5, 0, 0, 6, 10]]; + f[0x138..0x138 + 48].copy_from_slice(&recs.concat()); + f[0x138 + 0x100] = 6; + f[0x138 + 0x110] = 2; + let (_, attrs) = ps_input_table(&f).unwrap(); + assert_eq!(attrs.iter().map(|a| (a.register, a.f16, a.pair)).collect::>(), [(1, true, Some(2)), (3, false, None), (4, true, Some(5)), (6, false, None), (7, true, Some(7)), (9, true, None)]); + let ps = PsInterface { inputs: sig, attrs: Some(attrs), ..Default::default() }; + assert_eq!((0..6).map(|a| ps_attribute_f16(&ps, a)).collect::>(), [Some(vec![(1, 0), (2, 2)]), None, Some(vec![(4, 0), (5, 2)]), None, Some(vec![(7, 0), (8, 2)]), Some(vec![(9, 0)])]); + let all = ranked(&ps.inputs, false); + // "semantic.component" of a (dword, half) + let at = |attr: usize, chan: usize, high: bool| ps_f16_slot(&ps, &ps_attribute_f16(&ps, attr).unwrap(), chan, high).map(|(s, c)| format!("{}.{c}", all[s].semantic())).unwrap_or_default(); + assert_eq!([at(0, 0, false), at(0, 0, true), at(0, 1, true), at(0, 2, false), at(0, 3, true)], ["COLOR0.0", "COLOR0.1", "COLOR0.3", "COLOR1.0", "COLOR1.3"]); + assert_eq!([at(2, 1, false), at(2, 2, true)], ["TEXCOORD1.2", "TEXCOORD4.1"]); + // two elements in the first register; a half past the last one's components + assert_eq!([at(4, 0, true), at(4, 1, true), at(4, 2, false)], ["TEXCOORD7.1", "TEXCOORD8.3", "TEXCOORD9.0"]); + assert_eq!([at(5, 0, false), at(5, 2, false)], ["TEXCOORD14.0", ""]); + // the attributes after a pair read their own registers + assert_eq!([1, 3].map(|a| all[ps_attribute_slot(&ps, a, 0).unwrap()].semantic()), ["TEXCOORD0", "TEXCOORD3"]); + assert_eq!((0..10).map(|j| ps_slot_attribute(&ps, j)).collect::>(), [0, 0, 1, 2, 2, 3, 4, 4, 4, 5].map(Some)); + // a second register without the float16 flag is not this table + f[0x138 + 7] = 18; + assert_eq!(ps_input_table(&f), None); + + // a .xy register takes one dword: the second register starts at dword 1 + let narrow = vec![SigElement { component_type: 6, mask: 0x3, ..input("COLOR", 3, 1, 0x3) }, SigElement { component_type: 6, mask: 0x7, ..input("TEXCOORD", 8, 2, 0x7) }]; + assert_eq!(f16_registers(&narrow, 1, None, true, &|r| r == 1), [(1, 0), (2, 1)]); + } + + /// Float16 params packed the same way in a VS / MS output table (the record shapes of the + /// title's MS): the table parses, the second register of a pair is the next float16 register + /// that starts no param of its own (the record does not name it), and `exp param N` writes + /// the elements of both registers. + #[test] + fn f16_packed_params() { + let sig = f16_sig(); + let mut f = vec![0u8; 0x400]; + f[0x10] = 6; + // VS / MS output records: [6, reg, param, reg, 0, 3]; param 5 is a single float16 (1) + let outs: [[u8; 6]; 6] = [[6, 1, 0, 1, 0, 3], [6, 3, 1, 0, 0, 0], [6, 4, 2, 4, 0, 3], [6, 6, 3, 0, 0, 0], [6, 7, 4, 7, 0, 3], [6, 9, 5, 0, 0, 1]]; + f[0x1DC..0x1DC + 36].copy_from_slice(&outs.concat()); + f[0x1DC + 0xC0] = 6; + let params = vs_output_table(&f).unwrap(); + assert_eq!(params.iter().map(|p| (p.register, p.f16, p.pair)).collect::>(), [(1, true, true), (3, false, false), (4, true, true), (6, false, false), (7, true, true), (9, true, false)]); + let regs = |n: usize| out_param_registers(&sig, Some(¶ms), n); + assert_eq!([regs(0), regs(1), regs(4), regs(5), regs(6)], [Some((vec![(1, 0), (2, 2)], true)), Some((vec![(3, 0)], false)), Some((vec![(7, 0), (8, 2)], true)), Some((vec![(9, 0)], true)), None]); + // elements in `ranked` order: r7 holds two, r8 one + assert_eq!(out_param_elements(&sig, Some(¶ms), 4), (vec![(6, 0), (7, 0), (8, 2)], true)); + } + /// Minecraft's UI vertex shader: an ISG1 input the program never reads (NORMAL0, r1) gets /// no fetch-shader VGPRs – POSITION0 (r2) is read in v8, TEXCOORD0 (r3) in v12. #[test] @@ -1701,7 +2096,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 da4b25e5fb..eafcfe9540 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -77,9 +77,34 @@ pub fn fspx(blob: &[u8]) -> Option> { /// Memory windows of the title's unified memory (1 without it), with `HEAP_WINDOWS` when /// shaders take them from the descriptor heap (`heap_windows`). 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 | super::HEAP_FLAT), + title & super::HEAP_WINDOWS != 0 && !SWITCH_FORM.with(|s| s.get()), + title & super::HEAP_FLAT != 0, + ); + } let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32); - if n > 1 && heap_windows() && !SWITCH_FORM.with(|s| s.get()) { - n | super::HEAP_WINDOWS + windows_for(n, heap_windows() && !SWITCH_FORM.with(|s| s.get()), heap_flat()) +} + +/// The title's windows (`mem_windows` with `HEAP_WINDOWS`) for a process without its memory: a +/// shader preparation worker builds the title's pipelines with them (0: none given). +static TITLE_WINDOWS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// `mem_windows` is `windows` from here on (a preparation worker: `uma::leave_out`). +pub fn set_title_windows(windows: u32) { + TITLE_WINDOWS.store(windows, std::sync::atomic::Ordering::Relaxed); +} + +/// `n` windows as shaders take them: from the descriptor heap (`heap`), or in the switch form +/// over the root UAVs – of which there are `MAX_WINDOWS`, so never more there (the HLSL path +/// refused a wider switch, and DXIL quietly made it 4: a 16-window run whose heap views could +/// not be made, or a pipeline the driver refused with them, lost every shader on HLSL). +fn windows_for(n: u32, heap: bool, flat: bool) -> u32 { + if n > 1 && heap { + n | super::HEAP_WINDOWS | if flat { super::HEAP_FLAT } else { 0 } } else { n } @@ -105,24 +130,30 @@ pub fn in_switch_form(f: impl FnOnce() -> R) -> R { } /// Whether translated shaders reach the memory windows through the shared descriptor heap -/// (`Options::heap_windows`; descriptors `MEM_HEAP_BASE`.. made by `console_heap::set_window_views`) -/// instead of a `switch` over root UAVs. Opt-in: on with `XCL_HEAP_WINDOWS=1`, unless the views -/// could not be made (no shared heap: then the switch, as before). Off by default: two NVIDIA -/// setups failed with it (the driver's compiler ending the process; a device removal when the -/// views are made on an 8 GB card) that other machines do not show. +/// (`Options::heap_windows`; descriptors `MEM_HEAP_BASE`..=`MEM_HEAP_NULL` made by `console_heap::set_window_views`) +/// instead of a `switch` over root UAVs. Default ON (`XCL_HEAP_WINDOWS=0` to fall back to the +/// 4-arm switch form), unless the views could not be made (no shared heap: then the switch). pub fn heap_windows() -> bool { static ENV: OnceLock = OnceLock::new(); - *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() + *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").map_or(true, |v| v.trim() != "0")) && !crate::hle::d3d12x::console_heap::window_views_failed() +} + +/// `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")) } /// A static sampler of a translated program: (S#, comparison) – see `Translation`. pub type StaticSampler = ([u32; 4], bool); /// A console shader as PC DXIL and the static samplers it needs in its root signature. +/// `dxil` is shared: a RAM-hit clone hands out the same bytes, not a copy (#2609). #[derive(Clone)] pub struct Compiled { pub dispatch_chain: Option>, - pub dxil: Vec, + pub dxil: std::sync::Arc>, pub samplers: Vec, } @@ -150,7 +181,10 @@ fn shader_cache() -> &'static Mutex { /// `console_to_dxil_for` with the title's memory windows given (`xcl shaders --precompile` /// fills the caches without a title: the same keys as at its run). pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result { - let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64); + // a ray-tracing program with `XCL_RT_GATE=miss` gets its own loop budget + // (`dxil::kernel::RT_LOOP_BUDGET`): what makes it one is in its bytes, as the caches' keys are + let rt = stage == Stage::Compute && crate::gpu::dxil::kernel::rt_all_miss() && crate::hle::d3d12x::real::rt_gated_program(blob); + let compile_one = || crate::gpu::dxil::kernel::with_rt_program(rt, || compile_console_shader(blob, stage, sampler_base, windows, split_wave64)); if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { return compile_one().map(|(c, _)| c); } @@ -267,6 +301,10 @@ 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_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"))) @@ -338,7 +376,7 @@ mod translated { if !rest.is_empty() { return None; } Some(std::sync::Arc::new(crate::gpu::dxil::kernel::DispatchChain { dwords_per_group, pieces })) }; - Some(Compiled { dxil: whole.to_vec(), samplers, dispatch_chain }) + Some(Compiled { dxil: whole.to_vec().into(), samplers, dispatch_chain }) } pub(super) fn store_in(path: &Path, ident: u64, blob: &[u8], c: &Compiled) { @@ -657,7 +695,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: t.hlsl = t.hlsl.replacen(" if (!xcl_live) discard;\n return xo;\n}", &format!(" xo.t0 = {expr};\n return xo;\n}}"), 1); } let dxil = dxc::compile_cached(&t.hlsl, "main", profile)?.0; - Ok((Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }, false)) + Ok((Compiled { dispatch_chain: None, dxil: dxil.into(), samplers: t.static_samplers }, false)) } /// Every `X_T.Sample(args)` of generated HLSL as `X_T.SampleLevel(args, 0.0f)`. @@ -931,6 +969,19 @@ pub fn compute_user_sgprs(blob: &[u8]) -> Option { } } +/// Thread-group dimensions `[x, y, z]` of a console compute shader (FSPX or FSSM). +pub fn compute_threads(blob: &[u8]) -> Option<[u32; 3]> { + if let Some(f) = fspx(blob) { + return Some(f.threads); + } + let sh = xbox::parse(blob)?; + let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?; + match interface(blob, &sh, f)? { + Mode::Compute(cs) => Some(cs.threads), + _ => None, + } +} + /// The HLSL and profile a console program compiles from at pipeline creation (for /// `xcl shaders --export-hlsl`: compile-time investigations outside a title). pub fn console_hlsl(blob: &[u8], stage: Stage, windows: u32, split_wave64: bool) -> Result<(String, &'static str), String> { @@ -945,6 +996,21 @@ fn direct_fallback(stage: &str, err: &str) { crate::xlog_info!("[SHADER] direct DXIL fallback stage={stage} reason=\"{reason}\" detail=\"{}\" – HLSL path", err.lines().next().unwrap_or("")); } +/// Whether the program takes an address in its code region for something else than a far jump +/// (`rdna2::resolve_far_jumps`): an `s_getpc_b64` the compiler emits to reach the constant +/// data after the program. +fn takes_code_address(code: &[u8]) -> bool { + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + let Ok(d) = crate::gpu::rdna2::decode(&code[off..], off as u64) else { return false }; + off += d.len; + insts.push(d); + } + crate::gpu::rdna2::resolve_far_jumps(&mut insts); + (0..insts.len()).any(|i| insts[i].inst.name == "S_GETPC_B64" && !insts.get(i + 3).is_some_and(|s| s.far_target.is_some())) +} + /// A console compute shader through the direct DXIL translator (`gpu::dxil::kernel`). /// FSPX (driver) containers are left to the HLSL path. fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bool) -> Result { @@ -953,15 +1019,18 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo let Some(Mode::Compute(cs)) = interface(blob, &sh, f) else { return Err("not a compute interface".into()) }; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; + // the constant data the program reads from its own code region (`Options::rodata`) + let rodata = f.rodata(p); let wave64 = super::fssm_wave64(f, code); let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64 && split_wave64, mem_windows: windows, sampler_base }; // `XCL_PER_LANE=1`: the per-lane form first, #1426's per-instruction form where it refuses - if super::lower_dxil::enabled() { + // (and for a program that reads constant data in its code: the per-lane form has no table) + if super::lower_dxil::enabled() && !(!rodata.is_empty() && takes_code_address(code)) { match super::lower_dxil::compute_with(code, &cs, o) { Ok(k) => { crate::gpu::dxil::coverage::record_translated("CS per-lane"); dump_direct(blob, &k.dxil); - return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }); + return Ok(Compiled { dispatch_chain: None, dxil: k.dxil.into(), samplers: k.static_samplers }); } Err(e) => { let reason = crate::gpu::dxil::coverage::record_fallback("CS per-lane", &e); @@ -969,9 +1038,9 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo } } } - let k = crate::gpu::dxil::kernel::translate_compute_on(code, o, &cs, split_wave64)?; + 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 }) + Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil.into(), samplers: k.static_samplers }) } /// `XCL_DXIL_DUMP=[,…]` (`[SHADER]` hashes, or `all`): writes the direct path's @@ -1000,13 +1069,14 @@ fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32) - let p = f.programs.first().ok_or("FSSM without a program")?; let code = &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 k = match (&mode, stage) { - (Mode::Vertex(vs), Stage::Vertex) => crate::gpu::dxil::kernel::translate_vertex(code, o, vs)?, - (Mode::Pixel(ps), Stage::Pixel) => crate::gpu::dxil::kernel::translate_pixel(code, o, ps)?, + let entry = match (&mode, stage) { + (Mode::Vertex(vs), Stage::Vertex) => crate::gpu::dxil::kernel::Entry::Vertex(vs.clone()), + (Mode::Pixel(ps), Stage::Pixel) => crate::gpu::dxil::kernel::Entry::Pixel(ps.clone()), _ => return Err("the shader stage does not match its slot in the PSO".into()), }; + let k = crate::gpu::dxil::kernel::translate_entry_rodata(code, o, entry, &f.rodata(p))?; dump_direct(blob, &k.dxil); - Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }) + Ok(Compiled { dispatch_chain: None, dxil: k.dxil.into(), samplers: k.static_samplers }) } pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(super::Translation, &'static str), String> { @@ -1044,7 +1114,7 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, }; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &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, ..Default::default() })?; + 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(); return Err(format!("incomplete translation, missing: {missing:?}")); @@ -1057,7 +1127,7 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, /// then a pass-through mesh shader rasterises the records with the pixel shader. pub struct TwoPass { /// compute pass (cs_6_6 DXIL) - pub cs: Vec, + pub cs: std::sync::Arc>, /// pass-through mesh shader (ms_6_6 DXIL) pub ms: Vec, pub record: super::MsInterface, @@ -1081,12 +1151,13 @@ fn finish_two_pass(t: super::Translation, record: super::MsInterface, ps: Option return Err(format!("incomplete translation, missing: {missing:?}")); } let cs = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; - finish_two_pass_compiled(Compiled { dispatch_chain: None, dxil: cs, samplers: t.static_samplers }, record, ps) + finish_two_pass_compiled(Compiled { dispatch_chain: None, dxil: cs.into(), samplers: t.static_samplers }, record, ps) } fn compile_console_mesh( blob: &[u8], code: &[u8], + rodata: Vec<(u32, Vec)>, ms: &super::MsInterface, wave64: bool, windows: u32, @@ -1103,22 +1174,22 @@ fn compile_console_mesh( mem_windows: windows, sampler_base: 0, }; - match crate::gpu::dxil::kernel::translate_mesh(code, o, ms) { + match crate::gpu::dxil::kernel::translate_entry_rodata(code, o, crate::gpu::dxil::kernel::Entry::Mesh(ms.clone()), &rodata) { Ok(k) => { crate::gpu::dxil::coverage::record_translated("MS"); dump_direct(blob, &k.dxil); - return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }); + return Ok(Compiled { dispatch_chain: None, dxil: k.dxil.into(), samplers: k.static_samplers }); } Err(e) => direct_fallback("MS", &e), } } - let t = super::translate_mesh(code, ms.clone(), wave64, split_wave64, windows)?; + let t = translate(code, &Options { mode: Mode::Mesh(ms.clone()), wave64, split_wave64, mem_windows: windows, rodata, ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); } let dxil = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; - Ok(Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }) + Ok(Compiled { dispatch_chain: None, dxil: dxil.into(), samplers: t.static_samplers }) } fn console_mesh_with( @@ -1128,7 +1199,7 @@ fn console_mesh_with( windows: u32, cache_dir: &std::path::Path, cache: &Mutex, - compile: impl FnOnce(&[u8], &super::MsInterface, bool) -> Result, + compile: impl FnOnce(&[u8], Vec<(u32, Vec)>, &super::MsInterface, bool) -> Result, ) -> Result { let sh = xbox::parse(blob).ok_or("not a console shader container")?; let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 7)).ok_or("no NGG hardware variant")?; @@ -1139,7 +1210,7 @@ fn console_mesh_with( let code = &f.data[p.offset..p.offset + p.len]; let wave64 = super::fssm_wave64(f, code); let split = wave64 && split_wave64; - let compile_one = || compile(code, ms, wave64); + let compile_one = || compile(code, f.rodata(p), ms, wave64); // Cache the mesh compute pass in RAM (`ShaderCache` + in-flight coalescing) and on disk // (`translated/v2`, namespaced by backend) across all `(MS, PS)` pipelines that share it. let cs = if cache_allowed(Stage::Mesh, |name| std::env::var_os(name).is_some()) { @@ -1164,8 +1235,8 @@ fn console_mesh_with( pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Result { let windows = mem_windows(); let dir = dxc::cache_dir(); - console_mesh_with(blob, ps, split_wave64, windows, &dir, shader_cache(), |code, ms, wave64| { - compile_console_mesh(blob, code, ms, wave64, windows, split_wave64) + 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) }) } @@ -1226,7 +1297,7 @@ pub fn console_geometry(vs: &[u8], gs: &[u8], ps: Option<&[u8]>, split_wave64: b let ps_inputs = ps.map(|p| crate::gpu::dxbc::signatures(p).0); let msb = dxc::compile_cached(&super::emit::mesh_passthrough_for(&record, ps_inputs.as_deref()), "main", "ms_6_6")?.0; let mesh_groups_per_record = super::emit::passthrough_split(&record, super::emit::passthrough_elements(&record, ps_inputs.as_deref())); - return Ok(TwoPass { cs: k.dxil, ms: msb, record, mesh_groups_per_record, samplers: k.static_samplers }); + return Ok(TwoPass { cs: k.dxil.into(), ms: msb, record, mesh_groups_per_record, samplers: k.static_samplers }); } Err(e) => direct_fallback("GS", &e), } @@ -1303,6 +1374,18 @@ pub(crate) fn dispatch_slabs(grid: [u32; 3], most: u64) -> Vec<([u32; 3], [u32; out } +/// How many slabs `dispatch_slabs` makes of `grid` (without making them) +pub(crate) fn slab_count(grid: [u32; 3], most: u64) -> u64 { + let [x, y, z] = grid.map(u64::from); + if x * y * z == 0 { + return 0; + } + let sx = x.min(most.max(1)); + let sy = if sx == x { y.min((most / x).max(1)) } else { 1 }; + let sz = if sx == x && sy == y { z.min((most / (x * y)).max(1)) } else { 1 }; + x.div_ceil(sx) * y.div_ceil(sy) * z.div_ceil(sz) +} + /// A chain's dispatch of `grid` groups, `most` of them at once (`dispatch_slabs`). `used`: the /// list (or one before it) has used `scratch`. pub(crate) unsafe fn record_dispatch_chain<'a>( @@ -1329,6 +1412,271 @@ pub(crate) fn dispatch_chain_root_signature(dev: &ID3D12Device, samplers: &[Stat abi_signature(dev, false, samplers, true) } +/// Bytes of one command of a chain's ExecuteIndirect (`chain_command_signature`): the eight +/// root constants of `record_dispatch_chain` and the slab's Dispatch. +pub(crate) const CHAIN_COMMAND_BYTES: u32 = 44; + +/// The command signature of a chain's ExecuteIndirect on the chain's root signature `rs`. +pub(crate) fn chain_command_signature(dev: &ID3D12Device, rs: &ID3D12RootSignature) -> Result { + let args = [ + D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT, + Anonymous: D3D12_INDIRECT_ARGUMENT_DESC_0 { + Constant: D3D12_INDIRECT_ARGUMENT_DESC_0_1 { + RootParameterIndex: 7, + DestOffsetIn32BitValues: 0, + Num32BitValuesToSet: 8, + }, + }, + }, + D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, + ..Default::default() + }, + ]; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: CHAIN_COMMAND_BYTES, + NumArgumentDescs: 2, + pArgumentDescs: args.as_ptr(), + NodeMask: 0, + }; + let mut sig: Option = None; + unsafe { dev.CreateCommandSignature(&desc, rs, &mut sig) }.map_err(|e| format!("CreateCommandSignature: {e}"))?; + sig.ok_or_else(|| "CreateCommandSignature".into()) +} + +/// One thread that turns a title's Dispatch arguments into a chain's commands: each command's +/// groups in the slabs of `dispatch_slabs`, one slab a round, `rounds` rounds of `pieces` +/// commands (`CHAIN_COMMAND_BYTES` each; unused rounds dispatch nothing). After them +/// (`chain_predicate_offset`): a 64-bit predicate, 1 when the rounds did not hold every slab, +/// and the slabs there were (at most 2^32 - 256). +/// +/// `args_off` and `count_off` carry sub-256-byte offsets so `t0`/`t1` root SRVs are always +/// 256-byte aligned (D3D12 root raw SRVs require >= 16-byte alignment). +const SLICER: &str = r#" +#define RS "RootConstants(num32BitConstants=8, b0), SRV(t0), SRV(t1), UAV(u0)" +cbuffer C : register(b0) { uint rounds; uint most; uint commands; uint stride; uint counted; uint pieces; uint args_off; uint count_off; }; +ByteAddressBuffer args : register(t0); +ByteAddressBuffer count : register(t1); +RWByteAddressBuffer cmds : register(u0); +void put(uint r, uint3 n, uint3 o) { + for (uint i = 0; i < pieces; i++) { + uint at = (r * pieces + i) * 44; + cmds.Store4(at, uint4(n, i)); + cmds.Store4(at + 16, uint4(o, 0)); + cmds.Store3(at + 32, n); + } +} +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint n = counted != 0 ? min(count.Load(count_off), commands) : commands; + uint r = 0; + bool partial = false; + float slabs = 0; + for (uint k = 0; k < n; k++) { + uint3 g = min(args.Load3(args_off + k * stride), 65535); + if (any(g == 0)) continue; + uint3 s; + s.x = min(g.x, max(most, 1)); + s.y = s.x == g.x ? min(g.y, max(most / g.x, 1)) : 1; + s.z = s.x == g.x && s.y == g.y ? min(g.z, max(most / g.x / g.y, 1)) : 1; + uint3 c = (g + s - 1) / s; + float need = (float)c.x * c.y * c.z; + slabs += need; + uint first = r; + for (uint oz = 0; oz < g.z && r < rounds; oz += s.z) + for (uint oy = 0; oy < g.y && r < rounds; oy += s.y) + for (uint ox = 0; ox < g.x && r < rounds; ox += s.x) { + uint3 o = uint3(ox, oy, oz); + put(r++, min(s, g - o), o); + } + partial = partial || (float)(r - first) < need; + } + for (; r < rounds; r++) put(r, 0, 0); + cmds.Store4((rounds * pieces * 44 + 7) & ~7u, uint4(partial ? 1 : 0, 0, (uint)min(slabs, 4294967040.0), 0)); +} +"#; + +/// Where the slicer's predicate is in a chain's command buffer +pub(crate) fn chain_predicate_offset(rounds: u32, pieces: u32) -> u64 { + u64::from(rounds * pieces * CHAIN_COMMAND_BYTES).next_multiple_of(8) +} + +/// Bytes of a chain's command buffer (`SLICER`) +pub(crate) fn chain_commands_bytes(rounds: u32, pieces: u32) -> u64 { + chain_predicate_offset(rounds, pieces) + 16 +} + +/// The slicer's root signature and pipeline (made once per device). +fn slicer(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static MADE: Mutex> = Mutex::new(None); + let mut g = MADE.lock().unwrap(); + if let Some((_, rs, pso)) = g.as_ref().filter(|m| m.0 == windows::core::Interface::as_raw(dev) as usize) { + return Ok((rs.clone(), pso.clone())); + } + let dxil = super::dxc::compile_cached(SLICER, "main", "cs_6_0")?.0; + unsafe { + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).map_err(|e| format!("slicer root signature: {e}"))?; + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: dxil.as_ptr().cast(), + BytecodeLength: dxil.len(), + }, + ..Default::default() + }; + let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).map_err(|e| format!("slicer pipeline: {e}"))?; + let _ = pso.SetName(windows::core::w!("xcl dispatch_chain_slicer")); + *g = Some((windows::core::Interface::as_raw(dev) as usize, rs.clone(), pso.clone())); + Ok((rs, pso)) + } +} + +/// A chain's command buffer (`chain_commands_bytes`) in the UNORDERED_ACCESS state: the slicer +/// writes it, ExecuteIndirect and predication read it, and the CPU reads the slabs back. +pub(crate) unsafe fn chain_commands_buffer(dev: &ID3D12Device, rounds: u32, pieces: u32) -> Option { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: chain_commands_bytes(rounds, pieces), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + CreationNodeMask: 1, + VisibleNodeMask: 1, + }; + let mut resource = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut resource).ok()?; + resource +} + +/// Align a GPU virtual address down to a 256-byte root SRV base and its 4-byte-aligned offset. +fn align_slicer_srv(va: u64, what: &str) -> Result<(u64, u32), String> { + if va < 256 || va % 4 != 0 { + return Err(format!("invalid indirect {what} address {va:#x}")); + } + Ok((va & !255, (va & 255) as u32)) +} + +/// The slicer's dispatch: the title's `commands` commands of `stride` bytes at `args` (GPU +/// address; the count at `count` when there is one) into `out` (`chain_commands_bytes`, in the +/// UNORDERED_ACCESS state, left in INDIRECT_ARGUMENT). It sets the list's compute root signature: +/// the caller binds its own again. Returns the raw slicer PSO address for DRED labeling. +#[allow(clippy::too_many_arguments)] +pub(crate) unsafe fn record_slicer( + list: &ID3D12GraphicsCommandList, + args: u64, + stride: u32, + commands: u32, + count: Option, + rounds: u32, + most: u64, + pieces: u32, + out: &ID3D12Resource, +) -> Result { + let (args_base, args_off) = align_slicer_srv(args, "args")?; + let (cnt_base, cnt_off) = match count { + Some(c) => align_slicer_srv(c, "count")?, + None => (args_base, 0), + }; + let dev: ID3D12Device = { + let mut d: Option = None; + list.GetDevice(&mut d).map_err(|e| e.to_string())?; + d.ok_or("device")? + }; + let (rs, pso) = slicer(&dev)?; + let constants = [ + rounds, + most.min(u64::from(u32::MAX)) as u32, + commands, + stride, + count.is_some() as u32, + pieces, + args_off, + cnt_off, + ]; + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRoot32BitConstants(0, constants.len() as u32, constants.as_ptr().cast(), 0); + list.SetComputeRootShaderResourceView(1, args_base); + list.SetComputeRootShaderResourceView(2, cnt_base); + list.SetComputeRootUnorderedAccessView(3, out.GetGPUVirtualAddress()); + // after the dispatches that wrote the arguments + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(out), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + StateAfter: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + }), + }, + }]); + Ok(windows::core::Interface::as_raw(&pso) as usize) +} + +/// `record_dispatch_chain` from the slicer's commands in `commands` (`rounds` rounds), after the +/// six common root views have been bound. With `predicated`, the pieces run only when the rounds +/// covered every slab (`record_slicer`'s predicate); the caller clears the predication. +pub(crate) unsafe fn record_dispatch_chain_indirect<'a>( + list: &ID3D12GraphicsCommandList, + sig: &ID3D12CommandSignature, + commands: &ID3D12Resource, + rounds: u32, + predicated: bool, + scratch: &ID3D12Resource, + pieces: impl IntoIterator + Clone, +) { + let n = pieces.clone().into_iter().count() as u32; + if predicated { + list.SetPredication(commands, chain_predicate_offset(rounds, n), D3D12_PREDICATION_OP_NOT_EQUAL_ZERO); + } + list.SetComputeRootUnorderedAccessView(6, scratch.GetGPUVirtualAddress()); + for r in 0..rounds { + for (i, piece) in pieces.clone().into_iter().enumerate() { + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + list.SetPipelineState(piece); + list.ExecuteIndirect( + sig, + 1, + commands, + u64::from((r * n + i as u32) * CHAIN_COMMAND_BYTES), + None::<&ID3D12Resource>, + 0, + ); + } + } +} + fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], split: bool) -> Result { let statics: Vec = samplers.iter().enumerate().map(|(k, s)| static_sampler_desc(k as u32, s)).collect(); unsafe { @@ -1405,7 +1753,15 @@ mod slab_tests { } } assert_eq!(dispatch_slabs([240, 135, 1], 1400).len(), 27, "five rows of 240 at once"); + for grid in [[1, 1, 1], [2, 3, 2], [240, 135, 1], [65_535, 2, 1], [5, 1, 7], [0, 4, 4]] { + for most in [0, 1, 3, 239, 240, 1000, u64::MAX] { + assert_eq!(super::slab_count(grid, most), dispatch_slabs(grid, most).len() as u64, "{grid:?} {most}"); + } + } assert!(dispatch_slabs([0, 4, 4], 8).is_empty()); + assert_eq!(super::align_slicer_srv(0x1000_000c, "args"), Ok((0x1000_0000, 12))); + assert!(super::align_slicer_srv(0, "args").is_err()); + assert!(super::align_slicer_srv(0x1000_0002, "args").is_err()); } } @@ -1448,7 +1804,7 @@ mod shader_cache_tests { fn translations_on_disk_need_the_same_bytes_and_identity() { let dir = std::env::temp_dir().join(format!("xcl-translated-{}", std::process::id())); let path = dir.join("t.bin"); - let c = Compiled { dispatch_chain: None, dxil: synthetic_dxil(5), samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)] }; + let c = Compiled { dispatch_chain: None, dxil: synthetic_dxil(5).into(), samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)] }; translated::store_in(&path, 42, b"console", &c); let back = translated::load_in(&path, 42, b"console").expect("stored"); assert_eq!((back.dxil, back.samplers), (c.dxil.clone(), c.samplers.clone())); @@ -1479,7 +1835,7 @@ mod shader_cache_tests { }) .unwrap(); assert_eq!(calls, 1); - assert_eq!(first.dxil, synthetic_dxil(7)); + assert_eq!(*first.dxil, synthetic_dxil(7)); assert!(unnamespaced.exists()); assert!(translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false).exists()); @@ -1684,7 +2040,7 @@ mod shader_cache_tests { // Store a valid entry first, then corrupt only the DXIL payload while keeping the // XCLTRAN2 header and payload length intact (e.g. zeroed blocks after a hard reset). - let valid = Compiled { dispatch_chain: None, dxil: synthetic_dxil(1), samplers: vec![([1, 2, 3, 4], false)] }; + let valid = Compiled { dispatch_chain: None, dxil: synthetic_dxil(1).into(), samplers: vec![([1, 2, 3, 4], false)] }; translated::store_in(&path, ident, blob, &valid); let mut raw = std::fs::read(&path).unwrap(); let dxil_start = raw.len() - valid.dxil.len(); @@ -1693,7 +2049,7 @@ mod shader_cache_tests { assert!(translated::load_in(&path, ident, blob).is_none(), "zeroed DXIL payload must not load as a cache hit"); // Also corrupt only the inner DXIL magic inside an otherwise valid-looking DXBC chunk. - let mut bad_inner = valid.dxil.clone(); + let mut bad_inner = (*valid.dxil).clone(); bad_inner[52..56].fill(0); raw[dxil_start..].copy_from_slice(&bad_inner); std::fs::write(&path, &raw).unwrap(); @@ -1703,17 +2059,17 @@ mod shader_cache_tests { let mut calls = 0usize; let rebuilt = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { calls += 1; - Ok(Compiled { dispatch_chain: None, dxil: synthetic_dxil(9), samplers: vec![([5, 6, 7, 8], true)] }) + Ok(Compiled { dispatch_chain: None, dxil: synthetic_dxil(9).into(), samplers: vec![([5, 6, 7, 8], true)] }) }) .unwrap(); assert_eq!(calls, 1); - assert_eq!(rebuilt.dxil, synthetic_dxil(9)); + assert_eq!(*rebuilt.dxil, synthetic_dxil(9)); let cached = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { panic!("rebuilt translated cache entry was not reused") }) .unwrap(); - assert_eq!(cached.dxil, synthetic_dxil(9)); + assert_eq!(*cached.dxil, synthetic_dxil(9)); assert_eq!(cached.samplers, vec![([5, 6, 7, 8], true)]); let _ = std::fs::remove_dir_all(&dir); } @@ -1727,35 +2083,35 @@ mod shader_cache_tests { let path = translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false); let err = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { - Ok(Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new() }) + Ok(Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec().into(), samplers: Vec::new() }) }) .err() .expect("invalid fresh DXIL must be rejected"); assert!(err.contains("invalid DXIL container"), "{err}"); assert!(!path.exists(), "invalid fresh DXIL must not be written to disk"); - translated::store_in(&path, ident, blob, &Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new() }); + translated::store_in(&path, ident, blob, &Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec().into(), samplers: Vec::new() }); assert!(!path.exists(), "store_in must not write an invalid DXIL container"); // A real container emitted by the direct DXIL backend must be accepted and cached. let real_direct = crate::gpu::dxil::shader::Shader::new(crate::gpu::dxil::container::Stage::Compute, (6, 6)).finish([1, 1, 1], None); let stored = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { - Ok(Compiled { dispatch_chain: None, dxil: real_direct.clone(), samplers: Vec::new() }) + Ok(Compiled { dispatch_chain: None, dxil: real_direct.clone().into(), samplers: Vec::new() }) }) .unwrap(); - assert_eq!(stored.dxil, real_direct); + assert_eq!(*stored.dxil, real_direct); let hit = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { panic!("valid direct DXIL entry was not reused") }) .unwrap(); - assert_eq!(hit.dxil, real_direct); + assert_eq!(*hit.dxil, real_direct); let _ = std::fs::remove_dir_all(&dir); } fn compiled(marker: u8) -> Compiled { Compiled { dispatch_chain: None, - dxil: synthetic_dxil(marker), + dxil: synthetic_dxil(marker).into(), samplers: vec![([marker as u32; 4], false)], } } @@ -1780,12 +2136,31 @@ mod shader_cache_tests { } assert_eq!(calls, 1); let mut owned = first.as_ref().clone(); - owned.dxil[67] = 99; owned.samplers.clear(); + // the clone shares the translated bytes instead of copying them: callers only read + assert!(Arc::ptr_eq(&first.dxil, &owned.dxil)); assert_eq!(first.dxil[67], 7); assert_eq!(first.samplers.len(), 1); } + /// The clone `console_to_dxil_in` hands a caller on a RAM hit carries the cached entry's + /// own bytes: repeated pipeline builds of one shader do not allocate and copy its whole + /// DXIL again (#2609). `as_ptr` compares the byte storage, not the `Arc`s. + #[test] + fn a_ram_hit_clone_shares_the_translated_bytes() { + let cache = Mutex::new(ShaderCache::new(1 << 20)); + let first = cached_shader(&cache, key(1), b"a", || Ok(compiled(7))).unwrap(); + for _ in 0..8 { + let next = cached_shader(&cache, key(1), b"a", || panic!("repeated shader reached the compiler path")) + .unwrap() + .as_ref() + .clone(); + assert!(std::ptr::eq(first.dxil.as_ptr(), next.dxil.as_ptr()), "the RAM hit copied the whole DXIL"); + assert_eq!(*next.dxil, *first.dxil); + assert_eq!(next.samplers, first.samplers); + } + } + #[test] fn shader_cache_checks_context_and_blob_bytes() { let cache = Mutex::new(ShaderCache::new(1 << 20)); @@ -1831,7 +2206,7 @@ mod shader_cache_tests { let dxil = dxc::compile_cached_in(&dir, "probe", "main", "cs_6_6")?.0; Ok(Compiled { dispatch_chain: None, - dxil, + dxil: dxil.into(), samplers: Vec::new(), }) }) @@ -1865,7 +2240,7 @@ mod shader_cache_tests { b"d", Arc::new(Compiled { dispatch_chain: None, - dxil: vec![0; limit + 1], + dxil: vec![0; limit + 1].into(), samplers: Vec::new(), }), ); @@ -1956,9 +2331,9 @@ mod shader_cache_tests { let compiles = AtomicUsize::new(0); let run = |c: &Mutex| { - console_mesh_with(&blob, None, false, 1, &dir, c, |code, ms, wave64| { + console_mesh_with(&blob, None, false, 1, &dir, c, |code, rodata, ms, wave64| { compiles.fetch_add(1, Ordering::SeqCst); - compile_console_mesh(&blob, code, ms, wave64, 1, false) + compile_console_mesh(&blob, code, rodata, ms, wave64, 1, false) }) }; @@ -2040,7 +2415,7 @@ mod shader_cache_tests { dxc::compile_cached_in(&dir, "pending probe", "main", "cs_6_6")?.0; Ok(Compiled { dispatch_chain: None, - dxil, + dxil: dxil.into(), samplers: Vec::new(), }) }) @@ -2130,7 +2505,7 @@ mod shader_cache_tests { let (res, missed) = dxc::cached_only(|| { translated::cached_in(&dir, ident_v1, deferred_blob, Stage::Compute, 0, 1, false, || { let dxil = dxc::compile_cached_in(&dir, "deferred probe", "main", "cs_6_6")?.0; - Ok(Compiled { dxil, samplers: Vec::new(), dispatch_chain: None }) + Ok(Compiled { dxil: dxil.into(), samplers: Vec::new(), dispatch_chain: None }) }) }); assert!(res.is_err() && missed); diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 2041690262..b59e459f5c 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 => { @@ -1532,7 +1554,7 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result Result, Some(&raw_window_uav(size as u64)), h); } + let mut h = dh.GetCPUDescriptorHandleForHeapStart(); + h.ptr += super::MEM_HEAP_NULL as usize * inc; + dev.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&raw_window_uav(0)), h); list.SetDescriptorHeaps(&[Some(dh.clone())]); list.SetComputeRootSignature(&gpu.rs); list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); @@ -1723,7 +1748,7 @@ fn dispatch_with( let dh: ID3D12DescriptorHeap = dev .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, - NumDescriptors: super::MEM_HEAP_BASE + win_count as u32, + NumDescriptors: super::MEM_HEAP_NULL + 1, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0, }) @@ -1734,12 +1759,16 @@ fn dispatch_with( h.ptr += (super::MEM_HEAP_BASE as usize + k) * inc; dev.CreateUnorderedAccessView(&mem_buf, None::<&ID3D12Resource>, Some(&raw_window_uav(mem_bytes)), h); } + let mut h = dh.GetCPUDescriptorHandleForHeapStart(); + h.ptr += super::MEM_HEAP_NULL as usize * inc; + dev.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&raw_window_uav(0)), h); list.SetDescriptorHeaps(&[Some(dh.clone()), Some(bound._heaps[1].clone())]); list.SetComputeRootSignature(rs); list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); - for k in 0..4 { - list.SetComputeRootUnorderedAccessView(2 + k as u32, mem_buf.GetGPUVirtualAddress()); + // every window (u2..u5) is `mem`, as in the heap above + for k in 2..6 { + list.SetComputeRootUnorderedAccessView(k, mem_buf.GetGPUVirtualAddress()); } let scratch = chain.map(|(_, words, most)| { let first = super::pso::dispatch_slabs(groups, most)[0].1; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 0b018edc36..e0d50f4fd3 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1426,6 +1426,164 @@ fn gpu_scalar_loop_and_scc() { assert_eq!((r.sgpr[41], r.sgpr[42], r.sgpr[43]), (48, 33, u32::MAX), "flbit_i64 high-then-low scan"); } +/// A spin of `spin` tries (a retail FSR pass polls a flag up to 0x10000 times, the loop budget), +/// inside an outer loop that runs once when `nested` (as in that pass), then a loop of `n` +/// iterations, then `s2 = 7`. +fn spin_then_loop(spin: u32, n: u32, nested: bool) -> Vec { + let i = |nm: &str, e: &str, f: &[(&str, u64)], lit: Option| encode(nm, e, f, lit).unwrap_or_else(|x| panic!("{nm}: {x}")); + let mut v = i("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)], None); // s0 = 0 + if nested { + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 3), ("SSRC1", 129)], None)); // outer: s3 += 1 + } + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); // spin: s0 += 1 + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 255)], Some(spin))); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None)); // → spin + if nested { + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 3), ("SSRC1", 129)], None)); // until s3 == 1 + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF9)], None)); // → outer + } + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)], None)); // s1 = 0 + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None)); // loop: s1 += 1 + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 255)], Some(n))); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None)); // → loop + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 135)], None)); // s2 = 7 + v.extend(i("S_ENDPGM", "ENC_SOPP", &[], None)); + v +} + +/// A program's own spin that gives up at the loop budget, or just before it, must not leave the +/// loops after it short of iterations: the FSR pass then published a flag built from a register +/// its main loop never set, and the pass waiting on it spun for 260 ms a frame. Both HLSL forms. +#[test] +fn gpu_a_loop_after_a_spin_to_the_budget_still_runs() { + if !gpu_ready() { + return; + } + for (spin, n, nested) in [(0x10000, 3, false), (0xFFF0, 1000, false), (0x10000, 3, true)] { + let code = spin_then_loop(spin, n, nested); + for structured in [true, false] { + let opt = Options { structured, ..runner::options(Mode::Kernel) }; + let t = translate(&code, &opt).unwrap(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let r = runner::run(&dxil, &KernelState::default(), &[]).unwrap(); + let what = format!("spin {spin:#x}, loop {n}, nested {nested}, structured {structured}"); + assert_eq!(r.sgpr[0], spin, "{what}: the spin ran to its own end"); + assert_eq!((r.sgpr[1], r.sgpr[2]), (n, 7), "{what}: the loop after it ran all its iterations"); + } + } +} + +/// Loops that never end still stop: four budgets in all, then every loop leaves. (The direct +/// translator ends the program where a budget runs out, so this is the HLSL path's.) +#[test] +fn gpu_endless_loops_in_many_regions_stop_after_four_budgets() { + if !gpu_ready() { + return; + } + // six regions, each `s0 += 1` until s0 == 0 (2^32 tries); s1 counts the regions reached + let mut list: Vec<(&str, &str, &[(&str, u64)], Option)> = Vec::new(); + for _ in 0..6 { + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None)); + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + list.push(("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None)); + list.push(("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None)); + } + let t = translate(&prog(&list), &runner::options(Mode::Kernel)).unwrap(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let r = runner::run(&dxil, &KernelState::default(), &[]).unwrap(); + assert_eq!(r.sgpr[1], 6, "every region was reached"); + assert_eq!(r.sgpr[0], super::LOOP_BUDGETS_IN_ALL << 16, "four budgets of iterations in all"); +} + +/// A loop of 80 instructions (320 B) that never ends: `s0 += 1`, 77 more adds, a compare that +/// holds until s0 wraps, the branch back. `after`: what follows the loop. +fn long_endless_loop(after: &[(&'static str, &'static str, &'static [(&'static str, u64)], Option)]) -> Vec { + let mut list: Vec<(&str, &str, &[(&str, u64)], Option)> = Vec::new(); + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + for _ in 0..77 { + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 129)], None)); + } + list.push(("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None)); + list.push(("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFB0)], None)); + list.extend_from_slice(after); + prog(&list) +} + +/// An iteration of a short loop spends 1 of the loop budget, one of a long loop more: a unit for +/// every `LOOP_COST_BYTES` of the innermost loop that holds the head, `LOOP_COST_MOST` at most. +/// A ray-tracing program's loops spend 1 of its small budget. +#[test] +fn a_long_loop_spends_more_of_the_budget_an_iteration() { + let u = super::LOOP_COST_BYTES; + let loops = [(0x100, 0x100 + 40 * u), (0x100 + 8 * u, 0x100 + 13 * u), (0x9000, 0x9010), (0x10000, 0x10000 + 1000 * u)]; + assert_eq!(super::loop_cost(&loops, 0x100), 40); + assert_eq!(super::loop_cost(&loops, 0x100 + 8 * u), 5, "the innermost loop that holds the head"); + assert_eq!(super::loop_cost(&loops, 0x9000), 1); + assert_eq!(super::loop_cost(&loops, 0x8000), 1, "no loop holds it"); + assert_eq!(super::loop_cost(&loops, 0x10000), super::LOOP_COST_MOST); + assert_eq!(super::loop_cost(&[(0, 2 * u - 4)], 0), 1, "under two units"); + crate::gpu::dxil::kernel::RT_ALL_MISS_FOR_TEST.with(|c| c.set(Some(true))); + let rt = crate::gpu::dxil::kernel::with_rt_program(true, || super::loop_cost(&loops, 0x100)); + crate::gpu::dxil::kernel::RT_ALL_MISS_FOR_TEST.with(|c| c.set(None)); + assert_eq!(rt, 1, "a ray-tracing program"); + + // the guards: a short loop's is the text it was, the 320 B loop's spends 2 an iteration + let short = prog(&[ + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None), + ]); + let t = translate(&short, &Options { mode: Mode::Kernel, ..Default::default() }).unwrap(); + assert!(t.hlsl.contains(super::LOOP_GUARD), "{}", t.hlsl); + let t = translate(&long_endless_loop(&[]), &Options { mode: Mode::Kernel, ..Default::default() }).unwrap(); + assert!(t.hlsl.contains("if (xcl_budget < 2u) break; xcl_budget -= 2u;") && !t.hlsl.contains(super::LOOP_GUARD), "{}", t.hlsl); +} + +/// A long loop that never ends stops after as many iterations as its cost leaves of the budget: +/// half of them for a loop of 320 B. +#[test] +fn gpu_an_endless_long_loop_stops_after_the_budget_by_its_cost() { + if !gpu_ready() { + return; + } + let t = translate(&long_endless_loop(&[]), &runner::options(Mode::Kernel)).unwrap(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let r = runner::run(&dxil, &KernelState::default(), &[]).unwrap(); + assert_eq!(r.sgpr[0], (1 << 16) / 2); +} + +/// Per-region loop budgets (`xcl_bown` / `xcl_btotal`) are compute-only: Compute and Kernel +/// modes emit them for multi-region loops, while Pixel and Mesh stages keep the single-budget +/// CFG (avoiding multi-PHI mesh loop headers that crash AMD LLPC). +#[test] +fn per_region_loop_budgets_are_compute_only() { + let mut list: Vec<(&str, &str, &[(&str, u64)], Option)> = Vec::new(); + for _ in 0..2 { + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + list.push(("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 130)], None)); + list.push(("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None)); + } + let code = prog(&list); + + let cs = super::CsInterface { threads: [64, 1, 1], ..Default::default() }; + let ps = super::PsInterface::default(); + let ms = super::MsInterface { threads: 64, max_vertices: 64, max_primitives: 64, ..Default::default() }; + + for mode in [Mode::Kernel, Mode::Compute(cs.clone())] { + let t = translate(&code, &Options { mode, ..Default::default() }).unwrap(); + assert!(t.hlsl.contains("xcl_bown") && t.hlsl.contains("xcl_btotal"), "compute/kernel should emit per-region budgets"); + } + for mode in [Mode::Pixel(ps), Mode::Mesh(ms.clone())] { + let t = translate(&code, &Options { mode, ..Default::default() }).unwrap(); + assert!(!t.hlsl.contains("xcl_bown") && !t.hlsl.contains("xcl_btotal"), "pixel/mesh must not emit per-region budgets"); + } + + // Direct DXIL compute & mesh both translate cleanly for a multi-region loop program. + let o = crate::gpu::dxil::kernel::KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + assert!(!crate::gpu::dxil::kernel::translate_compute(&code, o, &cs).unwrap().dxil.is_empty()); + assert!(!crate::gpu::dxil::kernel::translate_mesh(&code, o, &ms).unwrap().dxil.is_empty()); +} + #[test] fn gpu_divergence_through_exec() { if !gpu_ready() { @@ -1813,6 +1971,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, 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(); + 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] @@ -1851,6 +2048,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(); @@ -1935,6 +2133,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() { @@ -1984,6 +2183,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() }; @@ -2169,6 +2369,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(); @@ -2239,6 +2440,7 @@ fn draw_psi() -> super::PsInterface { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, } } @@ -2752,7 +2954,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() } } @@ -3110,6 +3312,53 @@ fn static_sampler_word_from_s_brev_is_a_constant() { assert!(!t.hlsl.contains("SamplerDescriptorHeap"), "no sampler heap lookup left"); } +/// An S# set before a branch and sampled after it (the compiler sets the S# of a blur's taps +/// before the loop, of an effect before its `if`) is a static sampler all the same: the +/// constants are followed into the next block. Before, a block's start forgot them and the +/// shader sampled through sampler-heap entry 0 (point, wrap, mip 0). +#[test] +fn static_sampler_set_before_a_branch_is_a_constant_after_it() { + let clamp = 2 | 2 << 3 | 2 << 6; + let linear = [clamp, 0x00FF_F000u32, 0x0050_0000u32, 0]; + let code = prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 255)], Some(linear[0])), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 25), ("SSRC0", 255)], Some(linear[1])), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 26), ("SSRC0", 255)], Some(linear[2])), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 27), ("SSRC0", 128)], None), + // (both ways go to the next instruction: it starts a block) + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 0)], None), + ("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0xF), ("DIM", 1)], None), + ]); + let pixel = Options { mode: Mode::Pixel(crate::gpu::recomp::PsInterface::default()), ..Default::default() }; + let t = translate(&code, &pixel).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + assert_eq!(t.static_samplers, vec![(linear, false)], "the S# set before the branch is a static sampler"); + assert!(!t.hlsl.contains("SamplerDescriptorHeap"), "no sampler heap lookup left"); + // a program that does not draw is read block by block, as before + let t = translate(&code, &Options::default()).unwrap(); + assert!(t.static_samplers.is_empty(), "{:?}", t.static_samplers); +} + +/// Two ways into a block that leave different words in an S# register: not a constant there, +/// the sampler is looked up as before. +#[test] +fn an_s_word_that_differs_by_the_way_in_is_no_constant() { + let clamp = 2 | 2 << 3 | 2 << 6; + let code = prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 255)], Some(clamp)), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 25), ("SSRC0", 255)], Some(0x00FF_F000)), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 26), ("SSRC0", 255)], Some(0x0050_0000)), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 27), ("SSRC0", 128)], None), + // over the next move (two dwords): one way keeps the first s26, the other sets another + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 2)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 26), ("SSRC0", 255)], Some(0)), + ("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0xF), ("DIM", 1)], None), + ]); + let pixel = Options { mode: Mode::Pixel(crate::gpu::recomp::PsInterface::default()), ..Default::default() }; + let t = translate(&code, &pixel).unwrap(); + assert!(t.static_samplers.is_empty(), "{:?}", t.static_samplers); +} + /// The same program on the GPU: the texel a point sampler picks at a texel boundary. #[test] fn gpu_static_sampler_word_from_s_brev() { @@ -3297,6 +3546,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] @@ -3563,7 +3875,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) }; @@ -3641,6 +3953,100 @@ fn gpu_mesh_mode_two_passes() { assert!(px16 == px, "split pass-through draws the same pixels"); } +/// A mesh (NGG) program whose param 0 packs two float16 registers, two components per dword +/// (TEXCOORD1.xy in dword 0, TEXCOORD4.xyzw in dwords 1 and 2 – a retail title's transform +/// programs): the record keeps every component as a float in its own element's slot, the +/// pass-through hands them to the pixel shader by semantic, and the float param after the +/// pair lands in its own register. Before: param 0 went raw into TEXCOORD1 alone and param 1 +/// into TEXCOORD4. +#[test] +fn gpu_mesh_f16_packed_params() { + if !gpu_ready() || !mesh_ready() { + return; + } + use super::{dxc, mesh_passthrough, MsInterface, OutParam, MESH_HEADER}; + let ms = MsInterface { + outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF), el("TEXCOORD", 1, 0, 6, 1, 0x3), el("TEXCOORD", 4, 0, 6, 2, 0xF), el("TEXCOORD", 3, 0, 3, 3, 0xF)], + threads: 128, + max_vertices: 128, + max_primitives: 128, + params: Some(vec![OutParam { register: 1, f16: true, pair: true }, OutParam { register: 3, f16: false, pair: false }]), + }; + 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) + }; + // as `gpu_mesh_mode_two_passes`: v20 = group, v15 = thread in the group (floats) + let mut list: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ + ("S_BFE_U32", "ENC_SOP2", vec![("SDST", 0), ("SSRC0", 3), ("SSRC1", 255)], Some(0x40018)), + ("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), + ("V_LSHL_ADD_U32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 0), ("SRC1", 134), ("SRC2", V)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", vec![("VDST", 1), ("SRC0", V + 5)], None), + ("S_LSHR_B32", "ENC_SOP2", vec![("SDST", 1), ("SSRC0", 1), ("SSRC1", 135)], None), + ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 124), ("SSRC0", 255)], Some(1 << 12 | 3)), + ("S_SENDMSG", "ENC_SOPP", vec![("SIMM16", 9)], None), + ("S_BARRIER", "ENC_SOPP", vec![], None), + ("V_CMPX_GT_U32", "ENC_VOPC", vec![("SRC0", 131), ("VSRC1", 0)], None), + ("BUFFER_LOAD_DWORDX4", "ENC_MUBUF", vec![("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 20), ("SRC0", 1)], None), + ("V_ADD_F32", "ENC_VOP2", vec![("VDST", 10), ("SRC0", V + 20), ("VSRC1", 10)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 14), ("SRC0", V + 20)], None), + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 15), ("SRC0", V)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 16), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 17), ("SRC0", 242)], None), + // halves: v22 = group, v23 = thread, v24 = 0.5, v25 = 2.0 + ("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 22), ("SRC0", V + 20)], None), + ("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 23), ("SRC0", V + 15)], None), + ("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 24), ("SRC0", 240)], None), + ("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 25), ("SRC0", 244)], None), + // TEXCOORD1 = (group, thread); TEXCOORD4 = (0.5, group, thread, 2.0) + ("V_PACK_B32_F16", "ENC_VOP3", vec![("VDST", 26), ("SRC0", V + 22), ("SRC1", V + 23)], None), + ("V_PACK_B32_F16", "ENC_VOP3", vec![("VDST", 27), ("SRC0", V + 24), ("SRC1", V + 22)], None), + ("V_PACK_B32_F16", "ENC_VOP3", vec![("VDST", 28), ("SRC0", V + 23), ("SRC1", V + 25)], None), + ]; + list.push(exp(12, 0xF, [10, 11, 12, 13], 1)); + list.push(exp(32, 0x7, [26, 27, 28, 0], 0)); + list.push(exp(33, 0xF, [14, 15, 16, 17], 0)); + list.push(("S_MOV_B64", "ENC_SOP1", vec![("SDST", 126), ("SSRC0", 193)], None)); + list.push(("V_CMPX_EQ_U32", "ENC_VOPC", vec![("SRC0", 128), ("VSRC1", 0)], None)); + list.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 21), ("SRC0", 255)], Some(1 << 10 | 2 << 20))); + list.push(exp(20, 1, [21, 0, 0, 0], 1)); + 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 opt = on_gpu(Options { mode: Mode::Mesh(ms.clone()), wave64: true, ..Default::default() }); + let t = translate(&code, &opt).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let cs = direct_or(&code, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl))); + let pass = mesh_passthrough(&ms); + let msb = dxc::compile(&pass, "main", "ms_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pass}")); + let ps_src = "struct V { float4 pos : SV_Position; float4 a : TEXCOORD1; float4 b : TEXCOORD4; float4 c : TEXCOORD3; };\nfloat4 main(V v) : SV_Target0 { return float4(v.a.x, v.b.x, v.b.w, v.c.w); }\n"; + let ps = dxc::compile(ps_src, "main", "ps_6_6", &[]).unwrap(); + let mut mem = vec![0u32; 256]; + for (i, (x, y)) in [(-1.0f32, -1.0f32), (-1.0, 1.0), (0.0, -1.0)].iter().enumerate() { + mem[0x40 + 4 * i..0x40 + 4 * i + 4].copy_from_slice(&[f(*x), f(*y), f(0.0), f(1.0)]); + } + let mut sg = vec![0u32; 128]; + sg[16..20].copy_from_slice(&[0x100, 16 << 16, 3, 0]); + let (px, rec) = runner::mesh_draw(&cs, &msb, &ps, 2, ms.record_dwords(), &sg, &mem, 32, [-1.0; 4]).unwrap(); + let (rd, vd) = (ms.record_dwords(), ms.vert_dwords()); + for g in 0..2usize { + let r = &rec[g * rd..(g + 1) * rd]; + assert_eq!((r[0], r[1]), (3, 1), "group {g}: GS_ALLOC_REQ counts"); + for v in 0..3usize { + let b = MESH_HEADER + v * vd; + let at = |k: usize| f32::from_bits(r[b + k]); + let (gf, vf) = (g as f32, v as f32); + assert_eq!([at(4), at(5)], [gf, vf], "group {g} vertex {v}: TEXCOORD1.xy"); + assert_eq!([at(8), at(9), at(10), at(11)], [0.5, gf, vf, 2.0], "group {g} vertex {v}: TEXCOORD4"); + assert_eq!([at(12), at(13), at(14), at(15)], [gf, vf, 0.0, 1.0], "group {g} vertex {v}: TEXCOORD3 (param 1)"); + } + } + let at = |x: usize, y: usize| px[y * 32 + x]; + assert_eq!(at(3, 29), [0.0, 0.5, 2.0, 1.0], "group 0 triangle (left)"); + assert_eq!(at(19, 29), [1.0, 0.5, 2.0, 1.0], "group 1 triangle (right)"); + assert_eq!(at(29, 3), [-1.0; 4], "outside both triangles"); +} + #[test] fn mesh_passthrough_strips_rdna2_edge_flag_bits() { use super::{mesh_passthrough, MsInterface}; @@ -3659,6 +4065,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}"); @@ -3700,7 +4107,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 @@ -3757,7 +4164,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 @@ -4013,7 +4420,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 @@ -4056,23 +4463,30 @@ fn gpu_mesh_mode_reads_memory_windows() { /// accesses in window 0. #[test] fn gpu_memory_windows_above_4_gib() { - memory_windows_above_4_gib(false); + memory_windows_above_4_gib(2, false); } /// The same program with the windows taken from the descriptor heap (`Options::heap_windows`): /// same results, and no `switch` over windows in the HLSL. #[test] fn gpu_memory_windows_from_the_heap() { - memory_windows_above_4_gib(true); + memory_windows_above_4_gib(2, true); } -fn memory_windows_above_4_gib(heap: bool) { +#[test] +fn gpu_memory_windows_beyond_the_root_uavs() { + for windows in [8, 16] { + memory_windows_above_4_gib(windows, true); + } +} + +fn memory_windows_above_4_gib(windows: usize, heap: bool) { if !gpu_ready() { return; } - let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap(); - let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64); - assert_eq!(w1 - w0, 1 << 32); + let arena = crate::gpu::uma::Uma::with_windows(windows, 1 << 20).unwrap(); + let (w0, w1) = (arena.window(0).0 as u64, arena.window(windows - 1).0 as u64); + assert_eq!(w1 - w0, ((windows - 1) as u64) << 32); let word = |a: u64| unsafe { &mut *(a as *mut u32) }; *word(w1 + 0x1000) = 0xC0FFEE; *word(w1 + 0x1004) = 0x1234; @@ -4097,12 +4511,18 @@ fn memory_windows_above_4_gib(heap: bool) { let p = prog(&refs); let one = translate(&p, &Options::default()).unwrap(); assert!(!one.hlsl.contains("mem1") && !one.hlsl.contains("xcl_w =") && !one.hlsl.contains("xcl_m"), "one window: the single-window HLSL"); - let t = translate(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() })).unwrap(); + let t = translate(&p, &on_gpu(Options { mem_windows: windows as u32, heap_windows: heap, ..Default::default() })).unwrap(); assert!(t.hlsl.contains("RWByteAddressBuffer mem1 : register(u3)")); assert_eq!(t.hlsl.contains("switch (xcl_w)"), !heap, "heap windows: no switch over windows"); - assert_eq!(t.hlsl.contains("ResourceDescriptorHeap[NonUniformResourceIndex(4u + xcl_w)]"), heap); let hlsl_dxil = || super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); - let dxil = direct_or(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() }), hlsl_dxil()); + let dxil = if windows > 4 && runner::direct_dxil() { + crate::gpu::dxil::kernel::translate(&p, crate::gpu::dxil::kernel::KernelOptions { + wave64: true, split: runner::split_wave64(), + mem_windows: windows as u32 | super::HEAP_WINDOWS, sampler_base: 0, + }).expect("expanded direct DXIL") + } else { + direct_or(&p, &on_gpu(Options { mem_windows: windows as u32, heap_windows: heap, ..Default::default() }), hlsl_dxil()) + }; let hi = |a: u64| (a >> 32) as u32; let mut st = KernelState::default(); st.sgpr[2..4].copy_from_slice(&[(w1 + 0x1000) as u32, hi(w1)]); @@ -4131,6 +4551,12 @@ fn memory_windows_above_4_gib(heap: bool) { } assert_eq!(*word(w1 + 0x6000), 64, "global_atomic_add in window 1"); assert_eq!(*word(w0 + 0x6000), 0, "nothing in window 0 at the same low address"); + if heap { + let null = super::MEM_HEAP_NULL - super::MEM_HEAP_BASE; + let index = if windows as u32 >= null { format!("min(xcl_w, {null}u)") } else { format!("select(xcl_w < {windows}u, xcl_w, {null}u)") }; + assert!(t.hlsl.contains(&format!("ResourceDescriptorHeap[NonUniformResourceIndex({}u + {index})]", super::MEM_HEAP_BASE))); + assert!(!t.hlsl.contains("if (xcl_w"), "heap windows: no branch around an access"); + } } /// Out-of-UMA addresses must NEVER alias onto live UMA windows via `& 3`: @@ -4143,24 +4569,33 @@ fn memory_windows_above_4_gib(heap: bool) { /// on `global_load`/`global_store` updates the target window accurately. #[test] fn gpu_memory_windows_reject_out_of_uma_aliasing() { - memory_windows_reject_out_of_uma_aliasing(false); + memory_windows_reject_out_of_uma_aliasing(false, 2); } /// The same with the windows taken from the descriptor heap (`Options::heap_windows`): an /// address outside them reads 0 and drops its stores and atomics there too. #[test] fn gpu_heap_windows_reject_out_of_uma_aliasing() { - memory_windows_reject_out_of_uma_aliasing(true); + memory_windows_reject_out_of_uma_aliasing(true, 2); +} + +/// Cover partial and complete expanded layouts; the full layout uses the min-index path. +#[test] +fn gpu_heap_windows_reject_out_of_uma_aliasing_all_slots() { + for windows in [4, 8, 16] { + memory_windows_reject_out_of_uma_aliasing(true, windows); + } } -fn memory_windows_reject_out_of_uma_aliasing(heap: bool) { +fn memory_windows_reject_out_of_uma_aliasing(heap: bool, windows: u32) { if !gpu_ready() { return; } - let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap(); + let arena = crate::gpu::uma::Uma::with_windows(windows as usize, 1 << 20).unwrap(); let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64); assert_eq!(w1 - w0, 1 << 32); let base_hi = (w0 >> 32) as u32; + let outside = windows.max(4); assert!(base_hi >= 4); let word = |a: u64| unsafe { &mut *(a as *mut u32) }; @@ -4207,17 +4642,23 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) { ]; 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 t = translate(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() })).unwrap(); + let t = translate(&p, &on_gpu(Options { mem_windows: windows, heap_windows: heap, ..Default::default() })).unwrap(); assert_eq!(t.hlsl.contains("switch (xcl_w)"), !heap); let hlsl_dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); - let dxil = direct_or(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() }), hlsl_dxil); + let dxil = if windows > 4 && runner::direct_dxil() { + crate::gpu::dxil::kernel::translate(&p, crate::gpu::dxil::kernel::KernelOptions { + wave64: true, split: runner::split_wave64(), mem_windows: windows | super::HEAP_WINDOWS, sampler_base: 0, + }).expect("expanded direct DXIL") + } else { + direct_or(&p, &on_gpu(Options { mem_windows: windows, heap_windows: heap, ..Default::default() }), hlsl_dxil) + }; let mut st = KernelState::default(); - st.sgpr[2..4].copy_from_slice(&[0x1000, base_hi + 4]); // s[2:3]: out-of-UMA hi = base_hi + 4 + st.sgpr[2..4].copy_from_slice(&[0x1000, base_hi + outside]); // s[2:3]: out-of-UMA hi = base_hi + outside st.sgpr[4..6].copy_from_slice(&[0x4000, 0]); // s[4:5]: hi == 0 32-bit descriptor read - st.sgpr[8..12].copy_from_slice(&[0x1000, ((base_hi + 5) & 0xFFFF) | (4 << 16), 64, 0]); // out-of-UMA V# (aliases w1 under & 3) + st.sgpr[8..12].copy_from_slice(&[0x1000, ((base_hi + outside + 1) & 0xFFFF) | (4 << 16), 64, 0]); // out-of-UMA V# (aliases w1 under & 3) st.sgpr[12..16].copy_from_slice(&[0x5000, ((base_hi + 1) & 0xFFFF) | (4 << 16), 64, 0]); // valid strided V# in w1 - st.sgpr[16..20].copy_from_slice(&[0x3000, ((base_hi + 4) & 0xFFFF) | (4 << 16), 64, 0]); // out-of-UMA atomic V# (aliases w0 under & 3) + st.sgpr[16..20].copy_from_slice(&[0x3000, ((base_hi + outside) & 0xFFFF) | (4 << 16), 64, 0]); // out-of-UMA atomic V# (aliases w0 under & 3) st.sgpr[20..22].copy_from_slice(&[0xFFFF_FFF0, base_hi]); // carry base st.sgpr[22..24].copy_from_slice(&[0, base_hi]); // borrow base (0 - 16 borrows into base_hi - 1) for r in st.vgpr.iter_mut() { @@ -4228,11 +4669,11 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) { r[11] = 0x7777_7777; r[14] = 0xBAD0_DEAD; r[4] = 0x1000; - r[5] = base_hi + 4; // out-of-UMA global_store (aliases w0 under & 3) + r[5] = base_hi + outside; // out-of-UMA global_store (aliases w0 under & 3) r[6] = 0x2000; r[7] = 0; // hi == 0 global_store (null pointer -> must be dropped) r[8] = 0x2000; - r[9] = base_hi + 5; // out-of-UMA global_atomic_add (aliases w1 under & 3) + r[9] = base_hi + outside + 1; // out-of-UMA global_atomic_add (aliases w1 under & 3) r[12] = 0x3000; r[13] = 0xFFFF_FFFF; // out-of-UMA global_atomic_inc CAS loop r[16] = 0x20; // carry offset: 0xFFFF_FFF0 + 0x20 = 0x1_0000_0010 -> w1 + 0x10 @@ -4258,6 +4699,82 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) { assert_eq!(*word(w1 + 0x3000), CANARY1, "out-of-UMA global_atomic_inc must not clobber w1"); } +/// Heap windows read without a branch (`HEAP_FLAT`, the direct translator): over 4 windows, the +/// same registers as the switch over root UAVs and as the guarded heap form, for scalar loads, +/// a V# load and per-lane global loads whose lanes pick different windows, some outside UMA +/// (read 0) and some not active (keep their old values). +#[test] +fn gpu_heap_flat_reads_match_the_switch_form() { + use crate::gpu::dxil::kernel::{translate, KernelOptions}; + if !gpu_ready() { + return; + } + let arena = crate::gpu::uma::Uma::with_windows(4, 1 << 20).unwrap(); + let w: Vec = (0..4).map(|k| arena.window(k).0 as u64).collect(); + let base_hi = (w[0] >> 32) as u32; + let word = |a: u64| unsafe { &mut *(a as *mut u32) }; + for (k, &wk) in w.iter().enumerate() { + *word(wk + 0x40) = 0xA0 + k as u32; + for l in 0..65u64 { + *word(wk + 0x100 + 4 * l) = (k as u32 + 1) * 1000 + l as u32; + } + } + let glbl = |n: &'static str, f: &[(&str, u64)]| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option) { + (n, "ENC_FLAT_GLBL", f.iter().map(|&(a, b)| (unsafe { std::mem::transmute::<&str, &'static str>(a) }, b)).collect(), None) + }; + let list = vec![ + ("S_LOAD_DWORD", "ENC_SMEM", vec![("SDATA", 30), ("SBASE", 1), ("OFFSET", 0)], None), + ("S_LOAD_DWORD", "ENC_SMEM", vec![("SDATA", 31), ("SBASE", 2), ("OFFSET", 0)], None), + ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", vec![("SDATA", 24), ("SBASE", 4), ("OFFSET", 4)], None), + ("V_CMPX_LT_U32", "ENC_VOPC", vec![("SRC0", 160), ("VSRC1", 0)], None), + ("BUFFER_LOAD_DWORD", "ENC_MUBUF", vec![("VDATA", 7), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + glbl("GLOBAL_LOAD_DWORD", &[("VDST", 6), ("ADDR", 4), ("SADDR", 0x7D), ("OFFSET", 0)]), + glbl("GLOBAL_LOAD_DWORDX2", &[("VDST", 8), ("ADDR", 10), ("SADDR", 16), ("OFFSET", 0)]), + ]; + 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 mut st = KernelState::default(); + st.sgpr[2..4].copy_from_slice(&[0x40, base_hi + 2]); + st.sgpr[4..6].copy_from_slice(&[0x40, base_hi + 6]); + st.sgpr[8..12].copy_from_slice(&[0x100, (base_hi + 3) & 0xFFFF, 0x400, 0]); + st.sgpr[12..16].copy_from_slice(&[0x100, (base_hi + 1) & 0xFFFF | 4 << 16, 64, 0]); + st.sgpr[16..18].copy_from_slice(&[0x100, base_hi]); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let l = l as u32; + r[0] = l; + r[4] = 0x100 + 4 * l; + r[5] = if l % 8 == 7 { base_hi + 5 } else { base_hi + l % 4 }; + for k in 6..10 { + r[k] = 0x7777_7777; + } + r[10] = 4 * l; + } + let split = runner::split_wave64(); + let run = |windows: u32| { + let dxil = translate(&p, KernelOptions { wave64: true, split, mem_windows: windows, sampler_base: 0 }).unwrap_or_else(|e| panic!("windows {windows:#x}: {e}")); + runner::run_in_arena(&dxil, &st, &arena).unwrap() + }; + let switch = run(4); + let flat = run(4 | super::HEAP_WINDOWS | super::HEAP_FLAT); + let guarded = run(4 | super::HEAP_WINDOWS); + assert_eq!((switch.sgpr[30], switch.sgpr[31]), (0xA2, 0), "s_load: window 2, outside UMA"); + assert_eq!(switch.sgpr[24..28], [4001, 4002, 4003, 4004], "s_buffer_load_dwordx4 from window 3"); + for l in 0..64u32 { + let v = &switch.vgpr[l as usize]; + let (old, active) = (0x7777_7777, l > 32); + assert_eq!(v[7], if active { 2000 + l } else { old }, "lane {l}: buffer_load from window 1"); + let global = if l % 8 == 7 { 0 } else { (l % 4 + 1) * 1000 + l }; + assert_eq!(v[6], if active { global } else { old }, "lane {l}: global_load from window {}", l % 4); + assert_eq!(v[8..10], if active { [1000 + l, 1001 + l] } else { [old, old] }, "lane {l}: global_load_dwordx2 from window 0"); + } + for (name, r) in [("heap flat", &flat), ("heap guarded", &guarded)] { + assert_eq!(r.sgpr[..32], switch.sgpr[..32], "{name}: SGPRs"); + for l in 0..64 { + assert_eq!(r.vgpr[l][..10], switch.vgpr[l][..10], "{name}: lane {l}"); + } + } +} + #[test] fn gpu_window_at_32bit_carry_edge_cases() { if !gpu_ready() { @@ -4510,6 +5027,88 @@ fn gpu_sparse_vram_descriptors_buffers_and_xmem() { } } +/// Constant data after the program (`Options::rodata`): `s_getpc_b64` plus the compiler's +/// offset is its address, and `s_load` / `global_load` read it from the shader. The memory +/// does not hold the code (a retail tone-map LUT bake read zeros for its spline coefficients +/// there and wrote one colour to every texel); any other address still reads the memory. +#[test] +fn gpu_loads_read_the_constant_data_after_the_program() { + let body = |table: u32| { + prog(&[ + ("S_GETPC_B64", "ENC_SOP1", &[("SDST", 0)], None), // s[0:1] = 4 + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 255)], Some(table.wrapping_sub(4))), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 128)], None), + ("GLOBAL_LOAD_DWORDX3", "ENC_FLAT_GLBL", &[("VDST", 5), ("ADDR", 10), ("SADDR", 0), ("OFFSET", 0)], None), + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 0), ("OFFSET", 4), ("SOFFSET", 125)], None), + ("S_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 0), ("OFFSET", 8), ("SOFFSET", 125)], None), + // memory, not the data: v[12:13] and s[2:3] + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 8), ("ADDR", 12), ("SADDR", 0x7D), ("OFFSET", 0)], None), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 28), ("SBASE", 1), ("OFFSET", 0), ("SOFFSET", 125)], None), + ]) + }; + // as in retail data: program, guard s_endpgm, block (u32 N, N dwords, s_endpgm) + let block = body(0).len() as u32 + 4; + let code = body(block + 4); + let table: Vec = (0..8).map(|i| 0x7AB1_E000 + i).collect(); + let mut data = vec![table.len() as u32]; + data.extend(&table); + data.push(0xBF81_0000); + let rodata = vec![(block, data)]; + assert!(!translate(&code, &Options::default()).unwrap().hlsl.contains("xcl_gload"), "no data, no loader"); + if !gpu_ready() { + return; + } + let check = |r: &runner::KernelResult, what: &str| { + assert_eq!(r.sgpr[20], table[1], "{what}: s_load_dword of the table"); + assert_eq!(r.sgpr[24..28], table[2..6], "{what}: s_load_dwordx4 of the table"); + assert_eq!(r.sgpr[28..30], [4242, 4343], "{what}: s_load from memory"); + for l in 0..64usize { + let k = l % 6; + assert_eq!(r.vgpr[l][5..8], table[k..k + 3], "{what}, lane {l}: three dwords of the table from {k}"); + assert_eq!(r.vgpr[l][8], 7000 + l as u32, "{what}, lane {l}: memory outside the data"); + } + }; + // one window: nothing of the code is in the memory + let mut st = KernelState::default(); + st.sgpr[2] = 0x900; + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[10] = 4 * (l as u32 % 6); + r[12] = 0x800 + 4 * l as u32; + } + let mut mem = vec![0u32; 1024]; + mem[0x240..0x242].copy_from_slice(&[4242, 4343]); + for l in 0..64 { + mem[0x200 + l] = 7000 + l as u32; + } + let t = translate(&code, &Options { rodata: rodata.clone(), ..runner::options(Mode::Kernel) }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); + check(&runner::run(&dxil, &st, &mem).unwrap(), "one window"); + // several windows: a code address is in none of them, and window 0 holds other bytes at + // the table's offset + let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap(); + let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64); + let word = |a: u64| unsafe { &mut *(a as *mut u32) }; + for k in 0..16u64 { + *word(w0 + block as u64 + 4 * k) = 0xBAD0_0000 + k as u32; + } + *word(w1 + 0x900) = 4242; + *word(w1 + 0x904) = 4343; + st.sgpr[2..4].copy_from_slice(&[(w1 + 0x900) as u32, (w1 >> 32) as u32]); + for (l, r) in st.vgpr.iter_mut().enumerate() { + *word(w1 + 0x800 + 4 * l as u64) = 7000 + l as u32; + r[12] = (w1 + 0x800 + 4 * l as u64) as u32; + r[13] = (w1 >> 32) as u32; + } + for heap in [false, true] { + let t = translate(&code, &on_gpu(Options { mem_windows: 2, heap_windows: heap, rodata: rodata.clone(), ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported); + assert!(t.hlsl.contains(&format!("if (xcl_w == 0xC0DEu - xcl_uma_base && a - {block}u < 40u)")), "the data is at code addresses only:\n{}", t.hlsl); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); + check(&runner::run_in_arena(&dxil, &st, &arena).unwrap(), if heap { "heap windows" } else { "two windows" }); + } +} + /// Experiment: does OpenExistingHeapFromAddress accept a reservation with only part committed? #[test] #[ignore] @@ -5629,10 +6228,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))])); @@ -6477,7 +7076,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(); @@ -6883,7 +7482,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] { @@ -8270,7 +8869,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() { @@ -8322,6 +8921,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); @@ -9707,7 +10307,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() } @@ -9788,7 +10388,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 cc8b830edd..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; @@ -398,7 +411,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 +455,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 +541,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 +619,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 +773,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 +891,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] @@ -997,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(); @@ -1133,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/texture.rs b/crates/xcl/src/gpu/texture.rs index cde3561492..a8963663f2 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -207,12 +207,15 @@ pub unsafe fn upload(dev: &ID3D12Device, queue: &ID3D12CommandQueue, res: &ID3D1 /// retail game most of its frame once it streamed textures: each of those D3D12 calls waits for /// the video memory manager, 200 – 650 ms apiece then. struct Uploader { + dev_key: usize, alloc: ID3D12CommandAllocator, list: ID3D12GraphicsCommandList, fence: ID3D12Fence, value: u64, /// (buffer, its mapped bytes, capacity) staging: Option<(ID3D12Resource, *mut u8, u64)>, + last_used_ms: u64, + last_used_frame: u64, } // D3D12 objects are free-threaded; the mapped pointer is only used by the holder of the uploader @@ -225,6 +228,149 @@ static UPLOADERS: std::sync::Mutex u64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 +} + +fn staging_pool_cap_bytes() -> u64 { + static CAP: std::sync::OnceLock = std::sync::OnceLock::new(); + *CAP.get_or_init(|| { + std::env::var("XCL_STAGING_POOL_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map_or(STAGING_POOL_DEFAULT_CAP, |mb| mb.saturating_mul(1 << 20)) + }) +} + +/// Power-of-2 bucket size for the shared upload staging pool (`<= 8 MiB`), or `None` if oversized. +fn staging_pool_bucket(bytes: u64) -> Option { + let cap = bytes.max(64 << 10).checked_next_power_of_two()?; + (cap <= STAGING_POOL_MAX_ITEM).then_some(cap) +} + +struct PooledStaging { + item: T, + last_ms: u64, + last_frame: u64, +} + +/// Power-of-2 upload staging buffer pool (`<= 8 MiB` per entry, bounded total capacity) with +/// idle reclamation after `STAGING_IDLE_MS` and `STAGING_IDLE_FRAMES`. +struct StagingPool { + buckets: std::collections::BTreeMap>>, + total_bytes: u64, + cap_bytes: u64, +} + +impl StagingPool { + fn new(cap_bytes: u64) -> Self { + Self { + buckets: std::collections::BTreeMap::new(), + total_bytes: 0, + cap_bytes, + } + } + + fn acquire(&mut self, bytes: u64) -> Option<(u64, T)> { + let bucket = staging_pool_bucket(bytes)?; + let list = self.buckets.get_mut(&bucket)?; + let entry = list.pop()?; + if list.is_empty() { + self.buckets.remove(&bucket); + } + self.total_bytes = self.total_bytes.saturating_sub(bucket); + Some((bucket, entry.item)) + } + + /// Return a GPU-idle power-of-2 buffer to the pool, or hand it back to the caller to drop if + /// pooling is disabled or the buffer exceeds `STAGING_POOL_MAX_ITEM` / `cap_bytes`. + fn release(&mut self, cap: u64, item: T, now_ms: u64, frame: u64) -> Option { + if self.cap_bytes == 0 || cap == 0 || !cap.is_power_of_two() || cap > STAGING_POOL_MAX_ITEM || cap > self.cap_bytes { + return Some(item); + } + while self.total_bytes.saturating_add(cap) > self.cap_bytes { + if !self.evict_oldest() { + return Some(item); + } + } + self.buckets.entry(cap).or_default().push(PooledStaging { item, last_ms: now_ms, last_frame: frame }); + self.total_bytes = self.total_bytes.saturating_add(cap); + None + } + + fn evict_oldest(&mut self) -> bool { + let mut victim: Option<(u64, usize, u64)> = None; + for (&cap, list) in &self.buckets { + for (idx, e) in list.iter().enumerate() { + if victim.is_none_or(|(_, _, ts)| e.last_ms < ts) { + victim = Some((cap, idx, e.last_ms)); + } + } + } + let Some((cap, idx, _)) = victim else { return false }; + if let Some(list) = self.buckets.get_mut(&cap) { + list.remove(idx); + if list.is_empty() { + self.buckets.remove(&cap); + } + self.total_bytes = self.total_bytes.saturating_sub(cap); + return true; + } + false + } + + fn trim_idle(&mut self, now_ms: u64, frame: u64, force_all: bool) -> (usize, u64) { + let mut freed_count = 0usize; + let mut freed_bytes = 0u64; + let mut empty_buckets = Vec::new(); + for (&cap, list) in &mut self.buckets { + let before = list.len(); + if force_all { + list.clear(); + } else { + list.retain(|e| { + let ms_idle = now_ms.saturating_sub(e.last_ms) >= STAGING_IDLE_MS; + let fr_idle = frame.saturating_sub(e.last_frame) >= STAGING_IDLE_FRAMES; + !(ms_idle && fr_idle) + }); + } + let dropped = before - list.len(); + if dropped > 0 { + freed_count += dropped; + let bytes = cap.saturating_mul(dropped as u64); + freed_bytes = freed_bytes.saturating_add(bytes); + self.total_bytes = self.total_bytes.saturating_sub(bytes); + } + if list.is_empty() { + empty_buckets.push(cap); + } + } + for cap in empty_buckets { + self.buckets.remove(&cap); + } + (freed_count, freed_bytes) + } +} + +struct MappedStaging(ID3D12Resource, *mut u8); + +// D3D12 resources are free-threaded; mapped pointer is owned exclusively while pooled or held. +unsafe impl Send for MappedStaging {} + +static STAGING_POOLS: std::sync::Mutex>>> = std::sync::Mutex::new(None); + fn staging_capacity(bytes: u64) -> Option { const LARGE: u64 = 64 << 20; const STEP: u64 = 16 << 20; @@ -241,20 +387,53 @@ impl Uploader { let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?; list.Close().map_err(err)?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(err)?; - Ok(Uploader { alloc, list, fence, value: 0, staging: None }) + Ok(Uploader { + dev_key: windows::core::Interface::as_raw(dev) as usize, + alloc, + list, + fence, + value: 0, + staging: None, + last_used_ms: monotonic_ms(), + last_used_frame: CURRENT_FRAME.load(std::sync::atomic::Ordering::Relaxed), + }) } - /// An upload buffer of at least `bytes`, mapped: the one kept, or a bigger one. - unsafe fn staging(&mut self, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, *mut u8), String> { + /// An upload buffer of at least `bytes`, mapped: the one kept, a pooled power-of-2 buffer, + /// or a freshly allocated one. + unsafe fn staging(&mut self, dev: &ID3D12Device, bytes: u64, now_ms: u64, frame: u64) -> Result<(ID3D12Resource, *mut u8), String> { + self.last_used_ms = now_ms; + self.last_used_frame = frame; if let Some((b, p, cap)) = &self.staging { if *cap >= bytes { return Ok((b.clone(), *p)); } } let cap = staging_capacity(bytes).ok_or("texture upload buffer size overflow")?; - // A cached uploader has passed its last copy fence. Return this reference before - // acquiring the replacement so the growth path does not keep two buffers itself. - drop(self.staging.take()); + // A cached uploader has passed its last copy fence. Return its old `<= 8 MiB` buffer to + // the shared power-of-2 pool (or drop an oversized one) before acquiring the replacement + // so the growth path does not keep two oversized buffers alive simultaneously. + if let Some((old_b, old_p, old_cap)) = self.staging.take() { + if old_cap <= STAGING_POOL_MAX_ITEM && staging_pool_cap_bytes() > 0 { + let mut pools = STAGING_POOLS.lock().unwrap(); + let pool = pools + .get_or_insert_with(Default::default) + .entry(self.dev_key) + .or_insert_with(|| StagingPool::new(staging_pool_cap_bytes())); + let _ = pool.release(old_cap, MappedStaging(old_b, old_p), now_ms, frame); + } + } + if cap <= STAGING_POOL_MAX_ITEM && staging_pool_cap_bytes() > 0 { + let mut pools = STAGING_POOLS.lock().unwrap(); + if let Some((pooled_cap, MappedStaging(b, p))) = pools + .as_mut() + .and_then(|m| m.get_mut(&self.dev_key)) + .and_then(|pool| pool.acquire(cap)) + { + self.staging = Some((b.clone(), p, pooled_cap)); + return Ok((b, p)); + } + } let b = buffer(dev, cap)?; let mut p = std::ptr::null_mut(); b.Map(0, None, Some(&mut p)).map_err(err)?; @@ -263,6 +442,56 @@ impl Uploader { } } +/// Reclaim idle upload staging buffers (unused for `>= 2 s` and `>= 30` frames, or immediately +/// under low Windows commit headroom) to prevent post-streaming upload buffers from pinning +/// commit memory indefinitely. +pub fn trim_idle_staging(frame: u64, low_commit: bool) { + CURRENT_FRAME.store(frame, std::sync::atomic::Ordering::Relaxed); + if !low_commit && !frame.is_multiple_of(15) { + return; + } + let now_ms = monotonic_ms(); + let mut freed_bytes = 0u64; + let mut freed_count = 0usize; + { + let mut pools = STAGING_POOLS.lock().unwrap(); + if let Some(map) = pools.as_mut() { + for pool in map.values_mut() { + let (n, b) = pool.trim_idle(now_ms, frame, low_commit); + freed_count += n; + freed_bytes = freed_bytes.saturating_add(b); + } + } + } + { + let mut ups = UPLOADERS.lock().unwrap(); + if let Some(map) = ups.as_mut() { + for up in map.values_mut() { + let Some((_, _, cap)) = up.staging else { continue }; + let idle = now_ms.saturating_sub(up.last_used_ms) >= STAGING_IDLE_MS + && frame.saturating_sub(up.last_used_frame) >= STAGING_IDLE_FRAMES; + let shrink_low = low_commit && cap > STAGING_MIN; + if idle || shrink_low { + up.staging = None; + freed_count += 1; + freed_bytes = freed_bytes.saturating_add(cap); + } + } + } + } + if freed_bytes > 0 { + static LOGGED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = LOGGED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if n < 4 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: released {freed_count} idle texture upload staging buffer(s) ({:.1} MiB{})", + freed_bytes as f64 / (1024.0 * 1024.0), + if low_commit { ", low commit" } else { "" } + ); + } + } +} + /// Several uploads on one list, one wait: (resource, subresources, states) each – the states /// the texture is in and is left in: one for every subresource, or one per subresource (D3D12 /// order). A failure of one is returned with its index; the others still run. The texels go @@ -278,24 +507,14 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items None => Uploader::new(dev)?, }; // where each texture's texels go in the upload buffer - let mut failed = Vec::new(); - let mut planned = Vec::with_capacity(items.len()); - let mut total = 0u64; - for (k, (res, subs, states)) in items.iter().enumerate() { - match layout(dev, res, subs, states, states) { - Ok(l) => { - let base = total.div_ceil(PLACEMENT) * PLACEMENT; - total = base + l.total; - planned.push((k, l, base)); - } - Err(e) => failed.push((k, e)), - } - } + let (failed, planned, total) = plan_batch(dev, items); if planned.is_empty() { put_back(key, up); return Ok(failed); } - let (staging, mapped) = up.staging(dev, total)?; + let now_ms = monotonic_ms(); + let frame = CURRENT_FRAME.load(std::sync::atomic::Ordering::Relaxed); + let (staging, mapped) = up.staging(dev, total, now_ms, frame)?; up.alloc.Reset().map_err(err)?; up.list.Reset(&up.alloc, None).map_err(err)?; for (k, l, base) in &planned { @@ -313,10 +532,111 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items std::mem::forget(up); return Err(copy_error(e)); } + up.last_used_ms = monotonic_ms(); + up.last_used_frame = CURRENT_FRAME.load(std::sync::atomic::Ordering::Relaxed); put_back(key, up); Ok(failed) } +unsafe fn plan_batch(dev: &ID3D12Device, items: &[(ID3D12Resource, Vec, Vec)]) -> (Vec<(usize, String)>, Vec<(usize, Layout, u64)>, u64) { + let mut failed = Vec::new(); + let mut planned = Vec::with_capacity(items.len()); + let mut total = 0u64; + for (k, (res, subs, states)) in items.iter().enumerate() { + match layout(dev, res, subs, states, states) { + Ok(l) => { + let base = total.div_ceil(PLACEMENT) * PLACEMENT; + total = base + l.total; + planned.push((k, l, base)); + } + Err(e) => failed.push((k, e)), + } + } + (failed, planned, total) +} + +struct StagingSlot { + dev_key: usize, + cap: u64, + pooled: Option, + _unpooled: Option, +} + +impl Drop for StagingSlot { + fn drop(&mut self) { + if let Some(ms) = self.pooled.take() { + if self.cap <= STAGING_POOL_MAX_ITEM && staging_pool_cap_bytes() > 0 { + let now_ms = monotonic_ms(); + let frame = CURRENT_FRAME.load(std::sync::atomic::Ordering::Relaxed); + let mut pools = STAGING_POOLS.lock().unwrap(); + let pool = pools + .get_or_insert_with(Default::default) + .entry(self.dev_key) + .or_insert_with(|| StagingPool::new(staging_pool_cap_bytes())); + let _ = pool.release(self.cap, ms, now_ms, frame); + } + } + } +} + +/// GPU-side upload resources kept alive until `queue`'s fence passes the submitted batch. +/// Dropping an `InFlight` returns pooled `<= 8 MiB` staging buffers to `STAGING_POOLS` and frees +/// oversized staging buffers immediately. +pub struct InFlight { + _alloc: ID3D12CommandAllocator, + _list: ID3D12GraphicsCommandList, + _staging: StagingSlot, + pub bytes: u64, +} + +/// Record and execute a batch of texture uploads directly on `queue` without waiting on the CPU. +/// The returned `InFlight` must stay alive until `queue` completes this submission. +pub unsafe fn submit_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result<(Vec<(usize, String)>, Option), String> { + let (failed, planned, bytes) = plan_batch(dev, items); + if planned.is_empty() { + return Ok((failed, None)); + } + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(err)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?; + let dev_key = windows::core::Interface::as_raw(dev) as usize; + let slot = if let Some(bucket) = (staging_pool_cap_bytes() > 0).then(|| staging_pool_bucket(bytes)).flatten() { + let cached = STAGING_POOLS + .lock() + .unwrap() + .as_mut() + .and_then(|m| m.get_mut(&dev_key)) + .and_then(|pool| pool.acquire(bucket)); + let (cap, ms) = match cached { + Some(hit) => hit, + None => { + let b = buffer(dev, bucket)?; + let mut mapped = std::ptr::null_mut(); + b.Map(0, None, Some(&mut mapped)).map_err(err)?; + (bucket, MappedStaging(b, mapped as *mut u8)) + } + }; + for (k, layout, base) in &planned { + let (res, subs, states) = &items[*k]; + record_into(&list, res, subs, layout, states, states, &ms.0, ms.1, *base); + } + StagingSlot { dev_key, cap, pooled: Some(ms), _unpooled: None } + } else { + let staging = buffer(dev, bytes)?; + let mut mapped = std::ptr::null_mut(); + staging.Map(0, None, Some(&mut mapped)).map_err(err)?; + for (k, layout, base) in &planned { + let (res, subs, states) = &items[*k]; + record_into(&list, res, subs, layout, states, states, &staging, mapped as *mut u8, *base); + } + staging.Unmap(0, None); + StagingSlot { dev_key, cap: bytes, pooled: None, _unpooled: Some(staging) } + }; + list.Close().map_err(err)?; + queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).map_err(err)?)]); + let tracked = slot.cap; + Ok((failed, Some(InFlight { _alloc: alloc, _list: list, _staging: slot, bytes: tracked }))) +} + fn put_back(key: usize, up: Uploader) { UPLOADERS.lock().unwrap().get_or_insert_with(Default::default).insert(key, up); } @@ -821,6 +1141,44 @@ mod tests { assert_eq!(staging_capacity(u64::MAX), None); } + #[test] + fn staging_pool_buckets_caps_reuses_and_reclaims_idle() { + let mib = 1u64 << 20; + assert_eq!(staging_pool_bucket(1), Some(64 << 10)); + assert_eq!(staging_pool_bucket(3 * mib), Some(4 * mib)); + assert_eq!(staging_pool_bucket(8 * mib), Some(8 * mib)); + assert_eq!(staging_pool_bucket(8 * mib + 1), None); + + // Disabled pool (cap 0) immediately returns released items. + let mut disabled = StagingPool::::new(0); + assert_eq!(disabled.release(4 * mib, 1, 0, 0), Some(1)); + + // Power-of-2 pooling with 12 MiB cap: LIFO reuse, oldest eviction on cap pressure, + // and idle reclamation only once BOTH >= 2 s and >= 30 frames have elapsed. + let mut pool = StagingPool::::new(12 * mib); + assert_eq!(pool.release(4 * mib, 10, 100, 1), None); + assert_eq!(pool.release(8 * mib, 20, 200, 2), None); + assert_eq!(pool.total_bytes, 12 * mib); + // Oversized (> 8 MiB) or non-power-of-2 buffers bypass the pool. + assert_eq!(pool.release(16 * mib, 99, 250, 3), Some(99)); + assert_eq!(pool.release(6 * mib, 98, 250, 3), Some(98)); + // Inserting another 4 MiB evicts the oldest (id 10, ts 100). + assert_eq!(pool.release(4 * mib, 30, 300, 4), None); + assert_eq!(pool.total_bytes, 12 * mib); + assert_eq!(pool.acquire(3 * mib), Some((4 * mib, 30))); + assert_eq!(pool.total_bytes, 8 * mib); + // Not idle yet: only time elapsed (frames < 30), or only frames elapsed (time < 2000ms). + assert_eq!(pool.trim_idle(5_000, 10, false), (0, 0)); + assert_eq!(pool.trim_idle(1_000, 100, false), (0, 0)); + // Both thresholds met -> idle 8 MiB buffer reclaimed. + assert_eq!(pool.trim_idle(2_200, 32, false), (1, 8 * mib)); + assert_eq!(pool.total_bytes, 0); + // Low-commit forced trim reclaims immediately regardless of idle age. + assert_eq!(pool.release(4 * mib, 40, 2_200, 32), None); + assert_eq!(pool.trim_idle(2_200, 32, true), (1, 4 * mib)); + assert_eq!(pool.total_bytes, 0); + } + fn select_large_upload_device_with( selector: &crate::gpu::adapter::Selector, make_factory: impl FnOnce() -> Result, diff --git a/crates/xcl/src/gpu/tiling.rs b/crates/xcl/src/gpu/tiling.rs index b9fa1abdd3..0ac818b320 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, } } @@ -204,34 +231,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 } } @@ -378,6 +586,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) } @@ -425,59 +634,16 @@ 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; - 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]); - } - } - 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 } /// 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]); - } - } + self.layout.tile_2d(dst, linear, l.offset, l.width, l.height, l.pitch, l.origin, slice); } } @@ -872,5 +1038,37 @@ 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}"); + } + } + } + } + } + } } diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 7592d044b0..309689ce7f 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -679,6 +679,22 @@ impl Uma { Some(p) } + /// The committed-window allocation covering `p`: `(start, bytes)` (excluding XCL's arena pool). + pub fn allocation_at(&self, p: usize) -> Option<(usize, usize)> { + if !self.is_committed(p) { + return None; + } + { + let pool = self.pool.lock().unwrap(); + if p >= pool.0 && p < pool.1 { + return None; + } + } + let off = p - self.base; + let g = self.inner.lock().unwrap(); + g.used.range(..=off).next_back().map(|(&o, &l)| (self.base + o, l)).filter(|&(a, l)| p < a + l) + } + /// Release a block from `alloc` (false: not one of ours). pub fn free(&self, p: usize) -> bool { if !self.is_committed(p) { @@ -740,8 +756,12 @@ pub struct Arena { end: usize, } -/// block size of an `Arena` -pub const ARENA_BLOCK: usize = 4 * GRAIN; +/// block size of an `Arena` (64 KiB grain keeps ~190 live allocators under ~25 MB instead of ~100 MB) +pub const ARENA_BLOCK: usize = GRAIN; + +/// Maximum `AllocateUploadMemory` request routed through the per-list arena (keeps the 128 KiB +/// threshold unchanged after shrinking `ARENA_BLOCK` from 256 KiB to 64 KiB). +pub const UPLOAD_IN_ARENA_MOST: usize = 2 * GRAIN; impl Arena { /// `n` bytes at an `align`-aligned address in committed unified memory (not zeroed), or @@ -774,6 +794,13 @@ impl Arena { static GLOBAL: OnceLock> = OnceLock::new(); +/// A process that holds no title memory (a shader preparation worker): `get` is None from here +/// on, and nothing is reserved or committed for it (a run's region commits its coherent window). +/// Before any `get`. +pub fn leave_out() { + let _ = GLOBAL.set(None); +} + /// The title's graphics memory XCL places in the coherent window (`note_coherent_need`) is /// known only once it asks for it, and the window is committed when it is made: its size is /// what the title asked for in its last run (`/cache/uma_coherent.txt`) and XCL's own @@ -782,11 +809,22 @@ fn coherent_file() -> std::path::PathBuf { crate::state::data_dir().join("cache").join("uma_coherent.txt") } +/// Optional upper cap on the coherent window(s) in bytes (`XCL_COHERENT_CAP_MB`), keeping +/// `uma_coherent.txt` auto-growth bounded so large general-purpose title heaps stay out of +/// GPU-writable Window 3 when desired. +fn coherent_cap_bytes(max_cap: usize) -> usize { + std::env::var("XCL_COHERENT_CAP_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map(|mb| (mb << 20).clamp(GRAIN, max_cap)) + .unwrap_or(max_cap) +} + /// Bytes the coherent window(s) are made with for a runtime layout of `windows` windows. pub fn coherent_hint_for(windows: usize) -> usize { - let cap = max_coherent_bytes(windows); + let cap = coherent_cap_bytes(max_coherent_bytes(windows)); if let Some(mb) = std::env::var("XCL_COHERENT_MB").ok().and_then(|v| v.parse::().ok()) { - return (mb << 20).clamp(GRAIN, cap); + return (mb << 20).clamp(GRAIN, max_coherent_bytes(windows)); } let title = std::fs::read_to_string(coherent_file()).ok().and_then(|s| s.trim().parse::().ok()).unwrap_or(0); // only with the commit for all of it: the title's ~13 GB, video memory for its render targets @@ -799,7 +837,7 @@ pub fn coherent_hint_for(windows: usize) -> usize { free_commit() >> 20, NEEDS_FOR_COHERENT_HEAPS >> 20 ); - return RUNTIME_COMMITTED_CAP; + return RUNTIME_COMMITTED_CAP.min(cap); } (title + RUNTIME_COMMITTED_CAP).min(cap) } @@ -1157,7 +1195,10 @@ mod tests { // HLSL path accepts 8/16 with heap_windows, rejects without. assert!(recomp::translate(&code, &Options { mem_windows: w, heap_windows: false, ..Default::default() }).is_err()); let t = recomp::translate(&code, &Options { mem_windows: w, heap_windows: true, ..Default::default() }).unwrap(); - assert!(t.hlsl.contains(&format!("xcl_w >= {w}u")), "HLSL must range-check against {w} windows"); + // no guard branch: an index outside the windows takes the null view at MEM_HEAP_NULL + let null = recomp::MEM_HEAP_NULL - recomp::MEM_HEAP_BASE; + let want = if w >= null { format!("min(xcl_w, {null}u)") } else { format!("select(xcl_w < {w}u, xcl_w, {null}u)") }; + assert!(t.hlsl.contains(&want) && !t.hlsl.contains("xcl_w >= "), "HLSL must clamp to {w} windows: {want}"); assert!(!t.hlsl.contains("mem4"), "root signature ABI stays at 4 root UAVs"); // Direct DXIL path validates cleanly with 8/16 | HEAP_WINDOWS. translate(&code, KernelOptions { wave64: true, split: false, mem_windows: w | HEAP_WINDOWS, sampler_base: 0 }).unwrap(); diff --git a/crates/xcl/src/gpu/xbox.rs b/crates/xcl/src/gpu/xbox.rs index d24ef4aca0..28a1abf0da 100644 --- a/crates/xcl/src/gpu/xbox.rs +++ b/crates/xcl/src/gpu/xbox.rs @@ -151,6 +151,19 @@ impl Fssm { self.version == 0x101 && rd32(&self.data, 0xD4).is_some_and(|w| w != 0xDEAD_BEEF && w & 0x20 != 0) } + /// The constant data blocks that follow program `p` in the code region, as the program + /// addresses them (`s_getpc_b64`: from its own start): (address, dwords of the block). + pub fn rodata(&self, p: &Program) -> Vec<(u32, Vec)> { + self.data_blocks + .iter() + .filter(|b| b.offset >= p.offset + p.len) + .filter_map(|b| { + let bytes = self.data.get(b.offset..b.offset + b.len)?; + Some(((b.offset - p.offset) as u32, bytes.chunks_exact(4).map(|w| u32::from_le_bytes(w.try_into().unwrap())).collect())) + }) + .collect() + } + pub fn stage_label(&self) -> String { if self.stages.is_empty() { return "?".into(); diff --git a/crates/xcl/src/hle/bcpack/victory.rs b/crates/xcl/src/hle/bcpack/victory.rs index 20b8fa5129..9886e914d9 100644 --- a/crates/xcl/src/hle/bcpack/victory.rs +++ b/crates/xcl/src/hle/bcpack/victory.rs @@ -331,10 +331,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 @@ -348,26 +377,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 < ix3 + ix2 { - ix[k] = if k < ix3 { 3 } else { 2 }; + while k < 8 { + if ep[k] != 0 { + ep_mask[k] = ((1u16 << ep[k]) - 1) as u8; + ep_len = k + 1; + } k += 1; } - Widths { ep, ix, paired } + let mut ix_mask = [0u8; 32]; + let ix_len = ix3 + ix2; + let mut k = 0; + while k < ix_len { + ix_mask[k] = if k < ix3 { 7 } else { 3 }; + k += 1; + } + 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); @@ -390,11 +433,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); @@ -403,22 +452,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; } } @@ -427,7 +480,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 } @@ -447,7 +500,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 } @@ -471,54 +524,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 { @@ -539,9 +626,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; } @@ -735,15 +824,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); } }; @@ -920,11 +1009,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); @@ -999,14 +1084,186 @@ 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()); } Ok(()) } +#[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"); + } + } +} + diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 8b81b85913..914562f9f3 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -28,6 +28,8 @@ struct Backing { users: HashSet, /// queue → (fence, value after the last submit of one of them) marks: HashMap, + /// true once this backing has been PC-reset while idle and no new recording/submit has touched it + already_reset: bool, } impl Backing { @@ -54,6 +56,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 VRAM `io` slabs 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 { @@ -81,7 +93,24 @@ fn move_list(s: &mut State, list: usize, backing: usize) { } } } - s.backings.entry(backing).or_default().users.insert(list); + let b = s.backings.entry(backing).or_default(); + b.users.insert(list); + b.already_reset = false; +} + +/// A split segment or stand-in PC list has been retired into `title_list`'s spare pool (or +/// superseded by a new recording on `wrapper`): it will not be submitted again until a future +/// `Reset` binds it to a new backing. Removing it from `users` lets its old backing become +/// reusable once its already-submitted GPU `marks` complete, while keeping `last_submit` so +/// `in_flight(list)` still prevents premature reuse. +pub(super) fn retire_recording(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); + } + } } /// The PC list's final Release ended its recording. Submitted work still holds the backing @@ -178,6 +207,78 @@ pub unsafe fn note_resubmits(queue: *mut c_void, lists: &[*mut c_void]) -> usize found } +/// How long a submit waits for the previous submits of its lists (`XCL_RESUBMIT_WAIT_MS`, 2 000; +/// 0: not at all, as before). +fn resubmit_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_RESUBMIT_WAIT_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2000))) +} + +/// `lists` are about to be submitted: the ones whose previous submit the GPU has not finished +/// (`note_resubmits`) wait for it first, `limit` at most for all of them; then they go as they +/// are. On the PC a list must not be executed again before its previous execution is done (debug +/// layer id 553); a console lets a title do it, and a retail title did it about once a second in +/// its world – 128 times before its device was removed with shader memory faults, and not once in +/// a run that ended well. Returns (lists waited for, of them not done in time). +pub unsafe fn wait_for_previous_submits(lists: &[*mut c_void]) -> (usize, usize) { + wait_for_previous_submits_within(lists, resubmit_wait()) +} + +unsafe fn wait_for_previous_submits_within(lists: &[*mut c_void], limit: std::time::Duration) -> (usize, usize) { + if !enabled() || limit.is_zero() { + return (0, 0); + } + // (the fences are taken out: nothing is waited for with STATE held) + let pending: Vec<(ID3D12Fence, u64)> = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return (0, 0) }; + lists + .iter() + .filter_map(|&l| s.last_submit.get(&(l as usize))) + .filter(|l| l.fence.GetCompletedValue() < l.value) + .map(|l| (l.fence.clone(), l.value)) + .collect() + }; + if pending.is_empty() { + return (0, 0); + } + let start = std::time::Instant::now(); + let mut late = 0; + for (fence, value) in &pending { + // (XCL's own fence, read without the title's hook; a removed device reads as the largest + // value: no wait then. Such a submit is milliseconds from done: a short poll) + let mut polls = 0u32; + while fence.GetCompletedValue() < *value { + if start.elapsed() >= limit { + late += 1; + break; + } + if polls < 64 { + std::thread::yield_now(); + } else { + std::thread::sleep(std::time::Duration::from_micros(200)); + } + polls += 1; + } + } + static WAITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = WAITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if late > 0 { + crate::xlog_warn!( + "D3D12.X: {late} of {} previous submits of lists submitted again were not done after {} ms – they go as they are (#{n} such submits)", + pending.len(), + limit.as_millis() + ); + } else if n <= 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: a submit waited {:.1} ms for the previous submits of {} of its lists (#{n} such submits)", + start.elapsed().as_secs_f64() * 1e3, + pending.len() + ); + } + (pending.len(), late) +} + /// Whether the GPU has not finished the last submit of the PC list `list` (#1452: it must not be /// submitted again before that; `title_list` records the title's next recording elsewhere). pub fn in_flight(list: usize) -> bool { @@ -209,9 +310,14 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { *v += 1; (f.clone(), *v) }; + super::flight::signaled("title", key, &fence, value); + // (how many PC lists that value stands for: 0 is a signal alone) + super::flight::event("title lists", key as u64, value, lists.len() as u64); for &l in lists { if let Some(&b) = s.of_list.get(&(l as usize)) { - s.backings.entry(b).or_default().marks.insert(key, (fence.clone(), value)); + let entry = s.backings.entry(b).or_default(); + entry.marks.insert(key, (fence.clone(), value)); + entry.already_reset = false; } let recording = s.recordings.get(&(l as usize)).copied().unwrap_or(0); s.last_submit.insert(l as usize, LastSubmit { queue: key, fence: fence.clone(), value, recording }); @@ -227,6 +333,89 @@ 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 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 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 f.GetCompletedValue() < 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 { + 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)| f.GetCompletedValue() >= *v) { + ready.push(s.pending_releases.swap_remove(i)); + } else { + i += 1; + } + } + ready + }; + for item in done { + (item.cleanup)(); + for b in item.made { + 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). @@ -258,44 +447,296 @@ pub unsafe fn forget(alloc: usize) { } } +/// Pop idle put-aside backings of title allocator `a` whose lists and GPU work have finished +/// so the caller can reset them OUTSIDE `STATE` (preventing re-entrant deadlocks if resetting +/// an allocator drops a prelude `ID3D12CommandAllocator` whose `Release` calls `forget`). +unsafe fn take_free_aside(s: &mut State, a: usize) -> Vec { + let Some(v) = s.aside.get_mut(&a) else { + return Vec::new(); + }; + let mut ready = Vec::new(); + let mut i = 0; + while i < v.len() { + let f = v[i]; + if s.backings.get(&f).is_some_and(|b| !b.already_reset && b.free()) { + ready.push(v.remove(i)); + } else { + i += 1; + } + } + ready +} + +unsafe fn restore_aside(s: &mut State, a: usize, f: usize, ok: bool) -> bool { + if ok { + if let Some(b) = s.backings.get_mut(&f) { + b.marks.clear(); + b.already_reset = true; + } + } + if s.types.contains_key(&a) { + s.aside.entry(a).or_default().push(f); + true + } else { + false + } +} + /// The title resets its allocator `alloc`. `None`: reset it as it is (nothing holds a /// recording on it, or this is off). `Some(hr)`: done here – the PC allocator in use was put /// aside with its recordings and another one took its place. +/// +/// Releases `STATE` before every `reset_pc_allocator` call so COM callbacks triggered while +/// releasing per-allocator resources (e.g. prelude `ID3D12CommandAllocator::Release` -> `forget`) +/// can never self-deadlock on `STATE`. pub unsafe fn title_reset(alloc: *mut c_void) -> Option { if !enabled() { return None; } - let mut g = STATE.lock().unwrap(); - let s = g.get_or_insert_with(State::default); - title_reset_in(s, alloc, |raw| super::real::reset_pc_allocator(raw)) + let a = alloc as usize; + enum Action { + CleanPrimary { aside: Vec }, + ResetCurrent { cur: usize, aside: Vec }, + SwapReuse { cur: usize, owner: usize, spare: usize, needs_reset: bool, aside: Vec }, + SwapNew { cur: usize, ty: i32, aside: Vec }, + } + let action = { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + let c = s.cur.get(&a).copied().unwrap_or(a); + if s.backings.get(&c).is_none_or(|b| b.free()) { + let aside = take_free_aside(s, a); + if c == a { + if let Some(b) = s.backings.get_mut(&c) { + b.marks.clear(); + b.already_reset = true; + } + Action::CleanPrimary { aside } + } else { + Action::ResetCurrent { cur: c, aside } + } + } else { + let ty = *s.types.get(&a)?; + let reuse = s + .aside + .get(&a) + .and_then(|v| v.iter().position(|f| s.backings.get(f).is_none_or(|b| b.free()))) + .map(|idx| (a, idx)) + // … also one another title allocator of the type put aside: a title that resets many + // allocators while lists hold their recordings would otherwise make a PC allocator for each, + // and keep it (only one made here: the title's own allocator goes with the title's Release) + .or_else(|| { + s.aside + .iter() + .filter(|(o, _)| **o != a && s.types.get(o) == Some(&ty)) + .find_map(|(o, v)| { + v.iter() + .position(|f| f != o && s.backings.get(f).is_none_or(|b| b.free())) + .map(|idx| (*o, idx)) + }) + }); + match reuse { + Some((owner, idx)) => { + let spare = s.aside.get_mut(&owner).unwrap().remove(idx); + let needs_reset = s.backings.get(&spare).is_none_or(|b| !b.already_reset); + let aside = take_free_aside(s, a); + Action::SwapReuse { cur: c, owner, spare, needs_reset, aside } + } + None => { + let aside = take_free_aside(s, a); + Action::SwapNew { cur: c, ty, aside } + } + } + } + }; + + let finish_aside = |aside: Vec| { + if aside.is_empty() { + return; + } + let mut results = Vec::with_capacity(aside.len()); + for f in aside { + let hr = super::real::reset_pc_allocator(f as *mut c_void); + results.push((f, hr >= 0)); + } + let mut orphans = Vec::new(); + { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + for (f, ok) in results { + if !restore_aside(s, a, f, ok) && f != a { + orphans.push(f); + } + } + } + } + for f in orphans { + drop(ID3D12CommandAllocator::from_raw(f as *mut c_void)); + } + }; + + match action { + Action::CleanPrimary { aside } => { + finish_aside(aside); + None + } + Action::ResetCurrent { cur, aside } => { + let hr = super::real::reset_pc_allocator(cur as *mut c_void); + if hr >= 0 { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + if let Some(b) = s.backings.get_mut(&cur) { + b.marks.clear(); + b.already_reset = true; + } + } + } + finish_aside(aside); + Some(hr) + } + Action::SwapReuse { cur, owner, spare, needs_reset, aside } => { + let hr = if needs_reset { super::real::reset_pc_allocator(spare as *mut c_void) } else { 0 }; + let mut orphan = None; + { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + if hr < 0 { + if !restore_aside(s, owner, spare, false) && spare != owner { + orphan = Some(spare); + } + } else { + if let Some(b) = s.backings.get_mut(&spare) { + b.marks.clear(); + b.already_reset = true; + } + if s.types.contains_key(&a) { + s.aside.entry(a).or_default().push(cur); + s.cur.insert(a, spare); + s.swaps += 1; + if s.swaps.is_power_of_two() { + let aside_n: usize = s.aside.values().map(|v| v.len()).sum(); + 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_n} put aside now)", + s.swaps, + s.made + ); + } + } else if spare != a { + orphan = Some(spare); + } + } + } + } + if let Some(f) = orphan { + drop(ID3D12CommandAllocator::from_raw(f as *mut c_void)); + } + finish_aside(aside); + Some(hr) + } + Action::SwapNew { cur, ty, aside } => { + let this = ID3D12CommandAllocator::from_raw_borrowed(&alloc)?; + let mut dev: Option = None; + this.GetDevice(&mut dev).ok()?; + let made: ID3D12CommandAllocator = dev?.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE(ty)).ok()?; + let raw = made.into_raw(); + if !super::real::is_adopted(raw) { + super::real::adopt(raw, super::real::Kind::CommandAllocator); + } + let mut orphan = None; + { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + if s.types.contains_key(&a) { + s.made += 1; + s.aside.entry(a).or_default().push(cur); + s.cur.insert(a, raw as usize); + s.swaps += 1; + if s.swaps.is_power_of_two() { + let aside_n: usize = s.aside.values().map(|v| v.len()).sum(); + 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_n} put aside now)", + s.swaps, + s.made + ); + } + } else { + orphan = Some(raw as usize); + } + } + } + if let Some(f) = orphan { + drop(ID3D12CommandAllocator::from_raw(f as *mut c_void)); + } + finish_aside(aside); + Some(0) + } + } +} + +/// Reset idle put-aside backings of title allocator `a` whose lists and GPU work have finished +/// (used by lock-free unit tests via `title_reset_in`). +#[cfg(test)] +unsafe fn reclaim_free_aside(s: &mut State, a: usize, reset: &mut impl FnMut(*mut c_void) -> HRESULT) { + let ready = take_free_aside(s, a); + for f in ready { + let ok = reset(f as *mut c_void) >= 0; + let _ = restore_aside(s, a, f, ok); + } } /// The allocator transition, with the PC Reset supplied so failure/retry needs no GPU in tests. +#[cfg(test)] unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMut(*mut c_void) -> HRESULT) -> Option { let a = alloc as usize; let c = s.cur.get(&a).copied().unwrap_or(a); if s.backings.get(&c).is_none_or(|b| b.free()) { - if let Some(b) = s.backings.get_mut(&c) { - b.marks.clear(); - } + #[cfg(test)] + reclaim_free_aside(s, a, &mut reset); if c == a { + if let Some(b) = s.backings.get_mut(&c) { + b.marks.clear(); + b.already_reset = true; + } return None; } - return Some(reset(c as *mut c_void)); + let hr = reset(c as *mut c_void); + if hr >= 0 { + if let Some(b) = s.backings.get_mut(&c) { + b.marks.clear(); + b.already_reset = true; + } + } + return Some(hr); } let ty = *s.types.get(&a)?; // one put aside earlier that nothing uses any more, or a new one - let reuse = s.aside.get(&a).and_then(|v| v.iter().copied().find(|f| s.backings.get(f).is_none_or(|b| b.free()))); + let reuse = s + .aside + .get(&a) + .and_then(|v| v.iter().copied().find(|f| s.backings.get(f).is_none_or(|b| b.free()))) + .map(|f| (a, f)); + // … also one another title allocator of the type put aside: a title that resets many + // allocators while lists hold their recordings would otherwise make a PC allocator for each, + // and keep it (only one made here: the title's own allocator goes with the title's Release) + let reuse = reuse.or_else(|| { + s.aside.iter().filter(|(o, _)| **o != a && s.types.get(o) == Some(&ty)).find_map(|(o, v)| { + v.iter().copied().find(|f| f != o && s.backings.get(f).is_none_or(|b| b.free())).map(|f| (*o, f)) + }) + }); let next = match reuse { - Some(f) => { - // Keep ownership until Reset succeeds so a failure can be retried. - let hr = reset(f as *mut c_void); - if hr < 0 { - return Some(hr); + Some((owner, f)) => { + let needs = s.backings.get(&f).is_none_or(|b| !b.already_reset); + if needs { + // Keep ownership until Reset succeeds so a failure can be retried. + let hr = reset(f as *mut c_void); + if hr < 0 { + return Some(hr); + } } - s.aside.get_mut(&a).unwrap().retain(|&x| x != f); + s.aside.get_mut(&owner).unwrap().retain(|&x| x != f); if let Some(b) = s.backings.get_mut(&f) { b.marks.clear(); + b.already_reset = true; } f } @@ -315,6 +756,8 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu }; s.aside.entry(a).or_default().push(c); s.cur.insert(a, next); + #[cfg(test)] + reclaim_free_aside(s, a, &mut reset); s.swaps += 1; if s.swaps.is_power_of_two() { let aside: usize = s.aside.values().map(|v| v.len()).sum(); @@ -370,6 +813,39 @@ mod tests { assert_eq!((s.made, s.swaps), (0, 1)); } + /// A title allocator that has no free one of its own takes one another of the type put aside, + /// but never another title allocator itself, nor one still in use, nor one of another type. + #[test] + fn a_free_spare_another_title_allocator_put_aside_is_taken() { + let (a, b, c, list) = (0x1000usize, 0x4000usize, 0x6000usize, 0x3000usize); + let (spare_b, busy_c, other_type) = (0x5000usize, 0x7000usize, 0x8000usize); + let mut s = State::default(); + s.types.insert(a, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.types.insert(b, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.types.insert(c, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.types.insert(0x9000, D3D12_COMMAND_LIST_TYPE_COMPUTE.0); + move_list(&mut s, list, a); + s.aside.insert(b, vec![b, spare_b]); + s.aside.insert(c, vec![busy_c]); + s.aside.insert(0x9000, vec![other_type]); + move_list(&mut s, 0x7100, busy_c); + let mut calls = Vec::new(); + let hr = unsafe { + title_reset_in(&mut s, a as *mut c_void, |raw| { + calls.push(raw as usize); + 0 + }) + }; + assert_eq!(hr, Some(0)); + assert_eq!(calls, vec![spare_b]); + assert_eq!(s.cur.get(&a), Some(&spare_b)); + assert_eq!(s.aside.get(&b), Some(&vec![b]), "the title's own allocator stays with it"); + assert_eq!(s.aside.get(&a), Some(&vec![a])); + assert_eq!((s.made, s.swaps), (0, 1)); + // (now a's: it goes with a, not with b) + assert!(!s.aside.values().flatten().any(|&f| f == spare_b)); + } + /// Final-release cleanup drops only the recording's hold: another live list and a pending /// GPU fence each still prevent reuse, then completion makes the backing reusable. #[test] @@ -550,4 +1026,110 @@ mod tests { assert_eq!(after_forget, 0, "a forgotten list has no previous submit"); } } + + #[test] + fn retired_segment_releases_backing_after_gpu_completes_while_preserving_in_flight() { + unsafe { + 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"); + }; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut ids = Box::new([0u8; 3]); + let alloc = ids.as_mut_ptr() as usize; + let seg = alloc + 1; + let queue = alloc + 2; + created_on(seg, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.backings.entry(alloc).or_default().marks.insert(queue, (fence.clone(), 1)); + let recording = s.recordings[&seg]; + s.last_submit.insert(seg, LastSubmit { queue, fence: fence.clone(), value: 1, recording }); + } + + // Retiring the segment into `title_list`'s spare pool detaches it from `users` + // while keeping GPU fence `marks` and `in_flight(seg)` intact until completion. + retire_recording(seg); + assert!(in_flight(seg), "retired segment must stay in_flight until GPU finishes"); + { + let g = STATE.lock().unwrap(); + let b = &g.as_ref().unwrap().backings[&alloc]; + assert!(b.users.is_empty(), "retired segment must no longer pin backing.users"); + assert!(!b.free(), "GPU mark must still hold the backing until signaled"); + } + + fence.Signal(1).unwrap(); + assert!(!in_flight(seg)); + { + let g = STATE.lock().unwrap(); + assert!(g.as_ref().unwrap().backings[&alloc].free(), "backing must become free once GPU completes"); + } + forget_list(seg); + forget(alloc); + } + } + + #[test] + fn clean_title_reset_reclaims_idle_aside_backings_once() { + let (alloc, spare1, spare2) = (0x7E57_1000usize, 0x7E57_2000usize, 0x7E57_3000usize); + let mut s = State::default(); + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.aside.insert(alloc, vec![spare1, spare2]); + s.backings.insert(spare1, Backing::default()); + s.backings.insert(spare2, Backing::default()); + let mut resets = Vec::new(); + + unsafe { + assert_eq!(title_reset_in(&mut s, alloc as *mut c_void, |r| { resets.push(r as usize); 0 }), None); + assert_eq!(resets, vec![spare1, spare2], "clean reset must reclaim all idle aside backings"); + + // A second clean reset must not redundantly reset already-reclaimed aside backings. + resets.clear(); + assert_eq!(title_reset_in(&mut s, alloc as *mut c_void, |r| { resets.push(r as usize); 0 }), None); + assert!(resets.is_empty(), "already-reset aside backings should not be reset again"); + } + } + + /// A list whose previous submit still runs is waited for before it is submitted again: until + /// that submit is done, or the limit; a list with nothing running is not waited for. + #[test] + fn a_resubmit_waits_for_the_previous_submit() { + unsafe { + 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"); + }; + // a fence the GPU has not reached stands for a submit still running + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut ids = Box::new([0u8; 2]); + let (alloc, list) = (ids.as_mut_ptr() as usize, ids.as_mut_ptr() as usize + 1); + created_on(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + let recording = s.recordings[&list]; + s.last_submit.insert(list, LastSubmit { queue: 0x10, fence: fence.clone(), value: 1, recording }); + } + let lists = [list as *mut c_void]; + // it never finishes: the limit ends the wait, and says so + let t = std::time::Instant::now(); + assert_eq!(wait_for_previous_submits_within(&lists, std::time::Duration::from_millis(30)), (1, 1)); + assert!(t.elapsed() >= std::time::Duration::from_millis(30)); + // no limit: no wait + assert_eq!(wait_for_previous_submits_within(&lists, std::time::Duration::ZERO), (0, 0)); + // it finishes meanwhile: the wait ends then, far before the limit + let signal = fence.clone(); + let done = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(20)); + signal.Signal(1).unwrap(); + }); + let t = std::time::Instant::now(); + assert_eq!(wait_for_previous_submits_within(&lists, std::time::Duration::from_secs(20)), (1, 0)); + assert!(t.elapsed() < std::time::Duration::from_secs(10), "the wait ends when the submit is done"); + done.join().unwrap(); + // nothing runs now: nothing to wait for + assert_eq!(wait_for_previous_submits_within(&lists, std::time::Duration::from_secs(20)), (0, 0)); + forget_list(list); + forget(alloc); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs new file mode 100644 index 0000000000..72e3ed6848 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -0,0 +1,1815 @@ +//! 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: 1.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 => !real::bvh_traversal_allowed(), + } +} + +/// 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); + 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); + 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]| -> 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(|| ID3D12PipelineState::from_raw(raw)) + }; + let reduce_pso = make_cs(&reduce_bc)?; + let fill_pso = make_cs(&fill_bc)?; + let fill_write_pso = make_cs(&fill_write_bc)?; + let fill_r9_pso = make_cs(&fill_r9_bc)?; + let reflect_pso = make_cs(&reflect_bc)?; + let air_pso = make_cs(&air_bc)?; + + 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()); + 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()); + 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::*; + + #[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); + } +} diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 3f31c48b43..dafb11a066 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -11,13 +11,165 @@ use std::collections::HashMap; use std::ffi::c_void; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, RwLock}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; use super::console_list::{self, Layout, Param}; +#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)] +struct AbiBound { + /// PC root signature currently bound on this list for this stage (0 = unknown/clobbered). + rs: usize, + /// Root UAV GPU VAs currently bound at slots 0..6 for `rs`. + uavs: [u64; 6], +} + +/// Diff `target_rs` and `target_uavs` against `bound`, updating `bound` and returning +/// `(need_set_rs, uav_mask)` where bit `k` of `uav_mask` means slot `k` must be bound. +/// Changing the root signature invalidates all 6 root UAV slots per D3D12 semantics. +fn diff_abi_bindings(bound: &mut AbiBound, target_rs: usize, target_uavs: [u64; 6]) -> (bool, u8) { + if bound.rs != target_rs { + bound.rs = target_rs; + bound.uavs = target_uavs; + return (true, 0b0011_1111); + } + let mut mask = 0u8; + for k in 0..6 { + if bound.uavs[k] != target_uavs[k] { + bound.uavs[k] = target_uavs[k]; + mask |= 1u8 << k; + } + } + (false, mask) +} + +unsafe fn emit_abi_bindings(list: &ID3D12GraphicsCommandList, gfx: bool, rs: &ID3D12RootSignature, set_rs: bool, uav_mask: u8, uavs: [u64; 6]) { + if gfx { + if set_rs { + list.SetGraphicsRootSignature(rs); + } + for (k, &v) in uavs.iter().enumerate() { + if uav_mask & (1u8 << k) != 0 { + list.SetGraphicsRootUnorderedAccessView(k as u32, v); + } + } + } else { + if set_rs { + list.SetComputeRootSignature(rs); + } + for (k, &v) in uavs.iter().enumerate() { + if uav_mask & (1u8 << k) != 0 { + list.SetComputeRootUnorderedAccessView(k as u32, v); + } + } + } +} + +fn uma_va_in(u: &crate::gpu::uma::Uma, windows: &[u64], p: usize) -> Option { + let k = u.window_of(p)?; + let base = *windows.get(k)?; + (base != 0).then(|| base + (p - u.window(k).0) as u64) +} + +#[derive(Default)] +struct ScratchSlot { + buf: Option<(ID3D12Resource, u64, usize)>, + used: u64, + /// D3D12 state on this list (`COMMON` initially, kept in `INDIRECT_ARGUMENT` between uses; + /// buffers decay to `COMMON` after `ExecuteCommandLists`). + state: D3D12_RESOURCE_STATES, +} + +#[derive(Default)] +struct PreludeScratchSlot { + buf: Option<(ID3D12Resource, u64, usize)>, + used: u64, + buf_idx: usize, +} + +#[derive(Clone, Copy, Debug)] +struct PreludeGuardJob { + buf_idx: usize, + dst_off: u32, + src_win: u32, + src_off: u32, + most: u32, + lim_win: u32, + lim_off: u32, +} + +#[derive(Clone, Copy, Debug)] +struct PreludeScaleJob { + buf_idx: usize, + dst_off: u32, + count: u32, + stride: u32, + mesh_offset: u32, + split: u32, + cap: u32, + src_win: u32, + src_off: u32, + has_cnt: u32, + cnt_win: u32, + cnt_off: u32, +} + +#[derive(Clone, Copy, Debug)] +struct PreludeDrawJob { + buf_idx: usize, + dst_off: u32, + count: u32, + stride: u32, + draw_offset: u32, + src_win: u32, + src_off: u32, +} + +/// Cached free-threaded `ID3D12Device` wrapper for `State::vram_io_dev`. +#[derive(Clone)] +struct CachedIoDev(ID3D12Device); + +unsafe impl Send for CachedIoDev {} + +/// Cached resolved ABI metadata for the currently bound translated pipeline on a command list, +/// avoiding repeated global `pso_async`/`real` map lookups across consecutive draws/dispatches +/// using the same pipeline. +#[derive(Clone, Copy, Debug)] +struct CachedPsoAbi { + query_pso: usize, + real_pso: usize, + rs_raw: usize, + user_sgprs: Option, + is_gfx: bool, +} + +type PreludeEntry = (ID3D12CommandAllocator, ID3D12GraphicsCommandList, usize, i32); + +/// Paired persistently-mapped `UPLOAD` slab and L1 VRAM `DEFAULT` (`ALLOW_UNORDERED_ACCESS`) slab +/// for a recording's `io` (`u0`) user-SGPR blocks. CPU writes `io` bytes into `upload` during +/// command-list recording and `prelude_list_for` copies `0..used` into `vram` once before the +/// segment executes, avoiding PCIe/system-RAM stalls on every shader's first `u0` load. +struct IoBlock { + vram: ID3D12Resource, + upload: ID3D12Resource, + mapped: usize, + vram_va: u64, + cap: u64, + used: u64, + dev_key: usize, +} + +impl Drop for IoBlock { + fn drop(&mut self) { + if self.mapped != 0 { + unsafe { self.upload.Unmap(0, None) }; + self.mapped = 0; + } + } +} + #[derive(Default)] struct State { layout: Option>, @@ -28,15 +180,435 @@ struct State { /// the title's graphics root signature (a PC object), bound before a draw with an /// untranslated pipeline – created with it – since SetGraphicsRootSignature binds nothing rs_gfx: usize, + /// the title's compute root signature (a PC object), preserved for internal-pass restoration + rs_cs: usize, pso: usize, + /// 32-bit addresses of the view heap and the sampler heap set (0: none) + heaps: [u32; 2], allocator: usize, /// unified memory of this recording (io, argument tables) uma: Vec, /// where the next draw's io and argument table go (blocks in `uma`) arena: crate::gpu::uma::Arena, + res_buf: Option<(ID3D12Resource, u64, usize)>, + res_retired: Vec<(ID3D12Resource, u64, usize)>, + /// the recording used the shared record buffer (`shared_record_buffer`) + shared_records: bool, + /// rewritten indirect arguments (`scratch_args`): two ping-pong scratch slots so consecutive + /// guarded/two-pass ExecuteIndirects avoid false WAR transition stalls on the same buffer, + /// plus total bytes of blocks this recording took (`scratch_taken`). + scratch: [ScratchSlot; 2], + scratch_next: usize, + scratch_taken: u64, + /// Hoisted indirect-argument clamps recorded into a single batched prelude command list + /// submitted right before this segment (`title_list::push_segments` / `reclaim_for_kickoff`). + /// Disabled for the remainder of the segment once any GPU buffer write or cross-queue wait + /// is recorded (`prelude_blocked`). + prelude_blocked: bool, + prelude_scratch: PreludeScratchSlot, + prelude_bufs: Vec, + prelude_guards: Vec, + prelude_scales: Vec, + prelude_draws: Vec, + prelude_owned: Option, + prelude_built: Option, + /// CUSTOM write-back L0 blocks backing prelude job tables when UMA is full (`JobBlock`), and + /// the bytes used of the last one + prelude_job_bufs: Vec, + prelude_job_used: u64, + /// true after an `INDIRECT_ARGUMENT` transition has ordered prior writes on this list and + /// no compute/mesh dispatch has run since (skips redundant `fresh_indirect_arguments` barriers + /// across runs of consecutive indirect graphics draws). + arg_order_clean: bool, + /// cached UMA window GPU VAs for this recording (avoids locking `UMA_BUFFER` every draw) + uma_windows: Option>, + /// reusable zeroed 256-byte `u1` (`res`) slot in this recording's UMA arena + dummy_res_va: u64, + /// reusable 16-byte UMA root-argument table slot for draws/dispatches whose arguments fit + /// completely inline in user SGPRs (`tail.is_empty()`) + dummy_table_p: usize, + /// true once `list_x::ensure_view_heap` confirmed all required shared heaps are bound on this + /// list (invalidated on `Reset`, `ClearState`, split, `SetDescriptorHeaps`, or internal pass) + heaps_ensured: bool, + /// cached resolved ABI metadata for the active translated PSO on this list + pso_abi_cache: Option, + /// lazily cached `vram_io_device(this)` result for this recording + vram_io_dev: Option>, + /// tracked PC ABI root bindings for state-diffing + pc_abi_gfx: AbiBound, + pc_abi_cs: AbiBound, + /// monotonic generations incremented when root args, layout, or descriptor heaps change + args_gen_gfx: u64, + args_gen_cs: u64, + /// cached `io` GPU VAs keyed on `args_gen_*` (and compute `user_sgprs`) + io_cache_gfx: Option<(u64, u64)>, + io_cache_cs: Option<(u64, Option, u64)>, + io_cache_tp_cs: Option<(u64, u64)>, + io_cache_tp_ms: Option<(u64, u64)>, + /// Active inline 256-slot indirect-dispatch guard batch: one inline `PRELUDE_GUARD_*` + /// `Dispatch(4, 1, 1)` + barrier pair already emitted on this list, with subsequent + /// consecutive single indirect dispatches (up to 256, invalidated on any GPU write/barrier) + /// appending their 32-byte clamp jobs into its coherent UMA job table with zero extra barriers. + inline_guard: Option, + /// Per-list 16-entry MRU cache of resolved outside-UMA root descriptor VAs (`raw -> resolved`) + /// so repeatedly binding the same frame/pass/material CBV skips global `resolve_uma_va` and + /// `sparse::gpu_view` lock lookups. + root_va_cache: [(u64, u64); 16], + root_va_next: usize, + /// L1 VRAM `io` (`u0`) slabs populated during this recording and copied in `prelude_list_for` + io_blocks: Vec, +} + +/// Active inline 256-slot indirect-dispatch guard batch recorded directly on a command list. +struct InlineGuardBatch { + /// Host pointer to `[count, 0, 0, 0]` + 256 × 32-byte `PreludeGuardJob` records in coherent UMA. + jobs_cpu: usize, + /// Committed scratch buffer holding 256 × 256-byte guarded argument outputs (`GUARDED_ARGS_STATE`). + dst: ID3D12Resource, + dst_base_off: u64, + count: u32, +} + +const INLINE_GUARD_BATCH_MAX: u32 = 256; +const INLINE_GUARD_JOBS_BYTES: usize = 16 + INLINE_GUARD_BATCH_MAX as usize * 32; +const INLINE_GUARD_DST_BYTES: u64 = INLINE_GUARD_BATCH_MAX as u64 * 256; + +fn parse_inline_guard_batch(val: Option<&str>) -> bool { + val.is_some_and(|v| v.trim() == "1") +} + +/// Opt-in inline 256-slot guard batching (`XCL_INLINE_GUARD_BATCH=1`). Defaults off because +/// `execute_indirect` clears `s.inline_guard` after each dispatch (so batching never exceeds 1) +/// while allocating 64 KiB scratch + 8 KiB coherent UMA per dispatch and triggering page faults on +/// AMD RDNA4; the default `guard_indirect_heap_pipeline` uses 32-bit root constants and 256 B scratch. +fn inline_guard_batch_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| parse_inline_guard_batch(std::env::var("XCL_INLINE_GUARD_BATCH").ok().as_deref())) +} + +/// 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; +/// Default per-recording cap on rewritten indirect-argument scratch (MiB). Overridable via +/// `XCL_INDIRECT_SCRATCH_MB` (clamped 4..=128 MiB) so dense open-world indirect draw lists do +/// not exhaust scratch mid-recording and drop trailing draws. +const SCRATCH_CAP: u64 = 32 << 20; + +fn scratch_cap() -> u64 { + static CAP: std::sync::OnceLock = std::sync::OnceLock::new(); + *CAP.get_or_init(|| { + std::env::var("XCL_INDIRECT_SCRATCH_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map(|mb| mb.clamp(4, 128) << 20) + .unwrap_or(SCRATCH_CAP) + }) +} +/// Most bytes of buffers kept for reuse (`FREE_RES`) +const FREE_RES_CAP: u64 = 256 << 20; +/// Size of one pooled VRAM `io` (`u0`) slab (64 KiB = 256 distinct 256-byte `io` slots). +const IO_BLOCK_BYTES: u64 = 64 << 10; +/// Most bytes of VRAM `io` slabs kept for reuse (`FREE_IO`). +const FREE_IO_CAP: u64 = 64 << 20; +/// Most recycled prelude (allocator, list) pairs kept for reuse (`FREE_PRELUDE`) +const FREE_PRELUDE_CAP: usize = 256; + +static ALLOC_RES: Mutex>>> = Mutex::new(None); +static FREE_RES: Mutex> = Mutex::new(Vec::new()); +static ALLOC_IO: Mutex>>> = Mutex::new(None); +static FREE_IO: Mutex> = Mutex::new(Vec::new()); +static ALLOC_PRELUDE: Mutex>>> = Mutex::new(None); +static FREE_PRELUDE: Mutex> = Mutex::new(Vec::new()); +static ALLOC_PRELUDE_JOBS: Mutex>>> = Mutex::new(None); + +/// A block of CPU-visible GPU memory (CUSTOM write-back, L0) for prelude job tables when the +/// title's unified memory is full, mapped for good. A retail title fills its coherent window, +/// so every prelude took this path: one committed buffer of a few hundred bytes each (64 KiB of +/// commit and ~0.5 ms each), 1 250 a second – a second of the title's threads in every two, and +/// 2.5 GB of commit a minute until the system's memory ran out and the device was lost in a +/// tile mapping it could not page for. Now tables are cut from 1 MiB blocks, and a block goes +/// back to `FREE_JOB_BLOCKS` when the allocator its lists were recorded with is reset. +pub(super) struct JobBlock { + buf: ID3D12Resource, + cpu: usize, + va: u64, + dev: usize, +} +// (the mapping stays valid while `buf` lives; it is written by the recording thread only) +unsafe impl Send for JobBlock {} + +const JOB_BLOCK_BYTES: u64 = 1 << 20; +/// blocks kept for reuse at most (64 MiB) +const JOB_BLOCKS_KEPT: usize = 64; +static FREE_JOB_BLOCKS: Mutex> = Mutex::new(Vec::new()); + +/// A job block of `dev`: a kept one, or a new one. +unsafe fn job_block(dev: &ID3D12Device) -> Result { + let key = dev.as_raw() as usize; + { + let mut free = FREE_JOB_BLOCKS.lock().unwrap(); + if let Some(i) = free.iter().position(|b| b.dev == key) { + return Ok(free.swap_remove(i)); + } + } + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + CreationNodeMask: 1, + VisibleNodeMask: 1, + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: JOB_BLOCK_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, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buf: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut buf) + .map_err(|e| format!("prelude job block: {e}"))?; + let buf = buf.ok_or("prelude job block was null")?; + let _ = buf.SetName(windows::core::w!("xcl prelude job block (UMA full)")); + let mut mapped = std::ptr::null_mut(); + let empty = D3D12_RANGE { Begin: 0, End: 0 }; + buf.Map(0, Some(&empty), Some(&mut mapped)).map_err(|e| format!("prelude job block map: {e}"))?; + let va = buf.GetGPUVirtualAddress(); + if va == 0 || mapped.is_null() { + return Err("prelude job block has no address".into()); + } + static MADE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = MADE.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: prelude job tables outside unified memory (it is full): {n} blocks of 1 MiB made"); + } + Ok(JobBlock { buf, cpu: mapped as usize, va, dev: key }) +} + +/// `blocks` back for reuse (their allocator was reset: the GPU is done with them); the rest are +/// dropped outside the lock. +fn keep_job_blocks(blocks: Vec) { + recycle_into_pool(&FREE_JOB_BLOCKS, blocks, |pool, _| pool.len() < JOB_BLOCKS_KEPT); +} + +fn hold_res_until_reset(allocator: usize, mut bufs: Vec<(ID3D12Resource, u64, usize)>) { + if bufs.is_empty() || allocator == 0 { + return; + } + ALLOC_RES.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().append(&mut bufs); +} + +fn hold_io_until_reset(allocator: usize, mut blocks: Vec) { + if blocks.is_empty() || allocator == 0 { + return; + } + ALLOC_IO.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().append(&mut blocks); +} + +fn hold_prelude_until_reset(allocator: usize, entry: Option) { + let Some(entry) = entry else { return }; + if allocator == 0 { + return; + } + ALLOC_PRELUDE.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().push(entry); +} + +fn hold_prelude_jobs_until_reset(allocator: usize, mut bufs: Vec) { + if bufs.is_empty() { + return; + } + if allocator == 0 { + // (no allocator to wait for: not reused, dropped as before) + drop(bufs); + return; + } + ALLOC_PRELUDE_JOBS.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().append(&mut bufs); +} + +/// Return `items` into `free` whenever `keep(&pool, &item)` holds, dropping overflow items +/// *after* releasing `free` so COM `Release` hooks that re-enter `release_allocator_res` +/// cannot self-deadlock on the pool mutex. +fn recycle_into_pool(free: &Mutex>, items: Vec, mut keep: impl FnMut(&[T], &T) -> bool) { + let mut overflow = Vec::new(); + { + let mut pool = free.lock().unwrap(); + for item in items { + if keep(&pool, &item) { + pool.push(item); + } else { + overflow.push(item); + } + } + } + drop(overflow); +} + +pub(super) fn release_allocator_res(allocator: usize) { + // Bind each removed entry before locking the free pool (avoiding nested `ALLOC_* -> FREE_*` + // lock holding from `if let` temporary lifetimes) and drop overflow COM objects outside both + // locks so re-entrant `real::alloc_release` -> `console_list::allocator_reset` -> + // `release_allocator_res` cannot self-deadlock. + let bufs = ALLOC_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)); + if let Some(bufs) = bufs { + recycle_into_pool(&FREE_RES, bufs, |pool, b| { + let held: u64 = pool.iter().map(|f| f.1).sum(); + pool_keeps(pool.len(), held, b.1) + }); + } + let blocks = ALLOC_IO.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)); + if let Some(mut blocks) = blocks { + for b in &mut blocks { + b.used = 0; + } + recycle_into_pool(&FREE_IO, blocks, |pool, b| { + let held: u64 = pool.iter().map(|f| f.cap).sum(); + io_pool_keeps(held, b.cap) + }); + } + let entries = ALLOC_PRELUDE.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)); + if let Some(entries) = entries { + recycle_into_pool(&FREE_PRELUDE, entries, |pool, _| pool.len() < FREE_PRELUDE_CAP); + } + // back to the pool, the overflow dropped outside the locks (COM Release hooks re-enter here) + let job_bufs = ALLOC_PRELUDE_JOBS.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)); + if let Some(b) = job_bufs { + keep_job_blocks(b); + } +} + +/// Whether `FREE_RES`, holding `count` buffers of `held` bytes, keeps one of `bytes` more. +fn pool_keeps(count: usize, held: u64, bytes: u64) -> bool { + count < 256 && held + bytes <= FREE_RES_CAP +} + +/// Whether `FREE_IO`, holding `held` bytes of VRAM `io` slabs, keeps one of `bytes` more. +fn io_pool_keeps(held: u64, bytes: u64) -> bool { + held.saturating_add(bytes) <= FREE_IO_CAP +} + +/// `XCL_VRAM_IO=0`: keep `io` (`u0`) user-SGPR buffers in UMA system RAM instead of L1 VRAM. +fn vram_io_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_VRAM_IO").map_or(true, |v| v.trim() != "0")) +} + +/// Return the device if `this` can place `io` (`u0`) slots in L1 VRAM (wrapped DIRECT/COMPUTE +/// command list whose prelude list runs before it on submit). +unsafe fn vram_io_device(this: *mut c_void) -> Option { + if !vram_io_on() + || super::title_list::wrapper_of(this).is_none() + || !matches!( + super::list_x::tracked_list_type(this), + Some(D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE) + ) + { + return None; + } + super::real::list_device(this) +} + +unsafe fn create_io_block(dev: &ID3D12Device, cap: u64) -> Option { + let vram_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: cap, + 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 vram: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, CreationNodeMask: 1, VisibleNodeMask: 1, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &vram_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + None, + &mut vram, + ) + .ok()?; + let vram = vram?; + let _ = vram.SetName(windows::core::w!("xcl io vram")); + let vram_va = vram.GetGPUVirtualAddress(); + if vram_va == 0 { + return None; + } + let up_desc = D3D12_RESOURCE_DESC { + Flags: D3D12_RESOURCE_FLAG_NONE, + ..vram_desc + }; + let mut upload: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, CreationNodeMask: 1, VisibleNodeMask: 1, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &up_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut upload, + ) + .ok()?; + let upload = upload?; + let _ = upload.SetName(windows::core::w!("xcl io upload")); + let mut mapped = std::ptr::null_mut(); + let empty_read = D3D12_RANGE { Begin: 0, End: 0 }; + upload.Map(0, Some(&empty_read), Some(&mut mapped)).ok()?; + if mapped.is_null() { + return None; + } + Some(IoBlock { + vram, + upload, + mapped: mapped as usize, + vram_va, + cap, + used: 0, + dev_key: dev.as_raw() as usize, + }) +} + +/// Write `bytes` into a 256-byte-aligned slot of `io_blocks` and return its L1 VRAM GPU VA. +unsafe fn alloc_vram_io_in(io_blocks: &mut Vec, allocator: usize, prelude_built: bool, dev: &ID3D12Device, bytes: &[u8]) -> Option { + if allocator == 0 || prelude_built { + return None; + } + let take = (bytes.len().max(16) as u64).next_multiple_of(256); + if let Some(b) = io_blocks.last_mut().filter(|b| b.used + take <= b.cap) { + let off = b.used; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), (b.mapped as *mut u8).add(off as usize), bytes.len()); + b.used += take; + return Some(b.vram_va + off); + } + let dev_key = dev.as_raw() as usize; + let mut block = { + let mut free = FREE_IO.lock().unwrap(); + free.iter().position(|b| b.dev_key == dev_key && b.cap >= take).map(|i| free.swap_remove(i)) + }; + if block.is_none() { + block = create_io_block(dev, take.max(IO_BLOCK_BYTES)); + } + let mut b = block?; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), b.mapped as *mut u8, bytes.len()); + b.used = take; + let va = b.vram_va; + io_blocks.push(b); + Some(va) } -static STATES: Mutex>> = Mutex::new(None); +/// 64-way sharded per-list bind state map so parallel recording threads do not contend on a +/// single global mutex across every root-argument update, draw, and dispatch. +const STATE_SHARDS: usize = 64; +static STATES: [Mutex>>; STATE_SHARDS] = [const { Mutex::new(None) }; STATE_SHARDS]; + +#[inline] +fn state_shard(list: usize) -> usize { + ((list >> 6) ^ (list >> 16)) & (STATE_SHARDS - 1) +} /// draws / dispatches of console code: with a translated pipeline, skipped, with a PC one static COUNTS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; @@ -66,15 +638,56 @@ fn count(k: usize) { } fn with(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { - f(STATES.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default()) + let key = list as usize; + f(STATES[state_shard(key)].lock().unwrap().get_or_insert_with(HashMap::new).entry(key).or_default()) +} + +/// Note that the active recording segment issued a GPU buffer write or cross-queue fence wait: +/// subsequent indirect argument clamps must execute inline instead of hoisting into the prelude, +/// any open inline indirect-guard batch is closed so later dispatches observe the new writes, +/// and indirect argument ordering is no longer clean. +pub(super) fn note_gpu_write(list: *mut c_void) { + with(list, |s| { + s.prelude_blocked = true; + s.inline_guard = None; + s.arg_order_clean = false; + }); +} + +/// Close any open inline indirect-guard batch on `list` (called on `ResourceBarrier` / direct +/// `Dispatch` so subsequent indirect dispatches see post-barrier argument bytes). +pub(super) fn invalidate_inline_guard(list: *mut c_void) { + with(list, |s| { + s.inline_guard = None; + }); +} + +/// Allow indirect-argument prelude hoisting on a freshly split continuation segment whose +/// predecessor finished on the same queue with no cross-queue head fence wait. +pub(super) fn unblock_prelude(list: *mut c_void) { + with(list, |s| { + s.prelude_blocked = false; + }); +} + +/// Resolve the PC backing allocator that actually owns `list`'s recording (`alloc_pool` can swap +/// a title allocator to a new PC allocator while recordings on the old backing are still in flight, +/// so UMA arena blocks and scratch buffers must stay pinned to the backing allocator until +/// `reset_pc_allocator` genuinely resets it). +fn backing_allocator(list: *mut c_void, allocator: usize) -> usize { + if allocator == 0 || !super::alloc_pool::enabled() { + return allocator; + } + super::alloc_pool::recording_backing(list as usize).unwrap_or_else(|| super::alloc_pool::current(allocator)) } /// The list was created or reset onto `allocator` with `initial_pso`: the previous /// recording's memory is the previous allocator's until that one is reset, and pipeline /// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { - let (old, blocks) = with(list, |s| { - let old = std::mem::replace(&mut s.allocator, allocator); + let backing = backing_allocator(list, allocator); + let (old, blocks, res_bufs, io_blocks, prelude, job_bufs) = with(list, |s| { + let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); s.pso = initial_pso; s.layout = None; @@ -82,9 +695,53 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; - (old, std::mem::take(&mut s.uma)) + s.heaps = [0; 2]; + s.shared_records = false; + // (the scratch blocks are in `res_retired` already) + s.scratch = Default::default(); + s.scratch_next = 0; + s.scratch_taken = 0; + s.prelude_blocked = false; + s.prelude_scratch = Default::default(); + s.prelude_bufs.clear(); + s.prelude_guards.clear(); + s.prelude_scales.clear(); + s.prelude_draws.clear(); + let prelude = s.prelude_owned.take(); + s.prelude_built = None; + let job_bufs = std::mem::take(&mut s.prelude_job_bufs); + s.prelude_job_used = 0; + s.inline_guard = None; + s.root_va_cache = [(0, 0); 16]; + s.root_va_next = 0; + s.arg_order_clean = false; + s.uma_windows = None; + s.dummy_res_va = 0; + s.dummy_table_p = 0; + s.heaps_ensured = false; + s.pso_abi_cache = None; + s.vram_io_dev = None; + s.pc_abi_gfx = AbiBound::default(); + s.pc_abi_cs = AbiBound::default(); + s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); + s.args_gen_cs = s.args_gen_cs.wrapping_add(1); + s.io_cache_gfx = None; + s.io_cache_cs = None; + s.io_cache_tp_cs = None; + s.io_cache_tp_ms = None; + let mut res_bufs = std::mem::take(&mut s.res_retired); + if let Some(b) = s.res_buf.take() { + res_bufs.push(b); + } + let io_blocks = std::mem::take(&mut s.io_blocks); + s.rs_cs = 0; + (old, std::mem::take(&mut s.uma), res_bufs, io_blocks, prelude, job_bufs) }); console_list::hold_until_reset(old, blocks); + hold_res_until_reset(old, res_bufs); + hold_io_until_reset(old, io_blocks); + hold_prelude_until_reset(old, prelude); + hold_prelude_jobs_until_reset(old, job_bufs); } /// `ClearState(pso)`: resets pipeline and root-argument state back to creation defaults @@ -97,28 +754,137 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; + s.heaps = [0; 2]; + s.rs_cs = 0; + s.heaps_ensured = false; + s.pso_abi_cache = None; + s.pc_abi_gfx = AbiBound::default(); + s.pc_abi_cs = AbiBound::default(); + s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); + s.args_gen_cs = s.args_gen_cs.wrapping_add(1); + s.io_cache_gfx = None; + s.io_cache_cs = None; + s.io_cache_tp_cs = None; + s.io_cache_tp_ms = None; + }); +} + +/// Update `list`'s tracked backing allocator after `alloc_pool::reset_list` rotates `list` onto a +/// fresh PC command allocator (e.g., `KickoffX` or `record_deferred`), retiring any prior +/// recording buffers on the old allocator first. +pub(super) fn rebind_allocator(list: *mut c_void, allocator: usize) { + let backing = backing_allocator(list, allocator); + let (old, blocks, res_bufs, io_blocks, prelude, job_bufs) = with(list, |s| { + s.heaps_ensured = false; + s.pc_abi_gfx = AbiBound::default(); + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = false; + s.inline_guard = None; + s.prelude_scratch = Default::default(); + s.prelude_bufs.clear(); + s.prelude_guards.clear(); + s.prelude_scales.clear(); + s.prelude_draws.clear(); + let prelude = s.prelude_owned.take(); + s.prelude_built = None; + let job_bufs = std::mem::take(&mut s.prelude_job_bufs); + s.prelude_job_used = 0; + if s.allocator == backing { + for sl in &mut s.scratch { + sl.state = D3D12_RESOURCE_STATE_COMMON; + } + return (backing, Vec::new(), Vec::new(), Vec::new(), prelude, job_bufs); + } + let old = std::mem::replace(&mut s.allocator, backing); + s.arena = Default::default(); + s.scratch = Default::default(); + s.scratch_next = 0; + s.scratch_taken = 0; + s.dummy_res_va = 0; + s.dummy_table_p = 0; + s.io_cache_gfx = None; + s.io_cache_cs = None; + s.io_cache_tp_cs = None; + s.io_cache_tp_ms = None; + let mut res_bufs = std::mem::take(&mut s.res_retired); + if let Some(b) = s.res_buf.take() { + res_bufs.push(b); + } + let io_blocks = std::mem::take(&mut s.io_blocks); + (old, std::mem::take(&mut s.uma), res_bufs, io_blocks, prelude, job_bufs) }); + console_list::hold_until_reset(old, blocks); + hold_res_until_reset(old, res_bufs); + hold_io_until_reset(old, io_blocks); + hold_prelude_until_reset(old, prelude); + hold_prelude_jobs_until_reset(old, job_bufs); } /// Carry bound pipeline and root-signature / root-argument state from `from` to `to` across a /// deferred mid-list split (`to` records into `allocator` with its own fresh UMA arena while /// `from` retains its previously allocated blocks until `allocator` resets). pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: usize) { - let (layout, args, layout_gfx, args_gfx, rs_gfx, pso) = with(from, |s| { - (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso) + let backing = backing_allocator(to, allocator); + let (layout, args, layout_gfx, args_gfx, rs_gfx, rs_cs, pso, heaps) = with(from, |s| { + (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.rs_cs, s.pso, s.heaps) }); - let (old, blocks) = with(to, |s| { - let old = std::mem::replace(&mut s.allocator, allocator); + let (old, blocks, res_bufs, io_blocks, prelude, job_bufs) = with(to, |s| { + let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); s.layout = layout; s.args = args; s.layout_gfx = layout_gfx; s.args_gfx = args_gfx; s.rs_gfx = rs_gfx; + s.rs_cs = rs_cs; s.pso = pso; - (old, std::mem::take(&mut s.uma)) + s.heaps = heaps; + s.scratch = Default::default(); + s.scratch_next = 0; + s.scratch_taken = 0; + // A continuation segment (`from != to`) begins after a mid-list Wait32/64 split, so never + // hoist clamps ahead of that segment's head fence wait. A KickoffX non-split (`from == to`) + // starts a fresh post-kickoff segment and may hoist again. + s.prelude_blocked = from != to; + s.prelude_scratch = Default::default(); + s.prelude_bufs.clear(); + s.prelude_guards.clear(); + s.prelude_scales.clear(); + s.prelude_draws.clear(); + let prelude = s.prelude_owned.take(); + s.prelude_built = None; + let job_bufs = std::mem::take(&mut s.prelude_job_bufs); + s.prelude_job_used = 0; + s.inline_guard = None; + s.root_va_cache = [(0, 0); 16]; + s.root_va_next = 0; + s.arg_order_clean = false; + s.uma_windows = None; + s.dummy_res_va = 0; + s.dummy_table_p = 0; + s.heaps_ensured = false; + s.pso_abi_cache = None; + s.vram_io_dev = None; + s.pc_abi_gfx = AbiBound::default(); + s.pc_abi_cs = AbiBound::default(); + s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); + s.args_gen_cs = s.args_gen_cs.wrapping_add(1); + s.io_cache_gfx = None; + s.io_cache_cs = None; + s.io_cache_tp_cs = None; + s.io_cache_tp_ms = None; + let mut res_bufs = std::mem::take(&mut s.res_retired); + if let Some(b) = s.res_buf.take() { + res_bufs.push(b); + } + let io_blocks = std::mem::take(&mut s.io_blocks); + (old, std::mem::take(&mut s.uma), res_bufs, io_blocks, prelude, job_bufs) }); console_list::hold_until_reset(old, blocks); + hold_res_until_reset(old, res_bufs); + hold_io_until_reset(old, io_blocks); + hold_prelude_until_reset(old, prelude); + hold_prelude_jobs_until_reset(old, job_bufs); } /// A submit is about to wait for the pipeline `this` has bound. @@ -126,6 +892,12 @@ pub(super) fn want_bound(this: *mut c_void) { super::pso_async::want(with(this, |s| s.pso)); } +/// A submit records a put-off call of `this`: it waits until the pipeline `this` has bound is +/// built (`pso_async::wait_for_submit`). +pub(super) fn wait_for_bound(this: *mut c_void) { + super::pso_async::wait_for_submit(with(this, |s| s.pso)); +} + /// A put-off dispatch that could not be recorded. pub(super) fn dispatch_dropped() { count(DISPATCHES_SKIPPED); @@ -139,8 +911,17 @@ pub(super) fn pass_arena(from: *mut c_void, to: *mut c_void) { /// The list is gone. pub(super) fn forget(list: *mut c_void) { - if let Some(s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) { + let key = list as usize; + if let Some(mut s) = STATES[state_shard(key)].lock().unwrap().as_mut().and_then(|m| m.remove(&key)) { console_list::hold_until_reset(s.allocator, s.uma); + if let Some(b) = s.res_buf.take() { + s.res_retired.push(b); + } + hold_res_until_reset(s.allocator, s.res_retired); + hold_io_until_reset(s.allocator, s.io_blocks); + hold_prelude_until_reset(s.allocator, s.prelude_owned.take()); + s.prelude_job_used = 0; + hold_prelude_jobs_until_reset(s.allocator, std::mem::take(&mut s.prelude_job_bufs)); } } @@ -149,6 +930,7 @@ pub(crate) fn seed_reset_state_for_test(list: *mut c_void, allocator: usize, pso with(list, |s| { s.allocator = allocator; s.pso = pso; + s.pso_abi_cache = None; s.layout = Some(Arc::new(Layout::default())); s.args = vec![1, 2, 3, 4]; s.layout_gfx = Some(Arc::new(Layout::default())); @@ -164,7 +946,29 @@ pub(crate) fn reset_state_for_test(list: *mut c_void) -> (usize, usize, Vec, #[cfg(test)] pub(crate) fn remove_state_for_test(list: *mut c_void) { - STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))); + let key = list as usize; + STATES[state_shard(key)].lock().unwrap().as_mut().and_then(|m| m.remove(&key)); +} + +/// SetDescriptorHeaps: the console addresses of `heaps`, for shaders that index them themselves +/// (`Layout::heaps`). +pub(super) fn set_heaps(list: *mut c_void, heaps: &[usize]) { + let mut bases = [0u32; 2]; + for (sampler, base) in heaps.iter().filter_map(|&h| super::console_heap::base(h)) { + bases[sampler as usize] = base; + } + with(list, |s| { + s.heaps_ensured = false; + if s.heaps != bases { + s.heaps = bases; + s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); + s.args_gen_cs = s.args_gen_cs.wrapping_add(1); + s.io_cache_gfx = None; + s.io_cache_cs = None; + s.io_cache_tp_cs = None; + s.io_cache_tp_ms = None; + } + }); } /// bytes of parameter `i` at constant `offset` (of the compute or the graphics arguments) @@ -178,7 +982,18 @@ fn put_in(list: *mut c_void, gfx: bool, i: u32, offset: u32, bytes: &[u8]) { return; }; if let Some(t) = args.get_mut(at..at + bytes.len()) { - t.copy_from_slice(bytes); + if t != bytes { + t.copy_from_slice(bytes); + if gfx { + s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); + s.io_cache_gfx = None; + s.io_cache_tp_cs = None; + s.io_cache_tp_ms = None; + } else { + s.args_gen_cs = s.args_gen_cs.wrapping_add(1); + s.io_cache_cs = None; + } + } } }) } @@ -191,9 +1006,23 @@ fn put(list: *mut c_void, i: u32, offset: u32, bytes: &[u8]) { pub(super) unsafe extern "system" fn set_graphics_root_signature(this: *mut c_void, rs: *mut c_void) { 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) + let same = console_list::same_layout(&s.layout_gfx, &layout); + if same && s.rs_gfx == rs as usize { + return; + } + if !same { + let size = layout.as_ref().map_or(0, |l| l.size as usize); + s.args_gfx.clear(); + s.args_gfx.resize(size, 0); + } s.layout_gfx = layout; s.rs_gfx = rs as usize; + s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); + s.io_cache_gfx = None; + s.io_cache_tp_cs = None; + s.io_cache_tp_ms = None; }); } @@ -209,9 +1038,14 @@ pub(super) unsafe extern "system" fn set_graphics_root_constant(this: *mut c_voi /// #40 SetGraphicsRoot32BitConstants (PC #36) pub(super) unsafe extern "system" fn set_graphics_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { - if !data.is_null() { - let bytes: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); - put_in(this, true, i, offset, &bytes); + if !data.is_null() && n > 0 { + #[cfg(target_endian = "little")] + let bytes = std::slice::from_raw_parts(data.cast::(), (n as usize).saturating_mul(4)); + #[cfg(not(target_endian = "little"))] + let bytes_vec: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); + #[cfg(not(target_endian = "little"))] + let bytes = bytes_vec.as_slice(); + put_in(this, true, i, offset, bytes); } } @@ -219,9 +1053,46 @@ pub(super) unsafe extern "system" fn set_graphics_root_constants(this: *mut c_vo /// #40 / #42) pub(super) unsafe extern "system" fn set_graphics_root_descriptor(this: *mut c_void, i: u32, va: u64) { note_address(va); + let va = resolve_root_for_list(this, va); put_in(this, true, i, 0, &va.to_le_bytes()); } +/// Resolve a root descriptor VA for `list`, short-circuiting coherent-UMA addresses and caching +/// outside-UMA resolutions per recording (`root_va_cache`) to avoid repeated global map lookups +/// when the title rebinds the same frame/pass/material CBVs across consecutive draws. +fn resolve_root_for_list(list: *mut c_void, va: u64) -> u64 { + if va == 0 || crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize)) { + return va; + } + if let Some(hit) = with(list, |s| { + s.root_va_cache.iter().find(|&&(raw, _)| raw == va).map(|&(_, resolved)| resolved) + }) { + return hit; + } + let resolved = readable_root(va); + with(list, |s| { + let idx = s.root_va_next & 15; + s.root_va_cache[idx] = (va, resolved); + s.root_va_next = s.root_va_next.wrapping_add(1); + }); + resolved +} + +/// The address a root descriptor at `va` gets: first try resolving a GPU-view VA directly to +/// contiguous UMA backing (`real::resolve_uma_va`, zero-copy for both reads and root UAV writes), +/// then fall back to the read-only `sparse::gpu_view` mirror for scattered mappings. +fn readable_root(va: u64) -> u64 { + if let Some(u) = super::real::resolve_uma_va(va, 0x1000) { + return u; + } + for len in [0x1_0000usize, 0x1000] { + if let Some(b) = super::sparse::gpu_view::base_for(va as usize, len) { + return b as u64; + } + } + va +} + /// `XCL_TRACE_ADDRESSES=1`: root descriptor addresses of console code – in unified memory /// (translated shaders see them) or not – counted and logged fn note_address(va: u64) { @@ -239,18 +1110,42 @@ fn note_address(va: u64) { } /// command signatures that change root arguments (they need the title's root signature) -static ROOT_SIGNATURES: Mutex>> = Mutex::new(None); +static ROOT_SIGNATURES: RwLock>> = RwLock::new(None); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct DispatchMeshSig { + companion_dispatch: usize, + byte_stride: u32, + mesh_offset: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct DrawSig { + byte_stride: u32, + draw_offset: u32, + indexed: bool, +} + +static DISPATCH_MESH_SIGS: RwLock>> = RwLock::new(None); +static DRAW_SIGS: RwLock>> = RwLock::new(None); -pub(super) fn note_root_changing_signature(sig: usize) { - ROOT_SIGNATURES.lock().unwrap().get_or_insert_with(Default::default).insert(sig); +/// noted at every creation, so a signature made at a freed one's address does not keep its kind +pub(super) fn note_root_changing_signature(sig: usize, changes: bool) { + let mut s = ROOT_SIGNATURES.write().unwrap(); + let s = s.get_or_insert_with(Default::default); + if changes { + s.insert(sig); + } else { + s.remove(&sig); + } } /// command signatures with a Dispatch argument (noted at every creation, so a signature made /// at a freed one's address does not keep its kind) -static DISPATCH_SIGNATURES: Mutex>> = Mutex::new(None); +static DISPATCH_SIGNATURES: RwLock>> = RwLock::new(None); pub(super) fn note_signature_dispatches(sig: usize, dispatches: bool) { - let mut s = DISPATCH_SIGNATURES.lock().unwrap(); + let mut s = DISPATCH_SIGNATURES.write().unwrap(); let s = s.get_or_insert_with(Default::default); if dispatches { s.insert(sig); @@ -260,848 +1155,3853 @@ pub(super) fn note_signature_dispatches(sig: usize, dispatches: bool) { } fn signature_dispatches(sig: usize) -> bool { - DISPATCH_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) + DISPATCH_SIGNATURES.read().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) } -/// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a -/// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root -/// arguments themselves cannot be – skipped, logged) -pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { - type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); - let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); - let raw_pso = with(this, |s| s.pso); - let unbuilt_compute = signature_dispatches(sig) && super::pso_async::is_pending(raw_pso) && super::real::is_console_compute(raw_pso); - if unbuilt_compute && super::list_x::defer(this, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { - return super::pso_async::need_by_submit(raw_pso); +/// command signatures of one Dispatch argument → their stride (a split program runs them as its +/// chain, `chained_indirect`) +static DISPATCH_ONLY: RwLock>> = RwLock::new(None); + +pub(super) fn note_dispatch_only_signature(sig: usize, stride: Option) { + let mut s = DISPATCH_ONLY.write().unwrap(); + let s = s.get_or_insert_with(Default::default); + match stride { + Some(n) => { + s.insert(sig, n); + } + None => { + s.remove(&sig); + } } - let pso = super::pso_async::resolve_wait(raw_pso); - let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); - let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); - if !gfx && !compute { - // A pipeline still being built (or whose build failed): its stand-in draws nothing, and - // the list may hold XCL's ABI root signature from a translated draw before it – the PC - // call with that pair is invalid (debug layer 953, "the currently set Root Signature - // doesn't match the currently set Pipeline State Object"; a retail title's world then - // hung the GPU, 0x887a0006). Skipped, like a draw or dispatch of such a pipeline. - if super::pso_async::is_pending(raw_pso) { - count(DRAWS_SKIPPED); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: ExecuteIndirect with a pipeline that is still being built skipped"); - } - return; +} + +pub(super) fn note_dispatch_mesh_signature(sig: usize, companion_dispatch: usize, byte_stride: u32, mesh_offset: u32) { + DISPATCH_MESH_SIGS + .write() + .unwrap() + .get_or_insert_with(HashMap::new) + .insert(sig, DispatchMeshSig { companion_dispatch, byte_stride, mesh_offset }); +} + +fn dispatch_mesh_sig_of(sig: usize) -> Option { + DISPATCH_MESH_SIGS.read().unwrap().as_ref()?.get(&sig).copied() +} + +/// noted at every creation, so a non-draw signature made at a freed draw signature's address does +/// not inherit stale draw-guard metadata +pub(super) fn note_draw_signature(sig: usize, info: Option<(u32, u32, bool)>) { + let mut s = DRAW_SIGS.write().unwrap(); + let s = s.get_or_insert_with(HashMap::new); + match info { + Some((byte_stride, draw_offset, indexed)) => { + s.insert(sig, DrawSig { byte_stride, draw_offset, indexed }); } - // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in - // TWO_PASS rather than TRANSLATED_GRAPHICS. Falling through to raw PC ExecuteIndirect - // with the title's graphics root signature (e.g. a non-DispatchMesh indirect draw or a - // root-changing signature) invalidates the command list (Close → E_INVALIDARG). - if let Some(tp) = super::real::two_pass_of(pso) { - count(DRAWS_SKIPPED); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!( - "D3D12.X: ExecuteIndirect with two-pass {} pipeline ({pso:#x}) skipped – PC pipeline is a mesh shader", - tp.kind - ); - } - return; - } - // a console compute program without a translation (its build failed): nothing to run, - // as for Dispatch. The PC call would run it with the list's compute root signature, which - // can still be XCL's ABI one from a translated dispatch before it (debug layer 953). - // A native PC compute pipeline is not one of these and still goes to the PC call. - // (`CONSOLE_COMPUTE` holds the title's object, which for a shared stand-in differs from - // the driver pipeline `resolve_wait` returned.) - if signature_dispatches(sig) && (super::real::is_console_compute(raw_pso) || super::real::is_console_compute(pso)) { - count(DISPATCHES_SKIPPED); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: ExecuteIndirect dispatch with a pipeline that has no translated console shader ({raw_pso:#x}) skipped"); - } - return; - } - // a PC pipeline: the title's root signature, as for a draw (`graphics_bound`) - let rs = with(this, |s| s.rs_gfx) as *mut c_void; - if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { - list.SetGraphicsRootSignature(r); - } - return fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)); - } - if ROOT_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) { - 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 that changes root arguments with a translated pipeline skipped"); - } - return; - } - let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; - match bind_abi(this, list, pso, gfx) { - Ok(()) => { - if compute { - match super::real::dispatch_chain::whole(pso) { - Ok(Some(whole)) => list.SetPipelineState(&whole), - Ok(None) => {} - Err(e) => { - crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO: {e}"); - count(DISPATCHES_SKIPPED); - return; - } - } - } - count(if gfx { DRAWS } else { DISPATCHES }); - fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)) - } - Err(e) => { - count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: ExecuteIndirect with a translated pipeline skipped: {e}"); - } + None => { + s.remove(&sig); } } } -/// XCL's own buffer for `fresh_indirect_arguments` (device, buffer): COMMON between its uses -static ARGUMENT_ORDER: Mutex> = Mutex::new(None); +fn draw_sig_of(sig: usize) -> Option { + DRAW_SIGS.read().unwrap().as_ref()?.get(&sig).copied() +} -/// `op` (an ExecuteIndirect on `list`) reading the arguments and count the list wrote before it. -/// -/// The console orders a dispatch that writes indirect arguments before the ExecuteIndirect that -/// reads them with a barrier that reaches the PC as a UAV barrier (`list_x::resource_barrier_x`). -/// NVIDIA's driver (RTX 5090) fetches an ExecuteIndirect's arguments without waiting for that -/// barrier: it ran the count that was there before the list in all but a few of 100 tries, also -/// when the dispatch wrote them through another resource over the same memory, as translated -/// shaders do through the memory window buffers (`execute_indirect_reads_the_arguments_written_before_it`). -/// A retail title's ExecuteIndirect after the dispatch that writes its group count then runs -/// whatever count the memory held before. A transition to INDIRECT_ARGUMENT makes the driver -/// wait for the writes – of any buffer, as measured there. The title's buffer is in the title's -/// state (its transitions reach the PC list), so a buffer of XCL's own takes it, COMMON -> -/// INDIRECT_ARGUMENT before and back after. Only on a list XCL made (`list_x::on_create`) and -/// not a bundle, which cannot hold barriers; its type comes from XCL's state, not a call to it. -unsafe fn fresh_indirect_arguments(list: *mut c_void, op: impl FnOnce()) { - let tracked = super::list_x::tracked_list_type(list).is_some_and(|t| t != D3D12_COMMAND_LIST_TYPE_BUNDLE); - let buffer = if tracked { ID3D12GraphicsCommandList::from_raw_borrowed(&list).and_then(|l| argument_order_buffer(l)) } else { None }; - let Some(buffer) = buffer else { return op() }; - let b = buffer.as_raw() as usize; - super::list_x::transition(list, b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); - op(); - super::list_x::transition(list, b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); +unsafe fn emit_uav_barrier(list: &ID3D12GraphicsCommandList, res: Option<&ID3D12Resource>) { + let mut b = 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(res.cloned()), + }), + }, + }; + list.ResourceBarrier(&[std::ptr::read(&b)]); + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.UAV).pResource); } -/// The device's buffer for `fresh_indirect_arguments` (made on first use) -unsafe fn argument_order_buffer(list: &ID3D12GraphicsCommandList) -> Option { - let mut dev: Option = None; - list.GetDevice(&mut dev).ok()?; - let dev = dev?; - let mut g = ARGUMENT_ORDER.lock().unwrap(); - if let Some((_, b)) = g.as_ref().filter(|(d, _)| *d == dev.as_raw() as usize) { - return Some(b.clone()); - } +unsafe fn emit_uav_and_transition(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + let mut b = [ + 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), + }), + }, + }, + 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::ManuallyDrop::new(Some(res.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + }, + ]; + list.ResourceBarrier(&b); + std::mem::ManuallyDrop::drop(&mut (*b[1].Anonymous.Transition).pResource); +} + +unsafe fn emit_transition_and_uav(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + let mut b = [ + 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::ManuallyDrop::new(Some(res.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + }, + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }, + ]; + list.ResourceBarrier(&b); + std::mem::ManuallyDrop::drop(&mut (*b[0].Anonymous.Transition).pResource); +} + +unsafe fn emit_transition(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + let mut b = 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::ManuallyDrop::new(Some(res.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + }; + list.ResourceBarrier(&[std::ptr::read(&b)]); + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); +} + +unsafe fn default_uav_buffer(dev: &ID3D12Device, bytes: u64, what: &str) -> Result { let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: 256, + Alignment: 0, + Width: 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, - ..Default::default() + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, }; - let mut b: Option = None; - if let Err(e) = dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut b) { - 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: no buffer to order its arguments after the writes before it ({e}) – it may read old ones"); - } - return None; + let mut res: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut res, + ) + .map_err(|e| format!("{what} ({bytes:#x} B): {e}"))?; + let res = res.ok_or_else(|| format!("null {what}"))?; + if super::real::dred_on() { + super::real::name_resource(res.as_raw(), what); } - let b = b?; - *g = Some((dev.as_raw() as usize, b.clone())); - Some(b) + Ok(res) } -/// A DrawInstanced of the console's rect list (three corners of each rectangle, the fourth -/// implied) as two triangles a rectangle; false: not a rect list, or one this cannot expand -/// (the caller draws the three vertices as a triangle – half of each rectangle). -/// -/// The PC has no rect lists. The fourth corner is made here, on the CPU, from the title's -/// vertex data: v3 = v0 + v2 − v1 (seen in a retail title's full-screen passes: (−1,1) (−1,−1) -/// (1,−1) with texture coordinates (0,0) (0,1) (1,1) – the missing corner is (1,1), (1,0)). -/// The vertex layout is not looked at: each 4-byte word that is the same in all three vertices -/// is kept (a packed colour), any other is taken as a float. Vertices a shader makes from the -/// vertex index alone (no vertex buffer) are not expanded. -unsafe fn draw_rects(this: *mut c_void, list: &ID3D12GraphicsCommandList, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) -> bool { - if !cpu_rect_expansion(with(this, |s| s.pso)) { - return false; +/// Groups of a two-pass dispatch that have a record: one record a group in `cap_bytes` of +/// records of `record_bytes`, and every group in X, the mesh pass's `split` times as many (at most +/// 65 535 a dimension). The compute pass writes record `gid.x` with no bound of its own. +fn record_groups(cap_bytes: u64, record_bytes: u64, split: u32) -> u32 { + (cap_bytes / record_bytes.max(1)).min(65_535 / split.max(1) as u64) as u32 +} + +/// The ExecuteIndirects of a two-pass ExecuteIndirect of `max` commands, each of one command and +/// followed by a UAV barrier on the records: (command, compute pass). Each command's compute pass +/// writes its records from record 0, so the next one goes only after the mesh pass drew them. +fn two_pass_steps(max: u32) -> impl Iterator { + (0..max).flat_map(|k| [(k, true), (k, false)]) +} + +/// 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")) +} + +/// The queue the recordings with two-pass draws go to (0: none yet), and whether a second one +/// was seen: the shared buffer is for one queue's lists, which run in order. +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 Some(vbs) = super::list_x::rect_list_state(this) else { return false }; - let rects = (vertices / 3) as usize; - if vbs.is_empty() || rects == 0 || rects > 4096 { - return false; + let used = lists.iter().any(|&l| { + let key = l as usize; + STATES[state_shard(key)] + .lock() + .unwrap() + .as_ref() + .is_some_and(|m| m.get(&key).is_some_and(|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"); } - let mut views = Vec::new(); - for &(slot, (va, bytes, stride), _) in &vbs { - let (s, at) = (stride as usize, va as usize + first_vertex as usize * stride as usize); - let len = rects * 3 * s; - if va == 0 || s == 0 || s % 4 != 0 || first_vertex as usize * s + len > bytes as usize || !crate::gpu::shader::readable(at, len) { - return false; +} + +/// `queue` is the first one seen, or the same as it (`seen`: 0 before the first). +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, + } +} + +/// A shared record buffer of at least `need` bytes: buffer, address, bytes. +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)) +} + +/// The record buffer a two-pass ExecuteIndirect asks for (`XCL_TWO_PASS_LIST_MB`, 32 MiB): the +/// groups past it are dropped on the GPU (`SCALE_ARGS_HLSL`). With a buffer of each list +/// (`XCL_TWO_PASS_SHARED=0`) a retail title's world holds one for each of ~130 lists at once: +/// 4.3 GB of a 16 GB card's video memory at 32 MiB, and the device was lost when it ran out. +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)) +} + +/// The record buffer of this list for `need_bytes` (at most 128 MiB): buffer, address, bytes. +unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D12Resource, u64, u64), String> { + let need = need_bytes.max(4 << 20).next_multiple_of(1 << 20).min(128 << 20); + { + // local: which way the records go, once each + 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); // what an earlier list left in the records } - let p = allocate_upload_memory(this, rects * 6 * s, 16); - if p.is_null() { - return false; + let va = buf.GetGPUVirtualAddress(); + return Ok((buf, va, cap)); + } + if let Some((buf, cap, _dev)) = with(this, |s| s.res_buf.as_ref().filter(|(_, cap, _)| *cap >= need).cloned()) { + let va = buf.GetGPUVirtualAddress(); + return Ok((buf, va, cap)); + } + let dev = super::real::list_device(this).ok_or("no device for two-pass buffer")?; + let dev_key = dev.as_raw() as usize; + let picked = { + let mut free = FREE_RES.lock().unwrap(); + free.iter().position(|(_, cap, d)| *d == dev_key && *cap >= need).map(|i| free.swap_remove(i)) + }; + let entry = match picked { + Some(e) => e, + None => (default_uav_buffer(&dev, need, "two-pass res buffer")?, need, dev_key), + }; + let (buf, cap) = (entry.0.clone(), entry.1); + let va = buf.GetGPUVirtualAddress(); + with(this, |s| { + if let Some(old) = s.res_buf.replace(entry) { + s.res_retired.push(old); } - let word = |v: usize, w: usize| (at as *const u8).add(v * s + w * 4).cast::().read_unaligned(); - for r in 0..rects { - let out = p.add(r * 6 * s); - let src = (at as *const u8).add(r * 3 * s); - // v0 v1 v2, then v0 v2 v3 - std::ptr::copy_nonoverlapping(src, out, 3 * s); - std::ptr::copy_nonoverlapping(src, out.add(3 * s), s); - std::ptr::copy_nonoverlapping(src.add(2 * s), out.add(4 * s), s); - for w in 0..s / 4 { - let (a, b, c) = (word(r * 3, w), word(r * 3 + 1, w), word(r * 3 + 2, w)); - let d = if a == b && b == c { a } else { (f32::from_bits(a) + f32::from_bits(c) - f32::from_bits(b)).to_bits() }; - out.add(5 * s + w * 4).cast::().write_unaligned(d); - } + }); + Ok((buf, va, cap)) +} + +/// Write packed inline root arguments from `args` into `dst[first..]` as little-endian dwords, +/// returning the next free SGPR index (zero heap allocation). +fn write_inline_words(dst: &mut [u32], first: usize, inline_bytes: u32, args: &[u8]) -> usize { + let inline = &args[..(inline_bytes as usize).min(args.len())]; + let mut len = first; + for chunk in inline.chunks(4) { + let mut w = [0u8; 4]; + w[..chunk.len()].copy_from_slice(chunk); + if len < dst.len() { + dst[len] = u32::from_le_bytes(w); } - views.push((slot, D3D12_VERTEX_BUFFER_VIEW { BufferLocation: super::list_x::pc_va_of(p as u64), SizeInBytes: (rects * 6 * s) as u32, StrideInBytes: stride })); - } - for (slot, v) in &views { - list.IASetVertexBuffers(*slot, Some(&[*v])); + len += 1; } - list.DrawInstanced(rects as u32 * 6, instances, 0, first_instance); - for &(slot, _, pc) in &vbs { - if let Some(v) = pc { - list.IASetVertexBuffers(slot, Some(&[v])); + len +} + +/// Append heap base addresses requested by `l.heaps` into `dst[len..]`, respecting `user_sgprs`. +fn append_heap_words(dst: &mut [u32], mut len: usize, l: &Layout, user_sgprs: Option, heaps: [u32; 2]) { + for (_, base) in l.heaps.iter().zip(heaps).filter(|(&used, _)| used) { + if user_sgprs.is_some_and(|n| len as u32 >= n) { + break; } + if len < dst.len() { + dst[len] = base; + } + len += 1; } - static N: AtomicU64 = AtomicU64::new(0); - if N.fetch_add(1, Ordering::Relaxed) == 0 { - crate::xlog_info!("D3D12.X: rect lists are drawn as two triangles a rectangle, the fourth corner made on the CPU"); +} + +/// Zero-allocation stack builder for graphics `io` (`u0`) user SGPRs (`KERNEL_SGPRS` dwords). +fn fill_io_gfx(layout: Option<&Layout>, args: &[u8], table_at: u64, heaps: [u32; 2], uma_base: usize) -> [u32; crate::gpu::recomp::KERNEL_SGPRS] { + let mut io = [0u32; crate::gpu::recomp::KERNEL_SGPRS]; + io[0] = table_at as u32; + io[1] = (table_at >> 32) as u32; + if let Some(l) = layout { + let len = write_inline_words(&mut io, 8, l.inline_gfx, args); + append_heap_words(&mut io, len, l, None, heaps); } - true + io[crate::gpu::recomp::IO_UMA_BASE_HI] = (uma_base as u64 >> 32) as u32; + io } -/// Whether a rect list drawn with the bound pipeline `pso` is expanded on the CPU (`draw_rects`): -/// not with the rect list GS (`real::has_rect_list_gs`), which completes each rect itself – both -/// would draw every rect twice (each CPU half is three corners of the rect). -fn cpu_rect_expansion(pso: usize) -> bool { - !super::real::has_rect_list_gs(super::pso_async::resolve(pso)) +/// Zero-allocation stack builder for compute `io` (`u0`) user SGPRs (`KERNEL_SGPRS` dwords). +fn fill_io_compute(layout: Option<&Layout>, user_sgprs: Option, args: &[u8], table_at: u64, heaps: [u32; 2], uma_base: usize, group_limit: u32) -> [u32; crate::gpu::recomp::KERNEL_SGPRS] { + let mut io = [0u32; crate::gpu::recomp::KERNEL_SGPRS]; + io[0] = table_at as u32; + io[1] = (table_at >> 32) as u32; + if let Some(l) = layout { + let inline = console_list::inline_for(l, user_sgprs); + let len = write_inline_words(&mut io, 4, inline, args); + append_heap_words(&mut io, len, l, user_sgprs, heaps); + } + io[crate::gpu::recomp::IO_UMA_BASE_HI] = (uma_base as u64 >> 32) as u32; + io[crate::gpu::recomp::IO_GROUP_LIMIT] = group_limit; + io } -/// #12 DrawInstanced -pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) { - DRAW_ARGS.with(|d| d.set((false, vertices, instances, first_vertex, 0))); - if let Some(list) = graphics_bound(this) { - if draw_rects(this, &list, vertices, instances, first_vertex, first_instance) { - return; +/// Zero-allocation stack builder for two-pass stage `io` (`u0`) user SGPRs. +fn fill_io_two_pass(layout: Option<&Layout>, args: &[u8], table_at: u64, compute_pass: bool, uma_base: usize, heaps: [u32; 2]) -> [u32; crate::gpu::recomp::KERNEL_SGPRS] { + let mut io = [0u32; crate::gpu::recomp::KERNEL_SGPRS]; + if compute_pass { + io[8] = table_at as u32; + io[9] = (table_at >> 32) as u32; + if let Some(l) = layout { + let len = write_inline_words(&mut io, 16, l.inline_ms, args); + append_heap_words(&mut io, len, l, None, heaps); + } + } else { + io[0] = table_at as u32; + io[1] = (table_at >> 32) as u32; + if let Some(l) = layout { + write_inline_words(&mut io, 8, l.inline_gfx, args); } - 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); } + io[crate::gpu::recomp::IO_UMA_BASE_HI] = (uma_base as u64 >> 32) as u32; + io } -thread_local! { - /// the draw being bound: (indexed, count, instances, first index / vertex, base vertex) – for the frame trace - static DRAW_ARGS: std::cell::Cell<(bool, u32, u32, u32, i32)> = const { std::cell::Cell::new((false, 0, 0, 0, 0)) }; +/// The `io` block of a two-pass stage (test helper wrapping `fill_io_two_pass`). +#[cfg(test)] +fn two_pass_io(layout: Option<&Layout>, args: &[u8], table_at: u64, compute_pass: bool, uma_base: usize, heaps: [u32; 2]) -> Vec { + fill_io_two_pass(layout, args, table_at, compute_pass, uma_base, heaps).to_vec() } -/// #13 DrawIndexedInstanced -pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) { - 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); +/// Ensure shared shader-visible descriptor heaps are bound on `this`, skipping global locks when +/// already verified on this recording (`State::heaps_ensured`). +unsafe fn ensure_heaps_cached(this: *mut c_void) { + if with(this, |s| s.heaps_ensured) { + return; + } + if super::list_x::ensure_view_heap(this) { + with(this, |s| s.heaps_ensured = true); } } -/// Prepare an indexed draw once, before callers make temporary native state changes. -pub(super) unsafe fn prepare_indexed_draw( - this: *mut c_void, - indices: u32, - instances: u32, - first_index: u32, - base_vertex: i32, -) -> Option { - DRAW_ARGS.with(|d| d.set((true, indices, instances, first_index, base_vertex))); - graphics_bound(this) +/// Lazily resolve and cache `vram_io_device(this)` outside `STATES`, avoiding 3 global locks + +/// COM AddRef/Release on every draw/dispatch. +unsafe fn ensure_vram_io_dev(this: *mut c_void) -> Option { + if let Some(cached) = with(this, |s| s.vram_io_dev.as_ref().map(|o| o.as_ref().map(|d| d.0.clone()))) { + return cached; + } + let dev = vram_io_device(this); + with(this, |s| { + s.vram_io_dev = Some(dev.as_ref().map(|d| CachedIoDev(d.clone()))); + }); + dev } -/// Submit an indexed draw whose translated graphics state has already been prepared. -pub(super) unsafe fn emit_prepared_indexed_draw( - list: &ID3D12GraphicsCommandList, - indices: u32, - instances: u32, - first_index: u32, - base_vertex: i32, - first_instance: u32, -) { - list.DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance); +/// Copy `tail` of root arguments into UMA arena, reusing a single 16-byte dummy slot when `tail` +/// is empty (all root arguments fit inline in user SGPRs). Takes disjoint `State` fields so +/// callers can hold an immutable borrow of `s.uma_windows` across the call. +unsafe fn upload_arg_table( + u: &crate::gpu::uma::Uma, + arena: &mut crate::gpu::uma::Arena, + uma: &mut Vec, + dummy_table_p: &mut usize, + tail: &[u8], +) -> Result { + if tail.is_empty() { + if *dummy_table_p == 0 { + let p = arena.take(u, 16, 256, uma).ok_or("unified memory is full")?; + std::ptr::write_bytes(p, 0, 16); + *dummy_table_p = p as usize; + } + return Ok(*dummy_table_p as u64); + } + let table_p = arena.take(u, tail.len().max(16), 256, uma).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(tail.as_ptr(), table_p, tail.len()); + Ok(table_p as u64) } -/// Before a draw: with a translated pipeline its ABI root signature and the kept graphics -/// arguments are bound (None: the draw is skipped – a console pipeline without a -/// translation, or no unified memory). -unsafe fn graphics_bound(this: *mut c_void) -> Option { - let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); - let pso = with(this, |s| s.pso); - // a pipeline still being built in the background is waited for (its stand-in draws nothing) - let real = super::pso_async::resolve_wait(pso); - if !super::real::is_translated_graphics(real) { - // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in - // TWO_PASS rather than TRANSLATED_GRAPHICS. Binding the title's graphics RS and issuing - // DrawInstanced / DrawIndexedInstanced against a mesh PSO invalidates the command list - // (Close → E_INVALIDARG). - if let Some(tp) = super::real::two_pass_of(real) { - count(DRAWS_SKIPPED); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!( - "D3D12.X: draw with two-pass {} pipeline ({real:#x}) skipped – PC pipeline is a mesh shader", - tp.kind - ); +unsafe fn bind_two_pass_stage( + this: *mut c_void, + list: &ID3D12GraphicsCommandList, + real_mesh_pso: usize, + tp: &super::real::TwoPassPso, + res_va: u64, + compute_pass: bool, +) -> Result<(), String> { + // the pair is translated with heap windows when they are on (`pso::mem_windows`): as `bind_abi` + ensure_heaps_cached(this); + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let rs_usize = if compute_pass { tp.compute_rs } else { tp.mesh_rs }; + let rs_raw = rs_usize as *mut c_void; + let rs = ID3D12RootSignature::from_raw_borrowed(&rs_raw).ok_or("two-pass root signature")?; + let pso_raw = if compute_pass { tp.compute } else { real_mesh_pso } as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&pso_raw).ok_or(if compute_pass { "two-pass compute pipeline" } else { "two-pass mesh pipeline" })?; + + let need_io_dev = with(this, |s| { + let hit = if compute_pass { + s.io_cache_tp_cs.is_some_and(|(gen, _)| gen == s.args_gen_gfx) + } else { + s.io_cache_tp_ms.is_some_and(|(gen, _)| gen == s.args_gen_gfx) + }; + !hit && s.vram_io_dev.is_none() + }); + if need_io_dev { + let _ = ensure_vram_io_dev(this); + } + + let (set_rs, uav_mask, views) = with(this, |s| -> Result<(bool, u8, [u64; 6]), String> { + if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { + let w = super::real::uma_window_vas(); + if w.is_empty() { + return Err("unified memory is not open on the GPU".into()); } - return None; + s.uma_windows = Some(w); } - count(DRAWS_PC); - if super::present::trace_frame() { - // which pipelines draw without a translation (first 12 distinct) - static SEEN: Mutex> = Mutex::new(Vec::new()); - let mut g = SEEN.lock().unwrap(); - if !g.contains(&pso) && g.len() < 12 { - g.push(pso); - let real = super::pso_async::resolve_wait(pso); - crate::xlog_info!( - "frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {real:#x}; pending {}, two-pass {}, RT0 {:?})", - super::pso_async::is_pending(pso), - super::real::two_pass_of(real).is_some(), - super::present::rt0_resource(this as usize).map(|r| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0) })) - ); + let windows = s.uma_windows.as_deref().unwrap(); + let first = windows[0]; + let win_vas = [ + first, + windows.get(1).copied().filter(|&v| v != 0).unwrap_or(first), + windows.get(2).copied().filter(|&v| v != 0).unwrap_or(first), + windows.get(3).copied().filter(|&v| v != 0).unwrap_or(first), + ]; + + let cached_io = if compute_pass { + s.io_cache_tp_cs.filter(|&(gen, _)| gen == s.args_gen_gfx).map(|(_, va)| va) + } else { + s.io_cache_tp_ms.filter(|&(gen, _)| gen == s.args_gen_gfx).map(|(_, va)| va) + }; + let io_va = if let Some(va) = cached_io { + va + } else { + let inline = s.layout_gfx.as_deref() + .map_or(0, |l| if compute_pass { l.inline_ms } else { l.inline_gfx } as usize) + .min(s.args_gfx.len()); + let table_at = upload_arg_table(u, &mut s.arena, &mut s.uma, &mut s.dummy_table_p, &s.args_gfx[inline..])?; + let io = fill_io_two_pass(s.layout_gfx.as_deref(), s.args_gfx.as_slice(), table_at, compute_pass, u.base(), s.heaps); + let io_bytes = std::mem::size_of_val(&io); + let io_slice = std::slice::from_raw_parts(io.as_ptr().cast::(), io_bytes); + let va = match s.vram_io_dev.as_ref().and_then(|o| o.as_ref()).and_then(|dev| alloc_vram_io_in(&mut s.io_blocks, s.allocator, s.prelude_built.is_some(), &dev.0, io_slice)) { + Some(va) => va, + None => { + let io_p = s.arena.take(u, io_bytes.max(16), 256, &mut s.uma).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(io_slice.as_ptr(), io_p, io_bytes); + uma_va_in(u, windows, io_p as usize).unwrap_or(first) + } + }; + if compute_pass { + s.io_cache_tp_cs = Some((s.args_gen_gfx, va)); + } else { + s.io_cache_tp_ms = Some((s.args_gen_gfx, va)); } - } - // a PC pipeline (also a stand-in or fallback: made with the title's root signature): - // the title's root signature, which nothing else binds on the PC list – a draw without - // one is invalid (the debug layer reports it on every GPU; WARP faults on it) - if super::pso_async::is_pending(pso) { - super::list_x::note_dropped_draw(this); - } - let rs = with(this, |s| s.rs_gfx) as *mut c_void; - if let Some(r) = ID3D12RootSignature::from_raw_borrowed(&rs) { - list.SetGraphicsRootSignature(r); - } - return Some(list); + va + }; + + let views = [io_va, res_va, win_vas[0], win_vas[1], win_vas[2], win_vas[3]]; + let bound = if compute_pass { &mut s.pc_abi_cs } else { &mut s.pc_abi_gfx }; + let (set_rs, uav_mask) = diff_abi_bindings(bound, rs_usize, views); + Ok((set_rs, uav_mask, views)) + })?; + + emit_abi_bindings(list, !compute_pass, rs, set_rs, uav_mask, views); + list.SetPipelineState(pc); + Ok(()) +} + +/// The pass that rewrites a two-pass ExecuteIndirect's arguments, on XCL's ABI: u0 = `count`, +/// `stride`, `offset` (of the DispatchMesh argument), `split`, `cap` (groups with a record), and +/// where the commands are (u2) and go (u3), in bytes. Each command goes out twice, for the compute +/// 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. +pub(super) const SCALE_ARGS_HLSL: &str = r#"RWByteAddressBuffer io : register(u0); +RWByteAddressBuffer src : register(u2); +RWByteAddressBuffer dst : register(u3); +RWByteAddressBuffer cnt : register(u4); +[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); + if (tid >= count) return; + uint live = count; + if (io.Load(28) != 0u) { + live = min(count, cnt.Load(io.Load(32))); } - if super::present::trace_frame() { - trace_ui_draw(this, pso); + 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); + dst.Store(d + i, w); + dst.Store(m + i, w); } - match bind_abi(this, &list, pso, true) { - Ok(()) => { - count(DRAWS); - Some(list) - } - Err(e) => { - super::list_x::note_dropped_draw(this); - count(DRAWS_SKIPPED); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: draw with a translated pipeline skipped: {e}"); + uint3 g = src.Load3(s + offset); + uint n = 0u; + if (tid < live && g.x != 0u && g.y != 0u && g.z != 0u) { + n = min(g.x, cap); + n = g.y > cap / n ? cap : n * g.y; + n = g.z > cap / n ? cap : n * g.z; + } + dst.Store3(d + offset, uint3(n, 1u, 1u)); + dst.Store3(m + offset, uint3(n * split, 1u, 1u)); +} +"#; + +/// The groups of an indirect dispatch (u2, `io` dword 0: their byte offset) as they go out (u3): +/// 0 x 0 x 0 when they are more than `io` dword 1 in all, or a count alone is (`MOST_GROUPS`). The +/// counts come from memory the GPU wrote; where that is not what the title meant they can be +/// anything, and billions of groups hold the GPU for seconds or until Windows resets the driver. +/// More than 65 535 groups in X with 1 in Y are folded into `65 535 x ceil(x / 65 535)` with the +/// console count written to `u4` at `io` dword 3 (`IO_GROUP_LIMIT * 4`, when non-zero); any other +/// count over D3D12's 65 535 is cut to it. +pub(super) const GUARD_ARGS_HLSL: &str = r#"RWByteAddressBuffer io : register(u0); +RWByteAddressBuffer src : register(u2); +RWByteAddressBuffer dst : register(u3); +RWByteAddressBuffer lim : register(u4); +[numthreads(1, 1, 1)] +void main() { + uint at = io.Load(0), most = io.Load(4), to = io.Load(8), lim_at = io.Load(12); + uint3 g = src.Load3(at); + uint3 out_g = uint3(0u, 0u, 0u); + uint limit = 0u; + if (g.x != 0u && g.y != 0u && g.z != 0u && all(g <= most)) { + if (g.x <= most / g.y) { + if (g.x * g.y <= most / g.z) { + if (g.x > 65535u && g.y == 1u && g.z <= 65535u) { + uint rows = (g.x - 1u) / 65535u + 1u; + if (rows <= 65535u) { + out_g = uint3(65535u, rows, g.z); + limit = g.x; + } else { + out_g = min(g, 65535u.xxx); + } + } else { + out_g = min(g, 65535u.xxx); + } } - None } } + dst.Store3(to, out_g); + if (lim_at != 0u) { + lim.Store(lim_at, limit); + } } +"#; -/// `XCL_TRACE_FRAME`: draws into a presented buffer (the UI) once the title has presented for a -/// while – their pipeline, root arguments and the resources their descriptor tables start with -/// (format, size, kept in step with title memory or not). The first 24. -/// `XCL_TRACE_FRAME`, after 300 presents: one line per distinct (VS, PS, render target) drawn – -/// the shaders' dump hashes, the target and the textures of the first descriptor table. -unsafe fn trace_draw_kinds(this: *mut c_void, pso: usize) { - // keyed by the target's shape, not the object: a UI library's transient targets (Renoir's - // layers) are new objects every frame and would fill the list at once - static SEEN: Mutex)>> = Mutex::new(Vec::new()); - if super::present::activity().0 < 300 { - return; +const GUARD_ARGS_DRED_LABEL: &str = "xcl guard_dispatch_args"; +const SCALE_ARGS_DRED_LABEL: &str = "xcl make_scaled_args_buffer"; +const PRELUDE_GUARD_DRED_LABEL: &str = "xcl prelude_guard_dispatch_args"; +const PRELUDE_SCALE_DRED_LABEL: &str = "xcl prelude_scale_mesh_args"; +const GUARD_DRAW_DRED_LABEL: &str = "xcl guard_draw_args"; +const PRELUDE_DRAW_DRED_LABEL: &str = "xcl prelude_guard_draw_args"; + +/// Exclusive upper bound on vertices/indices per instance in indirect Draw/DrawIndexed (`2^23` = +/// `8,388,608`): any record with `verts >= 2^23` is zeroed to prevent garbage indirect-draw hangs. +#[cfg(test)] +const DRAW_VERTS_PER_INST_LIMIT: u32 = 1 << 23; +/// Inclusive upper bound on total vertices (`verts_per_inst * instances`, `2^26` = `67,108,864`): +/// any record with `verts * instances > 2^26` is zeroed. +#[cfg(test)] +const DRAW_TOTAL_VERTS_MAX: u32 = 1 << 26; + +/// Pure check matching `GUARD_DRAW_ARGS_*` / `PRELUDE_DRAW_GUARD_*`: true when an indirect +/// Draw/DrawIndexed record should be zeroed (`verts == 0`, `insts == 0`, `verts >= 2^23`, or +/// `verts * insts > 2^26`). +#[cfg(test)] +fn draw_record_rejected(verts: u32, insts: u32) -> bool { + verts == 0 || insts == 0 || verts >= DRAW_VERTS_PER_INST_LIMIT || insts > DRAW_TOTAL_VERTS_MAX / verts +} + +/// Inline indirect Draw/DrawIndexed argument guard (`u0` = `[count, stride, draw_offset, src_off]`, +/// `u2` = source UMA window, `u3` = destination scratch): copies each command and zeroes +/// `(verts, insts)` whenever `verts == 0 || insts == 0 || verts >= 2^23 || verts * insts > 2^26`. +pub(super) const GUARD_DRAW_ARGS_HLSL: &str = r#"RWByteAddressBuffer io : register(u0); +RWByteAddressBuffer src : register(u2); +RWByteAddressBuffer dst : register(u3); +[numthreads(64, 1, 1)] +void main(uint tid : SV_DispatchThreadID) { + uint count = io.Load(0), stride = io.Load(4), draw_off = io.Load(8), src_off = io.Load(12); + if (tid >= count) return; + uint s = src_off + tid * stride; + uint d = tid * stride; + for (uint i = 0u; i < stride; i += 4u) { + dst.Store(d + i, src.Load(s + i)); } - let Some((vs, ps)) = super::real::pso_shaders(super::pso_async::resolve(pso)) else { return }; - let rt = super::present::rt0_resource(this as usize).unwrap_or(0); - let desc = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0, d.SampleDesc.Count) }); - { - let mut g = SEEN.lock().unwrap(); - let key = (vs, ps, desc(rt)); - if g.len() >= 160 || g.contains(&key) { - return; + uint verts = src.Load(s + draw_off); + uint insts = src.Load(s + draw_off + 4u); + if (verts == 0u || insts == 0u || verts >= 8388608u || insts > 67108864u / verts) { + dst.Store(d + draw_off, 0u); + dst.Store(d + draw_off + 4u, 0u); + } +} +"#; + +/// Descriptor-heap + inline root-constants form of `GUARD_DRAW_ARGS_HLSL`. +pub(super) const GUARD_DRAW_ARGS_HEAP_HLSL: &str = r#"cbuffer Args : register(b0) { + uint count, stride, draw_off, src_slot, src_off; +}; +RWByteAddressBuffer dst : register(u0); +[numthreads(64, 1, 1)] +void main(uint tid : SV_DispatchThreadID) { + if (tid >= count) return; + RWByteAddressBuffer src = ResourceDescriptorHeap[src_slot]; + uint s = src_off + tid * stride; + uint d = tid * stride; + for (uint i = 0u; i < stride; i += 4u) { + dst.Store(d + i, src.Load(s + i)); + } + uint verts = src.Load(s + draw_off); + uint insts = src.Load(s + draw_off + 4u); + if (verts == 0u || insts == 0u || verts >= 8388608u || insts > 67108864u / verts) { + dst.Store(d + draw_off, 0u); + dst.Store(d + draw_off + 4u, 0u); + } +} +"#; + +/// Batched prelude pass guarding all hoisted indirect Draw/DrawIndexed buffers in one +/// `Dispatch(num_jobs, 1, 1)` (`jobs` u0: 32-byte records +/// `[count, stride, draw_off, src_win, src_off, dst_off, 0, 0]`). +pub(super) const PRELUDE_DRAW_GUARD_HLSL: &str = r#"RWByteAddressBuffer jobs : register(u0); +RWByteAddressBuffer dst : register(u1); +RWByteAddressBuffer w0 : register(u2); +RWByteAddressBuffer w1 : register(u3); +RWByteAddressBuffer w2 : register(u4); +RWByteAddressBuffer w3 : register(u5); +uint load_u32(uint win, uint off) { + if (win == 0u) return w0.Load(off); + if (win == 1u) return w1.Load(off); + if (win == 2u) return w2.Load(off); + return w3.Load(off); +} +[numthreads(64, 1, 1)] +void main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID) { + uint b = gid.x * 32u; + uint count = jobs.Load(b); + uint stride = jobs.Load(b + 4u); + uint draw_off = jobs.Load(b + 8u); + uint src_win = jobs.Load(b + 12u); + uint src_off = jobs.Load(b + 16u); + uint dst_off = jobs.Load(b + 20u); + for (uint tid = gtid.x; tid < count; tid += 64u) { + uint s = src_off + tid * stride; + uint d = dst_off + tid * stride; + for (uint i = 0u; i < stride; i += 4u) { + dst.Store(d + i, load_u32(src_win, s + i)); + } + uint verts = load_u32(src_win, s + draw_off); + uint insts = load_u32(src_win, s + draw_off + 4u); + if (verts == 0u || insts == 0u || verts >= 8388608u || insts > 67108864u / verts) { + dst.Store(d + draw_off, 0u); + dst.Store(d + draw_off + 4u, 0u); } - g.push(key); } - let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.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 tex = Vec::new(); - if let (Some(layout), Some(u)) = (layout, crate::gpu::uma::get()) { - for p in layout.params.iter() { - if let Param::Table { at } = *p { - let t = word(at as usize) as usize; - for k in 0..4usize { - if let Some(r) = super::console_heap::resource_at(u.base() + t + 32 * k) { - tex.push(format!("{:?}{}", desc(r), super::title_textures::address(r).map_or(String::new(), |a| format!(" at {a:#x}")))); +} +"#; + +/// Descriptor-heap form of `PRELUDE_DRAW_GUARD_HLSL`. +pub(super) const PRELUDE_DRAW_GUARD_HEAP_HLSL: &str = r#"RWByteAddressBuffer jobs : register(u0); +RWByteAddressBuffer dst : register(u1); +[numthreads(64, 1, 1)] +void main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID) { + uint b = gid.x * 32u; + uint count = jobs.Load(b); + uint stride = jobs.Load(b + 4u); + uint draw_off = jobs.Load(b + 8u); + uint src_win = jobs.Load(b + 12u); + uint src_off = jobs.Load(b + 16u); + uint dst_off = jobs.Load(b + 20u); + RWByteAddressBuffer src = ResourceDescriptorHeap[NonUniformResourceIndex(4u + src_win)]; + for (uint tid = gtid.x; tid < count; tid += 64u) { + uint s = src_off + tid * stride; + uint d = dst_off + tid * stride; + for (uint i = 0u; i < stride; i += 4u) { + dst.Store(d + i, src.Load(s + i)); + } + uint verts = src.Load(s + draw_off); + uint insts = src.Load(s + draw_off + 4u); + if (verts == 0u || insts == 0u || verts >= 8388608u || insts > 67108864u / verts) { + dst.Store(d + draw_off, 0u); + dst.Store(d + draw_off + 4u, 0u); + } + } +} +"#; + +/// Batched prelude pass clamping & >65,535-folding all hoisted indirect compute dispatches of a +/// command list in a single Dispatch(ceil(N / 64), 1, 1) before the list runs. +/// `jobs` (u0): `[total, 0, 0, 0]` followed by `total` 32-byte records +/// `[src_win, src_off, most, dst_off, lim_win, lim_off, 0, 0]`. +pub(super) const PRELUDE_GUARD_HLSL: &str = r#"RWByteAddressBuffer jobs : register(u0); +RWByteAddressBuffer dst : register(u1); +RWByteAddressBuffer w0 : register(u2); +RWByteAddressBuffer w1 : register(u3); +RWByteAddressBuffer w2 : register(u4); +RWByteAddressBuffer w3 : register(u5); +uint3 load_u32x3(uint win, uint off) { + if (win == 0u) return w0.Load3(off); + if (win == 1u) return w1.Load3(off); + if (win == 2u) return w2.Load3(off); + return w3.Load3(off); +} +void store_u32(uint win, uint off, uint v) { + if (win == 0u) w0.Store(off, v); + else if (win == 1u) w1.Store(off, v); + else if (win == 2u) w2.Store(off, v); + else w3.Store(off, v); +} +[numthreads(64, 1, 1)] +void main(uint tid : SV_DispatchThreadID) { + uint total = jobs.Load(0); + if (tid >= total) return; + uint b = 16u + tid * 32u; + uint src_win = jobs.Load(b); + uint src_off = jobs.Load(b + 4u); + uint most = jobs.Load(b + 8u); + uint dst_off = jobs.Load(b + 12u); + uint lim_win = jobs.Load(b + 16u); + uint lim_off = jobs.Load(b + 20u); + uint3 g = load_u32x3(src_win, src_off); + uint3 out_g = uint3(0u, 0u, 0u); + uint limit = 0u; + if (g.x != 0u && g.y != 0u && g.z != 0u && all(g <= most)) { + if (g.x <= most / g.y) { + if (g.x * g.y <= most / g.z) { + if (g.x > 65535u && g.y == 1u && g.z <= 65535u) { + uint rows = (g.x - 1u) / 65535u + 1u; + if (rows <= 65535u) { + out_g = uint3(65535u, rows, g.z); + limit = g.x; + } else { + out_g = min(g, 65535u.xxx); } + } else { + out_g = min(g, 65535u.xxx); } } - if tex.len() >= 4 { - break; - } } } - crate::xlog_info!( - "frame trace: draws vs {vs:016x} ps {ps:016x} into {:?}{} – textures {}; {}", - desc(rt), - if super::present::is_presented(rt) { " (presented)" } else { "" }, - tex.join(", "), - super::list_x::state_summary(this) - ); + dst.Store3(dst_off, out_g); + if (lim_off != 0xFFFFFFFFu) { + store_u32(lim_win, lim_off, limit); + } } +"#; -/// `XCL_TRACE_SHADERS=hash,…` (dump hashes, hex): the draws traced with their root arguments -/// are those whose vertex or pixel shader is listed – into any target, at any time (the first -/// 24); without it, draws into a presented target (or any – `XCL_TRACE_UI_ANY`) after 300 -/// presents. -fn traced_shaders() -> &'static [u64] { - static S: std::sync::OnceLock> = std::sync::OnceLock::new(); - S.get_or_init(|| std::env::var("XCL_TRACE_SHADERS").unwrap_or_default().split(',').filter_map(|h| u64::from_str_radix(h.trim(), 16).ok()).collect()) +/// Batched prelude pass scaling all hoisted two-pass ExecuteIndirect(DispatchMesh) draws of a +/// command list in a single Dispatch(num_jobs, 1, 1) before the list runs (one 64-lane group per +/// job, looping over `count` commands). `jobs` (u0): 48-byte records +/// `[count, stride, offset, split, cap, src_win, src_off, dst_off, has_cnt, cnt_win, cnt_off, 0]`. +pub(super) const PRELUDE_SCALE_HLSL: &str = r#"RWByteAddressBuffer jobs : register(u0); +RWByteAddressBuffer dst : register(u1); +RWByteAddressBuffer w0 : register(u2); +RWByteAddressBuffer w1 : register(u3); +RWByteAddressBuffer w2 : register(u4); +RWByteAddressBuffer w3 : register(u5); +uint load_u32(uint win, uint off) { + if (win == 0u) return w0.Load(off); + if (win == 1u) return w1.Load(off); + if (win == 2u) return w2.Load(off); + return w3.Load(off); +} +uint3 load_u32x3(uint win, uint off) { + if (win == 0u) return w0.Load3(off); + if (win == 1u) return w1.Load3(off); + if (win == 2u) return w2.Load3(off); + return w3.Load3(off); } +[numthreads(64, 1, 1)] +void main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID) { + uint b = gid.x * 48u; + uint count = jobs.Load(b); + uint stride = jobs.Load(b + 4u); + uint offset = jobs.Load(b + 8u); + uint split = jobs.Load(b + 12u); + uint cap = jobs.Load(b + 16u); + uint src_win = jobs.Load(b + 20u); + uint src_off = jobs.Load(b + 24u); + uint dst_off = jobs.Load(b + 28u); + uint has_cnt = jobs.Load(b + 32u); + uint cnt_win = jobs.Load(b + 36u); + uint cnt_off = jobs.Load(b + 40u); + uint live = count; + if (has_cnt != 0u) { + live = min(count, load_u32(cnt_win, cnt_off)); + } + for (uint tid = gtid.x; tid < count; tid += 64u) { + uint s = src_off + tid * stride; + uint d = dst_off + tid * stride; + uint m = d + count * stride; + for (uint i = 0u; i < stride; i += 4u) { + uint w = load_u32(src_win, s + i); + dst.Store(d + i, w); + dst.Store(m + i, w); + } + uint3 g = load_u32x3(src_win, s + offset); + uint n = 0u; + if (tid < live && g.x != 0u && g.y != 0u && g.z != 0u) { + n = min(g.x, cap); + n = g.y > cap / n ? cap : n * g.y; + n = g.z > cap / n ? cap : n * g.z; + } + dst.Store3(d + offset, uint3(n, 1u, 1u)); + dst.Store3(m + offset, uint3(n * split, 1u, 1u)); + } +} +"#; -/// `XCL_TRACE_FRAME` with a watched target (`present::watch_rt`): draws whose descriptor -/// tables name it – that object, or another at its title address (the first 16). -unsafe fn trace_reads_of_watched(this: *mut c_void, pso: usize) { - let Some(w) = super::present::watched_rt() else { return }; - let w_addr = super::real::title_address(w).or_else(|| super::title_textures::address(w)); - let Some(u) = crate::gpu::uma::get() else { return }; - let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.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) as usize; - for k in 0..16usize { - let Some(r) = super::console_heap::resource_at(u.base() + t + 32 * k) else { continue }; - let addr = super::real::title_address(r).or_else(|| super::title_textures::address(r)); - if super::present::is_watched(r) || (addr.is_some() && addr == w_addr) { - let rt = super::present::rt0_resource(this as usize).unwrap_or(0); - // each (source, target, shaders) once - static SEEN: Mutex> = Mutex::new(Vec::new()); - { - let mut g = SEEN.lock().unwrap(); - if g.len() >= 32 || g.contains(&(r, rt, pso)) { - return; +const _: () = assert!(crate::gpu::recomp::MEM_HEAP_BASE == 4); + +/// Descriptor-heap + inline root-constants form of `SCALE_ARGS_HLSL`: reads `src` and `cnt` +/// through the shared descriptor heap's raw window UAVs (`MEM_HEAP_BASE + win`, created with +/// `CreateUnorderedAccessView` on each reserved/committed window buffer so unmapped sparse tiles +/// safely read as zero instead of faulting on a raw root UAV) and passes all scalar parameters +/// inline in `b0` (zero UMA arena allocation). +pub(super) const SCALE_ARGS_HEAP_HLSL: &str = r#"cbuffer Args : register(b0) { + uint count, stride, offset, split, cap, src_slot, src_off, has_cnt, cnt_slot, cnt_off; +}; +RWByteAddressBuffer dst : register(u0); +[numthreads(64, 1, 1)] +void main(uint tid : SV_DispatchThreadID) { + if (tid >= count) return; + RWByteAddressBuffer src = ResourceDescriptorHeap[src_slot]; + uint live = count; + if (has_cnt != 0u) { + RWByteAddressBuffer cnt = ResourceDescriptorHeap[cnt_slot]; + live = min(count, cnt.Load(cnt_off)); + } + uint s = src_off + tid * stride, d = tid * stride, m = d + count * stride; + for (uint i = 0u; i < stride; i += 4u) { + uint w = src.Load(s + i); + dst.Store(d + i, w); + dst.Store(m + i, w); + } + uint3 g = src.Load3(s + offset); + uint n = 0u; + if (tid < live && g.x != 0u && g.y != 0u && g.z != 0u) { + n = min(g.x, cap); + n = g.y > cap / n ? cap : n * g.y; + n = g.z > cap / n ? cap : n * g.z; + } + dst.Store3(d + offset, uint3(n, 1u, 1u)); + dst.Store3(m + offset, uint3(n * split, 1u, 1u)); +} +"#; + +/// Descriptor-heap + inline root-constants form of `GUARD_ARGS_HLSL`. +pub(super) const GUARD_ARGS_HEAP_HLSL: &str = r#"cbuffer Args : register(b0) { + uint src_slot, src_off, most, lim_off; +}; +RWByteAddressBuffer dst : register(u0); +RWByteAddressBuffer lim : register(u1); +[numthreads(1, 1, 1)] +void main() { + RWByteAddressBuffer src = ResourceDescriptorHeap[src_slot]; + uint3 g = src.Load3(src_off); + uint3 out_g = uint3(0u, 0u, 0u); + uint limit = 0u; + if (g.x != 0u && g.y != 0u && g.z != 0u && all(g <= most)) { + if (g.x <= most / g.y) { + if (g.x * g.y <= most / g.z) { + if (g.x > 65535u && g.y == 1u && g.z <= 65535u) { + uint rows = (g.x - 1u) / 65535u + 1u; + if (rows <= 65535u) { + out_g = uint3(65535u, rows, g.z); + limit = g.x; + } else { + out_g = min(g, 65535u.xxx); } - g.push((r, rt, pso)); - } - if !super::present::is_presented(rt) { - super::present::follow(rt); - } - if let Some(dsv) = super::list_x::bound_dsv(this) { - super::list_x::watch_dsv(dsv); + } else { + out_g = min(g, 65535u.xxx); } - let d = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0, d.Flags.0) }); - crate::xlog_info!( - "frame trace: a draw (shaders {:x?}, {}) reads a watched target {r:#x} {:?} at {addr:x?} (slot {k}), drawing into {rt:#x} {:?}{} – {}", - super::real::pso_shaders(super::pso_async::resolve(pso)), - super::list_x::state_summary(this), - d(r), - d(rt), - if super::present::is_presented(rt) { " (presented)" } else { "" }, - root_args_summary(this, 32) - ); - let args = DRAW_ARGS.with(|d| d.get()); - crate::xlog_info!( - "frame trace: … that draw: {args:?} (indexed, count, instances, first, base vertex); input layout [{}]; {}", - super::real::pso_layout(super::pso_async::resolve(pso)).unwrap_or_default(), - super::list_x::geometry_summary(this, args) - ); - return; } } } + dst.Store3(0, out_g); + if (lim_off != 0u) { + lim.Store(lim_off, limit); + } } +"#; -/// `XCL_TRACE_FRAME`: render targets a draw into the watched target samples (a UI library's -/// layers) are dumped with it (`present::follow`). -unsafe fn follow_layer_sources(this: *mut c_void) { - let (Some(w), Some(rt)) = (super::present::watched_rt(), super::present::rt0_resource(this as usize)) else { return }; - if rt != w { - return; - } - let Some(u) = crate::gpu::uma::get() else { return }; - let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.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) as usize; - for k in 0..4usize { - let Some(r) = super::console_heap::resource_at(u.base() + t + 32 * k) else { continue }; - let layer = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).is_some_and(|x| { - let d = x.GetDesc(); - d.Flags.0 & 1 != 0 && d.Width >= 64 && d.Height >= 32 && d.SampleDesc.Count == 1 - }); - if layer && r != w { - super::present::follow(r); +/// Descriptor-heap form of `PRELUDE_GUARD_HLSL` (`ResourceDescriptorHeap[MEM_HEAP_BASE + win]`). +pub(super) const PRELUDE_GUARD_HEAP_HLSL: &str = r#"RWByteAddressBuffer jobs : register(u0); +RWByteAddressBuffer dst : register(u1); +[numthreads(64, 1, 1)] +void main(uint tid : SV_DispatchThreadID) { + uint total = jobs.Load(0); + if (tid >= total) return; + uint b = 16u + tid * 32u; + uint src_win = jobs.Load(b); + uint src_off = jobs.Load(b + 4u); + uint most = jobs.Load(b + 8u); + uint dst_off = jobs.Load(b + 12u); + uint lim_win = jobs.Load(b + 16u); + uint lim_off = jobs.Load(b + 20u); + RWByteAddressBuffer src = ResourceDescriptorHeap[NonUniformResourceIndex(4u + src_win)]; + uint3 g = src.Load3(src_off); + uint3 out_g = uint3(0u, 0u, 0u); + uint limit = 0u; + if (g.x != 0u && g.y != 0u && g.z != 0u && all(g <= most)) { + if (g.x <= most / g.y) { + if (g.x * g.y <= most / g.z) { + if (g.x > 65535u && g.y == 1u && g.z <= 65535u) { + uint rows = (g.x - 1u) / 65535u + 1u; + if (rows <= 65535u) { + out_g = uint3(65535u, rows, g.z); + limit = g.x; + } else { + out_g = min(g, 65535u.xxx); + } + } else { + out_g = min(g, 65535u.xxx); + } } } } + dst.Store3(dst_off, out_g); + if (lim_off != 0xFFFFFFFFu) { + RWByteAddressBuffer lim = ResourceDescriptorHeap[NonUniformResourceIndex(4u + lim_win)]; + lim.Store(lim_off, limit); + } } +"#; -unsafe fn trace_ui_draw(this: *mut c_void, pso: usize) { - trace_draw_kinds(this, pso); - trace_reads_of_watched(this, pso); - follow_layer_sources(this); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - // `XCL_TRACE_MANY=n`: n draws instead of 24 (a whole frame of a UI) - static CAP: std::sync::OnceLock = std::sync::OnceLock::new(); - let cap = *CAP.get_or_init(|| std::env::var("XCL_TRACE_MANY").ok().and_then(|v| v.parse().ok()).unwrap_or(24)); - if N.load(std::sync::atomic::Ordering::Relaxed) >= cap { - return; +/// Descriptor-heap form of `PRELUDE_SCALE_HLSL` (`ResourceDescriptorHeap[MEM_HEAP_BASE + win]`). +pub(super) const PRELUDE_SCALE_HEAP_HLSL: &str = r#"RWByteAddressBuffer jobs : register(u0); +RWByteAddressBuffer dst : register(u1); +[numthreads(64, 1, 1)] +void main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID) { + uint b = gid.x * 48u; + uint count = jobs.Load(b); + uint stride = jobs.Load(b + 4u); + uint offset = jobs.Load(b + 8u); + uint split = jobs.Load(b + 12u); + uint cap = jobs.Load(b + 16u); + uint src_win = jobs.Load(b + 20u); + uint src_off = jobs.Load(b + 24u); + uint dst_off = jobs.Load(b + 28u); + uint has_cnt = jobs.Load(b + 32u); + uint cnt_win = jobs.Load(b + 36u); + uint cnt_off = jobs.Load(b + 40u); + RWByteAddressBuffer src = ResourceDescriptorHeap[NonUniformResourceIndex(4u + src_win)]; + uint live = count; + if (has_cnt != 0u) { + RWByteAddressBuffer cnt = ResourceDescriptorHeap[NonUniformResourceIndex(4u + cnt_win)]; + live = min(count, cnt.Load(cnt_off)); } - let Some(rt) = super::present::rt0_resource(this as usize) else { return }; - let wanted = traced_shaders(); - if wanted.is_empty() { - // draws into a presented target, or – `XCL_TRACE_UI_ANY` – into any target - if super::present::activity().0 < 300 || (!super::present::is_presented(rt) && std::env::var_os("XCL_TRACE_UI_ANY").is_none()) { - return; + for (uint tid = gtid.x; tid < count; tid += 64u) { + uint s = src_off + tid * stride; + uint d = dst_off + tid * stride; + uint m = d + count * stride; + for (uint i = 0u; i < stride; i += 4u) { + uint w = src.Load(s + i); + dst.Store(d + i, w); + dst.Store(m + i, w); } - } else if !super::real::pso_shaders(super::pso_async::resolve(pso)).is_some_and(|(v, p)| wanted.contains(&v) || wanted.contains(&p)) { - return; - } else { - super::present::watch_rt(rt); - } - N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let sh = super::real::pso_shaders(super::pso_async::resolve(pso)).map(|(v, p)| format!("vs {v:016x} ps {p:016x}")); - crate::xlog_info!("frame trace: UI draw (pipeline {pso:#x}, {}): {}", sh.unwrap_or_default(), root_args_summary(this, 16)); - if !wanted.is_empty() { - // the picked shaders' geometry too (vertices dumped at the next present) - let args = DRAW_ARGS.with(|d| d.get()); - crate::xlog_info!( - "frame trace: … that draw: {args:?} (indexed, count, instances, first, base vertex); input layout [{}]; {}", - super::real::pso_layout(super::pso_async::resolve(pso)).unwrap_or_default(), - super::list_x::geometry_summary(this, args) - ); + uint3 g = src.Load3(s + offset); + uint n = 0u; + if (tid < live && g.x != 0u && g.y != 0u && g.z != 0u) { + n = min(g.x, cap); + n = g.y > cap / n ? cap : n * g.y; + n = g.z > cap / n ? cap : n * g.z; + } + dst.Store3(d + offset, uint3(n, 1u, 1u)); + dst.Store3(m + offset, uint3(n * split, 1u, 1u)); } } +"#; -/// 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 { - let Some(u) = crate::gpu::uma::get() else { return String::new() }; - let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); - let Some(layout) = layout else { return String::new() }; - let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); - let mut what = Vec::new(); - for (i, p) in layout.params.iter().enumerate() { - match *p { - Param::Constants { at, count } => what.push(format!("p{i} constants {:x?}", (0..count.min(8) as usize).map(|k| word(at as usize + 4 * k)).collect::>())), - Param::Descriptor { at } => { - let va = (word(at as usize) as u64 | (word(at as usize + 4) as u64) << 32) as usize; - let w: Vec = if va != 0 && crate::gpu::shader::readable(va, 4 * buffer_words) { (0..buffer_words).map(|k| ((va + 4 * k) as *const u32).read_unaligned()).collect() } else { Vec::new() }; - what.push(format!("p{i} buffer {va:#x} {w:x?}")); - } - Param::Table { at } => { - let t = word(at as usize) as usize; - let slots: Vec = (0..4usize) - .map(|k| { - let at = u.base() + t + 32 * k; - let w = super::console_heap::words_at((t + 32 * k) as u32); - match super::console_heap::resource_at(at) { - Some(r) => { - if super::title_textures::address(r).is_some() { - super::title_textures::probe_gpu_content(r); - } - let d = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| x.GetDesc()); - format!("[{k}] {r:#x} {:?} title {:?} T# {:x?}", d.map(|d| (d.Dimension.0, d.Width, d.Height, d.Format.0)), super::title_textures::address(r).map(|a| format!("{a:#x}")), w.map(|w| w[..4].to_vec())) - } - None => format!("[{k}] - T# {:x?}", w.map(|w| w[..4].to_vec())), - } - }) - .collect(); - what.push(format!("p{i} table {t:#x}: {}", slots.join(", "))); - } - } +/// `XCL_INDIRECT_PRELUDE=0`: run indirect argument clamp/scale passes inline instead of hoisting +/// them into a batched prelude command list submitted right before the recording. +fn indirect_prelude_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_INDIRECT_PRELUDE").map_or(true, |v| v.trim() != "0")) +} + +/// Top byte bound of a raw window UAV created by `runner::raw_window_uav`. +const RAW_WINDOW_UAV_MAX: usize = (1usize << 32) - 32; + +/// Map a 4-byte-aligned UMA host address + byte span to `(heap_slot, byte_offset)` within the +/// shared descriptor heap's window UAVs (`MEM_HEAP_BASE + win`), respecting `raw_window_uav`'s +/// 32-byte top margin on 4 GiB windows. +fn uma_heap_slot_off(u: &crate::gpu::uma::Uma, p: usize, span: usize) -> Option<(u32, u32)> { + if p % 4 != 0 || span == 0 { + return None; } - what.join("; ") + let k = u.window_of(p)?; + if k >= crate::gpu::uma::MAX_HEAP_WINDOWS { + return None; + } + let (base, size) = u.window(k); + let off = p.checked_sub(base)?; + let end = off.checked_add(span)?; + if end > size.min(RAW_WINDOW_UAV_MAX) { + return None; + } + Some((crate::gpu::recomp::MEM_HEAP_BASE + k as u32, off as u32)) } -/// #33 SetComputeRootSignature (PC #29) -pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_void, rs: *mut c_void) { - 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)]; - s.layout = layout; - }); +/// Map a 4-byte-aligned UMA host address + byte span to `(window_index, byte_offset)` for +/// prelude jobs (up to `MAX_HEAP_WINDOWS` when shared heap window views are active, else 4). +fn uma_win_off(u: &crate::gpu::uma::Uma, p: usize, span: usize) -> Option<(u32, u32)> { + if p % 4 != 0 || span == 0 { + return None; + } + let k = u.window_of(p)?; + let heap_mode = super::console_heap::window_views_ready(); + let max_wins = if heap_mode { crate::gpu::uma::MAX_HEAP_WINDOWS } else { 4 }; + if k >= max_wins { + return None; + } + let (base, size) = u.window(k); + let off = p.checked_sub(base)?; + let end = off.checked_add(span)?; + let limit = if heap_mode { size.min(RAW_WINDOW_UAV_MAX) } else { size.min(u32::MAX as usize) }; + if end > limit { + return None; + } + Some((k as u32, off as u32)) } -/// #35 SetComputeRootDescriptorTable (PC #31): the table's console address, 32 bits -pub(super) unsafe extern "system" fn set_compute_root_table(this: *mut c_void, i: u32, handle: u64) { - put(this, i, 0, &(handle as u32).to_le_bytes()); +fn can_hoist_prelude(this: *mut c_void) -> bool { + indirect_prelude_on() + && super::title_list::wrapper_of(this).is_some() + && matches!( + super::list_x::tracked_list_type(this), + Some(D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE) + ) + && with(this, |s| !s.prelude_blocked && s.allocator != 0 && s.prelude_built.is_none()) } -/// #37 SetComputeRoot32BitConstant (PC #33) -pub(super) unsafe extern "system" fn set_compute_root_constant(this: *mut c_void, i: u32, value: u32, offset: u32) { - put(this, i, offset, &value.to_le_bytes()); +unsafe fn prelude_root_signature(dev: &ID3D12Device) -> Result { + let params: [D3D12_ROOT_PARAMETER1; 6] = std::array::from_fn(|reg| D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: reg as u32, + RegisterSpace: 0, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + 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!("prelude root signature serialize: {e}"))?; + let blob = blob.ok_or("prelude root signature blob")?; + dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())) + .map_err(|e| format!("prelude root signature create: {e}")) } -/// #39 SetComputeRoot32BitConstants (PC #35) -pub(super) unsafe extern "system" fn set_compute_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { - if !data.is_null() { - let bytes: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); - put(this, i, offset, &bytes); +unsafe fn prelude_pipeline(dev: &ID3D12Device, hlsl: &str, label: &str, cache: &'static ArgsPipelines) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let key = dev.as_raw() as usize; + if let Some(pair) = cache.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(pair); } + let dxil = crate::gpu::recomp::dxc::compile_cached(hlsl, "main", "cs_6_6")?.0; + let rs = prelude_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() }, + ..Default::default() + }; + let res_pso: Result = dev.CreateComputePipelineState(&cdesc); + std::mem::ManuallyDrop::drop(&mut cdesc.pRootSignature); + let pso = res_pso.map_err(|e| format!("{label} pso create: {e}"))?; + let _ = pso.SetName(&windows::core::HSTRING::from(label)); + super::dred::label_text(pso.as_raw() as usize, || label.to_string()); + cache.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); + Ok((rs, pso)) } -/// #41 / #43 / #45 SetComputeRoot{ConstantBuffer,ShaderResource,UnorderedAccess}View (PC #37 / -/// #39 / #41): the 64-bit GPU address -pub(super) unsafe extern "system" fn set_compute_root_descriptor(this: *mut c_void, i: u32, va: u64) { - note_address(va); - put(this, i, 0, &va.to_le_bytes()); +unsafe fn prelude_guard_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + prelude_pipeline(dev, PRELUDE_GUARD_HLSL, PRELUDE_GUARD_DRED_LABEL, &CACHE) } -/// #25 SetPipelineState: noted, then bound as on the PC -pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: *mut c_void) { - with(this, |s| s.pso = pso as usize); - super::real::bind_pipeline(this, pso); +unsafe fn prelude_scale_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + prelude_pipeline(dev, PRELUDE_SCALE_HLSL, PRELUDE_SCALE_DRED_LABEL, &CACHE) } -/// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments -pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { - let pso = with(this, |s| s.pso); - if super::pso_async::is_pending(pso) && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z)) { - return super::pso_async::need_by_submit(pso); - } - let pso = super::pso_async::resolve_wait(pso); - let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; - if !super::real::is_translated_compute(pso) { - // a console pipeline without a translation (including a background build that - // failed): nothing to run (its root arguments were not given to the PC list either) - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: Dispatch with a pipeline that has no translated console shader ({pso:#x}) skipped"); - } - count(DISPATCHES_SKIPPED); - return; - } - match translated_dispatch(this, list, pso, x, y, z) { - Ok(()) => count(DISPATCHES), - Err(e) => { - count(DISPATCHES_SKIPPED); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: Dispatch with a translated pipeline skipped: {e}"); - } - } - } +unsafe fn prelude_draw_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + prelude_pipeline(dev, PRELUDE_DRAW_GUARD_HLSL, PRELUDE_DRAW_DRED_LABEL, &CACHE) } -/// `XCL_TRACE_FRAME`: a full-screen dispatch (enough groups to cover a 4K target in tiles of up -/// to 128 pixels) – what its root arguments say. A bindless title passes the indices of its -/// descriptors in root constants and constant buffers: every small value there is looked up -/// in the dispatch's descriptor tables, and the resources found (the pass's inputs and -/// outputs) are logged. -unsafe fn trace_fullscreen(this: *mut c_void, pso: usize, groups: [u32; 3]) { - if groups[0] < 30 || groups[1] < 17 { - 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 }; - static SEEN: Mutex> = Mutex::new(Vec::new()); - { - let mut g = SEEN.lock().unwrap(); - if g.contains(&pso) || g.len() >= 12 { - return; - } - g.push(pso); - } - let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); - let mut tables: Vec = Vec::new(); - let mut values: Vec = Vec::new(); - let mut what: Vec = Vec::new(); - for (i, p) in layout.params.iter().enumerate() { - match *p { - Param::Constants { at, count } => { - let w: Vec = (0..count as usize).filter_map(|k| word(at as usize + 4 * k)).collect(); - what.push(format!("p{i} constants {w:x?}")); - values.extend(&w); - } - 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; - let n = 64usize; - if va != 0 && crate::gpu::shader::readable(va, 4 * n) { - let w: Vec = (0..n).map(|k| ((va + 4 * k) as *const u32).read_unaligned()).collect(); - what.push(format!("p{i} buffer {va:#x}: {w:x?}")); - values.extend(&w); - } else { - what.push(format!("p{i} buffer {va:#x} (not readable)")); - } - } - Param::Table { at } => { - let v = word(at as usize).unwrap_or(0); - what.push(format!("p{i} table {v:#x}")); - tables.push(v); - } - } - } - let mut found: Vec<(u32, usize)> = Vec::new(); - for &v in &values { - if v >= 1 << 20 { - continue; - } - for &t in &tables { - let slot = u.base() + t as usize + 32 * v as usize; - if let Some(r) = super::console_heap::resource_at(slot) { - if !found.iter().any(|x| x.1 == r) { - found.push((v, r)); - } - } - } - } - let res: Vec = found - .iter() - .map(|&(v, r)| { - let d = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| x.GetDesc()); - format!("[{v}] {r:#x} {:?}{}", d.map(|d| (d.Dimension.0, d.Width, d.Height, d.Format.0)), if super::present::is_presented(r) { " PRESENTED" } else { "" }) - }) - .collect(); - crate::xlog_info!("frame trace: full-screen dispatch {groups:?}, pipeline {pso:#x}: {}", what.join("; ")); - crate::xlog_info!("frame trace: … its indices name: {}", if res.is_empty() { "nothing".to_string() } else { res.join("; ") }); +unsafe fn prelude_heap_root_signature(dev: &ID3D12Device) -> Result { + let params: [D3D12_ROOT_PARAMETER1; 2] = std::array::from_fn(|reg| D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: reg as u32, + RegisterSpace: 0, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + 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_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED, + }, + }, + }; + let mut blob: Option = None; + D3D12SerializeVersionedRootSignature(&desc, &mut blob, None).map_err(|e| format!("prelude heap root signature serialize: {e}"))?; + let blob = blob.ok_or("prelude heap root signature blob")?; + dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())) + .map_err(|e| format!("prelude heap root signature create: {e}")) } -/// #148 AllocateUploadMemory(size, alignment) → CPU/GPU pointer in unified memory (used by -/// `XboxBvhBuilder.dll` and other console middleware on default title command lists). -/// Freed automatically when the list's command allocator is reset. -pub(super) unsafe extern "system" fn allocate_upload_memory(this: *mut c_void, size: usize, align: usize) -> *mut u8 { - let Some(u) = crate::gpu::uma::get() else { - return std::ptr::null_mut(); - }; - let size = size.max(16); - 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)) { - return p; - } - } - if u.has_sparse() { - if let Some((p, _)) = super::sparse::alloc(size, align) { - with(this, |s| s.uma.push(p)); - return p as *mut u8; - } - } - match u.alloc(size, align) { - Some(p) => { - with(this, |s| s.uma.push(p as usize)); - p - } - None => std::ptr::null_mut(), +unsafe fn prelude_heap_pipeline(dev: &ID3D12Device, hlsl: &str, label: &str, cache: &'static ArgsPipelines) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let key = dev.as_raw() as usize; + if let Some(pair) = cache.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(pair); } + let dxil = crate::gpu::recomp::dxc::compile_cached(hlsl, "main", "cs_6_6")?.0; + let rs = prelude_heap_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() }, + ..Default::default() + }; + let res_pso: Result = dev.CreateComputePipelineState(&cdesc); + std::mem::ManuallyDrop::drop(&mut cdesc.pRootSignature); + let pso = res_pso.map_err(|e| format!("{label} heap pso create: {e}"))?; + let _ = pso.SetName(&windows::core::HSTRING::from(label)); + super::dred::label_text(pso.as_raw() as usize, || label.to_string()); + cache.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); + Ok((rs, pso)) } -unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, x: u32, y: u32, z: u32) -> Result<(), String> { - if super::present::trace_frame() { - trace_fullscreen(this, pso, [x, y, z]); - } - bind_abi(this, list, pso, false)?; - super::real::dispatch_chain::dispatch(list, pso, with(this, |s| s.allocator), [x, y, z]) +unsafe fn prelude_guard_heap_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + prelude_heap_pipeline(dev, PRELUDE_GUARD_HEAP_HLSL, PRELUDE_GUARD_DRED_LABEL, &CACHE) } -/// XCL's ABI for a translated pipeline: its root signature, the user SGPRs (`io`, the kept -/// arguments the console's way – compute or graphics) and the argument table in unified -/// memory, u1 res, u2… the memory windows; then the pipeline. -unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> { - super::list_x::ensure_view_heap(this); - let u = crate::gpu::uma::get().ok_or("no unified memory")?; - let windows = super::real::uma_window_vas(); - let first = *windows.first().ok_or("unified memory is not open on the GPU")?; - let (layout, args) = with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) }); - // 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("unified memory is full")?; - std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); - Ok(p as usize) - }; - // a pipeline still being built in the background is waited for - let real = super::pso_async::resolve_wait(pso); - // a compute shader takes no more arguments from registers than it has (`inline_for`) - let user_sgprs = if gfx { None } else { super::real::pso_user_sgprs(real) }; - let inline = layout.as_ref().map_or(0, |l| if gfx { l.inline_gfx } else { console_list::inline_for(l, user_sgprs) } as usize).min(args.len()); - let table_at = copy(&args[inline..])?; - let mut io = match layout.as_ref() { - Some(l) if gfx => console_list::user_data_gfx(l, &args, table_at as u64), - Some(l) => console_list::user_data_for(l, user_sgprs, &args, table_at as u64), - None => vec![table_at as u32, (table_at >> 32) as u32], - }; - io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); - io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; - let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; - let res_at = copy(&[0u8; 256])?; - let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); - let rs = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?; - let rs = rs as *mut c_void; - let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?; - let views = [va(io_at), va(res_at)].into_iter().chain((0..4).map(|k| windows.get(k).copied().filter(|&v| v != 0).unwrap_or(first))); - if gfx { - list.SetGraphicsRootSignature(rs); - for (k, v) in views.enumerate() { - list.SetGraphicsRootUnorderedAccessView(k as u32, v); - } - } else { - list.SetComputeRootSignature(rs); - for (k, v) in views.enumerate() { - list.SetComputeRootUnorderedAccessView(k as u32, v); - } - } - let real = real as *mut c_void; - let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; - list.SetPipelineState(pc); - Ok(()) +unsafe fn prelude_scale_heap_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + prelude_heap_pipeline(dev, PRELUDE_SCALE_HEAP_HLSL, PRELUDE_SCALE_DRED_LABEL, &CACHE) } -#[cfg(test)] -pub(super) fn last_draw_args() -> (bool, u32, u32, u32, i32) { - DRAW_ARGS.with(|d| d.get()) +unsafe fn prelude_draw_heap_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + prelude_heap_pipeline(dev, PRELUDE_DRAW_GUARD_HEAP_HLSL, PRELUDE_DRAW_DRED_LABEL, &CACHE) } -#[cfg(test)] -pub(super) fn counts_snapshot() -> [u64; 5] { - std::array::from_fn(|k| COUNTS[k].load(Ordering::Relaxed)) +unsafe fn guard_draw_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + args_pipeline(dev, GUARD_DRAW_ARGS_HLSL, GUARD_DRAW_DRED_LABEL, false, &CACHE) } -#[cfg(test)] -pub(super) fn tracked_pso(list: *mut c_void) -> usize { - STATES - .lock() - .unwrap() - .as_ref() - .and_then(|m| m.get(&(list as usize))) - .map_or(0, |s| s.pso) +unsafe fn guard_draw_heap_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + heap_args_pipeline(dev, GUARD_DRAW_ARGS_HEAP_HLSL, GUARD_DRAW_DRED_LABEL, 5, &[0], &CACHE) } -#[cfg(test)] -mod tests { - use super::super::{device_x, list_x, pso_async, real, title_list}; - use super::*; - use std::sync::atomic::AtomicUsize; +/// `XCL_INDIRECT_DRAW_GUARD=0`: skip indirect Draw/DrawIndexed vertex-count clamping. +fn indirect_draw_guard() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_INDIRECT_DRAW_GUARD").map_or(true, |v| v.trim() != "0")) +} - /// A pipeline with the rect list GS draws its rect lists whole: draw_rects leaves them alone. - #[test] - fn rect_lists_with_the_rect_list_gs_are_not_expanded_on_the_cpu() { - let (with_gs, without) = (0x7E57_4000usize, 0x7E57_5000usize); - real::register_rect_list_gs_for_test(with_gs); - assert!(!cpu_rect_expansion(with_gs)); - assert!(cpu_rect_expansion(without) && cpu_rect_expansion(0)); - real::forget_pso_for_test(with_gs); - assert!(cpu_rect_expansion(with_gs)); +/// Allocate `bytes` in `State::prelude_scratch` (disjoint from inline ping-pong scratch so the +/// prelude leaves these buffers in `INDIRECT_ARGUMENT` for the entire main segment). +unsafe fn alloc_prelude_scratch(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, u64, usize), String> { + let bytes = bytes.next_multiple_of(256); + if let Some(r) = with(this, |s| { + let sl = &mut s.prelude_scratch; + let (b, cap, _) = sl.buf.as_ref()?; + (sl.used + bytes <= *cap).then(|| { + sl.used += bytes; + (b.clone(), sl.used - bytes, sl.buf_idx) + }) + }) { + return Ok(r); } - - /// An ExecuteIndirect whose bound pipeline is still being built is skipped (its stand-in - /// with XCL's ABI root signature on the list is the debug layer's 953 and a hung GPU); + let size = bytes.max(SCRATCH_BLOCK); + let cap = scratch_cap(); + let remaining = cap.saturating_sub(with(this, |s| s.scratch_taken)); + if size > remaining { + return Err(format!("its rewritten arguments are past {} MiB this recording", cap >> 20)); + } + let dev_key = dev.as_raw() as usize; + let picked = { + let mut free = FREE_RES.lock().unwrap(); + free.iter().position(|(_, cap, d)| *d == dev_key && *cap >= size && *cap <= remaining).map(|i| free.swap_remove(i)) + }; + let block = match picked { + Some(e) => e, + None => (default_uav_buffer(dev, size, "prelude indirect argument scratch")?, size, dev_key), + }; + let b = block.0.clone(); + let buf_idx = with(this, |s| { + let idx = s.prelude_bufs.len(); + s.scratch_taken += block.1; + s.prelude_bufs.push(b.clone()); + s.prelude_scratch = PreludeScratchSlot { + buf: Some(block.clone()), + used: bytes, + buf_idx: idx, + }; + s.res_retired.push(block); + idx + }); + Ok((b, 0, buf_idx)) +} + +/// Build (once per recording) and return the closed PC prelude command list that runs all VRAM +/// `io` (`u0`) uploads and hoisted indirect-argument clamp/scale jobs for `seg` before `seg` +/// executes on the queue. +pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { + let (already, io_copies, bufs, guards, scales, draws) = with(seg, |s| { + if let Some(ref built) = s.prelude_built { + return (Some(built.as_raw()), Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); + } + let io_copies: Vec<(ID3D12Resource, ID3D12Resource, u64)> = s + .io_blocks + .iter() + .filter(|b| b.used > 0) + .map(|b| (b.vram.clone(), b.upload.clone(), b.used)) + .collect(); + if io_copies.is_empty() && s.prelude_guards.is_empty() && s.prelude_scales.is_empty() && s.prelude_draws.is_empty() { + return (None, Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); + } + (None, io_copies, s.prelude_bufs.clone(), s.prelude_guards.clone(), s.prelude_scales.clone(), s.prelude_draws.clone()) + }); + if let Some(p) = already { + return Some(p); + } + if io_copies.is_empty() && guards.is_empty() && scales.is_empty() && draws.is_empty() { + return None; + } + let run = (|| -> Result { + let dev = super::real::list_device(seg).ok_or("no device for prelude list")?; + let ty = super::list_x::tracked_list_type(seg).ok_or("no list type for prelude list")?; + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return Err("unsupported list type for prelude".into()); + } + + let dev_key = dev.as_raw() as usize; + let reused = { + let mut free = FREE_PRELUDE.lock().unwrap(); + free.iter().position(|e| e.2 == dev_key && e.3 == ty.0).map(|i| free.swap_remove(i)) + }; + let (alloc, list) = match reused { + Some((a, l, _, _)) => { + a.Reset().map_err(|e| format!("prelude allocator reset: {e}"))?; + l.Reset(&a, None).map_err(|e| format!("prelude list reset: {e}"))?; + (a, l) + } + None => { + let a: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).map_err(|e| format!("prelude allocator create: {e}"))?; + let _ = a.SetName(windows::core::w!("xcl prelude alloc")); + let l: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &a, None).map_err(|e| format!("prelude list create: {e}"))?; + let _ = l.SetName(windows::core::w!("xcl prelude")); + (a, l) + } + }; + + // 0. Upload all VRAM `io` (`u0`) slabs (`UNORDERED_ACCESS -> COPY_DEST -> CopyBufferRegion + // -> UNORDERED_ACCESS`) so `seg`'s shaders read user SGPRs from L1 VRAM. + if !io_copies.is_empty() { + let mut to_copy: Vec = Vec::with_capacity(io_copies.len()); + let mut to_uav: Vec = Vec::with_capacity(io_copies.len()); + for (vram, _, _) in &io_copies { + to_copy.push(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::ManuallyDrop::new(Some(vram.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + StateAfter: D3D12_RESOURCE_STATE_COPY_DEST, + }), + }, + }); + to_uav.push(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::ManuallyDrop::new(Some(vram.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_COPY_DEST, + StateAfter: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + }), + }, + }); + } + list.ResourceBarrier(&to_copy); + for (vram, upload, used) in &io_copies { + list.CopyBufferRegion(vram, 0, upload, 0, *used); + } + list.ResourceBarrier(&to_uav); + for b in to_copy.iter_mut().chain(to_uav.iter_mut()) { + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); + } + } + + if !guards.is_empty() || !scales.is_empty() || !draws.is_empty() { + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let win_vas = with(seg, |s| -> Result<[u64; 4], String> { + if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { + let w = super::real::uma_window_vas(); + if w.is_empty() { + return Err("unified memory is not open on the GPU".into()); + } + s.uma_windows = Some(w); + } + let w = s.uma_windows.as_deref().unwrap(); + let first = w.iter().copied().find(|&v| v != 0).ok_or("unified memory is not open on the GPU")?; + Ok([ + first, + w.get(1).copied().filter(|&v| v != 0).unwrap_or(first), + w.get(2).copied().filter(|&v| v != 0).unwrap_or(first), + w.get(3).copied().filter(|&v| v != 0).unwrap_or(first), + ]) + })?; + + // 1. Order prior queue writes into UMA and transition all prelude scratch buffers COMMON -> UAV. + let mut pre_barriers: Vec = Vec::with_capacity(1 + bufs.len()); + pre_barriers.push(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) }), + }, + }); + for b in &bufs { + pre_barriers.push(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::ManuallyDrop::new(Some(b.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_COMMON, + StateAfter: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + }), + }, + }); + } + list.ResourceBarrier(&pre_barriers); + for b in pre_barriers.iter_mut().skip(1) { + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); + } + + // Helper to upload a packed `u32` job slice into `seg`'s UMA arena, falling back to a + // dedicated non-pooled CUSTOM write-back L0 buffer when committed unified memory is full + // so the prelude never fails and leaves `seg` running with stale VRAM io / unguarded args. + let upload_words = |words: &[u32]| -> Result { + let bytes = std::mem::size_of_val(words); + if let Some(p) = with(seg, |s| s.arena.take(u, bytes.max(16), 256, &mut s.uma)) { + std::ptr::copy_nonoverlapping(words.as_ptr().cast::(), p, bytes); + return super::real::uma_va_of(p as usize).ok_or_else(|| "unified memory is not open on the GPU".into()); + } + let alloc_bytes = (bytes.max(16) as u64).next_multiple_of(256); + if alloc_bytes > JOB_BLOCK_BYTES { + return Err(format!("a prelude job table of {bytes} B is larger than a job block")); + } + // a fresh block when the last one has no room (made outside the state lock: its + // creation goes through the device's hooks) + let fits = with(seg, |s| s.prelude_job_bufs.last().is_some() && s.prelude_job_used + alloc_bytes <= JOB_BLOCK_BYTES); + if !fits { + let block = job_block(&dev)?; + with(seg, |s| { + s.prelude_job_bufs.push(block); + s.prelude_job_used = 0; + }); + } + let (cpu, va) = with(seg, |s| { + let b = s.prelude_job_bufs.last().expect("a job block"); + let at = s.prelude_job_used; + s.prelude_job_used += alloc_bytes; + (b.cpu + at as usize, b.va + at) + }); + std::ptr::copy_nonoverlapping(words.as_ptr().cast::(), cpu as *mut u8, bytes); + Ok(va) + }; + + let bind_windows = |list: &ID3D12GraphicsCommandList| { + for (k, &va) in win_vas.iter().enumerate() { + list.SetComputeRootUnorderedAccessView((2 + k) as u32, va); + } + }; + + let shared_heap = super::console_heap::window_views_ready().then(super::console_heap::global_heap).flatten(); + if let Some(ref heap) = shared_heap { + list.SetDescriptorHeaps(&[Some(heap.clone())]); + } + + // 2. Emit batched guard dispatches grouped by prelude scratch buffer. + if !guards.is_empty() { + let (rs, pso) = if shared_heap.is_some() { prelude_guard_heap_pipeline(&dev)? } else { prelude_guard_pipeline(&dev)? }; + list.SetComputeRootSignature(&rs); + if shared_heap.is_none() { + bind_windows(&list); + } + list.SetPipelineState(&pso); + for (buf_idx, buf) in bufs.iter().enumerate() { + let batch: Vec<&PreludeGuardJob> = guards.iter().filter(|j| j.buf_idx == buf_idx).collect(); + if batch.is_empty() { + continue; + } + let dst_va = buf.GetGPUVirtualAddress(); + list.SetComputeRootUnorderedAccessView(1, dst_va); + for chunk in batch.chunks(65_535 * 64) { + let mut words = Vec::with_capacity(4 + chunk.len() * 8); + words.extend_from_slice(&[chunk.len() as u32, 0, 0, 0]); + for j in chunk { + words.extend_from_slice(&[j.src_win, j.src_off, j.most, j.dst_off, j.lim_win, j.lim_off, 0, 0]); + } + let jobs_va = upload_words(&words)?; + list.SetComputeRootUnorderedAccessView(0, jobs_va); + list.Dispatch((chunk.len() as u32).div_ceil(64), 1, 1); + } + } + } + + // 3. Emit batched scale dispatches grouped by prelude scratch buffer. + if !scales.is_empty() { + let (rs, pso) = if shared_heap.is_some() { prelude_scale_heap_pipeline(&dev)? } else { prelude_scale_pipeline(&dev)? }; + list.SetComputeRootSignature(&rs); + if shared_heap.is_none() { + bind_windows(&list); + } + list.SetPipelineState(&pso); + for (buf_idx, buf) in bufs.iter().enumerate() { + let batch: Vec<&PreludeScaleJob> = scales.iter().filter(|j| j.buf_idx == buf_idx).collect(); + if batch.is_empty() { + continue; + } + let dst_va = buf.GetGPUVirtualAddress(); + list.SetComputeRootUnorderedAccessView(1, dst_va); + for chunk in batch.chunks(65_535) { + let mut words = Vec::with_capacity(chunk.len() * 12); + for j in chunk { + words.extend_from_slice(&[ + j.count, j.stride, j.mesh_offset, j.split, j.cap, j.src_win, j.src_off, j.dst_off, j.has_cnt, j.cnt_win, j.cnt_off, 0, + ]); + } + let jobs_va = upload_words(&words)?; + list.SetComputeRootUnorderedAccessView(0, jobs_va); + list.Dispatch(chunk.len() as u32, 1, 1); + } + } + } + + // 3b. Emit batched indirect draw-guard dispatches grouped by prelude scratch buffer. + if !draws.is_empty() { + let (rs, pso) = if shared_heap.is_some() { prelude_draw_heap_pipeline(&dev)? } else { prelude_draw_pipeline(&dev)? }; + list.SetComputeRootSignature(&rs); + if shared_heap.is_none() { + bind_windows(&list); + } + list.SetPipelineState(&pso); + for (buf_idx, buf) in bufs.iter().enumerate() { + let batch: Vec<&PreludeDrawJob> = draws.iter().filter(|j| j.buf_idx == buf_idx).collect(); + if batch.is_empty() { + continue; + } + let dst_va = buf.GetGPUVirtualAddress(); + list.SetComputeRootUnorderedAccessView(1, dst_va); + for chunk in batch.chunks(65_535) { + let mut words = Vec::with_capacity(chunk.len() * 8); + for j in chunk { + words.extend_from_slice(&[j.count, j.stride, j.draw_offset, j.src_win, j.src_off, j.dst_off, 0, 0]); + } + let jobs_va = upload_words(&words)?; + list.SetComputeRootUnorderedAccessView(0, jobs_va); + list.Dispatch(chunk.len() as u32, 1, 1); + } + } + } + + // 4. Transition all prelude scratch buffers UAV -> GUARDED_ARGS_STATE (plus global UAV + // barrier if any guard jobs wrote `IO_GROUP_LIMIT` into UMA). + let mut post_barriers: Vec = Vec::with_capacity(bufs.len() + usize::from(!guards.is_empty())); + for b in &bufs { + post_barriers.push(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::ManuallyDrop::new(Some(b.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + StateAfter: GUARDED_ARGS_STATE, + }), + }, + }); + } + if !guards.is_empty() { + post_barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }), + }, + }); + } + list.ResourceBarrier(&post_barriers); + for b in post_barriers.iter_mut().take(bufs.len()) { + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); + } + } + + list.Close().map_err(|e| format!("prelude list close: {e}"))?; + with(seg, |s| { + s.prelude_owned = Some((alloc, list.clone(), dev_key, ty.0)); + s.prelude_built = Some(list.clone()); + }); + if !guards.is_empty() || !scales.is_empty() || !draws.is_empty() { + static BATCHES: AtomicU64 = AtomicU64::new(0); + static TOTAL_JOBS: AtomicU64 = AtomicU64::new(0); + let n_jobs = (guards.len() + scales.len() + draws.len()) as u64; + let b = BATCHES.fetch_add(1, Ordering::Relaxed) + 1; + let tot = TOTAL_JOBS.fetch_add(n_jobs, Ordering::Relaxed) + n_jobs; + if b == 1 || (b.is_power_of_two() && b >= 16) { + crate::xlog_info!("D3D12.X: indirect prelude batch #{b} ({} guard + {} scale + {} draw jobs, {tot} hoisted total)", guards.len(), scales.len(), draws.len()); + } + } + if !io_copies.is_empty() { + static IO_BATCHES: AtomicU64 = AtomicU64::new(0); + let b = IO_BATCHES.fetch_add(1, Ordering::Relaxed) + 1; + if b == 1 || (b.is_power_of_two() && b >= 1024) { + let bytes: u64 = io_copies.iter().map(|(_, _, n)| *n).sum(); + crate::xlog_info!("D3D12.X: VRAM io (u0) prelude upload #{b} ({} slabs, {bytes} B)", io_copies.len()); + } + } + Ok(list) + })(); + match run { + Ok(l) => Some(l.as_raw()), + Err(e) => { + 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: indirect prelude build failed: {e}"); + } + None + } + } +} + +/// State left on guarded indirect argument scratch buffers: valid for both `ExecuteIndirect` +/// and `pso::record_slicer` SRV reads (pure read-only state that decays cleanly to COMMON). +const GUARDED_ARGS_STATE: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATES( + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT.0 | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE.0, +); + +/// The groups of an indirect dispatch above which they are not the title's (`GUARD_ARGS_HLSL`): +/// a 4K target in groups of 2x2 pixels is 2.1 million. +const MOST_GROUPS: u32 = 1 << 22; + +/// local: `XCL_INDIRECT_MOST_GROUPS` instead of `MOST_GROUPS` +fn most_groups() -> u32 { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_INDIRECT_MOST_GROUPS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(MOST_GROUPS)) +} + +/// 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 < 256 || va % 4 != 0 { + return Err(format!("invalid indirect buffer address {va:#x}")); + } + Ok((va & !255, (va & 255) as u32)) +} + +/// Resolve an optional auxiliary root UAV address (`u4`: count buffer in `SCALE_ARGS_HLSL`, +/// group-limit buffer in `GUARD_ARGS_HLSL`), guaranteeing a valid non-null GPU VA by falling +/// back to `fallback_va` whenever `primary_va` is `None` or `Some(0)` so drivers never +/// speculatively fetch from GPU VA `0x0`. +fn resolve_aux_uav_va(primary_va: Option, fallback_va: u64) -> Result { + match primary_va.filter(|&va| va != 0) { + Some(va) => Ok(va), + None if fallback_va != 0 => Ok(fallback_va), + None => Err("missing valid non-null fallback GPU VA for auxiliary root UAV (u4)".into()), + } +} + +/// Validate `SCALE_ARGS_HLSL`'s command-buffer layout and return the source byte span (`max * stride`). +fn validate_scale_args_layout(max: u32, stride: u32, mesh_offset: u32) -> Result { + if max == 0 { + return Err("zero indirect commands".into()); + } + if stride == 0 || stride % 4 != 0 { + return Err(format!("invalid indirect command stride {stride}")); + } + if mesh_offset % 4 != 0 || mesh_offset.checked_add(12).is_none_or(|end| end > stride) { + return Err(format!("invalid DispatchMesh argument offset {mesh_offset} for stride {stride}")); + } + 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) +} + +unsafe fn guard_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: Mutex>> = Mutex::new(None); + args_pipeline(dev, GUARD_ARGS_HLSL, GUARD_ARGS_DRED_LABEL, true, &CACHE) +} + +unsafe fn guard_indirect_heap_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + heap_args_pipeline(dev, GUARD_ARGS_HEAP_HLSL, GUARD_ARGS_DRED_LABEL, 4, &[0, 1], &CACHE) +} + +/// `XCL_INDIRECT_GUARD=0`: indirect dispatches run the groups memory holds, whatever they are. +fn indirect_guard() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_INDIRECT_GUARD").map_or(true, |v| v.trim() != "0")) +} + +/// The arguments of one indirect dispatch at UMA address `src`, checked and >65 535 X-folded +/// (`GUARD_ARGS_HLSL`): writes the guarded/folded `(x, y, z)` to scratch (`INDIRECT_ARGUMENT`) +/// and writes `IO_GROUP_LIMIT` into `dispatch_io_va`. When no prior GPU write or cross-queue +/// wait occurred in this segment, hoists the guard into the segment's batched prelude list so +/// the main list avoids inline compute/barrier bubbles; otherwise runs inline. +unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandList, src: usize, dispatch_io_va: u64, dispatch_io_host: usize) -> Result<(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 dev = super::real::list_device(this).ok_or("no device")?; + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + super::real::uma_window_buffer(src, 12).ok_or("the indirect arguments are not in one memory window")?; + if can_hoist_prelude(this) { + if let (Some((src_win, src_off)), Some((lim_win, lim_off))) = ( + uma_win_off(u, src, 12), + uma_win_off(u, dispatch_io_host + crate::gpu::recomp::IO_GROUP_LIMIT * 4, 4), + ) { + let (dst, dst_off, buf_idx) = alloc_prelude_scratch(this, &dev, 256)?; + if let Ok(dst_off32) = u32::try_from(dst_off) { + with(this, |s| { + s.prelude_guards.push(PreludeGuardJob { + buf_idx, + dst_off: dst_off32, + src_win, + src_off, + most: most_groups(), + lim_win, + lim_off, + }); + }); + return Ok((dst, dst_off)); + } + } + } + // Inline 256-slot offset-table batching (`XCL_INLINE_GUARD_BATCH=0` opt-out): when prelude + // hoisting is blocked (after a compute/UAV write), emit ONE `PRELUDE_GUARD_*` `Dispatch(4,1,1)` + // + barrier pair on the first indirect dispatch and append up to 255 subsequent consecutive + // indirect dispatches into its coherent UMA job table with zero extra barriers or PSO switches. + if inline_guard_batch_on() { + if let (Some((src_win, src_off)), Some((lim_win, lim_off))) = ( + uma_win_off(u, src, 12), + uma_win_off(u, dispatch_io_host + crate::gpu::recomp::IO_GROUP_LIMIT * 4, 4), + ) { + let most = most_groups(); + let appended = with(this, |s| { + let b = s.inline_guard.as_mut()?; + if b.count >= INLINE_GUARD_BATCH_MAX { + return None; + } + let idx = b.count; + let rec = [src_win, src_off, most, idx * 256, lim_win, lim_off, 0u32, 0u32]; + let slot_ptr = (b.jobs_cpu + 16 + idx as usize * 32) as *mut u32; + std::ptr::copy_nonoverlapping(rec.as_ptr(), slot_ptr, rec.len()); + (*(b.jobs_cpu as *const std::sync::atomic::AtomicU32)).store(idx + 1, Ordering::Release); + b.count = idx + 1; + Some((b.dst.clone(), b.dst_base_off + idx as u64 * 256)) + }); + if let Some(res) = appended { + return Ok(res); + } + let use_heap = super::console_heap::window_views_ready(); + let win_ok = use_heap || (src_win < 4 && lim_win < 4); + if win_ok { + let win_vas = if use_heap { + Some([0u64; 4]) + } else { + with(this, |s| { + if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { + s.uma_windows = Some(super::real::uma_window_vas()); + } + let w = s.uma_windows.as_deref()?; + let first = *w.first().filter(|&&v| v != 0)?; + Some([ + first, + w.get(1).copied().filter(|&v| v != 0).unwrap_or(first), + w.get(2).copied().filter(|&v| v != 0).unwrap_or(first), + w.get(3).copied().filter(|&v| v != 0).unwrap_or(first), + ]) + }) + }; + if let Some(win_vas) = win_vas { + let jobs_p = with(this, |s| s.arena.take(u, INLINE_GUARD_JOBS_BYTES, 256, &mut s.uma)); + if let Some(jobs_p) = jobs_p { + if let Some(jobs_va) = super::real::uma_va_of(jobs_p as usize) { + with(this, |s| s.inline_guard = None); + let (dst, dst_base_off, slot, prev_state) = scratch_args_pingpong(this, &dev, INLINE_GUARD_DST_BYTES)?; + let dst_va = dst.GetGPUVirtualAddress() + dst_base_off; + let hdr = [1u32, 0, 0, 0]; + let rec0 = [src_win, src_off, most, 0u32, lim_win, lim_off, 0u32, 0u32]; + std::ptr::copy_nonoverlapping(hdr.as_ptr(), jobs_p as *mut u32, hdr.len()); + std::ptr::copy_nonoverlapping(rec0.as_ptr(), (jobs_p as usize + 16) as *mut u32, rec0.len()); + let (rs, pso) = if use_heap { + ensure_heaps_cached(this); + prelude_guard_heap_pipeline(&dev)? + } else { + prelude_guard_pipeline(&dev)? + }; + emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetComputeRootSignature(&rs); + if !use_heap { + for (k, &va) in win_vas.iter().enumerate() { + list.SetComputeRootUnorderedAccessView((2 + k) as u32, va); + } + } + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, jobs_va); + list.SetComputeRootUnorderedAccessView(1, dst_va); + list.Dispatch(INLINE_GUARD_BATCH_MAX / 64, 1, 1); + emit_transition_and_uav(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, GUARDED_ARGS_STATE); + with(this, |s| { + s.scratch[slot].state = GUARDED_ARGS_STATE; + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = true; + s.inline_guard = Some(InlineGuardBatch { + jobs_cpu: jobs_p as usize, + dst: dst.clone(), + dst_base_off, + count: 1, + }); + }); + return Ok((dst, dst_base_off)); + } + } + } + } + } + } + with(this, |s| s.inline_guard = None); + let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, 256)?; + let dst_va = dst.GetGPUVirtualAddress() + dst_off; + if dst_va == 0 { + return Err("indirect guard scratch buffer has null GPU VA".into()); + } + let lim_off = if dispatch_io_va != 0 { (crate::gpu::recomp::IO_GROUP_LIMIT * 4) as u32 } else { 0 }; + if super::console_heap::window_views_ready() { + if let Some((src_slot, src_off)) = uma_heap_slot_off(u, src, 12) { + let (rs, pso) = guard_indirect_heap_pipeline(&dev)?; + let consts = [src_slot, src_off, most_groups(), lim_off]; + let lim_va = resolve_aux_uav_va((dispatch_io_va != 0).then_some(dispatch_io_va), dst_va)?; + ensure_heaps_cached(this); + // the title's writes of the arguments before this (`fresh_indirect_arguments`) + emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRoot32BitConstants(0, consts.len() as u32, consts.as_ptr() as *const c_void, 0); + list.SetComputeRootUnorderedAccessView(1, dst_va); + list.SetComputeRootUnorderedAccessView(2, lim_va); + list.Dispatch(1, 1, 1); + emit_transition_and_uav(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, GUARDED_ARGS_STATE); + with(this, |s| { + s.scratch[slot].state = GUARDED_ARGS_STATE; + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = true; + }); + return Ok((dst, dst_off)); + } + } + let (rs, pso) = guard_indirect_pipeline(&dev)?; + let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; + let (src_base, src_off) = align_root_uav(src_va)?; + let consts = [src_off, most_groups(), 0, lim_off]; + let p = with(this, |s| s.arena.take(u, std::mem::size_of_val(&consts), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(consts.as_ptr().cast::(), p, std::mem::size_of_val(&consts)); + let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; + let lim_va = resolve_aux_uav_va((dispatch_io_va != 0).then_some(dispatch_io_va), consts_va)?; + // the title's writes of the arguments before this (`fresh_indirect_arguments`) + emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, consts_va); + list.SetComputeRootUnorderedAccessView(1, src_base); + list.SetComputeRootUnorderedAccessView(2, dst_va); + list.SetComputeRootUnorderedAccessView(3, lim_va); + list.Dispatch(1, 1, 1); + // Transition scratch to INDIRECT_ARGUMENT | NON_PIXEL_SHADER_RESOURCE and flush the + // `IO_GROUP_LIMIT` store in `dispatch_io_va`. + emit_transition_and_uav(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, GUARDED_ARGS_STATE); + with(this, |s| { + s.scratch[slot].state = GUARDED_ARGS_STATE; + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = true; + }); + Ok((dst, dst_off)) +} + +/// Guard `max` indirect Draw/DrawIndexed command records at UMA address `src` (`stride` bytes +/// each, draw arguments at `draw_offset`), zeroing any record with `>= 2^23` vertices per +/// instance or `> 2^26` total vertices. Hoists into the batched prelude list when safe, else +/// executes inline into ping-pong scratch. +unsafe fn guard_draw_args( + this: *mut c_void, + list: &ID3D12GraphicsCommandList, + src: usize, + max: u32, + stride: u32, + draw_offset: u32, +) -> Result<(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()); + } + if max == 0 || stride == 0 || stride % 4 != 0 || draw_offset % 4 != 0 || draw_offset.checked_add(16).is_none_or(|e| e > stride) { + return Err(format!("invalid indirect draw layout (max {max}, stride {stride}, offset {draw_offset})")); + } + let commands = (max as u64).checked_mul(stride as u64).ok_or("indirect draw command span overflow")?; + if commands > u32::MAX as u64 { + return Err("indirect draw command buffer exceeds 32-bit offsets".into()); + } + let dev = super::real::list_device(this).ok_or("no device")?; + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + super::real::uma_window_buffer(src, commands as usize).ok_or("the indirect draw arguments are not in one memory window")?; + if can_hoist_prelude(this) { + if let Some((src_win, src_off)) = uma_win_off(u, src, commands as usize) { + let (dst, dst_off, buf_idx) = alloc_prelude_scratch(this, &dev, commands)?; + if let Ok(dst_off32) = u32::try_from(dst_off) { + if dst_off32.checked_add(commands as u32).is_some() { + with(this, |s| { + s.prelude_draws.push(PreludeDrawJob { + buf_idx, + dst_off: dst_off32, + count: max, + stride, + draw_offset, + src_win, + src_off, + }); + }); + return Ok((dst, dst_off)); + } + } + } + } + with(this, |s| s.inline_guard = None); + let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, commands)?; + let dst_va = dst.GetGPUVirtualAddress() + dst_off; + if dst_va == 0 { + return Err("indirect draw guard scratch buffer has null GPU VA".into()); + } + if super::console_heap::window_views_ready() { + if let Some((src_slot, src_off)) = uma_heap_slot_off(u, src, commands as usize) { + let (rs, pso) = guard_draw_heap_pipeline(&dev)?; + let consts = [max, stride, draw_offset, src_slot, src_off]; + ensure_heaps_cached(this); + emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRoot32BitConstants(0, consts.len() as u32, consts.as_ptr() as *const c_void, 0); + list.SetComputeRootUnorderedAccessView(1, dst_va); + list.Dispatch(max.div_ceil(64), 1, 1); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, GUARDED_ARGS_STATE); + with(this, |s| { + s.scratch[slot].state = GUARDED_ARGS_STATE; + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = true; + }); + return Ok((dst, dst_off)); + } + } + let (rs, pso) = guard_draw_pipeline(&dev)?; + let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; + 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 draw command range exceeds 32-bit shader offsets".into()); + } + let consts = [max, stride, draw_offset, src_off]; + let p = with(this, |s| s.arena.take(u, std::mem::size_of_val(&consts), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(consts.as_ptr().cast::(), p, std::mem::size_of_val(&consts)); + let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; + emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, consts_va); + list.SetComputeRootUnorderedAccessView(1, src_base); + list.SetComputeRootUnorderedAccessView(2, dst_va); + list.Dispatch(max.div_ceil(64), 1, 1); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, GUARDED_ARGS_STATE); + with(this, |s| { + s.scratch[slot].state = GUARDED_ARGS_STATE; + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = true; + }); + Ok((dst, dst_off)) +} + +unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: Mutex>> = Mutex::new(None); + args_pipeline(dev, SCALE_ARGS_HLSL, SCALE_ARGS_DRED_LABEL, true, &CACHE) +} + +unsafe fn scale_indirect_heap_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + heap_args_pipeline(dev, SCALE_ARGS_HEAP_HLSL, SCALE_ARGS_DRED_LABEL, 10, &[0], &CACHE) +} + +type ArgsPipelines = Mutex>>; + +/// Root signature for the descriptor-heap + inline root-constants internal argument passes: +/// param 0 = `num_consts` inline 32-bit constants at `b0`, followed by root UAVs for committed +/// scratch/io outputs, with `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for safe raw window UAV reads. +unsafe fn heap_args_root_signature(dev: &ID3D12Device, num_consts: u32, uav_regs: &[u32]) -> Result { + let mut params = Vec::with_capacity(1 + uav_regs.len()); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: 0, + Num32BitValues: num_consts, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + for ® in uav_regs { + params.push(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, + }); + } + 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_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED, + }, + }, + }; + let mut blob: Option = None; + D3D12SerializeVersionedRootSignature(&desc, &mut blob, None).map_err(|e| format!("heap args root signature serialize: {e}"))?; + let blob = blob.ok_or("heap args root signature blob")?; + dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())) + .map_err(|e| format!("heap args root signature create: {e}")) +} + +unsafe fn heap_args_pipeline(dev: &ID3D12Device, hlsl: &str, label: &str, num_consts: u32, uav_regs: &[u32], cache: &'static ArgsPipelines) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let key = dev.as_raw() as usize; + if let Some(pair) = cache.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(pair); + } + let dxil = crate::gpu::recomp::dxc::compile_cached(hlsl, "main", "cs_6_6")?.0; + let rs = heap_args_root_signature(dev, num_consts, uav_regs)?; + 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() }, + ..Default::default() + }; + let res_pso: Result = dev.CreateComputePipelineState(&cdesc); + std::mem::ManuallyDrop::drop(&mut cdesc.pRootSignature); + let pso = res_pso.map_err(|e| format!("{label} heap pso create: {e}"))?; + let _ = pso.SetName(&windows::core::HSTRING::from(label)); + super::dred::label_text(pso.as_raw() as usize, || label.to_string()); + cache.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); + Ok((rs, pso)) +} + +/// Minimal compute root signature for XCL's internal argument-rewrite passes: only the root UAVs +/// the shader declares (`u0, u2, u3`, plus `u4` when `with_count` is set) and no heap flags, so +/// every root parameter is unconditionally bound before Dispatch. +unsafe fn args_root_signature(dev: &ID3D12Device, with_count: bool) -> Result { + let regs: &[u32] = if with_count { &[0, 2, 3, 4] } else { &[0, 2, 3] }; + let params: Vec = regs + .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!("args root signature serialize: {e}"))?; + let blob = blob.ok_or("args root signature blob")?; + dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())) + .map_err(|e| format!("args root signature create: {e}")) +} + +unsafe fn args_pipeline(dev: &ID3D12Device, hlsl: &str, label: &str, with_count: bool, cache: &'static ArgsPipelines) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let key = dev.as_raw() as usize; + if let Some(pair) = cache.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(pair); + } + let dxil = crate::gpu::recomp::dxc::compile_cached(hlsl, "main", "cs_6_6")?.0; + let rs = args_root_signature(dev, with_count)?; + 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() }, + ..Default::default() + }; + let res_pso: Result = dev.CreateComputePipelineState(&cdesc); + std::mem::ManuallyDrop::drop(&mut cdesc.pRootSignature); + let pso = res_pso.map_err(|e| format!("{label} pso create: {e}"))?; + let _ = pso.SetName(&windows::core::HSTRING::from(label)); + super::dred::label_text(pso.as_raw() as usize, || label.to_string()); + cache.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); + Ok((rs, pso)) +} + +/// `bytes` of this recording's scratch slot `slot` (COMMON initially, kept in INDIRECT_ARGUMENT +/// between uses): the block, byte offset, and its prior D3D12 state. Past `SCRATCH_CAP` across +/// all slots a recording gets no more. +unsafe fn scratch_args_in(this: *mut c_void, dev: &ID3D12Device, bytes: u64, slot: usize) -> Result<(ID3D12Resource, u64, D3D12_RESOURCE_STATES), String> { + let bytes = bytes.next_multiple_of(256); + if let Some(r) = with(this, |s| { + let sl = &mut s.scratch[slot]; + let (b, cap, _) = sl.buf.as_ref()?; + (sl.used + bytes <= *cap).then(|| { + sl.used += bytes; + (b.clone(), sl.used - bytes, sl.state) + }) + }) { + return Ok(r); + } + let size = bytes.max(SCRATCH_BLOCK); + let cap = scratch_cap(); + let remaining = cap.saturating_sub(with(this, |s| s.scratch_taken)); + if size > remaining { + return Err(format!("its rewritten arguments are past {} MiB this recording", cap >> 20)); + } + let dev_key = dev.as_raw() as usize; + let picked = { + let mut free = FREE_RES.lock().unwrap(); + free.iter().position(|(_, cap, d)| *d == dev_key && *cap >= size && *cap <= remaining).map(|i| free.swap_remove(i)) + }; + let block = match picked { + Some(e) => e, + None => (default_uav_buffer(dev, size, "two-pass argument scratch")?, size, dev_key), + }; + let b = block.0.clone(); + with(this, |s| { + s.scratch_taken += block.1; + s.scratch[slot] = ScratchSlot { + buf: Some(block.clone()), + used: bytes, + state: D3D12_RESOURCE_STATE_COMMON, + }; + s.res_retired.push(block); + }); + Ok((b, 0, D3D12_RESOURCE_STATE_COMMON)) +} + +#[cfg(test)] +unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, u64), String> { + let (b, off, _) = scratch_args_in(this, dev, bytes, 0)?; + Ok((b, off)) +} + +/// Choose between the two ping-pong scratch slots (`preferred` vs `preferred ^ 1`): prefer +/// alternating so back-to-back indirect passes avoid WAR stalls on the same buffer, falling +/// back to the other slot when `preferred` would require a new block past `SCRATCH_CAP`. +fn pick_pingpong_slot(preferred: usize, fits: [bool; 2], can_alloc: bool) -> usize { + if fits[preferred] || can_alloc { + preferred + } else if fits[preferred ^ 1] { + preferred ^ 1 + } else { + preferred + } +} + +unsafe fn scratch_args_pingpong(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, u64, usize, D3D12_RESOURCE_STATES), String> { + let aligned = bytes.next_multiple_of(256); + let size = aligned.max(SCRATCH_BLOCK); + let slot = with(this, |s| { + let preferred = s.scratch_next; + let fits = [ + s.scratch[0].buf.as_ref().is_some_and(|(_, cap, _)| s.scratch[0].used + aligned <= *cap), + s.scratch[1].buf.as_ref().is_some_and(|(_, cap, _)| s.scratch[1].used + aligned <= *cap), + ]; + let can_alloc = scratch_cap().saturating_sub(s.scratch_taken) >= size; + let chosen = pick_pingpong_slot(preferred, fits, can_alloc); + s.scratch_next = chosen ^ 1; + chosen + }); + let (buf, off, prev_state) = scratch_args_in(this, dev, aligned, slot)?; + Ok((buf, off, slot, prev_state)) +} + +/// The arguments of `max` commands at UMA address `src`, rewritten for the two passes +/// (`SCALE_ARGS_HLSL`) into a scratch block: the block (INDIRECT_ARGUMENT until the caller puts +/// it back to COMMON) and where the compute pass's commands are; the mesh pass's follow them. +/// +/// They are read through the memory window over them, as translated shaders read memory, not +/// through the title's buffer: its state on the PC is the title's and not known here. So is the +/// 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) -> Result<(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 u = crate::gpu::uma::get().ok_or("no unified memory")?; + super::real::uma_window_buffer(src, commands as usize).ok_or("the indirect arguments are not in one memory window")?; + if let Some(p) = count { + super::real::uma_window_buffer(p, 4).ok_or("the indirect count is not in a memory window")?; + } + if can_hoist_prelude(this) { + if let Some((src_win, src_off)) = uma_win_off(u, src, commands as usize) { + let cnt_loc = match count { + Some(p) => uma_win_off(u, p, 4).map(|(w, o)| (1u32, w, o)), + None => Some((0u32, 0u32, 0u32)), + }; + if let Some((has_cnt, cnt_win, cnt_off)) = cnt_loc { + let (dst, dst_off, buf_idx) = alloc_prelude_scratch(this, &dev, commands.saturating_mul(2))?; + if let Ok(dst_off32) = u32::try_from(dst_off) { + if dst_off32.checked_add((commands * 2) as u32).is_some() { + with(this, |s| { + s.prelude_scales.push(PreludeScaleJob { + buf_idx, + dst_off: dst_off32, + count: max, + stride, + mesh_offset, + split, + cap, + src_win, + src_off, + has_cnt, + cnt_win, + cnt_off, + }); + }); + return Ok((dst, dst_off)); + } + } + } + } + } + with(this, |s| s.inline_guard = None); + let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, commands.saturating_mul(2))?; + let dst_va = dst.GetGPUVirtualAddress() + dst_off; + if dst_va == 0 { + return Err("scaled indirect scratch buffer has null GPU VA".into()); + } + if super::console_heap::window_views_ready() { + if let Some((src_slot, src_off)) = uma_heap_slot_off(u, src, commands as usize) { + let cnt_loc = match count { + Some(p) => uma_heap_slot_off(u, p, 4).map(|(sl, off)| (1u32, sl, off)), + None => Some((0u32, src_slot, 0u32)), + }; + if let Some((has_cnt, cnt_slot, cnt_off)) = cnt_loc { + let (rs, pso) = scale_indirect_heap_pipeline(&dev)?; + let consts = [max, stride, mesh_offset, split, cap, src_slot, src_off, has_cnt, cnt_slot, cnt_off]; + ensure_heaps_cached(this); + // the title's writes of the arguments before this (`fresh_indirect_arguments`) + emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRoot32BitConstants(0, consts.len() as u32, consts.as_ptr() as *const c_void, 0); + list.SetComputeRootUnorderedAccessView(1, dst_va); + list.Dispatch(max.div_ceil(64), 1, 1); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + with(this, |s| { + s.scratch[slot].state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = true; + }); + return Ok((dst, dst_off)); + } + } + } + let (rs, pso) = scale_indirect_pipeline(&dev)?; + let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; + 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) => { + 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 consts = [max, stride, mesh_offset, split, cap, src_off, 0, count_bound.is_some() as u32, count_bound.map_or(0, |(_, off)| off)]; + let p = with(this, |s| s.arena.take(u, std::mem::size_of_val(&consts), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(consts.as_ptr().cast::(), p, std::mem::size_of_val(&consts)); + let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; + // Bind u4 unconditionally to a valid non-null GPU VA (falling back to `consts_va` when no + // count buffer is supplied) because `SCALE_ARGS_HLSL` statically declares `cnt : register(u4)` + // and AMD/NVIDIA hardware may speculatively fetch unbound/null root UAVs. + let cnt_base = resolve_aux_uav_va(count_bound.map(|(base, _)| base), consts_va)?; + // the title's writes of the arguments before this (`fresh_indirect_arguments`) + emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, consts_va); + list.SetComputeRootUnorderedAccessView(1, src_base); + list.SetComputeRootUnorderedAccessView(2, dst_va); + list.SetComputeRootUnorderedAccessView(3, cnt_base); + list.Dispatch(max.div_ceil(64), 1, 1); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + with(this, |s| { + s.scratch[slot].state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = true; + }); + Ok((dst, dst_off)) +} + +/// local: `XCL_SKIP_MESH=1` leaves out the draws of the two-pass mesh path (a bisection of GPU hangs) +fn skip_mesh() -> bool { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_SKIP_MESH").is_ok_and(|v| v.trim() == "1")) +} + +pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: u32, z: u32) { + type PcDm = unsafe extern "system" fn(*mut c_void, u32, u32, u32); + let pc_dm: PcDm = std::mem::transmute(super::real::orig_fn(this, 79)); + let raw_pso = with(this, |s| s.pso); + let pso = pso_for_draw(raw_pso); + if let Some(tp) = super::real::two_pass_of(pso) { + if skip_mesh() { + count(DRAWS_SKIPPED); + return; + } + let groups = x.saturating_mul(y).saturating_mul(z); + if groups == 0 { + return; + } + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + let record_bytes = tp.record.record_dwords() as u64 * 4; + let need = (groups as u64).saturating_mul(record_bytes); + let run = (|| -> Result<(), String> { + let (res_buf, res_va, cap) = ensure_res_buffer(this, need)?; + let n = groups.min(record_groups(cap, record_bytes, tp.mesh_groups_per_record)); + if n == 0 { + return Err(format!("a record of {record_bytes} B does not fit the record buffer")); + } + if n < groups { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: two-pass DispatchMesh of {groups} groups: {} past the record buffer dropped", groups - n); + } + } + bind_two_pass_stage(this, list, pso, &tp, res_va, true)?; + let m1 = super::culprit::before_dispatch(list, raw_pso, pso, [n, 1, 1]); + list.Dispatch(n, 1, 1); + super::culprit::after_dispatch(list, m1); + emit_uav_barrier(list, Some(&res_buf)); + bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; + // (the mesh pass: what the marker says is its groups; 0x3e2 marks a mesh draw in the log) + let m2 = super::culprit::before_dispatch(list, raw_pso, pso, [n * tp.mesh_groups_per_record, 0x3e2, 1]); + pc_dm(this, n * tp.mesh_groups_per_record, 1, 1); + super::culprit::after_dispatch(list, m2); + emit_uav_barrier(list, Some(&res_buf)); + with(this, |s| { + s.arg_order_clean = false; + s.inline_guard = None; + }); + Ok(()) + })(); + match run { + Ok(()) => { + count(DRAWS); + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: two-pass DispatchMesh #{n} ({groups} groups, split {}, kind {})", tp.mesh_groups_per_record, tp.kind); + } + } + Err(e) => { + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: two-pass DispatchMesh skipped: {e}"); + } + } + } + return; + } + if super::pso_async::bound_unbuilt(raw_pso, pso) { + count(DRAWS_SKIPPED); + return; + } + let rs = with(this, |s| s.rs_gfx) as *mut c_void; + if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { + list.SetGraphicsRootSignature(r); + with(this, |s| s.pc_abi_gfx = AbiBound::default()); + } + count(DRAWS_PC); + pc_dm(this, x, y, z); +} + +/// An ExecuteIndirect that could have drawn is skipped: mark any active occlusion query visible +/// so the title does not treat skipped geometry as occluded (Dispatch signatures make no samples). +fn note_skipped_indirect(this: *mut c_void, sig: usize) { + if !signature_dispatches(sig) { + super::list_x::note_dropped_draw(this); + } +} + +/// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a +/// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root +/// arguments themselves cannot be – skipped, logged) +pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { + if max == 0 { + return; + } + type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); + let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); + let raw_pso = with(this, |s| s.pso); + let unbuilt_compute = signature_dispatches(sig) + && super::pso_async::is_pending(raw_pso) + && !super::pso_async::is_spared(raw_pso) + && super::real::is_console_compute(raw_pso); + if unbuilt_compute && super::list_x::defer(this, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { + return super::pso_async::need_by_submit(raw_pso); + } + let pso = pso_for_draw(raw_pso); + // where the commands are in unified memory (a console buffer's offsets are the title's) + let commands_at = super::real::console_buffer(args).and_then(|(p, n)| { + let off = usize::try_from(args_off).ok()?; + (off <= n).then(|| p.checked_add(off).map(|addr| (addr, n - off))).flatten() + }); + let count_at = super::real::console_buffer(count_buf).and_then(|(p, n)| { + let off = usize::try_from(count_off).ok()?; + (off.checked_add(4)? <= n).then(|| p.checked_add(off)).flatten() + }); + let (args_off_title, count_off_title) = (args_off, count_off); + let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); + if let Some(tp) = super::real::two_pass_of(pso) { + if skip_mesh() { + count(DRAWS_SKIPPED); + return; + } + if let Some(msig) = dispatch_mesh_sig_of(sig) { + // If an earlier compute dispatch blocked prelude hoisting on this segment, split once + // before the two-pass DispatchMesh burst so all consecutive indirect mesh draws hoist + // into one batched `PRELUDE_SCALE_*` dispatch instead of inline compute/barrier bubbles. + let mut this = this; + if max > 0 && args != 0 && indirect_prelude_on() && with(this, |s| s.prelude_blocked && s.allocator != 0 && s.prelude_built.is_none()) { + if let Some(next) = super::list_x::split_for_prelude(this) { + this = next; + } + } + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + let run = (|| -> Result<(), String> { + if max == 0 || args == 0 { + return Ok(()); + } + let commands = max as usize * msig.byte_stride as usize; + let src = match commands_at { + Some((p, n)) if commands <= n => p, + _ => return Err("its arguments are not in a console buffer in unified memory".into()), + }; + let record_bytes = tp.record.record_dwords() as u64 * 4; + let (res_buf, res_va, cap) = ensure_res_buffer(this, two_pass_indirect_bytes())?; + let cap = record_groups(cap, 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")); + } + let count = match (count_buf, count_at) { + (0, _) => None, + (_, Some(p)) => Some(p), + _ => return Err("its count is not in a console buffer in unified memory".into()), + }; + // the groups past the record buffer, and the commands past the count, are dropped + // 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)?; + for (k, compute) in two_pass_steps(max) { + bind_two_pass_stage(this, list, pso, &tp, res_va, compute)?; + let (s, first) = if compute { (msig.companion_dispatch, at) } else { (sig, at + commands as u64) }; + let mark = super::culprit::before_dispatch(list, raw_pso, pso, [0, 0, if compute { 1 } else { 0x3e2 }]); + pc(this, s, 1, scaled.as_raw() as usize, first + k as u64 * msig.byte_stride as u64, 0, 0); + super::culprit::after_dispatch(list, mark); + emit_uav_barrier(list, Some(&res_buf)); + } + with(this, |s| s.arg_order_clean = false); + Ok(()) + })(); + match run { + Ok(()) => { + count(DRAWS); + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: two-pass ExecuteIndirect(DispatchMesh) #{n} (max {max}, split {}, kind {})", tp.mesh_groups_per_record, tp.kind); + } + } + Err(e) => { + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: two-pass ExecuteIndirect skipped: {e}"); + } + } + } + return; + } + } + let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); + if !gfx && !compute { + // A pipeline still being built (or whose build failed): its stand-in draws nothing, and + // the list may hold XCL's ABI root signature from a translated draw before it – the PC + // call with that pair is invalid (debug layer 953, "the currently set Root Signature + // doesn't match the currently set Pipeline State Object"; a retail title's world then + // hung the GPU, 0x887a0006). Skipped, like a draw or dispatch of such a pipeline. + if super::pso_async::bound_unbuilt(raw_pso, pso) { + note_skipped_indirect(this, sig); + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect with a pipeline that is still being built skipped"); + } + return; + } + // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in + // TWO_PASS rather than TRANSLATED_GRAPHICS. Falling through to raw PC ExecuteIndirect + // with the title's graphics root signature (e.g. a non-DispatchMesh indirect draw or a + // root-changing signature) invalidates the command list (Close → E_INVALIDARG). + if let Some(tp) = super::real::two_pass_of(pso) { + note_skipped_indirect(this, sig); + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!( + "D3D12.X: ExecuteIndirect with two-pass {} pipeline ({pso:#x}) skipped – PC pipeline is a mesh shader", + tp.kind + ); + } + return; + } + // a console compute program without a translation (its build failed): nothing to run, + // as for Dispatch. The PC call would run it with the list's compute root signature, which + // can still be XCL's ABI one from a translated dispatch before it (debug layer 953). + // A native PC compute pipeline is not one of these and still goes to the PC call. + // (`CONSOLE_COMPUTE` holds the title's object, which for a shared stand-in differs from + // the driver pipeline `resolve_wait` returned.) + if signature_dispatches(sig) && (super::real::is_console_compute(raw_pso) || super::real::is_console_compute(pso)) { + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect dispatch with a pipeline that has no translated console shader ({raw_pso:#x}) skipped"); + } + return; + } + // a PC pipeline: the title's root signature, as for a draw (`graphics_bound`) + let rs = with(this, |s| s.rs_gfx) as *mut c_void; + if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { + list.SetGraphicsRootSignature(r); + with(this, |s| s.pc_abi_gfx = AbiBound::default()); + } + return fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)); + } + if ROOT_SIGNATURES.read().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) { + if gfx { + note_skipped_indirect(this, sig); + } + 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 that changes root arguments with a translated pipeline skipped"); + } + return; + } + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + // Guard single-command indirect dispatches and indirect Draw/DrawIndexed buffers before + // binding or chaining so out-of-range GPU-written counts are clamped/zeroed in scratch. + let mut guarded = None; + let mut preset_io = None; + if compute && max == 1 && indirect_guard() && signature_dispatches(sig) { + if let Some((p, _)) = commands_at.filter(|&(_, n)| n >= 12) { + // Allocate a dedicated `io` buffer for this dispatch so `guard_dispatch_args` can + // write `IO_GROUP_LIMIT` on the GPU without racing against cached `io` slots. + match alloc_fresh_compute_io(this, pso) { + Ok((io_va, io_host)) => { + preset_io = Some(io_va); + match guard_dispatch_args(this, list, p, io_va, io_host) { + Ok(g) => guarded = Some(g), + Err(e) => { + 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's group counts are not checked: {e}"); + } + } + } + } + Err(e) => { + 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's group counts are not checked: {e}"); + } + } + } + } + } else if gfx && indirect_guard() && indirect_draw_guard() { + if let Some(dsig) = draw_sig_of(sig) { + let _ = dsig.indexed; + if let Some(commands) = (max as usize).checked_mul(dsig.byte_stride as usize) { + if let Some((p, _)) = commands_at.filter(|&(_, n)| commands > 0 && commands <= n) { + match guard_draw_args(this, list, p, max, dsig.byte_stride, dsig.draw_offset) { + Ok(g) => guarded = Some(g), + Err(e) => { + 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's draw counts are not checked: {e}"); + } + } + } + } + } + } + } + let (exec_args, exec_args_off) = guarded.as_ref().map_or((args, args_off), |(b, o)| (b.as_raw() as usize, *o)); + if compute && super::real::dispatch_chain::is_split(pso) { + // Run split compute ExecuteIndirects through their already-built chain pieces on the GPU + // instead of stalling or skipping while the whole form compiles in the background. + let ei = || { + if guarded.is_some() { + pc(this, sig, max, exec_args, exec_args_off, count_buf, count_off); + } else { + fresh_indirect_arguments(this, || pc(this, sig, max, exec_args, exec_args_off, count_buf, count_off)); + } + }; + let mark = super::culprit::before_dispatch(list, raw_pso, pso, [0, 0, max]); + if let Some((p, _)) = commands_at.filter(|&(_, n)| n >= 12) { + super::culprit::indirect_args(mark, p); + } + match chained_indirect( + this, + list, + pso, + sig, + max, + guarded.as_ref(), + (args, args_off_title, args_off), + (count_buf, count_off_title, count_off), + preset_io, + ei, + ) { + Ok(true) => { + super::culprit::after_dispatch(list, mark); + 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, [0, 0, 0], layout.as_deref(), &args, view_heap); + } + with(this, |s| { + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = false; + s.prelude_blocked = true; + }); + return count(DISPATCHES); + } + Ok(false) => { + super::culprit::after_dispatch(list, mark); + } + Err(e) => { + super::culprit::after_dispatch(list, mark); + if let Some(real) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { + list.SetPipelineState(real); + } + with(this, |s| s.pc_abi_cs = AbiBound::default()); + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect of a split program skipped: {e}"); + } + return; + } + } + } + // Non-chainable fallback (bundles, non-dispatch-only signatures, or no scratch): resolve the + // whole form without stalling the title thread. + let whole_pso = if compute { + match super::real::dispatch_chain::whole_nonblocking(pso) { + super::real::dispatch_chain::WholeStatus::NotSplit => None, + super::real::dispatch_chain::WholeStatus::Ready(whole) => Some(whole), + super::real::dispatch_chain::WholeStatus::Pending => { + if guarded.is_some() { + if let Some(real) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { + list.SetPipelineState(real); + } + } + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_info!("D3D12.X: ExecuteIndirect of split compute PSO ({pso:#x}) skipped while whole form builds in background"); + } + return; + } + super::real::dispatch_chain::WholeStatus::Failed => { + if guarded.is_some() { + if let Some(real) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { + list.SetPipelineState(real); + } + } + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO ({pso:#x}) failed – skipped"); + } + return; + } + } + } else { + None + }; + let (args, args_off) = (exec_args, exec_args_off); + match bind_abi(this, list, pso, gfx, 0, preset_io) { + Ok(()) => { + if let Some(whole) = whole_pso { + list.SetPipelineState(&whole); + } + count(if gfx { DRAWS } else { DISPATCHES }); + // an indirect dispatch: its groups are in the argument buffer (`max` of them) + let mark = if gfx { 0 } else { super::culprit::before_dispatch(list, with(this, |s| s.pso), pso, [0, 0, max]) }; + if let Some((p, _)) = commands_at.filter(|&(_, n)| n >= 12) { + super::culprit::indirect_args(mark, p); + } + if guarded.is_some() && count_buf == 0 { + pc(this, sig, max, args, args_off, count_buf, count_off); + } else { + fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)) + } + super::culprit::after_dispatch(list, mark); + if compute { + 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, [0, 0, 0], layout.as_deref(), &args, view_heap); + } + with(this, |s| { + s.arg_order_clean = false; + s.prelude_blocked = true; + s.inline_guard = None; + }); + } else { + with(this, |s| s.inline_guard = None); + } + } + Err(e) => { + if gfx { + note_skipped_indirect(this, sig); + } + if guarded.is_some() { + if let Some(real) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { + list.SetPipelineState(real); + } + } + count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect with a translated pipeline skipped: {e}"); + } + } + } +} + +/// An ExecuteIndirect of split program `pso` with a command signature of one Dispatch, run as its +/// chain (`dispatch_chain::execute_indirect`); the buffers as (resource, title's offset, PC's). +/// Ok(false): nothing recorded – fall back to the whole form. +#[allow(clippy::too_many_arguments)] +unsafe fn chained_indirect( + this: *mut c_void, + list: &ID3D12GraphicsCommandList, + pso: usize, + sig: usize, + max: u32, + guarded: Option<&(ID3D12Resource, u64)>, + (args, args_title, args_pc): (usize, u64, u64), + (count_buf, count_title, count_pc): (usize, u64, u64), + preset_io: Option, + ei: impl FnOnce(), +) -> Result { + let Some(stride) = DISPATCH_ONLY.read().unwrap().as_ref().and_then(|m| m.get(&sig).copied()) else { + return Ok(false); + }; + let args_va = match guarded { + Some((b, off)) => { + let va = b.GetGPUVirtualAddress(); + if va == 0 { + return Ok(false); + } + va + *off + } + None => match indirect_address(args, args_title, args_pc) { + Some(v) => v, + None => return Ok(false), + }, + }; + let count_va = match count_buf { + 0 => None, + c => match indirect_address(c, count_title, count_pc) { + Some(v) => Some(v), + None => return Ok(false), + }, + }; + // the arguments there now (the GPU's last ones) size the rounds + let read = |res: usize, off: u64, n: usize| -> Option> { + let (p, size) = super::real::console_buffer(res)?; + let off = usize::try_from(off).ok()?; + let end = off.checked_add(4 * n)?; + let at = p.checked_add(off)?; + (end <= size && crate::gpu::shader::readable(at, 4 * n)) + .then(|| (0..n).map(|i| std::ptr::read_volatile((at as *const u32).add(i))).collect()) + }; + let n = if count_buf == 0 { + max + } else { + read(count_buf, count_title, 1).map_or(max, |c| c[0].min(max)) + }; + let seen: Vec<[u32; 3]> = (0..n.min(64)) + .filter_map(|k| read(args, args_title.checked_add(u64::from(k).checked_mul(u64::from(stride))?)?, 3)) + .map(|v| [v[0], v[1], v[2]]) + .collect(); + let predicated = super::list_x::predication_active(this); + super::real::dispatch_chain::execute_indirect( + list, + pso, + with(this, |s| s.allocator), + args_va, + stride, + max, + count_va, + &seen, + predicated, + || { + with(this, |s| s.pc_abi_cs = AbiBound::default()); + bind_abi(this, list, pso, false, 0, preset_io) + }, + ei, + ) +} + +/// The GPU address of a title's buffer `res` at its offset `title` (a buffer in unified memory) or +/// `pc` (another). +unsafe fn indirect_address(res: usize, title: u64, pc: u64) -> Option { + match super::real::console_buffer(res) { + Some((p, n)) => { + let off = usize::try_from(title).ok()?; + let addr = p.checked_add(off)?; + (off < n).then(|| super::real::uma_va_of(addr)).flatten() + } + None => Some(ID3D12Resource::from_raw_borrowed(&(res as *mut c_void))?.GetGPUVirtualAddress()) + .filter(|&va| va != 0) + .map(|va| va + pc), + } +} + +/// XCL's own buffer for `fresh_indirect_arguments` (device, buffer): COMMON between its uses +static ARGUMENT_ORDER: Mutex> = Mutex::new(None); + +/// `op` (an ExecuteIndirect on `list`) reading the arguments and count the list wrote before it. +/// +/// The console orders a dispatch that writes indirect arguments before the ExecuteIndirect that +/// reads them with a barrier that reaches the PC as a UAV barrier (`list_x::resource_barrier_x`). +/// NVIDIA's driver (RTX 5090) fetches an ExecuteIndirect's arguments without waiting for that +/// barrier: it ran the count that was there before the list in all but a few of 100 tries, also +/// when the dispatch wrote them through another resource over the same memory, as translated +/// shaders do through the memory window buffers (`execute_indirect_reads_the_arguments_written_before_it`). +/// A retail title's ExecuteIndirect after the dispatch that writes its group count then runs +/// whatever count the memory held before. A transition to INDIRECT_ARGUMENT makes the driver +/// wait for the writes – of any buffer, as measured there. The title's buffer is in the title's +/// state (its transitions reach the PC list), so a buffer of XCL's own takes it, COMMON -> +/// INDIRECT_ARGUMENT before and back after. Only on a list XCL made (`list_x::on_create`) and +/// not a bundle, which cannot hold barriers; its type comes from XCL's state, not a call to it. +unsafe fn fresh_indirect_arguments(list: *mut c_void, op: impl FnOnce()) { + if with(list, |s| s.arg_order_clean) { + return op(); + } + let tracked = super::list_x::tracked_list_type(list).is_some_and(|t| t != D3D12_COMMAND_LIST_TYPE_BUNDLE); + let buffer = if tracked { ID3D12GraphicsCommandList::from_raw_borrowed(&list).and_then(|l| argument_order_buffer(l)) } else { None }; + let Some(buffer) = buffer else { return op() }; + let b = buffer.as_raw() as usize; + super::list_x::transition(list, b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + with(list, |s| s.arg_order_clean = true); + op(); + super::list_x::transition(list, b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); +} + +/// The device's buffer for `fresh_indirect_arguments` (made on first use) +unsafe fn argument_order_buffer(list: &ID3D12GraphicsCommandList) -> Option { + let mut dev: Option = None; + list.GetDevice(&mut dev).ok()?; + let dev = dev?; + let mut g = ARGUMENT_ORDER.lock().unwrap(); + if let Some((_, b)) = g.as_ref().filter(|(d, _)| *d == dev.as_raw() as usize) { + return Some(b.clone()); + } + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + 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_ROW_MAJOR, + ..Default::default() + }; + let mut b: Option = None; + if let Err(e) = dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut b) { + 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: no buffer to order its arguments after the writes before it ({e}) – it may read old ones"); + } + return None; + } + let b = b?; + *g = Some((dev.as_raw() as usize, b.clone())); + Some(b) +} + +/// A DrawInstanced of the console's rect list (three corners of each rectangle, the fourth +/// implied) as two triangles a rectangle; false: not a rect list, or one this cannot expand +/// (the caller draws the three vertices as a triangle – half of each rectangle). +/// +/// The PC has no rect lists. The fourth corner is made here, on the CPU, from the title's +/// vertex data: v3 = v0 + v2 − v1 (seen in a retail title's full-screen passes: (−1,1) (−1,−1) +/// (1,−1) with texture coordinates (0,0) (0,1) (1,1) – the missing corner is (1,1), (1,0)). +/// The vertex layout is not looked at: each 4-byte word that is the same in all three vertices +/// is kept (a packed colour), any other is taken as a float. Vertices a shader makes from the +/// vertex index alone (no vertex buffer) are not expanded. +unsafe fn draw_rects(this: *mut c_void, list: &ID3D12GraphicsCommandList, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) -> bool { + if !cpu_rect_expansion(with(this, |s| s.pso)) { + return false; + } + let Some(vbs) = super::list_x::rect_list_state(this) else { return false }; + let rects = (vertices / 3) as usize; + if vbs.is_empty() || rects == 0 || rects > 4096 { + return false; + } + let mut views = Vec::new(); + for &(slot, (va, bytes, stride), _) in &vbs { + let (s, at) = (stride as usize, va as usize + first_vertex as usize * stride as usize); + let len = rects * 3 * s; + if va == 0 || s == 0 || s % 4 != 0 || first_vertex as usize * s + len > bytes as usize || !crate::gpu::shader::readable(at, len) { + return false; + } + let p = allocate_upload_memory(this, rects * 6 * s, 16); + if p.is_null() { + return false; + } + let word = |v: usize, w: usize| (at as *const u8).add(v * s + w * 4).cast::().read_unaligned(); + for r in 0..rects { + let out = p.add(r * 6 * s); + let src = (at as *const u8).add(r * 3 * s); + // v0 v1 v2, then v0 v2 v3 + std::ptr::copy_nonoverlapping(src, out, 3 * s); + std::ptr::copy_nonoverlapping(src, out.add(3 * s), s); + std::ptr::copy_nonoverlapping(src.add(2 * s), out.add(4 * s), s); + for w in 0..s / 4 { + let (a, b, c) = (word(r * 3, w), word(r * 3 + 1, w), word(r * 3 + 2, w)); + let d = if a == b && b == c { a } else { (f32::from_bits(a) + f32::from_bits(c) - f32::from_bits(b)).to_bits() }; + out.add(5 * s + w * 4).cast::().write_unaligned(d); + } + } + views.push((slot, D3D12_VERTEX_BUFFER_VIEW { BufferLocation: super::list_x::pc_va_of(p as u64), SizeInBytes: (rects * 6 * s) as u32, StrideInBytes: stride })); + } + for (slot, v) in &views { + list.IASetVertexBuffers(*slot, Some(&[*v])); + } + list.DrawInstanced(rects as u32 * 6, instances, 0, first_instance); + for &(slot, _, pc) in &vbs { + if let Some(v) = pc { + list.IASetVertexBuffers(slot, Some(&[v])); + } + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_info!("D3D12.X: rect lists are drawn as two triangles a rectangle, the fourth corner made on the CPU"); + } + true +} + +/// Whether a rect list drawn with the bound pipeline `pso` is expanded on the CPU (`draw_rects`): +/// not with the rect list GS (`real::has_rect_list_gs`), which completes each rect itself – both +/// would draw every rect twice (each CPU half is three corners of the rect). +fn cpu_rect_expansion(pso: usize) -> bool { + !super::real::has_rect_list_gs(super::pso_async::resolve(pso)) +} + +/// #12 DrawInstanced +pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) { + DRAW_ARGS.with(|d| d.set((false, vertices, instances, first_vertex, 0))); + if let Some(list) = graphics_bound(this) { + if draw_rects(this, &list, vertices, instances, first_vertex, first_instance) { + if super::ambient::has_sky_psos() { + let pso = pso_for_draw(with(this, |s| s.pso)); + super::ambient::after_draw(this, pso); + } + return; + } + 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); + if super::ambient::has_sky_psos() { + let pso = pso_for_draw(with(this, |s| s.pso)); + super::ambient::after_draw(this, pso); + } + } +} + +thread_local! { + /// the draw being bound: (indexed, count, instances, first index / vertex, base vertex) – for the frame trace + static DRAW_ARGS: std::cell::Cell<(bool, u32, u32, u32, i32)> = const { std::cell::Cell::new((false, 0, 0, 0, 0)) }; +} + +/// #13 DrawIndexedInstanced +pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) { + 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 = pso_for_draw(with(this, |s| s.pso)); + super::ambient::after_draw(this, pso); + } + } +} + +/// Prepare an indexed draw once, before callers make temporary native state changes. +pub(super) unsafe fn prepare_indexed_draw( + this: *mut c_void, + indices: u32, + instances: u32, + first_index: u32, + base_vertex: i32, +) -> Option { + DRAW_ARGS.with(|d| d.set((true, indices, instances, first_index, base_vertex))); + graphics_bound(this) +} + +/// Submit an indexed draw whose translated graphics state has already been prepared. +pub(super) unsafe fn emit_prepared_indexed_draw( + list: &ID3D12GraphicsCommandList, + indices: u32, + instances: u32, + first_index: u32, + base_vertex: i32, + first_instance: u32, +) { + list.DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance); +} + +/// The pipeline a draw (or an ExecuteIndirect) uses now: both graphics and compute pipelines wait +/// within their own per-frame wait window (`XCL_PSO_FRAME_BUDGET_MS`, default 12 s per kind per +/// frame); once a frame's window is spent, remaining unready draws/dispatches get the stand-in +/// for this frame and retry on the next frame (`pso_async`). +fn pso_for_draw(pso: usize) -> usize { + super::pso_async::resolve_for_bind(pso) +} + +/// Before a draw: with a translated pipeline its ABI root signature and the kept graphics +/// arguments are bound (None: the draw is skipped – a console pipeline without a +/// translation, or no unified memory). +unsafe fn graphics_bound(this: *mut c_void) -> Option { + let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); + let (pso, cached_gfx) = with(this, |s| { + s.inline_guard = None; + let hit = s.pso_abi_cache.is_some_and(|c| c.query_pso == s.pso && c.is_gfx); + (s.pso, hit) + }); + if !cached_gfx { + // a pipeline still being built in the background is not waited for (`pso_for_draw`) + let real = pso_for_draw(pso); + if !super::real::is_translated_graphics(real) { + // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in + // TWO_PASS rather than TRANSLATED_GRAPHICS. Binding the title's graphics RS and issuing + // DrawInstanced / DrawIndexedInstanced against a mesh PSO invalidates the command list + // (Close → E_INVALIDARG). + if let Some(tp) = super::real::two_pass_of(real) { + super::list_x::note_dropped_draw(this); + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!( + "D3D12.X: draw with two-pass {} pipeline ({real:#x}) skipped – PC pipeline is a mesh shader", + tp.kind + ); + } + return None; + } + count(DRAWS_PC); + if super::present::trace_frame() { + // which pipelines draw without a translation (first 12 distinct) + static SEEN: Mutex> = Mutex::new(Vec::new()); + let mut g = SEEN.lock().unwrap(); + if !g.contains(&pso) && g.len() < 12 { + g.push(pso); + let real = super::pso_async::resolve(pso); + crate::xlog_info!( + "frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {real:#x}; pending {}, two-pass {}, RT0 {:?})", + super::pso_async::is_pending(pso), + super::real::two_pass_of(real).is_some(), + super::present::rt0_resource(this as usize).map(|r| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0) })) + ); + } + } + // a PC pipeline (also a stand-in or fallback: made with the title's root signature): + // the title's root signature, which nothing else binds on the PC list – a draw without + // one is invalid (the debug layer reports it on every GPU; WARP faults on it) + if super::pso_async::is_stand_in(pso) { + super::list_x::note_dropped_draw(this); + } + let rs = with(this, |s| s.rs_gfx) as *mut c_void; + if let Some(r) = ID3D12RootSignature::from_raw_borrowed(&rs) { + list.SetGraphicsRootSignature(r); + with(this, |s| s.pc_abi_gfx = AbiBound::default()); + } + return Some(list); + } + } + if super::present::trace_frame() { + trace_ui_draw(this, pso); + } + match bind_abi(this, &list, pso, true, 0, None) { + Ok(()) => { + count(DRAWS); + Some(list) + } + Err(e) => { + super::list_x::note_dropped_draw(this); + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: draw with a translated pipeline skipped: {e}"); + } + None + } + } +} + +/// `XCL_TRACE_FRAME`: draws into a presented buffer (the UI) once the title has presented for a +/// while – their pipeline, root arguments and the resources their descriptor tables start with +/// (format, size, kept in step with title memory or not). The first 24. +/// `XCL_TRACE_FRAME`, after 300 presents: one line per distinct (VS, PS, render target) drawn – +/// the shaders' dump hashes, the target and the textures of the first descriptor table. +unsafe fn trace_draw_kinds(this: *mut c_void, pso: usize) { + // keyed by the target's shape, not the object: a UI library's transient targets (Renoir's + // layers) are new objects every frame and would fill the list at once + static SEEN: Mutex)>> = Mutex::new(Vec::new()); + if super::present::activity().0 < 300 { + return; + } + let Some((vs, ps)) = super::real::pso_shaders(super::pso_async::resolve(pso)) else { return }; + let rt = super::present::rt0_resource(this as usize).unwrap_or(0); + let desc = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0, d.SampleDesc.Count) }); + { + let mut g = SEEN.lock().unwrap(); + let key = (vs, ps, desc(rt)); + if g.len() >= 160 || g.contains(&key) { + return; + } + g.push(key); + } + let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.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 tex = Vec::new(); + if let (Some(layout), Some(u)) = (layout, crate::gpu::uma::get()) { + for p in layout.params.iter() { + if let Param::Table { at } = *p { + let t = word(at as usize) as usize; + for k in 0..4usize { + if let Some(r) = super::console_heap::resource_at(u.base() + t + 32 * k) { + tex.push(format!("{:?}{}", desc(r), super::title_textures::address(r).map_or(String::new(), |a| format!(" at {a:#x}")))); + } + } + } + if tex.len() >= 4 { + break; + } + } + } + crate::xlog_info!( + "frame trace: draws vs {vs:016x} ps {ps:016x} into {:?}{} – textures {}; {}", + desc(rt), + if super::present::is_presented(rt) { " (presented)" } else { "" }, + tex.join(", "), + super::list_x::state_summary(this) + ); +} + +/// `XCL_TRACE_SHADERS=hash,…` (dump hashes, hex): the draws traced with their root arguments +/// are those whose vertex or pixel shader is listed – into any target, at any time (the first +/// 24); without it, draws into a presented target (or any – `XCL_TRACE_UI_ANY`) after 300 +/// presents. +fn traced_shaders() -> &'static [u64] { + static S: std::sync::OnceLock> = std::sync::OnceLock::new(); + S.get_or_init(|| std::env::var("XCL_TRACE_SHADERS").unwrap_or_default().split(',').filter_map(|h| u64::from_str_radix(h.trim(), 16).ok()).collect()) +} + +/// `XCL_TRACE_FRAME` with a watched target (`present::watch_rt`): draws whose descriptor +/// tables name it – that object, or another at its title address (the first 16). +unsafe fn trace_reads_of_watched(this: *mut c_void, pso: usize) { + let Some(w) = super::present::watched_rt() else { return }; + let w_addr = super::real::title_address(w).or_else(|| super::title_textures::address(w)); + let Some(u) = crate::gpu::uma::get() else { return }; + let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.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) as usize; + for k in 0..16usize { + let Some(r) = super::console_heap::resource_at(u.base() + t + 32 * k) else { continue }; + let addr = super::real::title_address(r).or_else(|| super::title_textures::address(r)); + if super::present::is_watched(r) || (addr.is_some() && addr == w_addr) { + let rt = super::present::rt0_resource(this as usize).unwrap_or(0); + // each (source, target, shaders) once + static SEEN: Mutex> = Mutex::new(Vec::new()); + { + let mut g = SEEN.lock().unwrap(); + if g.len() >= 32 || g.contains(&(r, rt, pso)) { + return; + } + g.push((r, rt, pso)); + } + if !super::present::is_presented(rt) { + super::present::follow(rt); + } + if let Some(dsv) = super::list_x::bound_dsv(this) { + super::list_x::watch_dsv(dsv); + } + let d = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0, d.Flags.0) }); + crate::xlog_info!( + "frame trace: a draw (shaders {:x?}, {}) reads a watched target {r:#x} {:?} at {addr:x?} (slot {k}), drawing into {rt:#x} {:?}{} – {}", + super::real::pso_shaders(super::pso_async::resolve(pso)), + super::list_x::state_summary(this), + d(r), + d(rt), + if super::present::is_presented(rt) { " (presented)" } else { "" }, + root_args_summary(this, 32) + ); + let args = DRAW_ARGS.with(|d| d.get()); + crate::xlog_info!( + "frame trace: … that draw: {args:?} (indexed, count, instances, first, base vertex); input layout [{}]; {}", + super::real::pso_layout(super::pso_async::resolve(pso)).unwrap_or_default(), + super::list_x::geometry_summary(this, args) + ); + return; + } + } + } +} + +/// `XCL_TRACE_FRAME`: render targets a draw into the watched target samples (a UI library's +/// layers) are dumped with it (`present::follow`). +unsafe fn follow_layer_sources(this: *mut c_void) { + let (Some(w), Some(rt)) = (super::present::watched_rt(), super::present::rt0_resource(this as usize)) else { return }; + if rt != w { + return; + } + let Some(u) = crate::gpu::uma::get() else { return }; + let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.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) as usize; + for k in 0..4usize { + let Some(r) = super::console_heap::resource_at(u.base() + t + 32 * k) else { continue }; + let layer = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).is_some_and(|x| { + let d = x.GetDesc(); + d.Flags.0 & 1 != 0 && d.Width >= 64 && d.Height >= 32 && d.SampleDesc.Count == 1 + }); + if layer && r != w { + super::present::follow(r); + } + } + } +} + +unsafe fn trace_ui_draw(this: *mut c_void, pso: usize) { + trace_draw_kinds(this, pso); + trace_reads_of_watched(this, pso); + follow_layer_sources(this); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + // `XCL_TRACE_MANY=n`: n draws instead of 24 (a whole frame of a UI) + static CAP: std::sync::OnceLock = std::sync::OnceLock::new(); + let cap = *CAP.get_or_init(|| std::env::var("XCL_TRACE_MANY").ok().and_then(|v| v.parse().ok()).unwrap_or(24)); + if N.load(std::sync::atomic::Ordering::Relaxed) >= cap { + return; + } + let Some(rt) = super::present::rt0_resource(this as usize) else { return }; + let wanted = traced_shaders(); + if wanted.is_empty() { + // draws into a presented target, or – `XCL_TRACE_UI_ANY` – into any target + if super::present::activity().0 < 300 || (!super::present::is_presented(rt) && std::env::var_os("XCL_TRACE_UI_ANY").is_none()) { + return; + } + } else if !super::real::pso_shaders(super::pso_async::resolve(pso)).is_some_and(|(v, p)| wanted.contains(&v) || wanted.contains(&p)) { + return; + } else { + super::present::watch_rt(rt); + } + N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let sh = super::real::pso_shaders(super::pso_async::resolve(pso)).map(|(v, p)| format!("vs {v:016x} ps {p:016x}")); + crate::xlog_info!("frame trace: UI draw (pipeline {pso:#x}, {}): {}", sh.unwrap_or_default(), root_args_summary(this, 16)); + if !wanted.is_empty() { + // the picked shaders' geometry too (vertices dumped at the next present) + let args = DRAW_ARGS.with(|d| d.get()); + crate::xlog_info!( + "frame trace: … that draw: {args:?} (indexed, count, instances, first, base vertex); input layout [{}]; {}", + super::real::pso_layout(super::pso_async::resolve(pso)).unwrap_or_default(), + super::list_x::geometry_summary(this, args) + ); + } +} + +/// 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 { + let Some(u) = crate::gpu::uma::get() else { return String::new() }; + let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); + let Some(layout) = layout else { return String::new() }; + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); + let mut what = Vec::new(); + for (i, p) in layout.params.iter().enumerate() { + match *p { + Param::Constants { at, count } => what.push(format!("p{i} constants {:x?}", (0..count.min(8) as usize).map(|k| word(at as usize + 4 * k)).collect::>())), + Param::Descriptor { at } => { + let va = (word(at as usize) as u64 | (word(at as usize + 4) as u64) << 32) as usize; + let w: Vec = if va != 0 && crate::gpu::shader::readable(va, 4 * buffer_words) { (0..buffer_words).map(|k| ((va + 4 * k) as *const u32).read_unaligned()).collect() } else { Vec::new() }; + what.push(format!("p{i} buffer {va:#x} {w:x?}")); + } + Param::Table { at } => { + let t = word(at as usize) as usize; + let slots: Vec = (0..4usize) + .map(|k| { + let at = u.base() + t + 32 * k; + let w = super::console_heap::words_at((t + 32 * k) as u32); + match super::console_heap::resource_at(at) { + Some(r) => { + if super::title_textures::address(r).is_some() { + super::title_textures::probe_gpu_content(r); + } + let d = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| x.GetDesc()); + format!("[{k}] {r:#x} {:?} title {:?} T# {:x?}", d.map(|d| (d.Dimension.0, d.Width, d.Height, d.Format.0)), super::title_textures::address(r).map(|a| format!("{a:#x}")), w.map(|w| w[..4].to_vec())) + } + None => format!("[{k}] - T# {:x?}", w.map(|w| w[..4].to_vec())), + } + }) + .collect(); + what.push(format!("p{i} table {t:#x}: {}", slots.join(", "))); + } + } + } + what.join("; ") +} + +/// #33 SetComputeRootSignature (PC #29) +pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_void, rs: *mut c_void) { + let layout = console_list::layout_of(rs as usize); + with(this, |s| { + let same = console_list::same_layout(&s.layout, &layout); + if same && s.rs_cs == rs as usize { + return; + } + if !same { + let size = layout.as_ref().map_or(0, |l| l.size as usize); + s.args.clear(); + s.args.resize(size, 0); + } + s.layout = layout; + s.rs_cs = rs as usize; + s.args_gen_cs = s.args_gen_cs.wrapping_add(1); + s.io_cache_cs = None; + }); +} + +/// #35 SetComputeRootDescriptorTable (PC #31): the table's console address, 32 bits +pub(super) unsafe extern "system" fn set_compute_root_table(this: *mut c_void, i: u32, handle: u64) { + put(this, i, 0, &(handle as u32).to_le_bytes()); +} + +/// #37 SetComputeRoot32BitConstant (PC #33) +pub(super) unsafe extern "system" fn set_compute_root_constant(this: *mut c_void, i: u32, value: u32, offset: u32) { + put(this, i, offset, &value.to_le_bytes()); +} + +/// #39 SetComputeRoot32BitConstants (PC #35) +pub(super) unsafe extern "system" fn set_compute_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { + if !data.is_null() && n > 0 { + #[cfg(target_endian = "little")] + let bytes = std::slice::from_raw_parts(data.cast::(), (n as usize).saturating_mul(4)); + #[cfg(not(target_endian = "little"))] + let bytes_vec: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); + #[cfg(not(target_endian = "little"))] + let bytes = bytes_vec.as_slice(); + put(this, i, offset, bytes); + } +} + +/// #41 / #43 / #45 SetComputeRoot{ConstantBuffer,ShaderResource,UnorderedAccess}View (PC #37 / +/// #39 / #41): the 64-bit GPU address +pub(super) unsafe extern "system" fn set_compute_root_descriptor(this: *mut c_void, i: u32, va: u64) { + note_address(va); + let va = resolve_root_for_list(this, va); + put(this, i, 0, &va.to_le_bytes()); +} + +/// #25 SetPipelineState: noted, then bound as on the PC +pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: *mut c_void) { + with(this, |s| { + if s.pso != pso as usize { + s.pso = pso as usize; + s.pso_abi_cache = None; + } + }); + super::real::bind_pipeline(this, pso); +} + +/// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments +pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { + let pso = with(this, |s| { + s.inline_guard = None; + s.pso + }); + if super::pso_async::is_pending(pso) + && !super::pso_async::is_spared(pso) + && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z)) + { + return super::pso_async::need_by_submit(pso); + } + let pso = super::pso_async::resolve_wait(pso); + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + if !super::real::is_translated_compute(pso) { + // a console pipeline without a translation (including a background build that + // failed): nothing to run (its root arguments were not given to the PC list either) + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: Dispatch with a pipeline that has no translated console shader ({pso:#x}) skipped"); + } + count(DISPATCHES_SKIPPED); + return; + } + match translated_dispatch(this, list, pso, x, y, z) { + Ok(()) => count(DISPATCHES), + Err(e) => { + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: Dispatch with a translated pipeline skipped: {e}"); + } + } + } +} + +/// `XCL_TRACE_FRAME`: a full-screen dispatch (enough groups to cover a 4K target in tiles of up +/// to 128 pixels) – what its root arguments say. A bindless title passes the indices of its +/// descriptors in root constants and constant buffers: every small value there is looked up +/// in the dispatch's descriptor tables, and the resources found (the pass's inputs and +/// outputs) are logged. +unsafe fn trace_fullscreen(this: *mut c_void, pso: usize, groups: [u32; 3]) { + if groups[0] < 30 || groups[1] < 17 { + 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 }; + static SEEN: Mutex> = Mutex::new(Vec::new()); + { + let mut g = SEEN.lock().unwrap(); + if g.contains(&pso) || g.len() >= 12 { + return; + } + g.push(pso); + } + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); + let mut tables: Vec = Vec::new(); + let mut values: Vec = Vec::new(); + let mut what: Vec = Vec::new(); + for (i, p) in layout.params.iter().enumerate() { + match *p { + Param::Constants { at, count } => { + let w: Vec = (0..count as usize).filter_map(|k| word(at as usize + 4 * k)).collect(); + what.push(format!("p{i} constants {w:x?}")); + values.extend(&w); + } + 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; + let n = 64usize; + if va != 0 && crate::gpu::shader::readable(va, 4 * n) { + let w: Vec = (0..n).map(|k| ((va + 4 * k) as *const u32).read_unaligned()).collect(); + what.push(format!("p{i} buffer {va:#x}: {w:x?}")); + values.extend(&w); + } else { + what.push(format!("p{i} buffer {va:#x} (not readable)")); + } + } + Param::Table { at } => { + let v = word(at as usize).unwrap_or(0); + what.push(format!("p{i} table {v:#x}")); + tables.push(v); + } + } + } + let mut found: Vec<(u32, usize)> = Vec::new(); + for &v in &values { + if v >= 1 << 20 { + continue; + } + for &t in &tables { + let slot = u.base() + t as usize + 32 * v as usize; + if let Some(r) = super::console_heap::resource_at(slot) { + if !found.iter().any(|x| x.1 == r) { + found.push((v, r)); + } + } + } + } + let res: Vec = found + .iter() + .map(|&(v, r)| { + let d = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| x.GetDesc()); + format!("[{v}] {r:#x} {:?}{}", d.map(|d| (d.Dimension.0, d.Width, d.Height, d.Format.0)), if super::present::is_presented(r) { " PRESENTED" } else { "" }) + }) + .collect(); + crate::xlog_info!("frame trace: full-screen dispatch {groups:?}, pipeline {pso:#x}: {}", what.join("; ")); + crate::xlog_info!("frame trace: … its indices name: {}", if res.is_empty() { "nothing".to_string() } else { res.join("; ") }); +} + +/// #148 AllocateUploadMemory(size, alignment) → CPU/GPU pointer in unified memory (used by +/// `XboxBvhBuilder.dll` and other console middleware on default title command lists). +/// Freed automatically when the list's command allocator is reset. +pub(super) unsafe extern "system" fn allocate_upload_memory(this: *mut c_void, size: usize, align: usize) -> *mut u8 { + let Some(u) = crate::gpu::uma::get() else { + return std::ptr::null_mut(); + }; + let size = size.max(16); + let align = align.max(16); + if size <= crate::gpu::uma::UPLOAD_IN_ARENA_MOST { + if let Some(p) = with(this, |s| s.arena.take(u, size, align, &mut s.uma)) { + return p; + } + } + if u.has_sparse() { + if let Some((p, _)) = super::sparse::alloc(size, align) { + with(this, |s| s.uma.push(p)); + return p as *mut u8; + } + } + match u.alloc(size, align) { + Some(p) => { + with(this, |s| s.uma.push(p as usize)); + p + } + None => std::ptr::null_mut(), + } +} + +unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, x: u32, y: u32, z: u32) -> Result<(), String> { + if super::present::trace_frame() { + trace_fullscreen(this, pso, [x, y, z]); + } + // more groups in X than D3D12 takes: folded (`recomp::IO_GROUP_LIMIT`) + let (limit, [x, y, z]) = fold(x, y, z); + bind_abi(this, list, pso, false, limit, None)?; + let mark = super::culprit::before_dispatch(list, with(this, |s| s.pso), pso, [x, y, z]); + let r = super::real::dispatch_chain::dispatch(list, pso, with(this, |s| s.allocator), [x, y, z]); + super::culprit::after_dispatch(list, mark); + 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, [x, y, z], layout.as_deref(), &args, view_heap); + } + with(this, |s| { + s.arg_order_clean = false; + s.prelude_blocked = true; + }); + r +} + +/// A dispatch of `x` x `y` x `z` groups as D3D12 takes it: (the count for +/// `recomp::IO_GROUP_LIMIT` - 0: not folded -, the groups to dispatch). More than 65 535 in X +/// with 1 in Y is folded into Y; any other count past 65 535 is clamped (logged once). +pub(super) fn fold(x: u32, y: u32, z: u32) -> (u32, [u32; 3]) { + use crate::gpu::recomp::FOLD_X; + if x <= FOLD_X && y <= 65_535 && z <= 65_535 { + return (0, [x, y, z]); + } + if y == 1 && z <= 65_535 && x.div_ceil(FOLD_X) <= 65_535 { + return (x, [FOLD_X, x.div_ceil(FOLD_X), z]); + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: a dispatch of {x}x{y}x{z} groups cannot be folded – clamped to 65535 a dimension"); + } + (0, [x.min(65_535), y.min(65_535), z.min(65_535)]) +} + +/// Allocate a dedicated compute `io` buffer in UMA for an indirect dispatch whose `IO_GROUP_LIMIT` +/// slot will be written on the GPU by `guard_dispatch_args`. Returns `(gpu_va, host_ptr)`. +unsafe fn alloc_fresh_compute_io(this: *mut c_void, pso: usize) -> Result<(u64, usize), String> { + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let real = super::pso_async::resolve_wait(pso); + let user_sgprs = super::real::pso_user_sgprs(real); + with(this, |s| -> Result<(u64, usize), String> { + if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { + let w = super::real::uma_window_vas(); + if w.is_empty() { + return Err("unified memory is not open on the GPU".into()); + } + s.uma_windows = Some(w); + } + let windows = s.uma_windows.as_deref().unwrap(); + let first = windows[0]; + let inline = s.layout.as_deref().map_or(0, |l| console_list::inline_for(l, user_sgprs) as usize).min(s.args.len()); + let table_at = upload_arg_table(u, &mut s.arena, &mut s.uma, &mut s.dummy_table_p, &s.args[inline..])?; + let io = fill_io_compute(s.layout.as_deref(), user_sgprs, s.args.as_slice(), table_at, s.heaps, u.base(), 0); + let io_bytes = std::mem::size_of_val(&io); + let io_p = s.arena.take(u, io_bytes.max(16), 256, &mut s.uma).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(io.as_ptr().cast::(), io_p, io_bytes); + Ok((uma_va_in(u, windows, io_p as usize).unwrap_or(first), io_p as usize)) + }) +} + +/// XCL's ABI for a translated pipeline: its root signature, the user SGPRs (`io`, the kept +/// arguments the console's way – compute or graphics) and the argument table in unified +/// memory, u1 res, u2… the memory windows; then the pipeline. `group_limit`: a folded +/// dispatch's group count in X (`recomp::IO_GROUP_LIMIT`), 0 for any other. +unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool, group_limit: u32, preset_io_va: Option) -> Result<(), String> { + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let (need_heaps, cached_pso, need_io_dev) = with(this, |s| { + let c = s.pso_abi_cache.filter(|c| c.query_pso == pso && c.is_gfx == gfx); + let io_hit = preset_io_va.is_some() + || (group_limit == 0 + && if gfx { + s.io_cache_gfx.is_some_and(|(gen, _)| gen == s.args_gen_gfx) + } else { + c.is_some_and(|ci| s.io_cache_cs.is_some_and(|(gen, sg, _)| gen == s.args_gen_cs && sg == ci.user_sgprs)) + }); + (!s.heaps_ensured, c, (!io_hit || s.dummy_res_va == 0) && s.vram_io_dev.is_none()) + }); + if need_heaps { + ensure_heaps_cached(this); + } + let (real, user_sgprs, rs_raw, store_pso_cache) = match cached_pso { + Some(c) => (c.real_pso, c.user_sgprs, c.rs_raw, false), + None => { + // a pipeline still being built in the background is waited for + let real = super::pso_async::resolve_wait(pso); + // a compute shader takes no more arguments from registers than it has (`inline_for`) + let user_sgprs = if gfx { None } else { super::real::pso_user_sgprs(real) }; + let rs_raw = super::real::pso_root_signature(real) + .or_else(|| super::real::abi_rs_cached().map(|p| p as usize)) + .ok_or("no XCL ABI root signature")?; + (real, user_sgprs, rs_raw, true) + } + }; + if need_io_dev { + let _ = ensure_vram_io_dev(this); + } + let rs_ptr = rs_raw as *mut c_void; + let rs = ID3D12RootSignature::from_raw_borrowed(&rs_ptr).ok_or("root signature")?; + let real_ptr = real as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&real_ptr).ok_or("pipeline")?; + + let (set_rs, uav_mask, views) = with(this, |s| -> Result<(bool, u8, [u64; 6]), String> { + if store_pso_cache { + s.pso_abi_cache = Some(CachedPsoAbi { + query_pso: pso, + real_pso: real, + rs_raw, + user_sgprs, + is_gfx: gfx, + }); + } + if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { + let w = super::real::uma_window_vas(); + if w.is_empty() { + return Err("unified memory is not open on the GPU".into()); + } + s.uma_windows = Some(w); + } + let windows = s.uma_windows.as_deref().unwrap(); + let first = windows[0]; + let win_vas = [ + first, + windows.get(1).copied().filter(|&v| v != 0).unwrap_or(first), + windows.get(2).copied().filter(|&v| v != 0).unwrap_or(first), + windows.get(3).copied().filter(|&v| v != 0).unwrap_or(first), + ]; + + // Runtime VS/PS/CS shaders never write to `u1` (`res`), so one zeroed 256-byte slot + // per recording suffices across all `bind_abi` draws and dispatches. + if s.dummy_res_va == 0 { + s.dummy_res_va = match s.vram_io_dev.as_ref().and_then(|o| o.as_ref()).and_then(|dev| alloc_vram_io_in(&mut s.io_blocks, s.allocator, s.prelude_built.is_some(), &dev.0, &[0u8; 256])) { + Some(va) => va, + None => { + let p = s.arena.take(u, 256, 256, &mut s.uma).ok_or("unified memory is full")?; + std::ptr::write_bytes(p, 0, 256); + uma_va_in(u, windows, p as usize).unwrap_or(first) + } + }; + } + let res_va = s.dummy_res_va; + + let io_va = if let Some(va) = preset_io_va { + va + } else { + let cached_io = if group_limit != 0 { + None + } else if gfx { + s.io_cache_gfx.filter(|&(gen, _)| gen == s.args_gen_gfx).map(|(_, va)| va) + } else { + s.io_cache_cs.filter(|&(gen, sgprs, _)| gen == s.args_gen_cs && sgprs == user_sgprs).map(|(_, _, va)| va) + }; + if let Some(va) = cached_io { + va + } else { + let tail = if gfx { + let inline = s.layout_gfx.as_deref().map_or(0, |l| l.inline_gfx as usize).min(s.args_gfx.len()); + &s.args_gfx[inline..] + } else { + let inline = s.layout.as_deref().map_or(0, |l| console_list::inline_for(l, user_sgprs) as usize).min(s.args.len()); + &s.args[inline..] + }; + // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) + let table_at = upload_arg_table(u, &mut s.arena, &mut s.uma, &mut s.dummy_table_p, tail)?; + let io = if gfx { + fill_io_gfx(s.layout_gfx.as_deref(), s.args_gfx.as_slice(), table_at, s.heaps, u.base()) + } else { + fill_io_compute(s.layout.as_deref(), user_sgprs, s.args.as_slice(), table_at, s.heaps, u.base(), group_limit) + }; + let io_bytes = std::mem::size_of_val(&io); + let io_slice = std::slice::from_raw_parts(io.as_ptr().cast::(), io_bytes); + let va = match s.vram_io_dev.as_ref().and_then(|o| o.as_ref()).and_then(|dev| alloc_vram_io_in(&mut s.io_blocks, s.allocator, s.prelude_built.is_some(), &dev.0, io_slice)) { + Some(va) => va, + None => { + let io_p = s.arena.take(u, io_bytes.max(16), 256, &mut s.uma).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(io_slice.as_ptr(), io_p, io_bytes); + uma_va_in(u, windows, io_p as usize).unwrap_or(first) + } + }; + if group_limit == 0 { + if gfx { + s.io_cache_gfx = Some((s.args_gen_gfx, va)); + } else { + s.io_cache_cs = Some((s.args_gen_cs, user_sgprs, va)); + } + } + va + } + }; + + let views = [io_va, res_va, win_vas[0], win_vas[1], win_vas[2], win_vas[3]]; + let bound = if gfx { &mut s.pc_abi_gfx } else { &mut s.pc_abi_cs }; + let (set_rs, uav_mask) = diff_abi_bindings(bound, rs_raw, views); + Ok((set_rs, uav_mask, views)) + })?; + + emit_abi_bindings(list, gfx, rs, set_rs, uav_mask, views); + list.SetPipelineState(pc); + Ok(()) +} + +#[cfg(test)] +pub(super) fn last_draw_args() -> (bool, u32, u32, u32, i32) { + DRAW_ARGS.with(|d| d.get()) +} + +/// `list`'s compute arguments without a title root signature: `args` is the whole argument table. +#[cfg(test)] +pub(super) fn set_args_for_test(list: *mut c_void, args: Vec) { + with(list, |s| { + s.layout = None; + s.args = args; + }); +} + +#[cfg(test)] +pub(super) fn counts_snapshot() -> [u64; 5] { + std::array::from_fn(|k| COUNTS[k].load(Ordering::Relaxed)) +} + +#[cfg(test)] +pub(super) fn tracked_pso(list: *mut c_void) -> usize { + let key = list as usize; + STATES[state_shard(key)] + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&key)) + .map_or(0, |s| s.pso) +} + +/// Tracked console `(graphics_root_signature, compute_root_signature)` on `list` for restoring +/// PC root signatures after an internal graphics/compute sync pass (invalidating cached PC ABI +/// root bindings since the internal pass clobbered them). +pub(super) fn tracked_root_sigs(list: *mut c_void) -> (usize, usize) { + let key = list as usize; + STATES[state_shard(key)] + .lock() + .unwrap() + .as_mut() + .and_then(|m| m.get_mut(&key)) + .map_or((0, 0), |s| { + s.pc_abi_gfx = AbiBound::default(); + s.pc_abi_cs = AbiBound::default(); + s.heaps_ensured = false; + (s.rs_gfx, s.rs_cs) + }) +} + +#[cfg(test)] +mod tests { + use super::super::{device_x, list_x, pso_async, real, title_list}; + use super::*; + use std::sync::atomic::AtomicUsize; + + /// `XCL_TWO_PASS_LIST_MB`: 32 MiB unset, 0 or unreadable; at most 128 MiB. + #[test] + fn a_two_pass_indirect_record_buffer_takes_its_size_from_the_switch() { + assert_eq!(two_pass_list_mb(None), 32); + assert_eq!(two_pass_list_mb(Some("8")), 8); + assert_eq!(two_pass_list_mb(Some(" 16 ")), 16); + assert_eq!(two_pass_list_mb(Some("0")), 32); + assert_eq!(two_pass_list_mb(Some("x")), 32); + assert_eq!(two_pass_list_mb(Some("1000")), 128); + } + + #[test] + fn inline_guard_batch_defaults_off_and_opts_in() { + assert!(!parse_inline_guard_batch(None)); + assert!(!parse_inline_guard_batch(Some("0"))); + assert!(!parse_inline_guard_batch(Some(""))); + assert!(parse_inline_guard_batch(Some("1"))); + assert!(parse_inline_guard_batch(Some(" 1 "))); + } + + /// A pipeline with the rect list GS draws its rect lists whole: draw_rects leaves them alone. + #[test] + fn rect_lists_with_the_rect_list_gs_are_not_expanded_on_the_cpu() { + let (with_gs, without) = (0x7E57_4000usize, 0x7E57_5000usize); + real::register_rect_list_gs_for_test(with_gs); + assert!(!cpu_rect_expansion(with_gs)); + assert!(cpu_rect_expansion(without) && cpu_rect_expansion(0)); + real::forget_pso_for_test(with_gs); + assert!(cpu_rect_expansion(with_gs)); + } + + /// An ExecuteIndirect whose bound pipeline is still being built is skipped (its stand-in + /// with XCL's ABI root signature on the list is the debug layer's 953 and a hung GPU); /// a built or failed one goes to the PC call. The gate `execute_indirect` uses. #[test] fn execute_indirect_with_a_pipeline_still_building_is_skipped() { @@ -1273,6 +5173,22 @@ void main(uint t : SV_GroupIndex) { } } + /// Both graphics and compute draws wait within their per-frame pipeline wait window + /// (`XCL_PSO_FRAME_BUDGET_MS`) so cold compiles that finish in time render on their first use. + #[test] + fn a_draw_waits_for_a_graphics_pipeline_within_the_frame_window() { + let (graphics, compute) = (0x7E57_6101usize, 0x7E57_6102usize); + pso_async::submit_lazy(graphics, false, Box::new(|| { + std::thread::sleep(std::time::Duration::from_millis(50)); + 0x1301 + }), 0); + pso_async::submit_lazy(compute, true, Box::new(|| 0x1302), 0); + assert_eq!(pso_for_draw(graphics), 0x1301, "graphics waited within frame window"); + assert_eq!(pso_for_draw(compute), 0x1302, "compute waited within frame window"); + pso_async::released(graphics); + pso_async::released(compute); + } + /// Minimal RTS0 v2 root signature blob with one 4-constant parameter. fn test_rts0_blob() -> Vec { let words: [u32; 12] = [ @@ -1356,6 +5272,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, @@ -1387,442 +5347,1684 @@ void main(uint t : SV_GroupIndex) { (*(this as *const FakeAdoptedList)).set_compute_rs_calls.fetch_add(1, Ordering::Relaxed); } - unsafe extern "system" fn fake_set_compute_uav(this: *mut c_void, _slot: u32, _va: u64) { - (*(this as *const FakeAdoptedList)).set_compute_uav_calls.fetch_add(1, Ordering::Relaxed); - } + unsafe extern "system" fn fake_set_compute_uav(this: *mut c_void, _slot: u32, _va: u64) { + (*(this as *const FakeAdoptedList)).set_compute_uav_calls.fetch_add(1, Ordering::Relaxed); + } + + unsafe extern "system" fn fake_execute_indirect( + this: *mut c_void, + _sig: usize, + _max: u32, + _args: usize, + _args_off: u64, + _count_buf: usize, + _count_off: u64, + ) { + (*(this as *const FakeAdoptedList)).execute_indirect_calls.fetch_add(1, Ordering::Relaxed); + } + + #[test] + fn async_compute_pso_success_and_failure_in_dispatch_and_execute_indirect() { + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fake_add_ref as usize; + orig_vt[2] = fake_release as usize; + orig_vt[14] = fake_dispatch as usize; + orig_vt[25] = fake_set_pso as usize; + orig_vt[29] = fake_set_compute_rs as usize; + orig_vt[41] = fake_set_compute_uav as usize; + orig_vt[59] = fake_execute_indirect as usize; + + // Extended vtable layout expected by `real::orig_fn`: entry -1 holds `orig_vt` pointer, + // and entries 0..64 hold the COM method pointers used via `ID3D12GraphicsCommandList`. + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + + let fake = Box::new(FakeAdoptedList { + // SAFETY: `ext_vt` has 65 elements so `.add(1)` points to slot 0 with `orig_vt` at `-1`. + vt: unsafe { ext_vt.as_ptr().add(1) }, + refs: AtomicUsize::new(1), + dispatch_calls: AtomicUsize::new(0), + set_compute_rs_calls: AtomicUsize::new(0), + set_compute_uav_calls: AtomicUsize::new(0), + set_pso_calls: AtomicUsize::new(0), + execute_indirect_calls: AtomicUsize::new(0), + }); + let list_ptr = &*fake as *const FakeAdoptedList as *mut c_void; + + // 1. Background compute build SUCCEEDS: real PSO R is registered in TRANSLATED_COMPUTE, + // stand-in S is NOT. ExecuteIndirect resolves S -> R and treats it as translated. + let standin_ok = 0x7200_0001usize; + let real_ok = 0x7200_0002usize; + let sig_root_changing = 0x7200_00F0usize; + note_root_changing_signature(sig_root_changing, true); + + pso_async::submit( + standin_ok, + true, + Box::new(move || { + real::register_translated_compute_for_test(real_ok); + real_ok + }), + ); + assert_eq!(pso_async::resolve_wait(standin_ok), real_ok); + assert!(!real::is_translated_compute(standin_ok)); + assert!(real::is_translated_compute(real_ok)); + + reset(list_ptr, 0x7200_0100, standin_ok); + unsafe { + // With `sig_root_changing`, a translated compute PSO is caught by the root-changing + // guard instead of falling through to `pc` (which happened when `R` wasn't registered). + execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); + } + assert_eq!( + fake.execute_indirect_calls.load(Ordering::Relaxed), + 0, + "ExecuteIndirect must recognize resolved async compute PSO R as translated" + ); + + // 2. Background compute build FAILS (returns 0): stand-in S_fail is NOT in + // TRANSLATED_COMPUTE. Dispatch must skip cleanly without binding XCL's ABI RS/UAVs + // onto S_fail, and ExecuteIndirect must not enter bind_abi either. + let standin_fail = 0x7200_0003usize; + pso_async::submit(standin_fail, true, Box::new(|| 0)); + assert_eq!(pso_async::resolve_wait(standin_fail), standin_fail); + assert!(!real::is_translated_compute(standin_fail)); + + reset(list_ptr, 0x7200_0100, standin_fail); + let before = counts_snapshot(); + unsafe { + dispatch(list_ptr, 1, 1, 1); + } + let after = counts_snapshot(); + assert_eq!(after[DISPATCHES], before[DISPATCHES]); + assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]); + assert_eq!(fake.set_compute_rs_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.set_compute_uav_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.dispatch_calls.load(Ordering::Relaxed), 0); + + unsafe { + execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); + } + assert_eq!(fake.set_compute_rs_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.set_compute_uav_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 0); + assert_eq!( + fake.execute_indirect_calls.load(Ordering::Relaxed), + 1, + "failed async compute stand-in must not enter translated ExecuteIndirect path" + ); + + // 3. The same failed stand-in (made from a console shader) with a Dispatch signature: + // nothing to run, as for Dispatch – the PC call would pair the stand-in with the list's + // compute root signature (XCL's ABI one after a translated dispatch: debug layer 953) + let sig_dispatch = 0x7200_00F8usize; + real::register_console_compute_for_test(standin_fail); + note_signature_dispatches(sig_dispatch, true); + let before = counts_snapshot(); + unsafe { + execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + } + let after = counts_snapshot(); + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 1, "a dispatch of an untranslated console compute pipeline must not reach the PC ExecuteIndirect"); + assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]); + + // 4. A native PC compute pipeline (not made from a console shader) with the same Dispatch + // signature still goes to the PC call, as on main + let native = 0x7200_0004usize; + reset(list_ptr, 0x7200_0100, native); + unsafe { + execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + } + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 2, "a native PC compute pipeline must still reach the PC ExecuteIndirect"); + + // a signature made later at the same address without a Dispatch argument goes to the PC + reset(list_ptr, 0x7200_0100, standin_fail); + note_signature_dispatches(sig_dispatch, false); + unsafe { + execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + } + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 3); + + forget(list_ptr); + let _ = pso_async::released(standin_ok); + let _ = pso_async::released(standin_fail); + real::forget_pso_for_test(real_ok); + real::forget_pso_for_test(standin_fail); + assert!(!real::is_console_compute(standin_fail), "a released pipeline's address does not stay a console one"); + } + + #[test] + fn a_command_signature_made_at_a_freed_ones_address_does_not_keep_its_kind() { + let sig = 0x7230_00F0usize; + let changing = |s: usize| ROOT_SIGNATURES.read().unwrap().as_ref().is_some_and(|set| set.contains(&s)); + note_root_changing_signature(sig, true); + assert!(changing(sig)); + // the signature is freed; a simple one is made at its address + note_root_changing_signature(sig, false); + assert!(!changing(sig)); + } + + #[test] + fn execute_indirect_skips_failed_shared_console_compute_standin() { + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fake_add_ref as usize; + orig_vt[2] = fake_release as usize; + orig_vt[14] = fake_dispatch as usize; + orig_vt[25] = fake_set_pso as usize; + orig_vt[29] = fake_set_compute_rs as usize; + orig_vt[41] = fake_set_compute_uav as usize; + orig_vt[59] = fake_execute_indirect as usize; + + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + + let fake = Box::new(FakeAdoptedList { + vt: unsafe { ext_vt.as_ptr().add(1) }, + refs: AtomicUsize::new(1), + dispatch_calls: AtomicUsize::new(0), + set_compute_rs_calls: AtomicUsize::new(0), + set_compute_uav_calls: AtomicUsize::new(0), + set_pso_calls: AtomicUsize::new(0), + execute_indirect_calls: AtomicUsize::new(0), + }); + let list_ptr = &*fake as *const FakeAdoptedList as *mut c_void; + + // With shared stand-ins (`standin::shell`), `dev_create_compute_pso` registers the + // title-facing shell in `CONSOLE_COMPUTE`, while `pso_async::resolve_wait` returns the + // shared driver pipeline when the background build fails. + let shell_fail = 0x7210_0001usize; + let shell_ok = 0x7210_0002usize; + let shared_driver = 0x7210_0003usize; + let real_ok = 0x7210_0004usize; + let sig_dispatch = 0x7210_00F8usize; + let sig_root_changing = 0x7210_00F0usize; + note_signature_dispatches(sig_dispatch, true); + note_root_changing_signature(sig_root_changing, true); + + pso_async::submit_lazy(shell_fail, true, Box::new(|| 0), 0); + pso_async::shared(shell_fail, shared_driver); + real::register_console_compute_for_test(shell_fail); + + pso_async::submit_lazy( + shell_ok, + true, + Box::new(move || { + real::register_translated_compute_for_test(real_ok); + real_ok + }), + 0, + ); + pso_async::shared(shell_ok, shared_driver); + real::register_console_compute_for_test(shell_ok); + + assert_eq!(pso_async::resolve_wait(shell_fail), shared_driver); + assert!(!pso_async::is_pending(shell_fail)); + assert!(real::is_console_compute(shell_fail)); + assert!(!real::is_console_compute(shared_driver)); + + // 1. Failed shared console compute stand-in with a Dispatch signature must be skipped, + // never forwarded to PC ExecuteIndirect with the shared driver pipeline. + reset(list_ptr, 0x7210_0100, shell_fail); + let before = counts_snapshot(); + unsafe { + execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + } + let after = counts_snapshot(); + assert_eq!( + fake.execute_indirect_calls.load(Ordering::Relaxed), + 0, + "failed shared console compute stand-in must not reach PC ExecuteIndirect" + ); + assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]); + + // 2. Another shell sharing the same driver pipeline whose build succeeds still takes the + // translated path (caught here by the root-changing guard rather than falling through to PC). + reset(list_ptr, 0x7210_0100, shell_ok); + unsafe { + execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); + } + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0); + + // 3. Releasing `shell_fail` forgets its `CONSOLE_COMPUTE` entry so a native PC compute + // pipeline later allocated at the same address still reaches PC ExecuteIndirect. + let _ = pso_async::released(shell_fail); + real::forget_pso_for_test(shell_fail); + assert!(!real::is_console_compute(shell_fail)); + reset(list_ptr, 0x7210_0100, shell_fail); + unsafe { + execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + } + assert_eq!( + fake.execute_indirect_calls.load(Ordering::Relaxed), + 1, + "native PC pipeline at a released shell's address must still reach PC ExecuteIndirect" + ); - unsafe extern "system" fn fake_execute_indirect( - this: *mut c_void, - _sig: usize, - _max: u32, - _args: usize, - _args_off: u64, - _count_buf: usize, - _count_off: u64, - ) { - (*(this as *const FakeAdoptedList)).execute_indirect_calls.fetch_add(1, Ordering::Relaxed); + forget(list_ptr); + note_signature_dispatches(sig_dispatch, false); + let _ = pso_async::released(shell_ok); + real::forget_pso_for_test(shell_ok); + real::forget_pso_for_test(real_ok); } #[test] - fn async_compute_pso_success_and_failure_in_dispatch_and_execute_indirect() { + fn two_pass_pso_skips_direct_draw_and_unmatched_execute_indirect() { + #[repr(C)] + struct FakeTwoPassList { + vt: *const usize, + refs: AtomicUsize, + set_graphics_rs_calls: AtomicUsize, + execute_indirect_calls: AtomicUsize, + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + (*(this as *const FakeTwoPassList)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + (*(this as *const FakeTwoPassList)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 + } + unsafe extern "system" fn set_graphics_rs(this: *mut c_void, _rs: *mut c_void) { + (*(this as *const FakeTwoPassList)).set_graphics_rs_calls.fetch_add(1, Ordering::Relaxed); + } + unsafe extern "system" fn exec_indirect( + this: *mut c_void, + _sig: usize, + _max: u32, + _args: usize, + _args_off: u64, + _count_buf: usize, + _count_off: u64, + ) { + (*(this as *const FakeTwoPassList)).execute_indirect_calls.fetch_add(1, Ordering::Relaxed); + } + let mut orig_vt = [0usize; 64]; - orig_vt[1] = fake_add_ref as usize; - orig_vt[2] = fake_release as usize; - orig_vt[14] = fake_dispatch as usize; - orig_vt[25] = fake_set_pso as usize; - orig_vt[29] = fake_set_compute_rs as usize; - orig_vt[41] = fake_set_compute_uav as usize; - orig_vt[59] = fake_execute_indirect as usize; + orig_vt[1] = add_ref as usize; + orig_vt[2] = release as usize; + orig_vt[30] = set_graphics_rs as usize; + orig_vt[59] = exec_indirect as usize; - // Extended vtable layout expected by `real::orig_fn`: entry -1 holds `orig_vt` pointer, - // and entries 0..64 hold the COM method pointers used via `ID3D12GraphicsCommandList`. let mut ext_vt = vec![0usize; 65]; ext_vt[0] = orig_vt.as_ptr() as usize; ext_vt[1..].copy_from_slice(&orig_vt); - let fake = Box::new(FakeAdoptedList { - // SAFETY: `ext_vt` has 65 elements so `.add(1)` points to slot 0 with `orig_vt` at `-1`. + let fake = Box::new(FakeTwoPassList { vt: unsafe { ext_vt.as_ptr().add(1) }, refs: AtomicUsize::new(1), - dispatch_calls: AtomicUsize::new(0), - set_compute_rs_calls: AtomicUsize::new(0), - set_compute_uav_calls: AtomicUsize::new(0), - set_pso_calls: AtomicUsize::new(0), + set_graphics_rs_calls: AtomicUsize::new(0), execute_indirect_calls: AtomicUsize::new(0), }); - let list_ptr = &*fake as *const FakeAdoptedList as *mut c_void; - - // 1. Background compute build SUCCEEDS: real PSO R is registered in TRANSLATED_COMPUTE, - // stand-in S is NOT. ExecuteIndirect resolves S -> R and treats it as translated. - let standin_ok = 0x7200_0001usize; - let real_ok = 0x7200_0002usize; - let sig_root_changing = 0x7200_00F0usize; - note_root_changing_signature(sig_root_changing); + let list_ptr = &*fake as *const FakeTwoPassList as *mut c_void; + // Register a finished two-pass GS/MS PSO behind an async stand-in (registered in TWO_PASS, + // not TRANSLATED_GRAPHICS). + let standin_tp = 0x7250_0001usize; + let real_tp = 0x7250_0002usize; pso_async::submit( - standin_ok, - true, + standin_tp, + false, Box::new(move || { - real::register_translated_compute_for_test(real_ok); - real_ok + real::register_two_pass_for_test(real_tp, "GS"); + real_tp }), ); - assert_eq!(pso_async::resolve_wait(standin_ok), real_ok); - assert!(!real::is_translated_compute(standin_ok)); - assert!(real::is_translated_compute(real_ok)); + assert_eq!(pso_async::resolve_wait(standin_tp), real_tp); + assert!(real::two_pass_of(real_tp).is_some()); + assert!(!real::is_translated_graphics(real_tp)); - reset(list_ptr, 0x7200_0100, standin_ok); + reset(list_ptr, 0x7250_0100, standin_tp); unsafe { - // With `sig_root_changing`, a translated compute PSO is caught by the root-changing - // guard instead of falling through to `pc` (which happened when `R` wasn't registered). - execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); + // Seed a non-null title graphics RS so a fallthrough would visibly call SetGraphicsRootSignature. + set_graphics_root_signature(list_ptr, list_ptr); } - assert_eq!( - fake.execute_indirect_calls.load(Ordering::Relaxed), - 0, - "ExecuteIndirect must recognize resolved async compute PSO R as translated" - ); - // 2. Background compute build FAILS (returns 0): stand-in S_fail is NOT in - // TRANSLATED_COMPUTE. Dispatch must skip cleanly without binding XCL's ABI RS/UAVs - // onto S_fail, and ExecuteIndirect must not enter bind_abi either. - let standin_fail = 0x7200_0003usize; - pso_async::submit(standin_fail, true, Box::new(|| 0)); - assert_eq!(pso_async::resolve_wait(standin_fail), standin_fail); - assert!(!real::is_translated_compute(standin_fail)); + // 1. Direct draw (`graphics_bound`) must return None without binding the title's RS. + let before = counts_snapshot(); + let bound = unsafe { graphics_bound(list_ptr) }; + let after = counts_snapshot(); + assert!(bound.is_none(), "two-pass MS/GS PSO must not fall through to PC DrawInstanced"); + assert!(after[DRAWS_SKIPPED] > before[DRAWS_SKIPPED]); + assert_eq!(after[DRAWS_PC], before[DRAWS_PC]); + assert_eq!(fake.set_graphics_rs_calls.load(Ordering::Relaxed), 0); - reset(list_ptr, 0x7200_0100, standin_fail); + // 2. Unmatched `ExecuteIndirect` must skip without binding the title's RS or calling PC ExecuteIndirect. let before = counts_snapshot(); unsafe { - dispatch(list_ptr, 1, 1, 1); + execute_indirect(list_ptr, 0x7250_00F0, 1, 0, 0, 0, 0); } let after = counts_snapshot(); - assert_eq!(after[DISPATCHES], before[DISPATCHES]); - assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]); - assert_eq!(fake.set_compute_rs_calls.load(Ordering::Relaxed), 0); - assert_eq!(fake.set_compute_uav_calls.load(Ordering::Relaxed), 0); - assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 0); - assert_eq!(fake.dispatch_calls.load(Ordering::Relaxed), 0); + assert!(after[DRAWS_SKIPPED] > before[DRAWS_SKIPPED]); + assert_eq!(fake.set_graphics_rs_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0); + + forget(list_ptr); + let _ = pso_async::released(standin_tp); + real::forget_pso_for_test(real_tp); + assert!(real::two_pass_of(real_tp).is_none()); + } + + #[test] + fn create_list_reset_and_clear_state_track_initial_pso_on_d3d12() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + if console_list::enabled() { + return; + } unsafe { - execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.expect("D3D12 device"); + real::adopt(dev.as_raw(), real::Kind::Device); + + // Build two real PC compute PSOs from the inbox dummy CS bytecode. + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).expect("serialize RS"); + let ser = ser.unwrap(); + let rs: ID3D12RootSignature = dev + .CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())) + .expect("CreateRootSignature"); + let cs = real::dummy_cs_bytecode(); + let make_pso = || -> ID3D12PipelineState { + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }, + ..Default::default() + }; + let pso = dev.CreateComputePipelineState(&desc).expect("CreateComputePipelineState"); + std::mem::ManuallyDrop::drop(&mut desc.pRootSignature); + pso + }; + let pso1 = make_pso(); + let pso2 = make_pso(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + + // Stand-in synthetic key backed by real `pso1` in pso_async: CreateCommandList must + // resolve it via resolve_for_bind for PC D3D12 while tracking `standin` in `bind`. + let standin = 0x7300_0001usize; + let pso1_raw = pso1.as_raw() as usize; + pso_async::submit(standin, true, Box::new(move || pso1_raw)); + assert_eq!(pso_async::resolve_wait(standin), pso1_raw); + + let mut raw_list: *mut c_void = std::ptr::null_mut(); + let iid = windows_sys::core::GUID::from_u128(0x5b160d0f_ac1b_4185_8ba8_b3ae42a5a455); + let hr = device_x::create_command_list_pc( + dev.as_raw(), + 0, + D3D12_COMMAND_LIST_TYPE_DIRECT.0 as u32, + alloc.as_raw() as usize, + standin, + &iid, + &mut raw_list, + ); + assert!(hr >= 0 && !raw_list.is_null(), "create_command_list_pc failed: {hr:#x}"); + let backing = title_list::backing(raw_list).expect("wrapped in title_list"); + assert_eq!(tracked_pso(backing), standin, "CreateCommandList must seed bind::State.pso"); + + // ClearState(pso2) updates bind::State.pso to pso2 and clears root args. + let rs_key = 0x7300_0010usize; + console_list::note_root_signature(rs_key, &test_rts0_blob()); + set_compute_root_signature(backing, rs_key as *mut c_void); + set_compute_root_constant(backing, 0, 0xABCD, 0); + let cl = ID3D12GraphicsCommandList::from_raw_borrowed(&backing).unwrap(); + cl.ClearState(&pso2); + assert_eq!(tracked_pso(backing), pso2.as_raw() as usize, "ClearState must update bind::State.pso"); + with(backing, |s| assert!(s.layout.is_none() && s.args.is_empty())); + + // ClearState(None) clears bind::State.pso to 0. + cl.ClearState(None); + assert_eq!(tracked_pso(backing), 0, "ClearState(None) must clear bind::State.pso"); + + // Close + reset_x(alloc, pso2) updates bind::State.pso to pso2 and clears root args. + set_graphics_root_signature(backing, rs_key as *mut c_void); + set_graphics_root_constant(backing, 0, 0x1111, 0); + cl.Close().expect("Close"); + let hr = list_x::reset_x(backing, alloc.as_raw() as usize, pso2.as_raw() as usize); + assert!(hr >= 0, "reset_x failed: {hr:#x}"); + assert_eq!(tracked_pso(backing), pso2.as_raw() as usize, "Reset must update bind::State.pso"); + with(backing, |s| assert!(s.layout_gfx.is_none() && s.args_gfx.is_empty())); + + // Release the wrapped title list cleanly (calls bind::forget + list_x::on_release). + let release_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(raw_list as *const *const usize)).add(2)); + assert_eq!(release_fn(raw_list), 0); + let _ = pso_async::released(standin); } - assert_eq!(fake.set_compute_rs_calls.load(Ordering::Relaxed), 0); - assert_eq!(fake.set_compute_uav_calls.load(Ordering::Relaxed), 0); - assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 0); + } + + #[test] + fn dispatch_mesh_signature_tracking_returns_companion_and_layout() { + let sig = 0x7400_0001usize; + let companion = 0x7400_0002usize; + assert_eq!(dispatch_mesh_sig_of(sig), None); + note_dispatch_mesh_signature(sig, companion, 28, 16); assert_eq!( - fake.execute_indirect_calls.load(Ordering::Relaxed), - 1, - "failed async compute stand-in must not enter translated ExecuteIndirect path" + dispatch_mesh_sig_of(sig), + Some(DispatchMeshSig { companion_dispatch: companion, byte_stride: 28, mesh_offset: 16 }) ); + DISPATCH_MESH_SIGS.write().unwrap().as_mut().unwrap().remove(&sig); + assert_eq!(dispatch_mesh_sig_of(sig), None); + } - // 3. The same failed stand-in (made from a console shader) with a Dispatch signature: - // nothing to run, as for Dispatch – the PC call would pair the stand-in with the list's - // compute root signature (XCL's ABI one after a translated dispatch: debug layer 953) - let sig_dispatch = 0x7200_00F8usize; - real::register_console_compute_for_test(standin_fail); - note_signature_dispatches(sig_dispatch, true); - let before = counts_snapshot(); - unsafe { - execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + #[test] + fn two_pass_io_carries_the_unified_memory_base() { + use crate::gpu::recomp::{IO_UMA_BASE_HI, KERNEL_SGPRS}; + let base = 0x4_0000_0000usize; + for compute_pass in [true, false] { + let io = two_pass_io(None, &[], 0x4_1234_5600, compute_pass, base, [0; 2]); + assert_eq!(io.len(), KERNEL_SGPRS); + assert_eq!(io[IO_UMA_BASE_HI], 4, "compute pass {compute_pass}"); } - let after = counts_snapshot(); - assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 1, "a dispatch of an untranslated console compute pipeline must not reach the PC ExecuteIndirect"); - assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]); + let io = two_pass_io(None, &[], 0x4_1234_5600, true, base, [0; 2]); + assert_eq!((io[8], io[9]), (0x1234_5600, 4)); + } - // 4. A native PC compute pipeline (not made from a console shader) with the same Dispatch - // signature still goes to the PC call, as on main - let native = 0x7200_0004usize; - reset(list_ptr, 0x7200_0100, native); - unsafe { - execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + /// The compute pass of a mesh draw whose shaders index the heaps: the heaps' addresses right + /// after the mesh root arguments (from s16), the view heap's first – the 5-slot mesh layout + /// [table, table, table, root SRV, 2 constants] a retail title's mesh programs are built for + /// reads its view heap from s23. + #[test] + fn two_pass_compute_pass_gets_the_heap_addresses() { + // RTS0 v2: tables (0), an SRV (3), two constants (1); both DIRECTLY_INDEXED flags + let params = [(0u32, 0u32), (0, 0), (0, 0), (3, 0), (1, 2)]; + let mut r = vec![2u32, 5, 24, 0, 0, 0x400 | 0x800]; + r.extend(params.iter().enumerate().flat_map(|(k, &(ty, _))| [ty, 0, 24 + 12 * 5 + 12 * k as u32])); + r.extend(params.iter().flat_map(|&(_, count)| [0, 0, count])); + let l = console_list::layout_from_blob(&r.iter().flat_map(|w| w.to_le_bytes()).collect::>()).unwrap(); + assert_eq!(l.heaps, [true, true]); + let args: Vec = [0x100u32, 0x120, 0x140, 0x5000, 7, 1, 2].iter().flat_map(|w| w.to_le_bytes()).collect(); + let heaps = [0x4c61_0000, 0x6381_0000]; + let io = two_pass_io(Some(&l), &args, 0x7_0000_0200, true, 0x4_0000_0000, heaps); + assert_eq!((io[8], io[9]), (0x200, 7)); + assert_eq!(&io[16..25], &[0x100, 0x120, 0x140, 0x5000, 7, 1, 2, 0x4c61_0000, 0x6381_0000]); + // a layout without the flags: nothing after the arguments + let mut l = l; + l.heaps = [false; 2]; + assert_eq!(two_pass_io(Some(&l), &args, 0x7_0000_0200, true, 0x4_0000_0000, heaps)[23..25], [0, 0]); + } + + #[test] + fn two_pass_groups_stay_inside_the_record_buffer() { + // #304's transform record: 11 908 dwords + let record = 11_908 * 4; + assert_eq!(record_groups(32 << 20, record, 1), 704); + assert_eq!(record_groups(128 << 20, record, 1), 2817); + // the mesh pass's groups, `split` a record, all in X + assert_eq!(record_groups(1 << 30, 64, 7), 65_535 / 7); + assert_eq!(record_groups(1 << 20, 2 << 20, 1), 0); + } + + /// `SCALE_ARGS_HLSL` on `commands` (dwords each, the DispatchMesh argument at dword 1): + /// the compute pass's and the mesh pass's commands. + fn scale_args(commands: &[[u32; 4]], split: u32, cap: u32) -> Option<(Vec<[u32; 4]>, Vec<[u32; 4]>)> { + scale_args_counted(commands, split, cap, None) + } + + /// `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]>)> { + use crate::gpu::recomp::runner; + if runner::adapter().is_err() { + runner::skip_test("no GPU"); + return None; } - assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 2, "a native PC compute pipeline must still reach the PC ExecuteIndirect"); + let dxil = crate::gpu::recomp::dxc::compile(SCALE_ARGS_HLSL, "main", "cs_6_6", &[]).unwrap(); + let n = commands.len(); + 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); + 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())) + } - // a signature made later at the same address without a Dispatch argument goes to the PC - reset(list_ptr, 0x7200_0100, standin_fail); - note_signature_dispatches(sig_dispatch, false); - unsafe { - execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + /// Indirect group counts that are not the title's run nothing, the others go out as they are. + #[test] + fn gpu_indirect_dispatch_runs_no_garbage_group_counts() { + use crate::gpu::recomp::runner; + if runner::adapter().is_err() { + runner::skip_test("no GPU"); + return; } - assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 3); + let dxil = crate::gpu::recomp::dxc::compile(GUARD_ARGS_HLSL, "main", "cs_6_6", &[]).unwrap(); + let cases: [([u32; 3], [u32; 3]); 10] = [ + ([1, 1, 1], [1, 1, 1]), + ([2560 / 8, 1440 / 4, 1], [320, 360, 1]), + ([115_200, 1, 1], [65_535, 2, 1]), + ([0, 5, 5], [0, 0, 0]), + ([0xFF00_0000, 0xE3, 0xFF7F_0000], [0, 0, 0]), + ([65_535, 65_535, 65_535], [0, 0, 0]), + ([2048, 2048, 1], [2048, 2048, 1]), + ([2048, 2049, 1], [0, 0, 0]), + ([3, 1, 0xFFFF_FFFF], [0, 0, 0]), + ([1 << 16, 1 << 16, 1], [0, 0, 0]), + ]; + for (g, want) in cases { + let mut mem = vec![0xDEADu32; 64]; + mem[4..7].copy_from_slice(&g); + let out = runner::dispatch(&dxil, [1, 1, 1], &[16, MOST_GROUPS, 128], &mem).unwrap(); + assert_eq!(&out[32..35], &want, "{g:?}"); + } + } - forget(list_ptr); - let _ = pso_async::released(standin_ok); - let _ = pso_async::released(standin_fail); - real::forget_pso_for_test(real_ok); - real::forget_pso_for_test(standin_fail); - assert!(!real::is_console_compute(standin_fail), "a released pipeline's address does not stay a console one"); + #[test] + fn gpu_indirect_two_pass_groups_stay_inside_the_record_buffer() { + let Some((compute, mesh)) = scale_args(&[[7, 100, 1, 1], [8, 3, 1, 1], [9, 0, 1, 1]], 2, 10) else { return }; + assert_eq!(compute, [[7, 10, 1, 1], [8, 3, 1, 1], [9, 0, 1, 1]]); + assert_eq!(mesh, [[7, 20, 1, 1], [8, 6, 1, 1], [9, 0, 1, 1]]); } #[test] - fn execute_indirect_skips_failed_shared_console_compute_standin() { - let mut orig_vt = [0usize; 64]; - orig_vt[1] = fake_add_ref as usize; - orig_vt[2] = fake_release as usize; - orig_vt[14] = fake_dispatch as usize; - orig_vt[25] = fake_set_pso as usize; - orig_vt[29] = fake_set_compute_rs as usize; - orig_vt[41] = fake_set_compute_uav as usize; - orig_vt[59] = fake_execute_indirect as usize; + fn gpu_indirect_two_pass_groups_go_in_x() { + let commands = [[1, 1, 2, 1], [2, 2, 3, 4], [3, 300, 300, 1], [4, 5, 0, 2], [5, 70_000, 70_000, 70_000], [6, 1000, 1, 1], [7, 5000, 1, 1], [8, 5000, 1, 0]]; + let Some((compute, mesh)) = scale_args(&commands, 3, 1000) else { return }; + assert_eq!(compute, [[1, 2, 1, 1], [2, 24, 1, 1], [3, 1000, 1, 1], [4, 0, 1, 1], [5, 1000, 1, 1], [6, 1000, 1, 1], [7, 1000, 1, 1], [8, 0, 1, 1]]); + assert_eq!(mesh, [[1, 6, 1, 1], [2, 72, 1, 1], [3, 3000, 1, 1], [4, 0, 1, 1], [5, 3000, 1, 1], [6, 3000, 1, 1], [7, 3000, 1, 1], [8, 0, 1, 1]]); + } - let mut ext_vt = vec![0usize; 65]; - ext_vt[0] = orig_vt.as_ptr() as usize; - ext_vt[1..].copy_from_slice(&orig_vt); + #[test] + fn freed_two_pass_buffers_kept_for_reuse_are_capped() { + assert!(pool_keeps(0, 0, 128 << 20)); + assert!(pool_keeps(1, 128 << 20, 128 << 20)); + assert!(!pool_keeps(2, 256 << 20, 4 << 20)); + assert!(pool_keeps(16, 0, 1 << 20)); + assert!(!pool_keeps(256, 0, 1 << 20)); + } - let fake = Box::new(FakeAdoptedList { - vt: unsafe { ext_vt.as_ptr().add(1) }, - refs: AtomicUsize::new(1), - dispatch_calls: AtomicUsize::new(0), - set_compute_rs_calls: AtomicUsize::new(0), - set_compute_uav_calls: AtomicUsize::new(0), - set_pso_calls: AtomicUsize::new(0), - execute_indirect_calls: AtomicUsize::new(0), - }); - let list_ptr = &*fake as *const FakeAdoptedList as *mut c_void; + /// A second queue for two-pass draws is told from the first one. + #[test] + fn two_pass_records_are_shared_on_one_queue_only() { + let seen = std::sync::atomic::AtomicUsize::new(0); + assert!(same_records_queue(&seen, 0x10) && same_records_queue(&seen, 0x10)); + assert!(!same_records_queue(&seen, 0x20)); + assert!(same_records_queue(&seen, 0x10)); + } - // With shared stand-ins (`standin::shell`), `dev_create_compute_pso` registers the - // title-facing shell in `CONSOLE_COMPUTE`, while `pso_async::resolve_wait` returns the - // shared driver pipeline when the background build fails. - let shell_fail = 0x7210_0001usize; - let shell_ok = 0x7210_0002usize; - let shared_driver = 0x7210_0003usize; - let real_ok = 0x7210_0004usize; - let sig_dispatch = 0x7210_00F8usize; - let sig_root_changing = 0x7210_00F0usize; - note_signature_dispatches(sig_dispatch, true); - note_root_changing_signature(sig_root_changing); + /// Recordings share one record buffer, a bigger one is made only when that one is too small. + #[test] + fn gpu_two_pass_record_buffer_is_shared_by_the_recordings() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_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; + } + let dev = dev.unwrap(); + unsafe { + let (a, cap) = shared_record_buffer(&dev, 4 << 20).unwrap(); + assert_eq!(cap, SHARED_LEAST); + let (b, _) = shared_record_buffer(&dev, SHARED_LEAST).unwrap(); + assert_eq!(a.as_raw(), b.as_raw(), "a second recording's records are the first one's"); + let (c, big) = shared_record_buffer(&dev, SHARED_LEAST + 1).unwrap(); + assert!(c.as_raw() != a.as_raw() && big > SHARED_LEAST); + let (d, _) = shared_record_buffer(&dev, 4 << 20).unwrap(); + assert_eq!(d.as_raw(), a.as_raw()); + } + } - pso_async::submit_lazy(shell_fail, true, Box::new(|| 0), 0); - pso_async::shared(shell_fail, shared_driver); - real::register_console_compute_for_test(shell_fail); + #[test] + fn gpu_two_pass_argument_scratch_is_shared_and_capped() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_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; + } + let dev = dev.unwrap(); + let list = 0x7500_0001usize as *mut c_void; + unsafe { + // small rewrites share one block + let (a, at_a) = scratch_args(list, &dev, 100).unwrap(); + let (b, at_b) = scratch_args(list, &dev, 300).unwrap(); + assert_eq!((a.as_raw(), at_a), (b.as_raw(), 0)); + assert_eq!(at_b, 256); + // a recording takes at most SCRATCH_CAP of blocks + let mut taken = 1; + while scratch_args(list, &dev, SCRATCH_BLOCK).is_ok() { + taken += 1; + assert!(taken <= SCRATCH_CAP / SCRATCH_BLOCK, "past the cap"); + } + assert!(with(list, |s| s.scratch_taken) <= SCRATCH_CAP); + // the next recording starts again + reset(list, 0, 0); + assert!(scratch_args(list, &dev, SCRATCH_BLOCK).is_ok()); + } + forget(list); + } - pso_async::submit_lazy( - shell_ok, - true, - Box::new(move || { - real::register_translated_compute_for_test(real_ok); - real_ok - }), - 0, - ); - pso_async::shared(shell_ok, shared_driver); - real::register_console_compute_for_test(shell_ok); + #[test] + fn gpu_indirect_two_pass_commands_past_the_count_get_no_groups() { + let commands = [[1, 3, 1, 1], [2, 2, 1, 1], [3, 4, 1, 1]]; + let Some((compute, mesh)) = scale_args_counted(&commands, 2, 1000, Some(2)) else { return }; + assert_eq!(compute, [[1, 3, 1, 1], [2, 2, 1, 1], [3, 0, 1, 1]]); + assert_eq!(mesh, [[1, 6, 1, 1], [2, 4, 1, 1], [3, 0, 1, 1]]); + let Some((compute, _)) = scale_args_counted(&commands, 2, 1000, Some(7)) else { return }; + assert_eq!(compute, [[1, 3, 1, 1], [2, 2, 1, 1], [3, 4, 1, 1]]); + } - assert_eq!(pso_async::resolve_wait(shell_fail), shared_driver); - assert!(!pso_async::is_pending(shell_fail)); - assert!(real::is_console_compute(shell_fail)); - assert!(!real::is_console_compute(shared_driver)); + /// Commands of one two-pass ExecuteIndirect run in `two_pass_steps` order on the GPU, with + /// stand-ins for the two passes: the "compute pass" writes each group's record (from record 0) + /// with its command's constant, the "mesh pass" copies the records it reads out by command. + #[test] + fn gpu_two_pass_indirect_commands_keep_their_own_records() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + let src = r#" +#define RS "RootConstants(num32BitConstants=1, b0), UAV(u0), UAV(u1)" +cbuffer C : register(b0) { uint v; }; +RWByteAddressBuffer rec : register(u0); +RWByteAddressBuffer o : register(u1); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void cs(uint3 g : SV_GroupID) { rec.Store(g.x * 4u, v); } +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u)); } +"#; + // (constant, groups) of each command + let commands = [(1u32, 3u32), (2, 2), (3, 4)]; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let cs = crate::gpu::recomp::dxc::compile(src, "cs", "cs_6_6", &[]).unwrap(); + let ms = crate::gpu::recomp::dxc::compile(src, "ms", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &cs).unwrap(); + let pso = |dxil: &[u8]| -> ID3D12PipelineState { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }; + dev.CreateComputePipelineState(&desc).unwrap() + }; + let (pass1, pass2) = (pso(&cs), pso(&ms)); + 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: 1 } }, + }, + D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }, + ]; + let mut sig: Option = None; + dev.CreateCommandSignature(&D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 16, NumArgumentDescs: 2, pArgumentDescs: args.as_ptr(), NodeMask: 0 }, &rs, &mut sig).unwrap(); + let sig = sig.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, + 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() + }; + let (indirect, rec, out) = (buffer(256, true), buffer(256, false), buffer(1024, true)); + 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 (a, o) = (map(&indirect), map(&out)); + for (k, &(v, x)) in commands.iter().enumerate() { + std::ptr::copy_nonoverlapping([v, x, 1, 1].as_ptr(), a.add(4 * k), 4); + } + std::ptr::write_bytes(o, 0, 256); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + 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 alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, &pass1).unwrap(); + emit_transition(&list, &indirect, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(1, rec.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, out.GetGPUVirtualAddress()); + for (k, compute) in two_pass_steps(commands.len() as u32) { + list.SetPipelineState(if compute { &pass1 } else { &pass2 }); + list.ExecuteIndirect(&sig, 1, &indirect, k as u64 * 16, None::<&ID3D12Resource>, 0); + emit_uav_barrier(&list, Some(&rec)); + } + emit_transition(&list, &indirect, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 10_000).unwrap(); + for &(v, x) in &commands { + let got: Vec = (0..x).map(|g| *o.add((v * 16 + g) as usize)).collect(); + assert_eq!(got, vec![v; x as usize], "the records the mesh pass of command {v} read"); + } + indirect.Unmap(0, None); + out.Unmap(0, None); + } + } - // 1. Failed shared console compute stand-in with a Dispatch signature must be skipped, - // never forwarded to PC ExecuteIndirect with the shared driver pipeline. - reset(list_ptr, 0x7210_0100, shell_fail); - let before = counts_snapshot(); + /// 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.) + #[test] + fn two_pass_binds_set_the_shared_view_heap() { + use crate::gpu::recomp::runner::skip_test; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + if !crate::gpu::recomp::pso::heap_windows() { + skip_test("no heap windows (opt-in: XCL_HEAP_WINDOWS=1)"); + return; + } + #[repr(C)] + struct FakeList { + vt: *const usize, + calls: Mutex>>, + } + unsafe extern "system" fn fake_set_heaps(this: *mut c_void, n: u32, heaps: *const usize) { + let v = if heaps.is_null() { Vec::new() } else { std::slice::from_raw_parts(heaps, n as usize).to_vec() }; + (*(this as *const FakeList)).calls.lock().unwrap().push(v); + } unsafe { - execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + // the shared heap with a window view, unless the backend made it already + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1 << 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut window: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut window).unwrap(); + let window = window.unwrap(); + if super::super::console_heap::global_heap().is_none() && !super::super::console_heap::set_window_views(&dev, &[(window.as_raw() as usize, 1 << 16)]) { + skip_test("no shared heap"); + return; + } + let g = super::super::console_heap::global_heap().unwrap().as_raw() as usize; + let mut orig_vt = [0usize; 64]; + orig_vt[28] = fake_set_heaps as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let fake = Box::new(FakeList { vt: ext_vt.as_ptr().add(1), calls: Mutex::new(Vec::new()) }); + let this = &*fake as *const FakeList as *mut c_void; + let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this).unwrap(); + // no root signatures: the bind stops before it records anything else + let tp = super::super::real::TwoPassPso { compute: 0, compute_rs: 0, mesh_rs: 0, record: Default::default(), mesh_groups_per_record: 1, kind: "MS" }; + for compute_pass in [true, false] { + super::super::list_x::set_descriptor_heaps_x(this, 0, std::ptr::null()); + assert!(super::super::list_x::bound_heaps(this, false).is_empty()); + assert!(bind_two_pass_stage(this, list, 0, &tp, 0, compute_pass).is_err()); + assert_eq!(super::super::list_x::bound_heaps(this, false), vec![g], "compute pass {compute_pass}: the shared heap is bound"); + assert_eq!(fake.calls.lock().unwrap().last(), Some(&vec![g]), "compute pass {compute_pass}"); + } + super::super::list_x::bound_heaps(this, true); + forget(this); } - let after = counts_snapshot(); - assert_eq!( - fake.execute_indirect_calls.load(Ordering::Relaxed), - 0, - "failed shared console compute stand-in must not reach PC ExecuteIndirect" - ); - assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]); + } - // 2. Another shell sharing the same driver pipeline whose build succeeds still takes the - // translated path (caught here by the root-changing guard rather than falling through to PC). - reset(list_ptr, 0x7210_0100, shell_ok); + + /// A reusable block must fit the recording's remaining budget, not just its request. + #[test] + fn gpu_two_pass_pooled_scratch_respects_remaining_budget() { + use windows::Win32::Graphics::{Direct3D::D3D_FEATURE_LEVEL_12_0, Dxgi::*}; unsafe { - execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); + let factory: IDXGIFactory4 = CreateDXGIFactory1().unwrap(); + let wanted = std::env::var("XCL_ADAPTER").unwrap_or_default(); + let mut chosen = None; + for i in 0.. { + let Ok(adapter) = factory.EnumAdapters1(i) else { break }; + let desc = adapter.GetDesc1().unwrap(); + let end = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); + let name = String::from_utf16_lossy(&desc.Description[..end]); + if !wanted.is_empty() && !name.contains(&wanted) { continue; } + let mut dev: Option = None; + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut dev).is_ok() { + chosen = Some((name, dev.unwrap())); + break; + } + } + let Some((name, dev)) = chosen else { + crate::gpu::recomp::runner::skip_test("no selected D3D12 adapter"); + return; + }; + println!("POOLED_SCRATCH_ADAPTER={name}"); + let key = dev.as_raw() as usize; + // These are state keys only; scratch_args does not call through a list pointer. + let (consumer, producer, empty) = (0x7500_1011usize as *mut c_void, 0x7500_1012usize as *mut c_void, 0x7500_1013usize as *mut c_void); + let allocator = 0x7500_1014usize; + let first = scratch_args(consumer, &dev, SCRATCH_BLOCK).unwrap(); + assert_eq!(with(consumer, |s| s.scratch_taken), SCRATCH_BLOCK); + reset(producer, allocator, 0); + let large = scratch_args(producer, &dev, SCRATCH_CAP).unwrap(); + assert_eq!(large.0.GetDesc().Width, SCRATCH_CAP); + reset(producer, 0, 0); + release_allocator_res(allocator); + let second = scratch_args(consumer, &dev, SCRATCH_BLOCK).unwrap(); + let taken = with(consumer, |s| s.scratch_taken); + println!("POOLED_SCRATCH taken={taken} second_bytes={} cap={SCRATCH_CAP}", second.0.GetDesc().Width); + // If it was too large for consumer, the cached block remains reusable by an empty recording. + let reused = if taken <= SCRATCH_CAP { + let r = scratch_args(empty, &dev, SCRATCH_CAP).unwrap(); + assert_eq!(r.0.as_raw(), large.0.as_raw()); + assert_eq!(with(empty, |s| s.scratch_taken), SCRATCH_CAP); + assert!(scratch_args(empty, &dev, 256).is_err()); + Some(r) + } else { None }; + drop((first, second, large, reused)); + for list in [consumer, producer, empty] { forget(list); } + FREE_RES.lock().unwrap().retain(|(_, _, d)| *d != key); + assert!(taken <= SCRATCH_CAP, "pooled block exceeds recording budget: {taken} > {SCRATCH_CAP}"); } - assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0); + } - // 3. Releasing `shell_fail` forgets its `CONSOLE_COMPUTE` entry so a native PC compute - // pipeline later allocated at the same address still reaches PC ExecuteIndirect. - let _ = pso_async::released(shell_fail); - real::forget_pso_for_test(shell_fail); - assert!(!real::is_console_compute(shell_fail)); - reset(list_ptr, 0x7210_0100, shell_fail); + #[test] + fn root_uav_alignment_splits_unaligned_offsets_and_rejects_sub_dword() { + assert_eq!(align_root_uav(0x1_0000_0000).unwrap(), (0x1_0000_0000, 0)); + // 12-byte D3D12_DISPATCH_ARGUMENTS stride: not 16-byte aligned, split into 256-byte base + byte offset + assert_eq!(align_root_uav(0x1_0000_000c).unwrap(), (0x1_0000_0000, 12)); + assert_eq!(align_root_uav(0x1_0000_0018).unwrap(), (0x1_0000_0000, 24)); + assert_eq!(align_root_uav(0x1_0000_01fc).unwrap(), (0x1_0000_0100, 252)); + assert!(align_root_uav(0x1_0000_0001).is_err()); + assert!(align_root_uav(0x1_0000_0002).is_err()); + assert!(align_root_uav(0x1_0000_0003).is_err()); + assert!(align_root_uav(0).is_err(), "zero VA must never pass as a root UAV base"); + assert!(align_root_uav(0xFC).is_err(), "sub-256 VA must never round down to 0x0"); + } + + #[test] + fn scale_args_layout_validation_rejects_malformed_strides_and_offsets() { + assert_eq!(validate_scale_args_layout(4, 16, 4).unwrap(), 64); + assert_eq!(validate_scale_args_layout(1, 12, 0).unwrap(), 12); + assert_eq!(validate_scale_args_layout(8, 28, 16).unwrap(), 224); + assert!(validate_scale_args_layout(0, 16, 4).is_err()); + assert!(validate_scale_args_layout(1, 0, 0).is_err()); + assert!(validate_scale_args_layout(1, 14, 0).is_err()); + assert!(validate_scale_args_layout(1, 16, 2).is_err()); + assert!(validate_scale_args_layout(1, 16, 8).is_err()); + assert!(validate_scale_args_layout(1, 16, u32::MAX).is_err()); + } + + /// Both internal argument-rewrite pipelines build cleanly with their minimal root signatures + /// (no unbound ABI slots) and run with non-16-byte-aligned source/count byte offsets. + #[test] + fn gpu_args_pipelines_build_and_handle_non_16_aligned_offsets() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; unsafe { - execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let (guard_rs, guard_pso) = guard_indirect_pipeline(&dev).expect("guard_indirect_pipeline"); + let (scale_rs, scale_pso) = scale_indirect_pipeline(&dev).expect("scale_indirect_pipeline"); + + let make_cpu_buf = |bytes: u64| -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let 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 r: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + }; + + let io_buf = make_cpu_buf(512); + let src_buf = make_cpu_buf(512); + let dst_buf = make_cpu_buf(512); + 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 (io_p, src_p, dst_p) = (map(&io_buf), map(&src_buf), map(&dst_buf)); + std::ptr::write_bytes(io_p, 0, 128); + std::ptr::write_bytes(src_p, 0, 128); + std::ptr::write_bytes(dst_p, 0xCC, 128); + + // Guard pass reading 115 200 x 1 x 1 from 12-byte offset (not 16-byte aligned), folding into 65 535 x 2 x 1 and writing IO_GROUP_LIMIT. + let (guard_src_base, guard_src_off) = align_root_uav(src_buf.GetGPUVirtualAddress() + 12).unwrap(); + assert_eq!(guard_src_off, 12); + std::ptr::copy_nonoverlapping([115_200u32, 1, 1].as_ptr(), src_p.add(3), 3); + std::ptr::copy_nonoverlapping([guard_src_off, MOST_GROUPS, 0, 16].as_ptr(), io_p, 4); + + // Scale pass reading 2 commands at 12-byte offset (stride 16, mesh_offset 4) with no count buffer (u4 bound to io). + let (scale_src_base, scale_src_off) = align_root_uav(src_buf.GetGPUVirtualAddress() + 64 + 12).unwrap(); + assert_eq!(scale_src_off, 76); + std::ptr::copy_nonoverlapping([11u32, 20, 1, 1, 22, 3, 2, 1].as_ptr(), src_p.add(19), 8); + std::ptr::copy_nonoverlapping([2u32, 16, 4, 2, 10, scale_src_off, 0, 0, 0].as_ptr(), io_p.add(64), 9); + + 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(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + + list.SetComputeRootSignature(&guard_rs); + list.SetPipelineState(&guard_pso); + list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(1, guard_src_base); + list.SetComputeRootUnorderedAccessView(2, dst_buf.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, dst_buf.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + + list.SetComputeRootSignature(&scale_rs); + list.SetPipelineState(&scale_pso); + list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress() + 256); + list.SetComputeRootUnorderedAccessView(1, scale_src_base); + list.SetComputeRootUnorderedAccessView(2, dst_buf.GetGPUVirtualAddress() + 256); + list.SetComputeRootUnorderedAccessView(3, io_buf.GetGPUVirtualAddress() + 256); + list.Dispatch(1, 1, 1); + + 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(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 10_000).unwrap(); + + assert_eq!(std::slice::from_raw_parts(dst_p, 5), &[65_535, 2, 1, 0xCCCC_CCCC, 115_200]); + assert_eq!(std::slice::from_raw_parts(dst_p.add(64), 8), &[11, 10, 1, 1, 22, 6, 1, 1]); + assert_eq!(std::slice::from_raw_parts(dst_p.add(72), 8), &[11, 20, 1, 1, 22, 12, 1, 1]); + + io_buf.Unmap(0, None); + src_buf.Unmap(0, None); + dst_buf.Unmap(0, None); } - assert_eq!( - fake.execute_indirect_calls.load(Ordering::Relaxed), - 1, - "native PC pipeline at a released shell's address must still reach PC ExecuteIndirect" - ); + } - forget(list_ptr); - note_signature_dispatches(sig_dispatch, false); - let _ = pso_async::released(shell_ok); - real::forget_pso_for_test(shell_ok); - real::forget_pso_for_test(real_ok); + #[test] + fn dispatches_past_the_d3d12_limit_are_folded_or_clamped() { + assert_eq!(fold(64, 2, 1), (0, [64, 2, 1])); + assert_eq!(fold(65_535, 1, 1), (0, [65_535, 1, 1])); + assert_eq!(fold(72_512, 1, 1), (72_512, [65_535, 2, 1])); + assert_eq!(fold(115_200, 1, 1), (115_200, [65_535, 2, 1])); + assert_eq!(fold(131_071, 1, 3), (131_071, [65_535, 3, 3])); + assert_eq!(fold(70_000, 2, 1), (0, [65_535, 2, 1])); + for n in [65_536u32, 72_512, 75_072, 115_200, 200_000] { + let (limit, [x, y, _]) = fold(n, 1, 1); + assert_eq!(limit, n); + assert!(x * y >= n && x * y - n < x, "{n}: {x}x{y}"); + } + } + + #[test] + fn abi_binding_state_diff_only_rebinds_changed_slots_and_resets_on_rs_change() { + let mut bound = AbiBound::default(); + let uavs1 = [0x100, 0x200, 0x1000, 0x2000, 0x3000, 0x4000]; + assert_eq!(diff_abi_bindings(&mut bound, 0xA000, uavs1), (true, 0b0011_1111)); + assert_eq!(diff_abi_bindings(&mut bound, 0xA000, uavs1), (false, 0)); + + // Only io (slot 0) changed with same RS -> rebind slot 0 only. + let mut uavs2 = uavs1; + uavs2[0] = 0x180; + assert_eq!(diff_abi_bindings(&mut bound, 0xA000, uavs2), (false, 0b0000_0001)); + + // io + res changed with same RS -> rebind slots 0 and 1 only. + let mut uavs3 = uavs2; + uavs3[0] = 0x280; + uavs3[1] = 0x300; + assert_eq!(diff_abi_bindings(&mut bound, 0xA000, uavs3), (false, 0b0000_0011)); + + // Root signature changed -> must rebind RS and all 6 UAV slots even if VAs are unchanged. + assert_eq!(diff_abi_bindings(&mut bound, 0xB000, uavs3), (true, 0b0011_1111)); + assert_eq!(diff_abi_bindings(&mut bound, 0xB000, uavs3), (false, 0)); } #[test] - fn two_pass_pso_skips_direct_draw_and_unmatched_execute_indirect() { - #[repr(C)] - struct FakeTwoPassList { - vt: *const usize, - refs: AtomicUsize, - set_graphics_rs_calls: AtomicUsize, - execute_indirect_calls: AtomicUsize, - } - unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { - (*(this as *const FakeTwoPassList)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 - } - unsafe extern "system" fn release(this: *mut c_void) -> u32 { - (*(this as *const FakeTwoPassList)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 - } - unsafe extern "system" fn set_graphics_rs(this: *mut c_void, _rs: *mut c_void) { - (*(this as *const FakeTwoPassList)).set_graphics_rs_calls.fetch_add(1, Ordering::Relaxed); - } - unsafe extern "system" fn exec_indirect( - this: *mut c_void, - _sig: usize, - _max: u32, - _args: usize, - _args_off: u64, - _count_buf: usize, - _count_off: u64, - ) { - (*(this as *const FakeTwoPassList)).execute_indirect_calls.fetch_add(1, Ordering::Relaxed); + fn root_arg_caching_and_invalidation_track_changes_and_internal_passes() { + let list = 0x7600_0001usize as *mut c_void; + let rs_key = 0x7600_0010usize; + console_list::note_root_signature(rs_key, &test_rts0_blob()); + reset(list, 0x7600_0100, 0); + unsafe { + set_graphics_root_signature(list, rs_key as *mut c_void); + set_graphics_root_constant(list, 0, 0x1234, 0); } + let gen1 = with(list, |s| { + s.io_cache_gfx = Some((s.args_gen_gfx, 0x5555_0000)); + s.pc_abi_gfx = AbiBound { rs: 0xAAAA, uavs: [1, 2, 3, 4, 5, 6] }; + s.pc_abi_cs = AbiBound { rs: 0xBBBB, uavs: [7, 8, 9, 10, 11, 12] }; + s.scratch[0].state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + s.arg_order_clean = true; + s.args_gen_gfx + }); + // Writing the exact same value leaves generation and cached io intact. + unsafe { set_graphics_root_constant(list, 0, 0x1234, 0); } + with(list, |s| { + assert_eq!(s.args_gen_gfx, gen1); + assert_eq!(s.io_cache_gfx, Some((gen1, 0x5555_0000))); + }); + // Writing a different value bumps generation and invalidates cached io. + unsafe { set_graphics_root_constant(list, 0, 0x5678, 0); } + with(list, |s| { + assert_ne!(s.args_gen_gfx, gen1); + assert_eq!(s.io_cache_gfx, None); + }); + // tracked_root_sigs invalidates cached PC ABI bindings after internal sync passes. + assert_eq!(tracked_root_sigs(list), (rs_key, 0)); + with(list, |s| { + assert_eq!(s.pc_abi_gfx, AbiBound::default()); + assert_eq!(s.pc_abi_cs, AbiBound::default()); + }); + // reset resets scratch slots back to COMMON and clears arg_order_clean. + reset(list, 0x7600_0200, 0); + with(list, |s| { + assert_eq!(s.scratch[0].state, D3D12_RESOURCE_STATE_COMMON); + assert_eq!(s.scratch[1].state, D3D12_RESOURCE_STATE_COMMON); + assert!(!s.arg_order_clean); + }); + forget(list); + } - let mut orig_vt = [0usize; 64]; - orig_vt[1] = add_ref as usize; - orig_vt[2] = release as usize; - orig_vt[30] = set_graphics_rs as usize; - orig_vt[59] = exec_indirect as usize; + #[test] + fn pingpong_scratch_alternates_slots_and_falls_back_under_cap() { + assert_eq!(pick_pingpong_slot(0, [true, true], false), 0); + assert_eq!(pick_pingpong_slot(1, [true, true], false), 1); + assert_eq!(pick_pingpong_slot(1, [true, false], true), 1); + // Under SCRATCH_CAP (cannot allocate a new block for slot 1), fall back to slot 0 if it fits. + assert_eq!(pick_pingpong_slot(1, [true, false], false), 0); + assert_eq!(pick_pingpong_slot(0, [false, true], false), 1); + } + #[test] + fn execute_indirect_with_zero_max_count_short_circuits() { + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fake_add_ref as usize; + orig_vt[2] = fake_release as usize; + orig_vt[29] = fake_set_compute_rs as usize; + orig_vt[41] = fake_set_compute_uav as usize; + orig_vt[59] = fake_execute_indirect as usize; let mut ext_vt = vec![0usize; 65]; ext_vt[0] = orig_vt.as_ptr() as usize; ext_vt[1..].copy_from_slice(&orig_vt); - - let fake = Box::new(FakeTwoPassList { + let fake = Box::new(FakeAdoptedList { vt: unsafe { ext_vt.as_ptr().add(1) }, refs: AtomicUsize::new(1), - set_graphics_rs_calls: AtomicUsize::new(0), + dispatch_calls: AtomicUsize::new(0), + set_compute_rs_calls: AtomicUsize::new(0), + set_compute_uav_calls: AtomicUsize::new(0), + set_pso_calls: AtomicUsize::new(0), execute_indirect_calls: AtomicUsize::new(0), }); - let list_ptr = &*fake as *const FakeTwoPassList as *mut c_void; - - // Register a finished two-pass GS/MS PSO behind an async stand-in (registered in TWO_PASS, - // not TRANSLATED_GRAPHICS). - let standin_tp = 0x7250_0001usize; - let real_tp = 0x7250_0002usize; - pso_async::submit( - standin_tp, - false, - Box::new(move || { - real::register_two_pass_for_test(real_tp, "GS"); - real_tp - }), - ); - assert_eq!(pso_async::resolve_wait(standin_tp), real_tp); - assert!(real::two_pass_of(real_tp).is_some()); - assert!(!real::is_translated_graphics(real_tp)); - - reset(list_ptr, 0x7250_0100, standin_tp); - unsafe { - // Seed a non-null title graphics RS so a fallthrough would visibly call SetGraphicsRootSignature. - set_graphics_root_signature(list_ptr, list_ptr); - } - - // 1. Direct draw (`graphics_bound`) must return None without binding the title's RS. - let before = counts_snapshot(); - let bound = unsafe { graphics_bound(list_ptr) }; - let after = counts_snapshot(); - assert!(bound.is_none(), "two-pass MS/GS PSO must not fall through to PC DrawInstanced"); - assert!(after[DRAWS_SKIPPED] > before[DRAWS_SKIPPED]); - assert_eq!(after[DRAWS_PC], before[DRAWS_PC]); - assert_eq!(fake.set_graphics_rs_calls.load(Ordering::Relaxed), 0); - - // 2. Unmatched `ExecuteIndirect` must skip without binding the title's RS or calling PC ExecuteIndirect. + let list_ptr = &*fake as *const FakeAdoptedList as *mut c_void; let before = counts_snapshot(); unsafe { - execute_indirect(list_ptr, 0x7250_00F0, 1, 0, 0, 0, 0); + execute_indirect(list_ptr, 0x7700_0001, 0, 0, 0, 0, 0); } - let after = counts_snapshot(); - assert!(after[DRAWS_SKIPPED] > before[DRAWS_SKIPPED]); - assert_eq!(fake.set_graphics_rs_calls.load(Ordering::Relaxed), 0); assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.set_compute_rs_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.set_compute_uav_calls.load(Ordering::Relaxed), 0); + assert_eq!(counts_snapshot(), before); + } - forget(list_ptr); - let _ = pso_async::released(standin_tp); - real::forget_pso_for_test(real_tp); - assert!(real::two_pass_of(real_tp).is_none()); + #[test] + fn prelude_state_tracks_gpu_writes_splits_and_resets() { + let a = 0x7710_0001usize as *mut c_void; + let b = 0x7710_0002usize as *mut c_void; + reset(a, 0x7710_A001, 0); + with(a, |s| { + assert!(!s.prelude_blocked); + s.arg_order_clean = true; + s.prelude_guards.push(PreludeGuardJob { + buf_idx: 0, + dst_off: 0, + src_win: 0, + src_off: 16, + most: MOST_GROUPS, + lim_win: 0, + lim_off: 64, + }); + }); + // Recording a GPU write/wait blocks subsequent hoisting without dropping prior hoisted jobs. + note_gpu_write(a); + with(a, |s| { + assert!(s.prelude_blocked); + assert!(!s.arg_order_clean); + assert_eq!(s.prelude_guards.len(), 1); + }); + // Mid-list split (`from != to`) blocks hoisting on the continuation segment (Wait64 head); + // `unblock_prelude` re-enables hoisting for splits without a head wait (`split_for_prelude`, `defer`). + inherit_for_split(a, b, 0x7710_A001); + with(b, |s| { + assert!(s.prelude_blocked); + assert!(s.prelude_guards.is_empty()); + }); + unblock_prelude(b); + with(b, |s| { + assert!(!s.prelude_blocked); + }); + assert!(io_pool_keeps(0, IO_BLOCK_BYTES)); + assert!(io_pool_keeps(FREE_IO_CAP - IO_BLOCK_BYTES, IO_BLOCK_BYTES)); + assert!(!io_pool_keeps(FREE_IO_CAP, IO_BLOCK_BYTES)); + // KickoffX non-split (`from == to`) starts a fresh post-kickoff segment and unblocks hoisting. + inherit_for_split(a, a, 0x7710_A001); + with(a, |s| { + assert!(!s.prelude_blocked); + assert!(s.prelude_guards.is_empty()); + }); + note_gpu_write(a); + reset(a, 0x7710_A002, 0); + with(a, |s| { + assert!(!s.prelude_blocked); + assert!(s.prelude_guards.is_empty()); + assert!(s.prelude_scales.is_empty()); + }); + forget(a); + forget(b); } #[test] - fn create_list_reset_and_clear_state_track_initial_pso_on_d3d12() { + fn prelude_guard_and_scale_shaders_compile_and_transform_batches() { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; - use windows::Win32::Graphics::Dxgi::*; - - if console_list::enabled() { - return; - } unsafe { - let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); let mut dev: Option = None; if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { - let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); - D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + return; } - let dev = dev.expect("D3D12 device"); - real::adopt(dev.as_raw(), real::Kind::Device); - - // Build two real PC compute PSOs from the inbox dummy CS bytecode. - let mut ser = None; - D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).expect("serialize RS"); - let ser = ser.unwrap(); - let rs: ID3D12RootSignature = dev - .CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())) - .expect("CreateRootSignature"); - let cs = real::dummy_cs_bytecode(); - let make_pso = || -> ID3D12PipelineState { - let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), - CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }, + let dev = dev.unwrap(); + 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(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let (guard_rs, guard_pso) = prelude_guard_pipeline(&dev).expect("prelude guard pipeline"); + let (scale_rs, scale_pso) = prelude_scale_pipeline(&dev).expect("prelude scale pipeline"); + + let mk_buf = |bytes: u64, heap: D3D12_HEAP_TYPE, flags: D3D12_RESOURCE_FLAGS, state: D3D12_RESOURCE_STATES| -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 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, + Flags: flags, ..Default::default() }; - let pso = dev.CreateComputePipelineState(&desc).expect("CreateComputePipelineState"); - std::mem::ManuallyDrop::drop(&mut desc.pRootSignature); - pso + let mut res: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut res).unwrap(); + res.unwrap() }; - let pso1 = make_pso(); - let pso2 = make_pso(); - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); - // Stand-in synthetic key backed by real `pso1` in pso_async: CreateCommandList must - // resolve it via resolve_for_bind for PC D3D12 while tracking `standin` in `bind`. - let standin = 0x7300_0001usize; - let pso1_raw = pso1.as_raw() as usize; - pso_async::submit(standin, true, Box::new(move || pso1_raw)); - assert_eq!(pso_async::resolve_wait(standin), pso1_raw); + let w0 = mk_buf(4096, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + let dst = mk_buf(4096, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + let jobs = mk_buf(4096, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + let up_w0 = mk_buf(4096, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + let up_jobs = mk_buf(4096, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + let rb_dst = mk_buf(4096, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + let rb_w0 = mk_buf(4096, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + + // Seed w0: + // 0x000: guard job 0 input (115_200, 1, 1) -> folded (65_535, 2, 1), limit = 115_200 at 0x100 + // 0x010: guard job 1 input (0xFFFF_FFFF, 1, 1) -> zeroed (0, 0, 0), limit = 0 at 0x104 + // 0x200: scale job 0 (2 cmds, stride 16, mesh_offset 4, split 2, cap 10, count=1 at 0x300) + // cmd0 = [0xAA, 4, 2, 1] -> n=8 -> compute (8,1,1), mesh (16,1,1) + // cmd1 = [0xBB, 3, 1, 1] -> tid>=live(1) -> (0,1,1) + let mut p = std::ptr::null_mut(); + up_w0.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::write_bytes(p as *mut u8, 0, 4096); + let w0_u32 = std::slice::from_raw_parts_mut(p as *mut u32, 1024); + w0_u32[0..3].copy_from_slice(&[115_200, 1, 1]); + w0_u32[4..7].copy_from_slice(&[u32::MAX, 1, 1]); + w0_u32[0x200 / 4..0x200 / 4 + 8].copy_from_slice(&[0xAA, 4, 2, 1, 0xBB, 3, 1, 1]); + w0_u32[0x300 / 4] = 1; + up_w0.Unmap(0, None); + + // Seed jobs: guard batch at 0x000 (2 jobs), scale batch at 0x200 (1 job). + up_jobs.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::write_bytes(p as *mut u8, 0, 4096); + let j_u32 = std::slice::from_raw_parts_mut(p as *mut u32, 1024); + j_u32[0..4].copy_from_slice(&[2, 0, 0, 0]); + j_u32[4..12].copy_from_slice(&[0, 0x000, MOST_GROUPS, 0x000, 0, 0x100, 0, 0]); + j_u32[12..20].copy_from_slice(&[0, 0x010, MOST_GROUPS, 0x100, 0, 0x104, 0, 0]); + j_u32[0x200 / 4..0x200 / 4 + 12].copy_from_slice(&[2, 16, 4, 2, 10, 0, 0x200, 0x400, 1, 0, 0x300, 0]); + up_jobs.Unmap(0, None); + + list.CopyBufferRegion(&w0, 0, &up_w0, 0, 4096); + list.CopyBufferRegion(&jobs, 0, &up_jobs, 0, 4096); + emit_transition(&list, &w0, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + emit_transition(&list, &jobs, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + emit_transition(&list, &dst, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + + let w0_va = w0.GetGPUVirtualAddress(); + let dst_va = dst.GetGPUVirtualAddress(); + let jobs_va = jobs.GetGPUVirtualAddress(); + list.SetComputeRootSignature(&guard_rs); + list.SetPipelineState(&guard_pso); + list.SetComputeRootUnorderedAccessView(0, jobs_va); + list.SetComputeRootUnorderedAccessView(1, dst_va); + for k in 2..6 { + list.SetComputeRootUnorderedAccessView(k, w0_va); + } + list.Dispatch(1, 1, 1); + emit_uav_barrier(&list, Some(&w0)); + + list.SetComputeRootSignature(&scale_rs); + list.SetPipelineState(&scale_pso); + list.SetComputeRootUnorderedAccessView(0, jobs_va + 0x200); + list.SetComputeRootUnorderedAccessView(1, dst_va); + for k in 2..6 { + list.SetComputeRootUnorderedAccessView(k, w0_va); + } + list.Dispatch(1, 1, 1); + + emit_transition(&list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + emit_transition(&list, &w0, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.CopyBufferRegion(&rb_dst, 0, &dst, 0, 4096); + list.CopyBufferRegion(&rb_w0, 0, &w0, 0, 4096); + list.Close().unwrap(); + + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 5000).unwrap(); + + rb_dst.Map(0, None, Some(&mut p)).unwrap(); + let out = std::slice::from_raw_parts(p as *const u32, 1024); + assert_eq!(&out[0..3], &[65_535, 2, 1], "guard job 0 must fold 115,200 into 65,535 x 2 x 1"); + assert_eq!(&out[0x100 / 4..0x100 / 4 + 3], &[0, 0, 0], "guard job 1 overflow must zero out"); + // Scale job 0 output at 0x400: compute cmds (0x400..0x420), mesh cmds (0x420..0x440) + let s = 0x400 / 4; + assert_eq!(&out[s..s + 4], &[0xAA, 8, 1, 1], "scale cmd0 compute"); + assert_eq!(&out[s + 4..s + 8], &[0xBB, 0, 1, 1], "scale cmd1 masked by count"); + assert_eq!(&out[s + 8..s + 12], &[0xAA, 16, 1, 1], "scale cmd0 mesh (split=2)"); + assert_eq!(&out[s + 12..s + 16], &[0xBB, 0, 1, 1], "scale cmd1 mesh masked by count"); + rb_dst.Unmap(0, None); + + rb_w0.Map(0, None, Some(&mut p)).unwrap(); + let w0_out = std::slice::from_raw_parts(p as *const u32, 1024); + assert_eq!(w0_out[0x100 / 4], 115_200, "guard job 0 must store IO_GROUP_LIMIT"); + assert_eq!(w0_out[0x104 / 4], 0, "guard job 1 overflow must store 0 limit"); + rb_w0.Unmap(0, None); + let _ = alloc; + } + } - let mut raw_list: *mut c_void = std::ptr::null_mut(); - let iid = windows_sys::core::GUID::from_u128(0x5b160d0f_ac1b_4185_8ba8_b3ae42a5a455); - let hr = device_x::create_command_list_pc( - dev.as_raw(), - 0, - D3D12_COMMAND_LIST_TYPE_DIRECT.0 as u32, - alloc.as_raw() as usize, - standin, - &iid, - &mut raw_list, + /// When `alloc_pool` maps a list to a PC backing allocator distinct from the title allocator, + /// `bind::reset` must pin the recording's UMA blocks to the PC backing allocator so resetting + /// the title allocator (or a newer swapped backing) cannot free in-flight `io`/`consts` early. + #[test] + fn bind_reset_pins_resources_to_alloc_pool_backing() { + let list = 0x7E57_9001usize as *mut c_void; + let title_alloc = 0x7E57_9010usize; + let backing_a = 0x7E57_9020usize; + let backing_b = 0x7E57_9030usize; + super::super::alloc_pool::created_on(list as usize, backing_a, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + reset(list, title_alloc, 0); + assert_eq!(with(list, |s| s.allocator), backing_a); + with(list, |s| s.uma.push(0xDEAD_1000)); + // Next recording on a different backing retires the previous UMA block under `backing_a`. + super::super::alloc_pool::created_on(list as usize, backing_b, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + reset(list, title_alloc, 0); + assert_eq!(with(list, |s| s.allocator), backing_b); + assert!(console_list::take_pending_for_test(title_alloc).is_empty(), "must not attach to title allocator"); + assert!(console_list::take_pending_for_test(backing_b).is_empty(), "must not attach to newer backing"); + assert_eq!(console_list::take_pending_for_test(backing_a), vec![0xDEAD_1000]); + forget(list); + super::super::alloc_pool::forget_list(list as usize); + } + + #[test] + fn rebind_allocator_clears_per_recording_state_even_on_same_backing() { + let list = 0x7E57_9101usize as *mut c_void; + let title_alloc = 0x7E57_9110usize; + let backing_a = 0x7E57_9120usize; + let backing_b = 0x7E57_9130usize; + super::super::alloc_pool::created_on(list as usize, backing_a, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + reset(list, title_alloc, 0); + with(list, |s| { + s.heaps_ensured = true; + s.arg_order_clean = true; + s.pc_abi_gfx.rs = 0x1111; + s.pc_abi_cs.rs = 0x2222; + s.scratch[0].state = GUARDED_ARGS_STATE; + s.uma.push(0xBEEF_1000); + }); + + // Same backing: per-recording native-reset state must clear while UMA blocks stay pinned. + rebind_allocator(list, title_alloc); + with(list, |s| { + assert_eq!(s.allocator, backing_a); + assert!(!s.heaps_ensured); + assert!(!s.arg_order_clean); + assert_eq!(s.pc_abi_gfx.rs, 0); + assert_eq!(s.pc_abi_cs.rs, 0); + assert_eq!(s.scratch[0].state, D3D12_RESOURCE_STATE_COMMON); + assert_eq!(s.uma, vec![0xBEEF_1000]); + }); + + // Rotated backing: per-recording state clears and prior UMA blocks retire onto `backing_a`. + with(list, |s| s.heaps_ensured = true); + super::super::alloc_pool::created_on(list as usize, backing_b, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + rebind_allocator(list, title_alloc); + with(list, |s| { + assert_eq!(s.allocator, backing_b); + assert!(!s.heaps_ensured); + assert!(s.uma.is_empty()); + }); + assert_eq!(console_list::take_pending_for_test(backing_a), vec![0xBEEF_1000]); + forget(list); + super::super::alloc_pool::forget_list(list as usize); + } + + /// `SCALE_ARGS_HEAP_HLSL` and `GUARD_ARGS_HEAP_HLSL` read from a real 4 GiB reserved buffer's + /// raw UAV in `ResourceDescriptorHeap`: a mapped tile produces exact scaled/folded outputs, + /// while an unmapped NULL tile reads safely as zero with no GPU page fault. + #[test] + fn gpu_heap_args_pipelines_handle_mapped_and_unmapped_reserved_tiles() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + const TILE: u64 = 0x1_0000; + const GIB: u64 = 1 << 30; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let res_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 4 * GIB, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut win: Option = None; + if dev.CreateReservedResource(&res_desc, D3D12_RESOURCE_STATE_COMMON, None, &mut win).is_err() { + crate::gpu::recomp::runner::skip_test("no 4 GiB reserved buffer"); + return; + } + let win = win.unwrap(); + let mut tile_heap: Option = None; + dev.CreateHeap( + &D3D12_HEAP_DESC { + SizeInBytes: TILE, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, + }, + &mut tile_heap, + ) + .unwrap(); + let tile_heap = tile_heap.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + // Map ONLY tile 0; tile 1 (offset 0x1_0000) stays intentionally UNMAPPED (NULL tile). + let coord = D3D12_TILED_RESOURCE_COORDINATE { X: 0, ..Default::default() }; + let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, ..Default::default() }; + let flag = D3D12_TILE_RANGE_FLAG_NONE; + let zero = 0u32; + let one = 1u32; + queue.UpdateTileMappings(&win, 1, Some(&coord), Some(®ion), &tile_heap, 1, Some(&flag), Some(&zero), Some(&one), D3D12_TILE_MAPPING_FLAG_NONE); + + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: crate::gpu::recomp::MEM_HEAP_BASE + 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .unwrap(); + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let slot = crate::gpu::recomp::MEM_HEAP_BASE; + let cpu = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dh.GetCPUDescriptorHandleForHeapStart().ptr + slot as usize * inc }; + dev.CreateUnorderedAccessView(&win, None::<&ID3D12Resource>, Some(&crate::gpu::recomp::runner::raw_window_uav(4 * GIB)), cpu); + + let make_buf = |bytes: u64, heap_type: D3D12_HEAP_TYPE, uav: bool, state: D3D12_RESOURCE_STATES| -> ID3D12Resource { + let d = 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: if uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap_type, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, state, None, &mut r).unwrap(); + r.unwrap() + }; + let up = make_buf(256, D3D12_HEAP_TYPE_UPLOAD, false, D3D12_RESOURCE_STATE_GENERIC_READ); + let dst = make_buf(1024, D3D12_HEAP_TYPE_DEFAULT, true, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + let rb = make_buf(1024, D3D12_HEAP_TYPE_READBACK, false, D3D12_RESOURCE_STATE_COPY_DEST); + + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::write_bytes(p as *mut u8, 0, 256); + let u32s = std::slice::from_raw_parts_mut(p as *mut u32, 64); + // Offset 0x00: guard input (115_200, 1, 1); Offset 0x40: scale input [0x77, 15, 2, 1] + u32s[0..3].copy_from_slice(&[115_200, 1, 1]); + u32s[16..20].copy_from_slice(&[0x77, 15, 2, 1]); + up.Unmap(0, None); + + let (scale_rs, scale_pso) = scale_indirect_heap_pipeline(&dev).expect("scale_indirect_heap_pipeline"); + let (guard_rs, guard_pso) = guard_indirect_heap_pipeline(&dev).expect("guard_indirect_heap_pipeline"); + 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.CopyBufferRegion(&win, 0, &up, 0, 256); + emit_transition(&list, &win, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetDescriptorHeaps(&[Some(dh.clone())]); + + let dst_va = dst.GetGPUVirtualAddress(); + // 1. Guard on mapped tile 0 (offset 0) -> dst[0x000] + lim at dst[0x020] + let g_mapped = [slot, 0u32, MOST_GROUPS, 32u32]; + list.SetComputeRootSignature(&guard_rs); + list.SetPipelineState(&guard_pso); + list.SetComputeRoot32BitConstants(0, 4, g_mapped.as_ptr() as *const c_void, 0); + list.SetComputeRootUnorderedAccessView(1, dst_va); + list.SetComputeRootUnorderedAccessView(2, dst_va); + list.Dispatch(1, 1, 1); + // 2. Guard on UNMAPPED tile 1 (offset 0x1_0000) -> dst[0x100] (must read 0 without fault) + let g_unmapped = [slot, TILE as u32, MOST_GROUPS, 32u32]; + list.SetComputeRoot32BitConstants(0, 4, g_unmapped.as_ptr() as *const c_void, 0); + list.SetComputeRootUnorderedAccessView(1, dst_va + 0x100); + list.SetComputeRootUnorderedAccessView(2, dst_va + 0x100); + list.Dispatch(1, 1, 1); + // 3. Scale on mapped tile 0 (offset 0x40, cap 10, split 2) -> dst[0x200] + let s_mapped = [1u32, 16, 4, 2, 10, slot, 0x40, 0, slot, 0]; + list.SetComputeRootSignature(&scale_rs); + list.SetPipelineState(&scale_pso); + list.SetComputeRoot32BitConstants(0, 10, s_mapped.as_ptr() as *const c_void, 0); + list.SetComputeRootUnorderedAccessView(1, dst_va + 0x200); + list.Dispatch(1, 1, 1); + // 4. Scale on UNMAPPED tile 1 (offset 0x1_0000, count from UNMAPPED tile 1) -> dst[0x300] + let s_unmapped = [1u32, 16, 4, 2, 10, slot, TILE as u32, 1, slot, TILE as u32 + 16]; + list.SetComputeRoot32BitConstants(0, 10, s_unmapped.as_ptr() as *const c_void, 0); + list.SetComputeRootUnorderedAccessView(1, dst_va + 0x300); + list.Dispatch(1, 1, 1); + + emit_transition(&list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.CopyBufferRegion(&rb, 0, &dst, 0, 1024); + 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(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 10_000).unwrap(); + + rb.Map(0, None, Some(&mut p)).unwrap(); + let out = std::slice::from_raw_parts(p as *const u32, 256); + assert_eq!(&out[0..3], &[65_535, 2, 1], "mapped guard fold"); + assert_eq!(out[8], 115_200, "mapped guard IO_GROUP_LIMIT"); + assert_eq!(&out[0x100 / 4..0x100 / 4 + 3], &[0, 0, 0], "unmapped guard reads zero safely"); + assert_eq!(&out[0x200 / 4..0x200 / 4 + 8], &[0x77, 10, 1, 1, 0x77, 20, 1, 1], "mapped scale compute+mesh"); + assert_eq!(&out[0x300 / 4..0x300 / 4 + 8], &[0, 0, 1, 1, 0, 0, 1, 1], "unmapped scale reads zero safely"); + rb.Unmap(0, None); + } + } + + #[test] + fn stack_io_builders_match_console_list_user_data_bit_for_bit() { + let layout = console_list::layout_from_blob(&test_rts0_blob()).expect("test layout"); + let args = vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC]; + let table_at = 0x1234_5678_9ABC_DEF0u64; + let heaps = [0x0010_0000u32, 0x0020_0000u32]; + let uma_base = 0x0000_007F_0000_0000usize; + + let mut want_gfx = console_list::with_heaps(&layout, None, console_list::user_data_gfx(&layout, &args, table_at), heaps); + want_gfx.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + want_gfx[crate::gpu::recomp::IO_UMA_BASE_HI] = (uma_base as u64 >> 32) as u32; + assert_eq!(fill_io_gfx(Some(&layout), &args, table_at, heaps, uma_base).as_slice(), want_gfx.as_slice()); + + for user_sgprs in [None, Some(4), Some(8), Some(16)] { + let mut want_cs = console_list::with_heaps(&layout, user_sgprs, console_list::user_data_for(&layout, user_sgprs, &args, table_at), heaps); + want_cs.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + want_cs[crate::gpu::recomp::IO_UMA_BASE_HI] = (uma_base as u64 >> 32) as u32; + want_cs[crate::gpu::recomp::IO_GROUP_LIMIT] = 115_200; + assert_eq!( + fill_io_compute(Some(&layout), user_sgprs, &args, table_at, heaps, uma_base, 115_200).as_slice(), + want_cs.as_slice(), + "compute user_sgprs={user_sgprs:?}" ); - assert!(hr >= 0 && !raw_list.is_null(), "create_command_list_pc failed: {hr:#x}"); - let backing = title_list::backing(raw_list).expect("wrapped in title_list"); - assert_eq!(tracked_pso(backing), standin, "CreateCommandList must seed bind::State.pso"); + } + } - // ClearState(pso2) updates bind::State.pso to pso2 and clears root args. - let rs_key = 0x7300_0010usize; - console_list::note_root_signature(rs_key, &test_rts0_blob()); - set_compute_root_signature(backing, rs_key as *mut c_void); - set_compute_root_constant(backing, 0, 0xABCD, 0); - let cl = ID3D12GraphicsCommandList::from_raw_borrowed(&backing).unwrap(); - cl.ClearState(&pso2); - assert_eq!(tracked_pso(backing), pso2.as_raw() as usize, "ClearState must update bind::State.pso"); - with(backing, |s| assert!(s.layout.is_none() && s.args.is_empty())); + #[test] + fn idempotent_root_signature_preserves_io_cache_and_zero_alloc_constants_write_exact_words() { + let list = 0x7600_9001usize as *mut c_void; + let rs_key = 0x7600_9010usize; + console_list::note_root_signature(rs_key, &test_rts0_blob()); + reset(list, 0x7600_9100, 0); + unsafe { + set_graphics_root_signature(list, rs_key as *mut c_void); + let words = [0x1122_3344u32, 0x5566_7788u32]; + set_graphics_root_constants(list, 0, 2, words.as_ptr(), 0); + } + let gen1 = with(list, |s| { + assert_eq!(&s.args_gfx[..8], &[0x44, 0x33, 0x22, 0x11, 0x88, 0x77, 0x66, 0x55]); + s.io_cache_gfx = Some((s.args_gen_gfx, 0x8888_0000)); + s.args_gen_gfx + }); + // Re-binding the exact same graphics root signature preserves args_gen and io_cache. + unsafe { set_graphics_root_signature(list, rs_key as *mut c_void); } + with(list, |s| { + assert_eq!(s.args_gen_gfx, gen1); + assert_eq!(s.io_cache_gfx, Some((gen1, 0x8888_0000))); + }); + forget(list); + } - // ClearState(None) clears bind::State.pso to 0. - cl.ClearState(None); - assert_eq!(tracked_pso(backing), 0, "ClearState(None) must clear bind::State.pso"); + #[test] + fn indirect_draw_guard_caps_per_instance_and_total_vertices() { + // Zero verts or zero instances are zeroed cleanly. + assert!(draw_record_rejected(0, 1)); + assert!(draw_record_rejected(100, 0)); + assert!(draw_record_rejected(0, u32::MAX)); + // Just below 2^23 per instance is allowed. + assert!(!draw_record_rejected(DRAW_VERTS_PER_INST_LIMIT - 1, 1)); + // Exactly 2^23 (8,388,608) per instance is rejected. + assert!(draw_record_rejected(DRAW_VERTS_PER_INST_LIMIT, 1)); + // Exact 2^26 (67,108,864) total vertices is allowed; 2^26 + 1 is rejected. + assert!(!draw_record_rejected(1 << 22, 16)); + assert!(draw_record_rejected(1 << 22, 17)); + assert!(!draw_record_rejected(1, DRAW_TOTAL_VERTS_MAX)); + assert!(draw_record_rejected(1, DRAW_TOTAL_VERTS_MAX + 1)); + // Overflowing u32 products are rejected cleanly without wraparound. + assert!(draw_record_rejected(1 << 20, u32::MAX)); + assert!(draw_record_rejected(u32::MAX, u32::MAX)); + // Draw signature note/clear avoids stale address reuse. + let sig = 0x7600_A001usize; + note_draw_signature(sig, Some((20, 0, true))); + assert_eq!(draw_sig_of(sig), Some(DrawSig { byte_stride: 20, draw_offset: 0, indexed: true })); + note_draw_signature(sig, None); + assert_eq!(draw_sig_of(sig), None); + } - // Close + reset_x(alloc, pso2) updates bind::State.pso to pso2 and clears root args. - set_graphics_root_signature(backing, rs_key as *mut c_void); - set_graphics_root_constant(backing, 0, 0x1111, 0); - cl.Close().expect("Close"); - let hr = list_x::reset_x(backing, alloc.as_raw() as usize, pso2.as_raw() as usize); - assert!(hr >= 0, "reset_x failed: {hr:#x}"); - assert_eq!(tracked_pso(backing), pso2.as_raw() as usize, "Reset must update bind::State.pso"); - with(backing, |s| assert!(s.layout_gfx.is_none() && s.args_gfx.is_empty())); + #[test] + fn aux_uav_u4_fallback_and_non_poisoning_zero_max_guards() { + // Primary non-null GPU VA is preserved; None or Some(0) falls back to valid non-null VA. + assert_eq!(resolve_aux_uav_va(Some(0x1_0000_0100), 0x2_0000_0200).unwrap(), 0x1_0000_0100); + assert_eq!(resolve_aux_uav_va(None, 0x2_0000_0200).unwrap(), 0x2_0000_0200); + assert_eq!(resolve_aux_uav_va(Some(0), 0x2_0000_0200).unwrap(), 0x2_0000_0200); + // Never allows GPU VA 0x0 to be bound on u4 even if fallback is also 0. + assert!(resolve_aux_uav_va(None, 0).is_err()); + assert!(resolve_aux_uav_va(Some(0), 0).is_err()); + + // max == 0 is rejected immediately before emitting any scale/draw guard pass. + assert!(validate_scale_args_layout(0, 16, 4).is_err()); + + // Per-record indirect draw guard is strictly non-poisoning: a garbage record zeroes only + // itself and never rejects subsequent valid records. + let records = [(u32::MAX, u32::MAX), (3000, 4), (DRAW_VERTS_PER_INST_LIMIT, 1), (1024, 16)]; + let rejected: Vec = records.iter().map(|&(v, i)| draw_record_rejected(v, i)).collect(); + assert_eq!(rejected, vec![true, false, true, false]); + } - // Release the wrapped title list cleanly (calls bind::forget + list_x::on_release). - let release_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(raw_list as *const *const usize)).add(2)); - assert_eq!(release_fn(raw_list), 0); - let _ = pso_async::released(standin); + #[test] + fn recycle_into_pool_drops_overflow_outside_pool_lock() { + struct ReentrantDrop { + pool: Arc>>, + drops_outside_lock: Arc, + } + impl Drop for ReentrantDrop { + fn drop(&mut self) { + // Mirrors COM Release re-entering `release_allocator_res`: fails immediately if + // overflow drops while `pool` is still locked (would self-deadlock on `.lock()`). + let _guard = self + .pool + .try_lock() + .expect("overflow item must be dropped after releasing the pool mutex"); + self.drops_outside_lock.fetch_add(1, Ordering::SeqCst); + } } + + let pool: Arc>> = Arc::new(Mutex::new(Vec::new())); + let drops = Arc::new(AtomicU64::new(0)); + let items: Vec<_> = (0..4) + .map(|_| ReentrantDrop { pool: Arc::clone(&pool), drops_outside_lock: Arc::clone(&drops) }) + .collect(); + recycle_into_pool(&pool, items, |p, _| p.len() < 2); + assert_eq!(drops.load(Ordering::SeqCst), 2, "both overflow items must drop outside the lock"); + assert_eq!(pool.lock().unwrap().len(), 2); + let kept = std::mem::take(&mut *pool.lock().unwrap()); + drop(kept); + assert_eq!(drops.load(Ordering::SeqCst), 4); } } diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 4862abd84c..ff64e8c11c 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -25,7 +25,9 @@ //! 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::Mutex; +use std::collections::{HashMap, VecDeque}; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Mutex, RwLock}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; @@ -56,7 +58,7 @@ struct Heap { sampler: bool, /// views in the shared heap: the index there of each page's first SRV (`UNMAPPED`: the /// page has no place yet); empty: the heap's views are not in the shared heap - pages: Vec, + pages: Vec, /// shader visible as the title made it visible: bool, memory: Memory, @@ -72,7 +74,182 @@ impl Heap { } } -static HEAPS: Mutex> = Mutex::new(Vec::new()); +static HEAPS: RwLock> = RwLock::new(Vec::new()); + +/// Active destination descriptor leases for lock-free `CopyDescriptorsSimple` calls and any +/// freed ranges whose return to `free` is deferred until overlapping copies complete. +#[derive(Default)] +struct LeasePool { + leased: Vec<(u32, u32)>, + deferred: Vec<(u32, u32)>, +} + +fn ranges_overlap(a: (u32, u32), b: (u32, u32)) -> bool { + a.0 < b.0.saturating_add(b.1) && b.0 < a.0.saturating_add(a.1) +} + +impl LeasePool { + fn acquire(&mut self, first: u32, count: u32) { + if count > 0 { + self.leased.push((first, count)); + } + } + + fn release_or_defer(&mut self, free: &mut Vec<(u32, u32)>, first: u32, count: u32) -> bool { + if self.leased.iter().any(|&l| ranges_overlap(l, (first, count))) { + self.deferred.push((first, count)); + false + } else { + merge_release(free, first, count); + true + } + } + + fn end_leases(&mut self, free: &mut Vec<(u32, u32)>, ranges: &[(u32, u32)]) -> bool { + for &r in ranges { + if let Some(i) = self.leased.iter().position(|&x| x == r) { + self.leased.swap_remove(i); + } + } + let mut promoted = false; + let mut i = 0; + while i < self.deferred.len() { + let r = self.deferred[i]; + if !self.leased.iter().any(|&l| ranges_overlap(l, r)) { + self.deferred.swap_remove(i); + merge_release(free, r.0, r.1); + promoted = true; + } else { + i += 1; + } + } + promoted + } +} + +struct SingleLease { + sampler: bool, + first: u32, + count: u32, +} + +impl Drop for SingleLease { + fn drop(&mut self) { + if self.count == 0 { + return; + } + if self.sampler { + if let Some(s) = GLOBAL_SAMPLER.write().unwrap_or_else(|e| e.into_inner()).as_mut() { + if s.leases.end_leases(&mut s.free, &[(self.first, self.count)]) { + s.smallest_failed = u32::MAX; + } + } + } else if let Some(s) = GLOBAL.write().unwrap_or_else(|e| e.into_inner()).as_mut() { + if s.leases.end_leases(&mut s.free, &[(self.first, self.count)]) { + s.smallest_failed = u32::MAX; + } + } + } +} + +struct RangeLease { + sampler: bool, + ranges: Vec<(u32, u32)>, +} + +impl Drop for RangeLease { + fn drop(&mut self) { + if self.ranges.is_empty() { + return; + } + if self.sampler { + if let Some(s) = GLOBAL_SAMPLER.write().unwrap_or_else(|e| e.into_inner()).as_mut() { + if s.leases.end_leases(&mut s.free, &self.ranges) { + s.smallest_failed = u32::MAX; + } + } + } else if let Some(s) = GLOBAL.write().unwrap_or_else(|e| e.into_inner()).as_mut() { + if s.leases.end_leases(&mut s.free, &self.ranges) { + s.smallest_failed = u32::MAX; + } + } + } +} + +/// 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>, +} + +fn drain_retired_ranges( + retired: &mut VecDeque>, + free: &mut Vec<(u32, u32)>, + leases: &mut LeasePool, + mut completed: impl FnMut(&F) -> u64, +) -> bool { + let mut drained = false; + while retired + .front() + .is_some_and(|r| r.marks.as_ref().is_some_and(|m| m.iter().all(|(f, v)| completed(f) >= *v))) + { + if let Some(r) = retired.pop_front() { + if leases.release_or_defer(free, r.first, r.count) { + drained = true; + } + } + } + drained +} + +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); + +/// Signal every known live title queue belonging to `dev` (called outside `GLOBAL`/`GLOBAL_SAMPLER` +/// and `HEAPS`). 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 { @@ -83,14 +260,20 @@ 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 entering `free` + retired: VecDeque>, + leases: LeasePool, + /// smallest allocation size that recently failed on a full/fragmented heap (`u32::MAX` = none) + smallest_failed: u32, } // D3D12 descriptor heaps and devices are free-threaded unsafe impl Send for Global {} +unsafe impl Sync for Global {} -static GLOBAL: Mutex> = Mutex::new(None); +static GLOBAL: RwLock> = RwLock::new(None); static GLOBAL_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// descriptors of the shared heap at most (the GPU may take more: OPTIONS19) @@ -105,6 +288,14 @@ pub const PAGE_SLOTS: u32 = 256; /// a page with no place in the shared heap yet const UNMAPPED: u32 = u32::MAX; +/// Fallback index for a view slot when no `GLOBAL` page is mapped: +/// hosted heaps (`hosted == true`, whose lists bind `GLOBAL`) map overflowed slots to reserved +/// null-view slot `0` (SRV at 0, UAV at 1) so exhaustion never aliases `MEM_HEAP_BASE` window +/// UAVs or unrelated descriptors; unhosted heaps keep local `2 * k`. +fn view_unmapped_index(hosted: bool, k: u32) -> u32 { + if hosted { 0 } else { 2 * k } +} + /// PC descriptors of page `p` of a heap of `n` slots: 2 per slot, and the last page only as /// long as the heap (a heap of a few slots takes a few descriptors, not a whole page's). fn page_descriptors(n: u32, p: u32) -> u32 { @@ -153,7 +344,10 @@ unsafe fn global_cap(dev: &ID3D12Device) -> u32 { /// made) – view heaps then keep their own. pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { use std::sync::atomic::Ordering::Relaxed; - let mut g = GLOBAL.lock().unwrap(); + if GLOBAL.read().unwrap().is_some() { + return true; + } + let mut g = GLOBAL.write().unwrap(); if g.is_none() { if GLOBAL_FAILED.load(Relaxed) { return false; @@ -177,9 +371,13 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { inc: dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), heap, cap, - // 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, + // the memory windows' raw UAVs and the null view after them (`set_window_views`) + // come first + next: crate::gpu::recomp::MEM_HEAP_NULL + 1, free: Vec::new(), + retired: VecDeque::new(), + leases: LeasePool::default(), + smallest_failed: u32::MAX, }); } true @@ -211,6 +409,7 @@ unsafe fn null_views(dev: &ID3D12Device, cpu: u64, inc: u32) { } static WINDOW_VIEWS_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static WINDOW_VIEWS_READY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// Whether the memory windows could not be put in the shared heap (`set_window_views`): /// translated shaders then switch over root UAVs (`pso::heap_windows`). @@ -218,16 +417,32 @@ pub fn window_views_failed() -> bool { WINDOW_VIEWS_FAILED.load(std::sync::atomic::Ordering::Relaxed) } +/// Whether the memory windows' raw UAV descriptors are published at `MEM_HEAP_BASE + k` in +/// the shared shader-visible descriptor heap (`set_window_views` succeeded). +pub fn window_views_ready() -> bool { + WINDOW_VIEWS_READY.load(std::sync::atomic::Ordering::Acquire) +} + /// The memory windows' buffers `(resource, bytes)` as raw UAVs at `MEM_HEAP_BASE + k` of the /// shared heap, made now if need be (`Options::heap_windows`: shaders take window k from there). /// Active windows (`bytes > 0`) in wider layouts (8 / 16) must all have a valid buffer; unused -/// trailing slots (`(0, 0)`) safely alias window 0's buffer. +/// trailing slots (`(0, 0)`) safely alias window 0's buffer. `MEM_HEAP_NULL` after the windows +/// holds a null raw UAV; heap views require 64-bit atomics on descriptor heap resources. pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) -> bool { + let mut o11 = D3D12_FEATURE_DATA_D3D12_OPTIONS11::default(); + let atomics64 = dev + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS11, &mut o11 as *mut _ as *mut std::ffi::c_void, std::mem::size_of_val(&o11) as u32) + .is_ok() + && o11.AtomicInt64OnDescriptorHeapResourceSupported.as_bool(); + set_window_views_checked(dev, windows, atomics64) +} + +unsafe fn set_window_views_checked(dev: &ID3D12Device, windows: &[(usize, usize)], atomics64: bool) -> bool { let count = windows.len().max(crate::gpu::uma::MAX_WINDOWS); let complete = count <= crate::gpu::uma::MAX_WINDOWS || windows.iter().all(|&(raw, bytes)| raw != 0 || bytes == 0); - let ok = count <= crate::gpu::uma::MAX_HEAP_WINDOWS && complete && windows.first().is_some_and(|w| w.0 != 0) && shared_heap(dev) && { + let ok = atomics64 && count <= crate::gpu::uma::MAX_HEAP_WINDOWS && complete && windows.first().is_some_and(|w| w.0 != 0) && shared_heap(dev) && { let (device, cpu, inc) = { - let g = GLOBAL.lock().unwrap(); + let g = GLOBAL.read().unwrap(); let s = g.as_ref().unwrap(); (s.dev.clone(), s.cpu, s.inc) }; @@ -239,11 +454,14 @@ pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) - let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + (crate::gpu::recomp::MEM_HEAP_BASE as u64 + k as u64) * inc as u64) as usize }; device.CreateUnorderedAccessView(r, None::<&ID3D12Resource>, Some(&crate::gpu::recomp::runner::raw_window_uav(bytes as u64)), at); } + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + crate::gpu::recomp::MEM_HEAP_NULL as u64 * inc as u64) as usize }; + device.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&crate::gpu::recomp::runner::raw_window_uav(0)), at); true }; + WINDOW_VIEWS_READY.store(ok, std::sync::atomic::Ordering::Release); if !ok { WINDOW_VIEWS_FAILED.store(true, std::sync::atomic::Ordering::Relaxed); - crate::xlog_warn!("memory windows: could not bind {count} window(s) in the shared descriptor heap"); + crate::xlog_warn!("memory windows: could not bind {count} window(s) (64-bit atomics on heap views: {atomics64}) in the shared descriptor heap"); } ok } @@ -251,12 +469,19 @@ pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) - /// `count` descriptors of the shared heap: the index of the first. None: no shared heap, or /// no room left in it. fn reserve_global(count: u32) -> Option { - let mut g = GLOBAL.lock().unwrap(); + let mut g = GLOBAL.write().unwrap(); let s = g.as_mut()?; + if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, &mut s.leases, |f| f.GetCompletedValue()) } { + s.smallest_failed = u32::MAX; + } + if count >= s.smallest_failed { + return None; + } let (cap, mut next) = (s.cap, s.next); let r = take_range(&mut s.free, &mut next, cap, count); s.next = next; if r.is_none() { + s.smallest_failed = s.smallest_failed.min(count); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0 { crate::xlog_warn!("console descriptor heaps: the shared heap ({cap}) is full – shaders do not see the views of slots past it"); @@ -268,23 +493,45 @@ fn reserve_global(count: u32) -> Option { /// The place in the shared heap of the page slot `k` of `h` is in – (index of the page's /// first SRV there, the page's first slot) – given now if the page has none yet. None: the /// heap is not in the shared heap, or that is full. -fn page_of(h: &mut Heap, k: u32) -> Option<(u32, u32)> { +fn page_of(h: &Heap, k: u32) -> Option<(u32, u32)> { let p = (k / PAGE_SLOTS) as usize; - let mut first = *h.pages.get(p)?; + let slot_atom = h.pages.get(p)?; + let mut first = slot_atom.load(Ordering::Acquire); if first == UNMAPPED { - first = reserve_global(page_descriptors(h.n, p as u32))?; - h.pages[p] = first; + let count = page_descriptors(h.n, p as u32); + let alloc = reserve_global(count)?; + match slot_atom.compare_exchange(UNMAPPED, alloc, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => first = alloc, + Err(existing) => { + release_global(alloc, count); + first = existing; + } + } } Some((first, p as u32 * PAGE_SLOTS)) } -/// The shared range starting at `first` (`count` descriptors) is free again. +/// The shared range starting at `first` (`count` descriptors) is quarantined behind active GPU +/// queues (and any in-flight `publish` / `publish_range` destination leases) before returning to +/// `free`, preventing overwrites of live shader-visible descriptors. pub fn release_global(first: u32, count: u32) { if count == 0 { return; } - if let Some(s) = GLOBAL.lock().unwrap().as_mut() { - merge_release(&mut s.free, first, count); + let dev = GLOBAL.read().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.write().unwrap().as_mut() { + if marks.as_ref().is_some_and(Vec::is_empty) { + if s.leases.release_or_defer(&mut s.free, first, count) { + s.smallest_failed = u32::MAX; + } + } else { + s.retired.push_back(RetiredRange { first, count, marks }); + } + if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, &mut s.leases, |f| f.GetCompletedValue()) } { + s.smallest_failed = u32::MAX; + } } } @@ -305,12 +552,29 @@ fn merge_release(free: &mut Vec<(u32, u32)>, first: u32, count: u32) { /// The shader-visible PC heap lists bind for view descriptors (None: none shared). pub fn global_heap() -> Option { - GLOBAL.lock().unwrap().as_ref().map(|s| s.heap.clone()) + GLOBAL.read().unwrap().as_ref().map(|s| s.heap.clone()) +} + +/// Raw COM pointer of the shared shader-visible view heap without COM refcount traffic. +pub fn global_heap_raw() -> Option { + GLOBAL.read().unwrap().as_ref().map(|s| s.heap.as_raw() as usize) +} + +/// Binary-search `heaps` (sorted ascending by `shadow`) for the heap covering console handle `cpu`. +#[inline] +fn find_heap_by_addr(heaps: &[Heap], cpu: u64) -> Option<&Heap> { + let idx = heaps.partition_point(|h| (h.shadow as u64) <= cpu); + if idx == 0 { + return None; + } + let h = &heaps[idx - 1]; + let end = (h.shadow as u64).wrapping_add((h.n as u64) * (h.slot_bytes() as u64)); + (cpu < end).then_some(h) } /// Whether `obj` (a title's view heap) has its descriptors in the shared heap. pub fn in_global(obj: usize) -> bool { - HEAPS.lock().unwrap().iter().any(|h| h.obj == obj && !h.sampler && !h.pages.is_empty()) + HEAPS.read().unwrap().iter().any(|h| h.obj == obj && !h.sampler && !h.pages.is_empty()) } /// Memory for a heap of `bytes` from the title's allocation hook – where the title expects the @@ -369,48 +633,67 @@ pub fn register(obj: usize, n: u32, pc_cpu: u64, pc_gpu: u64, inc: u32, sampler: ); } } - let pages = if shared && !sampler && GLOBAL.lock().unwrap().is_some() { - vec![UNMAPPED; n.div_ceil(PAGE_SLOTS).max(1) as usize] - } else if shared && sampler && GLOBAL_SAMPLER.lock().unwrap().is_some() { - vec![UNMAPPED; n.div_ceil(SAMPLER_PAGE_SLOTS).max(1) as usize] + let pages = if shared && !sampler && GLOBAL.read().unwrap().is_some() { + (0..n.div_ceil(PAGE_SLOTS).max(1)).map(|_| AtomicU32::new(UNMAPPED)).collect() + } else if shared && sampler && GLOBAL_SAMPLER.read().unwrap().is_some() { + (0..n.div_ceil(SAMPLER_PAGE_SLOTS).max(1)).map(|_| AtomicU32::new(UNMAPPED)).collect() } else { Vec::new() }; - HEAPS.lock().unwrap().push(Heap { obj, shadow: p as usize, n, pc_cpu, pc_gpu, inc, sampler, pages, visible, memory }); + { + let mut heaps = HEAPS.write().unwrap(); + let idx = heaps.partition_point(|h| h.shadow < p as usize); + heaps.insert(idx, Heap { obj, shadow: p as usize, n, pc_cpu, pc_gpu, inc, sampler, pages, visible, memory }); + } true } /// The heap object was released for good: its slots go back to unified memory. pub fn unregister(obj: usize) { - let gone = { - let mut heaps = HEAPS.lock().unwrap(); - heaps.iter().position(|h| h.obj == obj).map(|i| heaps.swap_remove(i)) - }; - if let Some(h) = gone { - for (p, &f) in h.pages.iter().enumerate().filter(|&(_, &f)| f != UNMAPPED) { - if h.sampler { - release_global_sampler(f, sampler_page_descriptors(h.n, p as u32)); - } else { - release_global(f, page_descriptors(h.n, p as u32)); - } + if let Some(h) = take(obj) { + free(h); + } +} + +/// A heap `take` removed: `free` gives its slots and shadow memory back. +pub struct Taken(Heap); + +/// `unregister`'s first half: the heap is no longer found by its object's address. +pub fn take(obj: usize) -> Option { + let mut heaps = HEAPS.write().unwrap(); + heaps.iter().position(|h| h.obj == obj).map(|i| Taken(heaps.remove(i))) +} + +/// `unregister`'s second half. +pub fn free(Taken(h): Taken) { + for (p, f) in h.pages.iter().enumerate().map(|(p, a)| (p, a.load(Ordering::Relaxed))).filter(|&(_, f)| f != UNMAPPED) { + if h.sampler { + release_global_sampler(f, sampler_page_descriptors(h.n, p as u32)); + } else { + release_global(f, page_descriptors(h.n, p as u32)); } - match h.memory { - Memory::Sparse => { - unsafe { super::sparse::free(h.shadow) }; - } - Memory::Uma => { - if let Some(u) = crate::gpu::uma::get() { - u.free(h.shadow); - } + } + match h.memory { + Memory::Sparse => { + unsafe { super::sparse::free(h.shadow) }; + } + Memory::Uma => { + if let Some(u) = crate::gpu::uma::get() { + u.free(h.shadow); } - Memory::Title => unsafe { crate::hle::kernelx::runtime_free(h.shadow, crate::hle::kernelx::D3D_DESCRIPTOR_HEAP) }, } + Memory::Title => unsafe { crate::hle::kernelx::runtime_free(h.shadow, crate::hle::kernelx::D3D_DESCRIPTOR_HEAP) }, } } +/// Whether heap `obj` holds samplers, and the 32-bit console address of its slots. +pub fn base(obj: usize) -> Option<(bool, u32)> { + HEAPS.read().unwrap().iter().find(|h| h.obj == obj).map(|h| (h.sampler, h.shadow as u32)) +} + /// Start of the console slots of heap `obj` (CPU handle = GPU handle on the console). pub fn start(obj: usize) -> Option { - HEAPS.lock().unwrap().iter().find(|h| h.obj == obj).map(|h| h.shadow as u64) + HEAPS.read().unwrap().iter().find(|h| h.obj == obj).map(|h| h.shadow as u64) } /// A console slot: where its descriptor goes and its PC descriptors. @@ -431,15 +714,11 @@ pub struct Slot { pub k: u32, } -/// 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. -pub fn slot(cpu: u64) -> Option { - 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)?; +fn resolve_slot(h: &Heap, cpu: u64) -> Slot { let k = ((cpu - h.shadow as u64) / h.slot_bytes() as u64) as u32; if h.sampler { let shared = sampler_page_of(h, k).and_then(|(first, k0)| { - let g = GLOBAL_SAMPLER.lock().unwrap(); + let g = GLOBAL_SAMPLER.read().unwrap(); let g = g.as_ref()?; let i = first + (k - k0); Some((i, g.cpu + i as u64 * g.inc as u64)) @@ -448,17 +727,36 @@ pub fn slot(cpu: u64) -> Option { // shared heap must map overflowed slots to reserved zero-sampler slot 0 rather than // aliasing unrelated heap entries at local index `k`. 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 }); + return 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 = GLOBAL.read().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)) }); - let (index, pc_gpu_uav, shared_srv) = shared.unwrap_or((2 * k, if h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav }, 0)); - 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 hosted = !h.pages.is_empty(); + let (index, pc_gpu_uav, shared_srv) = shared.unwrap_or_else(|| { + (view_unmapped_index(hosted, k), if hosted || h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav }, 0) + }); + 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. +pub fn slot(cpu: u64) -> Option { + let heaps = HEAPS.read().unwrap(); + let h = find_heap_by_addr(&heaps, cpu)?; + Some(resolve_slot(h, cpu)) +} + +/// Resolve both `dst` and `src` console handles under a single `HEAPS` read lock. +pub fn slot_pair(dst: u64, src: u64) -> Option<(Slot, Slot)> { + let heaps = HEAPS.read().unwrap(); + let hd = find_heap_by_addr(&heaps, dst)?; + let hs = find_heap_by_addr(&heaps, src)?; + Some((resolve_slot(hd, dst), resolve_slot(hs, src))) } /// The view (or sampler) just made in slot `s` (its SRV, or with `uav` its UAV) goes to the shared heap. @@ -467,47 +765,123 @@ pub unsafe fn publish(s: &Slot, uav: bool) { return; } if s.sampler { - if let Some(g) = GLOBAL_SAMPLER.lock().unwrap().as_ref() { - g.dev.CopyDescriptorsSimple( - 1, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, - D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, - ); - } + let Some((dev, lease)) = GLOBAL_SAMPLER.write().unwrap().as_mut().map(|g| { + let lease = if g.inc > 0 && s.shared_srv >= g.cpu { + let idx = ((s.shared_srv - g.cpu) / g.inc as u64) as u32; + g.leases.acquire(idx, 1); + SingleLease { sampler: true, first: idx, count: 1 } + } else { + SingleLease { sampler: true, first: 0, count: 0 } + }; + (g.dev.clone(), lease) + }) else { + return; + }; + let _lease = lease; + dev.CopyDescriptorsSimple( + 1, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + ); return; } - if let Some(g) = GLOBAL.lock().unwrap().as_ref() { + let Some((dev, dst, src, lease)) = GLOBAL.write().unwrap().as_mut().map(|g| { let (dst, src) = if uav { (s.shared_srv + g.inc as u64, s.pc_uav) } else { (s.shared_srv, s.pc_srv) }; - g.dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - } + let lease = if g.inc > 0 && dst >= g.cpu { + let idx = ((dst - g.cpu) / g.inc as u64) as u32; + g.leases.acquire(idx, 1); + SingleLease { sampler: false, first: idx, count: 1 } + } else { + SingleLease { sampler: false, first: 0, count: 0 } + }; + (g.dev.clone(), dst, src, lease) + }) else { + return; + }; + let _lease = lease; + dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); } /// `n` view or sampler slots from `first` were copied (in the title's heap): they go to the shared heap, -/// a run per page (a heap's pages lie apart there). +/// a run per page (a heap's pages lie apart there), clamped to the heap's bounds. pub unsafe fn publish_range(first: &Slot, n: u32) { + if n == 0 { + return; + } + let mul = if first.sampler { 1u32 } else { 2u32 }; let page_slots = if first.sampler { SAMPLER_PAGE_SLOTS } else { PAGE_SLOTS }; - let step = if first.sampler { SAMPLER_SLOT } else { SLOT }; - let mut done = 0; - while done < n { - let s = if done == 0 { Some(*first) } else { slot((first.at + (done * step) as usize) as u64) }; - let Some(s) = s else { return }; - let run = (page_slots - s.k % page_slots).min(n - done); - if s.shared_srv != 0 { - if s.sampler { - if let Some(g) = GLOBAL_SAMPLER.lock().unwrap().as_ref() { - g.dev.CopyDescriptorsSimple( - run, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, - D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, - ); + let mut runs: Vec<(u32, u64, u32)> = Vec::new(); + let mut leased_ranges: Vec<(u32, u32)> = Vec::new(); + // Hold `HEAPS` while acquiring leases under `GLOBAL*` (strict `HEAPS -> GLOBAL*` lock order) + // so `unregister` cannot release and recycle these destination ranges before the leases exist. + let (dev, g_cpu, g_inc) = { + let heaps = HEAPS.read().unwrap(); + let mut standalone: Option<(u64, u64, u32)> = None; + if let Some(h) = find_heap_by_addr(&heaps, first.at as u64).filter(|h| h.sampler == first.sampler) { + let start_k = ((first.at - h.shadow) / h.slot_bytes() as usize) as u32; + let limit = n.min(h.n.saturating_sub(start_k)); + let mut done = 0u32; + while done < limit { + let k = start_k + done; + let run = (page_slots - k % page_slots).min(limit - done); + let page = if h.sampler { sampler_page_of(h, k) } else { page_of(h, k) }; + if let Some((first_idx, k0)) = page { + let dst_idx = first_idx + mul * (k - k0); + let src = h.pc_cpu + (mul as u64 * k as u64) * h.inc as u64; + runs.push((dst_idx, src, mul * run)); } - } else if let Some(g) = GLOBAL.lock().unwrap().as_ref() { - g.dev.CopyDescriptorsSimple(2 * run, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + done += run; } + } else if first.shared_srv != 0 { + let run = (page_slots - first.k % page_slots).min(n); + standalone = Some((first.shared_srv, first.pc_srv, mul * run)); } - done += run; + if runs.is_empty() && standalone.is_none() { + return; + } + let snap = if first.sampler { + GLOBAL_SAMPLER.write().unwrap().as_mut().map(|g| { + if let Some((dst_ptr, src, cnt)) = standalone { + if g.inc > 0 && dst_ptr >= g.cpu { + runs.push((((dst_ptr - g.cpu) / g.inc as u64) as u32, src, cnt)); + } + } + for &(idx, _, cnt) in &runs { + g.leases.acquire(idx, cnt); + leased_ranges.push((idx, cnt)); + } + (g.dev.clone(), g.cpu, g.inc) + }) + } else { + GLOBAL.write().unwrap().as_mut().map(|g| { + if let Some((dst_ptr, src, cnt)) = standalone { + if g.inc > 0 && dst_ptr >= g.cpu { + runs.push((((dst_ptr - g.cpu) / g.inc as u64) as u32, src, cnt)); + } + } + for &(idx, _, cnt) in &runs { + g.leases.acquire(idx, cnt); + leased_ranges.push((idx, cnt)); + } + (g.dev.clone(), g.cpu, g.inc) + }) + }; + let Some(snap) = snap else { + return; + }; + snap + }; + let _lease = RangeLease { sampler: first.sampler, ranges: leased_ranges }; + let heap_ty = if first.sampler { D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER } else { D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV }; + for (dst_idx, src, count) in runs { + let dst = g_cpu + (dst_idx as u64) * (g_inc as u64); + dev.CopyDescriptorsSimple( + count, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, + heap_ty, + ); } } @@ -545,6 +919,7 @@ pub fn copy_words(src: &Slot, dst: &Slot) { let n = if src.sampler { 4 } else { 8 }; let mut w = [0u32; 8]; unsafe { std::ptr::copy_nonoverlapping(src.at as *const u32, w.as_mut_ptr(), n) }; + let src_w0 = w[0]; if src.sampler { w[3] = (w[3] & !0xFFF) | (dst.index & 0xFFF); } else if w[3] >> 28 >= 8 { @@ -552,15 +927,98 @@ 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)); + if super::present::trace_frame() { + note_resource(dst, resource_at(src.at).unwrap_or(0)); + } + if w[3] >> 28 >= 8 { + let src_idx = if src.shared_srv != 0 { src_w0 } 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); + } } } +/// Copy `n` contiguous console slots from `src` to `dst` under a single shared `HEAPS` read lock, +/// renumbering T#/S# PC heap indices per page run instead of re-acquiring global locks per slot. +pub fn copy_words_range(dst: u64, src: u64, n: u32) -> bool { + if n == 0 { + return true; + } + let heaps = HEAPS.read().unwrap(); + let Some(hd) = find_heap_by_addr(&heaps, dst) else { + return false; + }; + let Some(hs) = find_heap_by_addr(&heaps, src) else { + return false; + }; + if hd.sampler != hs.sampler { + return false; + } + let sampler = hd.sampler; + let step = hd.slot_bytes(); + let kd0 = ((dst - hd.shadow as u64) / step as u64) as u32; + let ks0 = ((src - hs.shadow as u64) / step as u64) as u32; + let count = n.min(hd.n - kd0).min(hs.n - ks0); + let page_slots = if sampler { SAMPLER_PAGE_SLOTS } else { PAGE_SLOTS }; + let words_n = if sampler { 4 } else { 8 }; + let trace = !sampler && super::present::trace_frame(); + let d_hosted = !hd.pages.is_empty(); + let s_hosted = !hs.pages.is_empty(); + + let mut done = 0u32; + while done < count { + let kd = kd0 + done; + let ks = ks0 + done; + let run = (page_slots - kd % page_slots) + .min(page_slots - ks % page_slots) + .min(count - done); + let d_page = if sampler { sampler_page_of(hd, kd) } else { page_of(hd, kd) }; + let s_page = if sampler { sampler_page_of(hs, ks) } else { page_of(hs, ks) }; + for i in 0..run { + let kdi = kd + i; + let ksi = ks + i; + let dst_at = hd.shadow + (kdi * step) as usize; + let src_at = hs.shadow + (ksi * step) as usize; + let dst_idx = match d_page { + Some((first, k0)) => if sampler { first + (kdi - k0) } else { first + 2 * (kdi - k0) }, + None => if sampler { sampler_unmapped_index(d_hosted, kdi) } else { view_unmapped_index(d_hosted, kdi) }, + }; + let mut w = [0u32; 8]; + unsafe { std::ptr::copy_nonoverlapping(src_at as *const u32, w.as_mut_ptr(), words_n) }; + let src_w0 = w[0]; + let is_tex = !sampler && (w[3] >> 28 >= 8); + if sampler { + w[3] = (w[3] & !0xFFF) | (dst_idx & 0xFFF); + } else if is_tex { + w[0] = dst_idx; + } + unsafe { std::ptr::copy_nonoverlapping(w.as_ptr(), dst_at as *mut u32, words_n) }; + if trace { + let res = resource_at(src_at).unwrap_or(0); + let mut g = RES.lock().unwrap(); + let m = g.get_or_insert_with(Default::default); + if res == 0 { + m.remove(&dst_at); + } else { + m.insert(dst_at, res); + } + } + if is_tex { + let src_global = if s_hosted && s_page.is_some() { src_w0 } else { 0 }; + let dst_global = if d_hosted && d_page.is_some() { dst_idx } else { 0 }; + super::ambient::copy_descriptor(src_at, src_global, dst_at, dst_global); + } + } + done += run; + } + true +} + /// `XCL_TRACE_FRAME`: what the slots of each shader-visible view heap hold – images whose /// PC index is the slot's own (made or copied through the device) or another (copied by the /// title itself, as memory), buffers, empty. pub fn census() { - let heaps = HEAPS.lock().unwrap(); + let heaps = HEAPS.read().unwrap(); // samplers: S# word 3 [11:0] is the PC index in the sampler heap the slot belongs to for h in heaps.iter().filter(|h| h.sampler) { let (mut empty, mut own, mut other) = (0u32, 0u32, 0u32); @@ -569,7 +1027,7 @@ pub fn census() { let w = unsafe { std::slice::from_raw_parts((h.shadow + (k * SAMPLER_SLOT) as usize) as *const u32, 4) }; if w.iter().all(|&x| x == 0) { empty += 1; - } else if w[3] & 0xFFF == sampler_own_index(&h.pages, k) { + } else if w[3] & 0xFFF == sampler_own_index_atomic(&h.pages, k) { own += 1; } else { other += 1; @@ -588,8 +1046,8 @@ pub fn census() { for h in heaps.iter().filter(|h| !h.sampler) { let (mut empty, mut own, mut other, mut buffers) = (0u32, 0u32, 0u32, 0u32); let mut examples: Vec<(u32, u32)> = Vec::new(); - let own_index = |k: u32| match h.pages.get((k / PAGE_SLOTS) as usize) { - Some(&f) if f != UNMAPPED => f + 2 * (k % PAGE_SLOTS), + let own_index = |k: u32| match h.pages.get((k / PAGE_SLOTS) as usize).map(|a| a.load(Ordering::Relaxed)) { + Some(f) if f != UNMAPPED => f + 2 * (k % PAGE_SLOTS), _ => 2 * k, }; for k in 0..h.n { @@ -648,6 +1106,7 @@ fn sampler_unmapped_index(hosted: bool, k: u32) -> u32 { } /// Expected PC sampler index for slot `k` of a sampler heap with shared-page table `pages`. +#[cfg(test)] fn sampler_own_index(pages: &[u32], k: u32) -> u32 { match pages.get((k / SAMPLER_PAGE_SLOTS) as usize) { Some(&f) if f != UNMAPPED => f + (k % SAMPLER_PAGE_SLOTS), @@ -655,6 +1114,13 @@ fn sampler_own_index(pages: &[u32], k: u32) -> u32 { } } +fn sampler_own_index_atomic(pages: &[AtomicU32], k: u32) -> u32 { + match pages.get((k / SAMPLER_PAGE_SLOTS) as usize).map(|a| a.load(Ordering::Relaxed)) { + Some(f) if f != UNMAPPED => f + (k % SAMPLER_PAGE_SLOTS), + _ => sampler_unmapped_index(!pages.is_empty(), k), + } +} + struct GlobalSampler { dev: ID3D12Device, heap: ID3D12DescriptorHeap, @@ -663,11 +1129,15 @@ struct GlobalSampler { cap: u32, next: u32, free: Vec<(u32, u32)>, + retired: VecDeque>, + leases: LeasePool, + smallest_failed: u32, } unsafe impl Send for GlobalSampler {} +unsafe impl Sync for GlobalSampler {} -static GLOBAL_SAMPLER: Mutex> = Mutex::new(None); +static GLOBAL_SAMPLER: RwLock> = RwLock::new(None); static GLOBAL_SAMPLER_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); fn sampler_page_descriptors(n: u32, p: u32) -> u32 { @@ -680,7 +1150,10 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { if std::env::var("XCL_SHARED_SAMPLER_HEAP").is_ok_and(|v| v.trim() == "0") { return false; } - let mut g = GLOBAL_SAMPLER.lock().unwrap(); + if GLOBAL_SAMPLER.read().unwrap().is_some() { + return true; + } + let mut g = GLOBAL_SAMPLER.write().unwrap(); if g.is_none() { if GLOBAL_SAMPLER_FAILED.load(Relaxed) { return false; @@ -726,18 +1199,28 @@ 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(), + leases: LeasePool::default(), + smallest_failed: u32::MAX, }); } true } fn reserve_global_sampler(count: u32) -> Option { - let mut g = GLOBAL_SAMPLER.lock().unwrap(); + let mut g = GLOBAL_SAMPLER.write().unwrap(); let s = g.as_mut()?; + if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, &mut s.leases, |f| f.GetCompletedValue()) } { + s.smallest_failed = u32::MAX; + } + if count >= s.smallest_failed { + return None; + } let (cap, mut next) = (s.cap, s.next); let r = take_range(&mut s.free, &mut next, cap, count); s.next = next; if r.is_none() { + s.smallest_failed = s.smallest_failed.min(count); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0 { crate::xlog_warn!("console descriptor heaps: the shared sampler heap ({cap}) is full – overflowed sampler slots map to reserved slot 0"); @@ -746,12 +1229,20 @@ fn reserve_global_sampler(count: u32) -> Option { r } -fn sampler_page_of(h: &mut Heap, k: u32) -> Option<(u32, u32)> { +fn sampler_page_of(h: &Heap, k: u32) -> Option<(u32, u32)> { let p = (k / SAMPLER_PAGE_SLOTS) as usize; - let mut first = *h.pages.get(p)?; + let slot_atom = h.pages.get(p)?; + let mut first = slot_atom.load(Ordering::Acquire); if first == UNMAPPED { - first = reserve_global_sampler(sampler_page_descriptors(h.n, p as u32))?; - h.pages[p] = first; + let count = sampler_page_descriptors(h.n, p as u32); + let alloc = reserve_global_sampler(count)?; + match slot_atom.compare_exchange(UNMAPPED, alloc, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => first = alloc, + Err(existing) => { + release_global_sampler(alloc, count); + first = existing; + } + } } Some((first, p as u32 * SAMPLER_PAGE_SLOTS)) } @@ -760,19 +1251,36 @@ fn release_global_sampler(first: u32, count: u32) { if count == 0 { return; } - if let Some(s) = GLOBAL_SAMPLER.lock().unwrap().as_mut() { - merge_release(&mut s.free, first, count); + let dev = GLOBAL_SAMPLER.read().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.write().unwrap().as_mut() { + if marks.as_ref().is_some_and(Vec::is_empty) { + if s.leases.release_or_defer(&mut s.free, first, count) { + s.smallest_failed = u32::MAX; + } + } else { + s.retired.push_back(RetiredRange { first, count, marks }); + } + if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, &mut s.leases, |f| f.GetCompletedValue()) } { + s.smallest_failed = u32::MAX; + } } } /// The shared shader-visible PC sampler heap lists bind (None: no shared sampler heap). pub fn global_sampler_heap() -> Option { - GLOBAL_SAMPLER.lock().unwrap().as_ref().map(|s| s.heap.clone()) + GLOBAL_SAMPLER.read().unwrap().as_ref().map(|s| s.heap.clone()) +} + +/// Raw COM pointer of the shared shader-visible sampler heap without COM refcount traffic. +pub fn global_sampler_heap_raw() -> Option { + GLOBAL_SAMPLER.read().unwrap().as_ref().map(|s| s.heap.as_raw() as usize) } /// Whether `obj` (a title's sampler heap) has its descriptors in the shared sampler heap. pub fn in_global_sampler(obj: usize) -> bool { - HEAPS.lock().unwrap().iter().any(|h| h.obj == obj && h.sampler && !h.pages.is_empty()) + HEAPS.read().unwrap().iter().any(|h| h.obj == obj && h.sampler && !h.pages.is_empty()) } #[cfg(test)] @@ -854,7 +1362,7 @@ mod tests { unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 } unsafe extern "system" fn create_uav(_this: *mut c_void, _resource: *mut c_void, _counter: *mut c_void, _desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, _at: D3D12_CPU_DESCRIPTOR_HANDLE) { // The adopted device hook can re-enter descriptor bookkeeping. - UNLOCKED.fetch_and(GLOBAL.try_lock().is_ok(), Ordering::Relaxed); + UNLOCKED.fetch_and(GLOBAL.try_write().is_ok(), Ordering::Relaxed); CALLS.fetch_add(1, Ordering::Relaxed); } let mut vt = [0usize; 20]; @@ -866,28 +1374,31 @@ mod tests { let mut resource = Object { vt: vt.as_ptr() }; unsafe { let dev = ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void); - *GLOBAL.lock().unwrap() = Some(Global { + *GLOBAL.write().unwrap() = Some(Global { 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(), + next: crate::gpu::recomp::MEM_HEAP_NULL + 1, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX, }); let window = (&mut resource as *mut _ as usize, 0x10000); - assert!(set_window_views(&dev, &[window])); - assert_eq!(CALLS.swap(0, Ordering::Relaxed), crate::gpu::uma::MAX_WINDOWS as u32); + assert!(set_window_views_checked(&dev, &[window], true)); + assert_eq!(CALLS.swap(0, Ordering::Relaxed), crate::gpu::uma::MAX_WINDOWS as u32 + 1); let mut windows = [window; crate::gpu::uma::MAX_HEAP_WINDOWS]; - assert!(set_window_views(&dev, &windows)); - assert_eq!(CALLS.swap(0, Ordering::Relaxed), windows.len() as u32); + assert!(set_window_views_checked(&dev, &windows, true)); + assert_eq!(CALLS.swap(0, Ordering::Relaxed), windows.len() as u32 + 1); // Unused trailing window `(0, 0)` safely aliases window 0; an active window that failed // to open `(0, bytes > 0)` is rejected. windows[7] = (0, 0); - assert!(set_window_views(&dev, &windows)); - assert_eq!(CALLS.swap(0, Ordering::Relaxed), windows.len() as u32); + assert!(set_window_views_checked(&dev, &windows, true)); + assert_eq!(CALLS.swap(0, Ordering::Relaxed), windows.len() as u32 + 1); windows[7] = (0, 0x10000); - assert!(!set_window_views(&dev, &windows)); + assert!(!set_window_views_checked(&dev, &windows, true)); + assert_eq!(CALLS.load(Ordering::Relaxed), 0); + // Without 64-bit atomics on descriptor heap resources, heap window views are rejected. + assert!(!set_window_views_checked(&dev, &[window], false)); assert_eq!(CALLS.load(Ordering::Relaxed), 0); assert!(UNLOCKED.load(Ordering::Relaxed), "device callback ran while GLOBAL was locked"); - *GLOBAL.lock().unwrap() = None; + *GLOBAL.write().unwrap() = None; } } @@ -1059,10 +1570,10 @@ mod tests { let mut device = Object { vt: vt.as_ptr() }; let mut heap = Object { vt: vt.as_ptr() }; unsafe { - *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { + *GLOBAL_SAMPLER.write().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(), leases: LeasePool::default(), smallest_failed: u32::MAX, }); assert_eq!(reserve_global_sampler(4), Some(1)); assert_eq!(reserve_global_sampler(4), Some(5)); @@ -1073,24 +1584,25 @@ mod tests { release_global_sampler(5, 4); release_global_sampler(1, 4); release_global_sampler(1, 0); - assert_eq!(GLOBAL_SAMPLER.lock().unwrap().as_ref().unwrap().free, vec![(1, 8)]); + assert_eq!(GLOBAL_SAMPLER.read().unwrap().as_ref().unwrap().free, vec![(1, 8)]); assert_eq!(reserve_global_sampler(8), Some(1)); // Coalesced range ending at cursor straddles cleanly into the never-used tail. { - let mut g = GLOBAL_SAMPLER.lock().unwrap(); - let s = g.as_mut().unwrap(); + let mut s = GLOBAL_SAMPLER.write().unwrap(); + let s = s.as_mut().unwrap(); s.next = 13; s.free.clear(); + s.smallest_failed = u32::MAX; } release_global_sampler(9, 2); release_global_sampler(11, 2); assert_eq!(reserve_global_sampler(8), Some(9)); - let g = GLOBAL_SAMPLER.lock().unwrap(); + let g = GLOBAL_SAMPLER.read().unwrap(); let s = g.as_ref().unwrap(); assert_eq!(s.next, 17); assert!(s.free.is_empty()); drop(g); - *GLOBAL_SAMPLER.lock().unwrap() = None; + *GLOBAL_SAMPLER.write().unwrap() = None; } } @@ -1118,15 +1630,15 @@ mod tests { let mut sampler_heap = Object { vt: vt.as_ptr() }; unsafe { let dev = ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void); - *GLOBAL.lock().unwrap() = Some(Global { + *GLOBAL.write().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(), + cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX, }); - *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { + *GLOBAL_SAMPLER.write().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(), leases: LeasePool::default(), smallest_failed: u32::MAX, }); if crate::gpu::uma::get().is_some() { assert!(register(0xC100, 16, 0x9000, 0, 16, true, true, true)); @@ -1145,18 +1657,18 @@ mod tests { assert_eq!(slot(start(0xC111).unwrap()).unwrap().index, 5); unregister(0xC110); unregister(0xC111); - assert_eq!(GLOBAL_SAMPLER.lock().unwrap().as_ref().unwrap().free, vec![(1, 8)]); + assert_eq!(GLOBAL_SAMPLER.read().unwrap().as_ref().unwrap().free, vec![(1, 8)]); } else { - let mut heaps = HEAPS.lock().unwrap(); - heaps.push(Heap { obj: 0xC100, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 16, sampler: true, pages: vec![UNMAPPED; 2], visible: true, memory: Memory::Uma }); - heaps.push(Heap { obj: 0xC101, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); + let mut heaps = HEAPS.write().unwrap(); + heaps.push(Heap { obj: 0xC100, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 16, sampler: true, pages: vec![AtomicU32::new(UNMAPPED), AtomicU32::new(UNMAPPED)], visible: true, memory: Memory::Uma }); + heaps.push(Heap { obj: 0xC101, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 32, sampler: false, pages: vec![AtomicU32::new(UNMAPPED)], visible: true, memory: Memory::Uma }); drop(heaps); assert!(!in_global(0xC100) && in_global_sampler(0xC100)); assert!(in_global(0xC101) && !in_global_sampler(0xC101)); - HEAPS.lock().unwrap().clear(); + HEAPS.write().unwrap().clear(); } - *GLOBAL_SAMPLER.lock().unwrap() = None; - *GLOBAL.lock().unwrap() = None; + *GLOBAL_SAMPLER.write().unwrap() = None; + *GLOBAL.write().unwrap() = None; } } @@ -1176,4 +1688,294 @@ mod tests { assert_eq!(sampler_own_index(&[], 0), 0); assert_eq!(sampler_own_index(&[], 42), 42); } + + #[test] + fn exhausted_hosted_view_slots_map_to_null_slot_zero() { + // Hosted view heaps must never fall back to `2 * k`, which aliases `MEM_HEAP_BASE` window UAVs. + assert_eq!(view_unmapped_index(true, 0), 0); + assert_eq!(view_unmapped_index(true, crate::gpu::recomp::MEM_HEAP_BASE / 2), 0); + assert_eq!(view_unmapped_index(true, 42), 0); + // Unhosted heaps (no shared heap) keep their own local 2 * k layout. + assert_eq!(view_unmapped_index(false, 0), 0); + assert_eq!(view_unmapped_index(false, 42), 84); + } + + #[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(); + let mut leases = LeasePool::default(); + 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 }); + + // While f2 is still pending, neither range may re-enter `free`. + f1.store(1, Ordering::SeqCst); + drain_retired_ranges(&mut retired, &mut free, &mut leases, |f| f.load(Ordering::SeqCst)); + 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_retired_ranges(&mut retired, &mut free, &mut leases, |f| f.load(Ordering::SeqCst)); + 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_retired_ranges(&mut retired, &mut free, &mut leases, |f| f.load(Ordering::SeqCst)); + assert_eq!(free, vec![(64, 32)]); + assert_eq!(retired.len(), 1); + } + + #[test] + fn copy_words_range_copies_views_and_samplers_with_renumbering() { + let Some(u) = crate::gpu::uma::get() else { return }; + let rel = |p: u64| (p as usize - u.base()) as u32; + assert!(register(0xD100, 6, 0x1000, 0x5000, 32, false, false, true)); + assert!(register(0xD101, 4, 0x9000, 0, 16, true, false, true)); + let (v, sm) = (start(0xD100).unwrap(), start(0xD101).unwrap()); + // Slot 0 = 2D T#, Slot 1 = Buffer V#, Slot 2 = 2D T# + write(&slot(v).unwrap(), &[0, 0x1111_0000, 0, 9 << 28, 0, 0, 0, 0]); + write(&slot(v + SLOT as u64).unwrap(), &[0x5678, 0, 128, 0x3101_6FAC, 0, 0, 0, 0]); + write(&slot(v + 2 * SLOT as u64).unwrap(), &[4, 0x2222_0000, 0, 9 << 28, 0, 0, 0, 0]); + assert!(copy_words_range(v + 3 * SLOT as u64, v, 3)); + assert_eq!(words_at(rel(v + 3 * SLOT as u64)).unwrap()[..4], [6, 0x1111_0000, 0, 9 << 28]); + assert_eq!(words_at(rel(v + 4 * SLOT as u64)).unwrap()[..4], [0x5678, 0, 128, 0x3101_6FAC]); + assert_eq!(words_at(rel(v + 5 * SLOT as u64)).unwrap()[..4], [10, 0x2222_0000, 0, 9 << 28]); + // Samplers: copy slots 0..2 -> 2..4, renumbering word 3 [11:0] + write(&slot(sm).unwrap(), &[1, 2, 3, 0xABC0_0000]); + write(&slot(sm + SAMPLER_SLOT as u64).unwrap(), &[4, 5, 6, 0xDEF0_0001]); + assert!(copy_words_range(sm + 2 * SAMPLER_SLOT as u64, sm, 2)); + assert_eq!(words_at(rel(sm + 2 * SAMPLER_SLOT as u64)).unwrap()[..4], [1, 2, 3, 0xABC0_0002]); + assert_eq!(words_at(rel(sm + 3 * SAMPLER_SLOT as u64)).unwrap()[..4], [4, 5, 6, 0xDEF0_0003]); + unregister(0xD100); + unregister(0xD101); + } + + #[test] + fn publish_and_publish_range_do_not_hold_locks_during_device_calls() { + const CHILD: &str = "XCL_TEST_PUBLISH_LOCKS_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::publish_and_publish_range_do_not_hold_locks_during_device_calls", "--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; + use std::sync::atomic::{AtomicBool, Ordering}; + static UNLOCKED: AtomicBool = AtomicBool::new(true); + static CALLS: Mutex> = Mutex::new(Vec::new()); + #[repr(C)] + struct Object { vt: *const usize } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 } + unsafe extern "system" fn copy_simple(_this: *mut c_void, n: u32, dst: D3D12_CPU_DESCRIPTOR_HANDLE, src: D3D12_CPU_DESCRIPTOR_HANDLE, ty: D3D12_DESCRIPTOR_HEAP_TYPE) { + let ok = GLOBAL.try_write().is_ok() && GLOBAL_SAMPLER.try_write().is_ok() && HEAPS.try_write().is_ok(); + UNLOCKED.fetch_and(ok, Ordering::Relaxed); + CALLS.lock().unwrap().push((n, dst.ptr as u64, src.ptr as u64, ty.0)); + } + let mut vt = [0usize; 25]; + vt[1] = retain as usize; + vt[2] = retain as usize; + vt[24] = copy_simple as usize; + let (mut device, mut vheap, mut sheap) = (Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }); + let view_shadow = vec![0u8; (260 * SLOT) as usize]; + let samp_shadow = vec![0u8; (12 * SAMPLER_SLOT) as usize]; + unsafe { + let dev = ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void); + *GLOBAL.write().unwrap() = Some(Global { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut vheap as *mut _ as *mut c_void), cpu: 0x10_0000, gpu: 0x18_0000, inc: 32, cap: 4096, next: 64, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX }); + *GLOBAL_SAMPLER.write().unwrap() = Some(GlobalSampler { dev, heap: ID3D12DescriptorHeap::from_raw(&mut sheap as *mut _ as *mut c_void), cpu: 0x20_0000, inc: 16, cap: 256, next: 1, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX }); + { + let mut heaps = HEAPS.write().unwrap(); + heaps.push(Heap { obj: 0xA1, shadow: view_shadow.as_ptr() as usize, n: 260, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, pages: (0..2).map(|_| AtomicU32::new(UNMAPPED)).collect(), visible: true, memory: Memory::Uma }); + heaps.push(Heap { obj: 0xA2, shadow: samp_shadow.as_ptr() as usize, n: 12, pc_cpu: 0x40_0000, pc_gpu: 0, inc: 16, sampler: true, pages: (0..2).map(|_| AtomicU32::new(UNMAPPED)).collect(), visible: true, memory: Memory::Uma }); + heaps.sort_by_key(|h| h.shadow); + } + let vs = slot(view_shadow.as_ptr() as u64).unwrap(); + let ss = slot(samp_shadow.as_ptr() as u64).unwrap(); + publish(&vs, false); + publish(&vs, true); + publish(&ss, false); + let v250 = slot(view_shadow.as_ptr() as u64 + (250 * SLOT) as u64).unwrap(); + publish_range(&v250, 10); + let s6 = slot(samp_shadow.as_ptr() as u64 + (6 * SAMPLER_SLOT) as u64).unwrap(); + publish_range(&s6, 6); + HEAPS.write().unwrap().clear(); + *GLOBAL_SAMPLER.write().unwrap() = None; + *GLOBAL.write().unwrap() = None; + } + assert!(UNLOCKED.load(Ordering::Relaxed), "CopyDescriptorsSimple ran while GLOBAL, GLOBAL_SAMPLER, or HEAPS was locked"); + let calls = CALLS.lock().unwrap(); + assert_eq!(calls.len(), 7, "3 single publish + 2 view pages + 2 sampler pages"); + assert_eq!(calls[0], (1, 0x10_0000 + 64 * 32, 0x30_0000, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0)); + assert_eq!(calls[1], (1, 0x10_0000 + 65 * 32, 0x30_0000 + 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0)); + assert_eq!(calls[2], (1, 0x20_0000 + 16, 0x40_0000, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0)); + assert_eq!(calls[3], (12, 0x10_0000 + (64 + 500) * 32, 0x30_0000 + 500 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0)); + assert_eq!(calls[4], (8, 0x10_0000 + (64 + 512) * 32, 0x30_0000 + 512 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0)); + assert_eq!(calls[5], (2, 0x20_0000 + 7 * 16, 0x40_0000 + 6 * 16, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0)); + assert_eq!(calls[6], (4, 0x20_0000 + 9 * 16, 0x40_0000 + 8 * 16, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0)); + } + + #[test] + fn publish_range_clamps_to_heap_bounds_without_overrunning_tail_pages() { + const CHILD: &str = "XCL_TEST_PUBLISH_BOUNDS_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::publish_range_clamps_to_heap_bounds_without_overrunning_tail_pages", "--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; + static CALLS: Mutex> = Mutex::new(Vec::new()); + #[repr(C)] + struct Object { vt: *const usize } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 } + unsafe extern "system" fn copy_simple(_this: *mut c_void, n: u32, dst: D3D12_CPU_DESCRIPTOR_HANDLE, src: D3D12_CPU_DESCRIPTOR_HANDLE, ty: D3D12_DESCRIPTOR_HEAP_TYPE) { + CALLS.lock().unwrap().push((n, dst.ptr as u64, src.ptr as u64, ty.0)); + } + let mut vt = [0usize; 25]; + vt[1] = retain as usize; + vt[2] = retain as usize; + vt[24] = copy_simple as usize; + let (mut device, mut vheap, mut sheap) = (Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }); + let v4_shadow = vec![0u8; (4 * SLOT) as usize]; + let s3_shadow = vec![0u8; (3 * SAMPLER_SLOT) as usize]; + let v260_shadow = vec![0u8; (260 * SLOT) as usize]; + unsafe { + let dev = ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void); + *GLOBAL.write().unwrap() = Some(Global { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut vheap as *mut _ as *mut c_void), cpu: 0x10_0000, gpu: 0x18_0000, inc: 32, cap: 4096, next: 64, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX }); + *GLOBAL_SAMPLER.write().unwrap() = Some(GlobalSampler { dev, heap: ID3D12DescriptorHeap::from_raw(&mut sheap as *mut _ as *mut c_void), cpu: 0x20_0000, inc: 16, cap: 256, next: 1, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX }); + { + let mut heaps = HEAPS.write().unwrap(); + heaps.push(Heap { obj: 0xB1, shadow: v4_shadow.as_ptr() as usize, n: 4, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![AtomicU32::new(UNMAPPED)], visible: true, memory: Memory::Uma }); + heaps.push(Heap { obj: 0xB2, shadow: s3_shadow.as_ptr() as usize, n: 3, pc_cpu: 0x40_0000, pc_gpu: 0, inc: 16, sampler: true, pages: vec![AtomicU32::new(UNMAPPED)], visible: true, memory: Memory::Uma }); + heaps.push(Heap { obj: 0xB3, shadow: v260_shadow.as_ptr() as usize, n: 260, pc_cpu: 0x50_0000, pc_gpu: 0, inc: 32, sampler: false, pages: (0..2).map(|_| AtomicU32::new(UNMAPPED)).collect(), visible: true, memory: Memory::Uma }); + heaps.sort_by_key(|h| h.shadow); + } + let v4_s1 = slot(v4_shadow.as_ptr() as u64 + SLOT as u64).unwrap(); + publish_range(&v4_s1, 0); + publish_range(&v4_s1, 10); + let s3_s1 = slot(s3_shadow.as_ptr() as u64 + SAMPLER_SLOT as u64).unwrap(); + publish_range(&s3_s1, 10); + let v260_s250 = slot(v260_shadow.as_ptr() as u64 + (250 * SLOT) as u64).unwrap(); + publish_range(&v260_s250, 20); + HEAPS.write().unwrap().clear(); + *GLOBAL_SAMPLER.write().unwrap() = None; + *GLOBAL.write().unwrap() = None; + } + let calls = CALLS.lock().unwrap(); + assert_eq!( + *calls, + vec![ + // 4-slot view heap (allocated 64..72): k=1..4 => 6 descriptors (ending at 72, 0 overrun) + (6, 0x10_0000 + 66 * 32, 0x30_0000 + 2 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0), + // 3-slot sampler heap (allocated 1..4): k=1..3 => 2 descriptors (ending at 4, 0 overrun) + (2, 0x20_0000 + 2 * 16, 0x40_0000 + 16, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0), + // 260-slot view heap: page 0 (72..584) k=250..256 => 12 descs; tail page 1 (584..592) k=256..260 => 8 descs + (12, 0x10_0000 + (72 + 500) * 32, 0x50_0000 + 500 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0), + (8, 0x10_0000 + 584 * 32, 0x50_0000 + 512 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0), + ], + "publish_range must clamp strictly to heap bounds with 0 tail-page overrun" + ); + } + + #[test] + fn publish_leases_prevent_unregister_range_reuse_while_copy_in_flight() { + const CHILD: &str = "XCL_TEST_PUBLISH_LEASES_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::publish_leases_prevent_unregister_range_reuse_while_copy_in_flight", "--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; + use std::sync::{Arc, Barrier, OnceLock}; + static GATE: OnceLock<(Arc, Arc)> = OnceLock::new(); + static LOCKS_FREE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + #[repr(C)] + struct Object { vt: *const usize } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 } + unsafe extern "system" fn blocking_copy(_this: *mut c_void, _n: u32, _dst: D3D12_CPU_DESCRIPTOR_HANDLE, _src: D3D12_CPU_DESCRIPTOR_HANDLE, _ty: D3D12_DESCRIPTOR_HEAP_TYPE) { + let ok = GLOBAL.try_write().is_ok() && GLOBAL_SAMPLER.try_write().is_ok() && HEAPS.try_write().is_ok(); + LOCKS_FREE.fetch_and(ok, std::sync::atomic::Ordering::Relaxed); + let (entered, release) = GATE.get().unwrap(); + entered.wait(); + release.wait(); + } + let entered = Arc::new(Barrier::new(2)); + let release = Arc::new(Barrier::new(2)); + GATE.set((entered.clone(), release.clone())).ok(); + let mut vt = [0usize; 25]; + vt[1] = retain as usize; + vt[2] = retain as usize; + vt[24] = blocking_copy as usize; + let (mut device, mut vheap, mut sheap) = (Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }); + let v1_shadow = vec![0u8; (4 * SLOT) as usize]; + let v2_shadow = vec![0u8; (4 * SLOT) as usize]; + let s1_shadow = vec![0u8; (3 * SAMPLER_SLOT) as usize]; + unsafe { + let dev = ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void); + *GLOBAL.write().unwrap() = Some(Global { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut vheap as *mut _ as *mut c_void), cpu: 0x10_0000, gpu: 0x18_0000, inc: 32, cap: 4096, next: 64, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX }); + *GLOBAL_SAMPLER.write().unwrap() = Some(GlobalSampler { dev, heap: ID3D12DescriptorHeap::from_raw(&mut sheap as *mut _ as *mut c_void), cpu: 0x20_0000, inc: 16, cap: 256, next: 1, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX }); + { + let mut heaps = HEAPS.write().unwrap(); + heaps.push(Heap { obj: 0xD1, shadow: v1_shadow.as_ptr() as usize, n: 4, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![AtomicU32::new(UNMAPPED)], visible: true, memory: Memory::Uma }); + heaps.push(Heap { obj: 0xD2, shadow: v2_shadow.as_ptr() as usize, n: 4, pc_cpu: 0x31_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![AtomicU32::new(UNMAPPED)], visible: true, memory: Memory::Uma }); + heaps.push(Heap { obj: 0xD3, shadow: s1_shadow.as_ptr() as usize, n: 3, pc_cpu: 0x40_0000, pc_gpu: 0, inc: 16, sampler: true, pages: vec![AtomicU32::new(UNMAPPED)], visible: true, memory: Memory::Uma }); + heaps.sort_by_key(|h| h.shadow); + } + // 1. Single `publish` holds a lease until CopyDescriptorsSimple returns. + let vs1 = slot(v1_shadow.as_ptr() as u64).unwrap(); + assert_eq!(vs1.index, 64); + let t1 = std::thread::spawn(move || publish(&vs1, false)); + entered.wait(); + unregister(0xD1); + let new_v = reserve_global(8).unwrap(); + assert!(!ranges_overlap((new_v, 8), (64, 8)), "new heap reused leased publish range [64, 72): got {new_v}"); + release.wait(); + t1.join().unwrap(); + assert_eq!(reserve_global(8), Some(64), "deferred view range must return to free once publish completes"); + release_global(64, 8); + + // 2. `publish_range` (view) holds leases across unregister and releases them on completion. + let vs2 = slot(v2_shadow.as_ptr() as u64).unwrap(); + assert_eq!(vs2.index, 64); + let t2 = std::thread::spawn(move || publish_range(&vs2, 4)); + entered.wait(); + unregister(0xD2); + let new_v2 = reserve_global(8).unwrap(); + assert!(!ranges_overlap((new_v2, 8), (64, 8)), "new heap reused leased publish_range view range [64, 72): got {new_v2}"); + release.wait(); + t2.join().unwrap(); + assert_eq!(reserve_global(8), Some(64), "deferred publish_range view range must return to free on completion"); + + // 3. `publish_range` (sampler) holds leases across unregister and releases them on completion. + let ss1 = slot(s1_shadow.as_ptr() as u64).unwrap(); + assert_eq!(ss1.index, 1); + let t3 = std::thread::spawn(move || publish_range(&ss1, 3)); + entered.wait(); + unregister(0xD3); + let new_s = reserve_global_sampler(3).unwrap(); + assert!(!ranges_overlap((new_s, 3), (1, 3)), "new sampler heap reused leased range [1, 4): got {new_s}"); + release.wait(); + t3.join().unwrap(); + assert_eq!(reserve_global_sampler(3), Some(1), "deferred sampler range must return to free on completion"); + + HEAPS.write().unwrap().clear(); + *GLOBAL_SAMPLER.write().unwrap() = None; + *GLOBAL.write().unwrap() = None; + } + assert!(LOCKS_FREE.load(std::sync::atomic::Ordering::Relaxed), "CopyDescriptorsSimple must still run with all locks released"); + } } diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 7726419583..ebca17dc6e 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -74,15 +74,25 @@ pub struct Layout { pub size: u32, pub inline: u32, pub inline_gfx: u32, + /// the shaders index the view heap / the sampler heap themselves (the root signature's + /// CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED / SAMPLER_HEAP_DIRECTLY_INDEXED): they take the 32-bit + /// address of each from a user SGPR after the arguments, the view heap's first + pub heaps: [bool; 2], + pub inline_ms: u32, } +const CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED: u32 = 0x400; +const SAMPLER_HEAP_DIRECTLY_INDEXED: u32 = 0x800; + /// 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 /// fetch shader) – both measured on its output (`tests/console_shaders.rs`). const INLINE_SGPRS: u32 = 12; const INLINE_SGPRS_GFX: u32 = 24; +const INLINE_SGPRS_MS: u32 = 16; const FIRST_SGPR: usize = 4; const FIRST_SGPR_GFX: usize = 8; +const FIRST_SGPR_MS: usize = 16; /// Most bytes of root arguments a layout has. The PC's limit is 64 DWORDs (256 bytes: a /// constant or a table 1, a root descriptor 2, D3D12 "Root Signature Limits"); the console's /// is not known, so 16 times that. A malformed blob (a count of 0x3FFF_FFFF constants) gets no @@ -100,11 +110,12 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { }; let r = |o: usize| rts0.get(o..o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); let (n, poff) = (r(4)? as usize, r(8)? as usize); - let mut l = Layout::default(); + let flags = r(20).unwrap_or(0); + 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) = (false, false); + let (mut spilled, mut spilled_gfx, mut spilled_ms) = (false, false, false); for k in 0..n { let (ty, pay) = (r(poff + 12 * k)?, r(poff + 12 * k + 8)? as usize); let p = match ty { @@ -127,6 +138,10 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { if !spilled_gfx { l.inline_gfx += bytes; } + spilled_ms |= l.inline_ms + bytes > 4 * INLINE_SGPRS_MS; + if !spilled_ms { + l.inline_ms += bytes; + } l.size = size; l.params.push(p); } @@ -170,6 +185,32 @@ pub fn user_data_gfx(l: &Layout, args: &[u8], table_at: u64) -> Vec { sgprs(FIRST_SGPR_GFX, l.inline_gfx, args, table_at) } +/// `sgprs` (`user_data_for` / `user_data_gfx`) and the addresses of the view heap and the sampler +/// heap set that the shaders index (`Layout::heaps`). A compute shader without registers left +/// for them (`user_sgprs`: its count) gets none. +pub fn with_heaps(l: &Layout, user_sgprs: Option, mut sgprs: Vec, heaps: [u32; 2]) -> Vec { + for (_, base) in l.heaps.iter().zip(heaps).filter(|(&used, _)| used) { + if user_sgprs.is_some_and(|n| sgprs.len() as u32 >= n) { + break; + } + sgprs.push(base); + } + sgprs +} + +pub fn user_data_ms(l: &Layout, args: &[u8], table_at: u64) -> Vec { + let mut s = vec![0u32; FIRST_SGPR_MS]; + s[8] = table_at as u32; + s[9] = (table_at >> 32) as u32; + let inline = &args[..(l.inline_ms as usize).min(args.len())]; + s.extend(inline.chunks(4).map(|c| { + let mut w = [0u8; 4]; + w[..c.len()].copy_from_slice(c); + u32::from_le_bytes(w) + })); + s +} + fn sgprs(first: usize, inline: u32, args: &[u8], table_at: u64) -> Vec { let mut s = vec![0u32; first]; s[0] = table_at as u32; @@ -183,17 +224,27 @@ fn sgprs(first: usize, inline: u32, args: &[u8], table_at: u64) -> Vec { s } -static LAYOUTS: Mutex>>> = Mutex::new(None); +static LAYOUTS: std::sync::RwLock>>> = std::sync::RwLock::new(None); /// A root signature was created from `blob`: remember its argument layout. pub fn note_root_signature(rs: usize, blob: &[u8]) { if let Some(l) = layout_from_blob(blob) { - LAYOUTS.lock().unwrap().get_or_insert_with(HashMap::new).insert(rs, Arc::new(l)); + LAYOUTS.write().unwrap().get_or_insert_with(HashMap::new).insert(rs, Arc::new(l)); } } pub(super) fn layout_of(rs: usize) -> Option> { - LAYOUTS.lock().unwrap().as_ref()?.get(&rs).cloned() + LAYOUTS.read().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, + } } // --------------------------------------------------------------------------------------- @@ -331,6 +382,7 @@ pub fn allocator_reset(allocator: *mut c_void) { if let Some(b) = blocks { unsafe { free_uma(&b) }; } + super::bind::release_allocator_res(allocator as usize); } fn with_list(obj: usize, f: impl FnOnce(&mut ListState) -> R) -> Option { @@ -391,6 +443,7 @@ unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 { if left == 0 { if let Some(st) = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&obj)) { free_uma(&st.uma); + super::real::dispatch_chain::list_reset(st.pc); let release: unsafe extern "system" fn(usize) -> u32 = std::mem::transmute(pc_vtable_call(st.pc, 2)); release(st.pc); } @@ -412,7 +465,10 @@ list_forward!(cl_3 = 3, cl_4 = 4, cl_5 = 5, cl_6 = 6, cl_7 = 7, cl_8 = 8); unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { match close(this) { - Ok(_) => S_OK, + Ok(_) => { + super::title_textures::note_list_closed(this); + S_OK + } Err(e) => { crate::xlog_error!("console list: Close – {e}"); crate::util::E_FAIL @@ -435,7 +491,11 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, ps } with_list(obj, |st| new_chunk(obj, st)); let f: unsafe extern "system" fn(usize, *mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(pc_vtable_call(pc, 10)); - f(pc, allocator, pc_pso(pso)) + let hr = f(pc, allocator, pc_pso(pso)); + if hr >= 0 { + super::real::dispatch_chain::list_reset(pc); + } + hr } unsafe extern "system" fn cl_dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { @@ -536,7 +596,7 @@ unsafe extern "system" fn cl_allocate_upload_memory(this: *mut c_void, size: usi let Some(u) = crate::gpu::uma::get() else { return std::ptr::null_mut() }; let size = size.max(16); let align = align.max(16); - if size <= crate::gpu::uma::ARENA_BLOCK / 2 { + if size <= crate::gpu::uma::UPLOAD_IN_ARENA_MOST { if let Some(p) = with_list(this as usize, |st| st.arena.take(u, size, align, &mut st.uma)).flatten() { return p; } @@ -722,7 +782,7 @@ unsafe fn ensure_dispatch_heaps(list: &ID3D12GraphicsCommandList, bound: &mut Ve if let Some(d) = &dev { super::console_heap::shared_sampler_heap(d); } super::console_heap::global_sampler_heap() }); - let view = crate::gpu::recomp::pso::heap_windows().then(super::console_heap::global_heap).flatten(); + let view = super::console_heap::global_heap(); let (view, sampler) = match dev.as_ref().map(|d| d.as_raw() as usize) { Some(dev_raw) => (heap_on_device(view, dev_raw), heap_on_device(sampler, dev_raw)), None => (view, sampler), @@ -730,6 +790,46 @@ unsafe fn ensure_dispatch_heaps(list: &ID3D12GraphicsCommandList, bound: &mut Ve ensure_dispatch_heaps_with(list, bound, has_sampler, view, sampler); } +/// Choose the GPU descriptor handle for `ClearUnorderedAccessView*` on a console command list. +/// When both slots are hosted in the shared `GLOBAL` heap, an inline RAM `memcpy` +/// (`CopyDescriptorsSimple`) copies the console descriptor words without initializing `g`'s PC +/// UAV slot, so the live PC UAV lives at `c.pc_gpu_uav` (#2461). +fn clear_uav_gpu_handle(g: &super::console_heap::Slot, c: &super::console_heap::Slot) -> u64 { + if c.shared_srv != 0 && g.shared_srv != 0 && c.pc_gpu_uav != 0 { + c.pc_gpu_uav + } else { + g.pc_gpu_uav + } +} + +unsafe fn ensure_uav_clear_heap(list: &ID3D12GraphicsCommandList, bound: &mut Vec, has_sampler: &mut bool) { + let mut dev: Option = None; + let _ = list.GetDevice(&mut dev); + let view = super::console_heap::global_heap(); + let view = match dev.as_ref().map(|d| d.as_raw() as usize) { + Some(dev_raw) => heap_on_device(view, dev_raw), + None => view, + }; + let Some(view) = view else { return }; + if bound.iter().any(|h| h.as_raw() == view.as_raw()) { + return; + } + let sampler = (*has_sampler) + .then(|| bound.iter().find(|h| h.GetDesc().Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER).cloned()) + .flatten(); + let mut next = Vec::with_capacity(2); + next.push(view); + if let Some(s) = sampler { + next.push(s); + *has_sampler = true; + } else { + *has_sampler = false; + } + let args: Vec> = next.iter().cloned().map(Some).collect(); + list.SetDescriptorHeaps(&args); + *bound = next; +} + /// Turn the recorded console commands into commands on the PC list and close it. pub unsafe fn close(obj: *mut c_void) -> Result { let obj = obj as usize; @@ -770,8 +870,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; @@ -815,7 +918,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let q = |k: usize| get(1 + 2 * k) as u64 | (get(2 + 2 * k) as u64) << 32; let (dst, src) = (q(0) as *mut c_void, q(2) as *mut c_void); if let (Some(d), Some(s)) = (ID3D12Resource::from_raw_borrowed(&dst), ID3D12Resource::from_raw_borrowed(&src)) { - list.CopyBufferRegion(d, q(1), s, q(3), q(4)); + let dst_off = q(1).saturating_add(super::real::buffer_delta(dst as usize)); + let src_off = q(3).saturating_add(super::real::buffer_delta(src as usize)); + list.CopyBufferRegion(d, dst_off, s, src_off, q(4)); out.copies += 1; } else { out.skipped += 1; @@ -826,16 +931,29 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let values = [get(8), get(9), get(10), get(11)]; let res = q(2) as *mut c_void; let (gpu, cpu) = (super::console_heap::slot(q(0)), super::console_heap::slot(q(1))); - match (gpu, cpu, ID3D12Resource::from_raw_borrowed(&res)) { - (Some(g), Some(c), Some(r)) if g.pc_gpu_uav != 0 => { - let (gh, ch) = (D3D12_GPU_DESCRIPTOR_HANDLE { ptr: g.pc_gpu_uav }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: c.pc_uav as usize }); - if get(1) != 0 { - let f = values.map(f32::from_bits); - list.ClearUnorderedAccessViewFloat(gh, ch, r, &f, &[]); + match (gpu, cpu) { + (Some(g), Some(c)) if clear_uav_gpu_handle(&g, &c) != 0 => { + if super::real::is_unaligned_delta_uav(c.pc_uav as usize) { + out.skipped += 1; } else { - list.ClearUnorderedAccessViewUint(gh, ch, r, &values, &[]); + let pc_res = super::depth_uav::twin_for_pc_uav(c.pc_uav as usize).map_or(res, |t| t as *mut c_void); + if let Some(r) = ID3D12Resource::from_raw_borrowed(&pc_res) { + let gpu_uav = clear_uav_gpu_handle(&g, &c); + if g.shared_srv != 0 || (c.shared_srv != 0 && gpu_uav == c.pc_gpu_uav) { + ensure_uav_clear_heap(&list, &mut bound_heaps, &mut has_sampler_heap); + } + let (gh, ch) = (D3D12_GPU_DESCRIPTOR_HANDLE { ptr: gpu_uav }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: c.pc_uav as usize }); + if get(1) != 0 { + let f = values.map(f32::from_bits); + list.ClearUnorderedAccessViewFloat(gh, ch, r, &f, &[]); + } else { + list.ClearUnorderedAccessViewUint(gh, ch, r, &values, &[]); + } + out.clears += 1; + } else { + out.skipped += 1; + } } - out.clears += 1; } _ => out.skipped += 1, } @@ -895,24 +1013,32 @@ pub unsafe fn close(obj: *mut c_void) -> Result { }; io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; + // more groups in X than D3D12 takes: folded (`recomp::IO_GROUP_LIMIT`) + let (limit, [x, y, z]) = super::bind::fold(x, y, z); + io[crate::gpu::recomp::IO_GROUP_LIMIT] = limit; let io_at = uma_copy(st, bytemuck_u32(&io)).ok_or("UMA: io")?; let res_at = uma_copy(st, &[0u8; 256]).ok_or("UMA: res")?; + // Bind descriptor heaps before the root signature so SetDescriptorHeaps + // never invalidates root signature state (D3D12 #1419 / #2461). + ensure_dispatch_heaps(&list, &mut bound_heaps, &mut has_sampler_heap); // the pipeline's own root signature when it has static samplers let own = super::real::pso_root_signature(real).or(((*p).rs != 0).then_some((*p).rs)).map(|r| r as *mut c_void); match own.as_ref().and_then(|r| ID3D12RootSignature::from_raw_borrowed(r)) { Some(r) => list.SetComputeRootSignature(r), None => list.SetComputeRootSignature(rs.as_ref().ok_or("no XCL ABI root signature")?), } - ensure_dispatch_heaps(&list, &mut bound_heaps, &mut has_sampler_heap); list.SetComputeRootUnorderedAccessView(0, va(io_at)); list.SetComputeRootUnorderedAccessView(1, va(res_at)); for k in 0..4 { - list.SetComputeRootUnorderedAccessView(2 + k as u32, windows.get(k).copied().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; let pc = ID3D12PipelineState::from_raw_borrowed(&raw).ok_or("PSO")?; list.SetPipelineState(pc); - super::real::dispatch_chain::dispatch(&list, real, st.allocator, [x, y, z])?; + let mark = super::culprit::before_dispatch(&list, (*p).pc, real, [x, y, z]); + let r = super::real::dispatch_chain::dispatch(&list, real, st.allocator, [x, y, z]); + super::culprit::after_dispatch(&list, mark); + r?; out.dispatches += 1; } _ => out.skipped_dispatches += 1, @@ -1031,6 +1157,36 @@ mod tests { r.iter().flat_map(|w| w.to_le_bytes()).collect() } + /// Shaders that index the heaps set themselves get the heaps' addresses after their + /// arguments, the view heap's first; a compute shader without registers for them does not. + #[test] + fn heap_addresses_follow_the_arguments() { + let layout = |flags: u32, p: &[(u32, u32)]| { + let mut blob = rts0(p); + blob[20..24].copy_from_slice(&flags.to_le_bytes()); + layout_from_blob(&blob).unwrap() + }; + let heaps = [0x6000_0000, 0x6381_0000]; + // a table and two constants + let args: Vec = [0x80u32, 5, 0].iter().flat_map(|w| w.to_le_bytes()).collect(); + let gfx = |flags: u32| { + let l = layout(flags, &[(0, 0), (1, 2)]); + with_heaps(&l, None, user_data_gfx(&l, &args, 0x200), heaps)[8..].to_vec() + }; + assert_eq!(gfx(1), [0x80, 5, 0]); + assert_eq!(gfx(0x801), [0x80, 5, 0, 0x6381_0000]); + assert_eq!(gfx(0x401), [0x80, 5, 0, 0x6000_0000]); + assert_eq!(gfx(0xC01), [0x80, 5, 0, 0x6000_0000, 0x6381_0000]); + let cs = |flags: u32, user: u32| { + let l = layout(flags, &[(0, 0), (1, 2)]); + with_heaps(&l, Some(user), user_data_for(&l, Some(user), &args, 0x200), heaps)[4..].to_vec() + }; + assert_eq!(cs(0xC00, 9), [0x80, 5, 0, 0x6000_0000, 0x6381_0000]); + assert_eq!(cs(0xC00, 8), [0x80, 5, 0, 0x6000_0000]); + assert_eq!(cs(0xC00, 7), [0x80, 5, 0], "no register left"); + assert_eq!(cs(0, 9), [0x80, 5, 0]); + } + /// A blob whose constant count makes the arguments overflow u32 (0x4000_0000) or take /// gigabytes (0x3FFF_FFFF: 0xFFFF_FFFC bytes, allocated at every Set*RootSignature) has no /// layout; the largest one allowed still has one. @@ -1075,6 +1231,21 @@ mod tests { assert_eq!(user_data_gfx(&l, &args, 0x200), vec![0x200, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0x5000, 4, 0x80]); } + #[test] + fn mesh_arguments_go_in_user_sgprs_from_s16() { + let inline = |p: &[(u32, u32)]| layout_from_blob(&rts0(p)).unwrap().inline_ms; + assert_eq!(inline(&[(1, 2), (2, 0), (0, 0)]), 20); + assert_eq!(inline(&[(1, 14), (2, 0)]), 64); + assert_eq!(inline(&[(1, 15), (2, 0)]), 60); + assert_eq!(inline(&[(1, 17), (2, 0)]), 0); + let l = layout_from_blob(&rts0(&[(1, 2), (2, 0), (0, 0)])).unwrap(); + let args: Vec = [1u32, 2, 0x5000, 4, 0x80].iter().flat_map(|w| w.to_le_bytes()).collect(); + let got = user_data_ms(&l, &args, 0x7_0000_0200); + assert_eq!(got[8], 0x200); + assert_eq!(got[9], 7); + assert_eq!(&got[16..], &[1, 2, 0x5000, 4, 0x80]); + } + #[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. @@ -1140,4 +1311,50 @@ mod tests { list.Close().unwrap(); } } + + #[test] + fn clear_uav_prefers_cpu_slot_shared_gpu_handle_for_inline_copies() { + let slot = |shared_srv, pc_gpu_uav| super::super::console_heap::Slot { + at: 0, + k: 0, + index: 0, + pc_srv: 0, + pc_uav: 0x100, + pc_gpu_uav, + shared_srv, + sampler: false, + }; + // Both hosted in GLOBAL (inline CopyDescriptorsSimple): use CPU slot's initialized GPU handle. + assert_eq!(clear_uav_gpu_handle(&slot(0x2000, 0x3000), &slot(0x1000, 0x4000)), 0x4000); + // Unhosted shader-visible heap (no shared_srv): keep g.pc_gpu_uav. + assert_eq!(clear_uav_gpu_handle(&slot(0, 0x3000), &slot(0x1000, 0x4000)), 0x3000); + // CPU slot not in GLOBAL: keep g.pc_gpu_uav. + assert_eq!(clear_uav_gpu_handle(&slot(0x2000, 0x3000), &slot(0, 0)), 0x3000); + } + + #[test] + fn cl_reset_and_cl_release_clear_dispatch_chain_shared_scratch() { + unsafe extern "system" fn fake_release(_this: usize) -> u32 { 0 } + unsafe extern "system" fn fake_reset(_this: usize, _alloc: *mut c_void, _pso: *mut c_void) -> HRESULT { S_OK } + let mut vt = [0usize; 16]; + vt[2] = fake_release as usize; + vt[10] = fake_reset as usize; + #[repr(C)] + struct FakePc { vt: *const usize } + let pc_obj = Box::new(FakePc { vt: vt.as_ptr() }); + let pc_ptr = &*pc_obj as *const FakePc as *mut c_void; + let pc_key = pc_ptr as usize; + let alloc = 0x7E57_C110usize as *mut c_void; + unsafe { + let cl = create_with_allocator(pc_ptr, alloc); + super::super::real::dispatch_chain::seed_shared_for_test(pc_key, alloc as usize); + assert!(super::super::real::dispatch_chain::has_shared_for_test(pc_key)); + assert_eq!(cl_reset(cl, alloc, std::ptr::null_mut()), S_OK); + assert!(!super::super::real::dispatch_chain::has_shared_for_test(pc_key), "cl_reset must clear dispatch_chain SHARED"); + + super::super::real::dispatch_chain::seed_shared_for_test(pc_key, alloc as usize); + assert_eq!(cl_release(cl), 0); + assert!(!super::super::real::dispatch_chain::has_shared_for_test(pc_key), "cl_release must clear dispatch_chain SHARED"); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 0b20bfbd6a..b245384115 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -10,14 +10,160 @@ use std::collections::HashMap; use std::ffi::c_void; -use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; -use std::sync::{mpsc, Mutex, OnceLock}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; +use std::sync::{mpsc, Arc, Mutex, OnceLock}; use windows::core::Interface; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_FORMAT_R16G16_UINT, DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R32_FLOAT}; use windows_sys::Win32::System::Threading as th; +use crate::hle::xg; + +/// `XCL_WATER_READBACK=0`: disable GPU->UMA readback of placed ocean height/displacement/buoyancy +/// textures (`256×256` `R32_FLOAT`/`R32G32_FLOAT`, `64×64` `R32G32_FLOAT`, `128×128` `R16G16_UINT`). +pub(super) fn water_readback_enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WATER_READBACK").map_or(true, |v| v.trim() != "0")) +} + +/// Whether `desc` matches one of the 4 verified single-mip 2D ocean height/displacement/buoyancy +/// readback textures used by CPU water/boat physics: +/// - `256×256` `R32_FLOAT` (`41`) or `R32G32_FLOAT` (`16`) +/// - `64×64` `R32G32_FLOAT` (`16`) +/// - `128×128` `R16G16_UINT` (`36`) +pub(super) fn is_water_readback_desc(desc: &D3D12_RESOURCE_DESC) -> bool { + desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && desc.DepthOrArraySize == 1 + && desc.MipLevels == 1 + && desc.SampleDesc.Count <= 1 + && matches!( + (desc.Width, desc.Height, desc.Format), + (256, 256, DXGI_FORMAT_R32_FLOAT | DXGI_FORMAT_R32G32_FLOAT) + | (64, 64, DXGI_FORMAT_R32G32_FLOAT) + | (128, 128, DXGI_FORMAT_R16G16_UINT) + ) +} + +#[derive(Clone)] +pub(super) struct WaterTarget { + pub va: usize, + pub format: DXGI_FORMAT, + pub width: u32, + pub height: u32, + pub row_pitch: u32, + pub tex: Arc, +} + +static WATER_TARGETS: Mutex>> = Mutex::new(None); +static HAS_WATER_TARGETS: AtomicBool = AtomicBool::new(false); + +pub(super) fn has_water_readback() -> bool { + HAS_WATER_TARGETS.load(Ordering::Acquire) +} + +pub(super) fn register_water_readback(res: usize, va: usize, format: DXGI_FORMAT, width: u32, height: u32, tex: Arc) { + if !water_readback_enabled() || res == 0 || va == 0 { + return; + } + let bpe: u32 = match format { + DXGI_FORMAT_R32_FLOAT | DXGI_FORMAT_R16G16_UINT => 4, + DXGI_FORMAT_R32G32_FLOAT => 8, + _ => return, + }; + let Some(row_bytes) = width.checked_mul(bpe) else { return }; + // Align to D3D12_TEXTURE_DATA_PITCH_ALIGNMENT (256 B); all 4 verified formats are exact multiples. + let row_pitch = row_bytes.next_multiple_of(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT); + WATER_TARGETS.lock().unwrap().get_or_insert_with(HashMap::new).insert( + res, + WaterTarget { va, format, width, height, row_pitch, tex }, + ); + HAS_WATER_TARGETS.store(true, Ordering::Release); +} + +pub(super) fn unregister_water_readback(res: usize) { + if !HAS_WATER_TARGETS.load(Ordering::Acquire) { + return; + } + let mut g = WATER_TARGETS.lock().unwrap(); + if let Some(m) = g.as_mut() { + m.remove(&res); + if m.is_empty() { + HAS_WATER_TARGETS.store(false, Ordering::Release); + } + } +} + +pub(super) fn water_readback_target(res: usize) -> Option { + if !water_readback_enabled() || !HAS_WATER_TARGETS.load(Ordering::Acquire) { + return None; + } + WATER_TARGETS.lock().unwrap().as_ref()?.get(&res).cloned() +} + +/// Pooled persistently-mapped `READBACK` buffer returned to `FREE_WATER_RB` on drop once +/// `xcl-cpu-writes` finishes swizzling the heightmap into console memory. +pub(super) struct WaterReadbackBuf { + pub buf: Option, + pub mapped: usize, + pub bytes: u64, + pub dev_key: usize, +} + +unsafe impl Send for WaterReadbackBuf {} +unsafe impl Sync for WaterReadbackBuf {} + +const MAX_POOLED_WATER_RB: usize = 16; +static FREE_WATER_RB: Mutex> = Mutex::new(Vec::new()); + +impl Drop for WaterReadbackBuf { + fn drop(&mut self) { + let Some(buf) = self.buf.take() else { return }; + let mapped = std::mem::replace(&mut self.mapped, 0); + let mut free = FREE_WATER_RB.lock().unwrap(); + if free.len() < MAX_POOLED_WATER_RB && mapped != 0 { + free.push((buf, mapped, self.bytes, self.dev_key)); + } else if mapped != 0 { + unsafe { buf.Unmap(0, None) }; + } + } +} + +/// Acquire a persistently-mapped `READBACK` buffer of at least `bytes` bytes for `dev`. +pub(super) unsafe fn take_water_readback_buf(dev: &ID3D12Device, bytes: u64) -> Option> { + let dev_key = dev.as_raw() as usize; + { + let mut free = FREE_WATER_RB.lock().unwrap(); + if let Some(i) = free.iter().position(|(_, _, cap, d)| *d == dev_key && *cap >= bytes) { + let (buf, mapped, cap, d) = free.swap_remove(i); + return Some(Arc::new(WaterReadbackBuf { buf: Some(buf), mapped, bytes: cap, dev_key: d })); + } + } + let hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 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, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let mut rb: Option = None; + dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).ok()?; + let rb = rb?; + let _ = rb.SetName(windows::core::w!("xcl water heightmap readback")); + let mut mapped = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut mapped)).ok()?; + if mapped.is_null() { + return None; + } + Some(Arc::new(WaterReadbackBuf { buf: Some(rb), mapped: mapped as usize, bytes, dev_key })) +} + /// A bottom-of-pipe write into memory outside unified memory, applied by the CPU once the /// queue's fence reaches the submission that recorded it. #[derive(Clone)] @@ -28,6 +174,10 @@ pub(super) enum Write { /// (`src`), copied atomically to `va` once the queue's fence completes. Holding `_buf` keeps /// the mapping alive until the worker finishes. ReadbackU64 { va: usize, src: usize, _buf: ID3D12Resource }, + /// A 256×256 `R32_FLOAT` / `R32G32_FLOAT` ocean height/displacement texture read back from + /// VRAM into a persistently mapped READBACK buffer, tiled back into console memory `dst_va` + /// with `tex.chain.tile_level` once the queue's fence completes. + ReadbackTexture { dst_va: usize, format: DXGI_FORMAT, row_pitch: u32, tex: Arc, buf: Arc }, } struct Job { @@ -77,6 +227,9 @@ fn worker() -> &'static Mutex> { let value = (*(*src as *const AtomicU64)).load(Ordering::Acquire); write_u64_now(*va, value); } + Write::ReadbackTexture { dst_va, format, row_pitch, tex, buf } => { + write_texture_now(*dst_va, *format, *row_pitch, tex, buf); + } } } } @@ -141,12 +294,105 @@ pub(super) unsafe fn max_u64_now(va: usize, value: u64) { } } +/// Whether the entire byte span `[va, va + bytes)` is committed, writable, and without `PAGE_GUARD`. +unsafe fn range_writable_now(va: usize, bytes: usize) -> bool { + if va == 0 || bytes == 0 { + return false; + } + let Some(end) = va.checked_add(bytes) else { return false }; + if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { + return true; + } + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_GUARD, PAGE_READWRITE}; + let mut cur = va; + while cur < end { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(cur as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT { + return false; + } + if m.Protect & PAGE_GUARD != 0 || m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 { + return false; + } + let region_end = (m.BaseAddress as usize).saturating_add(m.RegionSize); + if region_end <= cur { + return false; + } + cur = region_end; + } + true +} + +fn main_surface(tex: &xg::Texture) -> Option<(usize, &xg::Surface)> { + let plane = tex.planes.get(tex.main)?; + let xg::PlaneKind::Surface(ref s) = plane.kind else { return None }; + Some((plane.offset as usize, s)) +} + +/// Swizzle `linear` rows (`row_pitch` bytes per row, 256 rows) into Xbox console tiled layout +/// inside `dst` using the main plane's `Surface::chain.tile_level`. +fn tile_readback_into_slice(dst: &mut [u8], linear: &[u8], row_pitch: u32, tex: &xg::Texture) -> bool { + let Some((_, surface)) = main_surface(tex) else { return false }; + let Some(l0) = surface.chain.levels.first() else { return false }; + let bpe = surface.bpe as usize; + let packed_row = l0.width.saturating_mul(bpe); + let pitch = row_pitch as usize; + let slice_bytes = surface.chain.slice_bytes; + if packed_row == 0 || pitch < packed_row || slice_bytes == 0 || dst.len() < slice_bytes { + return false; + } + let Some(src_need) = pitch.checked_mul(l0.height) else { return false }; + if linear.len() < src_need { + return false; + } + if pitch == packed_row { + surface.chain.tile_level(&mut dst[..slice_bytes], 0, 0, &linear[..src_need]); + } else { + let mut packed = Vec::with_capacity(packed_row * l0.height); + for row in 0..l0.height { + let start = row * pitch; + packed.extend_from_slice(&linear[start..start + packed_row]); + } + surface.chain.tile_level(&mut dst[..slice_bytes], 0, 0, &packed); + } + true +} + +/// Write a completed GPU readback of a 256×256 ocean height/displacement texture back into +/// console memory in its Xbox XOR-swizzled layout. +unsafe fn write_texture_now(dst_va: usize, format: DXGI_FORMAT, row_pitch: u32, tex: &xg::Texture, buf: &WaterReadbackBuf) { + if buf.mapped == 0 { + return; + } + let Some((plane_off, surface)) = main_surface(tex) else { return }; + let Some(target_va) = super::title_textures::mirror_source(dst_va).checked_add(plane_off) else { return }; + let dst_bytes = surface.chain.slice_bytes; + if dst_bytes == 0 { + return; + } + let _open = crate::hle::kernelx::lazy::ensure(target_va, dst_bytes); + if !range_writable_now(target_va, dst_bytes) { + return; + } + let linear = std::slice::from_raw_parts(buf.mapped as *const u8, buf.bytes as usize); + let dst = std::slice::from_raw_parts_mut(target_va as *mut u8, dst_bytes); + if tile_readback_into_slice(dst, linear, row_pitch, tex) { + std::sync::atomic::fence(Ordering::Release); + static COUNT: AtomicU64 = AtomicU64::new(0); + let n = COUNT.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || (n.is_power_of_two() && n >= 64) { + let (w, h) = surface.chain.levels.first().map_or((0, 0), |l| (l.width, l.height)); + crate::xlog_info!("D3D12.X: water heightmap readback #{n} ({w}x{h} fmt {}, -> {target_va:#x}, {dst_bytes} B)", format.0); + } + } +} + /// Whether `[va, va + bytes)` is memory the CPU can write for the GPU later. 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); + // (held while the protection is asked: a view of a physical page is not guarded again meanwhile) + let _open = 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; @@ -271,4 +517,56 @@ mod tests { assert_eq!(*dst, expected); } } + + #[test] + fn water_readback_desc_matches_verified_water_textures_only() { + let base = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32_FLOAT, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + assert!(is_water_readback_desc(&base)); + assert!(is_water_readback_desc(&D3D12_RESOURCE_DESC { Format: DXGI_FORMAT_R32G32_FLOAT, ..base })); + assert!(is_water_readback_desc(&D3D12_RESOURCE_DESC { Width: 64, Height: 64, Format: DXGI_FORMAT_R32G32_FLOAT, ..base })); + assert!(is_water_readback_desc(&D3D12_RESOURCE_DESC { Width: 128, Height: 128, Format: DXGI_FORMAT_R16G16_UINT, ..base })); + assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { Width: 64, Height: 64, Format: DXGI_FORMAT_R32_FLOAT, ..base })); + assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { Width: 256, Height: 256, Format: DXGI_FORMAT_R16G16_UINT, ..base })); + assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, ..base })); + assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { Width: 512, ..base })); + assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { MipLevels: 2, ..base })); + assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { DepthOrArraySize: 2, ..base })); + assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, ..base })); + } + + #[test] + fn tile_readback_roundtrips_all_verified_water_textures() { + for (dim, fmt, bpe) in [ + (256u32, DXGI_FORMAT_R32_FLOAT.0 as u32, 4usize), + (256u32, DXGI_FORMAT_R32G32_FLOAT.0 as u32, 8usize), + (64u32, DXGI_FORMAT_R32G32_FLOAT.0 as u32, 8usize), + (128u32, DXGI_FORMAT_R16G16_UINT.0 as u32, 4usize), + ] { + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&(D3D12_RESOURCE_DIMENSION_TEXTURE2D.0 as u32).to_le_bytes()); + x[0x10..0x18].copy_from_slice(&(dim as u64).to_le_bytes()); + x[0x18..0x1C].copy_from_slice(&dim.to_le_bytes()); + x[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + x[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + x[0x20..0x24].copy_from_slice(&fmt.to_le_bytes()); + x[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + x[0x2C..0x30].copy_from_slice(&0x11Bu32.to_le_bytes()); // console swizzle 64KB_R_X (0x100 | 27) + let tex = xg::Texture::new(&x).expect("console water texture layout"); + let (_, surface) = main_surface(&tex).expect("main color surface"); + let n = dim as usize; + let linear: Vec = (0..(n * n * bpe)).map(|i| ((i * 31 + 17) & 0xFF) as u8).collect(); + let mut tiled = vec![0u8; surface.chain.slice_bytes]; + assert!(tile_readback_into_slice(&mut tiled, &linear, (n * bpe) as u32, &tex)); + assert_eq!(surface.chain.detile_level(&tiled, 0, 0), linear); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/culprit.rs b/crates/xcl/src/hle/d3d12x/culprit.rs new file mode 100644 index 0000000000..a24cf9d8ad --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/culprit.rs @@ -0,0 +1,323 @@ +//! `XCL_GPU_CULPRIT=1` (diagnostics, off by default): which dispatches a stalled queue has not +//! finished. Around every dispatch XCL records (title lists, console-recorded lists, +//! ExecuteIndirect of a translated compute pipeline) the list writes a running number into a +//! readback buffer with `WriteBufferImmediate`: `MARKER_IN` before (the work before it has +//! started), `MARKER_OUT` after (the work before it is done), one pair of words per PC list. +//! When the GPU-wait watchdog releases a wait, a list whose last number in is above its last +//! number out has work that started and is not done: those dispatches are logged with their +//! console compute shader (`fnv64` of the title's CS bytecode, the name of its file in the +//! translated-shader cache) and their groups. +//! +//! DRED breadcrumbs would say the same on a device removal, but they change the driver's +//! pipeline cache keys: every pipeline is built again, and a retail title's start then takes +//! minutes. + +use std::collections::{HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Mutex, OnceLock}; +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +pub fn enabled() -> bool { + static E: OnceLock = OnceLock::new(); + *E.get_or_init(|| std::env::var("XCL_GPU_CULPRIT").is_ok_and(|v| v.trim() == "1")) +} + +/// Lists with a slot in the readback buffer (two words each). +const SLOTS: usize = 1 << 14; +/// Dispatches remembered by number (the oldest are forgotten). +const REMEMBERED: usize = 1 << 20; + +/// The console CS of the compute pipelines the title made, by the pointer it holds. +static CS: Mutex>> = Mutex::new(None); + +/// A compute pipeline the title made: its console CS, for the log. +pub unsafe fn note_compute(pso: usize, desc: *const c_void) { + if !enabled() || pso == 0 || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return; + } + let d = std::ptr::read(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC); + let (p, n) = (d.CS.pShaderBytecode as usize, d.CS.BytecodeLength); + if p == 0 || n == 0 || !crate::gpu::shader::readable(p, n) { + return; + } + let h = crate::gpu::shader::fnv64(std::slice::from_raw_parts(p as *const u8, n)); + CS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, h); +} + +/// The title's pipeline, or the one it stands for (a background build). +fn cs_of(title_pso: usize, pso: usize) -> u64 { + let g = CS.lock().unwrap(); + let Some(m) = g.as_ref() else { return 0 }; + [title_pso, pso, super::pso_async::resolve(title_pso)].iter().find_map(|p| m.get(p)).copied().unwrap_or(0) +} + +struct Markers { + _buf: ID3D12Resource, + gpu: u64, + cpu: *const u32, + /// PC list → its slot + slots: HashMap, + /// dispatch number → (list, what it was) + what: HashMap, + order: VecDeque, +} +// SAFETY: `cpu` is the persistent map of `_buf`, read only under the mutex +unsafe impl Send for Markers {} + +static MARKERS: Mutex> = Mutex::new(None); +static NEXT: AtomicU32 = AtomicU32::new(1); + +unsafe fn make_markers(dev: &ID3D12Device) -> Option { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: (SLOTS * 8) as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buf: Option = None; + if let Err(e) = dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut buf) { + crate::xlog_warn!("GPU culprit: no readback buffer for the dispatch markers: {e}"); + return None; + } + let buf = buf?; + let mut p: *mut c_void = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).ok()?; + crate::xlog_info!("GPU culprit: dispatch markers on ({SLOTS} list slots)"); + Some(Markers { gpu: buf.GetGPUVirtualAddress(), _buf: buf, cpu: p as *const u32, slots: HashMap::new(), what: HashMap::new(), order: VecDeque::new() }) +} + +/// Before a dispatch on `list`: a marker in with a new number, which the caller hands to +/// `after_dispatch` once the dispatch is recorded (0: no marker). `groups` `[0, 0, n]`: an +/// indirect one of at most `n` dispatches. +pub unsafe fn before_dispatch(list: &ID3D12GraphicsCommandList, title_pso: usize, pso: usize, groups: [u32; 3]) -> u32 { + if !enabled() { + return 0; + } + let Ok(l2) = list.cast::() else { return 0 }; + let mut g = MARKERS.lock().unwrap(); + if g.is_none() { + let mut dev: Option = None; + if list.GetDevice(&mut dev).is_err() { + return 0; + } + *g = make_markers(&dev.unwrap()); + } + let Some(m) = g.as_mut() else { return 0 }; + let key = list.as_raw() as usize; + let Some(slot) = slot_for(&mut m.slots, key, SLOTS) else { return 0 }; + let id = NEXT.fetch_add(1, Ordering::Relaxed); + let size = match groups { + [0, 0, n] => format!("indirect, up to {n} dispatches"), + [x, y, z] => format!("groups {x}x{y}x{z}"), + }; + m.what.insert(id, (key, format!("cs {:016x}, pipeline {pso:#x}, {size}", cs_of(title_pso, pso)))); + m.order.push_back(id); + if m.order.len() > REMEMBERED { + let old = m.order.pop_front().unwrap(); + m.what.remove(&old); + } + let p = D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: m.gpu + slot as u64 * 8, Value: id }; + l2.WriteBufferImmediate(1, &p, Some(&D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_IN)); + id +} + +/// Where in title memory the arguments of the indirect dispatches numbered so are (the newest +/// 65 536): a hung one is logged with the group counts there. +static ARGS: Mutex>> = Mutex::new(None); + +/// The indirect dispatch `id` (of `before_dispatch`) takes its group counts from `at` in title +/// memory. +pub fn indirect_args(id: u32, at: usize) { + if id == 0 { + return; + } + let mut g = ARGS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + if m.len() >= 1 << 16 { + m.clear(); + } + m.insert(id, at); +} + +/// ` ; its arguments in title memory now: x×y×z groups` for the dispatch `id`, when known. What +/// the GPU read can differ: these are the bytes the CPU sees (a count another dispatch wrote may +/// not be back yet). +fn args_now(id: u32) -> String { + let Some(at) = ARGS.lock().unwrap().as_ref().and_then(|m| m.get(&id).copied()) else { return String::new() }; + if !crate::gpu::shader::readable(at, 12) { + return format!("; its arguments at {at:#x} cannot be read"); + } + // SAFETY: 12 readable bytes, checked above + let [x, y, z] = unsafe { (at as *const [u32; 3]).read_unaligned() }; + format!("; its arguments in title memory ({at:#x}) now: {x}x{y}x{z} groups") +} + +/// After the dispatch: a marker out with its number. +pub unsafe fn after_dispatch(list: &ID3D12GraphicsCommandList, id: u32) { + if id == 0 { + return; + } + let Ok(l2) = list.cast::() else { return }; + let g = MARKERS.lock().unwrap(); + let Some(m) = g.as_ref() else { return }; + let Some(&slot) = m.slots.get(&(list.as_raw() as usize)) else { return }; + let p = D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: m.gpu + slot as u64 * 8 + 4, Value: id }; + l2.WriteBufferImmediate(1, &p, Some(&D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT)); +} + +/// The slot of `list`: its own, or the next free one; none once `cap` lists have one (the list is +/// then not recorded, so every recorded slot stays inside the readback buffer). +fn slot_for(slots: &mut HashMap, list: usize, cap: usize) -> Option { + if let Some(&s) = slots.get(&list) { + return Some(s); + } + let n = slots.len(); + (n < cap).then(|| { + slots.insert(list, n as u32); + n as u32 + }) +} + +/// The lists with work started and not done: (list, last number in, last number out), from +/// each slot's pair of words. A marker in only says that the work before it has started, so a +/// list counts when its number in is above its number out (in and out written out of order +/// otherwise look open). +fn open_lists(slots: &HashMap, words: impl Fn(u32) -> (u32, u32)) -> Vec<(usize, u32, u32)> { + let mut open: Vec<(usize, u32, u32)> = slots + .iter() + .filter_map(|(&list, &slot)| { + let (i, o) = words(slot); + (i > o).then_some((list, i, o)) + }) + .collect(); + open.sort_by_key(|&(_, i, _)| i); + open +} + +/// The dispatches of `list` numbered after `out` up to `in_` that are still remembered. +fn not_done(what: &HashMap, list: usize, in_: u32, out: u32) -> Vec<(u32, &str)> { + ((out + 1)..=in_).filter_map(|id| what.get(&id).filter(|(l, _)| *l == list).map(|(_, s)| (id, s.as_str()))).collect() +} + +/// The watchdog released GPU waits: log the dispatches started and not done (once per burst, +/// 4 s apart, at most 8 times). +pub fn on_watchdog_release() { + static BURSTS: AtomicU32 = AtomicU32::new(0); + static LAST: Mutex> = Mutex::new(None); + if !enabled() { + return; + } + { + let mut l = LAST.lock().unwrap(); + if l.is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(4)) { + return; + } + *l = Some(std::time::Instant::now()); + } + if BURSTS.fetch_add(1, Ordering::Relaxed) >= 8 { + return; + } + report(); +} + +/// The device was removed: the same report, once. A driver that gives up on a hung GPU after +/// 2 s does so before the watchdog's 3 s without progress, and the report never came. +pub fn on_device_removed() { + static DONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if enabled() && !DONE.swap(true, Ordering::Relaxed) { + report(); + } +} + +fn report() { + let g = MARKERS.lock().unwrap(); + let Some(m) = g.as_ref() else { return }; + // SAFETY: slots index the mapped buffer of SLOTS pairs + let open = open_lists(&m.slots, |s| unsafe { (std::ptr::read_volatile(m.cpu.add(s as usize * 2)), std::ptr::read_volatile(m.cpu.add(s as usize * 2 + 1))) }); + crate::xlog_warn!("GPU culprit: {} of {} lists have dispatches started and not done", open.len(), m.slots.len()); + for (list, i, o) in open.iter().take(16) { + let left = not_done(&m.what, *list, *i, *o); + crate::xlog_warn!("GPU culprit: list {list:#x}: marker in #{i}, last marker out #{o}; {} of its dispatches not known done:", left.len()); + for (id, s) in left.iter().take(24) { + crate::xlog_warn!("GPU culprit: #{id}: {s}{}", args_now(*id)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Only a list whose number in is above its number out has work in flight, and the + /// dispatches logged for it are its own, after the out. + #[test] + fn a_list_with_a_marker_in_above_its_marker_out_is_open() { + let slots: HashMap = [(0xA, 0), (0xB, 1), (0xC, 2), (0xD, 3)].into_iter().collect(); + // A: done; B: 12 started, 10 done; C: in and out written out of order; D: never ran + let words = |s: u32| [(9, 9), (12, 10), (20, 21), (0, 0)][s as usize]; + assert_eq!(open_lists(&slots, words), vec![(0xB, 12, 10)]); + + let what: HashMap = + [(10, (0xB, "b10".to_string())), (11, (0xA, "a11".to_string())), (12, (0xB, "b12".to_string()))].into_iter().collect(); + assert_eq!(not_done(&what, 0xB, 12, 10), vec![(12, "b12")], "11 belongs to another list"); + } + + /// Once every slot is taken, a new list gets none and is not recorded, and the lists that + /// have one keep it: no slot past the readback buffer is ever read. + #[test] + fn a_list_past_the_last_slot_gets_none() { + let mut slots = HashMap::new(); + assert_eq!(slot_for(&mut slots, 0xA, 2), Some(0)); + assert_eq!(slot_for(&mut slots, 0xB, 2), Some(1)); + assert_eq!(slot_for(&mut slots, 0xC, 2), None); + assert_eq!(slots.len(), 2, "the list without a slot is not recorded"); + assert_eq!(slot_for(&mut slots, 0xA, 2), Some(0)); + assert!(slots.values().all(|&s| (s as usize) < 2)); + } + + /// The markers reach the readback buffer: a list run to its end leaves its numbers in and + /// out equal, so nothing is reported for it. + #[test] + fn gpu_markers_of_a_finished_list_match() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let Some(m) = make_markers(&dev) else { panic!("readback buffer") }; + 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(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let l2: ID3D12GraphicsCommandList2 = list.cast().unwrap(); + for (i, mode) in [(0u64, D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_IN), (4, D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT)] { + let p = D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: m.gpu + 8 + i, Value: 77 }; + l2.WriteBufferImmediate(1, &p, Some(&mode)); + } + 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 t = std::time::Instant::now(); + while fence.GetCompletedValue() < 1 { + assert!(t.elapsed().as_secs() < 10, "the list did not finish"); + std::thread::yield_now(); + } + let words = |s: u32| (std::ptr::read_volatile(m.cpu.add(s as usize * 2)), std::ptr::read_volatile(m.cpu.add(s as usize * 2 + 1))); + assert_eq!(words(1), (77, 77)); + let slots: HashMap = [(list.as_raw() as usize, 1)].into_iter().collect(); + assert!(open_lists(&slots, words).is_empty()); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs new file mode 100644 index 0000000000..d5ad37aef2 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -0,0 +1,3157 @@ +//! Depth-stencil + unordered-access color twins (`ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS`). +//! +//! Console titles bind depth-stencil buffers as UAVs in compute passes (for example, writing +//! tiled material classifications into depth and bitmasks into stencil, then testing them with +//! `DEPTH_READ` / `EQUAL` draws). PC D3D12 rejects `D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS` +//! on depth-stencil textures, so `device_x::pc_resource_desc` strips bit 2 (`ALLOW_UNORDERED_ACCESS`). +//! Without a writable host twin, every UAV of the depth-stencil texture becomes a null view and +//! compute writes vanish. +//! +//! This module pairs each single-sample depth+UAV texture with lazily allocated `ALLOW_UNORDERED_ACCESS` +//! color twin texture(s) (`R32_TYPELESS` / `R16_TYPELESS` for the depth plane and `R8_TYPELESS` for +//! the stencil plane on two-plane formats). Outside synchronization ops, every twin stays in +//! `D3D12_RESOURCE_STATE_UNORDERED_ACCESS` (valid on both DIRECT and COMPUTE queues). On DIRECT +//! command list transitions out of / into `UNORDERED_ACCESS` (or before `OMSetRenderTargets` binds +//! the DSV), dirty planes synchronize lazily: +//! * Single-plane `R32_TYPELESS` / `R16_TYPELESS`: direct `CopyResource`. +//! * Two-plane `R32G8X24_TYPELESS` depth (plane 0) and any two-plane stencil (plane 1): +//! per-subresource buffer-through `CopyTextureRegion` (exact bit-for-bit transfer). +//! * Two-plane `R24G8_TYPELESS` depth (plane 0, e.g. console `D16_UNORM_S8_UINT` / `D24_UNORM_S8_UINT`): +//! fullscreen depth-write pass (`SV_Depth`, stencil writes disabled) for twin -> depth and a +//! compute copy (`R24_UNORM_X8_TYPELESS` -> `R16_UNORM`/`R32_FLOAT`) for depth -> twin, +//! restoring all list graphics/descriptor bindings afterward. +//! +//! Set `XCL_DEPTH_UAV_TWIN=0` to disable color twins. + +use std::collections::HashMap; +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, PCSTR}; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::list_x; +use super::real; + +const STATE_COMMON: u32 = 0; +const STATE_UAV: u32 = 0x8; +const STATE_DEPTH_WRITE: u32 = 0x10; +const STATE_DEPTH_READ: u32 = 0x20; +const STATE_COPY_DEST: u32 = 0x400; +const STATE_COPY_SOURCE: u32 = 0x800; +const STATE_SRV_ALL: u32 = 0x40 | 0x80; + +const FLAG_DEPTH_STENCIL: u32 = 0x2; +const FLAG_UAV: u32 = 0x4; + +/// How a depth resource's plane 0 synchronizes with its `depth_twin`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum DepthSyncKind { + /// Single-plane `R32_TYPELESS` or `R16_TYPELESS`: `CopyResource` directly. + DirectCopy, + /// Two-plane `R32G8X24_TYPELESS` plane 0 (`R32_TYPELESS`): buffer-through `CopyTextureRegion`. + BufferThrough, + /// Two-plane `R24G8_TYPELESS` plane 0: fullscreen depth-write pass (twin -> depth) and CS copy (depth -> twin). + /// When `steps` is true (console `D16_UNORM_S8_UINT` family `118..=120`), the `R16_TYPELESS` twin stores + /// 16-bit integer steps of `1/65535` read as `R16_UINT` and multiplied by `asfloat(0x37800080)` so the + /// 24-bit depth matches tiled-lighting `DepthFunc = EQUAL` vertex shaders bit-for-bit. + FullscreenPass { steps: bool, twin_srv_fmt: i32, twin_uav_fmt: i32 }, +} + +/// Twin allocation & sync plan derived from a console resource format. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct TwinPlan { + pub depth_twin_fmt: i32, + pub stencil_twin_fmt: Option, + pub depth_sync: DepthSyncKind, + pub two_plane: bool, +} + +/// Choose the color twin format(s) and sync strategy for a console depth-stencil format. +pub(super) fn plan_for_console_format(console_fmt: u32) -> Option { + match console_fmt { + // D32_FLOAT / R32_TYPELESS + 39 | 40 => Some(TwinPlan { + depth_twin_fmt: DXGI_FORMAT_R32_TYPELESS.0, + stencil_twin_fmt: None, + depth_sync: DepthSyncKind::DirectCopy, + two_plane: false, + }), + // D16_UNORM / R16_TYPELESS + 53 | 55 => Some(TwinPlan { + depth_twin_fmt: DXGI_FORMAT_R16_TYPELESS.0, + stencil_twin_fmt: None, + depth_sync: DepthSyncKind::DirectCopy, + two_plane: false, + }), + // D32_FLOAT_S8X24_UINT / R32G8X24_TYPELESS + 19 | 20 => Some(TwinPlan { + depth_twin_fmt: DXGI_FORMAT_R32_TYPELESS.0, + stencil_twin_fmt: Some(DXGI_FORMAT_R8_TYPELESS.0), + depth_sync: DepthSyncKind::BufferThrough, + two_plane: true, + }), + // Console D16_UNORM_S8_UINT family -> PC R24G8_TYPELESS + 118..=120 => Some(TwinPlan { + depth_twin_fmt: DXGI_FORMAT_R16_TYPELESS.0, + stencil_twin_fmt: Some(DXGI_FORMAT_R8_TYPELESS.0), + depth_sync: DepthSyncKind::FullscreenPass { + steps: true, + twin_srv_fmt: DXGI_FORMAT_R16_UINT.0, + twin_uav_fmt: DXGI_FORMAT_R16_UNORM.0, + }, + two_plane: true, + }), + // D24_UNORM_S8_UINT / R24G8_TYPELESS + 44 | 45 => Some(TwinPlan { + depth_twin_fmt: DXGI_FORMAT_R32_TYPELESS.0, + stencil_twin_fmt: Some(DXGI_FORMAT_R8_TYPELESS.0), + depth_sync: DepthSyncKind::FullscreenPass { + steps: false, + twin_srv_fmt: DXGI_FORMAT_R32_FLOAT.0, + twin_uav_fmt: DXGI_FORMAT_R32_FLOAT.0, + }, + two_plane: true, + }), + _ => None, + } +} + +/// Which plane(s) a view or barrier targets. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum PlaneMask { + Depth, + Stencil, + Both, +} + +impl PlaneMask { + fn includes_depth(self) -> bool { + matches!(self, PlaneMask::Depth | PlaneMask::Both) + } + + fn includes_stencil(self) -> bool { + matches!(self, PlaneMask::Stencil | PlaneMask::Both) + } +} + +/// Determine whether a UAV description targets the stencil plane of a two-plane depth resource. +pub(super) fn is_stencil_uav_format(fmt: u32, plane_slice: u32) -> bool { + plane_slice == 1 || matches!(fmt, 22 | 47 | 60..=64 | 120) +} + +/// Map a requested console/PC UAV format to a legal typed format on the chosen color twin. +pub(super) fn twin_uav_format(twin_typeless_fmt: i32, requested_fmt: u32) -> i32 { + match twin_typeless_fmt { + // R8_TYPELESS stencil twin + 60 => match requested_fmt { + 61 => DXGI_FORMAT_R8_UNORM.0, + 63 => DXGI_FORMAT_R8_SNORM.0, + 64 => DXGI_FORMAT_R8_SINT.0, + _ => DXGI_FORMAT_R8_UINT.0, + }, + // R16_TYPELESS depth twin + 53 => match requested_fmt { + 54 => DXGI_FORMAT_R16_FLOAT.0, + 57 => DXGI_FORMAT_R16_UINT.0, + 59 => DXGI_FORMAT_R16_SINT.0, + _ => DXGI_FORMAT_R16_UNORM.0, + }, + // R32_TYPELESS depth twin + 39 => match requested_fmt { + 42 => DXGI_FORMAT_R32_UINT.0, + 43 => DXGI_FORMAT_R32_SINT.0, + _ => DXGI_FORMAT_R32_FLOAT.0, + }, + other => other, + } +} + +/// Classify which plane(s) a D3D12 subresource index belongs to. +pub(super) fn plane_for_subresource(sub: u32, mips: u32, array_size: u32, two_plane: bool) -> PlaneMask { + if !two_plane { + return PlaneMask::Depth; + } + if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES { + return PlaneMask::Both; + } + let per_plane = mips.max(1).saturating_mul(array_size.max(1)); + if sub >= per_plane { + PlaneMask::Stencil + } else { + PlaneMask::Depth + } +} + +struct Entry { + device: usize, + plan: TwinPlan, + width: u64, + height: u32, + array_size: u16, + mip_levels: u16, + depth_twin: Option, + stencil_twin: Option, + /// Last known PC resource state per subresource for plane 0 (depth) and plane 1 (stencil). + pc_states_depth: Vec, + pc_states_stencil: Vec, + /// True when the color twin may contain newer UAV writes than the depth-stencil resource. + depth_twin_dirty: bool, + stencil_twin_dirty: bool, + /// True when the depth-stencil resource may contain newer DSV/clear writes than the twin. + depth_plane_dirty: bool, + stencil_plane_dirty: bool, + /// True per subresource if a split barrier (`BEGIN_ONLY`) involving `UNORDERED_ACCESS` was suppressed. + split_uav_depth: Vec, + split_uav_stencil: Vec, + /// Lazy DSV/SRV/UAV descriptor heaps for `FullscreenPass` sync on `R24G8_TYPELESS`. + pass_dsv_heap: Option, + pass_srv_uav_heap: Option, +} + +// D3D12 resources and descriptor heaps are free-threaded. +unsafe impl Send for Entry {} + +impl Entry { + fn new(device: usize, plan: TwinPlan, width: u64, height: u32, array_size: u16, mip_levels: u16, initial_pc_state: u32, started_as_uav: bool) -> Self { + let array_size = array_size.max(1); + let mip_levels = mip_levels.max(1); + let per_plane = (mip_levels as usize).saturating_mul(array_size as usize).max(1); + let stencil_len = if plan.two_plane { per_plane } else { 0 }; + Self { + device, + plan, + width, + height, + array_size, + mip_levels, + depth_twin: None, + stencil_twin: None, + pc_states_depth: vec![initial_pc_state; per_plane], + pc_states_stencil: vec![initial_pc_state; stencil_len], + depth_twin_dirty: started_as_uav, + stencil_twin_dirty: started_as_uav && plan.two_plane, + depth_plane_dirty: !started_as_uav && (initial_pc_state & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0), + stencil_plane_dirty: !started_as_uav && plan.two_plane && (initial_pc_state & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0), + split_uav_depth: vec![false; per_plane], + split_uav_stencil: vec![false; stencil_len], + pass_dsv_heap: None, + pass_srv_uav_heap: None, + } + } + + fn subresources_per_plane(&self) -> u32 { + (self.mip_levels as u32).saturating_mul(self.array_size as u32).max(1) + } + + fn local_subs_for(&self, subresource: u32, plane: u32) -> std::ops::Range { + let per_plane = self.subresources_per_plane(); + if subresource == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES { + return 0..per_plane as usize; + } + let base = plane * per_plane; + if subresource >= base && subresource < base + per_plane { + let idx = (subresource - base) as usize; + idx..idx + 1 + } else { + 0..0 + } + } +} + +/// Action queued by `filter_barrier` to run on the command list. +/// Each `(local_sub, before_state, after_state)` entry names the exact plane-local subresource +/// index and its tracked PC `StateBefore` / `StateAfter` so partial subresource barriers and +/// per-plane states never corrupt sibling subresources or planes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) enum SyncOp { + TwinToDepth { + res: usize, + depth: Vec<(u32, u32, u32)>, + stencil: Vec<(u32, u32, u32)>, + }, + DepthToTwin { + res: usize, + depth: Vec<(u32, u32, u32)>, + stencil: Vec<(u32, u32, u32)>, + }, + TransitionOnly { + res: usize, + depth: Vec<(u32, u32, u32)>, + stencil: Vec<(u32, u32, u32)>, + }, +} + +static ENTRIES: Mutex>> = Mutex::new(None); +static COUNT: AtomicUsize = AtomicUsize::new(0); +/// DSV CPU handle -> `(resource raw pointer, D3D12_DSV_FLAGS)`. +static DSV_TO_RES: Mutex>> = Mutex::new(None); +/// PC UAV CPU descriptor handle -> color twin `ID3D12Resource` raw pointer +/// (used to route `ClearUnorderedAccessViewUint/Float` onto the color twin). +static UAV_PC_TO_TWIN: Mutex>> = Mutex::new(None); +static UAV_TWIN_COUNT: AtomicUsize = AtomicUsize::new(0); + +/// Whether Depth+UAV color twins are enabled (`XCL_DEPTH_UAV_TWIN=0` turns them off). +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_DEPTH_UAV_TWIN").is_ok_and(|v| v.trim() == "0")) +} + +pub fn any() -> bool { + COUNT.load(Ordering::Relaxed) != 0 +} + +/// Register a newly created console depth+UAV texture (`flags & 6 == 6`, single-sample, 2D). +pub(super) fn register_if_depth_uav(device: *mut c_void, res: *mut c_void, console_desc: &[u8; 0x38], initial_pc_state: u32, console_initial_state: u32) { + if !enabled() || device.is_null() || res.is_null() { + return; + } + let dim = u32::from_le_bytes(console_desc[0..4].try_into().unwrap()); + let flags = u32::from_le_bytes(console_desc[0x30..0x34].try_into().unwrap()); + let samples = u32::from_le_bytes(console_desc[0x24..0x28].try_into().unwrap()); + if dim != D3D12_RESOURCE_DIMENSION_TEXTURE2D.0 as u32 || (flags & (FLAG_DEPTH_STENCIL | FLAG_UAV)) != (FLAG_DEPTH_STENCIL | FLAG_UAV) || samples > 1 { + return; + } + let console_fmt = u32::from_le_bytes(console_desc[0x20..0x24].try_into().unwrap()); + let Some(plan) = plan_for_console_format(console_fmt) else { + return; + }; + let width = u64::from_le_bytes(console_desc[0x10..0x18].try_into().unwrap()); + let height = u32::from_le_bytes(console_desc[0x18..0x1C].try_into().unwrap()); + let array_size = u16::from_le_bytes(console_desc[0x1C..0x1E].try_into().unwrap()).max(1); + let mip_levels = u16::from_le_bytes(console_desc[0x1E..0x20].try_into().unwrap()).max(1); + let started_as_uav = console_initial_state & STATE_UAV != 0; + + let mut g = ENTRIES.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + let prev = map.insert( + res as usize, + Entry::new(device as usize, plan, width, height, array_size, mip_levels, initial_pc_state, started_as_uav), + ); + if prev.is_none() { + COUNT.fetch_add(1, Ordering::Relaxed); + } + static LOGGED: AtomicU64 = AtomicU64::new(0); + static LOGGED_TWO_PLANE: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed); + let tp_n = if plan.two_plane { Some(LOGGED_TWO_PLANE.fetch_add(1, Ordering::Relaxed)) } else { None }; + if n < 8 || n.is_power_of_two() || tp_n.is_some_and(|k| k < 8 || k.is_power_of_two()) { + crate::xlog_info!( + "D3D12.X: tracked depth+UAV texture {res:p} ({width}x{height}x{array_size}, {mip_levels} mips, console fmt {console_fmt}, two_plane {}) for color-twin UAV sync ({} tracked)", + plan.two_plane, + map.len() + ); + } +} + +/// Remove tracking when a resource is released for good (twins go through `res_release` -> `late_release`). +pub(super) fn forget(res: usize) { + if !any() { + return; + } + let removed = { + let mut g = ENTRIES.lock().unwrap(); + let r = g.as_mut().and_then(|m| m.remove(&res)); + if r.is_some() { + COUNT.fetch_sub(1, Ordering::Relaxed); + } + r + }; + if let Some(mut e) = removed { + if let Some(m) = DSV_TO_RES.lock().unwrap().as_mut() { + m.retain(|_, &mut (v, _)| v != res); + } + let d_twin = e.depth_twin.as_ref().map(|t| t.as_raw() as usize); + let s_twin = e.stencil_twin.as_ref().map(|t| t.as_raw() as usize); + if (d_twin.is_some() || s_twin.is_some()) && UAV_TWIN_COUNT.load(Ordering::Relaxed) != 0 { + if let Some(m) = UAV_PC_TO_TWIN.lock().unwrap().as_mut() { + let before = m.len(); + m.retain(|_, &mut t| Some(t) != d_twin && Some(t) != s_twin); + let removed_n = before - m.len(); + if removed_n > 0 { + UAV_TWIN_COUNT.fetch_sub(removed_n, Ordering::Relaxed); + } + } + } + // Defer release of internal unadopted pass descriptor heaps until in-flight GPU work completes. + unsafe { + if let Some(h) = e.pass_dsv_heap.take() { + super::late_release::hold(h.into_raw() as usize); + } + if let Some(h) = e.pass_srv_uav_heap.take() { + super::late_release::hold(h.into_raw() as usize); + } + } + drop(e); + } +} + +/// Record DSV handle -> `(resource, dsv_flags)` for `OMSetRenderTargets` and `ClearDepthStencilView` hooks. +pub(super) fn note_dsv(dsv_cpu: usize, res: usize, dsv_flags: u32) { + if !any() || dsv_cpu == 0 { + return; + } + let tracked = ENTRIES.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&res)); + let mut g = DSV_TO_RES.lock().unwrap(); + if tracked { + g.get_or_insert_with(HashMap::new).insert(dsv_cpu, (res, dsv_flags)); + } else if let Some(m) = g.as_mut() { + m.remove(&dsv_cpu); + } +} + +/// Propagate tracked DSV mappings across `CopyDescriptorsSimple` / `CopyDescriptors` on DSV heaps, +/// snapshotting source entries first so overlapping ranges copy safely. +pub(super) fn copy_dsv(dst_cpu: usize, src_cpu: usize, count: u32, inc: usize) { + if !any() || count == 0 || inc == 0 || dst_cpu == 0 || src_cpu == 0 || dst_cpu == src_cpu { + return; + } + let mut g = DSV_TO_RES.lock().unwrap(); + let Some(m) = g.as_mut() else { + return; + }; + if m.is_empty() { + return; + } + let n = count as usize; + let mut snap: Vec> = Vec::with_capacity(n); + for i in 0..n { + let Some(src) = i.checked_mul(inc).and_then(|off| src_cpu.checked_add(off)) else { + break; + }; + snap.push(m.get(&src).copied()); + } + for (i, entry) in snap.into_iter().enumerate() { + let Some(dst) = i.checked_mul(inc).and_then(|off| dst_cpu.checked_add(off)) else { + break; + }; + if let Some(v) = entry { + m.insert(dst, v); + } else { + m.remove(&dst); + } + } +} + +/// Record that PC UAV CPU handle `pc_uav` was routed to color twin resource `twin_res`. +pub(super) fn note_uav_twin(pc_uav: usize, twin_res: usize) { + if pc_uav == 0 { + return; + } + if twin_res == 0 { + clear_uav_twin(pc_uav); + return; + } + let mut g = UAV_PC_TO_TWIN.lock().unwrap(); + if g.get_or_insert_with(HashMap::new).insert(pc_uav, twin_res).is_none() { + UAV_TWIN_COUNT.fetch_add(1, Ordering::Relaxed); + } +} + +/// Clear any recorded color-twin mapping for PC UAV CPU handle `pc_uav`. +pub(super) fn clear_uav_twin(pc_uav: usize) { + if pc_uav == 0 || UAV_TWIN_COUNT.load(Ordering::Relaxed) == 0 { + return; + } + if let Some(m) = UAV_PC_TO_TWIN.lock().unwrap().as_mut() { + if m.remove(&pc_uav).is_some() { + UAV_TWIN_COUNT.fetch_sub(1, Ordering::Relaxed); + } + } +} + +/// Look up the color twin resource for a twinned PC UAV CPU handle (e.g. for +/// `ClearUnorderedAccessViewUint/Float`) and mark that twin dirty so subsequent DSV/SRV uses flush. +pub(super) fn twin_for_pc_uav(pc_uav: usize) -> Option { + if pc_uav == 0 || UAV_TWIN_COUNT.load(Ordering::Relaxed) == 0 { + return None; + } + let twin = UAV_PC_TO_TWIN.lock().unwrap().as_ref()?.get(&pc_uav).copied()?; + if any() { + if let Some(map) = ENTRIES.lock().unwrap().as_mut() { + for e in map.values_mut() { + if e.depth_twin.as_ref().is_some_and(|t| t.as_raw() as usize == twin) { + e.depth_twin_dirty = true; + if e.plan.two_plane { + e.depth_plane_dirty = false; + } + break; + } + if e.stencil_twin.as_ref().is_some_and(|t| t.as_raw() as usize == twin) { + e.stencil_twin_dirty = true; + if e.plan.two_plane { + e.stencil_plane_dirty = false; + } + break; + } + } + } + } + Some(twin) +} + +unsafe fn create_twin_resource(device: *mut c_void, width: u64, height: u32, array_size: u16, mip_levels: u16, format: i32) -> Option { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Alignment: 0, + Width: width, + Height: height, + DepthOrArraySize: array_size, + MipLevels: mip_levels, + Format: DXGI_FORMAT(format), + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + }; + let mut out: *mut c_void = std::ptr::null_mut(); + let hr = real::dev_create_committed_resource( + device, + &heap as *const _ as usize, + 0, + &desc as *const _ as usize, + STATE_UAV as usize, + 0, + &ID3D12Resource::IID as *const _ as *const windows_sys::core::GUID, + &mut out, + ); + if hr < 0 || out.is_null() { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: depth+UAV twin allocation ({width}x{height}x{array_size}, fmt {format}) failed ({hr:#x})"); + } + return None; + } + Some(ID3D12Resource::from_raw(out)) +} + +/// Route a `CreateUnorderedAccessView` on a tracked depth+UAV resource to its depth or stencil +/// color twin, returning `(twin_raw_ptr, patched_uav_desc)` when handled. +pub(super) unsafe fn resolve_uav( + dev: *mut c_void, + res: *mut c_void, + orig_desc: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>, +) -> Option<(*mut c_void, D3D12_UNORDERED_ACCESS_VIEW_DESC)> { + if !any() || res.is_null() { + return None; + } + let key = res as usize; + let plane_slice = orig_desc.map_or(0, |d| match d.ViewDimension { + D3D12_UAV_DIMENSION_TEXTURE2D => d.Anonymous.Texture2D.PlaneSlice, + D3D12_UAV_DIMENSION_TEXTURE2DARRAY => d.Anonymous.Texture2DArray.PlaneSlice, + _ => 0, + }); + let req_fmt = orig_desc.map_or(0, |d| d.Format.0 as u32); + + // Inspect plan and check whether the twin already exists before allocating outside the lock. + let (need_alloc, is_stencil, two_plane, twin_fmt, width, height, array_size, mip_levels, device, existing_raw) = { + let g = ENTRIES.lock().unwrap(); + let e = g.as_ref()?.get(&key)?; + let stencil = e.plan.two_plane && is_stencil_uav_format(req_fmt, plane_slice); + let twin_fmt = if stencil { e.plan.stencil_twin_fmt? } else { e.plan.depth_twin_fmt }; + let existing = if stencil { + e.stencil_twin.as_ref().map(|r| r.as_raw()) + } else { + e.depth_twin.as_ref().map(|r| r.as_raw()) + }; + (existing.is_none(), stencil, e.plan.two_plane, twin_fmt, e.width, e.height, e.array_size, e.mip_levels, if dev.is_null() { e.device as *mut c_void } else { dev }, existing) + }; + + let twin_raw = if let Some(raw) = existing_raw { + raw + } else if need_alloc { + let created = create_twin_resource(device, width, height, array_size, mip_levels, twin_fmt)?; + let mut g = ENTRIES.lock().unwrap(); + let Some(e) = g.as_mut().and_then(|m| m.get_mut(&key)) else { + return None; + }; + let slot = if is_stencil { &mut e.stencil_twin } else { &mut e.depth_twin }; + if slot.is_none() { + *slot = Some(created); + } + slot.as_ref()?.as_raw() + } else { + return None; + }; + + let patched_fmt = twin_uav_format(twin_fmt, req_fmt); + let mut patched = match orig_desc { + Some(d) => *d, + None => { + let mut d = D3D12_UNORDERED_ACCESS_VIEW_DESC::default(); + if array_size > 1 { + d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + d.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { + MipSlice: 0, + FirstArraySlice: 0, + ArraySize: array_size as u32, + PlaneSlice: 0, + }; + } else { + d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + d.Anonymous.Texture2D = D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 }; + } + d + } + }; + patched.Format = DXGI_FORMAT(patched_fmt); + match patched.ViewDimension { + D3D12_UAV_DIMENSION_TEXTURE2D => patched.Anonymous.Texture2D.PlaneSlice = 0, + D3D12_UAV_DIMENSION_TEXTURE2DARRAY => patched.Anonymous.Texture2DArray.PlaneSlice = 0, + _ => {} + } + + static ROUTED: AtomicU64 = AtomicU64::new(0); + static ROUTED_TWO_PLANE: AtomicU64 = AtomicU64::new(0); + let n = ROUTED.fetch_add(1, Ordering::Relaxed); + let tp_n = if two_plane { Some(ROUTED_TWO_PLANE.fetch_add(1, Ordering::Relaxed)) } else { None }; + if n < 8 || n.is_power_of_two() || tp_n.is_some_and(|k| k < 8 || k.is_power_of_two()) { + crate::xlog_info!( + "D3D12.X: routed {} UAV of depth+UAV texture {res:p} (two_plane {two_plane}, req fmt {req_fmt} -> twin fmt {patched_fmt}) to color twin {twin_raw:p} ({} routed)", + if is_stencil { "stencil" } else { "depth" }, + n + 1 + ); + } + Some((twin_raw, patched)) +} + +/// Pure state-machine transition decision for a single barrier on a tracked depth+UAV texture. +/// Returns `(pass_through_barrier, needs_global_uav_barrier, optional_sync_op)`. +fn decide_transition( + e: &mut Entry, + subresource: u32, + before: u32, + after: u32, + flags: u32, + is_direct: bool, +) -> (bool, bool, Option) { + const BARRIER_BEGIN_ONLY: u32 = 1; + const BARRIER_END_ONLY: u32 = 2; + + let planes = plane_for_subresource(subresource, e.mip_levels as u32, e.array_size as u32, e.plan.two_plane); + let d_range = if planes.includes_depth() { e.local_subs_for(subresource, 0) } else { 0..0 }; + let s_range = if e.plan.two_plane && planes.includes_stencil() { e.local_subs_for(subresource, 1) } else { 0..0 }; + let touches_uav = (before | after) & STATE_UAV != 0; + + // Non-DIRECT lists (COMPUTE / COPY / BUNDLE) cannot transition a depth-stencil resource + // to/from DEPTH_* or UNORDERED_ACCESS; suppress invalid barriers and defer sync to DIRECT. + if !is_direct { + if touches_uav { + if after & STATE_UAV != 0 { + if !d_range.is_empty() && e.depth_twin.is_some() { + e.depth_twin_dirty = true; + } + if !s_range.is_empty() && e.stencil_twin.is_some() { + e.stencil_twin_dirty = true; + } + } + return (false, true, None); + } + return (false, false, None); + } + + // Handle split barriers touching UNORDERED_ACCESS: suppress BEGIN_ONLY and perform the + // complete atomic transition + sync at END_ONLY. + if flags == BARRIER_BEGIN_ONLY { + if touches_uav { + for s in d_range { + e.split_uav_depth[s] = true; + } + for s in s_range { + e.split_uav_stencil[s] = true; + } + return (false, false, None); + } + return (true, false, None); + } + if flags == BARRIER_END_ONLY { + let was_split_uav = d_range.clone().any(|s| e.split_uav_depth[s]) || s_range.clone().any(|s| e.split_uav_stencil[s]); + if !touches_uav && !was_split_uav { + for s in d_range.clone() { + e.pc_states_depth[s] = after; + } + if !d_range.is_empty() && after & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0 { + e.depth_plane_dirty = true; + } + for s in s_range.clone() { + e.pc_states_stencil[s] = after; + } + if !s_range.is_empty() && after & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0 { + e.stencil_plane_dirty = true; + } + return (true, false, None); + } + for s in d_range.clone() { + e.split_uav_depth[s] = false; + } + for s in s_range.clone() { + e.split_uav_stencil[s] = false; + } + } + + let collect_subs = |states: &mut [u32], range: std::ops::Range, target: u32| -> Vec<(u32, u32, u32)> { + let mut v = Vec::with_capacity(range.len()); + for s in range { + let prev = states[s]; + states[s] = target; + v.push((s as u32, prev, target)); + } + v + }; + + let leaving_uav = before & STATE_UAV != 0 && after & STATE_UAV == 0; + let entering_uav = before & STATE_UAV == 0 && after & STATE_UAV != 0; + + if leaving_uav { + let need_d = !d_range.is_empty() && e.depth_twin.is_some(); + let need_s = !s_range.is_empty() && e.stencil_twin.is_some(); + let depth = collect_subs(&mut e.pc_states_depth, d_range.clone(), after); + let stencil = collect_subs(&mut e.pc_states_stencil, s_range.clone(), after); + if !d_range.is_empty() { + e.depth_twin_dirty = false; + if after & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0 { + e.depth_plane_dirty = true; + } + } + if !s_range.is_empty() { + e.stencil_twin_dirty = false; + if after & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0 { + e.stencil_plane_dirty = true; + } + } + let op = if need_d || need_s { + Some(SyncOp::TwinToDepth { res: 0, depth, stencil }) + } else { + Some(SyncOp::TransitionOnly { res: 0, depth, stencil }) + }; + return (false, true, op); + } + + if entering_uav { + // Transition depth resource from each subresource's tracked PC state (`prev`) to + // `DEPTH_WRITE` as its resting state while UAV is active. + let need_d = !d_range.is_empty() && e.depth_twin.is_some() && (e.depth_plane_dirty || before & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0); + let need_s = !s_range.is_empty() && e.stencil_twin.is_some() && (e.stencil_plane_dirty || before & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0); + let depth = collect_subs(&mut e.pc_states_depth, d_range.clone(), STATE_DEPTH_WRITE); + let stencil = collect_subs(&mut e.pc_states_stencil, s_range.clone(), STATE_DEPTH_WRITE); + if !d_range.is_empty() { + e.depth_twin_dirty = e.depth_twin.is_some(); + e.depth_plane_dirty = false; + } + if !s_range.is_empty() { + e.stencil_twin_dirty = e.stencil_twin.is_some(); + e.stencil_plane_dirty = false; + } + let op = if need_d || need_s { + Some(SyncOp::DepthToTwin { res: 0, depth, stencil }) + } else { + Some(SyncOp::TransitionOnly { res: 0, depth, stencil }) + }; + return (false, true, op); + } + + // Neither before nor after is UNORDERED_ACCESS. If a twin became dirty (e.g. on an async + // compute list), flush it into the depth resource now as part of this transition. + let flush_d = !d_range.is_empty() && e.depth_twin_dirty && e.depth_twin.is_some(); + let flush_s = !s_range.is_empty() && e.stencil_twin_dirty && e.stencil_twin.is_some(); + let depth = collect_subs(&mut e.pc_states_depth, d_range.clone(), after); + let stencil = collect_subs(&mut e.pc_states_stencil, s_range.clone(), after); + if !d_range.is_empty() { + if flush_d { + e.depth_twin_dirty = false; + } + if after & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0 { + e.depth_plane_dirty = true; + } + } + if !s_range.is_empty() { + if flush_s { + e.stencil_twin_dirty = false; + } + if after & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0 { + e.stencil_plane_dirty = true; + } + } + if flush_d || flush_s { + let op = SyncOp::TwinToDepth { res: 0, depth, stencil }; + return (false, true, Some(op)); + } + + (true, false, None) +} + +/// Inspect a PC transition barrier `[ty, flags, res_lo, res_hi, sub, before, after, _]` inside +/// `list_x::resource_barrier_x`. Returns `(pass_through, emit_global_uav_barrier)` and pushes +/// any required sync operation onto `ops`. +pub(super) fn filter_transition( + b: &[u32; 8], + is_direct: bool, + ops: &mut Vec, +) -> (bool, bool) { + if !any() { + return (true, false); + } + let res = (b[2] as u64 | (b[3] as u64) << 32) as usize; + let mut g = ENTRIES.lock().unwrap(); + let Some(e) = g.as_mut().and_then(|m| m.get_mut(&res)) else { + return (true, false); + }; + let (pass, uav, op) = decide_transition(e, b[4], b[5], b[6], b[1], is_direct); + if let Some(mut op) = op { + match &mut op { + SyncOp::TwinToDepth { res: r, .. } | SyncOp::DepthToTwin { res: r, .. } | SyncOp::TransitionOnly { res: r, .. } => *r = res, + } + ops.push(op); + } + (pass, uav) +} + +/// Whether a `D3D12_BARRIER_LAYOUT` is an unordered-access layout (generic or queue-specific). +fn is_uav_layout(layout: D3D12_BARRIER_LAYOUT) -> bool { + matches!( + layout, + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS + ) +} + +/// Whether a `D3D12_BARRIER_LAYOUT` is a depth-write or copy-destination layout. +fn is_depth_write_or_copy_dest_layout(layout: D3D12_BARRIER_LAYOUT) -> bool { + matches!( + layout, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE + | D3D12_BARRIER_LAYOUT_COPY_DEST + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COPY_DEST + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_DEST + ) +} + +/// Map a `D3D12_BARRIER_LAYOUT` + `D3D12_BARRIER_ACCESS` pair to a valid PC `D3D12_RESOURCE_STATES` +/// value for a depth-stencil texture (never returning `STATE_UAV` or buffer-only state bits). +pub(super) fn enhanced_layout_to_pc_state(layout: D3D12_BARRIER_LAYOUT, access: D3D12_BARRIER_ACCESS) -> u32 { + let a = access.0 as u32; + let access_state = || -> u32 { + if a & (D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE.0 as u32) != 0 { + STATE_DEPTH_WRITE + } else if a & (D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ.0 as u32) != 0 { + STATE_DEPTH_READ + } else if a & (D3D12_BARRIER_ACCESS_SHADER_RESOURCE.0 as u32) != 0 { + STATE_SRV_ALL + } else if a & (D3D12_BARRIER_ACCESS_COPY_DEST.0 as u32) != 0 { + STATE_COPY_DEST + } else if a & (D3D12_BARRIER_ACCESS_COPY_SOURCE.0 as u32) != 0 { + STATE_COPY_SOURCE + } else { + STATE_COMMON + } + }; + match layout { + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE => STATE_DEPTH_WRITE, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ => STATE_DEPTH_READ, + D3D12_BARRIER_LAYOUT_SHADER_RESOURCE + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_SHADER_RESOURCE => STATE_SRV_ALL, + D3D12_BARRIER_LAYOUT_COPY_SOURCE + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COPY_SOURCE + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_SOURCE => STATE_COPY_SOURCE, + D3D12_BARRIER_LAYOUT_COPY_DEST + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COPY_DEST + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_DEST => STATE_COPY_DEST, + D3D12_BARRIER_LAYOUT_GENERIC_READ + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_GENERIC_READ + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_GENERIC_READ => { + if a & (D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ.0 as u32) != 0 { + STATE_DEPTH_READ + } else { + STATE_SRV_ALL | STATE_COPY_SOURCE + } + } + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS => STATE_DEPTH_WRITE, + _ => access_state(), + } +} + +/// Resolve an enhanced barrier's `D3D12_BARRIER_SUBRESOURCE_RANGE` into plane-local subresource +/// indices `(depth_subs, stencil_subs)`. +fn resolve_enhanced_subresources(e: &Entry, range: &D3D12_BARRIER_SUBRESOURCE_RANGE) -> (Vec, Vec) { + let mips = e.mip_levels as u32; + let slices = e.array_size as u32; + let two_plane = e.plan.two_plane; + if range.NumMipLevels == 0 { + let sub = range.IndexOrFirstMipLevel; + let planes = plane_for_subresource(sub, mips, slices, two_plane); + let d = if planes.includes_depth() { e.local_subs_for(sub, 0).map(|s| s as u32).collect() } else { Vec::new() }; + let s = if two_plane && planes.includes_stencil() { e.local_subs_for(sub, 1).map(|s| s as u32).collect() } else { Vec::new() }; + return (d, s); + } + let first_mip = range.IndexOrFirstMipLevel.min(mips); + let end_mip = range.IndexOrFirstMipLevel.saturating_add(range.NumMipLevels).min(mips); + let first_arr = range.FirstArraySlice.min(slices); + let num_arr = if range.NumArraySlices == 0 { 1 } else { range.NumArraySlices }; + let end_arr = range.FirstArraySlice.saturating_add(num_arr).min(slices); + let plane_count = if two_plane { 2u32 } else { 1u32 }; + let first_plane = range.FirstPlane.min(plane_count); + let num_planes = if range.NumPlanes == 0 { 1 } else { range.NumPlanes }; + let end_plane = range.FirstPlane.saturating_add(num_planes).min(plane_count); + + let mut depth = Vec::new(); + let mut stencil = Vec::new(); + for p in first_plane..end_plane { + let dst = if p == 0 { &mut depth } else { &mut stencil }; + for a in first_arr..end_arr { + for m in first_mip..end_mip { + dst.push(a * mips + m); + } + } + } + (depth, stencil) +} + +/// Pure state-machine transition decision for an enhanced `D3D12_TEXTURE_BARRIER` (`#146`) on a +/// tracked depth+UAV texture. +#[allow(clippy::too_many_arguments)] +fn decide_enhanced_texture_barrier( + e: &mut Entry, + access_before: D3D12_BARRIER_ACCESS, + access_after: D3D12_BARRIER_ACCESS, + layout_before: D3D12_BARRIER_LAYOUT, + layout_after: D3D12_BARRIER_LAYOUT, + subresources: &D3D12_BARRIER_SUBRESOURCE_RANGE, + flags: D3D12_TEXTURE_BARRIER_FLAGS, + is_direct: bool, +) -> Option { + let (d_subs, s_subs) = resolve_enhanced_subresources(e, subresources); + if d_subs.is_empty() && s_subs.is_empty() { + return None; + } + let ab = access_before.0 as u32; + let aa = access_after.0 as u32; + let uav_bit = D3D12_BARRIER_ACCESS_UNORDERED_ACCESS.0 as u32; + let write_bits = (D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE.0 as u32) | (D3D12_BARRIER_ACCESS_COPY_DEST.0 as u32); + let discard_before = (flags.0 as u32) & (D3D12_TEXTURE_BARRIER_FLAG_DISCARD.0 as u32) != 0 || layout_before == D3D12_BARRIER_LAYOUT_UNDEFINED; + + let common_before = ab == 0 && matches!(layout_before, D3D12_BARRIER_LAYOUT_COMMON | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COMMON | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COMMON); + let uav_before = (ab & uav_bit) != 0 || is_uav_layout(layout_before); + let uav_after = (aa & uav_bit) != 0 || is_uav_layout(layout_after); + let write_before = (ab & write_bits) != 0 || is_depth_write_or_copy_dest_layout(layout_before); + let write_after = (aa & write_bits) != 0 || is_depth_write_or_copy_dest_layout(layout_after); + let after_pc = enhanced_layout_to_pc_state(layout_after, access_after); + + if !is_direct { + if uav_before || uav_after || common_before { + if !d_subs.is_empty() && e.depth_twin.is_some() && (e.plan.two_plane || !e.depth_plane_dirty) { + e.depth_twin_dirty = true; + if e.plan.two_plane { + e.depth_plane_dirty = false; + } + } + if !s_subs.is_empty() && e.stencil_twin.is_some() && (e.plan.two_plane || !e.stencil_plane_dirty) { + e.stencil_twin_dirty = true; + if e.plan.two_plane { + e.stencil_plane_dirty = false; + } + } + } + return None; + } + + let collect_subs = |states: &mut [u32], subs: &[u32], target: u32| -> Vec<(u32, u32, u32)> { + let mut v = Vec::with_capacity(subs.len()); + for &s in subs { + let idx = s as usize; + if idx < states.len() { + let prev = states[idx]; + states[idx] = target; + v.push((s, prev, target)); + } + } + v + }; + + if uav_before && !uav_after { + let need_d = !discard_before && !d_subs.is_empty() && e.depth_twin.is_some(); + let need_s = !discard_before && !s_subs.is_empty() && e.stencil_twin.is_some(); + let depth = collect_subs(&mut e.pc_states_depth, &d_subs, after_pc); + let stencil = collect_subs(&mut e.pc_states_stencil, &s_subs, after_pc); + if !d_subs.is_empty() { + e.depth_twin_dirty = false; + if write_after { + e.depth_plane_dirty = true; + } + } + if !s_subs.is_empty() { + e.stencil_twin_dirty = false; + if write_after { + e.stencil_plane_dirty = true; + } + } + return if need_d || need_s { + Some(SyncOp::TwinToDepth { res: 0, depth, stencil }) + } else if depth.iter().any(|&(_, b, a)| b != a) || stencil.iter().any(|&(_, b, a)| b != a) { + Some(SyncOp::TransitionOnly { res: 0, depth, stencil }) + } else { + None + }; + } + + if !uav_before && uav_after { + let need_d = !discard_before && !d_subs.is_empty() && e.depth_twin.is_some() && (e.depth_plane_dirty || write_before); + let need_s = !discard_before && !s_subs.is_empty() && e.stencil_twin.is_some() && (e.stencil_plane_dirty || write_before); + let depth = collect_subs(&mut e.pc_states_depth, &d_subs, STATE_DEPTH_WRITE); + let stencil = collect_subs(&mut e.pc_states_stencil, &s_subs, STATE_DEPTH_WRITE); + if !d_subs.is_empty() { + e.depth_twin_dirty = e.depth_twin.is_some(); + e.depth_plane_dirty = false; + } + if !s_subs.is_empty() { + e.stencil_twin_dirty = e.stencil_twin.is_some(); + e.stencil_plane_dirty = false; + } + return if need_d || need_s { + Some(SyncOp::DepthToTwin { res: 0, depth, stencil }) + } else if depth.iter().any(|&(_, b, a)| b != a) || stencil.iter().any(|&(_, b, a)| b != a) { + Some(SyncOp::TransitionOnly { res: 0, depth, stencil }) + } else { + None + }; + } + + if uav_before && uav_after { + if !d_subs.is_empty() && e.depth_twin.is_some() { + e.depth_twin_dirty = true; + } + if !s_subs.is_empty() && e.stencil_twin.is_some() { + e.stencil_twin_dirty = true; + } + return None; + } + + // Neither before nor after explicitly names UAV. Flush dirty twins (including compute-only + // twins transitioning out of COMMON access) unless discarded, and advance tracked PC state. + let flush_d = !discard_before + && !d_subs.is_empty() + && e.depth_twin.is_some() + && (e.depth_twin_dirty || (common_before && (e.plan.two_plane || !e.depth_plane_dirty))); + let flush_s = !discard_before + && !s_subs.is_empty() + && e.stencil_twin.is_some() + && (e.stencil_twin_dirty || (common_before && (e.plan.two_plane || !e.stencil_plane_dirty))); + let depth = collect_subs(&mut e.pc_states_depth, &d_subs, after_pc); + let stencil = collect_subs(&mut e.pc_states_stencil, &s_subs, after_pc); + if !d_subs.is_empty() { + if flush_d || discard_before { + e.depth_twin_dirty = false; + } + if write_after { + e.depth_plane_dirty = true; + } else if discard_before || (flush_d && e.plan.two_plane) { + e.depth_plane_dirty = false; + } + } + if !s_subs.is_empty() { + if flush_s || discard_before { + e.stencil_twin_dirty = false; + } + if write_after { + e.stencil_plane_dirty = true; + } else if discard_before || (flush_s && e.plan.two_plane) { + e.stencil_plane_dirty = false; + } + } + if flush_d || flush_s { + return Some(SyncOp::TwinToDepth { res: 0, depth, stencil }); + } + if depth.iter().any(|&(_, b, a)| b != a) || stencil.iter().any(|&(_, b, a)| b != a) { + return Some(SyncOp::TransitionOnly { res: 0, depth, stencil }); + } + None +} + +/// Inspect `ID3D12GraphicsCommandList7::Barrier` (`#146`) barrier groups for tracked depth+UAV +/// textures. Queues any immediate `SyncOp`s on `ops` and returns `true` if a global (or unparsed) +/// UAV barrier was present so the caller should also call `on_global_uav_barrier()`. +pub(super) unsafe fn filter_enhanced_barriers( + n: u32, + groups: *const c_void, + is_direct: bool, + ops: &mut Vec, +) -> bool { + if !any() { + return false; + } + if n == 0 || groups.is_null() { + return true; + } + 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 true; + } + let slice = std::slice::from_raw_parts(groups as *const D3D12_BARRIER_GROUP, group_count); + let mut had_global_uav = false; + for grp in slice { + let count = (grp.NumBarriers as usize).min(4096); + match grp.Type { + D3D12_BARRIER_TYPE_GLOBAL => { + if count == 0 { + continue; + } + let ptr = grp.Anonymous.pGlobalBarriers; + let bytes = count.saturating_mul(std::mem::size_of::()); + if ptr.is_null() || !crate::gpu::shader::readable(ptr as usize, bytes) { + had_global_uav = true; + continue; + } + let gbs = std::slice::from_raw_parts(ptr, count); + for gb in gbs { + let ab = gb.AccessBefore.0 as u32; + if ab == 0 || ab & (D3D12_BARRIER_ACCESS_UNORDERED_ACCESS.0 as u32) != 0 { + had_global_uav = true; + break; + } + } + } + D3D12_BARRIER_TYPE_TEXTURE => { + 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) { + had_global_uav = true; + continue; + } + let tbs = std::slice::from_raw_parts(ptr, count); + let mut g = ENTRIES.lock().unwrap(); + let Some(map) = g.as_mut() else { + continue; + }; + for tb in tbs { + let res: usize = std::mem::transmute_copy(&tb.pResource); + if res == 0 { + continue; + } + let Some(e) = map.get_mut(&res) else { + continue; + }; + if let Some(mut op) = decide_enhanced_texture_barrier( + e, + tb.AccessBefore, + tb.AccessAfter, + tb.LayoutBefore, + tb.LayoutAfter, + &tb.Subresources, + tb.Flags, + is_direct, + ) { + match &mut op { + SyncOp::TwinToDepth { res: r, .. } | SyncOp::DepthToTwin { res: r, .. } | SyncOp::TransitionOnly { res: r, .. } => *r = res, + } + ops.push(op); + } + } + } + D3D12_BARRIER_TYPE_BUFFER => {} + _ => { + had_global_uav = true; + } + } + } + had_global_uav +} + +/// Apply a global UAV barrier to a single entry: mark materialized twins dirty. +/// For `two_plane` depth+UAV buffers (e.g. console `D16_UNORM_S8_UINT` material-mask buffers), +/// never let prior `DEPTH_WRITE` / `ClearDepthStencilView` (`depth_plane_dirty`) suppress twin +/// flushing; keep single-plane depth maps (e.g. `fmt 53` shadow maps) guarded by `!depth_plane_dirty` +/// so unrelated global UAV barriers do not clobber graphics-rendered shadow maps. +fn mark_global_uav_dirty(e: &mut Entry) { + if e.depth_twin.is_some() && (e.plan.two_plane || !e.depth_plane_dirty) { + e.depth_twin_dirty = true; + if e.plan.two_plane { + e.depth_plane_dirty = false; + } + } + if e.stencil_twin.is_some() && (e.plan.two_plane || !e.stencil_plane_dirty) { + e.stencil_twin_dirty = true; + if e.plan.two_plane { + e.stencil_plane_dirty = false; + } + } +} + +/// Mark materialized twins dirty on a global UAV barrier (`#146` global barrier or `#26` wildcard +/// `pResource == NULL` UAV barrier) for tracked depth+UAV resources whose depth/stencil plane is +/// not currently graphics-dirty, so compute-written depth+UAV targets flush on subsequent DSV bind. +pub(super) fn on_global_uav_barrier() { + if !any() { + return; + } + let mut g = ENTRIES.lock().unwrap(); + let Some(map) = g.as_mut() else { + return; + }; + for e in map.values_mut() { + mark_global_uav_dirty(e); + } +} + +/// Route a resource-specific UAV barrier targeting a tracked Depth+UAV resource to both its +/// materialized depth and stencil color twins, and mark those twins dirty so subsequent DSV/SRV +/// transitions flush their latest UAV writes back into the depth-stencil resource. +pub(super) fn on_uav_barrier(res: usize) -> [usize; 2] { + if !any() || res == 0 { + return [0, 0]; + } + let mut g = ENTRIES.lock().unwrap(); + let Some(e) = g.as_mut().and_then(|m| m.get_mut(&res)) else { + return [0, 0]; + }; + let d = match &e.depth_twin { + Some(t) => { + e.depth_twin_dirty = true; + if e.plan.two_plane { + e.depth_plane_dirty = false; + } + t.as_raw() as usize + } + None => 0, + }; + let s = match &e.stencil_twin { + Some(t) => { + e.stencil_twin_dirty = true; + if e.plan.two_plane { + e.stencil_plane_dirty = false; + } + t.as_raw() as usize + } + None => 0, + }; + [d, s] +} + +/// Before `OMSetRenderTargets` binds `dsv_cpu`, flush any dirty color twin into the depth resource. +pub(super) unsafe fn before_bind_dsv(list: *mut c_void, dsv_cpu: usize) { + if !any() || dsv_cpu == 0 { + return; + } + if list_x::tracked_list_type(list).is_some_and(|t| t != D3D12_COMMAND_LIST_TYPE_DIRECT) { + return; + } + let Some((res, dsv_flags)) = DSV_TO_RES.lock().unwrap().as_ref().and_then(|m| m.get(&dsv_cpu).copied()) else { + return; + }; + let d_target_from_common = if dsv_flags & (D3D12_DSV_FLAG_READ_ONLY_DEPTH.0 as u32) != 0 { + STATE_DEPTH_READ + } else { + STATE_DEPTH_WRITE + }; + let s_target_from_common = if dsv_flags & (D3D12_DSV_FLAG_READ_ONLY_STENCIL.0 as u32) != 0 { + STATE_DEPTH_READ + } else { + STATE_DEPTH_WRITE + }; + let op = { + let mut g = ENTRIES.lock().unwrap(); + let Some(e) = g.as_mut().and_then(|m| m.get_mut(&res)) else { + return; + }; + let d = e.depth_twin_dirty && e.depth_twin.is_some(); + let s = e.stencil_twin_dirty && e.stencil_twin.is_some(); + if !d && !s { + return; + } + if d { + e.depth_twin_dirty = false; + } + if s { + e.stencil_twin_dirty = false; + } + let depth = if d { + e.pc_states_depth + .iter_mut() + .enumerate() + .map(|(sub, st)| { + let before = *st; + let after = if before == STATE_COMMON { d_target_from_common } else { before }; + *st = after; + (sub as u32, before, after) + }) + .collect() + } else { + Vec::new() + }; + let stencil = if s { + e.pc_states_stencil + .iter_mut() + .enumerate() + .map(|(sub, st)| { + let before = *st; + let after = if before == STATE_COMMON { s_target_from_common } else { before }; + *st = after; + (sub as u32, before, after) + }) + .collect() + } else { + Vec::new() + }; + SyncOp::TwinToDepth { res, depth, stencil } + }; + execute_syncs(list, &[op]); +} + +/// Record a `ClearDepthStencilView` on a tracked depth+UAV resource so cleared planes are marked +/// depth-dirty (and no longer wait for a stale twin flush). +pub(super) fn on_clear_dsv(dsv_cpu: usize, clear_flags: u32) { + if !any() || dsv_cpu == 0 { + return; + } + let Some((res, _)) = DSV_TO_RES.lock().unwrap().as_ref().and_then(|m| m.get(&dsv_cpu).copied()) else { + return; + }; + let mut g = ENTRIES.lock().unwrap(); + if let Some(e) = g.as_mut().and_then(|m| m.get_mut(&res)) { + if clear_flags & 1 != 0 { + e.depth_twin_dirty = false; + e.depth_plane_dirty = true; + } + if clear_flags & 2 != 0 && e.plan.two_plane { + e.stencil_twin_dirty = false; + e.stencil_plane_dirty = true; + } + } +} + +/// RAII guard for `D3D12_TEXTURE_COPY_LOCATION` so `ManuallyDrop>` is +/// always dropped cleanly without leaking COM references. +struct OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION); + +impl Drop for OwnedCopyLoc { + fn drop(&mut self) { + unsafe { ManuallyDrop::drop(&mut self.0.pResource) }; + } +} + +/// Transition specific plane-local subresources on `list` from their tracked `before` state to +/// `target_override` (if `Some`) or their tracked `after` state (if `None`). +unsafe fn transition_plane_subs( + list: *mut c_void, + res: usize, + two_plane: bool, + per_plane: u32, + plane: u32, + subs: &[(u32, u32, u32)], + target_override: Option, +) { + if subs.is_empty() { + return; + } + if !two_plane && subs.len() == per_plane as usize { + let first_b = subs[0].1; + let first_a = target_override.unwrap_or(subs[0].2); + if subs.iter().all(|&(_, b, a)| b == first_b && target_override.unwrap_or(a) == first_a) { + if first_b != first_a { + list_x::transition(list, res, D3D12_RESOURCE_STATES(first_b as i32), D3D12_RESOURCE_STATES(first_a as i32)); + } + return; + } + } + let base = plane * per_plane; + let mut barriers = Vec::with_capacity(subs.len()); + for &(s, before, after) in subs { + let dst = target_override.unwrap_or(after); + if before == dst { + continue; + } + barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(&res), + Subresource: base + s, + StateBefore: D3D12_RESOURCE_STATES(before as i32), + StateAfter: D3D12_RESOURCE_STATES(dst as i32), + }), + }, + }); + } + if !barriers.is_empty() { + list_x::pc_resource_barriers(list, &barriers); + } +} + +/// Transition specific plane-local subresources from a common intermediate `from_state` back to +/// each subresource's tracked `after` state. +unsafe fn transition_plane_from( + list: *mut c_void, + res: usize, + two_plane: bool, + per_plane: u32, + plane: u32, + from_state: u32, + subs: &[(u32, u32, u32)], +) { + if subs.is_empty() { + return; + } + if !two_plane && subs.len() == per_plane as usize { + let first_a = subs[0].2; + if subs.iter().all(|&(_, _, a)| a == first_a) { + if from_state != first_a { + list_x::transition(list, res, D3D12_RESOURCE_STATES(from_state as i32), D3D12_RESOURCE_STATES(first_a as i32)); + } + return; + } + } + let base = plane * per_plane; + let mut barriers = Vec::with_capacity(subs.len()); + for &(s, _, after) in subs { + if from_state == after { + continue; + } + barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(&res), + Subresource: base + s, + StateBefore: D3D12_RESOURCE_STATES(from_state as i32), + StateAfter: D3D12_RESOURCE_STATES(after as i32), + }), + }, + }); + } + if !barriers.is_empty() { + list_x::pc_resource_barriers(list, &barriers); + } +} + +/// Copy specific subresources (`subs` local indices) directly between two format-compatible +/// single-plane resources via `CopyTextureRegion` (or `CopyResource` if all subresources match). +unsafe fn copy_direct_subs( + list: *mut c_void, + dst_res: &ID3D12Resource, + src_res: &ID3D12Resource, + per_plane: u32, + subs: &[(u32, u32, u32)], +) { + if subs.len() == per_plane as usize { + list_x::pc_copy_resource(list, dst_res.as_raw() as usize, src_res.as_raw() as usize); + return; + } + for &(s, _, _) in subs { + let dst_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(dst_res.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: s }, + }); + let src_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(src_res.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: s }, + }); + list_x::pc_copy_texture_region(list, &dst_loc.0, 0, 0, 0, &src_loc.0, std::ptr::null()); + } +} + +/// Copy specific subresources (`subs`) on one plane (`plane`: 0 or 1) between `depth_res` and +/// `twin_res` via a staging buffer using `CopyTextureRegion`. +unsafe fn copy_plane_through_buffer( + list: *mut c_void, + dev: &ID3D12Device, + dst_res: &ID3D12Resource, + dst_plane: u32, + src_res: &ID3D12Resource, + src_plane: u32, + per_plane: u32, + subs: &[(u32, u32, u32)], +) -> bool { + let dst_desc = dst_res.GetDesc(); + let src_desc = src_res.GetDesc(); + for &(s, _, _) in subs { + let src_sub = src_plane * per_plane + s; + let dst_sub = dst_plane * per_plane + s; + 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 + || src_fp.Footprint.Width != dst_fp.Footprint.Width + || src_fp.Footprint.Height != dst_fp.Footprint.Height + { + return false; + } + // Plane 1 of a two-plane depth-stencil texture (e.g. R24G8_TYPELESS stencil) can report a + // larger row pitch (e.g. 512 B) than a standalone R8_TYPELESS twin (256 B). D3D12 allows + // increasing Footprint.RowPitch to any 256-byte multiple >= the reported minimum, so + // unifying both footprints to `max(src_pitch, dst_pitch)` keeps every row aligned identically. + 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 needed = (row_pitch as u64).saturating_mul(src_rows as u64).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_res.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_res.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 +} + +// --------------------------------------------------------------------------------------- +// Internal fullscreen depth-write & compute depth-read pipelines for R24G8_TYPELESS +// (console D16_UNORM_S8_UINT / D24_UNORM_S8_UINT plane 0) +// --------------------------------------------------------------------------------------- + +struct SyncPipelines { + gfx_rs: ID3D12RootSignature, + gfx_pso: ID3D12PipelineState, + gfx_pso_steps: ID3D12PipelineState, + cs_rs: ID3D12RootSignature, + cs_pso: ID3D12PipelineState, +} + +unsafe impl Send for SyncPipelines {} + +static 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", + )?; + 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", + )?; + + // Graphics RS: [0] 2 root constants (b0), [1] 1 SRV table (t0) + let srv_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + 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 gfx_rs_desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: gfx_params.len() as u32, + pParameters: gfx_params.as_ptr(), + ..Default::default() + }; + let mut blob = None; + D3D12SerializeRootSignature(&gfx_rs_desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).ok()?; + let blob = blob?; + 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(real::orig_fn(dev_raw, 16)); + 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); + + // Compute RS: [0] 4 root constants (b0), [1] 1 SRV table (t0), [2] 1 UAV table (u0) + let uav_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + 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 cs_rs_desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: cs_params.len() as u32, + pParameters: cs_params.as_ptr(), + ..Default::default() + }; + let mut cs_blob = None; + D3D12SerializeRootSignature(&cs_rs_desc, 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); + + // Graphics PSO: write SV_Depth unconditionally, stencil disabled so plane 1 stays intact. + 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(real::orig_fn(dev_raw, 10)); + let mut gfx_pso_raw = std::ptr::null_mut(); + let hr_gfx = create_gfx(dev_raw, &gfx_desc, &ID3D12PipelineState::IID as *const _ as *const _, &mut gfx_pso_raw); + if hr_gfx < 0 || gfx_pso_raw.is_null() { + ManuallyDrop::drop(&mut gfx_desc.pRootSignature); + return None; + } + let gfx_pso = ID3D12PipelineState::from_raw(gfx_pso_raw); + + 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_gfx_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_gfx_steps < 0 || gfx_pso_steps_raw.is_null() { + return None; + } + let gfx_pso_steps = ID3D12PipelineState::from_raw(gfx_pso_steps_raw); + + 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(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); + + Some(SyncPipelines { gfx_rs, gfx_pso, gfx_pso_steps, cs_rs, cs_pso }) +} + +/// Ensure per-resource internal unadopted PC DSV + SRV/UAV descriptor heaps exist for `R24G8_TYPELESS` sync. +unsafe fn ensure_pass_heaps( + dev: &ID3D12Device, + depth_res: &ID3D12Resource, + twin_res: &ID3D12Resource, + e: &mut Entry, + twin_srv_fmt: i32, + twin_uav_fmt: i32, +) -> Option<(ID3D12DescriptorHeap, ID3D12DescriptorHeap)> { + 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(real::orig_fn(dev_raw, 14)); + let inc_size: IncSizeFn = std::mem::transmute(real::orig_fn(dev_raw, 15)); + 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 create_dsv: CreateDsvFn = std::mem::transmute(real::orig_fn(dev_raw, 21)); + + let mips = e.mip_levels as u32; + let slices = e.array_size as u32; + if e.pass_dsv_heap.is_none() { + let desc = D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + NumDescriptors: mips * slices, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }; + let mut raw = std::ptr::null_mut(); + if create_heap(dev_raw, &desc, &ID3D12DescriptorHeap::IID as *const _ as *const _, &mut raw) < 0 || raw.is_null() { + return None; + } + let dsv_heap = ID3D12DescriptorHeap::from_raw(raw); + let inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + let 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 }, + }, + }; + let idx = (m * slices + a) as usize; + create_dsv(dev_raw, depth_res.as_raw(), &dsv, base + idx * inc); + } + } + e.pass_dsv_heap = Some(dsv_heap); + } + if e.pass_srv_uav_heap.is_none() { + // Slot 0: twin SRV, Slot 1: depth plane 0 SRV (R24_UNORM_X8_TYPELESS), Slots 2..2+mips: twin UAV per mip + let total = 2 + mips; + let desc = D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: total, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }; + let mut raw = std::ptr::null_mut(); + if create_heap(dev_raw, &desc, &ID3D12DescriptorHeap::IID as *const _ as *const _, &mut raw) < 0 || raw.is_null() { + return None; + } + let heap = ID3D12DescriptorHeap::from_raw(raw); + let inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let base = heap.GetCPUDescriptorHandleForHeapStart().ptr; + let twin_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_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, twin_res.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_res.as_raw(), &depth_srv, base + inc); + for m in 0..mips { + let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_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, twin_res.as_raw(), std::ptr::null_mut(), &uav, base + (2 + m as usize) * inc); + } + e.pass_srv_uav_heap = Some(heap); + } + Some((e.pass_dsv_heap.clone()?, e.pass_srv_uav_heap.clone()?)) +} + +unsafe fn get_pipelines( + dev: &ID3D12Device, +) -> Option<(ID3D12RootSignature, ID3D12PipelineState, ID3D12PipelineState, ID3D12RootSignature, ID3D12PipelineState)> { + let key = dev.as_raw() as usize; + let mut g = PIPELINES.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + let entry = map.entry(key).or_insert_with(|| build_sync_pipelines(dev)); + let p = entry.as_ref()?; + Some((p.gfx_rs.clone(), p.gfx_pso.clone(), p.gfx_pso_steps.clone(), p.cs_rs.clone(), p.cs_pso.clone())) +} + +/// Execute queued depth+UAV synchronization ops on a `DIRECT` command list. +pub(super) unsafe fn execute_syncs(list: *mut c_void, ops: &[SyncOp]) { + if ops.is_empty() || list.is_null() { + return; + } + let Some(dev) = list_x::device_of_list(list) else { + return; + }; + 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(real::orig_fn(dev_raw, 15)); + let mut clobbered_gfx = false; + let mut clobbered_cs = false; + + for op in ops { + match op { + SyncOp::TransitionOnly { res, depth, stencil } => { + let res = *res; + let Some((two_plane, per_plane)) = ({ + let g = ENTRIES.lock().unwrap(); + g.as_ref().and_then(|m| m.get(&res)).map(|e| (e.plan.two_plane, e.subresources_per_plane())) + }) else { + continue; + }; + if !depth.is_empty() { + transition_plane_subs(list, res, two_plane, per_plane, 0, depth, None); + } + if two_plane && !stencil.is_empty() { + transition_plane_subs(list, res, two_plane, per_plane, 1, stencil, None); + } + } + SyncOp::TwinToDepth { res, depth, stencil } => { + let res = *res; + let res_ptr = res as *mut c_void; + let Some(depth_res) = ID3D12Resource::from_raw_borrowed(&res_ptr) else { + continue; + }; + let snapshot = { + let g = ENTRIES.lock().unwrap(); + g.as_ref().and_then(|m| m.get(&res)).map(|e| { + ( + e.plan, + e.width, + e.height, + e.array_size, + e.mip_levels, + e.subresources_per_plane(), + e.depth_twin.clone(), + e.stencil_twin.clone(), + ) + }) + }; + let Some((plan, width, height, array_size, mip_levels, per_plane, depth_twin, stencil_twin)) = snapshot else { + continue; + }; + + if plan.two_plane { + static SYNC_T2D_TWO_PLANE: AtomicU64 = AtomicU64::new(0); + let k = SYNC_T2D_TWO_PLANE.fetch_add(1, Ordering::Relaxed); + if k < 8 || k.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: depth+UAV TwinToDepth sync #{k} on two_plane {res:#x} ({width}x{height}, depth_subs={}, stencil_subs={}, depth_twin={}, stencil_twin={}, kind={:?})", + depth.len(), + stencil.len(), + depth_twin.is_some(), + stencil_twin.is_some(), + plan.depth_sync, + ); + } + } + + if !depth.is_empty() { + if let Some(twin) = depth_twin { + match plan.depth_sync { + DepthSyncKind::DirectCopy => { + let twin_raw = twin.as_raw() as usize; + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + transition_plane_subs(list, res, false, per_plane, 0, depth, Some(STATE_COPY_DEST)); + copy_direct_subs(list, depth_res, &twin, per_plane, depth); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_plane_from(list, res, false, per_plane, 0, STATE_COPY_DEST, depth); + } + DepthSyncKind::BufferThrough => { + let twin_raw = twin.as_raw() as usize; + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + transition_plane_subs(list, res, true, per_plane, 0, depth, Some(STATE_COPY_DEST)); + let _ = copy_plane_through_buffer(list, &dev, depth_res, 0, &twin, 0, per_plane, depth); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_plane_from(list, res, true, per_plane, 0, STATE_COPY_DEST, depth); + } + DepthSyncKind::FullscreenPass { steps, twin_srv_fmt, twin_uav_fmt } => { + let heaps = { + let mut g = ENTRIES.lock().unwrap(); + g.as_mut().and_then(|m| m.get_mut(&res)).and_then(|e| ensure_pass_heaps(&dev, depth_res, &twin, e, twin_srv_fmt, twin_uav_fmt)) + }; + if let (Some((gfx_rs, gfx_pso, gfx_pso_steps, _, _)), Some((dsv_heap, srv_heap))) = (get_pipelines(&dev), heaps) { + let twin_raw = twin.as_raw() as usize; + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATES(STATE_SRV_ALL as i32)); + transition_plane_subs(list, res, true, per_plane, 0, depth, Some(STATE_DEPTH_WRITE)); + let srv_raw = srv_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_gfx_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 30)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 25)); + let set_topo: unsafe extern "system" fn(*mut c_void, u32) = std::mem::transmute(real::orig_fn(list, 20)); + let set_gfx_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(real::orig_fn(list, 32)); + let set_vp: unsafe extern "system" fn(*mut c_void, u32, *const D3D12_VIEWPORT) = std::mem::transmute(real::orig_fn(list, 21)); + let set_sc: unsafe extern "system" fn(*mut c_void, u32, *const RECT) = std::mem::transmute(real::orig_fn(list, 22)); + let set_rt: unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize) = std::mem::transmute(real::orig_fn(list, 46)); + let set_gfx_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(real::orig_fn(list, 36)); + let draw: unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32) = std::mem::transmute(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; + let mips_u32 = mip_levels as u32; + for &(local_sub, _, _) in depth { + let m = local_sub % mips_u32; + let a = local_sub / mips_u32; + let mw = ((width as u32) >> m).max(1); + let mh = (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 * array_size as 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); + } + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATES(STATE_SRV_ALL as i32), D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_plane_from(list, res, true, per_plane, 0, STATE_DEPTH_WRITE, depth); + clobbered_gfx = true; + } else { + transition_plane_subs(list, res, true, per_plane, 0, depth, None); + } + } + } + } else { + transition_plane_subs(list, res, plan.two_plane, per_plane, 0, depth, None); + } + } + + if plan.two_plane && !stencil.is_empty() { + if let Some(twin) = stencil_twin { + let twin_raw = twin.as_raw() as usize; + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + transition_plane_subs(list, res, true, per_plane, 1, stencil, Some(STATE_COPY_DEST)); + let _ = copy_plane_through_buffer(list, &dev, depth_res, 1, &twin, 0, per_plane, stencil); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_plane_from(list, res, true, per_plane, 1, STATE_COPY_DEST, stencil); + } else { + transition_plane_subs(list, res, true, per_plane, 1, stencil, None); + } + } + } + SyncOp::DepthToTwin { res, depth, stencil } => { + let res = *res; + let res_ptr = res as *mut c_void; + let Some(depth_res) = ID3D12Resource::from_raw_borrowed(&res_ptr) else { + continue; + }; + let snapshot = { + let g = ENTRIES.lock().unwrap(); + g.as_ref().and_then(|m| m.get(&res)).map(|e| { + ( + e.plan, + e.width, + e.height, + e.array_size, + e.mip_levels, + e.subresources_per_plane(), + e.depth_twin.clone(), + e.stencil_twin.clone(), + ) + }) + }; + let Some((plan, width, height, array_size, mip_levels, per_plane, depth_twin, stencil_twin)) = snapshot else { + continue; + }; + + if plan.two_plane { + static SYNC_D2T_TWO_PLANE: AtomicU64 = AtomicU64::new(0); + let k = SYNC_D2T_TWO_PLANE.fetch_add(1, Ordering::Relaxed); + if k < 8 || k.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: depth+UAV DepthToTwin sync #{k} on two_plane {res:#x} ({width}x{height}, depth_subs={}, stencil_subs={}, depth_twin={}, stencil_twin={}, kind={:?})", + depth.len(), + stencil.len(), + depth_twin.is_some(), + stencil_twin.is_some(), + plan.depth_sync, + ); + } + } + + if !depth.is_empty() { + if let Some(twin) = depth_twin { + match plan.depth_sync { + DepthSyncKind::DirectCopy => { + let twin_raw = twin.as_raw() as usize; + transition_plane_subs(list, res, false, per_plane, 0, depth, Some(STATE_COPY_SOURCE)); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + copy_direct_subs(list, &twin, depth_res, per_plane, depth); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_plane_from(list, res, false, per_plane, 0, STATE_COPY_SOURCE, depth); + } + DepthSyncKind::BufferThrough => { + let twin_raw = twin.as_raw() as usize; + transition_plane_subs(list, res, true, per_plane, 0, depth, Some(STATE_COPY_SOURCE)); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + let _ = copy_plane_through_buffer(list, &dev, &twin, 0, depth_res, 0, per_plane, depth); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_plane_from(list, res, true, per_plane, 0, STATE_COPY_SOURCE, depth); + } + DepthSyncKind::FullscreenPass { twin_srv_fmt, twin_uav_fmt, .. } => { + let heaps = { + let mut g = ENTRIES.lock().unwrap(); + g.as_mut().and_then(|m| m.get_mut(&res)).and_then(|e| ensure_pass_heaps(&dev, depth_res, &twin, e, twin_srv_fmt, twin_uav_fmt)) + }; + if let (Some((_, _, _, cs_rs, cs_pso)), Some((_, srv_heap))) = (get_pipelines(&dev), heaps) { + transition_plane_subs(list, res, true, per_plane, 0, depth, Some(STATE_SRV_ALL)); + let srv_raw = srv_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)); + + 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 mips_u32 = mip_levels as u32; + let mut dispatched_mips = vec![false; mips_u32 as usize]; + for &(local_sub, _, _) in depth { + let m = local_sub % mips_u32; + if dispatched_mips[m as usize] { + continue; + } + dispatched_mips[m as usize] = true; + let mw = ((width as u32) >> m).max(1); + let mh = (height >> m).max(1); + let c = [mw, mh, array_size as 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), array_size as u32); + } + // Order internal compute UAV writes to `twin` before subsequent title dispatches. + let twin_raw = twin.as_raw() as usize; + let uav_barrier = 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(&twin_raw), + }), + }, + }; + list_x::pc_resource_barriers(list, &[uav_barrier]); + transition_plane_from(list, res, true, per_plane, 0, STATE_SRV_ALL, depth); + clobbered_cs = true; + } else { + transition_plane_subs(list, res, true, per_plane, 0, depth, None); + } + } + } + } else { + transition_plane_subs(list, res, plan.two_plane, per_plane, 0, depth, None); + } + } + + if plan.two_plane && !stencil.is_empty() { + if let Some(twin) = stencil_twin { + let twin_raw = twin.as_raw() as usize; + transition_plane_subs(list, res, true, per_plane, 1, stencil, Some(STATE_COPY_SOURCE)); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + let _ = copy_plane_through_buffer(list, &dev, &twin, 0, depth_res, 1, per_plane, stencil); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_plane_from(list, res, true, per_plane, 1, STATE_COPY_SOURCE, stencil); + } else { + transition_plane_subs(list, res, true, per_plane, 1, stencil, None); + } + } + } + } + } + + if clobbered_gfx || clobbered_cs { + list_x::restore_after_internal_pass(list, clobbered_gfx, clobbered_cs); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn twin_plans_cover_console_depth_formats() { + let d32 = plan_for_console_format(40).expect("D32_FLOAT"); + assert_eq!((d32.depth_twin_fmt, d32.stencil_twin_fmt, d32.depth_sync, d32.two_plane), (39, None, DepthSyncKind::DirectCopy, false)); + + let d16 = plan_for_console_format(55).expect("D16_UNORM"); + assert_eq!((d16.depth_twin_fmt, d16.stencil_twin_fmt, d16.depth_sync, d16.two_plane), (53, None, DepthSyncKind::DirectCopy, false)); + + let d32s8 = plan_for_console_format(20).expect("D32_FLOAT_S8X24_UINT"); + assert_eq!((d32s8.depth_twin_fmt, d32s8.stencil_twin_fmt, d32s8.depth_sync, d32s8.two_plane), (39, Some(60), DepthSyncKind::BufferThrough, true)); + + let d16s8 = plan_for_console_format(118).expect("D16_UNORM_S8_UINT"); + assert_eq!(d16s8.depth_twin_fmt, 53); + assert_eq!(d16s8.stencil_twin_fmt, Some(60)); + assert!(d16s8.two_plane); + assert_eq!(d16s8.depth_sync, DepthSyncKind::FullscreenPass { steps: true, twin_srv_fmt: 57, twin_uav_fmt: 56 }); + + let d24s8 = plan_for_console_format(45).expect("D24_UNORM_S8_UINT"); + assert_eq!(d24s8.depth_twin_fmt, 39); + assert_eq!(d24s8.stencil_twin_fmt, Some(60)); + assert_eq!(d24s8.depth_sync, DepthSyncKind::FullscreenPass { steps: false, twin_srv_fmt: 41, twin_uav_fmt: 41 }); + + assert!(plan_for_console_format(28).is_none(), "color format has no depth twin plan"); + } + + #[test] + fn uav_format_and_plane_classification() { + // Stencil plane detection via format or explicit PlaneSlice == 1 + assert!(is_stencil_uav_format(62, 0)); // R8_UINT + assert!(is_stencil_uav_format(120, 0)); // console X16_TYPELESS_G8_UINT + assert!(is_stencil_uav_format(47, 0)); // X24_TYPELESS_G8_UINT + assert!(is_stencil_uav_format(22, 0)); // X32_TYPELESS_G8X24_UINT + assert!(is_stencil_uav_format(0, 1)); // explicit PlaneSlice 1 + assert!(!is_stencil_uav_format(56, 0)); // R16_UNORM depth + assert!(!is_stencil_uav_format(41, 0)); // R32_FLOAT depth + + // Legal typed UAV formats on each typeless twin + assert_eq!(twin_uav_format(60, 120), 62); + assert_eq!(twin_uav_format(60, 61), 61); + assert_eq!(twin_uav_format(53, 118), 56); + assert_eq!(twin_uav_format(53, 57), 57); + assert_eq!(twin_uav_format(39, 40), 41); + assert_eq!(twin_uav_format(39, 42), 42); + + // Subresource plane split (2 mips * 3 slices = 6 subresources per plane) + assert_eq!(plane_for_subresource(D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, 2, 3, true), PlaneMask::Both); + assert_eq!(plane_for_subresource(0, 2, 3, true), PlaneMask::Depth); + assert_eq!(plane_for_subresource(5, 2, 3, true), PlaneMask::Depth); + assert_eq!(plane_for_subresource(6, 2, 3, true), PlaneMask::Stencil); + assert_eq!(plane_for_subresource(11, 2, 3, true), PlaneMask::Stencil); + assert_eq!(plane_for_subresource(D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, 2, 3, false), PlaneMask::Depth); + } + + #[test] + fn state_machine_handles_split_and_async_compute_transitions() { + let plan = plan_for_console_format(118).unwrap(); + let mut e = Entry::new(0x1, plan, 1920, 1080, 1, 1, STATE_DEPTH_WRITE, true); + + // Without twins allocated yet, leaving UAV becomes a plain TransitionOnly (DEPTH_WRITE -> DEPTH_READ) + let (pass, uav, op) = decide_transition(&mut e, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, STATE_UAV, 0x20, 0, true); + assert!(!pass && uav); + assert_eq!( + op, + Some(SyncOp::TransitionOnly { + res: 0, + depth: vec![(0, STATE_DEPTH_WRITE, 0x20)], + stencil: vec![(0, STATE_DEPTH_WRITE, 0x20)], + }) + ); + assert_eq!((e.pc_states_depth[0], e.pc_states_stencil[0]), (0x20, 0x20)); + + // Split barrier BEGIN_ONLY touching UAV is suppressed, and END_ONLY performs the atomic transition + let (pass, uav, op) = decide_transition(&mut e, 1, 0x20, STATE_UAV, 1, true); + assert!(!pass && !uav && op.is_none()); + assert!(e.split_uav_stencil[0] && !e.split_uav_depth[0]); + + let (pass, uav, op) = decide_transition(&mut e, 1, 0x20, STATE_UAV, 2, true); + assert!(!pass && uav); + assert!(!e.split_uav_stencil[0]); + assert_eq!( + op, + Some(SyncOp::TransitionOnly { + res: 0, + depth: vec![], + stencil: vec![(0, 0x20, STATE_DEPTH_WRITE)], + }) + ); + // Plane 0 stayed in DEPTH_READ while plane 1 moved to DEPTH_WRITE + assert_eq!((e.pc_states_depth[0], e.pc_states_stencil[0]), (0x20, STATE_DEPTH_WRITE)); + + // Multi-mip per-subresource tracking: transitioning only mip 1 must leave mip 0 untouched + // and entering UAV must use each subresource's tracked PC state as StateBefore (not title `before`). + let mut multi = Entry::new(0x1, plan, 512, 512, 1, 2, STATE_DEPTH_WRITE, false); + let (pass, _, op) = decide_transition(&mut multi, 1, STATE_DEPTH_WRITE, 0x20, 0, true); + assert!(pass && op.is_none()); + assert_eq!(multi.pc_states_depth, vec![STATE_DEPTH_WRITE, 0x20]); + let (pass, uav, op) = decide_transition(&mut multi, 1, STATE_COMMON, STATE_UAV, 0, true); + assert!(!pass && uav); + assert_eq!( + op, + Some(SyncOp::TransitionOnly { + res: 0, + depth: vec![(1, 0x20, STATE_DEPTH_WRITE)], + stencil: vec![], + }), + "single-subresource UAV entry transitions only mip 1 from its tracked PC state 0x20" + ); + assert_eq!(multi.pc_states_depth, vec![STATE_DEPTH_WRITE, STATE_DEPTH_WRITE]); + + // On a COMPUTE list, UAV transitions are suppressed with a global UAV barrier (no invalid DEPTH state) + let (pass, uav, op) = decide_transition(&mut e, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, STATE_UAV, STATE_COMMON, 0, false); + assert!(!pass && uav && op.is_none()); + } + + #[test] + fn uav_barrier_returns_zero_for_untracked_resources() { + assert_eq!(on_uav_barrier(0), [0, 0]); + assert_eq!(on_uav_barrier(0xDEAD_BEE0), [0, 0]); + } + + #[test] + fn enhanced_barriers_handle_texture_subresources_uav_and_discard() { + // Layout + access -> valid PC resource state (never STATE_UAV or buffer-only bits) + assert_eq!( + enhanced_layout_to_pc_state(D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ, D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ), + STATE_DEPTH_READ + ); + assert_eq!( + enhanced_layout_to_pc_state(D3D12_BARRIER_LAYOUT_COMMON, D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ), + STATE_DEPTH_READ + ); + assert_eq!( + enhanced_layout_to_pc_state(D3D12_BARRIER_LAYOUT_COMMON, D3D12_BARRIER_ACCESS_SHADER_RESOURCE), + STATE_SRV_ALL + ); + assert_eq!( + enhanced_layout_to_pc_state(D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS), + STATE_DEPTH_WRITE + ); + assert_eq!( + enhanced_layout_to_pc_state(D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS), + STATE_DEPTH_WRITE + ); + + let plan = plan_for_console_format(44).unwrap(); + let mut e = Entry::new(0x1, plan, 2560, 1440, 1, 2, STATE_COMMON, false); + let all = D3D12_BARRIER_SUBRESOURCE_RANGE { + IndexOrFirstMipLevel: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + NumMipLevels: 0, + FirstArraySlice: 0, + NumArraySlices: 0, + FirstPlane: 0, + NumPlanes: 0, + }; + assert_eq!(resolve_enhanced_subresources(&e, &all), (vec![0, 1], vec![0, 1])); + + // Plane-specific range: stencil plane only, mip 1 only + let stencil_mip1 = D3D12_BARRIER_SUBRESOURCE_RANGE { + IndexOrFirstMipLevel: 1, + NumMipLevels: 1, + FirstArraySlice: 0, + NumArraySlices: 1, + FirstPlane: 1, + NumPlanes: 1, + }; + assert_eq!(resolve_enhanced_subresources(&e, &stencil_mip1), (vec![], vec![1])); + + // Without twins materialized yet, leaving UAV produces TransitionOnly -> DEPTH_READ + let op = decide_enhanced_texture_barrier( + &mut e, + D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ, + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ, + &all, + D3D12_TEXTURE_BARRIER_FLAG_NONE, + true, + ); + assert_eq!( + op, + Some(SyncOp::TransitionOnly { + res: 0, + depth: vec![(0, STATE_COMMON, STATE_DEPTH_READ), (1, STATE_COMMON, STATE_DEPTH_READ)], + stencil: vec![(0, STATE_COMMON, STATE_DEPTH_READ), (1, STATE_COMMON, STATE_DEPTH_READ)], + }) + ); + assert_eq!(e.pc_states_depth, vec![STATE_DEPTH_READ, STATE_DEPTH_READ]); + assert_eq!(e.pc_states_stencil, vec![STATE_DEPTH_READ, STATE_DEPTH_READ]); + + // DISCARD entering DEPTH_STENCIL_WRITE marks plane dirty and transitions DEPTH_READ -> DEPTH_WRITE + let op = decide_enhanced_texture_barrier( + &mut e, + D3D12_BARRIER_ACCESS_NO_ACCESS, + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE, + D3D12_BARRIER_LAYOUT_UNDEFINED, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE, + &all, + D3D12_TEXTURE_BARRIER_FLAG_DISCARD, + true, + ); + assert_eq!( + op, + Some(SyncOp::TransitionOnly { + res: 0, + depth: vec![(0, STATE_DEPTH_READ, STATE_DEPTH_WRITE), (1, STATE_DEPTH_READ, STATE_DEPTH_WRITE)], + stencil: vec![(0, STATE_DEPTH_READ, STATE_DEPTH_WRITE), (1, STATE_DEPTH_READ, STATE_DEPTH_WRITE)], + }) + ); + assert!(e.depth_plane_dirty && e.stencil_plane_dirty); + + // Non-DIRECT list never returns a SyncOp + let op = decide_enhanced_texture_barrier( + &mut e, + D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ, + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ, + &all, + D3D12_TEXTURE_BARRIER_FLAG_NONE, + false, + ); + assert!(op.is_none()); + } + + /// GPU: verify `D24_UNORM_S8_UINT` (console fmt 44) and `D16_UNORM_S8_UINT` (console fmt 118) + /// compute UAV writes (`permutation / 65535.0` depth + per-pixel stencil) synchronize cleanly + /// via BOTH enhanced texture barriers (`#146` `D3D12_TEXTURE_BARRIER`) AND global UAV barriers + /// + `before_bind_dsv`, passing exact `DepthFunc = EQUAL` draws while preserving stencil. + #[test] + fn gpu_d24s8_and_d16s8_enhanced_barrier_twin_sync_passes_equal_depth_test() { + unsafe { + let dev: ID3D12Device = { + use windows::Win32::Graphics::Dxgi::*; + if std::env::var_os("XCL_D3D12_DEBUG").is_some() { + let _ = crate::gpu::agility::enable_debug_layer(); + } + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let adapter: Option = if sel == crate::gpu::adapter::Selector::Warp { + let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) else { + return crate::gpu::recomp::runner::skip_test("no DXGI factory"); + }; + let Ok(warp) = factory.EnumWarpAdapter::() else { + return crate::gpu::recomp::runner::skip_test("no WARP adapter"); + }; + Some(warp.cast().unwrap()) + } else { + None + }; + let Ok(d) = crate::gpu::agility::create_device(adapter.as_ref(), windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + d + }; + let q: 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 mut fence_val = 0u64; + + let wait_gpu = |q: &ID3D12CommandQueue, fence: &ID3D12Fence, val: &mut u64| { + *val += 1; + q.Signal(fence, *val).unwrap(); + while fence.GetCompletedValue() < *val { + std::thread::yield_now(); + } + }; + + // Compute shader writing 4 quadrant permutations (1, 17, 42, 120) / 65535.0 to depth twin + // and (0x11, 0x22, 0x5A, 0xA5) to stencil twin; c0 overrides quadrant 0 permutation. + let cs_write = compile_sm5( + "RWTexture2D dstD : register(u0);\n\ + RWTexture2D dstS : register(u1);\n\ + cbuffer C : register(b0) { uint q0_perm; };\n\ + [numthreads(8, 8, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + uint q = (id.x >= 8 ? 1u : 0u) + (id.y >= 8 ? 2u : 0u);\n\ + uint perm = (q == 0u) ? q0_perm : ((q == 1u) ? 17u : ((q == 2u) ? 42u : 120u));\n\ + uint st = (q == 0u) ? 0x11u : ((q == 1u) ? 0x22u : ((q == 2u) ? 0x5Au : 0xA5u));\n\ + dstD[id.xy] = float(perm) / 65535.0;\n\ + dstS[id.xy] = st;\n\ + }\n", + "cs_5_0", + ) + .expect("cs_write"); + let uav_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + NumDescriptors: 2, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + 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: 1 }, + }, + }, + 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 rs_blob = None; + D3D12SerializeRootSignature( + &D3D12_ROOT_SIGNATURE_DESC { NumParameters: 2, pParameters: cs_params.as_ptr(), ..Default::default() }, + D3D_ROOT_SIGNATURE_VERSION_1, + &mut rs_blob, + None, + ) + .unwrap(); + let rs_blob = rs_blob.unwrap(); + let cs_rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(rs_blob.GetBufferPointer() as *const u8, rs_blob.GetBufferSize())).unwrap(); + let mut cs_pso_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(cs_rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs_write.as_ptr() as _, BytecodeLength: cs_write.len() }, + ..Default::default() + }; + let cs_pso: ID3D12PipelineState = dev.CreateComputePipelineState(&cs_pso_desc).unwrap(); + ManuallyDrop::drop(&mut cs_pso_desc.pRootSignature); + + // Graphics EQUAL test shader: VS outputs z = target_perm / 65535.0, PS writes solid 0xFF red. + let eq_vs = compile_sm5( + "cbuffer C : register(b0) { uint target_perm; };\n\ + 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, float(target_perm) / 65535.0, 1.0);\n\ + }\n", + "vs_5_0", + ) + .expect("eq_vs"); + let eq_ps = compile_sm5("float4 main() : SV_Target { return float4(1.0, 0.0, 0.0, 1.0); }\n", "ps_5_0").expect("eq_ps"); + let eq_param = D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: D3D12_SHADER_VISIBILITY_VERTEX, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 1 }, + }, + }; + let mut eq_rs_blob = None; + D3D12SerializeRootSignature( + &D3D12_ROOT_SIGNATURE_DESC { NumParameters: 1, pParameters: &eq_param, ..Default::default() }, + D3D_ROOT_SIGNATURE_VERSION_1, + &mut eq_rs_blob, + None, + ) + .unwrap(); + let eq_rs_blob = eq_rs_blob.unwrap(); + let eq_rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(eq_rs_blob.GetBufferPointer() as *const u8, eq_rs_blob.GetBufferSize())).unwrap(); + let mut eq_pso_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(eq_rs.clone())), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: eq_vs.as_ptr() as _, BytecodeLength: eq_vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: eq_ps.as_ptr() as _, BytecodeLength: eq_ps.len() }, + SampleMask: u32::MAX, + BlendState: D3D12_BLEND_DESC { + RenderTarget: [ + D3D12_RENDER_TARGET_BLEND_DESC { RenderTargetWriteMask: 0xF, ..Default::default() }, + Default::default(), Default::default(), Default::default(), + Default::default(), Default::default(), Default::default(), Default::default(), + ], + ..Default::default() + }, + 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: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_EQUAL, + StencilEnable: false.into(), + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: [DXGI_FORMAT_R8G8B8A8_UNORM, Default::default(), Default::default(), Default::default(), Default::default(), Default::default(), Default::default(), Default::default()], + DSVFormat: DXGI_FORMAT_D24_UNORM_S8_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + let eq_pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&eq_pso_desc).unwrap(); + ManuallyDrop::drop(&mut eq_pso_desc.pRootSignature); + + // Helper descriptors & heaps + let rt_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 16, + Height: 16, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let mut rt: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &rt_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut rt, + ) + .unwrap(); + let rt = rt.unwrap(); + + let rtv_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() }).unwrap(); + let rtv_cpu = rtv_heap.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(&rt, None, rtv_cpu); + + let dsv_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, NumDescriptors: 1, ..Default::default() }).unwrap(); + let dsv_cpu = dsv_heap.GetCPUDescriptorHandleForHeapStart(); + + let uav_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .unwrap(); + let uav_cpu_base = uav_heap.GetCPUDescriptorHandleForHeapStart().ptr; + let uav_gpu_base = uav_heap.GetGPUDescriptorHandleForHeapStart().ptr; + let uav_inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + + let rb_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 16 * 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut rb_rt: Option = None; + let mut rb_st: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rb_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb_rt).unwrap(); + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rb_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb_st).unwrap(); + let (rb_rt, rb_st) = (rb_rt.unwrap(), rb_st.unwrap()); + + let pc_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 16, + Height: 16, + 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 mut rt_fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + dev.GetCopyableFootprints(&rt_desc, 0, 1, 0, Some(&mut rt_fp), None, None, None); + let mut st_fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + dev.GetCopyableFootprints(&pc_desc, 1, 1, 0, Some(&mut st_fp), None, None, None); + + // Create both depth-stencil targets BEFORE adopting `dev` so test heaps/resources stay + // pure unadopted PC COM objects (no console vtable ABI or global UMA side effects). + let mut depth_targets: Vec<(u32, ID3D12Resource)> = Vec::new(); + for console_fmt in [44u32, 118u32] { + let mut depth_res: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &pc_desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut depth_res, + ) + .unwrap(); + depth_targets.push((console_fmt, depth_res.unwrap())); + } + + // Adopt dev + list so `depth_uav` internal helpers use `real::orig_fn` cleanly. + real::adopt(dev.as_raw(), real::Kind::Device); + real::adopt(list.as_raw(), real::Kind::CommandList); + list_x::on_create(list.as_raw(), alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + + type CreateUavOrig = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + type CreateDsvOrig = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_DEPTH_STENCIL_VIEW_DESC, usize); + let create_uav_orig: CreateUavOrig = std::mem::transmute(real::orig_fn(dev.as_raw(), 19)); + let create_dsv_orig: CreateDsvOrig = std::mem::transmute(real::orig_fn(dev.as_raw(), 21)); + + for (console_fmt, depth_res) in depth_targets { + let mut console_desc = [0u8; 0x38]; + console_desc[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + console_desc[0x10..0x18].copy_from_slice(&16u64.to_le_bytes()); + console_desc[0x18..0x1C].copy_from_slice(&16u32.to_le_bytes()); + console_desc[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + console_desc[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + console_desc[0x20..0x24].copy_from_slice(&console_fmt.to_le_bytes()); + console_desc[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + console_desc[0x30..0x34].copy_from_slice(&6u32.to_le_bytes()); // DEPTH_STENCIL | UAV + + register_if_depth_uav(dev.as_raw(), depth_res.as_raw(), &console_desc, STATE_COMMON, STATE_COMMON); + + let dsv_desc = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D24_UNORM_S8_UINT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + Flags: D3D12_DSV_FLAG_READ_ONLY_DEPTH | D3D12_DSV_FLAG_READ_ONLY_STENCIL, + ..Default::default() + }; + create_dsv_orig(dev.as_raw(), depth_res.as_raw(), &dsv_desc, dsv_cpu.ptr); + note_dsv(dsv_cpu.ptr, depth_res.as_raw() as usize, dsv_desc.Flags.0 as u32); + + let depth_uav_req = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R24_UNORM_X8_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let stencil_uav_req = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_X24_TYPELESS_G8_UINT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let (d_twin_raw, d_uav_desc) = resolve_uav(dev.as_raw(), depth_res.as_raw(), Some(&depth_uav_req)).expect("depth twin"); + let (s_twin_raw, s_uav_desc) = resolve_uav(dev.as_raw(), depth_res.as_raw(), Some(&stencil_uav_req)).expect("stencil twin"); + create_uav_orig(dev.as_raw(), d_twin_raw, std::ptr::null_mut(), &d_uav_desc, uav_cpu_base); + create_uav_orig(dev.as_raw(), s_twin_raw, std::ptr::null_mut(), &s_uav_desc, uav_cpu_base + uav_inc); + + // --- Phase 1: Compute writes twins -> Enhanced #146 Texture Barrier (UAV -> DEPTH_READ) -> EQUAL draw (perm 42) --- + let set_heaps_orig: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list.as_raw(), 28)); + let set_cs_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list.as_raw(), 29)); + let set_gfx_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list.as_raw(), 30)); + let set_cs_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(real::orig_fn(list.as_raw(), 31)); + let set_cs_const: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list.as_raw(), 33)); + let set_gfx_const: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list.as_raw(), 34)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list.as_raw(), 25)); + let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list.as_raw(), 14)); + let draw: unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32) = std::mem::transmute(real::orig_fn(list.as_raw(), 12)); + let set_topo: unsafe extern "system" fn(*mut c_void, u32) = std::mem::transmute(real::orig_fn(list.as_raw(), 20)); + let set_vp: unsafe extern "system" fn(*mut c_void, u32, *const D3D12_VIEWPORT) = std::mem::transmute(real::orig_fn(list.as_raw(), 21)); + let set_sc: unsafe extern "system" fn(*mut c_void, u32, *const RECT) = std::mem::transmute(real::orig_fn(list.as_raw(), 22)); + let set_rt: unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize) = std::mem::transmute(real::orig_fn(list.as_raw(), 46)); + let clear_rt: unsafe extern "system" fn(*mut c_void, usize, *const [f32; 4], u32, *const RECT) = std::mem::transmute(real::orig_fn(list.as_raw(), 48)); + + let uav_heap_raw = uav_heap.as_raw() as usize; + set_heaps_orig(list.as_raw(), 1, &uav_heap_raw); + set_cs_rs(list.as_raw(), cs_rs.as_raw()); + set_pso(list.as_raw(), cs_pso.as_raw()); + set_cs_const(list.as_raw(), 0, 1, 0); // q0_perm = 1 + set_cs_table(list.as_raw(), 1, uav_gpu_base); + dispatch(list.as_raw(), 2, 2, 1); + + // Enhanced #146 Texture Barrier: UNORDERED_ACCESS -> DEPTH_STENCIL_READ + let tb = D3D12_TEXTURE_BARRIER { + SyncBefore: D3D12_BARRIER_SYNC_COMPUTE_SHADING, + SyncAfter: D3D12_BARRIER_SYNC_DEPTH_STENCIL, + AccessBefore: D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + AccessAfter: D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ, + LayoutBefore: D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + LayoutAfter: D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ, + pResource: ManuallyDrop::new(Some(depth_res.clone())), + Subresources: D3D12_BARRIER_SUBRESOURCE_RANGE { + IndexOrFirstMipLevel: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + NumMipLevels: 0, + FirstArraySlice: 0, + NumArraySlices: 0, + FirstPlane: 0, + NumPlanes: 0, + }, + Flags: D3D12_TEXTURE_BARRIER_FLAG_NONE, + }; + let grp = D3D12_BARRIER_GROUP { + Type: D3D12_BARRIER_TYPE_TEXTURE, + NumBarriers: 1, + Anonymous: D3D12_BARRIER_GROUP_0 { pTextureBarriers: &tb }, + }; + let mut ops = Vec::new(); + let had_global = filter_enhanced_barriers(1, &grp as *const _ as *const c_void, true, &mut ops); + ManuallyDrop::drop(&mut { tb }.pResource); + assert!(!had_global); + assert_eq!(ops.len(), 1, "enhanced texture barrier must queue TwinToDepth"); + execute_syncs(list.as_raw(), &ops); + + // Draw with DepthFunc = EQUAL at z = 42 / 65535.0 + let black = [0.0f32; 4]; + clear_rt(list.as_raw(), rtv_cpu.ptr, &black, 0, std::ptr::null()); + let vp = D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: 16.0, Height: 16.0, MinDepth: 0.0, MaxDepth: 1.0 }; + let sc = RECT { left: 0, top: 0, right: 16, bottom: 16 }; + set_vp(list.as_raw(), 1, &vp); + set_sc(list.as_raw(), 1, &sc); + set_rt(list.as_raw(), 1, &rtv_cpu.ptr, 0, &dsv_cpu.ptr); + set_gfx_rs(list.as_raw(), eq_rs.as_raw()); + set_pso(list.as_raw(), eq_pso.as_raw()); + set_topo(list.as_raw(), D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32); + set_gfx_const(list.as_raw(), 0, 42, 0); + draw(list.as_raw(), 3, 1, 0, 0); + + // Copy RT + stencil plane (subresource 1) to readback + list_x::transition(list.as_raw(), rt.as_raw() as usize, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + let dst_rt = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { pResource: ManuallyDrop::new(Some(rb_rt.clone())), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: rt_fp } }); + let src_rt = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { pResource: ManuallyDrop::new(Some(rt.clone())), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }); + list_x::pc_copy_texture_region(list.as_raw(), &dst_rt.0, 0, 0, 0, &src_rt.0, std::ptr::null()); + list_x::transition(list.as_raw(), rt.as_raw() as usize, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + + // Copy stencil plane (subresource 1) from DEPTH_READ -> COPY_SOURCE -> DEPTH_READ + let st_to_src = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(&depth_res), + Subresource: 1, + StateBefore: D3D12_RESOURCE_STATE_DEPTH_READ, + StateAfter: D3D12_RESOURCE_STATE_COPY_SOURCE, + }), + }, + }; + list_x::pc_resource_barriers(list.as_raw(), &[st_to_src]); + let dst_st = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { pResource: ManuallyDrop::new(Some(rb_st.clone())), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: st_fp } }); + let src_st = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { pResource: ManuallyDrop::new(Some(depth_res.clone())), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 1 } }); + list_x::pc_copy_texture_region(list.as_raw(), &dst_st.0, 0, 0, 0, &src_st.0, std::ptr::null()); + let st_to_read = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(&depth_res), + Subresource: 1, + StateBefore: D3D12_RESOURCE_STATE_COPY_SOURCE, + StateAfter: D3D12_RESOURCE_STATE_DEPTH_READ, + }), + }, + }; + list_x::pc_resource_barriers(list.as_raw(), &[st_to_read]); + + let close_orig: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(real::orig_fn(list.as_raw(), 9)); + let hr_close = close_orig(list.as_raw()); + if hr_close != 0 { + if let Ok(iq) = dev.cast::() { + let n = iq.GetNumStoredMessages(); + for i in 0..n { + let mut sz = 0usize; + let _ = iq.GetMessage(i, None, &mut sz); + if sz > 0 { + let mut buf = vec![0u8; sz]; + if iq.GetMessage(i, Some(buf.as_mut_ptr() as *mut D3D12_MESSAGE), &mut sz).is_ok() { + let msg = &*(buf.as_ptr() as *const D3D12_MESSAGE); + let desc = std::ffi::CStr::from_ptr(msg.pDescription as *const i8).to_string_lossy(); + eprintln!("D3D12 INFO[{i}]: id={} sev={} {desc}", msg.ID.0, msg.Severity.0); + } + } + } + } + } + assert_eq!(hr_close, 0); + q.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + wait_gpu(&q, &fence, &mut fence_val); + + // Verify Phase 1 RT: ONLY quadrant 2 (x < 8, y >= 8, perm 42) passed EQUAL! + let mut mapped = std::ptr::null_mut(); + rb_rt.Map(0, None, Some(&mut mapped)).unwrap(); + let rt_bytes = std::slice::from_raw_parts(mapped as *const u8, 16 * rt_fp.Footprint.RowPitch as usize); + for (qx, qy, expect_r) in [(2usize, 2usize, 0u8), (10, 2, 0), (2, 10, 255), (10, 10, 0)] { + let r = rt_bytes[qy * rt_fp.Footprint.RowPitch as usize + qx * 4]; + assert_eq!(r, expect_r, "fmt {console_fmt} Phase 1 EQUAL(42) at ({qx},{qy})"); + } + rb_rt.Unmap(0, None); + + // Verify stencil survived FullscreenPass intact + let mut st_mapped = std::ptr::null_mut(); + rb_st.Map(0, None, Some(&mut st_mapped)).unwrap(); + let st_bytes = std::slice::from_raw_parts(st_mapped as *const u8, 16 * st_fp.Footprint.RowPitch as usize); + for (qx, qy, expect_s) in [(2usize, 2usize, 0x11u8), (10, 2, 0x22), (2, 10, 0x5A), (10, 10, 0xA5)] { + let s = st_bytes[qy * st_fp.Footprint.RowPitch as usize + qx]; + assert_eq!(s, expect_s, "fmt {console_fmt} stencil at ({qx},{qy})"); + } + rb_st.Unmap(0, None); + + // --- Phase 2: Global UAV barrier (#146 GLOBAL) + before_bind_dsv --- + alloc.Reset().unwrap(); + let reset_orig: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> i32 = std::mem::transmute(real::orig_fn(list.as_raw(), 10)); + { + // the runtime's Reset puts its own vtable back (as `list_x::reset_pc` knows) + let ext = *(list.as_raw() as *const usize); + assert_eq!(reset_orig(list.as_raw(), alloc.as_raw(), std::ptr::null_mut()), 0); + real::preserve_vtable(list.as_raw(), ext); + } + + set_heaps_orig(list.as_raw(), 1, &uav_heap_raw); + set_cs_rs(list.as_raw(), cs_rs.as_raw()); + set_pso(list.as_raw(), cs_pso.as_raw()); + set_cs_const(list.as_raw(), 0, 77, 0); // q0_perm = 77 + set_cs_table(list.as_raw(), 1, uav_gpu_base); + dispatch(list.as_raw(), 2, 2, 1); + + let gb = D3D12_GLOBAL_BARRIER { + SyncBefore: D3D12_BARRIER_SYNC_COMPUTE_SHADING, + SyncAfter: D3D12_BARRIER_SYNC_ALL, + AccessBefore: D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + AccessAfter: D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ, + }; + let ggrp = D3D12_BARRIER_GROUP { + Type: D3D12_BARRIER_TYPE_GLOBAL, + NumBarriers: 1, + Anonymous: D3D12_BARRIER_GROUP_0 { pGlobalBarriers: &gb }, + }; + let mut ops2 = Vec::new(); + assert!(filter_enhanced_barriers(1, &ggrp as *const _ as *const c_void, true, &mut ops2)); + assert!(ops2.is_empty()); + on_global_uav_barrier(); + before_bind_dsv(list.as_raw(), dsv_cpu.ptr); + + clear_rt(list.as_raw(), rtv_cpu.ptr, &black, 0, std::ptr::null()); + set_vp(list.as_raw(), 1, &vp); + set_sc(list.as_raw(), 1, &sc); + set_rt(list.as_raw(), 1, &rtv_cpu.ptr, 0, &dsv_cpu.ptr); + set_gfx_rs(list.as_raw(), eq_rs.as_raw()); + set_pso(list.as_raw(), eq_pso.as_raw()); + set_topo(list.as_raw(), D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32); + set_gfx_const(list.as_raw(), 0, 77, 0); + draw(list.as_raw(), 3, 1, 0, 0); + + list_x::transition(list.as_raw(), rt.as_raw() as usize, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + list_x::pc_copy_texture_region(list.as_raw(), &dst_rt.0, 0, 0, 0, &src_rt.0, std::ptr::null()); + list_x::transition(list.as_raw(), rt.as_raw() as usize, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + assert_eq!(close_orig(list.as_raw()), 0); + q.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + wait_gpu(&q, &fence, &mut fence_val); + + let mut mapped2 = std::ptr::null_mut(); + rb_rt.Map(0, None, Some(&mut mapped2)).unwrap(); + let rt_bytes2 = std::slice::from_raw_parts(mapped2 as *const u8, 16 * rt_fp.Footprint.RowPitch as usize); + for (qx, qy, expect_r) in [(2usize, 2usize, 255u8), (10, 2, 0), (2, 10, 0), (10, 10, 0)] { + let r = rt_bytes2[qy * rt_fp.Footprint.RowPitch as usize + qx * 4]; + assert_eq!(r, expect_r, "fmt {console_fmt} Phase 2 global+before_bind_dsv EQUAL(77) at ({qx},{qy})"); + } + rb_rt.Unmap(0, None); + + forget(depth_res.as_raw() as usize); + alloc.Reset().unwrap(); + { + // the runtime's Reset puts its own vtable back (as `list_x::reset_pc` knows) + let ext = *(list.as_raw() as *const usize); + assert_eq!(reset_orig(list.as_raw(), alloc.as_raw(), std::ptr::null_mut()), 0); + real::preserve_vtable(list.as_raw(), ext); + } + } + if let Some(m) = PIPELINES.lock().unwrap().as_mut() { + m.remove(&(dev.as_raw() as usize)); + } + } + } + + #[test] + fn two_plane_global_and_enhanced_barriers_do_not_suppress_twin_dirty() { + #[repr(C)] + struct DummyCom { + vt: *const usize, + } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { + 1 + } + let mut vt = [0usize; 4]; + vt[1] = retain as usize; + vt[2] = retain as usize; + let mut d_obj = DummyCom { vt: vt.as_ptr() }; + let mut s_obj = DummyCom { vt: vt.as_ptr() }; + let mut sp_obj = DummyCom { vt: vt.as_ptr() }; + let all = D3D12_BARRIER_SUBRESOURCE_RANGE { + IndexOrFirstMipLevel: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + NumMipLevels: 0, + FirstArraySlice: 0, + NumArraySlices: 0, + FirstPlane: 0, + NumPlanes: 0, + }; + + unsafe { + // 1. Two-plane D16_UNORM_S8_UINT (fmt 118, RAGE9 material mask): + // starting in DEPTH_WRITE sets depth_plane_dirty = true, stencil_plane_dirty = true. + let plan = plan_for_console_format(118).unwrap(); + let mut e = Entry::new(0x1, plan, 1920, 1080, 1, 1, STATE_DEPTH_WRITE, false); + e.depth_twin = Some(ID3D12Resource::from_raw(&mut d_obj as *mut _ as *mut c_void)); + e.stencil_twin = Some(ID3D12Resource::from_raw(&mut s_obj as *mut _ as *mut c_void)); + assert!(e.depth_plane_dirty && e.stencil_plane_dirty); + assert!(!e.depth_twin_dirty && !e.stencil_twin_dirty); + + // Global UAV barrier must mark both twins dirty and clear plane_dirty even when plane_dirty was true. + mark_global_uav_dirty(&mut e); + assert!(e.depth_twin_dirty && e.stencil_twin_dirty); + assert!(!e.depth_plane_dirty && !e.stencil_plane_dirty); + + // Non-DIRECT enhanced barrier must also mark both twins dirty when plane_dirty was true. + e.depth_twin_dirty = false; + e.stencil_twin_dirty = false; + e.depth_plane_dirty = true; + e.stencil_plane_dirty = true; + let op = decide_enhanced_texture_barrier( + &mut e, + D3D12_BARRIER_ACCESS(0), + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ, + D3D12_BARRIER_LAYOUT_COMMON, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ, + &all, + D3D12_TEXTURE_BARRIER_FLAG_NONE, + false, + ); + assert!(op.is_none()); + assert!(e.depth_twin_dirty && e.stencil_twin_dirty); + assert!(!e.depth_plane_dirty && !e.stencil_plane_dirty); + + // DIRECT enhanced barrier out of COMMON access must flush TwinToDepth even when plane_dirty was true. + e.depth_twin_dirty = false; + e.stencil_twin_dirty = false; + e.depth_plane_dirty = true; + e.stencil_plane_dirty = true; + let op = decide_enhanced_texture_barrier( + &mut e, + D3D12_BARRIER_ACCESS(0), + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ, + D3D12_BARRIER_LAYOUT_COMMON, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ, + &all, + D3D12_TEXTURE_BARRIER_FLAG_NONE, + true, + ); + assert!(matches!(op, Some(SyncOp::TwinToDepth { .. })), "expected TwinToDepth flush, got {op:?}"); + assert!(!e.depth_plane_dirty && !e.stencil_plane_dirty); + + // 2. Single-plane fmt 53 shadow map: global UAV barrier must stay guarded by !depth_plane_dirty. + let sp_plan = plan_for_console_format(53).unwrap(); + let mut sp = Entry::new(0x1, sp_plan, 1024, 1024, 1, 1, STATE_DEPTH_WRITE, false); + sp.depth_twin = Some(ID3D12Resource::from_raw(&mut sp_obj as *mut _ as *mut c_void)); + assert!(sp.depth_plane_dirty && !sp.depth_twin_dirty); + mark_global_uav_dirty(&mut sp); + assert!(!sp.depth_twin_dirty && sp.depth_plane_dirty, "single-plane shadow map must remain guarded"); + } + } + + #[test] + fn copy_dsv_copies_clears_and_handles_overlaps() { + let mut console_desc = [0u8; 0x38]; + console_desc[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + console_desc[0x10..0x18].copy_from_slice(&64u64.to_le_bytes()); + console_desc[0x18..0x1C].copy_from_slice(&64u32.to_le_bytes()); + console_desc[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + console_desc[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + console_desc[0x20..0x24].copy_from_slice(&118u32.to_le_bytes()); + console_desc[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + console_desc[0x30..0x34].copy_from_slice(&6u32.to_le_bytes()); + + let res_a = 0x7001_0000usize; + let res_b = 0x7002_0000usize; + register_if_depth_uav(0x1 as *mut c_void, res_a as *mut c_void, &console_desc, STATE_COMMON, STATE_COMMON); + register_if_depth_uav(0x1 as *mut c_void, res_b as *mut c_void, &console_desc, STATE_COMMON, STATE_COMMON); + + let base = 0x9000_0000usize; + let inc = 32usize; + // Slots: [0]=A(1), [1]=empty, [2]=B(2), [3]=A(3) + note_dsv(base, res_a, 1); + note_dsv(base + 2 * inc, res_b, 2); + note_dsv(base + 3 * inc, res_a, 3); + + // Zero count / inc are no-ops + copy_dsv(base + 4 * inc, base, 0, inc); + copy_dsv(base + 4 * inc, base, 2, 0); + + // Disjoint copy including clearing a pre-existing destination where src is empty + note_dsv(base + 5 * inc, res_b, 9); + copy_dsv(base + 4 * inc, base, 4, inc); + { + let g = DSV_TO_RES.lock().unwrap(); + let m = g.as_ref().unwrap(); + assert_eq!(m.get(&(base + 4 * inc)).copied(), Some((res_a, 1))); + assert_eq!(m.get(&(base + 5 * inc)).copied(), None); + assert_eq!(m.get(&(base + 6 * inc)).copied(), Some((res_b, 2))); + assert_eq!(m.get(&(base + 7 * inc)).copied(), Some((res_a, 3))); + } + + // Overlapping forward copy: dst = base + inc, src = base, count = 3 -> [1]=A(1), [2]=empty, [3]=B(2) + copy_dsv(base + inc, base, 3, inc); + { + let g = DSV_TO_RES.lock().unwrap(); + let m = g.as_ref().unwrap(); + assert_eq!(m.get(&base).copied(), Some((res_a, 1))); + assert_eq!(m.get(&(base + inc)).copied(), Some((res_a, 1))); + assert_eq!(m.get(&(base + 2 * inc)).copied(), None); + assert_eq!(m.get(&(base + 3 * inc)).copied(), Some((res_b, 2))); + } + + // Overlapping backward copy: dst = base + 4*inc, src = base + 5*inc, count = 3 -> [4]=empty, [5]=B(2), [6]=A(3) + copy_dsv(base + 4 * inc, base + 5 * inc, 3, inc); + { + let g = DSV_TO_RES.lock().unwrap(); + let m = g.as_ref().unwrap(); + assert_eq!(m.get(&(base + 4 * inc)).copied(), None); + assert_eq!(m.get(&(base + 5 * inc)).copied(), Some((res_b, 2))); + assert_eq!(m.get(&(base + 6 * inc)).copied(), Some((res_a, 3))); + } + + forget(res_a); + forget(res_b); + } + + #[test] + fn uav_twin_tracking_and_forget_cleanup() { + #[repr(C)] + struct DummyCom { + vt: *const usize, + } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { + 1 + } + let mut vt = [0usize; 4]; + vt[1] = retain as usize; + vt[2] = retain as usize; + let mut d_obj = DummyCom { vt: vt.as_ptr() }; + let mut s_obj = DummyCom { vt: vt.as_ptr() }; + let d_raw = &mut d_obj as *mut _ as usize; + let s_raw = &mut s_obj as *mut _ as usize; + + let mut console_desc = [0u8; 0x38]; + console_desc[0..4].copy_from_slice(&3u32.to_le_bytes()); + console_desc[0x10..0x18].copy_from_slice(&64u64.to_le_bytes()); + console_desc[0x18..0x1C].copy_from_slice(&64u32.to_le_bytes()); + console_desc[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + console_desc[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + console_desc[0x20..0x24].copy_from_slice(&118u32.to_le_bytes()); + console_desc[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + console_desc[0x30..0x34].copy_from_slice(&6u32.to_le_bytes()); + + let res = 0x7003_0000usize; + register_if_depth_uav(0x1 as *mut c_void, res as *mut c_void, &console_desc, STATE_DEPTH_WRITE, STATE_DEPTH_WRITE); + unsafe { + let mut g = ENTRIES.lock().unwrap(); + let e = g.as_mut().unwrap().get_mut(&res).unwrap(); + e.depth_twin = Some(ID3D12Resource::from_raw(d_raw as *mut c_void)); + e.stencil_twin = Some(ID3D12Resource::from_raw(s_raw as *mut c_void)); + } + + let uav_d = 0xA000_0100usize; + let uav_s = 0xA000_0120usize; + let uav_other = 0xA000_0140usize; + let other_twin = 0x7004_0000usize; + note_uav_twin(uav_d, d_raw); + note_uav_twin(uav_s, s_raw); + note_uav_twin(uav_other, other_twin); + + assert_eq!(twin_for_pc_uav(uav_d), Some(d_raw)); + assert_eq!(twin_for_pc_uav(uav_s), Some(s_raw)); + { + let g = ENTRIES.lock().unwrap(); + let e = g.as_ref().unwrap().get(&res).unwrap(); + assert!(e.depth_twin_dirty && e.stencil_twin_dirty); + assert!(!e.depth_plane_dirty && !e.stencil_plane_dirty); + } + + // `forget(res)` must remove both depth and stencil UAV twin mappings while keeping unrelated ones. + forget(res); + assert_eq!(twin_for_pc_uav(uav_d), None); + assert_eq!(twin_for_pc_uav(uav_s), None); + assert_eq!(twin_for_pc_uav(uav_other), Some(other_twin)); + clear_uav_twin(uav_other); + assert_eq!(twin_for_pc_uav(uav_other), None); + } +} diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 57c30e0ffe..27e97adc29 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -13,6 +13,7 @@ //! Console queue and list types add DMA (0x10, the copy engine); console queue priorities //! are mapped onto PC ones. +use super::place_times::{self, Step}; use std::collections::HashMap; use std::ffi::{c_char, c_void, CStr, CString}; use std::sync::atomic::{AtomicI8, AtomicU64, Ordering}; @@ -95,10 +96,11 @@ unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: let hr = if super::console_list::enabled() { 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 resolved_pso = super::pso_async::resolve(pso); + 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); @@ -327,10 +329,10 @@ struct Base { unsafe impl Send for Base {} unsafe impl Sync for Base {} -static BASES: Mutex>>> = Mutex::new(None); +static BASES: std::sync::RwLock>>> = std::sync::RwLock::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); +static DEPTH_BIAS_PSOS: std::sync::RwLock>> = std::sync::RwLock::new(None); fn rd32(d: &[u8], o: usize) -> u32 { u32::from_le_bytes(d[o..o + 4].try_into().unwrap()) @@ -386,7 +388,7 @@ unsafe fn note_base(pso: *mut c_void, desc: *const c_void, dynamic_depth_bias: b 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 }); - BASES.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso as usize, base); + BASES.write().unwrap().get_or_insert_with(HashMap::new).insert(pso as usize, base); } /// Depth-bias metadata for a tracked graphics PSO: `(created_with_dynamic_depth_bias, static_bias)`. @@ -394,12 +396,12 @@ pub(super) fn base_depth_bias_info(pso: usize) -> Option<(bool, DepthBias)> { if pso == 0 { return None; } - BASES.lock().unwrap().as_ref()?.get(&pso).map(|b| (b.dynamic_depth_bias, b.static_bias)) + BASES.read().unwrap().as_ref()?.get(&pso).map(|b| (b.dynamic_depth_bias, b.static_bias)) } #[cfg(test)] pub(super) fn depth_bias_cache_len() -> usize { - DEPTH_BIAS_PSOS.lock().unwrap().as_ref().map_or(0, HashMap::len) + DEPTH_BIAS_PSOS.read().unwrap().as_ref().map_or(0, HashMap::len) } #[cfg(test)] @@ -412,16 +414,16 @@ pub(super) fn register_test_base(pso: usize, dynamic_depth_bias: bool, static_bi _elems: Vec::new(), _names: Vec::new(), }); - BASES.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, base); + BASES.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, base); } /// A pipeline released for good is no longer a base; its cached depth-bias variants go with it. pub(super) fn forget_base(pso: usize) { - if let Some(m) = BASES.lock().unwrap().as_mut() { + if let Some(m) = BASES.write().unwrap().as_mut() { m.remove(&pso); } let gone: Vec = { - let mut g = DEPTH_BIAS_PSOS.lock().unwrap(); + let mut g = DEPTH_BIAS_PSOS.write().unwrap(); match g.as_mut() { Some(m) => { let mut out = Vec::new(); @@ -452,10 +454,10 @@ pub(super) unsafe fn depth_bias_pso(dev: *mut c_void, base: usize, bias: DepthBi if dev.is_null() || base == 0 { return None; } - if let Some(&cached) = DEPTH_BIAS_PSOS.lock().unwrap().as_ref().and_then(|m| m.get(&(base, bias))) { + if let Some(&cached) = DEPTH_BIAS_PSOS.read().unwrap().as_ref().and_then(|m| m.get(&(base, bias))) { return Some(cached); } - let b = BASES.lock().unwrap().as_ref().and_then(|m| m.get(&base).cloned())?; + let b = BASES.read().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"); @@ -477,8 +479,8 @@ pub(super) unsafe fn depth_bias_pso(dev: *mut c_void, base: usize, bias: DepthBi let mut release_extra = 0usize; let result = { // re-check base liveness so we never leak a derived PSO for a concurrently released base - let alive = BASES.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&base)); - let mut g = DEPTH_BIAS_PSOS.lock().unwrap(); + let alive = BASES.read().unwrap().as_ref().is_some_and(|m| m.contains_key(&base)); + let mut g = DEPTH_BIAS_PSOS.write().unwrap(); let map = g.get_or_insert_with(HashMap::new); if !alive { release_extra = derived; @@ -529,7 +531,7 @@ pub(super) unsafe extern "system" fn create_derived_pso_x(this: *mut c_void, bas return E_INVALIDARG; } *ppv = std::ptr::null_mut(); - let found = BASES.lock().unwrap().as_ref().and_then(|m| m.get(&(base as usize)).cloned()); + let found = BASES.read().unwrap().as_ref().and_then(|m| m.get(&(base as usize)).cloned()); let Some(b) = found else { if once(&N, 4) { crate::xlog_warn!("D3D12.X: CreateDerivedPipelineStateX – base pipeline {base:?} unknown (its creation failed, or it has stream output)"); @@ -693,7 +695,7 @@ fn uav_format_supported_by_caps(format: u32, support1: u32, support2: u32) -> bo (support2 & typed_rw) != 0 } -static UAV_FORMAT_SUPPORT: Mutex>> = Mutex::new(None); +static UAV_FORMAT_SUPPORT: std::sync::RwLock>> = std::sync::RwLock::new(None); /// Query (and cache per adapter LUID + format) whether the PC device supports `ALLOW_UNORDERED_ACCESS` /// on `format`. Falls back to `texture_format_allows_uav` if the device cannot be queried. @@ -709,7 +711,7 @@ unsafe fn device_format_supports_uav(device: *mut c_void, format: u32) -> bool { }; let luid = dev.GetAdapterLuid(); let key = ((luid.LowPart, luid.HighPart), format); - if let Some(&cached) = UAV_FORMAT_SUPPORT.lock().unwrap().as_ref().and_then(|m| m.get(&key)) { + if let Some(&cached) = UAV_FORMAT_SUPPORT.read().unwrap().as_ref().and_then(|m| m.get(&key)) { return cached; } let mut fs = D3D12_FEATURE_DATA_FORMAT_SUPPORT { @@ -728,7 +730,7 @@ unsafe fn device_format_supports_uav(device: *mut c_void, format: u32) -> bool { } else { true }; - UAV_FORMAT_SUPPORT.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, supported); + UAV_FORMAT_SUPPORT.write().unwrap().get_or_insert_with(HashMap::new).insert(key, supported); supported } @@ -878,11 +880,11 @@ pub fn pc_shader_view_format(resource: u32, view: u32) -> u32 { let view = pc_view_format(view); match (resource, view) { // R32G8X24_TYPELESS: depth 21, stencil 22 - (19..=22, 0 | 19 | 20 | 21 | 39 | 40 | 41) => 21, - (19..=22, 22 | 61 | 62) => 22, + (19..=22, 0 | 19 | 20 | 21 | 39 | 40 | 41 | 42 | 43) => 21, + (19..=22, 22 | 60..=64) => 22, // R24G8_TYPELESS: depth 46, stencil 47 - (44..=47, 0 | 41 | 44 | 45 | 46 | 53 | 54 | 55 | 56) => 46, - (44..=47, 47 | 61 | 62) => 47, + (44..=47, 0 | 41 | 42 | 44 | 45 | 46 | 53 | 54 | 55 | 56 | 57 | 59) => 46, + (44..=47, 47 | 60..=64) => 47, // R32_TYPELESS, R16_TYPELESS (39 | 40, 0 | 39 | 40) => 41, (53 | 55, 0 | 53 | 55) => 56, @@ -896,7 +898,7 @@ pub fn pc_shader_view_format(resource: u32, view: u32) -> u32 { } /// Cached host `D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW` answers per `(adapter LUID, DXGI_FORMAT)`. -static TYPED_UAV_SUPPORT: Mutex>> = Mutex::new(None); +static TYPED_UAV_SUPPORT: std::sync::RwLock>> = std::sync::RwLock::new(None); /// Map sRGB formats (never valid for PC UAVs) to their linear UAV-capable counterparts. pub fn pc_uav_linear_format(fmt: u32) -> u32 { @@ -919,7 +921,7 @@ pub(super) unsafe fn pc_typed_uav_supported(dev_raw: *mut c_void, fmt: i32) -> b }; let luid = dev.GetAdapterLuid(); let key = ((luid.LowPart, luid.HighPart), fmt); - if let Some(&cached) = TYPED_UAV_SUPPORT.lock().unwrap().as_ref().and_then(|m| m.get(&key)) { + if let Some(&cached) = TYPED_UAV_SUPPORT.read().unwrap().as_ref().and_then(|m| m.get(&key)) { return cached; } let mut data = D3D12_FEATURE_DATA_FORMAT_SUPPORT { @@ -931,7 +933,7 @@ pub(super) unsafe fn pc_typed_uav_supported(dev_raw: *mut c_void, fmt: i32) -> b } else { data.Support1.0 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0 != 0 }; - TYPED_UAV_SUPPORT.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, supported); + TYPED_UAV_SUPPORT.write().unwrap().get_or_insert_with(HashMap::new).insert(key, supported); supported } @@ -1093,12 +1095,18 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, // the PC's reserved resource and tile mappings for it can take long where the console's // placement takes no time (`pso_async::title_held`) let _in_pc = super::pso_async::pc_call(); + let _prof = super::prof::span(super::prof::Kind::Placement); let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); + let texture = u32::from_le_bytes(x[0..4].try_into().unwrap()) != D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32; + let _total = texture.then(|| place_times::step(Step::Total)); + let timer = texture.then(|| place_times::step(Step::Desc)); let d = pc_resource_desc_for_device(this, &x); let buffer = u32::from_le_bytes(d[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32; note_alias(va as usize, &x); + drop(timer); // console-only state bits (Unicorn Overlord's 4K display target: 0x100000) are not the // PC's: the PC refused the resource (E_INVALIDARG) and the title threw + let console_state = state; let state = pc_initial_state(u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()), state); let mut clear_buf = [0u8; 24]; let pc_format = u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()); @@ -1121,9 +1129,20 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, // sampled textures: on the same shared 64 KiB pages when tiled resources allow, else committed let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); let mut placed_hr = None; + let mut pc_tex_desc: Option = None; + let mut water_tex: Option<(windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, u32, u32, crate::hle::xg::Texture)> = None; if !buffer { let pc = std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC); - let console_bytes = crate::hle::xg::Texture::new(&x).ok().map(|t| t.size()).filter(|&s| s != u64::MAX && s != 0); + pc_tex_desc = Some(pc); + let timer = place_times::step(Step::Desc); + let xg_tex = crate::hle::xg::Texture::new(&x).ok(); + let console_bytes = xg_tex.as_ref().map(|t| t.size()).filter(|&s| s != u64::MAX && s != 0); + if console_bytes.is_some() && super::cpu_writes::is_water_readback_desc(&pc) { + if let Some(t) = xg_tex { + water_tex = Some((pc.Format, pc.Width as u32, pc.Height, t)); + } + } + drop(timer); if super::vram::gpu_owned(flags) { if let Some(hr) = super::vram::place(this, va as usize, &pc, state, clear, console_bytes, riid, ppv) { if hr >= 0 && !(*ppv).is_null() { @@ -1131,6 +1150,13 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, super::title_textures::retire_overlapping(va as usize, bytes as usize); } real::note_title_address(*ppv as usize, va as usize); + super::depth_uav::register_if_depth_uav(this, *ppv, &x, state, console_state); + super::format_alias::register_title_texture(this as usize, *ppv as usize, va as usize, &pc, flags, state); + if let Some((fmt, w, h, t)) = water_tex { + super::cpu_writes::register_water_readback(*ppv as usize, va as usize, fmt, w, h, std::sync::Arc::new(t)); + } else if super::cpu_writes::has_water_readback() { + super::cpu_writes::unregister_water_readback(*ppv as usize); + } } return hr; } @@ -1146,21 +1172,35 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } }; if hr >= 0 && !buffer && !(*ppv).is_null() { + if let Some((fmt, w, h, t)) = water_tex { + super::cpu_writes::register_water_readback(*ppv as usize, va as usize, fmt, w, h, std::sync::Arc::new(t)); + } else if super::cpu_writes::has_water_readback() { + super::cpu_writes::unregister_water_readback(*ppv as usize); + } + super::depth_uav::register_if_depth_uav(this, *ppv, &x, state, console_state); + let aliased_to_gpu = pc_tex_desc.as_ref().is_some_and(|pc| { + super::format_alias::register_title_texture(this as usize, *ppv as usize, va as usize, pc, flags, state) + }); static M: AtomicU64 = AtomicU64::new(0); - 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); - return hr; - } - Err(e) if once(&M, 4) => { - let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); - crate::xlog_warn!( - "D3D12.X: CreatePlacedResourceX texture at {va:#x} (dimension {} {}x{}x{}, {} mips, format {}, {} samples, layout {:#x}, flags {:#x}): not kept in step with the memory ({e})", - u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u16::from_le_bytes(x[0x1C..0x1E].try_into().unwrap()), - u16::from_le_bytes(x[0x1E..0x20].try_into().unwrap()), u(0x20), u(0x24), u(0x2C), u(0x30) - ) + if !aliased_to_gpu { + let timer = place_times::step(Step::Register); + let registered = super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)); + drop(timer); + match registered { + Ok(()) => { + real::note_title_address(*ppv as usize, va as usize); + return hr; + } + Err(e) if once(&M, 4) => { + let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); + crate::xlog_warn!( + "D3D12.X: CreatePlacedResourceX texture at {va:#x} (dimension {} {}x{}x{}, {} mips, format {}, {} samples, layout {:#x}, flags {:#x}): not kept in step with the memory ({e})", + u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u16::from_le_bytes(x[0x1C..0x1E].try_into().unwrap()), + u16::from_le_bytes(x[0x1E..0x20].try_into().unwrap()), u(0x20), u(0x24), u(0x2C), u(0x30) + ) + } + Err(_) => {} } - Err(_) => {} } } if hr >= 0 && !(*ppv).is_null() { @@ -1237,6 +1277,19 @@ pub(super) unsafe extern "system" fn get_copyable_footprints_x( /// device #41 CreateCommandSignature(desc, root signature, riid, signature): the console's /// DispatchX argument (105) is a PC Dispatch; the root signature only goes with arguments /// that need one (constants, CBV / SRV / UAV) +fn indirect_arg_bytes(arg: &[u32; 4]) -> u32 { + match arg[0] { + 0 => 16, + 1 => 20, + 2 | 10 => 12, + 3 | 4 => 16, + 5 => arg[3].saturating_mul(4), + 6..=8 => 8, + 9 => 108, + _ => 0, + } +} + pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_void, desc: *const u8, root: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { if desc.is_null() || ppv.is_null() { return E_INVALIDARG; @@ -1254,11 +1307,39 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi let needs_root = list.iter().any(|a| (5..=8).contains(&a[0])); pc[8..16].copy_from_slice(&(if list.is_empty() { 0 } else { list.as_ptr() as u64 }).to_le_bytes()); let hr = real::dev_create_command_signature(this, pc.as_ptr() as usize, if needs_root { root } else { 0 }, riid, ppv); - if hr >= 0 && !ppv.is_null() && needs_root { - super::bind::note_root_changing_signature(*ppv as usize); - } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + super::bind::note_root_changing_signature(*ppv as usize, needs_root); + if !needs_root { + if let Some(idx) = list.iter().position(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH.0 as u32) { + let offset: u32 = list[..idx].iter().map(indirect_arg_bytes).sum(); + let byte_stride = u32::from_le_bytes(pc[0..4].try_into().unwrap()); + let mut dispatch_list = list.clone(); + dispatch_list[idx][0] = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32; + let mut dpc = pc; + dpc[8..16].copy_from_slice(&(dispatch_list.as_ptr() as u64).to_le_bytes()); + let mut companion: *mut c_void = std::ptr::null_mut(); + let hr2 = real::dev_create_command_signature(this, dpc.as_ptr() as usize, 0, riid, &mut companion); + if hr2 >= 0 && !companion.is_null() { + super::bind::note_dispatch_mesh_signature(*ppv as usize, companion as usize, byte_stride, offset); + } + } + } super::bind::note_signature_dispatches(*ppv as usize, list.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)); + let stride = u32::from_le_bytes(pc[0..4].try_into().unwrap()); + let dispatch_only = list.len() == 1 && list[0][0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32 && stride >= 12 && stride % 4 == 0; + super::bind::note_dispatch_only_signature(*ppv as usize, dispatch_only.then_some(stride)); + let draw_sig = (!needs_root).then(|| { + let idx = list.iter().position(|a| { + a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW.0 as u32 + || a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED.0 as u32 + })?; + let offset: u32 = list[..idx].iter().map(indirect_arg_bytes).sum(); + let indexed = list[idx][0] == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED.0 as u32; + let min_arg = if indexed { 20u32 } else { 16u32 }; + (stride % 4 == 0 && offset % 4 == 0 && offset.checked_add(min_arg).is_some_and(|end| end <= stride)) + .then_some((stride, offset, indexed)) + }).flatten(); + super::bind::note_draw_signature(*ppv as usize, draw_sig); } hr } @@ -1679,7 +1760,7 @@ mod tests { assert!(device_format_supports_uav(ptr, 24) && dev.checks == 2); assert!(device_format_supports_uav(ptr, 24) && dev.checks == 2); } - if let Some(m) = UAV_FORMAT_SUPPORT.lock().unwrap().as_mut() { + if let Some(m) = UAV_FORMAT_SUPPORT.write().unwrap().as_mut() { m.remove(&((luid_a.LowPart, luid_a.HighPart), 24)); m.remove(&((luid_b.LowPart, luid_b.HighPart), 24)); } @@ -1718,7 +1799,7 @@ mod tests { get_copyable_footprints_x(&mut dev as *mut FakeAdoptedDev as *mut c_void, x.as_ptr(), 0, 1, 0, std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), &mut total); } assert_eq!((dev.calls, dev.last_flags & 4, total), (2, 0, 65536)); - if let Some(m) = UAV_FORMAT_SUPPORT.lock().unwrap().as_mut() { + if let Some(m) = UAV_FORMAT_SUPPORT.write().unwrap().as_mut() { m.remove(&((luid.LowPart, luid.HighPart), 24)); } } diff --git a/crates/xcl/src/hle/d3d12x/dred.rs b/crates/xcl/src/hle/d3d12x/dred.rs index 85bb784bdf..404eb53939 100644 --- a/crates/xcl/src/hle/d3d12x/dred.rs +++ b/crates/xcl/src/hle/d3d12x/dred.rs @@ -18,11 +18,19 @@ use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::{ID3D12GraphicsCommandList, D3D12_AUTO_BREADCRUMB_OP_SETMARKER}; /// translated pipeline → its label -static LABELS: Mutex>> = Mutex::new(None); +static LABELS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// PC command list → its last `RECORDINGS` recordings, oldest first: the label of each marker /// (`None`: the title's own) static MARKS: Mutex>>>>> = Mutex::new(None); +/// Null-terminated UTF-16 marker text (`"xcl pipeline\0"`) reused across `mark_pipeline` calls +/// without per-PSO heap allocations. +const PIPELINE_MARKER_W: &[u16] = &[ + b'x' as u16, b'c' as u16, b'l' as u16, b' ' as u16, + b'p' as u16, b'i' as u16, b'p' as u16, b'e' as u16, + b'l' as u16, b'i' as u16, b'n' as u16, b'e' as u16, 0, +]; + /// Recordings kept per list: a list can be Reset and recorded again while an earlier /// submission of it still runs, and that one can be the one that faults. const RECORDINGS: usize = 4; @@ -43,11 +51,18 @@ pub fn label(pso: usize, shaders: &[(&str, Option<&[u8]>)]) { return; } let text = shaders.iter().filter_map(|(k, b)| b.map(|b| format!("{k} {:016x}", crate::gpu::shader::fnv64(b)))).collect::>().join(" "); - LABELS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, text); + LABELS.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, text); +} + +/// `label` with a text of XCL's own: a piece of a split program, a pass of two. +pub fn label_text(pso: usize, text: impl FnOnce() -> String) { + if on() && pso != 0 { + LABELS.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, text()); + } } fn label_of(pso: usize) -> Option { - LABELS.lock().unwrap().as_ref()?.get(&pso).cloned() + LABELS.read().unwrap().as_ref()?.get(&pso).cloned() } /// After `SetPipelineState(pso)` on `list`: a marker, and the label of what is bound now. @@ -58,16 +73,24 @@ pub unsafe fn mark_pipeline(list: *mut c_void, pso: usize, bound: usize) { } // nothing labelled: a stand-in still building, or a pipeline of PC shaders let text = label_of(bound).unwrap_or_else(|| format!("pipeline {pso:#x} (a stand-in, or not translated)")); - let first = !MARKS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).and_then(|r| r.last()).is_some_and(|v| v.iter().any(Option::is_some)); - push(list as usize, Some(text)); + let first = { + let mut g = MARKS.lock().unwrap(); + let recordings = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); + if recordings.is_empty() { + recordings.push(Vec::new()); + } + let cur = recordings.last_mut().unwrap(); + let first = !cur.iter().any(Option::is_some); + cur.push(Some(text)); + first + }; if let Some(l) = ID3D12GraphicsCommandList::from_raw_borrowed(&list) { // DRED's node may give the list's name and not its pointer (NVIDIA, Windows 26300) if first { let _ = l.SetName(&windows::core::HSTRING::from(format!("xcl list {:#x}", list as usize))); } - let w: Vec = "xcl pipeline".encode_utf16().chain([0]).collect(); OWN_MARKER.with(|f| f.set(true)); - l.SetMarker(0, Some(w.as_ptr() as *const c_void), (w.len() * 2) as u32); + l.SetMarker(0, Some(PIPELINE_MARKER_W.as_ptr() as *const c_void), std::mem::size_of_val(PIPELINE_MARKER_W) as u32); OWN_MARKER.with(|f| f.set(false)); } } @@ -112,7 +135,7 @@ pub fn forget_list(list: *mut c_void) { /// A pipeline was released: its address may be another pipeline's next. pub fn forget_pso(pso: usize) { if on() { - if let Some(m) = LABELS.lock().unwrap().as_mut() { + if let Some(m) = LABELS.write().unwrap().as_mut() { m.remove(&pso); } } @@ -210,4 +233,10 @@ mod tests { assert_eq!(bound_after(list, &h, 6), Vec::::new()); MARKS.lock().unwrap().as_mut().unwrap().remove(&list); } + + #[test] + fn pipeline_marker_constant_matches_nul_terminated_utf16() { + let expected: Vec = "xcl pipeline\0".encode_utf16().collect(); + assert_eq!(PIPELINE_MARKER_W, expected.as_slice()); + } } diff --git a/crates/xcl/src/hle/d3d12x/driver_crash.rs b/crates/xcl/src/hle/d3d12x/driver_crash.rs new file mode 100644 index 0000000000..dfc52d84ef --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/driver_crash.rs @@ -0,0 +1,260 @@ +//! The driver's shader compiler crashing on one pipeline: an access violation inside +//! `Create*PipelineState` ends the process, and the next run ends at the same pipeline (seen in +//! AMD's compiler on a 331 KiB mesh pipeline, every run, a minute into a retail world). +//! +//! The pipeline a thread hands to the driver is noted while the driver has it (`building`). The +//! unhandled-exception filter, on the thread that crashed, writes that pipeline's key to +//! `driver-crashes.txt` beside the DXIL cache and its shaders to the log folder (`on_crash`). A +//! later run does not hand a pipeline with a key of that file to the driver (`blocked`): it fails +//! as one the driver refused. The key is of the translated shaders and the state, so a translation +//! that changes makes a new key and is tried again; deleting the file tries them all again. +//! +//! A preparation worker (`shaders::in_workers`) has no such filter, and a fast-fail inside the +//! driver calls none anyway: it says which pipeline it builds in a file of its own beside the +//! list (`driver-building--.txt`), gone when the pipeline is built. One left by a +//! process that is gone names a pipeline the driver did not come back from: `blocked` moves it +//! into the list, so the worker started again for that part (`in_workers`) goes on after it. + +use std::cell::Cell; +use std::collections::HashSet; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +/// A pipeline in the driver: its key and its shaders (file name ending, address, bytes). +struct Building { + key: String, + shaders: Vec<(String, usize, usize)>, +} + +thread_local! { + /// the pipeline this thread's driver call is building (null: none) + static BUILDING: Cell<*const Building> = const { Cell::new(std::ptr::null()) }; +} + +/// Until dropped, this thread's driver call builds the pipeline it was made for. +pub(crate) struct Guard { + _now: Box, + before: *const Building, + /// a worker's file that names the pipeline while the driver has it + marker: Option, +} + +impl Drop for Guard { + fn drop(&mut self) { + let _ = BUILDING.try_with(|b| b.set(self.before)); + if let Some(m) = &self.marker { + let _ = std::fs::remove_file(m); + } + } +} + +/// This process is a preparation worker (`shaders::worker_command`). +fn worker() -> bool { + static W: std::sync::OnceLock = std::sync::OnceLock::new(); + *W.get_or_init(|| std::env::var_os("XCL_PRECOMPILE_PARENT").is_some()) +} + +fn marker_name(pid: u32, thread: u32) -> String { + format!("driver-building-{pid}-{thread}.txt") +} + +/// The driver call this thread makes next builds the pipeline `key` from `shaders` (each with the +/// ending of the file it is dumped to after a crash); they outlive the returned guard. +pub(crate) fn building(key: &str, shaders: &[(String, &[u8])]) -> Guard { + let now = Box::new(Building { key: key.to_string(), shaders: shaders.iter().map(|(n, c)| (n.clone(), c.as_ptr() as usize, c.len())).collect() }); + let before = BUILDING.with(|b| b.replace(&*now)); + let marker = worker().then(|| mark(&path(), key)).flatten(); + Guard { _now: now, before, marker } +} + +/// A file beside `list` that names `key` as in the driver for this thread of this process. +fn mark(list: &Path, key: &str) -> Option { + let dir = list.parent()?; + std::fs::create_dir_all(dir).ok()?; + let m = dir.join(marker_name(std::process::id(), unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() })); + std::fs::write(&m, key).ok()?; + Some(m) +} + +/// The process `pid` is gone (or cannot be asked about, which a live worker of this user can). +fn gone(pid: u32) -> bool { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Threading::{OpenProcess, WaitForSingleObject, PROCESS_SYNCHRONIZE}; + unsafe { + let h = OpenProcess(PROCESS_SYNCHRONIZE, 0, pid); + if h.is_null() { + return true; + } + let ended = WaitForSingleObject(h, 0) == 0; + CloseHandle(h); + ended + } +} + +/// The markers beside `list` of processes that are gone (`is_gone`): their keys go into the list +/// and the markers are removed. The keys. +fn collect_markers(list: &Path, is_gone: impl Fn(u32) -> bool) -> Vec { + let Some(dir) = list.parent() else { return Vec::new() }; + let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut found = Vec::new(); + for e in entries.flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + let Some(pid) = name.strip_prefix("driver-building-").and_then(|r| r.split('-').next()).and_then(|p| p.parse::().ok()) else { continue }; + if !is_gone(pid) { + continue; + } + if let Some(key) = std::fs::read_to_string(e.path()).ok().and_then(|t| t.split_whitespace().next().map(str::to_string)) { + if note(list, &key).is_ok() { + found.push(key); + } + } + let _ = std::fs::remove_file(e.path()); + } + found +} + +/// The key of the compute pipelines of a console program (`record`: the hash of its container), +/// whole or in pieces: what a preparation worker and the title both know it by. +pub(crate) fn compute_key(record: u64) -> String { + format!("cs-{record:016x}") +} + +/// The keys of the pipelines the driver crashed on, one a line. +fn path() -> PathBuf { + crate::gpu::recomp::dxc::cache_dir().join("driver-crashes.txt") +} + +fn keys(text: &str) -> HashSet { + text.lines().filter_map(|l| l.split_whitespace().next()).map(str::to_string).collect() +} + +fn note(list: &Path, key: &str) -> std::io::Result<()> { + if let Some(dir) = list.parent() { + std::fs::create_dir_all(dir)?; + } + let mut f = std::fs::OpenOptions::new().create(true).append(true).open(list)?; + writeln!(f, "{key}")?; + f.sync_all() +} + +static BLOCKED: Mutex>> = Mutex::new(None); + +/// The driver crashed building the pipeline `key` in an earlier run, or a process that is gone +/// was still building it: it is not built. +pub(crate) fn blocked(key: &str) -> bool { + let mut g = BLOCKED.lock().unwrap_or_else(|e| e.into_inner()); + // tests start with none, not with what the machine's runs left + g.get_or_insert_with(|| if cfg!(test) { HashSet::new() } else { load(&path()) }).contains(key) +} + +/// The keys of `list`, with those of the markers that processes now gone left beside it. +fn load(list: &Path) -> HashSet { + for key in collect_markers(list, gone) { + crate::xlog_warn!("D3D12.X: a process that ended was building pipeline {key} in the driver – noted in {} and not built again", list.display()); + } + std::fs::read_to_string(list).map(|t| keys(&t)).unwrap_or_default() +} + +#[cfg(test)] +pub(super) fn block(key: &str) { + BLOCKED.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashSet::new).insert(key.to_string()); +} + +/// The pipeline this thread's driver call was building, if any: its key goes to `list` and its +/// shaders to `dir`; what to log. +unsafe fn crashed(list: &Path, dir: Option<&Path>) -> Option { + let p = BUILDING.try_with(|b| b.replace(std::ptr::null())).ok()?; + let b = p.as_ref()?; + let noted = match note(list, &b.key) { + Ok(()) => format!("noted in {} and not built again", list.display()), + Err(e) => format!("not noted in {} ({e})", list.display()), + }; + let mut shaders = Vec::new(); + for (name, at, len) in &b.shaders { + if !crate::gpu::shader::readable(*at, *len) { + continue; + } + let code = std::slice::from_raw_parts(*at as *const u8, *len); + let file = format!("driver-crash-{}-{name}", b.key); + let written = dir.is_some_and(|d| std::fs::create_dir_all(d).and_then(|()| std::fs::write(d.join(&file), code)).is_ok()); + shaders.push(format!("{file} ({:016x}, {len} B{})", crate::gpu::shader::fnv64(code), if written { "" } else { ", not written" })); + } + let dir = dir.map_or_else(String::new, |d| format!(" in {}", d.display())); + Some(format!("the driver crashed building pipeline {}: {noted}; its shaders{dir}: {}", b.key, shaders.join(", "))) +} + +/// From the unhandled-exception filter, on the thread that crashed. +pub fn on_crash() { + // (a process without a title, a preparation worker: beside the list) + let dir = crate::state::boot().map_or_else(|| path().with_file_name("driver-crashes"), |b| b.logs_dir()); + if let Some(msg) = unsafe { crashed(&path(), Some(&dir)) } { + crate::xlog_error!("D3D12.X: {msg}"); + crate::log::flush(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_crash_notes_the_pipeline_being_built_and_dumps_its_shaders() { + let dir = std::env::temp_dir().join(format!("xcl-driver-crash-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let list = dir.join("cache").join("driver-crashes.txt"); + let logs = dir.join("logs"); + unsafe { + // no driver call on this thread: nothing to note + assert!(crashed(&list, Some(&logs)).is_none()); + assert!(!list.exists()); + + let (ms, ps) = (vec![1u8, 2, 3], vec![4u8; 5]); + let outer = building("s-outer-10", &[("ms.dxil".to_string(), &ms[..])]); + { + let _inner = building("s-inner-8", &[("ms.dxil".to_string(), &ms[..]), ("ps.dxil".to_string(), &ps[..])]); + let msg = crashed(&list, Some(&logs)).expect("the inner pipeline"); + assert!(msg.contains("s-inner-8") && msg.contains("driver-crash-s-inner-8-ps.dxil"), "{msg}"); + // once: the filter may run again for the same crash + assert!(crashed(&list, Some(&logs)).is_none()); + } + // the inner call returned: the outer pipeline is the one being built again + assert!(crashed(&list, Some(&logs)).expect("the outer pipeline").contains("s-outer-10")); + drop(outer); + assert!(crashed(&list, Some(&logs)).is_none()); + } + assert_eq!(std::fs::read(logs.join("driver-crash-s-inner-8-ms.dxil")).unwrap(), [1, 2, 3]); + assert_eq!(std::fs::read(logs.join("driver-crash-s-inner-8-ps.dxil")).unwrap(), [4; 5]); + let noted = keys(&std::fs::read_to_string(&list).unwrap()); + assert_eq!(noted, HashSet::from(["s-inner-8".to_string(), "s-outer-10".to_string()])); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A worker's marker names the pipeline while the driver has it and is gone after; one left + /// by a process that is gone puts its key into the list, one of a live process stays. + #[test] + fn a_marker_left_by_a_process_that_is_gone_blocks_its_pipeline() { + let dir = std::env::temp_dir().join(format!("xcl-driver-marker-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let list = dir.join("driver-crashes.txt"); + let m = mark(&list, "cs-00000000000000aa").expect("a marker"); + assert_eq!(std::fs::read_to_string(&m).unwrap(), "cs-00000000000000aa"); + // built: the guard removes it (as `Guard::drop` does) + std::fs::remove_file(&m).unwrap(); + assert!(collect_markers(&list, |_| true).is_empty()); + + std::fs::write(dir.join(marker_name(111, 1)), "cs-0000000000000001").unwrap(); + std::fs::write(dir.join(marker_name(222, 7)), "cs-0000000000000002").unwrap(); + assert_eq!(collect_markers(&list, |pid| pid == 111), ["cs-0000000000000001"]); + assert!(!dir.join(marker_name(111, 1)).exists() && dir.join(marker_name(222, 7)).exists()); + assert_eq!(keys(&std::fs::read_to_string(&list).unwrap()), HashSet::from(["cs-0000000000000001".to_string()])); + assert!(!gone(std::process::id()), "this process is not gone"); + assert_eq!(compute_key(0xab), "cs-00000000000000ab"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn keys_are_the_first_word_of_each_line() { + assert_eq!(keys("s-1-a\r\n\n s-2-b later text\n"), HashSet::from(["s-1-a".to_string(), "s-2-b".to_string()])); + } +} diff --git a/crates/xcl/src/hle/d3d12x/fence_x.rs b/crates/xcl/src/hle/d3d12x/fence_x.rs index f67967345e..c2a33259b9 100644 --- a/crates/xcl/src/hle/d3d12x/fence_x.rs +++ b/crates/xcl/src/hle/d3d12x/fence_x.rs @@ -6,7 +6,7 @@ use std::collections::HashMap; use std::ffi::c_void; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Mutex, OnceLock}; +use std::sync::{Arc, Mutex, OnceLock}; use windows::core::Interface; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D12::ID3D12Fence; @@ -16,17 +16,130 @@ use windows_sys::Win32::System::Threading as th; #[repr(C, align(64))] struct Cell(AtomicU64); +/// Heap-isolated cell plus per-fence refresh lock (`true` = live, `false` = retired). +/// Keeping `Box` off the lock's cache line avoids false-sharing `monitorx`/`mwaitx` wakes. +struct CellMirror { + cell: Box, + refresh_lock: Mutex, +} + #[derive(Default)] struct Fence { - cell: Option<&'static Cell>, + cell: Option>, /// the highest value a queue was told to signal signalled: u64, /// the highest value a queue was told to wait for waited: u64, } -/// (fences are never freed: XCL holds a reference to each) -static FENCES: Mutex>> = Mutex::new(None); +#[derive(Default)] +struct State { + map: HashMap, + cells: Vec<(usize, Arc)>, +} + +/// (fences are never freed in production: XCL holds a reference to each) +struct FenceTable { + inner: Mutex, +} + +impl FenceTable { + fn new() -> Self { + Self { inner: Mutex::new(State::default()) } + } + + fn refresh_one(fence: usize, mirror: &CellMirror) { + let live = mirror.refresh_lock.lock().unwrap_or_else(|e| e.into_inner()); + if !*live { + return; + } + if let Some(v) = unsafe { borrowed(fence, |f| f.GetCompletedValue()) } { + mirror.cell.0.store(v, Ordering::Release); + } + } + + fn refresh(&self) { + let cells = self.inner.lock().unwrap_or_else(|e| e.into_inner()).cells.clone(); + for (p, mirror) in cells { + Self::refresh_one(p, &mirror); + } + } + + fn note_queue_signal(&self, fence: usize, value: u64) -> bool { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + let f = g.map.entry(fence).or_default(); + f.signalled = f.signalled.max(value); + f.cell.is_some() + } + + fn note_queue_wait(&self, fence: usize, value: u64) { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + let f = g.map.entry(fence).or_default(); + f.waited = f.waited.max(value); + } + + fn note_cpu_signal(&self, fence: usize) { + let mirror = self.inner.lock().unwrap_or_else(|e| e.into_inner()).map.get(&fence).and_then(|f| f.cell.clone()); + if let Some(mirror) = mirror { + Self::refresh_one(fence, &mirror); + } + } + + fn pending_summary(&self) -> String { + let snap: Vec<(usize, u64, u64, bool)> = { + let g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + g.map.iter().map(|(&p, f)| (p, f.signalled, f.waited, f.cell.is_some())).collect() + }; + let mut parts = Vec::new(); + for (p, signalled, waited, has_cell) in snap { + let done = unsafe { borrowed(p, |f| f.GetCompletedValue()) }.unwrap_or(0); + if done < signalled || done < waited { + parts.push(format!("{p:#x}(done={done:#x}/sig={signalled:#x}/wait={waited:#x},cell={has_cell})")); + } + } + if parts.is_empty() { "none".into() } else { parts.join(", ") } + } + + fn completed_value_address_with(&self, this: *mut c_void, arm_fn: impl FnOnce(usize, u64)) -> *const u64 { + let key = this as usize; + let (mirror, pending) = { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(m) = g.map.get(&key).and_then(|f| f.cell.as_ref()) { + return m.cell.0.as_ptr(); + } + let m = Arc::new(CellMirror { cell: Box::new(Cell(AtomicU64::new(0))), refresh_lock: Mutex::new(true) }); + let pending = { + let f = g.map.entry(key).or_default(); + f.cell = Some(Arc::clone(&m)); + f.signalled + }; + g.cells.push((key, Arc::clone(&m))); + (m, pending) + }; + if pending > 0 { + arm_fn(key, pending); + } + Self::refresh_one(key, &mirror); + mirror.cell.0.as_ptr() + } + + #[cfg(test)] + fn forget_fence(&self, fence: usize) { + let removed = { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + g.cells.retain(|(p, _)| *p != fence); + g.map.remove(&fence).and_then(|f| f.cell) + }; + if let Some(mirror) = removed { + *mirror.refresh_lock.lock().unwrap_or_else(|e| e.into_inner()) = false; + } + } +} + +fn table() -> &'static FenceTable { + static T: OnceLock = OnceLock::new(); + T.get_or_init(FenceTable::new) +} /// the event a completion sets (auto-reset); the first use starts the thread that follows it fn event() -> usize { @@ -35,7 +148,7 @@ fn event() -> usize { let e = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) as usize; let spawned = std::thread::Builder::new().name("xcl-fences".into()).spawn(move || loop { th::WaitForSingleObject(e as _, th::INFINITE); - refresh(); + table().refresh(); }); if let Err(err) = spawned { crate::xlog_error!("D3D12.X: no thread for the fences' completed values: {err}"); @@ -49,17 +162,6 @@ unsafe fn borrowed(fence: usize, f: impl FnOnce(&ID3D12Fence) -> R) -> Option ID3D12Fence::from_raw_borrowed(&p).map(f) } -fn refresh() { - let g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - for (&p, f) in g.iter().flatten() { - if let Some(c) = f.cell { - if let Some(v) = unsafe { borrowed(p, |f| f.GetCompletedValue()) } { - c.0.store(v, Ordering::Release); - } - } - } -} - unsafe fn arm(fence: usize, value: u64) { if let Some(Err(e)) = borrowed(fence, |f| f.SetEventOnCompletion(value, HANDLE(event() as *mut c_void))) { crate::xlog_warn!("D3D12.X: fence {fence:#x}: SetEventOnCompletion({value:#x}): {e}"); @@ -68,76 +170,35 @@ unsafe fn arm(fence: usize, value: u64) { /// A queue was told to signal `fence` (one of the title's) with `value`. pub(super) unsafe fn note_queue_signal(fence: usize, value: u64) { - let cell = { - let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let f = g.get_or_insert_with(HashMap::new).entry(fence).or_default(); - f.signalled = f.signalled.max(value); - f.cell.is_some() - }; - if cell { + if table().note_queue_signal(fence, value) { arm(fence, value); } } /// A queue was told to wait for `fence` (one of the title's) to reach `value`. pub(super) fn note_queue_wait(fence: usize, value: u64) { - let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let f = g.get_or_insert_with(HashMap::new).entry(fence).or_default(); - f.waited = f.waited.max(value); + table().note_queue_wait(fence, value); } /// The CPU signalled `fence`. pub(super) fn note_cpu_signal(fence: usize) { - let known = FENCES.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.get(&fence).is_some_and(|f| f.cell.is_some())); - if known { - refresh(); - } + table().note_cpu_signal(fence); } /// Diagnostic summary of title fences whose completed value lags their signalled or waited value. pub(super) fn pending_summary() -> String { - let g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let mut parts = Vec::new(); - for (&p, f) in g.iter().flatten() { - let done = unsafe { borrowed(p, |f| f.GetCompletedValue()) }.unwrap_or(0); - if done < f.signalled || done < f.waited { - parts.push(format!("{p:#x}(done={done:#x}/sig={:#x}/wait={:#x},cell={})", f.signalled, f.waited, f.cell.is_some())); - } - } - if parts.is_empty() { - "none".into() - } else { - parts.join(", ") - } + table().pending_summary() } /// fence #12: the address of its completed value pub(super) unsafe extern "system" fn completed_value_address(this: *mut c_void) -> *const u64 { - let (cell, pending) = { - let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let f = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); - match f.cell { - Some(c) => return c.0.as_ptr(), - None => { - let c: &'static Cell = Box::leak(Box::new(Cell(AtomicU64::new(0)))); - f.cell = Some(c); - (c, f.signalled) - } - } - }; - if pending > 0 { - arm(this as usize, pending); - } - refresh(); - cell.0.as_ptr() + table().completed_value_address_with(this, |f, v| arm(f, v)) } /// Remove a synthetic test fence from `FENCES` before it is dropped. #[cfg(test)] pub(super) fn forget_fence_for_test(fence: usize) { - if let Some(m) = FENCES.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { - m.remove(&fence); - } + table().forget_fence(fence); } #[cfg(test)] @@ -183,4 +244,144 @@ mod tests { std::mem::forget(fence); // the map keeps its address } } + + struct Gate { + entered: Arc, + release: Arc, + } + + #[repr(C)] + struct MockFence { + vtable: *const usize, + val: AtomicU64, + calls: std::sync::atomic::AtomicUsize, + gate: Mutex>, + } + unsafe impl Send for MockFence {} + unsafe impl Sync for MockFence {} + + impl MockFence { + fn new(val: u64) -> Box { + use std::mem::{offset_of, size_of}; + unsafe extern "system" fn get_val(this: *mut c_void) -> u64 { + let f = &*this.cast::(); + f.calls.fetch_add(1, Ordering::AcqRel); + let v = f.val.load(Ordering::Acquire); + if let Some(g) = f.gate.lock().unwrap().take() { + g.entered.wait(); + g.release.wait(); + } + v + } + extern "system" fn unexpected() { std::process::abort(); } + const SLOT: usize = size_of::(); + const LEN: usize = size_of::() / SLOT; + static VT: OnceLock<[usize; LEN]> = OnceLock::new(); + let vt = VT.get_or_init(|| { + let mut t = [unexpected as usize; LEN]; + t[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = get_val as usize; + t + }); + Box::new(Self { vtable: vt.as_ptr(), val: AtomicU64::new(val), calls: Default::default(), gate: Mutex::new(None) }) + } + fn as_ptr(&self) -> *mut c_void { std::ptr::from_ref(self) as *mut c_void } + fn arm_gate(&self) -> (Arc, Arc) { + let (e, r) = (Arc::new(std::sync::Barrier::new(2)), Arc::new(std::sync::Barrier::new(2))); + *self.gate.lock().unwrap() = Some(Gate { entered: e.clone(), release: r.clone() }); + (e, r) + } + } + + #[test] + fn refresh_and_pending_summary_do_not_block_concurrent_queue_and_cpu_signals() { + let table = Arc::new(FenceTable::new()); + let (a, b) = (MockFence::new(1), MockFence::new(2)); + let (pa, pb) = (a.as_ptr(), b.as_ptr()); + let _cell_a = table.completed_value_address_with(pa, |_, _| {}); + let cell_b = table.completed_value_address_with(pb, |_, _| {}); + assert!(table.note_queue_signal(pa as usize, 10)); + + // 1. refresh() must not hold global lock across GetCompletedValue(). + let (entered, release) = a.arm_gate(); + let t1 = Arc::clone(&table); + let h1 = std::thread::spawn(move || t1.refresh()); + entered.wait(); + b.val.store(4, Ordering::Release); + assert!(table.note_queue_signal(pb as usize, 4)); + table.note_queue_wait(pb as usize, 4); + table.note_cpu_signal(pb as usize); + assert_eq!(unsafe { (*(cell_b as *const AtomicU64)).load(Ordering::Acquire) }, 4); + release.wait(); + h1.join().unwrap(); + + // 2. pending_summary() must not hold global lock across GetCompletedValue(). + let (entered, release) = a.arm_gate(); + let t2 = Arc::clone(&table); + let h2 = std::thread::spawn(move || t2.pending_summary()); + entered.wait(); + b.val.store(7, Ordering::Release); + assert!(table.note_queue_signal(pb as usize, 7)); + table.note_queue_wait(pb as usize, 7); + table.note_cpu_signal(pb as usize); + assert_eq!(unsafe { (*(cell_b as *const AtomicU64)).load(Ordering::Acquire) }, 7); + release.wait(); + let summary = h2.join().unwrap(); + assert!(summary.contains("done=0x1/sig=0xa/"), "unexpected summary: {summary}"); + } + + #[test] + fn note_cpu_signal_and_refresh_avoid_unrelated_and_non_cell_fences() { + let table = FenceTable::new(); + let (a, b) = (MockFence::new(3), MockFence::new(5)); + let non_cells: Vec> = (0..64).map(|i| MockFence::new(i)).collect(); + let (pa, pb) = (a.as_ptr(), b.as_ptr()); + let _ = table.completed_value_address_with(pa, |_, _| {}); + let _ = table.completed_value_address_with(pb, |_, _| {}); + for f in &non_cells { + assert!(!table.note_queue_signal(f.as_ptr() as usize, 10)); + table.note_queue_wait(f.as_ptr() as usize, 10); + } + a.calls.store(0, Ordering::Release); + b.calls.store(0, Ordering::Release); + table.note_cpu_signal(pb as usize); + assert_eq!((a.calls.load(Ordering::Acquire), b.calls.load(Ordering::Acquire)), (0, 1)); + assert!(non_cells.iter().all(|f| f.calls.load(Ordering::Acquire) == 0)); + + a.calls.store(0, Ordering::Release); + b.calls.store(0, Ordering::Release); + table.refresh(); + assert_eq!((a.calls.load(Ordering::Acquire), b.calls.load(Ordering::Acquire)), (1, 1)); + assert!(non_cells.iter().all(|f| f.calls.load(Ordering::Acquire) == 0)); + + table.forget_fence(pa as usize); + a.calls.store(0, Ordering::Release); + b.calls.store(0, Ordering::Release); + table.refresh(); + assert_eq!((a.calls.load(Ordering::Acquire), b.calls.load(Ordering::Acquire)), (0, 1)); + } + + #[test] + fn per_cell_lock_prevents_stale_refresh_overwrite() { + let table = Arc::new(FenceTable::new()); + let a = MockFence::new(10); + let pa = a.as_ptr(); + let cell = table.completed_value_address_with(pa, |_, _| {}); + a.calls.store(0, Ordering::Release); + + let (entered, release) = a.arm_gate(); + let t1 = Arc::clone(&table); + let h1 = std::thread::spawn(move || t1.refresh()); + entered.wait(); + a.val.store(11, Ordering::Release); + let t2 = Arc::clone(&table); + let pa_addr = pa as usize; + let h2 = std::thread::spawn(move || t2.note_cpu_signal(pa_addr)); + std::thread::sleep(std::time::Duration::from_millis(20)); + assert_eq!(a.calls.load(Ordering::Acquire), 1, "note_cpu_signal must serialize behind in-flight refresh_lock"); + release.wait(); + h1.join().unwrap(); + h2.join().unwrap(); + assert_eq!(a.calls.load(Ordering::Acquire), 2); + assert_eq!(unsafe { (*(cell as *const AtomicU64)).load(Ordering::Acquire) }, 11); + } } diff --git a/crates/xcl/src/hle/d3d12x/flight.rs b/crates/xcl/src/hle/d3d12x/flight.rs new file mode 100644 index 0000000000..df7782eda0 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/flight.rs @@ -0,0 +1,383 @@ +//! A flight recorder of XCL's GPU side, on with `XCL_ACTIVITY` (or `XCL_FLIGHT=1`): what one run +//! of a title has to tell when the device is lost or the title stops, without another run. +//! +//! - **Queues.** Every fence XCL signals on a queue after its work (`signaled`: the title's +//! submits through `alloc_pool`, the sparse windows' queue and its read-back queue, the video +//! memory pages' queue, texture uploads, the AMD keep-awake queue) is polled every 50 ms: the +//! value submitted, the value done and when it last moved. A queue with work that has not moved +//! for a second is logged at once (`flight: … has not finished …`), and on a device removal or +//! a crash all queues are listed, the one that stopped first first. A device removed with no +//! command buffer in flight (what AMD's crash analysis showed for a retail title) leaves only +//! the queues' own operations – tile mappings, waits – and this says which queue stopped. +//! - **Counters**, a `flight (2 s)` line beside `profile (2 s)`: tile mappings by caller (calls, +//! tiles, time) and resources made by kind (calls, time), and the adapter's video memory +//! against its budget (`OVER` when past it) with the system's free memory and commit. +//! - **Events**, the last 2 048 (submits, tile mappings, big resources), printed with the queues. + +use std::collections::{HashMap, VecDeque}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use windows::Win32::Graphics::Direct3D12::*; + +pub fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + std::env::var("XCL_FLIGHT").map_or(std::env::var_os("XCL_ACTIVITY").is_some(), |v| v.trim() != "0") + }) +} + +fn start() -> Instant { + static T0: OnceLock = OnceLock::new(); + *T0.get_or_init(Instant::now) +} + +fn now_ms() -> u64 { + start().elapsed().as_millis() as u64 +} + +fn thread_id() -> u32 { + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() } +} + +// ---- events ------------------------------------------------------------------------------- + +#[derive(Clone)] +struct Event { + ms: u64, + thread: u32, + what: &'static str, + a: u64, + b: u64, + c: u64, +} + +const RING: usize = 2048; +static EVENTS: Mutex> = Mutex::new(VecDeque::new()); + +/// Notes `what` with three numbers (their meaning is the caller's: see `dump`'s lines). +pub fn event(what: &'static str, a: u64, b: u64, c: u64) { + if !on() { + return; + } + let e = Event { ms: now_ms(), thread: thread_id(), what, a, b, c }; + let mut g = EVENTS.lock().unwrap(); + if g.len() >= RING { + g.pop_front(); + } + g.push_back(e); +} + +// ---- queues ------------------------------------------------------------------------------- + +struct Tracked { + name: &'static str, + queue: usize, + fence: ID3D12Fence, + submitted: u64, + completed: u64, + last_submit_ms: u64, + last_progress_ms: u64, + stalled: bool, +} +// (the fence is used under the lock and by the poll thread only) +unsafe impl Send for Tracked {} + +static QUEUES: Mutex>> = Mutex::new(None); + +/// `queue` was given `Signal(fence, value)` after its work (`name`: whose queue it is). +pub fn signaled(name: &'static str, queue: usize, fence: &ID3D12Fence, value: u64) { + if !on() { + return; + } + ensure_poller(); + let now = now_ms(); + let key = windows::core::Interface::as_raw(fence) as usize; + { + let mut g = QUEUES.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + let t = m.entry(key).or_insert_with(|| Tracked { + name, + queue, + fence: fence.clone(), + submitted: 0, + completed: 0, + last_submit_ms: now, + last_progress_ms: now, + stalled: false, + }); + if value > t.submitted { + // a queue that had nothing to do starts its wait now + if t.submitted <= t.completed { + t.last_progress_ms = now; + } + t.submitted = value; + } + t.last_submit_ms = now; + } + event(name, queue as u64, value, 0); +} + +/// How long a queue with work may stay without finishing any before it is logged. +const STALL_MS: u64 = 1000; + +fn ensure_poller() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let _ = std::thread::Builder::new().name("xcl-flight".into()).spawn(|| loop { + std::thread::sleep(Duration::from_millis(50)); + poll(); + }); + }); +} + +fn poll() { + let now = now_ms(); + // (logged after the lock: submits note their fences under it) + let mut lines = Vec::new(); + // how long the longest stalled queue has not moved (ms) + let mut longest = 0u64; + { + let mut g = QUEUES.lock().unwrap(); + let Some(m) = g.as_mut() else { return }; + for t in m.values_mut() { + let c = unsafe { t.fence.GetCompletedValue() }; + if c == u64::MAX { + // the device is gone: what the queues held stays as it was for `dump` + continue; + } + if t.submitted > c { + longest = longest.max(now.saturating_sub(t.last_progress_ms)); + } + if c > t.completed { + t.completed = c; + t.last_progress_ms = now; + if t.stalled { + t.stalled = false; + lines.push((false, format!("flight: {} (queue {:#x}) moves again: done {} of {}", t.name, t.queue, c, t.submitted))); + } + } + if t.submitted > t.completed && !t.stalled && now.saturating_sub(t.last_progress_ms) >= STALL_MS { + t.stalled = true; + lines.push(( + true, + format!( + "flight: {} (queue {:#x}) has not finished value {} for {} ms (submitted up to {}, last submit {} ms ago)", + t.name, + t.queue, + t.completed + 1, + now - t.last_progress_ms, + t.submitted, + now.saturating_sub(t.last_submit_ms) + ), + )); + } + } + } + let stopped = lines.iter().any(|(warn, _)| *warn); + for (warn, l) in lines { + if warn { + crate::xlog_warn!("{l}"); + } else { + crate::xlog_info!("{l}"); + } + } + // a queue stopped: what the queues wait for on the GPU, while the fences can still be asked + if stopped { + super::list_x::log_pending_waits("a queue stopped"); + } + // A GPU that has not moved for 3 s: which dispatches started and did not finish (the markers + // are CPU memory, read without the driver), and at 8 s where every thread is. Here and not + // in the activity thread: in a retail title's hang its DXGI queries blocked in the driver, + // and the report never came. + if longest >= 3_000 { + super::culprit::on_watchdog_release(); + } + static DUMPED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if longest >= 8_000 && std::env::var("XCL_STALL_DUMP").is_ok_and(|v| v.trim() == "1") && !DUMPED.swap(true, std::sync::atomic::Ordering::Relaxed) { + crate::xlog_info!("flight: the GPU has not moved for {longest} ms: thread dump"); + crate::eh::dump_threads(); + } +} + +// ---- counters ----------------------------------------------------------------------------- + +#[derive(Default, Clone, Copy)] +struct Count { + calls: u64, + units: u64, + ns: u64, + longest_ns: u64, +} + +static TILE_MAPS: Mutex> = Mutex::new(Vec::new()); +static MADE: Mutex> = Mutex::new(Vec::new()); + +fn add(list: &Mutex>, key: &'static str, units: u64, d: Duration) { + let ns = d.as_nanos().min(u64::MAX as u128) as u64; + let mut g = list.lock().unwrap(); + let c = match g.iter_mut().find(|(k, _)| *k == key) { + Some((_, c)) => c, + None => { + g.push((key, Count::default())); + &mut g.last_mut().unwrap().1 + } + }; + c.calls += 1; + c.units += units; + c.ns += ns; + c.longest_ns = c.longest_ns.max(ns); +} + +/// An `UpdateTileMappings` of `caller` on `queue`: `tiles` tiles, the call took `d`. +pub fn tile_map(caller: &'static str, queue: usize, tiles: u64, d: Duration) { + if !on() { + return; + } + add(&TILE_MAPS, caller, tiles, d); + event("tile map", queue as u64, tiles, d.as_micros() as u64); +} + +/// A resource or heap made through `kind` (a creation call, `bytes` when known), in `d`. +pub fn made(kind: &'static str, bytes: u64, d: Duration) { + if !on() { + return; + } + add(&MADE, kind, bytes, d); + if bytes >= 8 << 20 || d >= Duration::from_millis(20) { + event(kind, bytes, d.as_micros() as u64, 0); + } +} + +fn take(list: &Mutex>) -> Vec<(&'static str, Count)> { + std::mem::take(&mut *list.lock().unwrap()) +} + +fn mb(b: u64) -> u64 { + b >> 20 +} + +/// The adapter's video memory against its budget, and the system's memory. +fn budget_text() -> String { + let mut s = String::new(); + if let Some((local, non_local)) = super::real::video_budget() { + let part = |name: &str, i: &windows::Win32::Graphics::Dxgi::DXGI_QUERY_VIDEO_MEMORY_INFO| { + format!( + "{name} {} of {} MB{}", + mb(i.CurrentUsage), + mb(i.Budget), + if i.Budget > 0 && i.CurrentUsage > i.Budget { " OVER" } else { "" } + ) + }; + s = format!("video memory {}, {}", part("local", &local), part("non-local", &non_local)); + } + unsafe { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m: MEMORYSTATUSEX = std::mem::zeroed(); + m.dwLength = std::mem::size_of::() as u32; + if GlobalMemoryStatusEx(&mut m) != 0 { + s.push_str(&format!( + "; system memory free {} of {} MB, commit free {} of {} MB", + mb(m.ullAvailPhys), + mb(m.ullTotalPhys), + mb(m.ullAvailPageFile), + mb(m.ullTotalPageFile) + )); + } + } + s +} + +/// The `flight (2 s)` line: tile mappings and resources made since the last line, the budget. +pub fn line() -> String { + let list = |v: Vec<(&'static str, Count)>, unit: &str| -> String { + if v.is_empty() { + return "none".into(); + } + v.iter() + .map(|(k, c)| { + format!("{k} {} calls, {} {unit}, {} ms (longest {} ms)", c.calls, c.units, c.ns / 1_000_000, c.longest_ns / 1_000_000) + }) + .collect::>() + .join(", ") + }; + let maps = list(take(&TILE_MAPS), "tiles"); + let made = take(&MADE); + let made = if made.is_empty() { + "none".to_string() + } else { + made.iter() + .map(|(k, c)| format!("{k} {} ({} MB, {} ms, longest {} ms)", c.calls, mb(c.units), c.ns / 1_000_000, c.longest_ns / 1_000_000)) + .collect::>() + .join(", ") + }; + format!("flight (2 s): tile mappings: {maps}; made: {made}; {}", budget_text()) +} + +// ---- the dump ----------------------------------------------------------------------------- + +/// Everything the recorder holds, into the log (once): on a device removal or a crash. A crash +/// leaves the video memory budget out: the title may have stopped inside the driver, holding its +/// locks, and asking DXGI then could hang the crash report. +pub fn dump(why: &str) { + static DONE: AtomicBool = AtomicBool::new(false); + if !on() || DONE.swap(true, Ordering::AcqRel) { + return; + } + let now = now_ms(); + // (a crash can come with these locks held: then without that part) + if let Ok(g) = QUEUES.try_lock() { + if let Some(m) = g.as_ref() { + let mut v: Vec<&Tracked> = m.values().collect(); + // the queue with work that stopped first, first + v.sort_by_key(|t| (t.submitted <= t.completed, t.last_progress_ms)); + crate::xlog_error!("flight: {why} at {now} ms – the queues XCL signals (the one that stopped first first):"); + for t in v { + crate::xlog_error!( + "flight: {} queue {:#x}: done {} of {} ({}), last moved {} ms ago, last submit {} ms ago", + t.name, + t.queue, + t.completed, + t.submitted, + if t.submitted > t.completed { "WORK PENDING" } else { "idle" }, + now.saturating_sub(t.last_progress_ms), + now.saturating_sub(t.last_submit_ms) + ); + } + } + } + if let Ok(g) = EVENTS.try_lock() { + // the tile mappings, most of the ring in a world load, are left out but for the slow ones + // (1 ms and more): they pushed the submits before a stop out of the 400 lines + let shown = |e: &&Event| e.what != "tile map" || e.c >= 1000; + let n = g.iter().filter(shown).count(); + let skip = n.saturating_sub(400); + crate::xlog_error!("flight: the last {} events but quick tile mappings (ms, thread, what, numbers), {} ms of them:", n - skip, g.front().map_or(0, |e| now.saturating_sub(e.ms))); + for e in g.iter().filter(shown).skip(skip) { + crate::xlog_error!("flight: {} t{} {} {:#x} {} {}", e.ms, e.thread, e.what, e.a, e.b, e.c); + } + } + if why != "crash" { + crate::xlog_error!("flight: {}", budget_text()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Counters sum calls, units and time by key and start again after a line. + #[test] + fn counters_sum_by_key_and_start_again() { + let l: Mutex> = Mutex::new(Vec::new()); + add(&l, "vram", 10, Duration::from_millis(3)); + add(&l, "vram", 5, Duration::from_millis(7)); + add(&l, "sparse", 1, Duration::from_millis(1)); + let v = take(&l); + let vram = v.iter().find(|(k, _)| *k == "vram").unwrap().1; + assert_eq!((vram.calls, vram.units), (2, 15)); + assert_eq!(vram.longest_ns, 7_000_000); + assert!(take(&l).is_empty()); + } +} 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..b601fc8f52 --- /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); + } + } +} + +/// 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::register_if_depth_uav(dev, raw, &prepared, init_state, STATE_UAV); + } + 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(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(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(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/frame.rs b/crates/xcl/src/hle/d3d12x/frame.rs index 38c073c0ec..e9caf39765 100644 --- a/crates/xcl/src/hle/d3d12x/frame.rs +++ b/crates/xcl/src/hle/d3d12x/frame.rs @@ -360,6 +360,7 @@ fn trace_calls(what: std::fmt::Arguments) { } pub unsafe extern "system" fn wait_frame_event_x(_this: *mut std::ffi::c_void, ty: u32, timeout_ms: u32, block: *const u8, flags: u32, token: *mut u64) -> HRESULT { + let _prof = super::prof::span(super::prof::Kind::FrameEvent); trace_calls(format_args!("WaitFrameEventX(type {ty}, timeout {timeout_ms} ms, block {block:p}, flags {flags:#x}, token in {:#x})", if token.is_null() { 0 } else { *token })); let scheduled = with(|c| { ((ty as usize) < TYPES && c.kinds[ty as usize].scheduled) diff --git a/crates/xcl/src/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs new file mode 100644 index 0000000000..cb4b872354 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -0,0 +1,674 @@ +//! The graphics pipelines a title used, as it described them, kept for the shader preparation of +//! its next run (`shaders::prepare_for_launch`): it builds them before the title starts, the way +//! the title does (`real::prepare_graphics`), so the title finds their translations and the +//! driver's blobs on disk. `used-pipelines.txt` holds only the keys of the shader sets and the +//! driver cache only blobs named after the translated DXIL: neither is enough to make one again. +//! +//! `used-graphics-pipelines.bin` beside the DXIL cache: +//! +//! ```text +//! file = "XCLGFXP\0", version u32, entry* +//! entry = length u32, check u32 (the low half of fnv64 of the payload), payload +//! payload = 1 key u64 shaders [u64; 5] state input* a pipeline +//! | 2 key u64 bytes a shader (preparation job files only) +//! key = `real::shaders_key` of the set (as `used-pipelines.txt` has it); in a shader entry +//! `real::shader_key` of it +//! shaders = `real::shader_key` of the VS, PS, DS, HS, GS (0: none) +//! state = every field of the description but its pointers, in `state`'s order (varints) +//! input = count, then each element's semantic name (length, bytes), index, format, slot, +//! offset, class, step rate (varints) +//! ``` +//! +//! Integers little-endian, varints LEB128. A pipeline entry holds no shader code: the preparation +//! takes the shaders from the title's shader files by key, as it does those of `used-shaders.txt` +//! (~200 bytes a pipeline). A file of another version is read as none and started again; an entry +//! cut short or damaged ends the file there (the writer cuts it off before it appends). The title +//! side: a pipeline's description is noted at its first use in a run (`note`, from +//! `pso_async::on_first_use`), each once, written by a thread of its own, the file at most +//! `XCL_GFX_RECORDS_MB` (64). + +use std::collections::HashSet; +use std::ffi::CString; +use std::io::{Seek, Write}; +use std::path::{Path, PathBuf}; +use windows::Win32::Graphics::Direct3D12::*; + +const MAGIC: &[u8; 8] = b"XCLGFXP\0"; +/// The layout of an entry: a change makes every file of the older one read as none. +const VERSION: u32 = 1; +const HEADER: usize = 12; +const PIPELINE: u8 = 1; +const SHADER: u8 = 2; + +/// The records of this cache (beside the DXIL cache, as `used-pipelines.txt`). +pub(crate) fn path() -> PathBuf { + crate::gpu::recomp::dxc::cache_dir().join("used-graphics-pipelines.bin") +} + +/// `XCL_GFX_RECORDS_MB`: the most the records may take on disk (64 MB: ~300 000 pipelines). +fn cap_bytes() -> u64 { + cap_of(std::env::var("XCL_GFX_RECORDS_MB").ok().as_deref()) +} + +fn cap_of(v: Option<&str>) -> u64 { + v.and_then(|v| v.trim().parse::().ok()).unwrap_or(64) << 20 +} + +fn put_var(out: &mut Vec, mut v: u64) { + loop { + let b = (v & 0x7f) as u8; + v >>= 7; + if v == 0 { + out.push(b); + return; + } + out.push(b | 0x80); + } +} + +struct Reader<'a>(&'a [u8]); + +impl Reader<'_> { + fn var(&mut self) -> Option { + let mut v = 0u64; + for shift in (0..64).step_by(7) { + let (&b, rest) = self.0.split_first()?; + self.0 = rest; + v |= ((b & 0x7f) as u64) << shift; + if b & 0x80 == 0 { + return Some(v); + } + } + None + } + fn u32var(&mut self) -> Option { + self.var().and_then(|v| u32::try_from(v).ok()) + } + fn u64(&mut self) -> Option { + let (b, rest) = self.0.split_at_checked(8)?; + self.0 = rest; + Some(u64::from_le_bytes(b.try_into().ok()?)) + } + fn bytes(&mut self, n: usize) -> Option<&[u8]> { + let (b, rest) = self.0.split_at_checked(n)?; + self.0 = rest; + Some(b) + } +} + +/// Every field of `d` but its pointers (shaders, root signature, input layout, stream output, +/// cached blob), each as a u32 handed to `f`, which may change it: one order for writing and +/// reading. What the title's translated pipeline is made of beside its shaders +/// (`real::graphics_blob_key` hashes the same). +fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32)) { + macro_rules! int { + ($x:expr) => {{ + let mut v = $x as u32; + f(&mut v); + $x = v as i32; + }}; + } + macro_rules! byte { + ($x:expr) => {{ + let mut v = $x as u32; + f(&mut v); + $x = v as u8; + }}; + } + macro_rules! float { + ($x:expr) => {{ + let mut v = $x.to_bits(); + f(&mut v); + $x = f32::from_bits(v); + }}; + } + let b = &mut d.BlendState; + int!(b.AlphaToCoverageEnable.0); + int!(b.IndependentBlendEnable.0); + for rt in &mut b.RenderTarget { + int!(rt.BlendEnable.0); + int!(rt.LogicOpEnable.0); + int!(rt.SrcBlend.0); + int!(rt.DestBlend.0); + int!(rt.BlendOp.0); + int!(rt.SrcBlendAlpha.0); + int!(rt.DestBlendAlpha.0); + int!(rt.BlendOpAlpha.0); + int!(rt.LogicOp.0); + byte!(rt.RenderTargetWriteMask); + } + f(&mut d.SampleMask); + let r = &mut d.RasterizerState; + int!(r.FillMode.0); + int!(r.CullMode.0); + int!(r.FrontCounterClockwise.0); + int!(r.DepthBias); + float!(r.DepthBiasClamp); + float!(r.SlopeScaledDepthBias); + int!(r.DepthClipEnable.0); + int!(r.MultisampleEnable.0); + int!(r.AntialiasedLineEnable.0); + f(&mut r.ForcedSampleCount); + int!(r.ConservativeRaster.0); + let z = &mut d.DepthStencilState; + int!(z.DepthEnable.0); + int!(z.DepthWriteMask.0); + int!(z.DepthFunc.0); + int!(z.StencilEnable.0); + byte!(z.StencilReadMask); + byte!(z.StencilWriteMask); + for face in [&mut z.FrontFace, &mut z.BackFace] { + int!(face.StencilFailOp.0); + int!(face.StencilDepthFailOp.0); + int!(face.StencilPassOp.0); + int!(face.StencilFunc.0); + } + int!(d.IBStripCutValue.0); + int!(d.PrimitiveTopologyType.0); + f(&mut d.NumRenderTargets); + for format in &mut d.RTVFormats { + int!(format.0); + } + int!(d.DSVFormat.0); + f(&mut d.SampleDesc.Count); + f(&mut d.SampleDesc.Quality); + f(&mut d.NodeMask); + int!(d.Flags.0); +} + +/// The pipeline entry of `d` (a title's description, its input layout readable), of the shader +/// set `key` whose shaders are `shaders` (`Record::shaders`). +pub(crate) unsafe fn encode(key: u64, shaders: [u64; 5], d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Vec { + let mut out = Vec::with_capacity(256); + out.push(PIPELINE); + out.extend_from_slice(&key.to_le_bytes()); + for s in shaders { + out.extend_from_slice(&s.to_le_bytes()); + } + // (a copy for `state`, which takes the fields by `&mut`; its pointers are not used) + let mut copy: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::ptr::read(d); + state(&mut copy, &mut |v| put_var(&mut out, *v as u64)); + let il = &d.InputLayout; + let elems = if il.NumElements > 0 && !il.pInputElementDescs.is_null() { std::slice::from_raw_parts(il.pInputElementDescs, il.NumElements as usize) } else { &[] }; + put_var(&mut out, elems.len() as u64); + for e in elems { + let name = if e.SemanticName.0.is_null() { &[][..] } else { std::ffi::CStr::from_ptr(e.SemanticName.0 as *const std::ffi::c_char).to_bytes() }; + put_var(&mut out, name.len() as u64); + out.extend_from_slice(name); + for v in [e.SemanticIndex, e.Format.0 as u32, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0 as u32, e.InstanceDataStepRate] { + put_var(&mut out, v as u64); + } + } + out +} + +/// A shader entry (the preparation's job files): `bytes`, of `real::shader_key` `key`. +pub(crate) fn shader_entry(key: u64, bytes: &[u8]) -> Vec { + let mut out = Vec::with_capacity(9 + bytes.len()); + out.push(SHADER); + out.extend_from_slice(&key.to_le_bytes()); + out.extend_from_slice(bytes); + out +} + +/// A pipeline as a title described it, but its shaders and root signature (`desc` puts them in). +pub(crate) struct Record { + pub key: u64, + /// `real::shader_key` of the VS, PS, DS, HS, GS (0: none) + pub shaders: [u64; 5], + desc: Box, + inputs: Vec, + _names: Vec, +} + +// (only read once made; the names the inputs point at live as long) +unsafe impl Send for Record {} +unsafe impl Sync for Record {} + +impl Record { + /// The description with the shaders `code` (VS, PS, DS, HS, GS), pointing into `self` and + /// `code`, with no root signature (a translated pipeline gets XCL's). + pub(crate) fn desc(&self, code: [Option<&[u8]>; 5]) -> D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // (no root signature in it: nothing is released twice) + let mut d: D3D12_GRAPHICS_PIPELINE_STATE_DESC = unsafe { std::ptr::read(&*self.desc) }; + let bytecode = |c: Option<&[u8]>| c.map_or_else(D3D12_SHADER_BYTECODE::default, |c| D3D12_SHADER_BYTECODE { pShaderBytecode: c.as_ptr().cast(), BytecodeLength: c.len() }); + let [vs, ps, ds, hs, gs] = code; + (d.VS, d.PS, d.DS, d.HS, d.GS) = (bytecode(vs), bytecode(ps), bytecode(ds), bytecode(hs), bytecode(gs)); + if !self.inputs.is_empty() { + d.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: self.inputs.as_ptr(), NumElements: self.inputs.len() as u32 }; + } + d + } +} + +pub(crate) enum Entry { + Pipeline(Record), + Shader(u64, Vec), +} + +/// The entry of `payload` (None: not one this version writes). +pub(crate) fn decode(payload: &[u8]) -> Option { + let (&tag, rest) = payload.split_first()?; + let mut r = Reader(rest); + let key = r.u64()?; + if tag == SHADER { + return Some(Entry::Shader(key, r.0.to_vec())); + } + if tag != PIPELINE { + return None; + } + let mut shaders = [0u64; 5]; + for s in &mut shaders { + *s = r.u64()?; + } + let mut desc: Box = Box::new(unsafe { std::mem::zeroed() }); + let mut short = false; + state(&mut desc, &mut |v| match r.u32var() { + Some(x) => *v = x, + None => short = true, + }); + if short { + return None; + } + let n = r.var()? as usize; + let mut names = Vec::new(); + let mut fields = Vec::new(); + for _ in 0..n.min(64) { + let len = r.var()? as usize; + names.push(CString::new(r.bytes(len)?).ok()?); + let mut f = [0u32; 6]; + for v in &mut f { + *v = r.u32var()?; + } + fields.push(f); + } + if n > 64 || !r.0.is_empty() { + return None; + } + let inputs = names + .iter() + .zip(&fields) + .map(|(name, f)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: windows::core::PCSTR(name.as_ptr().cast()), + SemanticIndex: f[0], + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(f[1] as i32), + InputSlot: f[2], + AlignedByteOffset: f[3], + InputSlotClass: D3D12_INPUT_CLASSIFICATION(f[4] as i32), + InstanceDataStepRate: f[5], + }) + .collect(); + Some(Entry::Pipeline(Record { key, shaders, desc, inputs, _names: names })) +} + +fn header() -> [u8; HEADER] { + let mut h = [0u8; HEADER]; + h[..8].copy_from_slice(MAGIC); + h[8..].copy_from_slice(&VERSION.to_le_bytes()); + h +} + +fn check(payload: &[u8]) -> u32 { + crate::gpu::shader::fnv64(payload) as u32 +} + +/// The payloads of a file's whole entries and where the last of them ends. None: no file of this +/// version (another one, or not one at all). +fn payloads(file: &[u8]) -> Option<(Vec<&[u8]>, usize)> { + if file.len() < HEADER || file[..HEADER] != header() { + return None; + } + let (mut list, mut at) = (Vec::new(), HEADER); + while let Some(head) = file.get(at..at + 8) { + let len = u32::from_le_bytes(head[..4].try_into().unwrap()) as usize; + let Some(payload) = file.get(at + 8..at + 8 + len) else { break }; + if check(payload) != u32::from_le_bytes(head[4..].try_into().unwrap()) { + break; + } + list.push(payload); + at += 8 + len; + } + Some((list, at)) +} + +/// The entries of the file at `path` (none: no file, or one of another version). +pub(crate) fn read(path: &Path) -> Vec> { + let file = std::fs::read(path).unwrap_or_default(); + payloads(&file).map_or_else(Vec::new, |(list, _)| list.into_iter().map(<[u8]>::to_vec).collect()) +} + +/// What became of an entry handed to `Writer::add`. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Added { + New, + /// in the file already + Known, + /// not written: the file is at its cap + Full, +} + +/// Appends entries to a file of records, each once, up to `cap` bytes. +pub(crate) struct Writer { + file: std::fs::File, + len: u64, + cap: u64, + seen: HashSet, + full: bool, +} + +impl Writer { + /// The file at `path` for appending: its whole entries are kept (a cut-short tail is cut off), + /// one of another version is started again. + pub(crate) fn open(path: &Path, cap: u64) -> std::io::Result { + let old = std::fs::read(path).unwrap_or_default(); + let (seen, end) = match payloads(&old) { + Some((list, end)) => (list.iter().map(|p| crate::gpu::shader::fnv64(p)).collect(), end), + None => (HashSet::new(), 0), + }; + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + let mut file = std::fs::OpenOptions::new().write(true).create(true).truncate(false).open(path)?; + let len = if end == 0 { + file.set_len(0)?; + file.write_all(&header())?; + HEADER as u64 + } else { + file.set_len(end as u64)?; + end as u64 + }; + file.seek(std::io::SeekFrom::Start(len))?; + Ok(Writer { file, len, cap, seen, full: false }) + } + + /// Entries in the file. + pub(crate) fn count(&self) -> usize { + self.seen.len() + } + + pub(crate) fn add(&mut self, payload: &[u8]) -> std::io::Result { + let id = crate::gpu::shader::fnv64(payload); + if self.seen.contains(&id) { + return Ok(Added::Known); + } + let n = 8 + payload.len() as u64; + if self.full || self.len + n > self.cap { + self.full = true; + return Ok(Added::Full); + } + let mut entry = Vec::with_capacity(n as usize); + entry.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + entry.extend_from_slice(&check(payload).to_le_bytes()); + entry.extend_from_slice(payload); + self.file.write_all(&entry)?; + self.len += n; + self.seen.insert(id); + Ok(Added::New) + } +} + +/// A graphics pipeline's first use in this run: its entry (`encode`) goes to the file on a thread +/// of its own, not the title's. +pub(crate) fn note(payload: Vec) { + use std::sync::{mpsc, Mutex, OnceLock}; + // (a test does not write the user's file) + if cfg!(test) { + return; + } + static TX: OnceLock>>> = OnceLock::new(); + let tx = TX.get_or_init(|| { + let (tx, rx) = mpsc::channel::>(); + let _ = std::thread::Builder::new().name("xcl-gfx-records".into()).spawn(move || { + let (path, cap) = (path(), cap_bytes()); + let mut w = match Writer::open(&path, cap) { + Ok(w) => w, + Err(e) => { + crate::xlog_warn!("D3D12.X: {}: {e} – the graphics pipelines of this run are not prepared before the next", path.display()); + return; + } + }; + crate::xlog_info!("D3D12.X: graphics pipelines are recorded at their first use for the next run's preparation ({} from earlier runs)", w.count()); + for payload in rx.iter() { + match w.add(&payload) { + Ok(Added::Full) => { + crate::xlog_warn!("D3D12.X: the graphics pipeline records are at their cap of {} MB (XCL_GFX_RECORDS_MB): pipelines first used from here on are not prepared before the next run", cap >> 20); + // (the rest are dropped unread) + for _ in rx.iter() {} + return; + } + Ok(_) => {} + Err(e) => { + crate::xlog_warn!("D3D12.X: {}: {e} – no more graphics pipelines are recorded in this run", path.display()); + return; + } + } + } + }); + Mutex::new(tx) + }); + let _ = tx.lock().unwrap().send(payload); +} + +#[cfg(test)] +mod tests { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; + + struct Directory(PathBuf); + impl Drop for Directory { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn directory(name: &str) -> Directory { + let dir = std::env::temp_dir().join(format!("xcl-gfx-records-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + Directory(dir) + } + + /// A description with every field set to a value of its own (none its default), written out + /// field by field here: a field `state` leaves out does not come back. + fn described() -> D3D12_GRAPHICS_PIPELINE_STATE_DESC { + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let mut n = 0x10; + let mut next = || { + n += 3; + n + }; + let b = &mut d.BlendState; + b.AlphaToCoverageEnable.0 = 1; + b.IndependentBlendEnable.0 = 1; + for rt in &mut b.RenderTarget { + rt.BlendEnable.0 = 1; + rt.LogicOpEnable.0 = 1; + rt.SrcBlend.0 = next(); + rt.DestBlend.0 = next(); + rt.BlendOp.0 = next(); + rt.SrcBlendAlpha.0 = next(); + rt.DestBlendAlpha.0 = next(); + rt.BlendOpAlpha.0 = next(); + rt.LogicOp.0 = next(); + rt.RenderTargetWriteMask = next() as u8; + } + d.SampleMask = 0xfedc_ba98; + let r = &mut d.RasterizerState; + r.FillMode.0 = next(); + r.CullMode.0 = next(); + r.FrontCounterClockwise.0 = 1; + r.DepthBias = -1234; + r.DepthBiasClamp = -0.25; + r.SlopeScaledDepthBias = 3.5; + r.DepthClipEnable.0 = 1; + r.MultisampleEnable.0 = 1; + r.AntialiasedLineEnable.0 = 1; + r.ForcedSampleCount = 8; + r.ConservativeRaster.0 = 1; + let z = &mut d.DepthStencilState; + z.DepthEnable.0 = 1; + z.DepthWriteMask.0 = 1; + z.DepthFunc.0 = next(); + z.StencilEnable.0 = 1; + z.StencilReadMask = 0x3c; + z.StencilWriteMask = 0xc3; + for face in [&mut z.FrontFace, &mut z.BackFace] { + face.StencilFailOp.0 = next(); + face.StencilDepthFailOp.0 = next(); + face.StencilPassOp.0 = next(); + face.StencilFunc.0 = next(); + } + d.IBStripCutValue.0 = 2; + d.PrimitiveTopologyType.0 = 3; + d.NumRenderTargets = 7; + for f in &mut d.RTVFormats { + *f = DXGI_FORMAT(next()); + } + d.DSVFormat = DXGI_FORMAT(next()); + d.SampleDesc.Count = 4; + d.SampleDesc.Quality = 9; + d.NodeMask = 0x5; + d.Flags.0 = 1; + d + } + + fn pipeline(payload: &[u8]) -> Record { + match decode(payload) { + Some(Entry::Pipeline(r)) => r, + _ => panic!("not a pipeline entry"), + } + } + + /// A description comes back with every field (as the key of its translated pipeline's driver + /// blob sees them), its input layout and its shaders' keys. + #[test] + fn a_description_comes_back_as_it_was_written() { + let names = [CString::new("POSITION").unwrap(), CString::new("TEXCOORD").unwrap()]; + let elems = [ + D3D12_INPUT_ELEMENT_DESC { SemanticName: windows::core::PCSTR(names[0].as_ptr().cast()), SemanticIndex: 0, Format: DXGI_FORMAT(6), InputSlot: 0, AlignedByteOffset: 0, InputSlotClass: D3D12_INPUT_CLASSIFICATION(0), InstanceDataStepRate: 0 }, + D3D12_INPUT_ELEMENT_DESC { SemanticName: windows::core::PCSTR(names[1].as_ptr().cast()), SemanticIndex: 3, Format: DXGI_FORMAT(16), InputSlot: 2, AlignedByteOffset: u32::MAX, InputSlotClass: D3D12_INPUT_CLASSIFICATION(1), InstanceDataStepRate: 7 }, + ]; + let mut d = described(); + d.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elems.as_ptr(), NumElements: 2 }; + let shaders = [11, 22, 0, 0, 55]; + let payload = unsafe { encode(0xabcd_ef01, shaders, &d) }; + assert!(payload.len() < 400, "{} bytes", payload.len()); + let r = pipeline(&payload); + assert_eq!((r.key, r.shaders), (0xabcd_ef01, shaders)); + let (vs, ps, gs) = (b"vs".as_slice(), b"pixel".as_slice(), b"g".as_slice()); + let back = r.desc([Some(vs), Some(ps), None, None, Some(gs)]); + let key = |d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC| unsafe { super::super::real::graphics_blob_key(d, b"dxil", None, None, &[]) }; + assert_eq!(key(&back), key(&d), "the state and the input layout"); + assert_ne!(key(&back), key(&described()), "(the input layout is in the key)"); + assert_eq!(unsafe { encode(0xabcd_ef01, shaders, &back) }, payload); + assert_eq!((back.VS.BytecodeLength, back.PS.BytecodeLength, back.DS.BytecodeLength, back.GS.BytecodeLength), (2, 5, 0, 1)); + assert!(back.pRootSignature.is_none()); + // a description without an input layout + let plain = unsafe { encode(1, [1, 0, 0, 0, 0], &described()) }; + let back = pipeline(&plain).desc([None; 5]); + assert_eq!((back.InputLayout.NumElements, back.InputLayout.pInputElementDescs.is_null()), (0, true)); + assert_eq!(key(&back), key(&described())); + } + + #[test] + fn a_shader_entry_and_a_damaged_payload() { + match decode(&shader_entry(0x77, b"code")) { + Some(Entry::Shader(k, b)) => assert_eq!((k, b.as_slice()), (0x77, b"code".as_slice())), + _ => panic!("not a shader entry"), + } + let payload = unsafe { encode(9, [9, 0, 0, 0, 0], &described()) }; + assert!(decode(&payload[..payload.len() - 1]).is_none(), "cut short"); + assert!(decode(&[payload.as_slice(), &[0]].concat()).is_none(), "a byte too many"); + assert!(decode(&[3, 0, 0, 0, 0, 0, 0, 0, 0]).is_none(), "another kind of entry"); + } + + /// Written, read back in order, each entry once; a file cut short in its last entry keeps the + /// ones before it and the writer goes on after them. + #[test] + fn entries_are_written_once_and_read_back() { + let dir = directory("round"); + let p = dir.0.join("cache").join("records.bin"); + let a = unsafe { encode(1, [1, 0, 0, 0, 0], &described()) }; + let b = shader_entry(2, b"shader"); + let mut w = Writer::open(&p, 1 << 20).unwrap(); + assert_eq!(w.add(&a).unwrap(), Added::New); + assert_eq!(w.add(&b).unwrap(), Added::New); + assert_eq!(w.add(&a).unwrap(), Added::Known); + drop(w); + assert_eq!(read(&p), vec![a.clone(), b.clone()]); + let mut w = Writer::open(&p, 1 << 20).unwrap(); + assert_eq!((w.count(), w.add(&b).unwrap()), (2, Added::Known), "known from the file"); + drop(w); + // a run cut short in its third entry + let whole = std::fs::read(&p).unwrap(); + std::fs::write(&p, [whole.as_slice(), &[40, 0, 0, 0, 1, 2]].concat()).unwrap(); + assert_eq!(read(&p), vec![a.clone(), b.clone()]); + let c = shader_entry(3, b"another"); + let mut w = Writer::open(&p, 1 << 20).unwrap(); + assert_eq!(w.add(&c).unwrap(), Added::New); + drop(w); + assert_eq!(read(&p), vec![a.clone(), b.clone(), c.clone()]); + // a damaged entry ends the file there + let mut bytes = std::fs::read(&p).unwrap(); + let last = bytes.len() - 1; + bytes[last] ^= 0xff; + std::fs::write(&p, &bytes).unwrap(); + assert_eq!(read(&p), vec![a, b]); + } + + /// A file of another version (or no file of records at all) is read as none, and the writer + /// starts it again. + #[test] + fn a_file_of_another_version_is_passed_over() { + let dir = directory("version"); + let p = dir.0.join("records.bin"); + let a = shader_entry(5, b"five"); + let mut w = Writer::open(&p, 1 << 20).unwrap(); + w.add(&a).unwrap(); + drop(w); + let mut bytes = std::fs::read(&p).unwrap(); + bytes[8..12].copy_from_slice(&(VERSION + 1).to_le_bytes()); + std::fs::write(&p, &bytes).unwrap(); + assert!(read(&p).is_empty()); + let mut w = Writer::open(&p, 1 << 20).unwrap(); + assert_eq!((w.count(), w.add(&a).unwrap()), (0, Added::New)); + drop(w); + assert_eq!(read(&p), vec![a.clone()]); + assert_eq!(&std::fs::read(&p).unwrap()[8..12], &VERSION.to_le_bytes()); + std::fs::write(&p, b"not records").unwrap(); + assert!(read(&p).is_empty()); + assert!(read(&dir.0.join("none.bin")).is_empty()); + } + + /// An entry that would take the file past its cap is not written, nor any after it. + #[test] + fn the_file_stops_at_its_cap() { + assert_eq!(cap_of(None), 64 << 20); + assert_eq!(cap_of(Some(" 2 ")), 2 << 20); + assert_eq!(cap_of(Some("lots")), 64 << 20); + let dir = directory("cap"); + let p = dir.0.join("records.bin"); + let (a, b, small) = (shader_entry(1, &[1; 40]), shader_entry(2, &[2; 40]), shader_entry(3, &[])); + // (room for `small` after `a`, not for `b`) + let cap = (HEADER + 8 + a.len() + 8 + small.len()) as u64; + let mut w = Writer::open(&p, cap).unwrap(); + assert_eq!(w.add(&a).unwrap(), Added::New); + assert_eq!(w.add(&b).unwrap(), Added::Full); + assert_eq!(w.add(&small).unwrap(), Added::Full, "nothing after the cap was hit"); + assert_eq!(w.add(&a).unwrap(), Added::Known); + drop(w); + assert_eq!(read(&p), vec![a]); + assert!(std::fs::metadata(&p).unwrap().len() <= cap); + } + + #[test] + fn varints_round_trip() { + for v in [0u64, 1, 0x7f, 0x80, 0x3fff, 0x4000, u32::MAX as u64, u64::MAX] { + let mut out = Vec::new(); + put_var(&mut out, v); + let mut r = Reader(&out); + assert_eq!(r.var(), Some(v)); + assert!(r.0.is_empty()); + } + assert_eq!(Reader(&[0x80]).var(), None, "cut short"); + } +} 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..77c5833209 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/gpu_awake.rs @@ -0,0 +1,415 @@ +//! 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 { + super::flight::signaled("gpu-awake", windows::core::Interface::as_raw(&state.queue) as usize, &state.fence, next_val); + } + 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/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 18ddc684e7..3ea02efb1c 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -21,8 +21,14 @@ const SEAL_EVERY: Duration = Duration::from_millis(10); /// how often the thread here looks for batches that can go const TICK: Duration = Duration::from_millis(4); +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum DeferredItem { + Com(usize), + Uma { ptr: usize, sparse: bool }, +} + struct Batch { - dead: Vec, + dead: Vec, /// (fence, value) a queue: all reached = nothing submitted before the batch closed is left marks: Vec<(ID3D12Fence, u64)>, } @@ -31,7 +37,7 @@ struct Batch { struct Held { /// queue → its fence here and the last value signalled on it fences: HashMap, - open: Vec, + open: Vec, sealed: VecDeque, last_seal: Option, } @@ -44,10 +50,23 @@ impl Held { self.open.is_empty() && self.sealed.is_empty() } + fn needs_seal(&self, seal_now: bool) -> bool { + !self.open.is_empty() && (seal_now || self.last_seal.is_none_or(|t| t.elapsed() >= SEAL_EVERY)) + } + + /// Take out the sealed batches every queue is past without touching `open`. + unsafe fn reap(&mut self) -> Vec { + let mut gone = Vec::new(); + while self.sealed.front().is_some_and(|b| b.marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)) { + gone.extend(self.sealed.pop_front().unwrap().dead); + } + gone + } + /// 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: the resources 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)) { + /// and take out the batches every queue is past: the items to release now. + unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec { + if self.needs_seal(seal_now) { let mut marks = Vec::with_capacity(queues.len()); let mut ok = true; for q in queues { @@ -76,11 +95,7 @@ impl Held { self.sealed.push_back(Batch { dead, marks }); } } - let mut gone = Vec::new(); - while self.sealed.front().is_some_and(|b| b.marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)) { - gone.extend(self.sealed.pop_front().unwrap().dead); - } - gone + self.reap() } } @@ -95,21 +110,7 @@ pub fn enabled() -> bool { /// how long a last `Release` itself waits for queues with nothing to do to say so const IDLE_WAIT: Duration = Duration::from_micros(300); -/// `res` (an adopted resource) holds one reference that is now this module's. With no work in -/// flight it goes before this returns (the queues pass a fence value at once): a title that -/// frees the memory under a resource right after its last `Release` finds it unpinned, as -/// before. Otherwise the thread here lets it go. -pub unsafe fn hold(res: usize) { - HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(res); - let start = Instant::now(); - drain_known(true); - while start.elapsed() < IDLE_WAIT && HELD.lock().unwrap().as_ref().is_some_and(|h| !h.is_empty()) { - std::hint::spin_loop(); - drain_known(false); - } - if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { - return; - } +fn ensure_thread() { // A thread of its own lets the held ones go: the title may release a resource and then // wait for its memory without another submit (an imported heap pins the pages under its // resources – unmapping them stood still while one was held "until the next submit"). @@ -122,29 +123,106 @@ pub unsafe fn hold(res: usize) { }); } -/// 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) { +unsafe fn enqueue(item: DeferredItem) { + let busy = { + let mut g = HELD.lock().unwrap(); + let h = g.get_or_insert_with(Held::default); + let busy = !h.sealed.is_empty(); + h.open.push(item); + busy + }; + if busy { + // A sealed batch is already in flight on the GPU: let the background thread batch + // this release into the next SEAL_EVERY signal instead of issuing a per-release + // Signal on every queue and spinning IDLE_WAIT on the caller's thread. + ensure_thread(); + return; + } + let start = Instant::now(); + drain_known(true); + while start.elapsed() < IDLE_WAIT && HELD.lock().unwrap().as_ref().is_some_and(|h| !h.is_empty()) { + std::hint::spin_loop(); + drain_known(false); + } if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { return; } - let mut queues: Vec = Vec::new(); - for raw in super::present::known_queues() { - let raw = raw as *mut c_void; - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) { - queues.push(q.clone()); - } + ensure_thread(); +} + +/// `res` (an adopted resource) holds one reference that is now this module's. With no work in +/// flight it goes before this returns (the queues pass a fence value at once): a title that +/// frees the memory under a resource right after its last `Release` finds it unpinned, as +/// before. Otherwise the thread here lets it go. +pub unsafe fn hold(res: usize) { + enqueue(DeferredItem::Com(res)); +} + +/// Defer freeing a UMA block (`sparse::free` or `uma::Uma::free`) until every queue XCL knows +/// of has passed the work submitted before this call, so in-flight GPU lists finish before the +/// block is reused or decommitted. +pub(super) fn hold_uma(ptr: usize, sparse: bool) { + if ptr == 0 { + return; } - queues.extend(super::sparse::queue()); - queues.extend(super::title_textures::upload_queues()); - let gone = match HELD.lock().unwrap().as_mut() { - Some(h) => h.drain(&queues, seal_now), - None => return, + unsafe { enqueue(DeferredItem::Uma { ptr, sparse }) }; +} + +/// 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) { + let need_queues = { + let g = HELD.lock().unwrap(); + let Some(h) = g.as_ref() else { return }; + if h.is_empty() { + return; + } + h.needs_seal(seal_now) + }; + let gone = if need_queues { + let mut queues: Vec = Vec::new(); + for raw in super::present::known_queues() { + let raw = raw as *mut c_void; + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) { + queues.push(q.clone()); + } + } + queues.extend(super::sparse::queue()); + queues.extend(super::vram::queues()); + queues.extend(super::title_textures::upload_queues()); + match HELD.lock().unwrap().as_mut() { + Some(h) => h.drain(&queues, seal_now), + None => return, + } + } else { + match HELD.lock().unwrap().as_mut() { + Some(h) => h.reap(), + None => return, + } }; // (outside the lock: a release may end other objects, whose releases come back here) - for res in gone { - 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); + for item in gone { + match item { + DeferredItem::Com(res) => { + if super::vram::recycle_ready(res) { + continue; + } + let ptr = res as *mut c_void; + let f: unsafe extern "system" fn(*mut c_void) -> u32 = if super::real::is_adopted(ptr) { + std::mem::transmute(super::real::orig_fn(ptr, 2)) + } else { + std::mem::transmute(*(*(ptr as *const *const usize)).add(2)) + }; + f(ptr); + } + DeferredItem::Uma { ptr, sparse } => { + if sparse { + super::sparse::free(ptr); + } else if let Some(u) = crate::gpu::uma::get() { + u.free(ptr); + } + } + } } } @@ -180,7 +258,7 @@ mod tests { let raw = res.unwrap().into_raw() as usize; let mut held = Held::default(); - held.open.push(raw); + held.open.push(DeferredItem::Com(raw)); let queues = [queue.clone()]; assert!(held.drain(&queues, false).is_empty(), "the queue has not passed the batch's fence value"); std::thread::sleep(Duration::from_millis(100)); @@ -194,7 +272,7 @@ mod tests { std::thread::sleep(Duration::from_millis(5)); gone = held.drain(&queues, false); } - assert_eq!(gone, vec![raw], "released once the queue is past the batch"); + assert_eq!(gone, vec![DeferredItem::Com(raw)], "released once the queue is past the batch"); assert!(held.is_empty()); drop(ID3D12Resource::from_raw(raw as *mut c_void)); } @@ -204,8 +282,47 @@ mod tests { #[test] fn without_queues_a_batch_goes_at_once() { let mut held = Held::default(); - held.open.push(0x1000); - assert_eq!(unsafe { held.drain(&[], false) }, vec![0x1000]); + held.open.push(DeferredItem::Com(0x1000)); + assert_eq!(unsafe { held.drain(&[], false) }, vec![DeferredItem::Com(0x1000)]); assert!(held.is_empty()); } + + /// `reap()` only drains completed sealed batches and never prematurely releases `open` items. + #[test] + fn reap_keeps_open_items_and_respects_seal_interval() { + let mut held = Held::default(); + held.last_seal = Some(Instant::now()); + held.open.push(DeferredItem::Com(0x2000)); + assert!(!held.needs_seal(false), "within SEAL_EVERY: batching defers sealing"); + assert!(held.needs_seal(true), "explicit seal_now seals immediately"); + assert!(unsafe { held.reap() }.is_empty()); + assert_eq!(held.open, vec![DeferredItem::Com(0x2000)]); + } + + /// Deferred UMA blocks retire in FIFO order alongside COM releases and wait for active GPU queues. + #[test] + fn hold_uma_preserves_order_and_frees_on_idle_drain() { + let mut held = Held::default(); + held.open.push(DeferredItem::Com(0x1000)); + held.open.push(DeferredItem::Uma { ptr: 0x2000_0000, sparse: false }); + held.open.push(DeferredItem::Uma { ptr: 0x3000_0000, sparse: true }); + assert_eq!( + unsafe { held.drain(&[], false) }, + vec![ + DeferredItem::Com(0x1000), + DeferredItem::Uma { ptr: 0x2000_0000, sparse: false }, + DeferredItem::Uma { ptr: 0x3000_0000, sparse: true }, + ] + ); + assert!(held.is_empty()); + + // Real UMA block deferred through `hold_uma` is returned once no GPU queues are busy. + let Some(u) = crate::gpu::uma::get() else { return }; + let before = u.used(); + let ptr = u.alloc(0x1_0000, 0x1_0000).expect("UMA alloc") as usize; + assert!(u.used() >= before + 0x1_0000); + hold_uma(ptr, false); + // With no active queues in unit tests, `hold_uma` drains synchronously and frees the block. + assert_eq!(u.used(), before, "deferred UMA block should be freed once queues are idle"); + } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..7330c2e324 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -21,7 +21,7 @@ use std::collections::HashMap; use std::ffi::c_void; use std::mem::{transmute_copy, ManuallyDrop}; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Condvar, LazyLock, Mutex, OnceLock}; +use std::sync::{Arc, Condvar, LazyLock, Mutex, OnceLock}; use std::time::{Duration, Instant}; use windows::core::Interface; @@ -124,6 +124,87 @@ 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 { + device_of(list) +} + +/// Restore title bindings, PC root signatures, bound PSO, and dynamic/fallback depth-bias state +/// after an internal graphics/compute sync pass on `list`. +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 = LISTS.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 let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.last_pc_pso = 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) = LISTS.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); @@ -309,16 +390,127 @@ impl PendingWait { } } -/// Recorded `OMSetRenderTargets` state for `KickoffX` restoration and `XCL_TRACE_FRAME`. +/// Number of per-list `(8 RTV + 1 DSV)` shadow slots per allocated CPU descriptor heap chunk. +const RT_SHADOW_CHUNK_SLOTS: u32 = 256; + +fn rt_snapshot_enabled() -> bool { + static ENABLED: OnceLock = OnceLock::new(); + *ENABLED.get_or_init(|| std::env::var("XCL_RT_SNAPSHOT").map(|v| v != "0").unwrap_or(true)) +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +struct RtShadowEntry { + rtv_base: usize, + rtv_inc: usize, + dsv_handle: usize, +} + +struct RtShadowPool { + /// Private CPU-only RTV/DSV descriptor heaps kept alive for the device's lifetime so copied + /// handles remain valid across mid-recording splits and `KickoffX` resets. + _heaps: Vec<(ID3D12DescriptorHeap, ID3D12DescriptorHeap)>, + free: Vec, +} + +static RT_SHADOW_POOLS: Mutex>> = Mutex::new(None); + +/// Owned slot in a device's private CPU-only RTV/DSV shadow heaps. +/// +/// D3D12 consumes CPU RTV/DSV descriptors synchronously when `OMSetRenderTargets` is recorded, +/// so recycling the slot on `Drop` (once every `Bindings` clone referencing it is gone) needs no +/// GPU fence wait. +#[derive(Debug, PartialEq, Eq)] +struct RtShadowSlot { + dev_key: usize, + entry: RtShadowEntry, +} + +impl Drop for RtShadowSlot { + fn drop(&mut self) { + let mut g = RT_SHADOW_POOLS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(pool) = g.as_mut().and_then(|m| m.get_mut(&self.dev_key)) { + pool.free.push(self.entry); + } + } +} + +unsafe fn alloc_rt_shadow_slot(dev: &ID3D12Device) -> Option> { + let dev_key = dev.as_raw() as usize; + { + let mut g = RT_SHADOW_POOLS.lock().unwrap(); + if let Some(entry) = g.as_mut().and_then(|m| m.get_mut(&dev_key)).and_then(|p| p.free.pop()) { + return Some(Arc::new(RtShadowSlot { dev_key, entry })); + } + } + let rtv_desc = D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: RT_SHADOW_CHUNK_SLOTS * D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }; + let dsv_desc = D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + NumDescriptors: RT_SHADOW_CHUNK_SLOTS, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }; + let rtv_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&rtv_desc).ok()?; + let dsv_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&dsv_desc).ok()?; + let rtv_start = rtv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + let dsv_start = dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + let rtv_inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; + let dsv_inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + if rtv_start == 0 || dsv_start == 0 || rtv_inc == 0 || dsv_inc == 0 { + return None; + } + let slots_per_rtv = D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT as usize; + let mut new_entries = Vec::with_capacity(RT_SHADOW_CHUNK_SLOTS as usize); + for i in 0..RT_SHADOW_CHUNK_SLOTS as usize { + new_entries.push(RtShadowEntry { + rtv_base: rtv_start + i * slots_per_rtv * rtv_inc, + rtv_inc, + dsv_handle: dsv_start + i * dsv_inc, + }); + } + let entry = new_entries.pop()?; + let mut g = RT_SHADOW_POOLS.lock().unwrap(); + let pool = g.get_or_insert_with(HashMap::new).entry(dev_key).or_insert_with(|| RtShadowPool { + _heaps: Vec::new(), + free: Vec::new(), + }); + pool._heaps.push((rtv_heap, dsv_heap)); + pool.free.extend(new_entries); + Some(Arc::new(RtShadowSlot { dev_key, entry })) +} + +/// Monotonic generation bumped whenever any CPU RTV or DSV descriptor slot is created or +/// overwritten (`CreateRenderTargetView`, `CreateDepthStencilView`, `CopyDescriptors*(RTV|DSV)`). +/// Semantic `OMSetRenderTargets` dedup skips a rebind only when this generation is unchanged. +static RT_DESC_GEN: AtomicU64 = AtomicU64::new(1); + +pub(super) fn bump_rt_desc_gen() { + RT_DESC_GEN.fetch_add(1, Ordering::Release); +} + +/// Recorded `OMSetRenderTargets` state for `KickoffX` / split restoration and `XCL_TRACE_FRAME`. #[derive(Clone, Debug, PartialEq, Eq)] struct RenderTargets { /// Requested `NumRenderTargetDescriptors` (clamped to D3D12 max 8; 0 if `handles` is empty). num_targets: u32, - /// Saved descriptor handles: 1 base handle when `single != 0` and `num_targets > 0`, + /// Saved guest descriptor handles: 1 base handle when `single != 0` and `num_targets > 0`, /// otherwise `num_targets` handles. handles: Vec, single: i32, dsv: Option, + /// Private CPU-descriptor snapshot taken at bind time so later mid-list splits and + /// `KickoffX` resets never replay a guest RTV/DSV slot the title already overwrote. + shadow: Option>, + shadow_has_rtvs: bool, + shadow_has_dsv: bool, + /// `RT_DESC_GEN` observed when these targets were bound on this list. + desc_gen: u64, + /// True when these exact targets are currently active on the PC command list. + live_on_pc: bool, } /// What console code set on a list that a PC Reset clears: `KickoffX` closes, submits and @@ -483,6 +675,17 @@ fn with_bindings(list: *mut c_void, f: impl FnOnce(&mut Bindings)) { f(&mut g.get_or_insert_with(HashMap::new).entry(list as usize).or_default().bindings); } +/// (tests) The view heaps XCL counts as bound on `list`; forgetting the list with `forget`. +#[cfg(test)] +pub(super) fn bound_heaps(list: *mut c_void, forget: bool) -> Vec { + let mut heaps = Vec::new(); + with_bindings(list, |b| heaps = b.heaps.clone()); + if forget { + LISTS.lock().unwrap().as_mut().map(|m| m.remove(&(list as usize))); + } + heaps +} + const PC_IA_SET_PRIMITIVE_TOPOLOGY: usize = 20; const PC_RS_SET_VIEWPORTS: usize = 21; const PC_RS_SET_SCISSOR_RECTS: usize = 22; @@ -554,15 +757,142 @@ pub(super) unsafe extern "system" fn om_set_stencil_ref_x(this: *mut c_void, r: pc::(this, PC_OM_SET_STENCIL_REF)(this, r) } +/// Whether `OMSetRenderTargets(n, rtvs, single, dsv)` is semantically identical to what is +/// already active on `this` (same handles/counts/single/DSV and no RTV/DSV CPU descriptor slot +/// was created or copied since that bind). Opt-out via `XCL_BIND_CACHE=0`. +pub(super) unsafe fn skip_redundant_render_targets( + this: *mut c_void, + n: u32, + rtvs: *const usize, + single: i32, + dsv: *const usize, +) -> bool { + if !bind_cache_enabled() || super::present::trace_frame() || this.is_null() { + return false; + } + let num_targets = if rtvs.is_null() { 0 } else { n.min(D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) }; + let read_count = if single != 0 { num_targets.min(1) } else { num_targets } as usize; + let slice: &[usize] = if read_count == 0 { &[] } else { std::slice::from_raw_parts(rtvs, read_count) }; + let d = dsv.as_ref().copied(); + let cur_gen = RT_DESC_GEN.load(Ordering::Acquire); + LISTS + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(this as usize))) + .and_then(|s| s.bindings.render_targets.as_ref()) + .is_some_and(|rt| { + rt.live_on_pc + && rt.desc_gen == cur_gen + && rt.num_targets == num_targets + && rt.single == single + && rt.dsv == d + && rt.handles.as_slice() == slice + }) +} + /// OMSetRenderTargets as the PC list got it (`real::cl_om_set_render_targets`) pub(super) unsafe fn note_render_targets(this: *mut c_void, n: u32, rtvs: *const usize, single: i32, dsv: *const usize) { + let desc_gen = RT_DESC_GEN.load(Ordering::Acquire); let num_targets = if rtvs.is_null() { 0 } else { n.min(D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) }; let read_count = if single != 0 { num_targets.min(1) } else { num_targets } as usize; // SAFETY: `rtvs` is non-null whenever `read_count > 0`, and D3D12 requires at least 1 // handle when `RTsSingleHandleToDescriptorRange != 0` or `num_targets` handles otherwise. 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 })); + + let want_rtv = num_targets > 0 && !handles.is_empty() && handles.iter().all(|&h| h != 0); + let want_dsv = d.is_some_and(|dh| dh != 0); + + // Check whether `this` is a tracked real D3D12 command list (fake test lists never call + // `on_create`, so `list_type` is `None` and we must not invoke COM `GetDevice` on them). + // When this list already owns an unshared shadow slot (`strong_count == 1`), detach it for + // lock-free in-place reuse outside `LISTS`. + let (is_real_list, prev_slot) = if rt_snapshot_enabled() && (want_rtv || want_dsv) { + let mut g = LISTS.lock().unwrap(); + if let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(this as usize))) { + let real_list = s.list_type.is_some(); + let reuse = if real_list { + s.bindings + .render_targets + .as_mut() + .and_then(|rt| { + if rt.shadow.as_ref().is_some_and(|a| Arc::strong_count(a) == 1) { + rt.shadow.take() + } else { + None + } + }) + } else { + None + }; + (real_list, reuse) + } else { + (false, None) + } + } else { + (false, None) + }; + + let mut shadow: Option> = None; + let mut shadow_has_rtvs = false; + let mut shadow_has_dsv = false; + + if is_real_list { + if let Some(dev) = device_of(this) { + let dev_key = dev.as_raw() as usize; + let slot = match prev_slot { + Some(existing) if existing.dev_key == dev_key => Some(existing), + _ => alloc_rt_shadow_slot(&dev), + }; + if let Some(slot) = slot { + if want_rtv { + if single != 0 { + dev.CopyDescriptorsSimple( + num_targets, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: slot.entry.rtv_base }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: handles[0] }, + D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + ); + } else { + for (i, &h) in handles.iter().enumerate() { + dev.CopyDescriptorsSimple( + 1, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: slot.entry.rtv_base + i * slot.entry.rtv_inc }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: h }, + D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + ); + } + } + shadow_has_rtvs = true; + } + if let Some(dh) = d.filter(|&dh| dh != 0) { + dev.CopyDescriptorsSimple( + 1, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: slot.entry.dsv_handle }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dh }, + D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + ); + shadow_has_dsv = true; + } + shadow = Some(slot); + } + } + } + + with_bindings(this, |b| { + b.render_targets = Some(RenderTargets { + num_targets, + handles, + single, + dsv: d, + shadow, + shadow_has_rtvs, + shadow_has_dsv, + desc_gen, + live_on_pc: true, + }); + }); } /// Set again what `b` holds (after KickoffX's Reset or a deferred mid-list split). @@ -595,14 +925,26 @@ unsafe fn restore_bindings(this: *mut c_void, b: &Bindings, ty: D3D12_COMMAND_LI pc::(this, PC_IA_SET_VERTEX_BUFFERS)(this, slot, 1, v); } if let Some(rt) = &b.render_targets { - let d = rt.dsv.unwrap_or(0); - let (n, rts_ptr) = if rt.handles.is_empty() { (0, std::ptr::null()) } else { (rt.num_targets, rt.handles.as_ptr()) }; + let rtv_shadow_base = rt.shadow.as_ref().map_or(0, |slot| slot.entry.rtv_base); + let (n, rts_ptr, single) = if rt.shadow.is_some() && rt.shadow_has_rtvs && rt.num_targets > 0 { + (rt.num_targets, &rtv_shadow_base as *const usize, 1) + } else if rt.handles.is_empty() { + (0, std::ptr::null(), rt.single) + } else { + (rt.num_targets, rt.handles.as_ptr(), rt.single) + }; + let dsv_opt = if let Some(slot) = rt.shadow.as_ref().filter(|_| rt.shadow_has_dsv) { + Some(slot.entry.dsv_handle) + } else { + rt.dsv + }; + let d = dsv_opt.unwrap_or(0); pc::(this, PC_OM_SET_RENDER_TARGETS)( this, n, rts_ptr, - rt.single, - if rt.dsv.is_some() { &d } else { std::ptr::null() }, + single, + if dsv_opt.is_some() { &d } else { std::ptr::null() }, ); } } @@ -614,6 +956,9 @@ struct ListState { last_queue: Option, /// Title's currently bound PSO (before dynamic depth-bias override) bound_pso: usize, + /// Last resolved PC PSO actually emitted via `SetPipelineState` on this PC list + /// (cleared on Reset / ClearState / KickoffX / split so bind dedup is always exact). + last_pc_pso: usize, /// Active `RSSetDepthBiasX` override (None = zero / disabled) depth_bias: Option, /// Last depth bias sent to `ID3D12GraphicsCommandList9::RSSetDepthBias` on this PC list @@ -630,6 +975,9 @@ struct ListState { occlusion: Occlusion, /// UMA address ranges written by this list since last Reset/KickoffX written_ranges: Vec<(u64, u64)>, + /// `(va, bytes, value)` of this list's last immediate write (`write`) to each address; a later + /// write over it of unknown value (fill, copy) removes it + written_values: Vec<(u64, u64, u64)>, /// Sparse-window `(va, bytes)` ranges written by memory ops (`Write32/64`, `Fill*`, /// `CopyMemoryToMemoryX`, timestamps) to copy back to the CPU view after execution. sparse_writes: Vec<(usize, usize)>, @@ -667,6 +1015,7 @@ impl ListState { return; } let end = va.saturating_add(size); + self.written_values.retain(|&(s, n, _)| !(va < s + n && s < end)); if self.written_ranges.len() < MAX_WRITTEN_RANGES { self.written_ranges.push((va, end)); } else if let Some(last) = self.written_ranges.last_mut() { @@ -803,12 +1152,23 @@ 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; } let key = list as usize; // (of a list that was here before and whose release was not seen: the GPU may still use it) release_copy_scratch(key); + real::dispatch_chain::list_reset(key); let old = { let mut g = LISTS.lock().unwrap(); let m = g.get_or_insert_with(HashMap::new); @@ -824,12 +1184,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 { @@ -847,7 +1208,9 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C pub(super) fn on_release(list: usize) { super::alloc_pool::forget_list(list); release_copy_scratch(list); + real::dispatch_chain::list_reset(list); super::title_textures::list_reset(list); + super::format_alias::list_reset(list); let old = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)); if let Some(old) = old { if !old.pending_waits.is_empty() { @@ -870,10 +1233,13 @@ pub(super) fn on_release(list: usize) { /// Clear per-recording sync/write tracking on a split segment moved into `title_list`'s spare pool. pub(super) fn clear_segment_state(list: usize) { + real::dispatch_chain::list_reset(list); super::title_textures::list_reset(list); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { + s.last_pc_pso = 0; s.occlusion = Occlusion::default(); s.written_ranges.clear(); + s.written_values.clear(); s.clear_sparse_writes(); s.clear_write64_signals(); s.clear_waits(); @@ -901,14 +1267,40 @@ pub(super) fn on_allocator_release(alloc: usize) { } } -/// Track `SetPipelineState` on a command list (for `RSSetDepthBiasX` and `KickoffX`), -/// syncing `ID3D12GraphicsCommandList9::RSSetDepthBias` when the bound PSO uses native dynamic -/// depth bias. +fn bind_cache_enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_BIND_CACHE").map_or(true, |v| v.trim() != "0")) +} + +/// Whether `SetPipelineState(pso)` resolved to `bound` is already active on `list` (same title +/// PSO or resolved PC PSO, with no pending/active depth-bias patch), allowing the redundant +/// D3D12 call and DRED marker to be skipped. +pub(super) fn skip_redundant_pso_bind(list: *mut c_void, pso: usize, bound: usize) -> bool { + if !bind_cache_enabled() || list.is_null() || pso == 0 || bound == 0 { + return false; + } + LISTS + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(list as usize))) + .is_some_and(|s| (s.bound_pso == pso || s.last_pc_pso == pso) && s.last_pc_pso == bound && !s.pso_dirty && !s.using_fallback_pso) +} + +/// Track `SetPipelineState` on a command list (for `RSSetDepthBiasX`, `KickoffX`, and redundant +/// bind dedup), syncing `ID3D12GraphicsCommandList9::RSSetDepthBias` when the bound PSO uses +/// native dynamic depth bias. +#[cfg(test)] pub(super) unsafe fn on_set_pipeline_state(list: *mut c_void, pso: usize) { + on_set_pipeline_state_bound(list, pso, pso); +} + +pub(super) unsafe fn on_set_pipeline_state_bound(list: *mut c_void, pso: usize, bound: usize) { let key = list as usize; let sync_target = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(key).or_default(); + s.last_pc_pso = bound; // Keep the title-visible base PSO key when `bind_abi` re-binds its resolved background PSO. if s.bound_pso == 0 || pso == s.bound_pso || super::pso_async::resolve(s.bound_pso) != pso { s.bound_pso = pso; @@ -962,6 +1354,7 @@ pub(super) unsafe fn on_clear_state(list: *mut c_void, pso: usize) { let mut g = LISTS.lock().unwrap(); if let Some(s) = g.get_or_insert_with(HashMap::new).get_mut(&key) { s.bound_pso = pso; + s.last_pc_pso = 0; s.depth_bias = None; s.native_bias = DepthBias::ZERO; s.pso_dirty = false; @@ -1033,6 +1426,16 @@ fn note_write(list: usize, va: u64, size: u64) { LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(va, size); } +/// `note_write` for an immediate write of `words`, keeping its value for `wait_memory`. +fn note_write_value(list: usize, va: u64, words: &[u32]) { + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(list).or_default(); + s.note_write(va, 4 * words.len() as u64); + if words.len() <= 2 && s.written_values.len() < MAX_WRITTEN_RANGES { + s.written_values.push((va, 4 * words.len() as u64, words.iter().rev().fold(0, |v, &w| v << 32 | w as u64))); + } +} + // --------------------------------------------------------------------------------------- // per-address GPU fence bridge for monotonic 64-bit Write64BitValue* -> Wait64BitValueX // --------------------------------------------------------------------------------------- @@ -1187,6 +1590,8 @@ pub(super) fn note_internal_wait(queue: usize, what: &'static str, fence: &ID3D1 let mut g = INTERNAL_WAITS.lock().unwrap(); let waits = g.get_or_insert_with(HashMap::new).entry(queue).or_default(); waits.retain(|w| unsafe { w.fence.GetCompletedValue() } < w.value); + // (flight: the queue, the value waited for and the fence's value now) + super::flight::event(what, queue as u64, value, unsafe { fence.GetCompletedValue() }); waits.push(InternalWait { what, fence: fence.clone(), value, at: Instant::now() }); } @@ -1209,6 +1614,61 @@ fn internal_waits_summary() -> String { unmet.into_iter().map(|(q, s)| format!("q{}: {s}", queue_id(q))).collect::>().join(", ") } +/// What the queues wait for on the GPU now – the title's `Wait*BitValueX` not met yet, its +/// fences, XCL's own queue waits – into the log when a queue stops (`flight`): the watchdog says +/// the same after 5 s, and a driver that gives up on the GPU after 2 s removes the device first. +/// At most 8 times, 3 s apart. +pub(super) fn log_pending_waits(why: &str) { + static LAST: Mutex> = Mutex::new(None); + static TIMES: AtomicU64 = AtomicU64::new(0); + { + let mut l = LAST.lock().unwrap(); + if l.is_some_and(|t| t.elapsed() < Duration::from_secs(3)) { + return; + } + *l = Some(Instant::now()); + } + if !once(&TIMES, 8) { + return; + } + let mut armed = Vec::new(); + if let Some(graph) = SYNC_GRAPH.lock().unwrap().as_mut() { + for (&va, cell) in graph.cells.iter_mut() { + if cell.armed_waits.is_empty() { + continue; + } + let completed = unsafe { prune_completed_waits(cell) }; + if completed == u64::MAX { + continue; + } + let producer = cell.submitted_queue.or(cell.recorded_last_queue); + // the signals submitted for the address and not done: value, queue, its place there + let signals: Vec = cell.submitted_signals.iter().map(|s| format!("{:#x} on {:#x} at #{}", s.val, s.queue, s.seq)).collect(); + for aw in &cell.armed_waits { + armed.push(format!( + "{va:#x} >= {:#x} for {} ms (waiter {:#x}/ty{} at #{}{}, producer {:x?}/ty{:?}, recorded {:#x}, submitted {:#x}, completed {completed:#x}, CPU-signalled {:#x}, signals [{}])", + aw.val, + aw.armed_at.elapsed().as_millis(), + aw.waiting_queue, + aw.waiting_queue_ty, + aw.wait_seq, + if aw.after_write64 { ", after a Write64 of its list" } else { "" }, + producer, + cell.recorded_list_type.map(|t| t.0), + cell.recorded_max, + cell.submitted_max, + cell.cpu_signaled_max, + signals.join(", ") + )); + } + } + } + let ids = QUEUE_IDS.lock().unwrap().iter().enumerate().map(|(i, q)| format!("q{i} {q:#x}")).collect::>().join(", "); + crate::xlog_warn!("D3D12.X: GPU waits as {why}: the title's value waits unmet: {}", if armed.is_empty() { "none".to_string() } else { armed.join("; ") }); + crate::xlog_warn!("D3D12.X: GPU waits as {why}: pending title ID3D12Fences: {}", super::fence_x::pending_summary()); + crate::xlog_warn!("D3D12.X: GPU waits as {why}: XCL's own queue waits unmet: {} (queues: {ids})", internal_waits_summary()); +} + fn queue_id(q: usize) -> usize { let mut g = QUEUE_IDS.lock().unwrap(); if let Some(pos) = g.iter().position(|&x| x == q) { @@ -1283,7 +1743,15 @@ unsafe fn would_signal_close_cycle(graph: &mut SyncGraph, sig_q: usize, target_v if completed == u64::MAX || target.armed_waits.is_empty() { return false; } - target.armed_waits.iter().filter(|aw| aw.val <= sig_val).map(|aw| (aw.waiting_queue, aw.wait_seq)).collect() + // A wait an earlier signal of this cell already satisfies (GPU or CPU) does not wait on + // this one: counting it made every pipelined frame (wait N armed, signal N+1 next) a cycle. + let covered = target.submitted_max.max(target.cpu_signaled_max); + target + .armed_waits + .iter() + .filter(|aw| aw.val <= sig_val && aw.val > covered) + .map(|aw| (aw.waiting_queue, aw.wait_seq)) + .collect() }; if target_waiters.is_empty() { return false; @@ -1422,7 +1890,10 @@ pub(super) unsafe fn break_cycles_before_title_signal(sig_q: usize, title_fence: let Some(graph) = g.as_mut() else { return }; let Some(tf) = graph.title_fences.get_mut(&title_fence) else { return }; prune_title_fence(title_fence, tf); - let target_waiters: Vec<(usize, u64)> = tf.waits.iter().filter(|&&(v, _, _)| v <= sig_val).map(|&(_, wq, wseq)| (wq, wseq)).collect(); + // (a wait an earlier signal of the fence satisfies does not wait on this one, as for the + // cells in `would_signal_close_cycle`) + let covered = tf.signals.iter().map(|s| s.val).max().unwrap_or(0); + let target_waiters: Vec<(usize, u64)> = tf.waits.iter().filter(|&&(v, _, _)| v <= sig_val && v > covered).map(|&(_, wq, wseq)| (wq, wseq)).collect(); if target_waiters.is_empty() { return; } @@ -1524,13 +1995,11 @@ fn wait_expired(aw: &mut ArmedGpuWait, held: bool) -> bool { fn wake_sync_watchdog() { let pair = sync_watchdog_pair(&SYNC_WATCHDOG_WAKE, || { let _ = std::thread::Builder::new().name("xcl-sync-watchdog".into()).spawn(|| loop { - let (lock, cv) = SYNC_WATCHDOG_WAKE.get().unwrap(); - let guard = lock.lock().unwrap(); - if ARMED_GPU_WAITS.load(Ordering::Acquire) == 0 { - let _g = cv.wait(guard).unwrap(); + let pair = SYNC_WATCHDOG_WAKE.get().unwrap(); + let Some(guard) = sync_watchdog_sleep_if_idle(pair, &ARMED_GPU_WAITS, || {}) else { continue; - } - let _ = cv.wait_timeout(guard, Duration::from_millis(50)).unwrap(); + }; + let _ = pair.1.wait_timeout(guard, Duration::from_millis(50)).unwrap(); let (expired, rewinds) = { let mut g = SYNC_GRAPH.lock().unwrap(); let mut out: Vec<(u64, u64, ID3D12Fence, usize, i32, Option, Option, u64, u64, u64)> = Vec::new(); @@ -1616,9 +2085,35 @@ fn wake_sync_watchdog() { if had_expired { crate::xlog_warn!("D3D12.X: pending title ID3D12Fences during GPU wait timeout: {}", super::fence_x::pending_summary()); crate::xlog_warn!("D3D12.X: XCL's own queue waits unmet during GPU wait timeout: {}", internal_waits_summary()); + super::culprit::on_watchdog_release(); } }); }); + notify_sync_watchdog(pair); +} + +/// The watchdog's check for armed waits: none (`armed` is 0) – it sleeps until a +/// `notify_sync_watchdog` and returns `None`; some – the pair's lock, still held. The lock is held +/// from the check until `cv.wait` releases it; `after_check` runs in between (a test's pause). +fn sync_watchdog_sleep_if_idle<'a>( + pair: &'a (Mutex<()>, Condvar), + armed: &AtomicUsize, + after_check: impl FnOnce(), +) -> Option> { + let guard = pair.0.lock().unwrap(); + if armed.load(Ordering::Acquire) != 0 { + return Some(guard); + } + after_check(); + let _g = pair.1.wait(guard).unwrap(); + None +} + +/// Wake the watchdog after a wait was armed. The notify takes the pair's lock: without it, it can +/// fall between the watchdog's check (still 0) and its `cv.wait`, and the watchdog sleeps with the +/// wait armed and never releases it (the lock is a leaf: the watchdog takes no other lock with it). +fn notify_sync_watchdog(pair: &(Mutex<()>, Condvar)) { + let _g = pair.0.lock().unwrap(); pair.1.notify_one(); } @@ -1759,6 +2254,8 @@ unsafe fn signal_write64_pairs(queue: *mut c_void, pairs: &[(u64, u64)]) { .is_some_and(|c| c.non_monotonic || c.submitted_max >= val) }; if skip { + // (flight: the value was submitted before, or the address is not monotonic) + super::flight::event("w64 signal not sent", sig_q as u64, val, va); continue; } let Some(fence) = ensure_cell_fence(va, &dev, dev_raw) else { continue }; @@ -1820,6 +2317,17 @@ unsafe fn signal_write64_pairs(queue: *mut c_void, pairs: &[(u64, u64)]) { } } }; + // (flight: the queue, the value and the address, in the order the queue gets them) + super::flight::event( + match action { + SignalAction::Skip => "w64 signal left out", + SignalAction::GpuSignal => "w64 signal", + SignalAction::CpuCycleBreak(_) => "w64 signal on the CPU (cycle)", + }, + sig_q as u64, + val, + va, + ); match action { SignalAction::Skip => {} SignalAction::GpuSignal => { @@ -1979,6 +2487,8 @@ unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait, list_writes: &[(u64, (pre_ok.0, pre_ok.1, pre_ok.2, wait_seq) }; + // (flight: the waiting queue, the value and the address the title waits on) + super::flight::event("title value wait", q_raw as u64, w.value, w.va); if let Err(e) = q.Wait(&fence, w.value) { let mut g = SYNC_GRAPH.lock().unwrap(); if let Some(cell) = g.as_mut().and_then(|gr| gr.cells.get_mut(&w.va)) { @@ -2188,12 +2698,17 @@ const MAX_COPY_SCRATCH: u64 = 64 << 20; struct CopyScratch { buffer: ID3D12Resource, bytes: u64, + extra: Vec<(ID3D12Resource, u64)>, recorded: bool, untracked_submission: bool, marks: HashMap, } impl CopyScratch { + fn total_bytes(&self) -> u64 { + self.bytes + self.extra.iter().map(|(_, b)| *b).sum::() + } + fn idle(&mut self) -> bool { self.marks.retain(|_, (fence, value)| unsafe { fence.GetCompletedValue() < *value }); !self.untracked_submission && self.marks.is_empty() @@ -2215,7 +2730,7 @@ impl CopyScratchCache { if !scratch.idle() { return true; } - self.bytes -= scratch.bytes; + self.bytes -= scratch.total_bytes(); false }); } @@ -2235,12 +2750,12 @@ impl CopyScratchCache { if !scratch.recorded && !scratch.idle() { return None; } - if scratch.recorded || scratch.bytes >= bytes || bytes > MAX_COPY_SCRATCH - self.bytes + scratch.bytes { + if scratch.recorded || scratch.bytes >= bytes || bytes > MAX_COPY_SCRATCH - self.bytes + scratch.total_bytes() { 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; + self.bytes -= self.active.remove(&key).unwrap().total_bytes(); } if bytes > MAX_COPY_SCRATCH - self.bytes { return None; @@ -2248,11 +2763,33 @@ impl CopyScratchCache { let buffer = make_copy_scratch(list, bytes)?; let raw = buffer.as_raw() as usize; self.active.insert(key, CopyScratch { - buffer, bytes, recorded: true, untracked_submission: false, marks: HashMap::new(), + buffer, bytes, extra: Vec::new(), recorded: true, untracked_submission: false, marks: HashMap::new(), }); self.bytes += bytes; Some((raw, bytes)) } + + /// Acquire a scratch buffer on `list` guaranteed to hold at least `bytes` bytes (allocating + /// an extra GPU-fenced buffer on `list` if an earlier smaller scratch was already recorded). + unsafe fn acquire_exact(&mut self, list: *mut c_void, bytes: u64) -> Option { + let (raw, cap) = self.acquire(list, bytes)?; + if cap >= bytes { + return Some(raw); + } + let key = list as usize; + let scratch = self.active.get_mut(&key)?; + if let Some((buf, _)) = scratch.extra.iter().find(|(_, b)| *b >= bytes) { + return Some(buf.as_raw() as usize); + } + if bytes > MAX_COPY_SCRATCH.saturating_sub(self.bytes) { + return None; + } + let buffer = make_copy_scratch(list, bytes)?; + let raw = buffer.as_raw() as usize; + scratch.extra.push((buffer, bytes)); + self.bytes += bytes; + Some(raw) + } } static COPY_SCRATCH: LazyLock> = LazyLock::new(|| Mutex::new(CopyScratchCache::default())); @@ -2286,6 +2823,18 @@ unsafe fn copy_scratch(list: *mut c_void, n: u64) -> Option<(usize, u64)> { COPY_SCRATCH.lock().unwrap().acquire(list, bytes) } +/// Acquire a per-list DEFAULT-heap scratch buffer in `COMMON` state large enough to hold `n` bytes. +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); + if bytes > MAX_COPY_SCRATCH { + return COPY_SCRATCH.lock().unwrap().acquire_exact(list, n.next_multiple_of(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64)); + } + COPY_SCRATCH.lock().unwrap().acquire_exact(list, bytes) +} + fn reset_copy_scratch(list: *mut c_void) { real::dispatch_chain::list_reset(list as usize); if let Some(scratch) = COPY_SCRATCH.lock().unwrap().active.get_mut(&(list as usize)) { @@ -2455,7 +3004,7 @@ unsafe fn write(list: *mut c_void, va: u64, words: &[u32], mode: D3D12_WRITEBUFF } return warn(&N, what, format_args!("{va:#x} is not in unified memory")); }; - note_write(list as usize, va, n); + note_write_value(list as usize, va, words); let params: Vec = words.iter().enumerate().map(|(i, &w)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: at + 4 * i as u64, Value: w }).collect(); let modes = vec![mode; words.len()]; type F = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, *const D3D12_WRITEBUFFERIMMEDIATE_MODE); @@ -2648,9 +3197,57 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { Some(next_pc) } +/// Cap on deferred compute segments per frame so a cold burst of unbuilt dispatches never +/// exhausts command-list memory (`#2581`). Once reached, subsequent `!spared` producer dispatches +/// fall through to `pso_async::resolve_wait` and wait inline instead of being dropped. +const MAX_DEFERRED_PER_FRAME: u32 = 16; + +struct FrameDeferCap { + frame: u64, + count: u32, +} + +impl FrameDeferCap { + const fn new() -> Self { + Self { frame: 0, count: 0 } + } + + fn try_reserve(&mut self, frame: u64, limit: u32) -> bool { + if frame > self.frame { + self.frame = frame; + self.count = 0; + } + if frame == self.frame && self.count >= limit { + return false; + } + if frame == self.frame { + self.count = self.count.saturating_add(1); + } + true + } + + fn release(&mut self, frame: u64) { + if frame == self.frame { + self.count = self.count.saturating_sub(1); + } + } +} + +static FRAME_DEFER_CAP: Mutex = Mutex::new(FrameDeferCap::new()); + /// Gives a dispatch whose pipeline is still being built a segment of its own, recorded at the submit. pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { + // With bounded per-PSO waits (`XCL_PSO_WAIT_MS`, #2581), record at once instead of allocating + // a segment per unbuilt dispatch. + if super::pso_async::waits_bounded() { + return false; + } + let frame = super::present::presents(); + if !FRAME_DEFER_CAP.lock().unwrap().try_reserve(frame, MAX_DEFERRED_PER_FRAME) { + return false; + } if split(list, Some(what)).is_none() { + FRAME_DEFER_CAP.lock().unwrap().release(frame); return false; } static N: AtomicU64 = AtomicU64::new(0); @@ -2661,13 +3258,39 @@ pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { true } +#[cfg(test)] +mod defer_cap_tests { + use super::FrameDeferCap; + + #[test] + fn frame_defer_cap_bounds_segments_per_frame_and_resets_on_new_frame() { + let mut cap = FrameDeferCap::new(); + for _ in 0..3 { + assert!(cap.try_reserve(1, 3)); + } + assert!(!cap.try_reserve(1, 3), "must stop deferring once per-frame segment cap is reached"); + // Releasing a failed split frees the slot atomically on the same frame. + cap.release(1); + assert!(cap.try_reserve(1, 3)); + assert!(!cap.try_reserve(1, 3)); + // Advancing frame resets the per-frame defer cap. + assert!(cap.try_reserve(2, 3), "advancing frame must reset the per-frame defer cap"); + // Stale lower frame must not disturb frame 2's count. + cap.release(1); + assert!(cap.try_reserve(2, 3)); + assert!(cap.try_reserve(2, 3)); + assert!(!cap.try_reserve(2, 3)); + } +} + /// Builds of a submit's put-off calls that go on without the commit headroom, as a title thread's own do: about what the title's threads had in the driver at once before. const WANTED_AT_ONCE: usize = 4; -/// Records the deferred dispatches of `wrapper`'s recording, waiting for their pipelines as a bind did. +/// Records the deferred dispatches of `wrapper`'s recording, each once its pipeline is built +/// (`pso_async::wait_for_submit`: not bounded by `XCL_PSO_WAIT_MS`). pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { let mut segs = Vec::new(); - super::title_list::push_segments(wrapper, &mut segs); + super::title_list::raw_segments(wrapper, &mut segs); let Some(&first) = segs.first() else { return }; segs.retain(|&seg| seg == first || LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(seg as usize))).is_some_and(|s| s.deferred.is_some())); let mut last: Option<*mut c_void> = None; @@ -2698,7 +3321,9 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { super::bind::dispatch_dropped(); continue; } + super::bind::rebind_allocator(seg, own as usize); reset_copy_scratch(seg); + super::dred::reset(seg); if !heaps.is_empty() { pc::(seg, 28)(seg, heaps.len() as u32, heaps.as_ptr()); } @@ -2706,6 +3331,7 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { super::bind::pass_arena(last, seg); real::dispatch_chain::list_follows(last as usize, seg as usize); } + super::bind::wait_for_bound(seg); match what { Deferred::Dispatch(x, y, z) => super::bind::dispatch(seg, x, y, z), Deferred::Indirect(sig, max, args, args_off, count_buf, count_off) => super::bind::execute_indirect(seg, sig, max, args, args_off, count_buf, count_off), @@ -2816,17 +3442,24 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } let next_pc = match next_pc { Some(p) => p, - None => match real::create_raw_pc_command_list(dev.as_raw(), ty, super::alloc_pool::current(alloc), init_pso) { - Some(p) => p, - None => { - static CREATE_ERR: AtomicU64 = AtomicU64::new(0); - warn(&CREATE_ERR, "mid-list split", format_args!("CreateCommandList failed")); - return None; + None => { + let pc_alloc = super::alloc_pool::current(alloc); + match real::create_raw_pc_command_list(dev.as_raw(), ty, pc_alloc, init_pso) { + Some(p) => { + super::alloc_pool::created_on(p as usize, pc_alloc, ty.0); + p + } + None => { + static CREATE_ERR: AtomicU64 = AtomicU64::new(0); + warn(&CREATE_ERR, "mid-list split", format_args!("CreateCommandList failed")); + return None; + } } - }, + } }; // the next segment is a recording of its own (reset or made here, not through `cl_reset`) + real::dispatch_chain::list_reset(next_pc as usize); super::dred::reset(next_pc); if init_pso != 0 { super::dred::mark_pipeline(next_pc, bound_pso, init_pso); @@ -2835,7 +3468,10 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ let old_next = { let mut g = LISTS.lock().unwrap(); let m = g.get_or_insert_with(HashMap::new); - let old = m.remove(&(next_pc as usize)); + let mut old = m.remove(&(next_pc as usize)); + // A spare that was previously a first segment holds the allocator its deferred segments + // recorded on: keep it alive while those dispatches may still execute on the GPU (#2549). + let own_alloc = old.as_mut().and_then(|o| o.own_alloc.take()); if let Some(ref o) = old { if !o.pending_waits.is_empty() { PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); @@ -2866,6 +3502,7 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ pred_in_state: false, predication, bindings: bindings.clone(), + own_alloc, ..Default::default() }, ); @@ -2933,16 +3570,38 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } super::bind::inherit_for_split(list, seg, alloc); super::bind::pass_arena(list, next_pc); + // A deferred-dispatch split has no head fence wait on `next_pc` (`seg` executes on the + // same queue before `next_pc`'s prelude), so `next_pc` may hoist indirect clamps again. + super::bind::unblock_prelude(next_pc); } super::title_list::activate_segment(wrapper, list, next_pc); Some(next_pc) } +/// Split `list` into a fresh continuation segment with an unblocked indirect-argument prelude +/// (used right before a two-pass `ExecuteIndirect(DispatchMesh)` burst after earlier compute +/// dispatches blocked hoisting on the current segment). Skips when predication or an occlusion +/// query is active so D3D12 command-list invariants stay intact. +pub(super) unsafe fn split_for_prelude(list: *mut c_void) -> Option<*mut c_void> { + let ok = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).is_some_and(|s| { + s.allocator != 0 + && s.predication.is_none() + && s.occlusion.active.is_none() + && matches!(s.list_type, Some(D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE)) + }); + if !ok { + return None; + } + let next = split(list, None)?; + super::bind::unblock_prelude(next); + Some(next) +} + /// A closed, empty segment of `wrapper`'s recording for a dispatch recorded at the submit, on the wrapper's own allocator. unsafe fn deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_COMMAND_LIST_TYPE) -> Option<*mut c_void> { let dev = device_of(list)?; let mut segs = Vec::new(); - super::title_list::push_segments(wrapper, &mut segs); + super::title_list::raw_segments(wrapper, &mut segs); let first = *segs.first()? as usize; let own = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&first)?.own_alloc.clone()); let own = match own { @@ -2966,7 +3625,12 @@ unsafe fn deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_CO }; let p = match super::title_list::pop_spare(wrapper).filter(emptied) { Some(p) => p, - None => real::create_raw_pc_command_list(dev.as_raw(), ty, super::alloc_pool::current(own), 0)?, + None => { + let pc_alloc = super::alloc_pool::current(own); + let made = real::create_raw_pc_command_list(dev.as_raw(), ty, pc_alloc, 0)?; + super::alloc_pool::created_on(made as usize, pc_alloc, ty.0); + made + } }; let ext = *(p as *const usize); pc:: i32>(p, PC_CLOSE)(p); @@ -3004,7 +3668,9 @@ unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, va let need_split = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); - if s.has_prior_write(va, n) { + // (only when the value it wrote meets the wait: else another queue is to produce it) + let own = s.written_values.iter().find(|&&(w, len, _)| w == va && len == n); + if s.has_prior_write(va, n) && own.is_none_or(|&(_, _, v)| compare_u64(comparison, v & mask, value) == Some(true)) { return; } if s.write64_signals.is_empty() { @@ -3063,14 +3729,89 @@ pub(super) unsafe extern "system" fn set_depth_bounds_x(this: *mut c_void, min: pc::(this, PC_OM_SET_DEPTH_BOUNDS)(this, min, max); } +/// `D3D12XBOX_DISPATCH_FLAG_USE_THREAD_DIMENSIONS`: `(x, y, z)` are total thread counts rather +/// than workgroup counts (used by `XboxBvhBuilder.dll` BVH build passes). +const DISPATCH_FLAG_USE_THREAD_DIMENSIONS: u32 = 0x20; + +/// Convert `(x, y, z)` thread dimensions into workgroup counts for a compute shader with +/// `[numthreads(tx, ty, tz)]`. Returns `None` if any thread count is 0. +pub(crate) fn thread_dims_to_groups(threads: [u32; 3], group_size: [u32; 3]) -> Option<[u32; 3]> { + if threads[0] == 0 || threads[1] == 0 || threads[2] == 0 { + return None; + } + Some([ + threads[0].div_ceil(group_size[0].max(1)), + threads[1].div_ceil(group_size[1].max(1)), + threads[2].div_ceil(group_size[2].max(1)), + ]) +} + +/// Whether the BVH builder's passes (`DispatchX` with `USE_THREAD_DIMENSIONS`, the title's +/// `XboxBvhBuilder.dll`) run: off unless `XCL_BVH_BUILDER=1`. Its 52 programs build and refit the +/// ray-tracing structures in the title's memory by raw address; while their pipelines are built +/// one by one some passes run and others do not, and a partly run builder writes garbage bounds +/// and sizes there. A retail title's world loading crashed (title code reading corrupted +/// pointers) or hung the device 2 to 100 s after its first builder pass, in every run of nine. +/// Without the builder the structures stay unbuilt and every ray misses; the project the +/// maintainer calls `nnnee`, playable with that title, keeps its builder off by default for the +/// same finding. +fn bvh_builder_runs(flags: u32, enabled: bool) -> bool { + flags & DISPATCH_FLAG_USE_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")) +} + /// command list #78 DispatchX(x, y, z, flags) -pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, _flags: u32) { +pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { + if !bvh_builder_runs(flags, bvh_builder_enabled()) { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, 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; + } + if flags & DISPATCH_FLAG_USE_THREAD_DIMENSIONS != 0 { + if super::real::bvh_builder_failed() { + return; + } + let raw_pso = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).map_or(0, |s| s.bound_pso); + let resolved = super::pso_async::resolve_wait(raw_pso); + if !super::real::is_translated_compute_raw(resolved) || super::pso_async::is_pending(raw_pso) { + super::real::note_bvh_builder_failed(raw_pso); + return; + } + let group_size = super::real::pso_compute_threads(raw_pso) + .or_else(|| super::real::pso_compute_threads(resolved)) + .unwrap_or([64, 1, 1]); + let Some([gx, gy, gz]) = thread_dims_to_groups([x, y, z], group_size) else { + return; + }; + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: DispatchX USE_THREAD_DIMENSIONS ({x}, {y}, {z}) / {:?} -> groups ({gx}, {gy}, {gz}) ({} dispatches)", + group_size, + n + 1 + ); + } + super::real::note_bvh_builder_dispatched(); + super::bind::dispatch(this, gx, gy, gz); + return; + } super::bind::dispatch(this, x, y, z); } -/// 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) { +/// command list #146 console enhanced/UAV barrier (`ID3D12GraphicsCommandList7::Barrier`, also +/// used by `XboxBvhBuilder.dll` between BVH build passes): emits a global PC UAV barrier so UMA +/// writes become visible, parses any readable `D3D12_BARRIER_GROUP` texture barriers targeting +/// tracked depth+UAV resources, and notifies `depth_uav` / `format_alias` of global UAV barriers. +pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, n: u32, barriers: *const c_void) { + super::bind::note_gpu_write(this); let b = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, @@ -3079,6 +3820,23 @@ pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, _n: u32, _ }, }; pc::(this, PC_RESOURCE_BARRIER)(this, 1, &b); + if super::depth_uav::any() { + let is_direct = list_type(this) == D3D12_COMMAND_LIST_TYPE_DIRECT; + let mut depth_syncs = Vec::new(); + let had_global_uav = super::depth_uav::filter_enhanced_barriers(n, barriers, is_direct, &mut depth_syncs); + if !depth_syncs.is_empty() { + super::depth_uav::execute_syncs(this, &depth_syncs); + } + if had_global_uav { + super::depth_uav::on_global_uav_barrier(); + } + } + let mut alias_writers = 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); } /// command list #84 CopyResourceX(destination, source, flags); in place (the console's @@ -3135,7 +3893,11 @@ 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) { - if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { + if list.is_null() { + return; + } + super::format_alias::before_close(list); + if !PREDICATION_USED.load(Ordering::Acquire) { return; } let pb = { @@ -3155,18 +3917,29 @@ pub(super) unsafe fn before_close(list: *mut c_void) { } } -/// Clear active predication state when `ID3D12GraphicsCommandList::Reset` resets a recording. +/// Clear active predication and snapshotted render-target state when +/// `ID3D12GraphicsCommandList::Reset` resets a recording. pub(super) fn on_pc_reset(list: *mut c_void) { reset_copy_scratch(list); - if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { + super::format_alias::list_reset(list as usize); + if list.is_null() { return; } if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { - s.predication = None; - s.pred_in_state = false; + s.bindings.render_targets = None; + s.last_pc_pso = 0; + if PREDICATION_USED.load(Ordering::Acquire) { + s.predication = None; + s.pred_in_state = false; + } } } +/// Whether the title's predication is set on `list` (XCL cannot set its own there) +pub(super) fn predication_active(list: *mut c_void) -> bool { + LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).is_some_and(|s| s.predication.is_some()) +} + /// Copy 8 predicate bytes from `(uma_buf, off)` into `pb` with exact barrier transitions and /// bind `SetPredication(pb, 0, op)` on `this`. unsafe fn apply_predication_copy(this: *mut c_void, uma_buf: usize, off: u64, pb: usize, op: D3D12_PREDICATION_OP) { @@ -3293,6 +4066,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let sparse_writes = s.clear_sparse_writes(); let write64_signals = s.clear_write64_signals(); s.written_ranges.clear(); + s.written_values.clear(); let cpu_writes = std::mem::take(&mut s.cpu_writes); let pred_in_state = std::mem::replace(&mut s.pred_in_state, false); let pred_buf = s.pred_buf.as_ref().map(|r| r.as_raw() as usize); @@ -3321,6 +4095,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } let q_raw = queue as *mut c_void; + // (a submit as `ExecuteCommandLists` is, for `prof`: the refresh, the waits and the driver) + let _prof = super::prof::span(super::prof::Kind::Submit); super::title_textures::refresh(q_raw); type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = transmute_copy(&real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); @@ -3389,6 +4165,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { s.pred_in_state = false; s.occlusion = Occlusion { active: None, ended_early }; s.written_ranges.clear(); + s.written_values.clear(); s.clear_sparse_writes(); s.clear_write64_signals(); s.clear_waits(); @@ -3401,7 +4178,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { }; let ext_closed = *(target as *const usize); - let init_pso = super::pso_async::resolve_for_bind(bound_pso); + let init_pso = super::pso_async::resolve(bound_pso); let reset_hr = super::alloc_pool::reset_list(target as usize, alloc, list_type(target).0, |pc_alloc| { pc:: i32>(target, PC_RESET)(target, pc_alloc, init_pso) }); @@ -3409,7 +4186,16 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if reset_hr < 0 { return warn(&ERR, "KickoffX", format_args!("Reset after kickoff failed ({reset_hr:#x})")); } + // `alloc_pool::reset_list` can rotate `target` onto a fresh PC backing allocator because + // the pre-kickoff submit is now in flight; sync `bind`'s allocator so subsequent VRAM `io` + // slabs and prelude lists stay pinned to the new backing allocator rather than the old one. + super::bind::rebind_allocator(target, alloc); reset_copy_scratch(target); + // `KickoffX` calls PC `Reset` directly (bypassing `real::cl_reset`), so rotate DRED markers here. + super::dred::reset(target); + if bound_pso != 0 { + super::dred::mark_pipeline(target, bound_pso, init_pso); + } let bindings = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(target as usize))).map(|s| s.bindings.clone()); if let Some(b) = bindings { restore_bindings(target, &b, ty); @@ -3417,6 +4203,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { // Reset() cleared the PC list's native RSSetDepthBias state to (0, 0, 0) and bound init_pso. if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(target as usize))) { + s.last_pc_pso = init_pso; s.native_bias = DepthBias::ZERO; s.using_fallback_pso = false; s.pso_dirty = false; @@ -3514,6 +4301,9 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b if let Some(base) = need_restore_base { let resolved = super::pso_async::resolve_for_bind(base); pc::(this, PC_SET_PIPELINE_STATE)(this, resolved); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&key)) { + s.last_pc_pso = resolved; + } } if !need_native_call { return; @@ -3558,6 +4348,9 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b if let Some(base) = restore { let resolved = super::pso_async::resolve_for_bind(base); pc::(this, PC_SET_PIPELINE_STATE)(this, resolved); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&key)) { + s.last_pc_pso = resolved; + } } } @@ -3599,6 +4392,7 @@ pub(super) unsafe fn prepare_draw(list: *mut c_void) { let resolved = super::pso_async::resolve_for_bind(target); pc::(list, PC_SET_PIPELINE_STATE)(list, resolved); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.last_pc_pso = resolved; s.using_fallback_pso = is_fallback; } } @@ -3629,6 +4423,26 @@ fn pc_va(va: u64) -> u64 { /// it reads there first (`sync_title_buffers`), as the title wrote it by then. (A copy of the /// whole buffer at every bind filled unified memory within two minutes of a retail title's /// menus, and missed what the title wrote after the bind.) +/// A vertex buffer view at address 0 is a null view whatever its size: the console reads zeros +/// from it, and the PC's input assembler would fetch from GPU address 0 (a page fault there is +/// what a removed device reports, `0x887a0006` with "GPU VA 0x0"). +fn null_if_at_zero(mut v: D3D12_VERTEX_BUFFER_VIEW) -> D3D12_VERTEX_BUFFER_VIEW { + if v.BufferLocation == 0 && v.SizeInBytes != 0 { + note_null_buffer("vertex buffer"); + v.SizeInBytes = 0; + } + v +} + +/// A view at address 0 with a size was bound (`null_if_at_zero`). +fn note_null_buffer(what: &str) { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: a {what} at address 0 with a size is bound: a null view ({n} so far)"); + } +} + unsafe fn gpu_va(list: *mut c_void, va: u64, bytes: usize, what: &str, mirror: bool) -> u64 { let t = pc_va(va); if t != va || va == 0 || bytes == 0 { @@ -3672,13 +4486,188 @@ unsafe fn gpu_va(list: *mut c_void, va: u64, bytes: usize, what: &str, mirror: b /// title binds one buffer at many offsets (a ring it fills through the frame: a retail title's /// views all end at the buffer's end), so a mirror covers a 64 KiB-aligned range and a view /// inside a mirrored range uses that mirror at its offset. -static MIRRORS: Mutex> = Mutex::new(Vec::new()); +static MIRRORS: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); /// bytes of mirrors made (never freed) static MIRROR_BYTES: AtomicU64 = AtomicU64::new(0); /// 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) + MIRRORS.read().unwrap().iter().find(|&&(s, l, _)| va >= s && va + bytes as u64 <= s + l as u64).map(|&(s, _, m)| m + (va - s) as usize) +} + +/// Per mirror (start, bytes, a bit per 4 KiB page from `start & !0xfff`): pages of its source +/// the title wrote that a look took off the write-watch (`mirror_pages_written`) and no draw has +/// copied since. A draw copies these and the pages still on the write-watch (`written_pages`). +static MIRROR_STALE: Mutex)>> = Mutex::new(Vec::new()); +/// odd while a look takes pages off the write-watch and has not handed them on yet: a draw +/// then (or across one) copies its whole range +static MIRROR_LOOK_SEQ: AtomicU64 = AtomicU64::new(0); +// the write-watch's answer and reusable dirty-page bitset for a draw's range (one per thread) +thread_local! { + static WRITTEN_BUF: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + static WRITTEN_BITS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// The title's ranges with a mirror (start, end), which `title_textures`' look watches. +pub(super) fn mirror_sources() -> Vec<(usize, usize)> { + MIRRORS.read().unwrap().iter().map(|&(s, l, _)| (s as usize, s as usize + l)).collect() +} + +/// Changes when a mirror is made (`mirror_sources` then has a new range). +pub(super) fn mirror_sources_gen() -> u64 { + MIRROR_BYTES.load(Ordering::Relaxed) +} + +/// A look is about to take written pages off the write-watch. +pub(super) fn mirror_look_begin() { + MIRROR_LOOK_SEQ.fetch_add(1, Ordering::SeqCst); +} + +/// The look took `dirty` (4 KiB pages, sorted) off the write-watch: those in a mirror's +/// source are copied at the mirror's next draw. +pub(super) fn mirror_pages_written(dirty: &[usize]) { + { + let mut g = MIRROR_STALE.lock().unwrap(); + for (s, l, bits) in g.iter_mut() { + let (s, e) = (*s as usize, *s as usize + *l); + let first = dirty.partition_point(|&p| p + 0x1000 <= s); + for &p in dirty[first..].iter().take_while(|&&p| p < e) { + let k = (p - (s & !0xfff)) >> 12; + bits[k / 64] |= 1 << (k % 64); + } + } + } + MIRROR_LOOK_SEQ.fetch_add(1, Ordering::SeqCst); +} + +/// Call `on_run(first, end)` for every maximal contiguous run of set bits in `bits[..]` below `n`. +fn for_each_bitset_run(bits: &[u64], n: usize, mut on_run: impl FnMut(usize, usize)) { + let words = n.div_ceil(64).min(bits.len()); + let mut run_start: Option = None; + for (wi, &raw) in bits[..words].iter().enumerate() { + let valid_bits = (n - wi * 64).min(64); + let mask = if valid_bits == 64 { u64::MAX } else { (1u64 << valid_bits) - 1 }; + let mut w = raw & mask; + if w == 0 { + if let Some(s) = run_start.take() { + on_run(s, wi * 64); + } + continue; + } + if w == u64::MAX && valid_bits == 64 { + if run_start.is_none() { + run_start = Some(wi * 64); + } + continue; + } + let mut bit = 0usize; + while bit < valid_bits { + if run_start.is_some() { + let ones = (w >> bit).trailing_ones() as usize; + let take = ones.min(valid_bits - bit); + bit += take; + if bit < valid_bits { + let s = run_start.take().unwrap(); + on_run(s, wi * 64 + bit); + } + } else { + let zeros = (w >> bit).trailing_zeros() as usize; + bit += zeros; + if bit < valid_bits { + run_start = Some(wi * 64 + bit); + } + } + } + let _ = &mut w; + } + if let Some(s) = run_start { + on_run(s, n); + } +} + +/// Walk the dirty 4 KiB page runs of `[a, end)` (from `a & !0xfff`, in the mirror of the buffer at +/// `va`) using a reusable thread-local bitset: pages on the write-watch plus those a look took off +/// it since the last copy (whose bits are cleared). Returns `false` when not write-watched. +unsafe fn for_each_written_page_run(va: u64, a: usize, end: usize, mut on_run: impl FnMut(usize, usize)) -> bool { + use windows_sys::Win32::System::Memory::GetWriteWatch; + let base = a & !0xfff; + let n = (end - base + 0xfff) >> 12; + let words = n.div_ceil(64); + WRITTEN_BITS.with(|bits_cell| { + let mut bits = bits_cell.borrow_mut(); + if bits.len() < words { + bits.resize(words, 0); + } + bits[..words].fill(0); + let ok = WRITTEN_BUF.with(|c| { + let mut buf = c.borrow_mut(); + if buf.len() < n { + buf.resize(n, std::ptr::null_mut()); + } + let (mut count, mut granularity) = (n, 0u32); + // (no reset: the look's to do, which hands the pages on) + if GetWriteWatch(0, base as *const c_void, n << 12, buf.as_mut_ptr(), &mut count, &mut granularity) != 0 || granularity != 0x1000 { + return false; + } + for &p in &buf[..count] { + let k = (p as usize - base) >> 12; + bits[k >> 6] |= 1u64 << (k & 63); + } + true + }); + if !ok { + return false; + } + { + let mut g = MIRROR_STALE.lock().unwrap(); + if let Some((s, _, stale)) = g.iter_mut().find(|(s, l, _)| va >= *s && end as u64 <= *s + *l as u64) { + let first = (base - (*s as usize & !0xfff)) >> 12; + for k in 0..n { + let j = first + k; + let sw = stale[j >> 6]; + let sm = 1u64 << (j & 63); + if sw & sm != 0 { + bits[k >> 6] |= 1u64 << (k & 63); + stale[j >> 6] = sw & !sm; + } + } + } + } + for_each_bitset_run(&bits[..words], n, |first, last| { + on_run(base + (first << 12), base + (last << 12)); + }); + true + }) +} + +/// `[from, from + len)` of the title's buffer at `va` (`bytes` long) into its mirror at +/// `mirror`: only the pages the title wrote since they were last copied (#2393), all of it when +/// the source is not write-watched or a look ran meanwhile. +/// +/// (No `readable` first – for a range not resident or over 16 pages it walks the region with +/// `VirtualQuery`, a 1–9 ms stall of the render thread (#2392): the copy cannot fault, and a +/// page the title freed or protected since keeps what the mirror had.) +unsafe fn copy_written(va: u64, mirror: usize, bytes: u32, from: u64, len: u64) { + let from = from.min(bytes as u64); + let len = len.min(bytes as u64 - from) as usize; + if len == 0 { + return; + } + let (a, end) = ((va + from) as usize, (va + from) as usize + len); + let copy = |lo: usize, hi: usize| { + let (lo, hi) = (lo.max(a), hi.min(end)); + if lo < hi { + super::title_textures::copy_committed_region(lo, (mirror + (lo - va as usize)) as *mut u8, hi - lo); + } + }; + let seq = MIRROR_LOOK_SEQ.load(Ordering::SeqCst); + if seq % 2 != 0 || !for_each_written_page_run(va, a, end, copy) { + return copy(a, end); + } + // a look took pages off the write-watch meanwhile, which may not have been handed on yet + if MIRROR_LOOK_SEQ.load(Ordering::SeqCst) != seq { + copy(a, end); + } } /// The mirror address of the title's buffer at `va`; its range's mirror is made (and filled @@ -3687,7 +4676,7 @@ unsafe fn mirror_of(va: u64, bytes: usize, what: &str) -> Option { if let Some(p) = mirrored(va, bytes) { return Some(p); } - let mut g = MIRRORS.lock().unwrap(); + let mut g = MIRRORS.write().unwrap(); // again under the lock: two lists binding one new range at once must share a mirror (a // second one would never be synced – every later lookup finds the first) if let Some(&(s, _, m)) = g.iter().find(|&&(s, l, _)| va >= s && va + bytes as u64 <= s + l as u64) { @@ -3710,6 +4699,8 @@ 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); + let pages = (((start as usize + len + 0xfff) & !0xfff) - (start as usize & !0xfff)) >> 12; + MIRROR_STALE.lock().unwrap().push((start, len, vec![0; pages.div_ceil(64)])); 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() { @@ -3737,26 +4728,26 @@ pub(super) unsafe fn sync_title_buffers(list: *mut c_void, indexed: Option<(u32, } v }; - let copy = |va: u64, mirror: usize, bytes: u32, from: u64, len: u64| { - let from = from.min(bytes as u64); - let len = len.min(bytes as u64 - from) as usize; - if len > 0 && crate::gpu::shader::readable(va as usize + from as usize, len) { - std::ptr::copy_nonoverlapping((va + from) as *const u8, (mirror + from as usize) as *mut u8, len); - } - }; + let copy = |va: u64, mirror: usize, bytes: u32, from: u64, len: u64| copy_written(va, mirror, bytes, from, len); // the vertices read: [lo, hi) let (lo, hi) = match (indexed, ib) { (Some((first, count, base)), Some((va, bytes, format))) => { let size: u64 = if format == DXGI_FORMAT_R32_UINT.0 { 4 } else { 2 }; let (from, len) = (first as u64 * size, count as u64 * size); - if let Some(m) = mirrors[vbs.len()] { - copy(va, m, bytes, from, len); - } let n = (len.min((bytes as u64).saturating_sub(from)) / size) as usize; - if n == 0 || !crate::gpu::shader::readable((va + from) as usize, n * size as usize) { + // the indices are read from the mirror once copied there, which is readable whatever + // the title did to its memory; an index buffer without a mirror is checked + let at = match mirrors[vbs.len()] { + Some(m) => { + copy(va, m, bytes, from, len); + Some(m + from as usize) + } + None => (n > 0 && crate::gpu::shader::readable((va + from) as usize, n * size as usize)).then_some((va + from) as usize), + }; + if n == 0 || at.is_none() { (0, u64::MAX) } else { - let at = (va + from) as *const u8; + let at = at.unwrap() as *const u8; let (mut lo, mut hi) = (u32::MAX, 0u32); for k in 0..n { let i = if size == 4 { at.add(4 * k).cast::().read_unaligned() } else { at.add(2 * k).cast::().read_unaligned() as u32 }; @@ -3791,6 +4782,17 @@ unsafe fn set_index_buffer(list: *mut c_void, view: Option<&D3D12_INDEX_BUFFER_V f(list, view.map_or(std::ptr::null(), |v| v as *const _)); } +unsafe fn ensure_global_sampler_heap_raw() -> Option { + if let Some(s) = super::console_heap::global_sampler_heap_raw() { + return Some(s); + } + let dev_raw = real::device_raw(); + if let Some(dev) = ID3D12Device::from_raw_borrowed(&dev_raw) { + let _ = super::console_heap::shared_sampler_heap(dev); + } + super::console_heap::global_sampler_heap_raw() +} + /// Ensure the shared shader-visible PC sampler heap exists when a console device is live so /// directly-indexed root signatures (`SAMPLER_HEAP_DIRECTLY_INDEXED`) never run with 0 sampler /// heaps bound (D3D12 #1419 / `0x887A0001`). @@ -3864,21 +4866,58 @@ pub(super) unsafe fn pc_heaps(n: u32, heaps: *const usize) -> Vec bool) -> Option<(Vec, bool)> { + if current.contains(&view) { + return None; + } + if has_sampler { + if let Some(&s) = current.iter().find(|&&p| is_sampler(p)) { + return Some((vec![view, s], true)); + } + } + Some((vec![view], false)) +} + +/// Bind `console_heap::global_heap()` on `this` when a console-slot `ClearUnorderedAccessView*` +/// passes a GPU handle from the shared view heap and that heap is not currently bound (for +/// example after `Reset()` or `SetDescriptorHeaps(0, NULL)`, even when `heap_windows()` is off). +unsafe fn ensure_console_view_heap(this: *mut c_void) { + let Some(view) = super::console_heap::global_heap() else { return }; + let view_raw = view.as_raw() as usize; + let mut to_bind: Option> = None; + with_bindings(this, |b| { + let next = bind_view_heap(view_raw, &b.heaps, b.has_sampler_heap, |p| { + let p = p as *mut c_void; + ID3D12DescriptorHeap::from_raw_borrowed(&p).is_some_and(|h| h.GetDesc().Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) + }); + if let Some((next, has_sampler)) = next { + b.heaps = next.clone(); + b.has_sampler_heap = has_sampler; + to_bind = Some(next); + } + }); + if let Some(raw) = to_bind { + pc::(this, 28)(this, raw.len() as u32, raw.as_ptr()); + } +} + /// Translated shaders with directly-indexed root signatures (`CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` /// / `SAMPLER_HEAP_DIRECTLY_INDEXED`) and heap windows (`pso::heap_windows`) require valid /// shader-visible view and sampler heaps to be bound even if the title bound 0 heaps (or only a -/// view heap with 0 sampler heaps). -pub(super) unsafe fn ensure_view_heap(this: *mut c_void) { - let view = if crate::gpu::recomp::pso::heap_windows() { - super::console_heap::global_heap() +/// view heap with 0 sampler heaps). Returns `true` when all required shared heaps exist and are +/// bound on `this` so callers may cache the check until `SetDescriptorHeaps` / `Reset`. +pub(super) unsafe fn ensure_view_heap(this: *mut c_void) -> bool { + let need_view = crate::gpu::recomp::pso::heap_windows(); + let view_raw = if need_view { + super::console_heap::global_heap_raw() } else { None }; - let sampler = ensure_global_sampler_heap(); - let view_raw = view.as_ref().map(|h| h.as_raw() as usize); - let sampler_raw = sampler.as_ref().map(|h| h.as_raw() as usize); + let sampler_raw = ensure_global_sampler_heap_raw(); if view_raw.is_none() && sampler_raw.is_none() { - return; + return false; } let mut to_bind: Option> = None; with_bindings(this, |b| { @@ -3891,12 +4930,14 @@ pub(super) unsafe fn ensure_view_heap(this: *mut c_void) { if let Some(raw) = to_bind { pc::(this, 28)(this, raw.len() as u32, raw.as_ptr()); } + (!need_view || view_raw.is_some()) && sampler_raw.is_some() } /// console #32 SetDescriptorHeaps (PC #28) pub(super) unsafe extern "system" fn set_descriptor_heaps_x(this: *mut c_void, n: u32, heaps: *const usize) { const PC_SET_DESCRIPTOR_HEAPS: usize = 28; let f = pc::(this, PC_SET_DESCRIPTOR_HEAPS); + super::bind::set_heaps(this, if heaps.is_null() { &[] } else { std::slice::from_raw_parts(heaps, n as usize) }); if heaps.is_null() || n == 0 { // no heaps: nothing bound any more (`ensure_view_heap` binds the shared heaps again // before a translated draw or dispatch reads memory windows or samplers from them) @@ -3943,6 +4984,7 @@ pub(super) unsafe extern "system" fn ia_set_vertex_buffers_x(this: *mut c_void, let mut v = views.add(k).read_unaligned(); let title = v.BufferLocation; v.BufferLocation = gpu_va(this, v.BufferLocation, v.SizeInBytes as usize, "vertex buffer", true); + v = null_if_at_zero(v); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); let i = N.fetch_add(1, Ordering::Relaxed); @@ -3990,6 +5032,13 @@ pub(super) unsafe extern "system" fn ia_set_index_buffer_x(this: *mut c_void, vi s.bindings.index_title = Some((v.BufferLocation, v.SizeInBytes, v.Format.0)); drop(g); v.BufferLocation = gpu_va(this, v.BufferLocation, v.SizeInBytes as usize, "index buffer", true); + if v.BufferLocation == 0 { + note_null_buffer("index buffer"); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { + s.index_buffer = None; + } + return set_index_buffer(this, None); + } if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { s.index_buffer = Some(v); } @@ -4013,7 +5062,11 @@ pub(super) unsafe extern "system" fn draw_indexed_x(this: *mut c_void, va: u64, }; let bound = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).and_then(|s| s.index_buffer)); sync_title_buffers(this, None, 0, 0, 2); - let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: gpu_va(this, va, count.saturating_mul(stride) as usize, "DrawIndexedX indices", false), SizeInBytes: count.saturating_mul(stride), Format: format }; + let at = gpu_va(this, va, count.saturating_mul(stride) as usize, "DrawIndexedX indices", false); + if at == 0 { + return note_null_buffer("DrawIndexedX index buffer"); + } + let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: at, SizeInBytes: count.saturating_mul(stride), Format: format }; set_index_buffer(this, Some(&view)); super::bind::emit_prepared_indexed_draw(&list, count, 1, 0, 0, 0); set_index_buffer(this, bound.as_ref()); @@ -4059,7 +5112,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 // A failed native Reset leaves the old recording alive. Do not discard its tracked state or // transfer its allocations until the driver accepts the new recording. let ext = *(this as *const usize); - let resolved = super::pso_async::resolve_for_bind(pso); + let resolved = super::pso_async::resolve(pso); // (the PC allocator the title's allocator stands for now: `alloc_pool`) let ty = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).and_then(|s| s.list_type).map_or(-1, |t| t.0); let hr = super::alloc_pool::reset_list(this as usize, alloc, ty, |pc_alloc| { @@ -4071,12 +5124,19 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 } reset_copy_scratch(this); + // `reset_pc` calls PC `Reset` directly (bypassing `real::cl_reset`), so rotate DRED markers here. + super::dred::reset(this); + if pso != 0 { + super::dred::mark_pipeline(this, pso, resolved); + } + super::format_alias::list_reset(this as usize); reset_own_alloc(this); let is_bundle = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); s.allocator = alloc; s.bound_pso = pso; + s.last_pc_pso = resolved; s.depth_bias = None; s.native_bias = DepthBias::ZERO; s.pso_dirty = false; @@ -4085,6 +5145,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 s.depth_bounds = None; s.occlusion = Occlusion::default(); s.written_ranges.clear(); + s.written_values.clear(); s.clear_sparse_writes(); s.clear_write64_signals(); s.clear_waits(); @@ -4121,7 +5182,11 @@ 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 any_uav, mut global_uav_barrier, mut uav_transition) = (false, false, false); + let mut uav_targets: Vec = Vec::new(); + let is_direct = tracked_list_type(this).is_none_or(|t| t == D3D12_COMMAND_LIST_TYPE_DIRECT); + let mut depth_syncs: Vec = Vec::new(); + let mut alias_writers: Vec<(usize, u32)> = Vec::new(); for k in 0..n as usize { let mut b = barriers.add(k).read_unaligned(); let (ty, flags) = (b[0], b[1]); @@ -4151,6 +5216,19 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } } if ty == 2 { + // Route resource-specific UAV barriers on tracked Depth+UAV textures to both their + // materialized depth and stencil color twins before emitting the wildcard UMA UAV barrier. + let res = (b[2] as u64 | (b[3] as u64) << 32) as usize; + if res != 0 { + uav_targets.push(res); + for twin in super::depth_uav::on_uav_barrier(res) { + if twin != 0 { + out.push([2, 0, twin as u32, (twin as u64 >> 32) as u32, 0, 0, 0, 0]); + } + } + } else { + global_uav_barrier = true; + } // UAV (resource +8): translated shaders reach title memory through XCL's memory // 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 @@ -4169,18 +5247,30 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } b[5] &= PC_STATES; b[6] &= PC_STATES; + let res = (b[2] as u64 | (b[3] as u64) << 32) as usize; // VERTEX_AND_CONSTANT_BUFFER / INDEX_BUFFER are buffer states on the PC; the console // takes them for textures too (Minecraft moves a texture to a generic-read // combination) – the PC list then fails to close - if (b[5] | b[6]) & BUFFER_ONLY_STATES != 0 && !is_buffer((b[2] as u64 | (b[3] as u64) << 32) as usize) { + if (b[5] | b[6]) & BUFFER_ONLY_STATES != 0 && !is_buffer(res) { b[5] &= !BUFFER_ONLY_STATES; b[6] &= !BUFFER_ONLY_STATES; } if b[5] == b[6] { continue; } + // Depth+UAV textures: rewrite invalid UNORDERED_ACCESS transitions on depth resources + // and lazily synchronize their writable color twins. + let (pass, need_uav) = super::depth_uav::filter_transition(&b, is_direct, &mut depth_syncs); + uav_transition |= need_uav; + if !pass { + continue; + } + super::format_alias::note_title_transition(res, b[4], b[5], b[6], flags, &mut alias_writers); // UAV writes before (or after) the transition: the same holds for the window buffers - uav_transition |= (b[5] | b[6]) & UNORDERED_ACCESS != 0; + if (b[5] | b[6]) & UNORDERED_ACCESS != 0 { + uav_transition = true; + uav_targets.push(res); + } } out.push(b); } @@ -4194,7 +5284,39 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 super::title_textures::note_transitions(this as usize, &t); } if !out.is_empty() { + if any_uav || uav_transition { + super::bind::note_gpu_write(this); + } else { + super::bind::invalidate_inline_guard(this); + } pc::(this, PC_RESOURCE_BARRIER)(this, out.len() as u32, out.as_ptr()); + if super::cpu_writes::has_water_readback() { + const WRITE_STATES: u32 = UNORDERED_ACCESS | 0x4; // UNORDERED_ACCESS | RENDER_TARGET + for b in &out { + if b[0] == 0 + && b[1] == 0 + && (b[4] == 0 || b[4] == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES) + && (b[5] & WRITE_STATES) != 0 + && (b[6] & WRITE_STATES) == 0 + { + let res = (b[2] as u64 | (b[3] as u64) << 32) as usize; + maybe_enqueue_water_readback(this, res, D3D12_RESOURCE_STATES(b[6] as i32)); + } + } + } + } + if !depth_syncs.is_empty() { + super::depth_uav::execute_syncs(this, &depth_syncs); + } + if !alias_writers.is_empty() { + super::format_alias::sync_title_writers(this, &alias_writers); + } + if any_uav || uav_transition { + if global_uav_barrier { + super::depth_uav::on_global_uav_barrier(); + } + let targets = if global_uav_barrier || uav_targets.is_empty() { None } else { Some(uav_targets.as_slice()) }; + super::format_alias::on_uav_barrier(this, targets); } } @@ -4215,6 +5337,9 @@ pub(super) unsafe extern "system" fn dma_close_x(this: *mut c_void) -> i32 { let ext = *(this as *const usize); let hr = pc:: i32>(this, 9)(this); real::preserve_vtable(this, ext); + if hr >= 0 && !super::title_textures::is_own_work() { + super::title_textures::note_list_closed(this); + } if hr < 0 { let ty = pc:: i32>(this, PC_GET_TYPE)(this); crate::xlog_warn!("D3D12.X: DMA list Close → {:#x} (PC list type {ty})", hr as u32); @@ -4355,7 +5480,23 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds } } 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); + let water_dst = if d.Type == D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX + && d.Anonymous.SubresourceIndex == 0 + && x == 0 + && y == 0 + && z == 0 + && bx.is_null() + { + transmute_copy::<_, usize>(&d.pResource) + } else { + 0 + }; + 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); + } + if water_dst != 0 { + maybe_enqueue_water_readback(this, water_dst, D3D12_RESOURCE_STATE_COPY_DEST); + } std::mem::forget((d, s)); // borrowed resource pointers } @@ -4381,6 +5522,7 @@ pub(super) unsafe extern "system" fn clear_depth_stencil_x(this: *mut c_void, ds ); } } + super::depth_uav::on_clear_dsv(dsv, flags); pc::(this, PC_CLEAR_DEPTH_STENCIL_VIEW)(this, dsv, flags, depth, stencil, n, rects) } @@ -4391,8 +5533,8 @@ const PC_CLEAR_UAV_FLOAT: usize = 50; #[derive(Debug, PartialEq)] enum UavClearHandles { /// both are console slots: their PC UAVs (GPU: in the heap lists bind; CPU: in the - /// title's CPU-only heap) - Console { gpu: u64, cpu: u64 }, + /// title's CPU-only heap); `shared` is true when `gpu` lives in `console_heap::global_heap()` + Console { gpu: u64, cpu: u64, shared: bool }, /// neither is a console slot: PC handles already Pc, /// one console slot and one not, or a slot with no shader-visible UAV @@ -4402,7 +5544,9 @@ enum UavClearHandles { fn uav_clear_handles(gpu: Option, cpu: Option) -> UavClearHandles { match (gpu, cpu) { (None, None) => UavClearHandles::Pc, - (Some(g), Some(c)) if !g.sampler && !c.sampler && g.pc_gpu_uav != 0 => UavClearHandles::Console { gpu: g.pc_gpu_uav, cpu: c.pc_uav }, + (Some(g), Some(c)) if !g.sampler && !c.sampler && g.pc_gpu_uav != 0 => { + UavClearHandles::Console { gpu: g.pc_gpu_uav, cpu: c.pc_uav, shared: g.shared_srv != 0 } + } _ => UavClearHandles::Unusable, } } @@ -4411,9 +5555,9 @@ fn uav_clear_handles(gpu: Option, cpu: Option (gpu, cpu), - UavClearHandles::Pc => (gpu, cpu), + let (gpu, cpu, shared) = match uav_clear_handles(super::console_heap::slot(gpu), super::console_heap::slot(cpu)) { + UavClearHandles::Console { gpu, cpu, shared } => (gpu, cpu, shared), + UavClearHandles::Pc => (gpu, cpu, false), UavClearHandles::Unusable => { static N: AtomicU64 = AtomicU64::new(0); if once(&N, 1) { @@ -4422,7 +5566,24 @@ unsafe fn clear_uav(this: *mut c_void, slot: usize, gpu: u64, cpu: u64, res: usi return; } }; - pc::(this, slot)(this, gpu, cpu, res, values, n, rects) + 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; + } + let pc_res = super::depth_uav::twin_for_pc_uav(cpu as usize).unwrap_or(res); + if let Some((va, len)) = real::console_buffer(res) { + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va)) { + note_write(this as usize, va as u64, len as u64); + } + } + super::bind::note_gpu_write(this); + if shared { + ensure_console_view_heap(this); + } + pc::(this, slot)(this, gpu, cpu, pc_res, values, n, rects) } pub(super) unsafe extern "system" fn clear_uav_uint_x(this: *mut c_void, gpu: u64, cpu: u64, res: usize, values: *const u32, n: u32, rects: *const windows::Win32::Foundation::RECT) { @@ -4463,6 +5624,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; super::present::note_use(dst, super::present::USE_COPY); trace_resolve("ResolveSubresource", dst, src, format, ""); pc::(this, PC_RESOLVE_SUBRESOURCE)(this, dst, dst_sub, src, src_sub, format) @@ -4472,6 +5634,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; super::present::note_use(dst, super::present::USE_COPY); if super::present::trace_frame() { trace_resolve("ResolveSubresourceRegion", dst, src, format, &format!(" mode {mode} at ({x}, {y}) rect {:?}", rect.as_ref().map(|r| (r.left, r.top, r.right, r.bottom)))); @@ -4479,6 +5642,64 @@ pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_v pc::(this, PC_RESOLVE_SUBRESOURCE_REGION)(this, dst, dst_sub, x, y, src, src_sub, rect, format, mode) } +/// If `dst` is a tracked placed ocean height/displacement/buoyancy texture (`256×256` +/// `R32_FLOAT`/`R32G32_FLOAT`, `64×64` `R32G32_FLOAT`, or `128×128` `R16G16_UINT`), copy +/// subresource 0 into a pooled `READBACK` buffer using its actual current `cur_state` (skipping +/// redundant barriers if already in `COPY_SOURCE`) and queue asynchronous XOR-swizzled writeback +/// into console memory on `xcl-cpu-writes` after this submission's GPU fence completes. +unsafe fn maybe_enqueue_water_readback(this: *mut c_void, dst: usize, cur_state: D3D12_RESOURCE_STATES) { + let Some(target) = super::cpu_writes::water_readback_target(dst) else { return }; + if list_type(this) == D3D12_COMMAND_LIST_TYPE_BUNDLE { + return; + } + let Some(dev) = device_of(this) else { return }; + let total_bytes = u64::from(target.row_pitch) * u64::from(target.height); + let Some(rb) = super::cpu_writes::take_water_readback_buf(&dev, total_bytes) else { return }; + let Some(rb_res) = rb.buf.as_ref() else { return }; + let src_loc = D3D12_TEXTURE_COPY_LOCATION { + pResource: transmute_copy(&dst), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let dst_loc = D3D12_TEXTURE_COPY_LOCATION { + pResource: transmute_copy(&rb_res.as_raw()), + 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: target.format, + Width: target.width, + Height: target.height, + Depth: 1, + RowPitch: target.row_pitch, + }, + }, + }, + }; + let need_barrier = (cur_state.0 & D3D12_RESOURCE_STATE_COPY_SOURCE.0) == 0; + if need_barrier { + transition(this, dst, cur_state, D3D12_RESOURCE_STATE_COPY_SOURCE); + } + pc::( + this, + PC_COPY_TEXTURE_REGION, + )(this, &dst_loc, 0, 0, 0, &src_loc, std::ptr::null()); + if need_barrier { + transition(this, dst, D3D12_RESOURCE_STATE_COPY_SOURCE, cur_state); + } + std::mem::forget((src_loc, dst_loc)); // borrowed resource pointers + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); + s.cpu_writes.push(super::cpu_writes::Write::ReadbackTexture { + dst_va: target.va, + format: target.format, + row_pitch: target.row_pitch, + tex: target.tex, + buf: rb, + }); +} + /// CopyResource(dst, src) (PC #17; DMA list #13): buffers placed below their console address /// are copied as their own bytes (the PC resources also hold what lies before them) pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usize, src: usize) { @@ -4489,7 +5710,11 @@ 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 { - 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); + } + maybe_enqueue_water_readback(this, dst, D3D12_RESOURCE_STATE_COPY_DEST); + 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); @@ -4592,6 +5817,19 @@ pub(super) unsafe extern "system" fn resolve_query_data_x(this: *mut c_void, hea #[cfg(test)] mod tests { use super::*; + + /// A vertex buffer view at address 0 with a size is a null view; any other is as it was. + #[test] + fn a_vertex_buffer_view_at_address_0_is_null() { + let view = |at: u64, size: u32| D3D12_VERTEX_BUFFER_VIEW { BufferLocation: at, SizeInBytes: size, StrideInBytes: 16 }; + let v = null_if_at_zero(view(0, 4096)); + assert_eq!((v.BufferLocation, v.SizeInBytes, v.StrideInBytes), (0, 0, 16)); + for (at, size) in [(0, 0), (0x1000, 4096), (0x1000, 0)] { + let v = null_if_at_zero(view(at, size)); + assert_eq!((v.BufferLocation, v.SizeInBytes), (at, size)); + } + } + use std::sync::Arc; /// An internal wait shows in the watchdog's summary while its fence is short of the value, @@ -4947,6 +6185,73 @@ mod tests { assert!(!s.has_prior_write(0x0FF8, 8)); } + /// A wait on an address the same list wrote is dropped only when the value that write left + /// meets it: a list that resets a counter to 0 and then waits for another queue to raise it + /// keeps its wait. + #[test] + fn a_wait_after_an_own_write_is_dropped_only_when_the_written_value_meets_it() { + let cell64 = AtomicU64::new(0); + let cell32 = AtomicU32::new(0); + let (va64, va32) = (&cell64 as *const AtomicU64 as u64, &cell32 as *const AtomicU32 as u64); + let mut token = 0usize; + let list = (&mut token as *mut usize).cast::(); + // records the writes (as `write` does) and the wait, and returns the waits left on the list + let kept = |writes: &[(u64, &[u32])], wait: &dyn Fn()| -> usize { + for &(va, words) in writes { + note_write_value(list as usize, va, words); + } + wait(); + let n = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).map_or(0, |s| s.pending_waits.len()); + on_release(list as usize); + n + }; + let w64 = |v: u64| [v as u32, (v >> 32) as u32]; + use D3D12_COMPARISON_FUNC as F; + // (value written, comparison, value waited for, wait kept) + for (written, op, wanted, keep) in [ + (0u64, D3D12_COMPARISON_FUNC_GREATER_EQUAL, 1u64, true), + (5, D3D12_COMPARISON_FUNC_GREATER_EQUAL, 1, false), + (0xFFFF_FFFF, D3D12_COMPARISON_FUNC_GREATER_EQUAL, 1 << 32, true), + (0, D3D12_COMPARISON_FUNC_EQUAL, 1, true), + (1, D3D12_COMPARISON_FUNC_EQUAL, 1, false), + (1, D3D12_COMPARISON_FUNC_NOT_EQUAL, 1, true), + (0, D3D12_COMPARISON_FUNC_NOT_EQUAL, 1, false), + (1, D3D12_COMPARISON_FUNC_LESS, 1, true), + (0, D3D12_COMPARISON_FUNC_LESS, 1, false), + (2, D3D12_COMPARISON_FUNC_LESS_EQUAL, 1, true), + (1, D3D12_COMPARISON_FUNC_LESS_EQUAL, 1, false), + (1, D3D12_COMPARISON_FUNC_GREATER, 1, true), + (2, D3D12_COMPARISON_FUNC_GREATER, 1, false), + (0, D3D12_COMPARISON_FUNC_ALWAYS, 1, false), + (0, D3D12_COMPARISON_FUNC_NEVER, 1, false), + ] { + let F(op) = op; + let got = kept(&[(va64, &w64(written))], &|| unsafe { wait64_x(list, va64, op as u32, wanted, 0, 0) }); + assert_eq!(got, keep as usize, "64-bit: wrote {written:#x}, wait op {op} {wanted:#x}"); + if wanted <= u32::MAX as u64 && written <= u32::MAX as u64 { + let got = kept(&[(va32, &[written as u32])], &|| unsafe { wait32_x(list, va32, op as u32, wanted as u32, u32::MAX, 0) }); + assert_eq!(got, keep as usize, "32-bit: wrote {written:#x}, wait op {op} {wanted:#x}"); + } + } + let ge = D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32; + let eq = D3D12_COMPARISON_FUNC_EQUAL.0 as u32; + // the mask applies to the written value too + assert_eq!(kept(&[(va32, &[0x1234_00FF])], &|| unsafe { wait32_x(list, va32, eq, 0xFF, 0xFF, 0) }), 0); + assert_eq!(kept(&[(va32, &[0x0000_12FE])], &|| unsafe { wait32_x(list, va32, eq, 0xFF, 0xFF, 0) }), 1); + // the last write before the wait counts + assert_eq!(kept(&[(va64, &w64(5)), (va64, &w64(0))], &|| unsafe { wait64_x(list, va64, ge, 1, 0, 0) }), 1); + assert_eq!(kept(&[(va64, &w64(0)), (va64, &w64(5))], &|| unsafe { wait64_x(list, va64, ge, 1, 0, 0) }), 0); + // a write to another address leaves the wait alone + assert_eq!(kept(&[(va32, &[5])], &|| unsafe { wait64_x(list, va64, ge, 1, 0, 0) }), 1); + // a write of unknown value over it (a fill or a copy) still drops the wait, as before + let fill = || { + note_write_value(list as usize, va64, &w64(0)); + note_write(list as usize, va64, 8); + unsafe { wait64_x(list, va64, ge, 1, 0, 0) } + }; + assert_eq!(kept(&[], &fill), 0); + } + #[test] fn execute_with_waits_splits_batches_before_unsatisfied_list() { // Use synthetic non-zero list pointers distinct from real COM objects. @@ -6146,6 +7451,43 @@ mod tests { assert_eq!(seen, [true]); } + /// A wait armed between the watchdog's check (no wait armed) and its `cv.wait` wakes it: the + /// watchdog pauses there (`after_check`) until the arm's notify is done, or 200 ms when the + /// notify waits for the lock. A notify that does not take the lock is lost there, and the + /// watchdog sleeps with the wait armed (no "did not complete" release). + #[test] + fn a_wait_armed_during_the_watchdogs_check_wakes_it() { + use std::sync::{mpsc, Arc}; + let pair = Arc::new((Mutex::new(()), Condvar::new())); + let armed = Arc::new(AtomicUsize::new(0)); + let (checked_tx, checked_rx) = mpsc::channel(); + let (notified_tx, notified_rx) = mpsc::channel::<()>(); + let (woke_tx, woke_rx) = mpsc::channel(); + let (p, a) = (pair.clone(), armed.clone()); + let watchdog = std::thread::spawn(move || { + let slept = sync_watchdog_sleep_if_idle(&p, &a, || { + checked_tx.send(()).unwrap(); + let _ = notified_rx.recv_timeout(Duration::from_millis(200)); + }) + .is_none(); + woke_tx.send(slept).unwrap(); + }); + checked_rx.recv().unwrap(); + armed.fetch_add(1, Ordering::AcqRel); + notify_sync_watchdog(&pair); + // (the pause may be over already: then nobody receives this) + let _ = notified_tx.send(()); + let woke = woke_rx.recv_timeout(Duration::from_secs(2)); + if woke.is_err() { + // let the thread end before the test fails + pair.1.notify_one(); + } + watchdog.join().unwrap(); + assert_eq!(woke, Ok(true), "the watchdog slept through the arm's notify"); + // a wait already armed: no sleep, the lock comes back + assert!(sync_watchdog_sleep_if_idle(&pair, &armed, || unreachable!()).is_some()); + } + /// Submitting a DIRECT list with `Wait64BitValueX(va, >=, 0x677)` BEFORE submitting the /// COMPUTE list that recorded `Write64BitValueBottomOfPipeX(va, 0x677)` must bridge via /// GPU `queue.Wait`/`queue.Signal` without blocking the submitter thread for `WAIT_TIMEOUT`. @@ -6735,6 +8077,123 @@ mod tests { !would_signal_close_cycle(&mut g3, 0xD001, 0x3000, 0x78d), "pipelined 3-queue chain with wait_seq > sig_seq must NOT be treated as a cycle" ); + + // 3. Next frame's signal on a cell whose armed wait an earlier signal already covers + // (a retail title, frame 0x6dc): C (0xC001) signalled A=0x6db, Direct (0xD001) + // waits A >= 0x6db (seq 3544) and later signals B=0x6dc (seq 3572); C waits on + // B >= 0x6dc (seq 34) and now signals A=0x6dc. Direct's wait is satisfied by C's + // 0x6db signal, not by this one: no cycle. + let fa: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let fb: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut gp = SyncGraph::default(); + gp.cells.insert( + 0x4000, + SyncCell { + fence: Some(fa), + device: dev.as_raw() as usize, + recorded_max: 0x6dc, + submitted_max: 0x6db, + submitted_queue: Some(0xC001), + armed_waits: vec![ArmedGpuWait { + val: 0x6db, + waiting_queue: 0xD001, + waiting_queue_ty: D3D12_COMMAND_LIST_TYPE_DIRECT.0, + wait_seq: 3544, + armed_at: Instant::now(), + after_write64: false, + }], + submitted_signals: vec![SubmittedSignal { val: 0x6db, queue: 0xC001, seq: 16 }], + ..Default::default() + }, + ); + gp.cells.insert( + 0x5000, + SyncCell { + fence: Some(fb), + device: dev.as_raw() as usize, + recorded_max: 0x6dc, + submitted_max: 0x6dc, + submitted_queue: Some(0xD001), + armed_waits: vec![ArmedGpuWait { + val: 0x6dc, + waiting_queue: 0xC001, + waiting_queue_ty: D3D12_COMMAND_LIST_TYPE_COMPUTE.0, + wait_seq: 34, + armed_at: Instant::now(), + after_write64: false, + }], + submitted_signals: vec![SubmittedSignal { val: 0x6dc, queue: 0xD001, seq: 3572 }], + ..Default::default() + }, + ); + assert!( + !would_signal_close_cycle(&mut gp, 0xC001, 0x4000, 0x6dc), + "a wait an earlier signal already satisfies must NOT make the next frame's signal a cycle" + ); + // Direct waiting on A >= 0x6dc instead (only this signal satisfies it): a true cycle. + gp.cells.get_mut(&0x4000).unwrap().armed_waits[0].val = 0x6dc; + assert!( + would_signal_close_cycle(&mut gp, 0xC001, 0x4000, 0x6dc), + "a wait only this signal satisfies, armed before the waiter's own signal, MUST be a cycle" + ); + } + } + + /// The next frame's Signal of a title fence does not break a "cycle" through a wait an earlier + /// signal of that fence satisfies; one that only the new signal satisfies is a cycle, broken + /// by releasing the cell's wait. + #[test] + fn a_title_fence_wait_an_earlier_signal_covers_is_no_cycle() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let title: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let cell: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let (q0, q1, va, f) = (0xC0F0usize, 0xC0F1usize, 0x7E57_C0F0u64, title.as_raw() as usize); + // q1 signalled the fence at 1; q0 waits for that and signals the cell later, which q1 + // waits for; q1 is about to signal the fence at 2 + let set = |wait: u64| { + let mut g = SYNC_GRAPH.lock().unwrap(); + let gr = g.get_or_insert_with(SyncGraph::default); + let mut tf = TitleFenceSync::default(); + tf.waits.push((wait, q0, 5)); + tf.signals.push(SubmittedSignal { val: 1, queue: q1, seq: 3 }); + gr.title_fences.insert(f, tf); + if !gr.cells.contains_key(&va) { + ARMED_GPU_WAITS.fetch_add(1, Ordering::AcqRel); + gr.cells.insert( + va, + SyncCell { + fence: Some(cell.clone()), + device: dev.as_raw() as usize, + recorded_max: 9, + submitted_max: 9, + submitted_queue: Some(q0), + armed_waits: vec![ArmedGpuWait { val: 9, waiting_queue: q1, waiting_queue_ty: D3D12_COMMAND_LIST_TYPE_COMPUTE.0, wait_seq: 4, armed_at: Instant::now(), after_write64: false }], + submitted_signals: vec![SubmittedSignal { val: 9, queue: q0, seq: 7 }], + ..Default::default() + }, + ); + } + }; + set(1); + break_cycles_before_title_signal(q1, f, 2); + assert_eq!(cell.GetCompletedValue(), 0, "the wait is the earlier signal's: nothing is released"); + set(2); + break_cycles_before_title_signal(q1, f, 2); + assert_eq!(cell.GetCompletedValue(), 9, "a wait only the new signal satisfies: released"); + let mut g = SYNC_GRAPH.lock().unwrap(); + let gr = g.as_mut().unwrap(); + gr.title_fences.remove(&f); + let left = gr.cells.remove(&va).map_or(0, |c| c.armed_waits.len()); + if left > 0 { + ARMED_GPU_WAITS.fetch_sub(left, Ordering::AcqRel); + } } } @@ -7079,6 +8538,149 @@ mod tests { } } + /// With `XCL_PSO_WAIT_MS`, a dispatch put off to the submit whose pipeline is built after the + /// budget (and that a bind already found `late`) is recorded with the built pipeline: its + /// output is written, as is the `Write64` after it in the list. Before, the submit's bind gave + /// up after the budget and left the dispatch out while the label still fired. + #[test] + fn a_put_off_dispatch_runs_at_the_submit_when_its_build_outlasts_the_wait_budget() { + use super::super::{bind, pso_async, title_list}; + use crate::gpu::recomp::runner; + use crate::gpu::xbox::tests::{fssm, sample}; + use std::time::{Duration, Instant}; + + if crate::gpu::recomp::dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + if super::super::backend() != super::super::Backend::Real { + return runner::skip_test("no GPU"); + } + if runner::wave64_programs_supported() != Ok(true) { + return runner::skip_test("no wave64"); + } + if real::uma_window_vas().is_empty() { + return runner::skip_test("no unified memory on the GPU"); + } + const MARK: u32 = 0x600D_F00D; + const LABEL: u64 = 0x1AB_E15E_7000_0001; + unsafe { + let raw = real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw).unwrap().clone(); + // s[0:1]: the argument table; its first 8 bytes say where the program stores MARK + let code: Vec = [ + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 0x7D)][..], None), + ("S_WAITCNT", "ENC_SOPP", &[("SIMM16", 0)][..], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 4)][..], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 5)][..], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 255)][..], Some(MARK)), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 1), ("SADDR", 0x7D)][..], None), + ("S_ENDPGM", "ENC_SOPP", &[][..], None), + ] + .iter() + .flat_map(|(n, e, f, l)| crate::gpu::rdna2::encode(n, e, f, *l).unwrap_or_else(|x| panic!("{n}: {x}"))) + .collect(); + let mut f = fssm(&code, &[(6, 1)]); + // COMPUTE_PGM_RSRC2 (2 user SGPRs) and numthreads + for (k, x) in [2u32 << 1, 64, 1, 1].into_iter().enumerate() { + f[0x138 + 4 * k..0x13C + 4 * k].copy_from_slice(&x.to_le_bytes()); + } + let blob = sample(5, &[f]); + let game_rs: ID3D12RootSignature = { + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).unwrap(); + let ser = ser.unwrap(); + dev.CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())).unwrap() + }; + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(game_rs)), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: blob.as_ptr() as _, BytecodeLength: blob.len() }, + ..Default::default() + }; + let made: windows::core::Result = dev.CreateComputePipelineState(&desc); + std::mem::ManuallyDrop::drop(&mut desc.pRootSignature); + let made = made.expect("CreateComputePipelineState through the backend hook"); + let built = pso_async::resolve_wait(made.as_raw() as usize); + assert!(real::is_translated_compute(built), "not translated: {:?}", real::stats().translation_errors); + + // the title's pipeline: a stand-in whose build ends once the submit has begun + let standin = 0x7E57_D0F1usize; + static BUILD: AtomicBool = AtomicBool::new(false); + BUILD.store(false, Ordering::Release); + pso_async::submit( + standin, + true, + Box::new(move || { + let t = Instant::now(); + while !BUILD.load(Ordering::Acquire) && t.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(5)); + } + ID3D12PipelineState::from_raw_borrowed(&(built as *mut c_void)).unwrap().clone().into_raw() as usize + }), + ); + pso_async::set_wait_budget_for_test(Some(Duration::from_millis(50))); + assert_eq!(pso_async::resolve_wait(standin), standin, "a bind as the title records: past the budget, late"); + + let u = crate::gpu::uma::get().unwrap(); + let out = u.alloc(256, 256).unwrap(); + std::ptr::write_bytes(out, 0, 256); + let label = out.add(64) as *mut u64; + + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let a = alloc.as_raw() as usize; + let pc0 = real::create_raw_pc_command_list(raw, ty, a, 0).expect("a PC command list"); + on_create(pc0, a, 0, ty); + bind::reset(pc0, a, standin); + let wrap = title_list::wrap(pc0); + bind::set_args_for_test(pc0, (out as u64).to_le_bytes().to_vec()); + + bind::dispatch(pc0, 1, 1, 1); + let mut segs = Vec::new(); + assert!(title_list::push_segments(wrap, &mut segs)); + assert_eq!(segs.len(), 3, "the dispatch was not put off"); + write64_bottom_x(*segs.last().unwrap(), label as u64, LABEL, 0, 0); + let close_fn: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(9)); + assert_eq!(close_fn(wrap), 0); + + let build = std::thread::spawn(|| { + std::thread::sleep(Duration::from_millis(400)); + BUILD.store(true, Ordering::Release); + }); + let t = Instant::now(); + record_deferred(wrap); + let took = t.elapsed(); + pso_async::set_wait_budget_for_test(None); + build.join().unwrap(); + + 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(); + segs.clear(); + assert!(title_list::push_segments(wrap, &mut segs)); + type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + let q = queue.as_raw(); + let exec: ExecFn = if real::is_adopted(q) { + std::mem::transmute(real::orig_fn(q, PC_QUEUE_EXECUTE_COMMAND_LISTS)) + } else { + std::mem::transmute(*(*(q as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)) + }; + exec(q, segs.len() as u32, segs.as_ptr()); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 5000).expect("the list runs"); + let (mark, labelled) = (std::ptr::read_volatile(out as *const u32), std::ptr::read_volatile(label)); + let removed = dev.GetDeviceRemovedReason(); + + let rel_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(2)); + rel_fn(wrap); + pso_async::release(pso_async::released(standin)); + drop(made); + + assert!(removed.is_ok()); + assert_eq!(labelled, LABEL, "the Write64 after the dispatch"); + assert_eq!(mark, MARK, "the put-off dispatch was left out (the submit waited {took:?})"); + assert!(took >= Duration::from_millis(300), "the submit did not wait for the build ({took:?})"); + } + } + /// Reproduces the exact intra-list fork-join pattern seen on retail compute queues: /// q_compute list O_c: Write64(cell_A, frame) -> Wait64(cell_B >= frame) -> Write64(cell_C, frame) /// q_direct list O_d: Wait64(cell_A >= frame) -> Write64(cell_B, frame) @@ -7264,6 +8866,132 @@ mod tests { } } + /// The per-draw sync copies a mirrored vertex buffer without asking `readable` (#2392): with + /// one page of it made unreadable after the mirror was made, the draw's other pages are + /// still brought up to date and the unreadable one keeps what the mirror had, and the + /// vertex range comes from the indices as the title wrote them (read from their mirror). + /// Before, `readable` failed for the whole range and nothing was copied. + #[test] + fn the_mirror_sync_copies_around_a_page_the_title_made_unreadable() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualProtect, MEM_COMMIT, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + if crate::gpu::uma::get().is_none() { + crate::gpu::recomp::runner::skip_test("no unified memory"); + return; + } + unsafe { + let len = 0x1_0000usize; + let vb = VirtualAlloc(std::ptr::null(), len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; + let ib = VirtualAlloc(std::ptr::null(), len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u16; + assert!(!vb.is_null() && !ib.is_null()); + let (vb_bytes, stride) = (0x3000u32, 16u32); + std::ptr::write_bytes(vb, 0x11, vb_bytes as usize); + for (k, i) in [0u16, 1, 2].into_iter().enumerate() { + *ib.add(k) = i; + } + let list = 0x7e57_0000_2392usize as *mut c_void; + assert_ne!(gpu_va(list, vb as u64, vb_bytes as usize, "test vertex buffer", true), vb as u64); + assert_ne!(gpu_va(list, ib as u64, 6, "test index buffer", true), ib as u64); + let vm = mirrored(vb as u64, vb_bytes as usize).unwrap() as *const u8; + with_bindings(list, |b| { + b.vertex_titles.insert(0, (vb as u64, vb_bytes, stride)); + b.index_title = Some((ib as u64, 6, DXGI_FORMAT_R16_UINT.0)); + }); + // the title writes new vertices on all three pages and indices that reach them, then + // makes the middle page unreadable + std::ptr::write_bytes(vb, 0x22, vb_bytes as usize); + for (k, i) in [0u16, 0x1000 / 16, (vb_bytes / stride - 1) as u16].into_iter().enumerate() { + *ib.add(k) = i; + } + let mut old = 0u32; + assert_ne!(VirtualProtect(vb.add(0x1000) as *const _, 0x1000, PAGE_NOACCESS, &mut old), 0); + sync_title_buffers(list, Some((0, 3, 0)), 0, 0, 1); + assert!((0..0x1000).all(|k| *vm.add(k) == 0x22), "the first page is copied"); + assert!((0x1000..0x2000).all(|k| *vm.add(k) == 0x11), "the unreadable page keeps the mirror's bytes"); + assert!((0x2000..0x3000).all(|k| *vm.add(k) == 0x22), "the last page, reached by the last index, is copied"); + LISTS.lock().unwrap().as_mut().unwrap().remove(&(list as usize)); + // (the ranges stay allocated: the mirror table is never emptied) + } + } + + /// The per-draw sync copies only the pages of a write-watched source the title wrote + /// (#2393): none after a look found it unchanged; a page written since the look at the next + /// draw (still on the write-watch); a page written and then taken off the write-watch by a + /// look at the draw after that look (handed on by `mirror_pages_written`). A source that is + /// not write-watched is copied at every draw, as before. + #[test] + fn the_mirror_sync_copies_only_the_pages_the_title_wrote() { + use windows_sys::Win32::System::Memory::{GetWriteWatch, VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE}; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + if crate::gpu::uma::get().is_none() { + crate::gpu::recomp::runner::skip_test("no unified memory"); + return; + } + unsafe { + let (len, bytes, stride) = (0x1_0000usize, 0x3000u32, 16u32); + let list = 0x7e57_0000_2393usize as *mut c_void; + // a look as `title_textures` makes it: written pages off the write-watch, handed on + let look = |src: *mut u8| { + mirror_look_begin(); + let mut buf = vec![std::ptr::null_mut(); len >> 12]; + let (mut n, mut granularity) = (buf.len(), 0u32); + assert_eq!(GetWriteWatch(1, src as *const c_void, len, buf.as_mut_ptr(), &mut n, &mut granularity), 0); + let dirty: Vec = buf[..n].iter().map(|&p| p as usize).collect(); + mirror_pages_written(&dirty); + }; + // the draw, with the mirror's pages set to `mark` first; again when another test's + // look overlapped it (a draw then copies its whole range) + let draw = |m: *mut u8, mark: u8| loop { + std::ptr::write_bytes(m, mark, bytes as usize); + let seq = MIRROR_LOOK_SEQ.load(Ordering::SeqCst); + sync_title_buffers(list, None, 0, bytes / stride, 1); + if seq % 2 == 0 && MIRROR_LOOK_SEQ.load(Ordering::SeqCst) == seq { + break; + } + }; + let page = |m: *mut u8, k: usize| *m.add(k << 12 | 0x123); + + let src = VirtualAlloc(std::ptr::null(), len, MEM_COMMIT | MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) as *mut u8; + assert!(!src.is_null()); + std::ptr::write_bytes(src, 0x11, bytes as usize); + assert_ne!(gpu_va(list, src as u64, bytes as usize, "test vertex buffer", true), src as u64); + let m = mirrored(src as u64, bytes as usize).unwrap() as *mut u8; + with_bindings(list, |b| { + b.vertex_titles.insert(0, (src as u64, bytes, stride)); + }); + // the title's writes before the mirror was made: on the write-watch until a look, + // copied once at the draw after it + look(src); + draw(m, 0xee); + assert_eq!((page(m, 0), page(m, 2)), (0x11, 0x11), "pages written before the look are copied once"); + draw(m, 0xee); + assert_eq!((page(m, 0), page(m, 1), page(m, 2)), (0xee, 0xee, 0xee), "unchanged since: nothing copied"); + *src.add(0x1000 | 0x123) = 0x22; + draw(m, 0xee); + assert_eq!((page(m, 0), page(m, 1), page(m, 2)), (0xee, 0x22, 0xee), "the page written since the look is copied"); + look(src); + *src.add(0x2000 | 0x123) = 0x33; + look(src); + draw(m, 0xee); + assert_eq!((page(m, 0), page(m, 2)), (0xee, 0x33), "the page a look took off the write-watch is copied at the next draw"); + draw(m, 0xee); + assert_eq!(page(m, 2), 0xee, "and only once"); + + // not write-watched: every draw copies + let plain = VirtualAlloc(std::ptr::null(), len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; + assert!(!plain.is_null()); + std::ptr::write_bytes(plain, 0x44, bytes as usize); + assert_ne!(gpu_va(list, plain as u64, bytes as usize, "test vertex buffer", true), plain as u64); + let pm = mirrored(plain as u64, bytes as usize).unwrap() as *mut u8; + with_bindings(list, |b| { + b.vertex_titles.insert(0, (plain as u64, bytes, stride)); + }); + draw(pm, 0xee); + assert_eq!((page(pm, 0), page(pm, 2)), (0x44, 0x44), "a source that is not write-watched is copied"); + LISTS.lock().unwrap().as_mut().unwrap().remove(&(list as usize)); + // (the ranges stay allocated: the mirror table is never emptied) + } + } + #[test] fn occlusion_tracks_dropped_draws_and_active_counter() { let mut occ = Occlusion::default(); @@ -7310,21 +9038,38 @@ mod tests { assert_eq!(default_bound_heaps(Some(0x10), Some(0x20), &[0x10, 0x99], true), None); } + #[test] + fn bind_view_heap_binds_shared_heap_after_reset_and_preserves_sampler() { + let is_sampler = |p: usize| p == 0x20 || p == 0x99; + // Empty after Reset() / SetDescriptorHeaps(0, NULL) -> binds shared view heap + assert_eq!(bind_view_heap(0x10, &[], false, is_sampler), Some((vec![0x10], false))); + // Shared view heap already bound -> no-op + assert_eq!(bind_view_heap(0x10, &[0x10], false, is_sampler), None); + assert_eq!(bind_view_heap(0x10, &[0x10, 0x20], true, is_sampler), None); + // Sampler heap bound alone -> bind shared view heap alongside it + assert_eq!(bind_view_heap(0x10, &[0x20], true, is_sampler), Some((vec![0x10, 0x20], true))); + // Different view heap bound with sampler -> replace view heap while keeping sampler + assert_eq!(bind_view_heap(0x10, &[0x77, 0x99], true, is_sampler), Some((vec![0x10, 0x99], true))); + // Different view heap bound alone -> replace with shared view heap + assert_eq!(bind_view_heap(0x10, &[0x77], false, is_sampler), Some((vec![0x10], false))); + } + /// ClearUnorderedAccessView* handles: two console slots → their PC UAVs, two PC handles as /// they are, anything else not usable. #[test] fn uav_clear_handles_translate_console_slots() { use super::super::console_heap::Slot; - let s = |pc_uav: u64, pc_gpu_uav: u64, sampler: bool| Some(Slot { at: 0x1000, index: 1, pc_srv: 0, pc_uav, pc_gpu_uav, sampler, shared_srv: 0, k: 0 }); - assert_eq!(uav_clear_handles(s(0x10, 0x5010, false), s(0x20, 0, false)), UavClearHandles::Console { gpu: 0x5010, cpu: 0x20 }); + let s = |pc_uav: u64, pc_gpu_uav: u64, shared_srv: u64, sampler: bool| Some(Slot { at: 0x1000, index: 1, pc_srv: 0, pc_uav, pc_gpu_uav, sampler, shared_srv, k: 0 }); + assert_eq!(uav_clear_handles(s(0x10, 0x5010, 0, false), s(0x20, 0, 0, false)), UavClearHandles::Console { gpu: 0x5010, cpu: 0x20, shared: false }); + assert_eq!(uav_clear_handles(s(0x10, 0x5010, 0x9000, false), s(0x20, 0, 0, false)), UavClearHandles::Console { gpu: 0x5010, cpu: 0x20, shared: true }); assert_eq!(uav_clear_handles(None, None), UavClearHandles::Pc); // a console slot beside a PC handle, a GPU slot of a heap that is not shader visible, // sampler slots - assert_eq!(uav_clear_handles(s(0x10, 0x5010, false), None), UavClearHandles::Unusable); - assert_eq!(uav_clear_handles(None, s(0x20, 0, false)), UavClearHandles::Unusable); - assert_eq!(uav_clear_handles(s(0x10, 0, false), s(0x20, 0, false)), UavClearHandles::Unusable); - assert_eq!(uav_clear_handles(s(0x10, 0x5010, false), s(0, 0, true)), UavClearHandles::Unusable); - assert_eq!(uav_clear_handles(s(0, 0, true), s(0x20, 0, false)), UavClearHandles::Unusable); + assert_eq!(uav_clear_handles(s(0x10, 0x5010, 0, false), None), UavClearHandles::Unusable); + assert_eq!(uav_clear_handles(None, s(0x20, 0, 0, false)), UavClearHandles::Unusable); + assert_eq!(uav_clear_handles(s(0x10, 0, 0, false), s(0x20, 0, 0, false)), UavClearHandles::Unusable); + assert_eq!(uav_clear_handles(s(0x10, 0x5010, 0, false), s(0, 0, 0, true)), UavClearHandles::Unusable); + assert_eq!(uav_clear_handles(s(0, 0, 0, true), s(0x20, 0, 0, false)), UavClearHandles::Unusable); } /// Console code clears a UAV with its console heap slots (heap #9 / #10 give it their @@ -7432,4 +9177,255 @@ mod tests { assert!(got.iter().all(|&v| v == 0xDEAD_BEEF), "the UAV was not cleared: {:x?}", &got[..4]); } } + + #[test] + fn thread_dims_to_groups_divides_and_ceils_each_axis() { + assert_eq!(thread_dims_to_groups([0, 1, 1], [64, 1, 1]), None); + assert_eq!(thread_dims_to_groups([64, 1, 1], [64, 1, 1]), Some([1, 1, 1])); + assert_eq!(thread_dims_to_groups([70, 1, 1], [64, 1, 1]), Some([2, 1, 1])); + assert_eq!(thread_dims_to_groups([1920, 1080, 3], [8, 8, 1]), Some([240, 135, 3])); + assert_eq!(thread_dims_to_groups([1, 1, 1], [0, 0, 0]), Some([1, 1, 1])); + } + + #[test] + fn dispatch_chain_shared_scratch_clears_on_create_release_and_segment_clear() { + let list = 0x7E57_D150usize; + let alloc = 0x7E57_D160usize; + // 1. on_create clears any stale SHARED entry at a recycled COM pointer. + real::dispatch_chain::seed_shared_for_test(list, alloc); + assert!(real::dispatch_chain::has_shared_for_test(list)); + unsafe { on_create(list as *mut c_void, alloc, 0, D3D12_COMMAND_LIST_TYPE_DIRECT) }; + assert!(!real::dispatch_chain::has_shared_for_test(list)); + // 2. clear_segment_state clears SHARED when a split segment returns to spares. + real::dispatch_chain::seed_shared_for_test(list, alloc); + clear_segment_state(list); + assert!(!real::dispatch_chain::has_shared_for_test(list)); + // 3. on_release clears SHARED when the list is released. + real::dispatch_chain::seed_shared_for_test(list, alloc); + on_release(list); + assert!(!real::dispatch_chain::has_shared_for_test(list)); + } + + #[test] + fn render_target_snapshot_survives_guest_slot_overwrite_and_recycles() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory4}; + + unsafe { + let Ok(fac) = CreateDXGIFactory1::() else { + return; + }; + let Ok(warp) = fac.EnumWarpAdapter::() else { + return; + }; + let mut dev: Option = None; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + return; + } + let dev = dev.unwrap(); + let dev_key = dev.as_raw() as usize; + + let tex_desc = |format, flags| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 16, + Height: 16, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: flags, + ..Default::default() + }; + let make_tex = |format, flags, state| -> ID3D12Resource { + let mut r: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &tex_desc(format, flags), + state, + None, + &mut r, + ) + .unwrap(); + r.unwrap() + }; + let rt_a = make_tex(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_RENDER_TARGET); + let rt_b = make_tex(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_RENDER_TARGET); + let ds_a = make_tex(DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, D3D12_RESOURCE_STATE_DEPTH_WRITE); + let ds_b = make_tex(DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, D3D12_RESOURCE_STATE_DEPTH_WRITE); + + let rtv_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }) + .unwrap(); + let dsv_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + NumDescriptors: 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }) + .unwrap(); + let rtv_inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; + let rtv0 = rtv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + let rtv1 = rtv0 + rtv_inc; + let dsv0 = dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + dev.CreateRenderTargetView(&rt_a, None, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: rtv0 }); + dev.CreateRenderTargetView(&rt_b, None, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: rtv1 }); + dev.CreateDepthStencilView(&ds_a, None, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dsv0 }); + + 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 raw = list.as_raw(); + real::adopt(raw, real::Kind::CommandList); + on_create(raw, alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + + // 1. Separate-handle MRT + DSV bind creates a private shadow snapshot. + let handles = [rtv0, rtv1]; + note_render_targets(raw, 2, handles.as_ptr(), 0, &dsv0); + let split_clone = LISTS.lock().unwrap().as_ref().unwrap().get(&(raw as usize)).unwrap().bindings.clone(); + let rt_snap = split_clone.render_targets.as_ref().expect("render_targets recorded"); + assert!(rt_snap.shadow_has_rtvs && rt_snap.shadow_has_dsv); + let first_entry = rt_snap.shadow.as_ref().expect("shadow slot allocated").entry; + assert_ne!(first_entry.rtv_base, rtv0); + assert_ne!(first_entry.dsv_handle, dsv0); + + // Overwrite the guest RTV/DSV slots with different resources, then restore the split clone. + dev.CreateRenderTargetView(&rt_b, None, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: rtv0 }); + dev.CreateDepthStencilView(&ds_b, None, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dsv0 }); + restore_bindings(raw, &split_clone, D3D12_COMMAND_LIST_TYPE_DIRECT); + + // 2. While `split_clone` holds a reference (`strong_count == 2`), rebinding on `raw` + // must allocate a distinct shadow slot rather than overwriting `split_clone`'s snapshot. + note_render_targets(raw, 1, &rtv0, 1, std::ptr::null()); + let second_entry = LISTS + .lock() + .unwrap() + .as_ref() + .unwrap() + .get(&(raw as usize)) + .unwrap() + .bindings + .render_targets + .as_ref() + .and_then(|rt| rt.shadow.as_ref()) + .expect("second shadow slot allocated") + .entry; + assert_ne!(second_entry.rtv_base, first_entry.rtv_base, "shared split snapshot must not be clobbered"); + + // 3. Rebinding again with `strong_count == 1` reuses the same shadow slot in place. + note_render_targets(raw, 0, std::ptr::null(), 0, &dsv0); + let reused = LISTS + .lock() + .unwrap() + .as_ref() + .unwrap() + .get(&(raw as usize)) + .unwrap() + .bindings + .render_targets + .clone() + .expect("depth-only recorded"); + assert!(!reused.shadow_has_rtvs && reused.shadow_has_dsv); + assert_eq!(reused.shadow.as_ref().unwrap().entry, second_entry, "unshared shadow slot should be reused in place"); + drop(reused); + + // 4. Restoring and closing the PC command list succeeds cleanly, and dropping all + // references recycles every shadow slot back to the pool. + let b_depth = LISTS.lock().unwrap().as_ref().unwrap().get(&(raw as usize)).unwrap().bindings.clone(); + restore_bindings(raw, &b_depth, D3D12_COMMAND_LIST_TYPE_DIRECT); + drop(b_depth); + drop(split_clone); + on_release(raw as usize); + + let ext = *(raw as *const *const usize); + *(raw as *mut usize) = *ext.sub(1); + list.Close().unwrap(); + + let free_count = RT_SHADOW_POOLS + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&dev_key)) + .map_or(0, |p| p.free.len()); + assert_eq!(free_count, RT_SHADOW_CHUNK_SLOTS as usize, "all shadow slots must recycle on release"); + } + } + + #[test] + fn redundant_pso_bind_cache_skips_identical_and_invalidates_on_upgrade_or_reset() { + let list = 0x7E57_B1D0usize as *mut c_void; + unsafe { + on_create(list, 0xA110_0001, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + // First bind is never skipped. + assert!(!skip_redundant_pso_bind(list, 0x1000, 0x2000)); + on_set_pipeline_state_bound(list, 0x1000, 0x2000); + // Exact same (pso, resolved) is skipped. + assert!(skip_redundant_pso_bind(list, 0x1000, 0x2000)); + // Async compile completion: same title PSO resolves to a new real PC PSO -> must bind! + assert!(!skip_redundant_pso_bind(list, 0x1000, 0x3000)); + on_set_pipeline_state_bound(list, 0x1000, 0x3000); + assert!(skip_redundant_pso_bind(list, 0x1000, 0x3000)); + // bind_abi re-binding the resolved PC PSO directly also hits the cache. + assert!(skip_redundant_pso_bind(list, 0x3000, 0x3000)); + // Different title PSO -> must bind! + assert!(!skip_redundant_pso_bind(list, 0x1001, 0x3001)); + // ClearState / PC Reset / segment clear invalidate the cached PC PSO. + on_clear_state(list, 0x1000); + assert!(!skip_redundant_pso_bind(list, 0x1000, 0x3000)); + on_set_pipeline_state_bound(list, 0x1000, 0x3000); + on_pc_reset(list); + assert!(!skip_redundant_pso_bind(list, 0x1000, 0x3000)); + on_set_pipeline_state_bound(list, 0x1000, 0x3000); + clear_segment_state(list as usize); + assert!(!skip_redundant_pso_bind(list, 0x1000, 0x3000)); + on_release(list as usize); + } + } + + #[test] + fn redundant_render_targets_dedup_invalidates_on_descriptor_mutation_or_reset() { + let list = 0x7E57_B1D1usize as *mut c_void; + let rtvs = [0x4000usize, 0x4020]; + let dsv = 0x5000usize; + unsafe { + assert!(!skip_redundant_render_targets(list, 2, rtvs.as_ptr(), 0, &dsv)); + note_render_targets(list, 2, rtvs.as_ptr(), 0, &dsv); + // Identical bind with unchanged RTV/DSV descriptor generation is skipped. + assert!(skip_redundant_render_targets(list, 2, rtvs.as_ptr(), 0, &dsv)); + // Different DSV or count -> not skipped. + assert!(!skip_redundant_render_targets(list, 2, rtvs.as_ptr(), 0, std::ptr::null())); + assert!(!skip_redundant_render_targets(list, 1, rtvs.as_ptr(), 0, &dsv)); + // Overwriting any RTV/DSV CPU slot bumps RT_DESC_GEN -> must rebind! + bump_rt_desc_gen(); + assert!(!skip_redundant_render_targets(list, 2, rtvs.as_ptr(), 0, &dsv)); + note_render_targets(list, 2, rtvs.as_ptr(), 0, &dsv); + assert!(skip_redundant_render_targets(list, 2, rtvs.as_ptr(), 0, &dsv)); + // ClearState / PC Reset invalidate live render targets. + on_pc_reset(list); + assert!(!skip_redundant_render_targets(list, 2, rtvs.as_ptr(), 0, &dsv)); + on_release(list as usize); + } + } + + #[test] + fn bitset_runs_emit_exact_contiguous_page_ranges() { + let collect = |bits: &[u64], n: usize| { + let mut runs = Vec::new(); + for_each_bitset_run(bits, n, |a, b| runs.push((a, b))); + runs + }; + assert_eq!(collect(&[0, 0], 100), vec![]); + assert_eq!(collect(&[u64::MAX, u64::MAX], 130), vec![(0, 128)]); + assert_eq!(collect(&[u64::MAX, u64::MAX, 0b11], 130), vec![(0, 130)]); + // Word-boundary straddle (bits 62..66), single bit 0, and trailing bit clipped by `n`. + let w0 = (1u64 << 0) | (1u64 << 62) | (1u64 << 63); + let w1 = (1u64 << 0) | (1u64 << 1) | (1u64 << 5) | (1u64 << 10); + assert_eq!(collect(&[w0, w1], 70), vec![(0, 1), (62, 66), (69, 70)]); + } } diff --git a/crates/xcl/src/hle/d3d12x/memory_report.rs b/crates/xcl/src/hle/d3d12x/memory_report.rs new file mode 100644 index 0000000000..59cc96096f --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/memory_report.rs @@ -0,0 +1,318 @@ +//! Where XCL's memory goes: the parts it knows of, against what Windows and DXGI report (#2688, +//! workstream 1). One snapshot holds the process's commit, the adapter's local (video) and +//! non-local (system) memory in use against their budgets, and XCL's owners of each. What the +//! owners don't cover is shown as its own part: the title's own resources, the driver, and +//! whatever XCL doesn't count yet. + +/// Which memory a part takes. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Kind { + /// the adapter's own memory (DXGI local segment) + Video, + /// system memory the GPU reads (DXGI non-local segment: upload and readback heaps) + NonLocal, + /// the process's commit + Commit, +} + +/// One owner's bytes. +#[derive(Clone, Debug, PartialEq)] +pub struct Part { + pub owner: &'static str, + pub kind: Kind, + pub bytes: u64, +} + +/// What DXGI reports for one segment group. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Segment { + pub usage: u64, + pub budget: u64, +} + +#[derive(Clone, Debug, Default)] +pub struct Snapshot { + /// the process's committed bytes (`PrivateUsage`; None where it reads 0: Wine leaves it so) + pub commit: Option, + /// None: no device or DXGI did not answer + pub local: Option, + pub non_local: Option, + pub parts: Vec, +} + +impl Snapshot { + /// The bytes of the parts of `kind`. + pub fn counted(&self, kind: Kind) -> u64 { + self.parts.iter().filter(|p| p.kind == kind).map(|p| p.bytes).sum() + } + + /// What the total of `kind` holds besides the parts XCL counts (negative when the parts are + /// more than the total: a part counted on the wrong side, or memory not made yet). + pub fn other(&self, kind: Kind) -> Option { + let total = match kind { + Kind::Video => self.local?.usage, + Kind::NonLocal => self.non_local?.usage, + Kind::Commit => self.commit?, + }; + Some(total as i64 - self.counted(kind) as i64) + } + + /// One log line: each total, its budget, its parts and what is left (MB). + pub fn line(&self) -> String { + let mb = |b: u64| b >> 20; + let smb = |b: i64| b >> 20; + let parts = |kind: Kind| { + let mut s: Vec = self.parts.iter().filter(|p| p.kind == kind).map(|p| format!("{} {}", p.owner, mb(p.bytes))).collect(); + if let Some(o) = self.other(kind) { + s.push(format!("other {}", smb(o))); + } + s.join(", ") + }; + let segment = |name: &str, seg: Option, kind: Kind| match seg { + Some(g) => format!("{name} {} of a {} budget ({})", mb(g.usage), mb(g.budget), parts(kind)), + None => format!("{name} unknown ({})", parts(kind)), + }; + format!( + // (not "memory: N MB committed": the line `scripts/smoke.ps1` reads stays as it is) + "memory by owner (MB): commit {} ({}); {}; {}", + self.commit.map_or("unknown".into(), |c| mb(c).to_string()), + parts(Kind::Commit), + segment("video memory", self.local, Kind::Video), + segment("non-local", self.non_local, Kind::NonLocal) + ) + } +} + +/// The process's committed bytes, or None where `PrivateUsage` reads 0 (Wine leaves it so; #1097 +/// and #2362 read the commit there another way). +fn process_commit() -> Option { + unsafe { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; + 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); + Some(c.PrivateUsage as u64).filter(|&n| n != 0) + } +} + +/// What DXGI reports for the device's adapter: (local, non-local), or None without a device. +fn video_memory() -> Option<(Segment, Segment)> { + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D12::ID3D12Device; + use windows::Win32::Graphics::Dxgi::*; + let raw = super::real::device_raw(); + let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }?; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let adapter: IDXGIAdapter3 = factory.EnumAdapterByLuid(dev.GetAdapterLuid()).ok()?; + let query = |group| { + let mut i = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + adapter.QueryVideoMemoryInfo(0, group, &mut i).ok().map(|_| Segment { usage: i.CurrentUsage, budget: i.Budget }) + }; + Some((query(DXGI_MEMORY_SEGMENT_GROUP_LOCAL)?, query(DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)?)) + } +} + +/// The commit Windows charges for the process's D3D12 heaps: what DXGI counts in both segments, +/// less the coherent window D3D12 imported (`imported`: CPU memory, already committed as such); +/// 0 when unknown. +fn heap_charge(local: Option, non_local: Option, imported: u64) -> u64 { + match (local, non_local) { + (Some(l), Some(n)) => (l.usage + n.usage).saturating_sub(imported), + _ => 0, + } +} + +/// Where DXGI counts memory the GPU reads from system memory: the non-local segment, or on an +/// adapter with one segment (no non-local budget: an integrated GPU) the local one. +fn uma_segment(non_local: Option) -> Kind { + if non_local.is_some_and(|n| n.budget > 0) { + Kind::NonLocal + } else { + Kind::Video + } +} + +/// Now. +pub fn snapshot() -> Snapshot { + let (pages, page_pools) = super::vram::page_bytes(); + let (arenas, _) = super::vram::arena_bytes(); + let (pools, mapped) = super::sparse::pool_bytes(); + let (_, committed_textures) = super::title_textures::committed_bytes(); + let (local, non_local) = video_memory().map_or((None, None), |(l, n)| (Some(l), Some(n))); + let uma = crate::gpu::uma::get().map_or(0, |u| u.size() as u64); + // (what of it D3D12 has imported, which DXGI counts: none if the import failed) + let imported = super::real::uma_imported_bytes(); + let b = |n: usize| n as u64; + let parts = vec![ + // the title's memory in the coherent window: committed once, the GPU reads it there + Part { owner: "UMA window", kind: Kind::Commit, bytes: uma }, + // a title page in a sparse window is committed on the CPU as well as mapped to a tile + Part { owner: "sparse CPU copy", kind: Kind::Commit, bytes: b(super::sparse::committed_bytes()) }, + // Windows charges the process's D3D12 heaps to its commit as well, local and non-local + // alike (1 GiB heap: +1 GiB of commit, on an RTX 4070 Ti and an RDNA2 iGPU) – all DXGI + // counts but the coherent window, which is CPU memory imported and committed once + Part { owner: "D3D12 heaps", kind: Kind::Commit, bytes: heap_charge(local, non_local, imported) }, + // the console shaders pipelines not built yet keep (`real::intern_blob`) + Part { owner: "pipeline shader copies", kind: Kind::Commit, bytes: b(super::real::pipeline_blob_bytes().1) }, + Part { owner: "target pages", kind: Kind::Video, bytes: b(pages) }, + Part { owner: "target pools free", kind: Kind::Video, bytes: b(page_pools.saturating_sub(pages)) }, + Part { owner: "arenas", kind: Kind::Video, bytes: b(arenas) }, + Part { owner: "sparse tiles", kind: Kind::Video, bytes: b(mapped) }, + Part { owner: "sparse pools free", kind: Kind::Video, bytes: b(pools.saturating_sub(mapped)) }, + Part { owner: "sparse pools retired", kind: Kind::Video, bytes: b(super::sparse::retired_bytes()) }, + Part { owner: "committed textures", kind: Kind::Video, bytes: committed_textures }, + // the GPU reads the coherent window (imported, `OpenExistingHeapFromAddress`) as system + // memory: DXGI counts it in the non-local segment of a card (an RTX 4070 Ti and an + // RX 7800 XT), and in the local one of an integrated GPU, whose only segment that is + // (no non-local budget) + Part { owner: "UMA window", kind: uma_segment(non_local), bytes: imported }, + ]; + Snapshot { commit: process_commit(), local, non_local, parts } +} + +/// The process's address space, walked (`VirtualQuery`): its committed private memory outside +/// the unified-memory block by allocation, the largest ones, and the rest by size; mapped and +/// image memory. What `snapshot`'s "other" holds, for finding its owner (the title's heaps, the +/// driver's, XCL's). +pub fn walk_line() -> String { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_IMAGE, MEM_MAPPED, MEM_PRIVATE}; + let u = crate::gpu::uma::get(); + let t0 = std::time::Instant::now(); + let (mut uma, mut mapped, mut image, mut regions) = (0u64, 0u64, 0u64, 0usize); + let mut by_base: std::collections::HashMap = std::collections::HashMap::new(); + let mut at = 0x1_0000usize; + while at < 0x7FFF_FFFE_0000 { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + if unsafe { VirtualQuery(at as *const _, &mut m, std::mem::size_of_val(&m)) } == 0 { + break; + } + regions += 1; + let (base, size) = (m.BaseAddress as usize, m.RegionSize); + if m.State == MEM_COMMIT { + let n = size as u64; + if u.is_some_and(|u| u.contains(base)) { + uma += n; + } else if m.Type == MEM_PRIVATE { + let e = by_base.entry(m.AllocationBase as usize).or_insert((0, 0, m.Protect)); + e.0 += n; + e.1 += 1; + } else if m.Type == MEM_MAPPED { + mapped += n; + } else if m.Type == MEM_IMAGE { + image += n; + } + } + match base.checked_add(size) { + Some(next) if next > at => at = next, + _ => break, + } + } + let mut all: Vec<(usize, u64, u32, u32)> = by_base.into_iter().map(|(b, (n, r, p))| (b, n, r, p)).collect(); + all.sort_unstable_by(|a, b| b.1.cmp(&a.1)); + let private: u64 = all.iter().map(|a| a.1).sum(); + let mb = |b: u64| b >> 20; + let top: Vec = all.iter().take(8).map(|&(b, n, r, p)| format!("{b:#x} {} ({r} regions, protect {p:#x})", mb(n))).collect(); + // the rest by size: (< 1 MB, < 16 MB, < 256 MB, larger) → (allocations, MB) + let mut sizes = [(0usize, 0u64); 4]; + for &(_, n, _, _) in all.iter().skip(8) { + let k = match n { + n if n < 1 << 20 => 0, + n if n < 16 << 20 => 1, + n if n < 256 << 20 => 2, + _ => 3, + }; + sizes[k].0 += 1; + sizes[k].1 += n; + } + format!( + "memory walk (MB, {} regions, {} ms): unified memory {}; private elsewhere {} in {} allocations – largest {}; the rest under 1 MB {} in {}, under 16 MB {} in {}, under 256 MB {} in {}, larger {} in {}; mapped {}, images {}", + regions, + t0.elapsed().as_millis(), + mb(uma), + mb(private), + all.len(), + top.join(", "), + mb(sizes[0].1), + sizes[0].0, + mb(sizes[1].1), + sizes[1].0, + mb(sizes[2].1), + sizes[2].0, + mb(sizes[3].1), + sizes[3].0, + mb(mapped), + mb(image) + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The rest of each total is its total less its parts, a part is counted on its side only, + /// and the line shows every part, each total against its budget, and the rest. + #[test] + fn the_rest_is_the_total_less_the_parts() { + const M: u64 = 1 << 20; + let s = Snapshot { + commit: Some(10_000 * M), + local: Some(Segment { usage: 9_000 * M, budget: 11_000 * M }), + non_local: Some(Segment { usage: 300 * M, budget: 16_000 * M }), + parts: vec![ + Part { owner: "UMA window", kind: Kind::Commit, bytes: 4_096 * M }, + Part { owner: "target pages", kind: Kind::Video, bytes: 5_000 * M }, + Part { owner: "arenas", kind: Kind::Video, bytes: 1_000 * M }, + Part { owner: "upload staging", kind: Kind::NonLocal, bytes: 400 * M }, + ], + }; + assert_eq!(s.counted(Kind::Video), 6_000 * M); + assert_eq!(s.other(Kind::Video), Some((3_000 * M) as i64)); + assert_eq!(s.other(Kind::Commit), Some((5_904 * M) as i64)); + // more counted than DXGI reports: a negative rest, not a wrap + assert_eq!(s.other(Kind::NonLocal), Some(-((100 * M) as i64))); + assert_eq!( + s.line(), + "memory by owner (MB): commit 10000 (UMA window 4096, other 5904); video memory 9000 of a 11000 budget (target pages 5000, arenas 1000, other 3000); non-local 300 of a 16000 budget (upload staging 400, other -100)" + ); + // the coherent window: non-local on a card, local on a GPU of one segment + assert_eq!(uma_segment(Some(Segment { usage: 0, budget: 16_000 * M })), Kind::NonLocal); + assert_eq!(uma_segment(Some(Segment { usage: 0, budget: 0 })), Kind::Video); + assert_eq!(uma_segment(None), Kind::Video); + // the heaps' charge to the commit: both segments less the coherent window + let (l, n) = (Some(Segment { usage: 9_000 * M, budget: 1 }), Some(Segment { usage: 4_500 * M, budget: 1 })); + assert_eq!(heap_charge(l, n, 4_096 * M), 9_404 * M); + assert_eq!(heap_charge(l, None, 4_096 * M), 0); + assert_eq!(heap_charge(Some(Segment { usage: 100 * M, budget: 1 }), n, 8_000 * M), 0, "never below 0"); + // a window whose import failed is not in DXGI's usage: nothing of it is taken off + assert_eq!(heap_charge(Some(Segment { usage: 3_000 * M, budget: 1 }), Some(Segment { usage: 0, budget: 1 }), 0), 3_000 * M); + let unknown = Snapshot { commit: None, local: None, non_local: None, ..s }; + assert_eq!(unknown.other(Kind::Video), None); + // a commit that reads 0 (Wine) is unknown, not 0 with a negative rest + assert_eq!(unknown.other(Kind::Commit), None); + assert!(unknown.line().starts_with("memory by owner (MB): commit unknown (UMA window 4096)"), "{}", unknown.line()); + assert!(unknown.line().contains("video memory unknown (target pages 5000, arenas 1000)"), "{}", unknown.line()); + } + + /// On a device the snapshot has DXGI's totals with a budget, the process's commit, and every + /// owner. + #[test] + fn a_snapshot_on_the_device_has_its_budget_and_owners() { + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let s = snapshot(); + // (an integrated GPU has one segment: its non-local budget is 0) + assert!(s.non_local.is_some(), "{}", s.line()); + assert!(s.local.expect("local video memory").budget > 0, "{}", s.line()); + // (`PrivateUsage` reads 0 under Wine: the commit is unknown there, and the line says so) + match s.commit { + Some(c) => assert!(c > 0), + None => assert!(s.line().contains("commit unknown"), "{}", s.line()), + } + for owner in ["UMA window", "sparse CPU copy", "D3D12 heaps", "pipeline shader copies", "target pages", "target pools free", "arenas", "sparse tiles", "sparse pools free", "sparse pools retired", "committed textures"] { + assert!(s.parts.iter().any(|p| p.owner == owner), "{owner} missing: {}", s.line()); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 8886624632..ccc7c443dc 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -10,22 +10,35 @@ #![allow(non_snake_case)] mod alloc_pool; +mod ambient; pub mod bind; pub mod console_heap; pub mod console_list; +mod depth_uav; +pub mod culprit; pub mod device_x; pub mod dxgi_device; mod cpu_writes; pub mod dred; +pub mod driver_crash; mod fence_x; +mod format_alias; pub mod frame; +pub mod flight; +pub(crate) mod gfx_records; +pub(crate) mod gpu_awake; pub mod guard; mod late_release; pub mod layout; pub mod list_x; +pub mod memory_report; pub mod null; +pub(crate) mod pcores; +mod place_times; pub mod present; +pub mod prof; pub mod pso_async; +pub mod pso_library; pub mod real; mod shader_cache_session; pub mod sparse; @@ -33,6 +46,7 @@ mod standin; pub mod title_list; pub mod title_textures; pub mod vram; +mod vram_small; use std::ffi::c_void; use std::sync::OnceLock; @@ -134,46 +148,31 @@ pub unsafe extern "system" fn D3D12GetDebugInterface(riid: *const c_void, ppv: * forward!("D3D12GetDebugInterface", unsafe extern "system" fn(*const c_void, *mut *mut c_void) -> HRESULT, null::D3D12GetDebugInterface, (riid, ppv)) } -pub unsafe extern "system" fn D3D12SerializeRootSignature(d: *const c_void, v: u32, blob: *mut *mut c_void, err: *mut *mut c_void) -> HRESULT { - forward!( - "D3D12SerializeRootSignature", - unsafe extern "system" fn(*const c_void, u32, *mut *mut c_void, *mut *mut c_void) -> HRESULT, - null::D3D12SerializeRootSignature, - (d, v, blob, err) - ) -} +// console-only root signature flags (seen: 0x3000000 from XboxBvhBuilder.dll) – Windows +// rejects unknown bits; flags sit at +32 in 40-byte 1.0 desc and +40 in 48-byte versioned desc +const PC_FLAGS: u32 = 0xFFF; -pub unsafe extern "system" fn D3D12SerializeVersionedRootSignature(d: *const c_void, blob: *mut *mut c_void, err: *mut *mut c_void) -> HRESULT { +unsafe fn serialize_root_sig( + name: &str, d: *const c_void, flags_off: usize, err: *mut *mut c_void, + meta: impl FnOnce(*const u8) -> (u32, u32, u32, u32), + call: impl FnOnce(*const c_void, *mut *mut c_void) -> HRESULT, +) -> HRESULT { let mut own_err: *mut c_void = std::ptr::null_mut(); - let e = if err.is_null() { &mut own_err as *mut _ } else { err }; - // console-only root signature flags (seen: 0x3000000 from XboxBvhBuilder.dll) – Windows - // rejects unknown bits; the flags sit at +40 in every version of the desc (48 bytes) - const PC_FLAGS: u32 = 0xFFF; - let mut copy = [0u8; 48]; + let e = if err.is_null() { &mut own_err as *mut _ } else { *err = std::ptr::null_mut(); err }; + let mut copy = [0u64; QWORDS]; let mut d = d; - if !d.is_null() && *(d as *const u8).add(40).cast::() & !PC_FLAGS != 0 { - std::ptr::copy_nonoverlapping(d as *const u8, copy.as_mut_ptr(), 48); - let f = copy.as_mut_ptr().add(40).cast::(); - crate::xlog_info!("D3D12SerializeVersionedRootSignature: console flags {:#x} dropped", *f & !PC_FLAGS); + if !d.is_null() && (d as *const u8).add(flags_off).cast::().read_unaligned() & !PC_FLAGS != 0 { + let dst = copy.as_mut_ptr().cast::(); + std::ptr::copy_nonoverlapping(d.cast::(), dst, QWORDS * 8); + let f = dst.add(flags_off).cast::(); + crate::xlog_info!("{name}: console flags {:#x} dropped", *f & !PC_FLAGS); *f &= PC_FLAGS; - d = copy.as_ptr() as *const c_void; + d = dst.cast::(); } - type Serialize = unsafe extern "system" fn(*const c_void, *mut *mut c_void, *mut *mut c_void) -> HRESULT; - let hr = match sys("D3D12SerializeVersionedRootSignature").filter(|_| backend() == Backend::Real) { - Some(f) => std::mem::transmute::<_, Serialize>(f)(d, blob, e), - None => null::D3D12SerializeVersionedRootSignature(d, blob, e), - }; + let hr = call(d, e); if hr < 0 && !d.is_null() { - // D3D12_VERSIONED_ROOT_SIGNATURE_DESC: version, then (1.1 / 1.2) parameters, samplers, flags - let w = |o: usize| *(d as *const u8).add(o).cast::(); - let text = blob_text(*e); - crate::xlog_warn!( - "D3D12SerializeVersionedRootSignature: {hr:#x} (version {}, parameters {}, samplers {}, flags {:#x}): {text}", - w(0), - w(8), - w(24), - w(40) - ); + let (ver, params, samplers, flags) = meta(d.cast::()); + crate::xlog_warn!("{name}: {hr:#x} (version {ver}, parameters {params}, samplers {samplers}, flags {flags:#x}): {}", blob_text(*e)); } if err.is_null() && !own_err.is_null() { blob_release(own_err); @@ -181,6 +180,26 @@ pub unsafe extern "system" fn D3D12SerializeVersionedRootSignature(d: *const c_v hr } +pub unsafe extern "system" fn D3D12SerializeRootSignature(d: *const c_void, v: u32, blob: *mut *mut c_void, err: *mut *mut c_void) -> HRESULT { + type Serialize = unsafe extern "system" fn(*const c_void, u32, *mut *mut c_void, *mut *mut c_void) -> HRESULT; + serialize_root_sig::<5>("D3D12SerializeRootSignature", d, 32, err, |p| (v, p.cast::().read_unaligned(), p.add(16).cast::().read_unaligned(), p.add(32).cast::().read_unaligned()), |d, e| { + match sys("D3D12SerializeRootSignature").filter(|_| backend() == Backend::Real) { + Some(f) => std::mem::transmute::<_, Serialize>(f)(d, v, blob, e), + None => null::D3D12SerializeRootSignature(d, v, blob, e), + } + }) +} + +pub unsafe extern "system" fn D3D12SerializeVersionedRootSignature(d: *const c_void, blob: *mut *mut c_void, err: *mut *mut c_void) -> HRESULT { + type Serialize = unsafe extern "system" fn(*const c_void, *mut *mut c_void, *mut *mut c_void) -> HRESULT; + serialize_root_sig::<6>("D3D12SerializeVersionedRootSignature", d, 40, err, |p| (p.cast::().read_unaligned(), p.add(8).cast::().read_unaligned(), p.add(24).cast::().read_unaligned(), p.add(40).cast::().read_unaligned()), |d, e| { + match sys("D3D12SerializeVersionedRootSignature").filter(|_| backend() == Backend::Real) { + Some(f) => std::mem::transmute::<_, Serialize>(f)(d, blob, e), + None => null::D3D12SerializeVersionedRootSignature(d, blob, e), + } + }) +} + /// text of an ID3DBlob (error messages) unsafe fn blob_text(b: *mut c_void) -> String { if b.is_null() { @@ -252,3 +271,49 @@ pub unsafe extern "system" fn D3D12ConfigureVirtualMemoryX(config: *const c_void } S_OK } + +#[cfg(test)] +mod tests { + use super::*; + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_ROOT_SIGNATURE_DESC, D3D12_ROOT_SIGNATURE_FLAGS, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, + D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS, D3D12_VERSIONED_ROOT_SIGNATURE_DESC, + D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0, D3D_ROOT_SIGNATURE_VERSION_1_0, ID3D12RootSignatureDeserializer, + }; + + #[test] + fn serialize_root_signature_strips_console_flags_and_preserves_pc_flags() { + assert_eq!((std::mem::size_of::(), std::mem::offset_of!(D3D12_ROOT_SIGNATURE_DESC, Flags)), (40, 32)); + assert_eq!((std::mem::size_of::(), std::mem::offset_of!(D3D12_VERSIONED_ROOT_SIGNATURE_DESC, Anonymous) + std::mem::offset_of!(D3D12_ROOT_SIGNATURE_DESC, Flags)), (48, 40)); + unsafe { + let deser_flags = |blob_raw: *mut c_void| -> D3D12_ROOT_SIGNATURE_FLAGS { + let blob = ID3DBlob::from_raw(blob_raw); + let mut deser_raw = std::ptr::null_mut(); + assert_eq!(D3D12CreateRootSignatureDeserializer(blob.GetBufferPointer(), blob.GetBufferSize(), (&ID3D12RootSignatureDeserializer::IID as *const windows::core::GUID).cast(), &mut deser_raw), S_OK); + (*ID3D12RootSignatureDeserializer::from_raw(deser_raw).GetRootSignatureDesc()).Flags + }; + let pc_flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS; + let raw_flags = D3D12_ROOT_SIGNATURE_FLAGS(pc_flags.0 | 0x0300_0000); + let desc = D3D12_ROOT_SIGNATURE_DESC { Flags: raw_flags, ..Default::default() }; + let (mut blob_raw, mut vblob_raw) = (std::ptr::null_mut(), std::ptr::null_mut()); + assert_eq!(D3D12SerializeRootSignature(&desc as *const _ as *const c_void, D3D_ROOT_SIGNATURE_VERSION_1_0.0 as u32, &mut blob_raw, std::ptr::null_mut()), S_OK); + assert_eq!(desc.Flags, raw_flags, "caller descriptor must not be mutated"); + assert_eq!(deser_flags(blob_raw), pc_flags); + + let vdesc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { Version: D3D_ROOT_SIGNATURE_VERSION_1_0, Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { Desc_1_0: desc } }; + assert_eq!(D3D12SerializeVersionedRootSignature(&vdesc as *const _ as *const c_void, &mut vblob_raw, std::ptr::null_mut()), S_OK); + assert_eq!(deser_flags(vblob_raw), pc_flags); + + let (mut out, mut err_out) = (std::ptr::null_mut(), 1usize as *mut c_void); + assert!(D3D12SerializeRootSignature(&desc as *const _ as *const c_void, 99, &mut out, std::ptr::null_mut()) < 0); + assert!(D3D12SerializeRootSignature(&desc as *const _ as *const c_void, 99, &mut out, &mut err_out) < 0); + assert!(blob_text(err_out).contains("version"), "caller error blob missing diagnostic"); + blob_release(err_out); + err_out = 1usize as *mut c_void; + assert!(D3D12SerializeRootSignature(std::ptr::null(), D3D_ROOT_SIGNATURE_VERSION_1_0.0 as u32, &mut out, &mut err_out) < 0); + assert!(err_out.is_null()); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/pcores.rs b/crates/xcl/src/hle/d3d12x/pcores.rs new file mode 100644 index 0000000000..802db928af --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/pcores.rs @@ -0,0 +1,270 @@ +//! Hybrid CPU P-core pinning (`XCL_FAST_CORES`). +//! +//! On hybrid CPUs (such as Intel 12th/13th/14th-gen processors with both Performance and Efficiency +//! cores), Windows can schedule latency-sensitive render/submit threads onto slower E-cores, +//! introducing frame-time spikes and delaying GPU submissions. This module queries +//! `GetSystemCpuSetInformation` dynamically from `kernel32.dll`, selects the Group 0 CPU set IDs +//! belonging to the highest `EfficiencyClass` when at least two distinct efficiency classes exist +//! (automatically a no-op on homogeneous CPUs such as AMD Ryzen), and pins calling threads via +//! `SetThreadSelectedCpuSets`. +//! +//! Controlled by `XCL_FAST_CORES`: `0` / `off` / `false` disables; default enabled on hybrid CPUs. + +use std::cell::Cell; +use std::ffi::c_void; +use std::sync::{Once, OnceLock}; + +/// `CPU_SET_INFORMATION_TYPE::CpuSetInformation` in `winnt.h`. +const CPU_SET_INFORMATION_TYPE_CPU_SET: u32 = 0; +/// Minimum byte size of a valid `SYSTEM_CPU_SET_INFORMATION` header + `CpuSet` fields through +/// `EfficiencyClass` and `AllFlags` / `Reserved` (`offset 0..24`). +const MIN_CPU_SET_ENTRY_SIZE: usize = 24; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct CpuSetEntry { + id: u32, + group: u16, + efficiency_class: u8, +} + +fn parse_enabled(val: Option<&str>) -> bool { + let Some(raw) = val.map(str::trim).filter(|s| !s.is_empty()) else { + return true; + }; + !(raw.eq_ignore_ascii_case("0") || raw.eq_ignore_ascii_case("off") || raw.eq_ignore_ascii_case("false")) +} + +fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| parse_enabled(std::env::var("XCL_FAST_CORES").ok().as_deref())) +} + +/// Parse a raw `GetSystemCpuSetInformation` buffer into `CpuSetEntry` records. +/// +/// Layout of `SYSTEM_CPU_SET_INFORMATION` (`winnt.h`): +/// - `+0`: `DWORD Size` +/// - `+4`: `DWORD Type` (`0` = `CpuSetInformation`) +/// - `+8`: `DWORD Id` +/// - `+12`: `WORD Group` +/// - `+14..18`: `LogicalProcessorIndex`, `CoreIndex`, `LastLevelCacheIndex`, `NumaNodeIndex` +/// - `+18`: `BYTE EfficiencyClass` +fn parse_cpu_set_buffer(buf: &[u8]) -> Vec { + let mut entries = Vec::new(); + let mut offset = 0usize; + while offset + MIN_CPU_SET_ENTRY_SIZE <= buf.len() { + let size = u32::from_le_bytes(buf[offset..offset + 4].try_into().unwrap()) as usize; + if size < MIN_CPU_SET_ENTRY_SIZE || offset + size > buf.len() { + break; + } + let kind = u32::from_le_bytes(buf[offset + 4..offset + 8].try_into().unwrap()); + if kind == CPU_SET_INFORMATION_TYPE_CPU_SET { + let id = u32::from_le_bytes(buf[offset + 8..offset + 12].try_into().unwrap()); + let group = u16::from_le_bytes(buf[offset + 12..offset + 14].try_into().unwrap()); + let efficiency_class = buf[offset + 18]; + entries.push(CpuSetEntry { id, group, efficiency_class }); + } + offset += size; + } + entries +} + +/// Select Group 0 CPU set IDs with the highest `EfficiencyClass`, returning an empty `Vec` unless +/// Group 0 contains at least two distinct efficiency classes (auto-no-op on homogeneous CPUs). +fn select_fast_cpu_sets(entries: &[CpuSetEntry]) -> Vec { + let mut min_eff = u8::MAX; + let mut max_eff = u8::MIN; + let mut any_group0 = false; + for e in entries { + if e.group != 0 { + continue; + } + any_group0 = true; + min_eff = min_eff.min(e.efficiency_class); + max_eff = max_eff.max(e.efficiency_class); + } + if !any_group0 || min_eff == max_eff { + return Vec::new(); + } + entries + .iter() + .filter(|e| e.group == 0 && e.efficiency_class == max_eff) + .map(|e| e.id) + .collect() +} + +type GetSystemCpuSetInformationFn = unsafe extern "system" fn( + information: *mut u8, + buffer_length: u32, + returned_length: *mut u32, + process: *mut c_void, + flags: u32, +) -> i32; + +type SetThreadSelectedCpuSetsFn = unsafe extern "system" fn( + thread: *mut c_void, + cpu_set_ids: *const u32, + cpu_set_id_count: u32, +) -> i32; + +unsafe fn kernel32_proc(name: &[u8]) -> Option<*const c_void> { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + let h = GetModuleHandleA(b"kernel32.dll\0".as_ptr()); + if h.is_null() { + return None; + } + GetProcAddress(h, name.as_ptr()).map(|f| f as *const c_void) +} + +fn query_fast_cpu_sets() -> Vec { + if !enabled() { + return Vec::new(); + } + unsafe { + let Some(p) = kernel32_proc(b"GetSystemCpuSetInformation\0") else { + return Vec::new(); + }; + let get_info: GetSystemCpuSetInformationFn = std::mem::transmute(p); + let mut needed: u32 = 0; + let _ = get_info(std::ptr::null_mut(), 0, &mut needed, std::ptr::null_mut(), 0); + if needed < MIN_CPU_SET_ENTRY_SIZE as u32 { + return Vec::new(); + } + let mut buf = vec![0u8; needed as usize]; + let mut returned: u32 = 0; + if get_info(buf.as_mut_ptr(), buf.len() as u32, &mut returned, std::ptr::null_mut(), 0) == 0 { + return Vec::new(); + } + let len = (returned as usize).min(buf.len()); + select_fast_cpu_sets(&parse_cpu_set_buffer(&buf[..len])) + } +} + +fn fast_cpu_sets() -> &'static [u32] { + static IDS: OnceLock> = OnceLock::new(); + IDS.get_or_init(query_fast_cpu_sets) +} + +fn set_thread_cpu_sets_fn() -> Option { + static FN: OnceLock> = OnceLock::new(); + *FN.get_or_init(|| unsafe { + kernel32_proc(b"SetThreadSelectedCpuSets\0").map(|p| std::mem::transmute(p)) + }) +} + +thread_local! { + static THREAD_PINNED: Cell = const { Cell::new(false) }; +} + +/// Pin the calling thread to Group 0 P-core CPU sets on hybrid CPUs. +/// +/// Idempotent and cached per thread via `thread_local!`; no-op on homogeneous CPUs or when +/// `XCL_FAST_CORES=0`. +pub(super) fn pin_current_thread_fast() { + if THREAD_PINNED.with(|p| p.replace(true)) { + return; + } + let ids = fast_cpu_sets(); + if ids.is_empty() { + return; + } + let Some(set_fn) = set_thread_cpu_sets_fn() else { + return; + }; + let ok = unsafe { + let thread = windows_sys::Win32::System::Threading::GetCurrentThread(); + set_fn(thread, ids.as_ptr(), ids.len() as u32) != 0 + }; + if ok { + static LOGGED: Once = Once::new(); + LOGGED.call_once(|| { + crate::xlog_info!( + "D3D12.X: pinned latency-sensitive thread(s) to {} P-core logical CPUs (XCL_FAST_CORES=0 to disable)", + ids.len() + ); + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn env_parsing_enables_by_default_and_disables_on_zero_or_off() { + assert!(parse_enabled(None)); + assert!(parse_enabled(Some(""))); + assert!(parse_enabled(Some("1"))); + assert!(parse_enabled(Some("on"))); + assert!(parse_enabled(Some("true"))); + assert!(!parse_enabled(Some("0"))); + assert!(!parse_enabled(Some(" 0 "))); + assert!(!parse_enabled(Some("off"))); + assert!(!parse_enabled(Some("OFF"))); + assert!(!parse_enabled(Some("false"))); + } + + #[test] + fn heterogeneous_cpu_selects_highest_efficiency_group0_only() { + // Simulates Intel i5-13600KF (12 P-core threads @ eff 1, 8 E-core threads @ eff 0) + // plus a Group 1 entry with higher eff to verify Group 0 filtering. + let mut entries = Vec::new(); + for id in 0x100u32..0x10C { + entries.push(CpuSetEntry { id, group: 0, efficiency_class: 1 }); + } + for id in 0x10Cu32..0x114 { + entries.push(CpuSetEntry { id, group: 0, efficiency_class: 0 }); + } + entries.push(CpuSetEntry { id: 0x200, group: 1, efficiency_class: 2 }); + + let selected = select_fast_cpu_sets(&entries); + let expected: Vec = (0x100u32..0x10C).collect(); + assert_eq!(selected, expected); + } + + #[test] + fn homogeneous_cpu_is_noop() { + // Homogeneous Ryzen: all logical CPUs report the same EfficiencyClass (0). + let ryzen: Vec = (0..16) + .map(|i| CpuSetEntry { id: 256 + i, group: 0, efficiency_class: 0 }) + .collect(); + assert!(select_fast_cpu_sets(&ryzen).is_empty()); + + // Homogeneous all-1 efficiency class is also a no-op. + let uniform_one: Vec = (0..8) + .map(|i| CpuSetEntry { id: 256 + i, group: 0, efficiency_class: 1 }) + .collect(); + assert!(select_fast_cpu_sets(&uniform_one).is_empty()); + + // Empty list is a no-op. + assert!(select_fast_cpu_sets(&[]).is_empty()); + } + + #[test] + fn raw_buffer_parser_handles_variable_record_sizes_and_other_types() { + let mut buf = Vec::new(); + let push_rec = |buf: &mut Vec, size: usize, kind: u32, id: u32, group: u16, eff: u8| { + let start = buf.len(); + buf.resize(start + size, 0); + buf[start..start + 4].copy_from_slice(&(size as u32).to_le_bytes()); + buf[start + 4..start + 8].copy_from_slice(&kind.to_le_bytes()); + buf[start + 8..start + 12].copy_from_slice(&id.to_le_bytes()); + buf[start + 12..start + 14].copy_from_slice(&group.to_le_bytes()); + buf[start + 18] = eff; + }; + push_rec(&mut buf, 32, CPU_SET_INFORMATION_TYPE_CPU_SET, 0x100, 0, 1); + push_rec(&mut buf, 40, 99, 0x999, 0, 5); // non-CpuSetInformation record skipped + push_rec(&mut buf, 32, CPU_SET_INFORMATION_TYPE_CPU_SET, 0x101, 0, 0); + // Trailing truncated bytes must stop cleanly without panic. + buf.extend_from_slice(&[0u8; 8]); + + let parsed = parse_cpu_set_buffer(&buf); + assert_eq!( + parsed, + vec![ + CpuSetEntry { id: 0x100, group: 0, efficiency_class: 1 }, + CpuSetEntry { id: 0x101, group: 0, efficiency_class: 0 }, + ] + ); + assert_eq!(select_fast_cpu_sets(&parsed), vec![0x100]); + } +} diff --git a/crates/xcl/src/hle/d3d12x/place_times.rs b/crates/xcl/src/hle/d3d12x/place_times.rs new file mode 100644 index 0000000000..c005f4dd1b --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/place_times.rs @@ -0,0 +1,114 @@ +//! `XCL_PLACE_TIMES=1`: where the time of the title's texture placements goes +//! (`CreatePlacedResourceX` → `vram::place_pages`), logged every 4096 of them. Off: one load each. + +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::OnceLock; +use std::time::Instant; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Step { + /// the whole call, for a texture + Total, + /// the PC description, the alias note, the console's texture layout + Desc, + /// the CPU view of a GPU-view address (`canonical_va`) + Va, + /// waiting for the page table's lock, twice a placement + Lock, + /// `CreateReservedResource` + Reserved, + /// `GetResourceTiling` + Tiling, + /// pages gone idle, under the lock + Sweep, + /// `CreateHeap` of a pool heap, under the lock + Heap, + /// `UpdateTileMappings`, under the lock + Map, + /// the fence signal after them, under the lock + Signal, + /// `title_textures::register` + Register, +} + +const STEPS: [Step; 11] = [ + Step::Total, + Step::Desc, + Step::Va, + Step::Lock, + Step::Reserved, + Step::Tiling, + Step::Sweep, + Step::Heap, + Step::Map, + Step::Signal, + Step::Register, +]; +const EVERY: u64 = 4096; + +struct Sum { + calls: AtomicU64, + ns: AtomicU64, + max: AtomicU64, +} + +static SUMS: [Sum; STEPS.len()] = [const { Sum { calls: AtomicU64::new(0), ns: AtomicU64::new(0), max: AtomicU64::new(0) } }; STEPS.len()]; + +fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PLACE_TIMES").is_ok_and(|v| v.trim() == "1")) +} + +/// Times a step until dropped. +pub(super) struct Timer(Option<(Step, Instant)>); + +pub(super) fn step(step: Step) -> Timer { + Timer(on().then(|| (step, Instant::now()))) +} + +impl Drop for Timer { + fn drop(&mut self) { + let Some((step, since)) = self.0.take() else { return }; + let calls = add(step, since.elapsed().as_nanos() as u64); + if step == Step::Total && calls % EVERY == 0 { + crate::xlog_info!("D3D12.X: texture placements: {}", text()); + } + } +} + +/// How many times `step` has been counted, this one included. +fn add(step: Step, ns: u64) -> u64 { + let s = &SUMS[step as usize]; + s.ns.fetch_add(ns, Relaxed); + s.max.fetch_max(ns, Relaxed); + s.calls.fetch_add(1, Relaxed) + 1 +} + +fn text() -> String { + STEPS + .iter() + .map(|&s| { + let v = &SUMS[s as usize]; + let (calls, ns, max) = (v.calls.load(Relaxed), v.ns.load(Relaxed), v.max.load(Relaxed)); + format!("{s:?} {calls}x {} ms (max {:.1})", ns / 1_000_000, max as f64 / 1e6) + }) + .collect::>() + .join(", ") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_line_names_every_step_with_its_count_sum_and_longest() { + for (i, s) in STEPS.iter().enumerate() { + assert_eq!(*s as usize, i, "{s:?} has its own sum"); + } + assert_eq!(add(Step::Heap, 2_000_000), 1); + assert_eq!(add(Step::Heap, 5_500_000), 2); + let t = text(); + assert!(t.contains("Heap 2x 7 ms (max 5.5)"), "{t}"); + assert!(t.starts_with("Total 0x 0 ms"), "{t}"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d47e67841e..51c6f5949c 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -52,6 +52,7 @@ static PRESENTX_LOCK: Mutex<()> = Mutex::new(()); /// command queue #30 PresentX(planeCount, planes, parameters): plane 0's first resource is /// the frame; S_OK always (a console present does not fail for the title). pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, planes: *const u8, _params: *const u8) -> i32 { + let _prof = super::prof::span(super::prof::Kind::Present); if plane_count == 0 || planes.is_null() || !crate::gpu::shader::readable(planes as usize, 0x18) { return 0; } @@ -113,6 +114,11 @@ fn source_uv_rect(rect: Option<[i32; 4]>, w: u32, h: u32) -> [f32; 4] { [0.0, 0.0, 1.0, 1.0] } +unsafe fn raw_plane_words(plane_count: u32, planes: *const u8) -> Vec { + let n = (PLANE_STRIDE / 8) * (plane_count as usize).min(MAX_PLANES); + if crate::gpu::shader::readable(planes as usize, 8 * n) { (0..n).map(|k| (planes as *const u64).add(k).read_unaligned()).collect() } else { Vec::new() } +} + unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u8) { let frames = BOUNDARIES.fetch_add(1, Ordering::Relaxed) + 1; if frames % 300 == 0 { @@ -124,6 +130,8 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u } } super::real::stop_if_device_removed(); + super::alloc_pool::release_finished(); + crate::gpu::texture::trim_idle_staging(frames, super::vram::commit_low()); if !PRESENTX.swap(true, Ordering::Relaxed) { crate::xlog_info!("D3D12.X: PresentX – the title presents its own frames ({plane_count} plane(s))"); } @@ -132,8 +140,7 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u // plane over the game's): logged with the planes' raw words static LAST: AtomicU64 = AtomicU64::new(1); if LAST.swap(plane_count as u64, Ordering::Relaxed) != plane_count as u64 { - let n = (PLANE_STRIDE / 8) * plane_count as usize; - let words: Vec = if crate::gpu::shader::readable(planes as usize, 8 * n) { (0..n).map(|k| (planes as *const u64).add(k).read_unaligned()).collect() } else { Vec::new() }; + let words = raw_plane_words(plane_count, planes); crate::xlog_info!("D3D12.X: PresentX now with {plane_count} plane(s): {words:x?}"); } } @@ -206,7 +213,7 @@ unsafe fn release(p: usize) { } pub unsafe fn note_rtv(handle: usize, res: *mut c_void) { - if !enabled() { + if !enabled() || IN_PRESENT.with(|c| c.get()) { return; } let mut g = RTVS.lock().unwrap(); @@ -247,6 +254,15 @@ pub fn is_presented(res: usize) -> bool { PRESENTED.lock().unwrap().contains(&res) } +/// Look up the resource behind RTV `handle` and retain a COM reference while holding `RTVS`, +/// preventing a concurrent `note_rtv` overwrite/removal from freeing it before use. +unsafe fn retain_rtv_resource(handle: usize) -> Option { + let g = RTVS.lock().unwrap(); + let res = g.as_ref()?.get(&handle).copied()?; + add_ref(res); + Some(res) +} + /// the resource an RTV handle names (render-target binds) pub fn rtv_resource(handle: usize) -> Option { RTVS.lock().unwrap().as_ref()?.get(&handle).copied() @@ -259,7 +275,7 @@ pub fn rt0_resource(list: usize) -> Option { } pub fn note_rt0(list: usize, handle: usize) { - if !enabled() { + if !enabled() || IN_PRESENT.with(|c| c.get()) { return; } LISTS.lock().unwrap().get_or_insert_with(HashMap::new).insert(list, handle); @@ -306,6 +322,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)) { @@ -323,19 +340,21 @@ pub unsafe fn note_execute(queue: *mut c_void, lists: &[*mut c_void]) { lists.iter().rev().find_map(|l| m.get(&(*l as usize)).copied()) }; let Some(h) = handle else { return }; - let res = RTVS.lock().unwrap().as_ref().and_then(|m| m.get(&h).copied()); - let Some(res) = res else { return }; + let Some(res) = retain_rtv_resource(h) else { return }; if backbuffer_like(res).is_none() { + release(res); return; } - { + let to_release = { let mut c = CANDIDATE.lock().unwrap(); if c.map(|(_, r)| r) != Some(res) { - add_ref(res); - if let Some((_, old)) = c.replace((queue as usize, res)) { - release(old); - } + c.replace((queue as usize, res)).map(|(_, old)| old) + } else { + Some(res) } + }; + if let Some(old) = to_release { + release(old); } // no console present call seen recently → present on submissions (rate limited) if now_ms().saturating_sub(LAST_BOUNDARY_MS.load(Ordering::Relaxed)) > 500 { @@ -357,7 +376,10 @@ pub fn on_queue_console_method(_info: &StubInfo, _caller: usize) { // window // --------------------------------------------------------------------------------------- +pub(crate) mod preparation; + unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { + if let Some(result) = preparation::on_message(hwnd, msg, wp) { return result; } // keyboard and mouse as the gamepad: raw mouse input, the cursor held in the window if crate::hle::kbm::on_message(hwnd.0, msg, wp.0, lp.0) { return LRESULT(0); @@ -365,6 +387,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); @@ -499,10 +522,10 @@ fn window_thread() { crate::xlog_error!("could not create the XCL window"); return; }; - HWND_RAW.store(hwnd.0 as isize, Ordering::Release); crate::xlog_info!("XCL window created ({}x{})", cfg.window_width, cfg.window_height); - crate::hle::kbm::attach(hwnd.0); + if !preparation::active() { crate::hle::kbm::attach(hwnd.0); } SetTimer(Some(hwnd), COMPILE_TIMER, 500, None); + HWND_RAW.store(hwnd.0 as isize, Ordering::Release); let mut msg = MSG::default(); while GetMessageW(&mut msg, None, 0, 0).as_bool() { let _ = TranslateMessage(&msg); @@ -819,7 +842,9 @@ impl Compositor { } else { rt.BlendEnable = false.into(); } - dev.CreateGraphicsPipelineState(&pd).ok() + let pso = dev.CreateGraphicsPipelineState(&pd).ok(); + let _ = ManuallyDrop::into_inner(pd.pRootSignature); + pso }; let pair = (make_pso(false)?, make_pso(true)?); self.psos.insert(fmt.0, pair.clone()); @@ -837,6 +862,16 @@ impl Compositor { planes: &[(ID3D12Resource, D3D12_RESOURCE_DESC, [f32; 4])], slot: usize, ) -> bool { + let active = &planes[..planes.len().min(MAX_PLANES)]; + let plane_ok = |d: &D3D12_RESOURCE_DESC| { + d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && d.SampleDesc.Count == 1 + && !d.Flags.contains(D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) + && swap_format(d.Format).is_some() + }; + if dst_w == 0 || dst_h == 0 || active.is_empty() || !active.iter().all(|(_, d, _)| plane_ok(d)) { + return false; + } let first = slot % PRESENT_SLOTS * MAX_PLANES; let Some((opaque_pso, blend_pso)) = self.psos_for(dev, dst_fmt) else { return false }; let rtv_cpu = self.rtv_heap.GetCPUDescriptorHandleForHeapStart(); @@ -847,7 +882,7 @@ impl Compositor { }; dev.CreateRenderTargetView(dst, Some(&rtv_desc), rtv_cpu); let srv_cpu_base = self.srv_heap.GetCPUDescriptorHandleForHeapStart(); - for (i, (res, desc, _)) in planes.iter().take(MAX_PLANES).enumerate() { + for (i, (res, desc, _)) in active.iter().enumerate() { let mut srv_cpu = srv_cpu_base; srv_cpu.ptr += (first + i) * self.srv_inc as usize; let mut srv_desc = D3D12_SHADER_RESOURCE_VIEW_DESC { @@ -873,7 +908,7 @@ impl Compositor { list.SetDescriptorHeaps(&[Some(self.srv_heap.clone())]); list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); let srv_gpu_base = self.srv_heap.GetGPUDescriptorHandleForHeapStart(); - for (i, (_, _, uv_rect)) in planes.iter().take(MAX_PLANES).enumerate() { + for (i, (_, _, uv_rect)) in active.iter().enumerate() { list.SetPipelineState(if i == 0 { &opaque_pso } else { &blend_pso }); list.SetGraphicsRoot32BitConstants(0, 4, uv_rect.as_ptr() as *const c_void, 0); let mut gpu = srv_gpu_base; @@ -1005,6 +1040,7 @@ unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: D p.h = h; p.fmt = fmt; crate::xlog_info!("present: swap chain {w}x{h} {:?} – the game image will appear in the XCL window", fmt); + crate::xlog_info!("present: swap chain window {:#x}", hwnd.0 as usize); p.sc.is_some() } Err(e) => { @@ -1014,6 +1050,10 @@ unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: D } } +fn needs_compositor(planes: &[(ID3D12Resource, D3D12_RESOURCE_DESC, [f32; 4])]) -> bool { + planes.len() > 1 || planes.first().is_some_and(|(_, _, uv)| *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; @@ -1100,7 +1140,7 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, let due = frame_dump_due(); let mut dumps = Vec::new(); let mut composited = false; - if resolved.len() > 1 { + if needs_compositor(&resolved) { if p.compositor.is_none() { p.compositor = Compositor::new(&p.dev); } @@ -1241,15 +1281,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. @@ -1594,6 +1655,10 @@ mod tests { assert_eq!(source_uv_rect(got[0].1, 1600, 900), [0.1, 0.1, 0.5, 0.5]); assert_eq!(source_uv_rect(got[1].1, 3840, 2160), [0.0, 0.0, 1.0, 1.0]); assert_eq!(source_uv_rect(Some([0, 0, 4000, 900]), 1920, 1080), [0.0, 0.0, 1.0, 1.0]); + let big = vec![0u8; (MAX_PLANES + 2) * PLANE_STRIDE]; + let cap = MAX_PLANES * (PLANE_STRIDE / 8); + assert_eq!(unsafe { raw_plane_words((MAX_PLANES + 2) as u32, big.as_ptr()) }.len(), cap); + assert_eq!(unsafe { raw_plane_words(u32::MAX, big.as_ptr()) }.len(), cap); } } @@ -1826,4 +1891,156 @@ mod frame_dump_tests { rb.Unmap(0, None); } } + + unsafe fn warp_env() -> (ID3D12Device, ID3D12CommandAllocator, ID3D12GraphicsCommandList, Compositor) { + let adapter: IDXGIAdapter = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap().EnumWarpAdapter().unwrap(); + let mut dev: Option = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev).unwrap(); + let dev = dev.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(); + (dev.clone(), alloc, list, Compositor::new(&dev).unwrap()) + } + + unsafe fn make_tex_2d(dev: &ID3D12Device, w: u32, h: u32, samples: u32, flags: D3D12_RESOURCE_FLAGS) -> ID3D12Resource { + let mut r: Option = None; + let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: w as u64, Height: h, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8G8B8A8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: samples, Quality: 0 }, Flags: flags, ..Default::default() }; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + } + + #[test] + fn compositor_releases_root_sig_and_rejects_invalid_planes() { + unsafe { + let (dev, _alloc, list, mut comp) = warp_env(); + let refcount = |p: *mut c_void| -> u32 { + let vtbl = *(p as *const *const usize); + std::mem::transmute:: u32>(*vtbl.add(1))(p); + std::mem::transmute:: u32>(*vtbl.add(2))(p) + }; + let before = refcount(comp.root_sig.as_raw()); + drop(comp.psos_for(&dev, DXGI_FORMAT_R8G8B8A8_UNORM).unwrap()); + assert!(comp.psos_for(&dev, DXGI_FORMAT_BC1_UNORM).is_none()); + comp.psos.clear(); + assert_eq!(refcount(comp.root_sig.as_raw()), before, "psos_for leaked root_sig COM refs"); + + let out = make_tex_2d(&dev, 8, 8, 1, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + let ok = make_tex_2d(&dev, 4, 4, 1, D3D12_RESOURCE_FLAG_NONE); + let msaa = make_tex_2d(&dev, 4, 4, 4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + let (mut deny, mut bad_fmt, mut buf) = (ok.GetDesc(), ok.GetDesc(), ok.GetDesc()); + deny.Flags |= D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; + bad_fmt.Format = DXGI_FORMAT_R32_FLOAT; + buf.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + let full = [0.0, 0.0, 1.0, 1.0]; + let cases: &[&[(ID3D12Resource, D3D12_RESOURCE_DESC, [f32; 4])]] = &[ + &[(ok.clone(), ok.GetDesc(), full), (ok.clone(), deny, full)], + &[(ok.clone(), ok.GetDesc(), full), (msaa.clone(), msaa.GetDesc(), full)], + &[(ok.clone(), bad_fmt, full)], &[(ok.clone(), buf, full)], &[], + ]; + for (idx, planes) in cases.iter().enumerate() { + assert!(!comp.record(&dev, &list, &out, 8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, planes, 0), "case {idx}"); + assert!(comp.psos.is_empty(), "case {idx} mutated compositor state"); + } + list.Close().unwrap(); + } + } + + #[test] + fn compositor_scales_single_plane_sub_rect() { + unsafe { + let (dev, _alloc, list, mut comp) = warp_env(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let (src, out) = (make_tex_2d(&dev, 8, 8, 1, D3D12_RESOURCE_FLAG_NONE), make_tex_2d(&dev, 8, 8, 1, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)); + let (full, sub) = ([0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.5, 0.5]); + assert!(!needs_compositor(&[(src.clone(), src.GetDesc(), full)])); + assert!(needs_compositor(&[(src.clone(), src.GetDesc(), sub)])); + assert!(needs_compositor(&[(src.clone(), src.GetDesc(), full), (src.clone(), src.GetDesc(), full)])); + + let mut up: Option = None; + let up_desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: 256 * 8, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &up_desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut up).unwrap(); + let (up, mut ptr) = (up.unwrap(), std::ptr::null_mut()); + up.Map(0, None, Some(&mut ptr)).unwrap(); + let bytes = std::slice::from_raw_parts_mut(ptr as *mut u8, 256 * 8); + for y in 0..8usize { + for x in 0..8usize { bytes[y * 256 + x * 4..y * 256 + x * 4 + 4].copy_from_slice(if x < 4 && y < 4 { &[0, 255, 0, 255] } else { &[255, 0, 0, 255] }); } + } + up.Unmap(0, None); + let dst_loc = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&src), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + let src_loc = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&up), 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_R8G8B8A8_UNORM, Width: 8, Height: 8, Depth: 1, RowPitch: 256 } } } }; + list.ResourceBarrier(&[transition(&src, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); + list.CopyTextureRegion(&dst_loc, 0, 0, 0, &src_loc, None); + list.ResourceBarrier(&[transition(&src, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON), transition(&out, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)]); + assert!(comp.record(&dev, &list, &out, 8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, &[(src.clone(), src.GetDesc(), sub)], 0)); + list.ResourceBarrier(&[transition(&out, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let (rb, fp) = readback_copy(&list, &out, &out.GetDesc()).unwrap(); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + fence::wait(&fence, 1, &dev, None, 5000).unwrap(); + rb.Map(0, None, Some(&mut ptr)).unwrap(); + for (x, y) in [(1usize, 1usize), (5, 5), (6, 6)] { + assert_eq!((ptr as *const u8).add(fp.Offset as usize + y * fp.Footprint.RowPitch as usize + x * 4).cast::<[u8; 4]>().read_unaligned(), [0, 255, 0, 255], "pixel ({x},{y})"); + } + rb.Unmap(0, None); + } + } + + #[test] + fn retain_rtv_resource_keeps_com_ref_alive_across_rtv_removal() { + use std::sync::atomic::AtomicU32; + #[repr(C)] + struct FakeCom { + vt: *const usize, + refs: AtomicU32, + } + unsafe extern "system" fn fake_add_ref(p: usize) -> u32 { + (*(p as *const FakeCom)).refs.fetch_add(1, Ordering::AcqRel) + 1 + } + unsafe extern "system" fn fake_release(p: usize) -> u32 { + (*(p as *const FakeCom)).refs.fetch_sub(1, Ordering::AcqRel) - 1 + } + let mut vt = [0usize; 3]; + vt[1] = fake_add_ref as usize; + vt[2] = fake_release as usize; + let obj = Box::new(FakeCom { vt: vt.as_ptr(), refs: AtomicU32::new(1) }); + let raw = &*obj as *const FakeCom as usize; + let handle = 0x7900_0001usize; + unsafe { + { + let mut g = RTVS.lock().unwrap(); + add_ref(raw); + g.get_or_insert_with(HashMap::new).insert(handle, raw); + } + assert_eq!(obj.refs.load(Ordering::Acquire), 2); + let retained = retain_rtv_resource(handle).expect("retained RTV resource"); + assert_eq!(retained, raw); + assert_eq!(obj.refs.load(Ordering::Acquire), 3); + // Simulate concurrent RTV slot clear releasing the table's ref while caller holds its own. + { + let mut g = RTVS.lock().unwrap(); + if let Some(old) = g.as_mut().and_then(|m| m.remove(&handle)) { + release(old); + } + } + assert_eq!(obj.refs.load(Ordering::Acquire), 2, "caller ref must keep object alive"); + release(retained); + assert_eq!(obj.refs.load(Ordering::Acquire), 1); + } + } + + #[test] + fn note_rtv_and_rt0_ignore_internal_present_calls() { + let handle = 0x7900_2456usize; + let list = 0x7900_2457usize; + let prev = IN_PRESENT.with(|c| c.replace(true)); + unsafe { + note_rtv(handle, 0x1000 as *mut c_void); + note_rt0(list, handle); + } + IN_PRESENT.with(|c| c.set(prev)); + assert_eq!(rtv_resource(handle), None, "internal present RTV must not be recorded"); + assert_eq!(rt0_resource(list), None, "internal present RT0 must not be recorded"); + } } diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs new file mode 100644 index 0000000000..5d468c52d6 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -0,0 +1,261 @@ +//! Pre-entry shader preparation in the same HWND that later owns the DXGI swap chain. +use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; +use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; +use windows::Win32::Foundation::{HWND, LRESULT, WPARAM}; +use windows_sys::Win32::Foundation::{RECT, WAIT_OBJECT_0}; +use windows_sys::Win32::Graphics::Gdi::*; +use windows_sys::Win32::System::Threading::WaitForSingleObject; +use windows_sys::Win32::UI::WindowsAndMessaging::*; +use crate::config::Boot; +use crate::shaders::{LaunchPreparation, prepare_for_launch}; +use crate::util::wide; + +static ACTIVE: AtomicBool = AtomicBool::new(false); +static SCREEN: Mutex> = Mutex::new(None); +const READY: u32 = WM_APP + 0x40; + +struct Screen { + progress: Arc, + start: Instant, + clock: StallClock, + ready: bool, +} + +impl Screen { + fn release(&mut self) -> bool { + self.ready = !self.progress.cancel.load(Ordering::Relaxed); + self.ready + } +} + +pub(super) fn active() -> bool { ACTIVE.load(Ordering::Acquire) } + +pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { + // This handle was opened by the launcher on itself, then inherited by this host. + let parent = std::env::var("XCL_PREPARATION_PARENT").ok() + .and_then(|s| s.parse::().ok()).filter(|&h| h != 0) + .map(|h| unsafe { OwnedHandle::from_raw_handle(h as _) }); + let menu = std::env::var_os("XCL_PREPARATION_MENU").is_some(); + std::env::remove_var("XCL_PREPARATION_PARENT"); + std::env::remove_var("XCL_PREPARATION_MENU"); + let root = &boot.game_root; + if boot.config.graphics.eq_ignore_ascii_case("null") || + (!root.join("shaders.rpf").try_exists().map_err(|e| e.to_string())? && !root.join("shaders").is_dir()) { + return Ok(()); + } + // `XCL_PREPARE=0`: the title starts at once and builds what it uses as it goes (it stands + // still for those builds): for a look at a change without the wait + if std::env::var("XCL_PREPARE").is_ok_and(|v| v.trim() == "0") { + crate::xlog_info!("Shader preparation left out (XCL_PREPARE=0): the title builds what it uses as it goes"); + return Ok(()); + } + let only = Some(crate::hle::d3d12x::pso_async::earlier_used_shaders()) + .filter(|used| !used.is_empty() && !std::env::var("XCL_PREPARE_ALL").is_ok_and(|v| v.trim() == "1")); + if let Some(used) = &only { + crate::xlog_info!("Shader preparation: only the {} shaders earlier runs used (XCL_PREPARE_ALL=1: every record)", used.len()); + } + let progress = Arc::new(LaunchPreparation { adapter: boot.config.d3d12_adapter.clone(), only, ..Default::default() }); + let hwnd = if super::enabled() { + *SCREEN.lock().unwrap() = Some(Screen { progress: progress.clone(), start: Instant::now(), clock: StallClock::default(), ready: false }); + ACTIVE.store(true, Ordering::Release); + let hwnd = super::ensure_window().ok_or("Could not create the presentation window for shader preparation")?; + crate::xlog_info!("Shader preparation window {:#x}", hwnd.0 as usize); + Some(hwnd) + } else { None }; + let result = std::thread::scope(|scope| { + let worker = scope.spawn(|| prepare_for_launch(root, &progress)); + // (a line every 5 s: a log that stands still for long reads as a frozen process) + let (began, mut said) = (Instant::now(), Instant::now()); + while !worker.is_finished() { + if said.elapsed() >= Duration::from_secs(5) { + 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() + ); + } + if let Some(parent) = &parent { + if unsafe { WaitForSingleObject(parent.as_raw_handle(), 80) } == WAIT_OBJECT_0 { + // The launcher was stopped during preparation. Do not leave an orphan compile or start the title. + std::process::exit(2); + } + } else { std::thread::sleep(Duration::from_millis(80)); } + } + worker.join().map_err(|_| "Shader preparation worker stopped unexpectedly")? + }); + let mut result = if progress.cancel.load(Ordering::Relaxed) { Err("Shader preparation cancelled".into()) } else { result }; + if let Some(hwnd) = hwnd { + if result.is_ok() { + // Complete painting on the window's owner thread before the guest can draw. + if unsafe { SendMessageW(hwnd.0, READY, 0, 0) } == 0 { + result = Err("Shader preparation cancelled".into()); + } + } else if let Err(e) = &result { + if menu && !progress.cancel.load(Ordering::Relaxed) { + unsafe { MessageBoxW(hwnd.0, wide(e).as_ptr(), wide("XCL – Shader preparation failed").as_ptr(), MB_OK | MB_ICONERROR); } + } + } + ACTIVE.store(false, Ordering::Release); + *SCREEN.lock().unwrap() = None; + } + result +} + +pub(super) unsafe fn on_message(hwnd: HWND, msg: u32, wp: WPARAM) -> Option { + if !active() { return None; } + match msg { + WM_PAINT => { + let mut guard = SCREEN.lock().unwrap(); + if let Some(s) = guard.as_mut() { paint(hwnd, s); } + } + WM_ERASEBKGND => return Some(LRESULT(1)), + WM_TIMER if wp.0 == super::COMPILE_TIMER => { InvalidateRect(hwnd.0, std::ptr::null(), 0); } + WM_CLOSE => { + if let Some(s) = SCREEN.lock().unwrap().as_ref() { s.progress.cancel.store(true, Ordering::Relaxed); } + InvalidateRect(hwnd.0, std::ptr::null(), 0); + } + READY => { + { + let mut view = SCREEN.lock().unwrap(); + let s = view.as_mut()?; + if !s.release() { return Some(LRESULT(0)); } + } + RedrawWindow(hwnd.0, std::ptr::null(), std::ptr::null_mut(), RDW_INVALIDATE | RDW_UPDATENOW); + crate::hle::kbm::attach(hwnd.0); + ACTIVE.store(false, Ordering::Release); + return Some(LRESULT(1)); + } + _ => return None, + } + Some(LRESULT(0)) +} + +unsafe fn fill(dc: HDC, rect: RECT, color: u32) { + let brush = CreateSolidBrush(color); + FillRect(dc, &rect, brush); + DeleteObject(brush); +} + +unsafe fn text(dc: HDC, rect: RECT, value: &str, size: i32, weight: i32, color: u32, align: u32) { + let font = CreateFontW(-size, 0, 0, 0, weight, 0, 0, 0, DEFAULT_CHARSET as _, 0, 0, CLEARTYPE_QUALITY as _, 0, wide("Segoe UI").as_ptr()); + let old = SelectObject(dc, font); + SetTextColor(dc, color); + let utf = wide(value); + let mut rect = rect; + DrawTextW(dc, utf.as_ptr(), (utf.len()-1) as i32, &mut rect, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS | align); + SelectObject(dc, old); + DeleteObject(font); +} + +unsafe fn paint(hwnd: HWND, s: &mut Screen) { + let mut ps: PAINTSTRUCT = std::mem::zeroed(); + let dest = BeginPaint(hwnd.0, &mut ps); + let mut rc = RECT::default(); + GetClientRect(hwnd.0, &mut rc); + if rc.right > 0 && rc.bottom > 0 { + let dc = CreateCompatibleDC(dest); + let bitmap = CreateCompatibleBitmap(dest, rc.right, rc.bottom); + let old = SelectObject(dc, bitmap); + SetBkMode(dc, TRANSPARENT as i32); + fill(dc, rc, 0x201815); + let scale = |px: i32| (px * GetDeviceCaps(dc, LOGPIXELSY as i32).max(96)) / 96; + let width = scale(560).min((rc.right - scale(40)).max(1)); + 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 mut title = row(0,48); + title.right -= scale(84); + text(dc, title, heading, scale(31), 600, 0xf7f5f1, DT_LEFT); + text(dc, row(0,48), &format!("{pct}%"), scale(27), 600, 0xdfd09a, DT_RIGHT); + let bar = row(65,72); + fill(dc, bar, 0x4b4038); + 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 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") }; + 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); + SelectObject(dc, old); + DeleteObject(bitmap); + DeleteDC(dc); + } + EndPaint(hwnd.0, &ps); +} + +#[derive(Default)] +struct StallClock { + done: usize, + advanced_at: Duration, + last_stall_ended: Option, +} + +impl StallClock { + fn sample(&mut self, done: usize, now: Duration) -> (u64, Option) { + if done != self.done { + if now - self.advanced_at >= Duration::from_secs(5) { + self.last_stall_ended = Some(now); + } + self.done = done; + self.advanced_at = now; + } + ((now - self.advanced_at).as_secs(), self.last_stall_ended.map(|end| (now - end).as_secs())) + } +} + +fn percent(done: usize, total: usize, ready: bool) -> usize { + if ready { 100 } else { done.saturating_mul(100).checked_div(total).unwrap_or(0).min(99) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clock_advances_during_a_stall_and_remembers_recovery() { + let mut clock = StallClock::default(); + let s = Duration::from_secs; + assert_eq!(clock.sample(0, s(1)), (1, None)); + assert_eq!(clock.sample(0, s(5)), (5, None)); + assert_eq!(clock.sample(2, s(6)), (0, Some(0))); + assert_eq!(clock.sample(2, s(8)), (2, Some(2))); + assert_eq!(clock.sample(3, s(9)), (0, Some(3))); + assert_eq!(clock.sample(3, s(15)), (6, Some(9))); + assert_eq!(clock.sample(4, s(16)), (0, Some(0))); + } + + #[test] + fn close_before_the_ready_message_cancels_the_handoff() { + let progress = Arc::new(LaunchPreparation::default()); + let mut screen = Screen { progress: progress.clone(), start: Instant::now(), clock: StallClock::default(), ready: false }; + progress.cancel.store(true, Ordering::Relaxed); + assert!(!screen.release()); + assert!(!screen.ready); + } + + #[test] + fn only_a_successful_join_releases_the_last_percent() { + assert_eq!(percent(0, 0, false), 0); + assert_eq!(percent(1, 4, false), 25); + assert_eq!(percent(4, 4, false), 99); + assert_eq!(percent(4, 4, true), 100); + } +} diff --git a/crates/xcl/src/hle/d3d12x/prof.rs b/crates/xcl/src/hle/d3d12x/prof.rs new file mode 100644 index 0000000000..39d9dec4cb --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/prof.rs @@ -0,0 +1,200 @@ +//! Where the title's threads spend their time in XCL: a `profile (2 s)` line beside the +//! `activity (2 s)` one (`XCL_ACTIVITY`). A console title's calls into the graphics driver take +//! next to no time; here a call can wait for a pipeline still being built, for XCL's uploads and +//! tile mappings before a submission, or for the GPU. Each kind of wait is timed where it happens +//! (`span`), summed over all the threads, so a frame rate near 0 shows what holds it: the line +//! gives each kind's time in the 2 s (over 2 000 ms: several threads at once), its calls and the +//! longest one. A wait counts when it ends; one that has not ended yet (a draw 36 s into waiting +//! for its pipeline) is given as still going, with its time so far. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +#[derive(Clone, Copy)] +pub enum Kind { + /// a draw waiting for its graphics pipeline (`pso_async::resolve_wait_in`) + GraphicsPipelineWait, + /// a dispatch or a submission waiting for a compute pipeline, its build on the title's + /// thread included (`pso_async`) + ComputePipelineWait, + /// `ExecuteCommandLists` / `KickoffX`: XCL's uploads and tile mappings, then the driver's + Submit, + /// `CreatePlacedResourceX`: the PC's reserved resource and its tile mappings + Placement, + /// `WaitFrameEventX`: the title waiting for its frame pacing (the GPU, a flip) + FrameEvent, + /// `PresentX` + Present, + /// the driver compiling a pipeline, on any thread (workers too) + DriverCompile, + /// in a submit: the write-watch look for the pages the CPU wrote (`title_textures::refresh_once`) + SubmitWatch, + /// in a submit: those pages copied to the sparse windows' video memory (`sparse::before_execute`) + SubmitSparse, + /// in a submit: textures in title memory uploaded again (`title_textures::upload_all`) + SubmitTextures, + /// in a submit: the title's lists expanded into their PC segments (put-off dispatches recorded) + SubmitRecord, + /// in a submit: the PC `ExecuteCommandLists` (the driver) + SubmitDriver, + /// in a submit: after the driver's call (scratch copies, Write64 signals, readbacks, CPU writes) + SubmitAfter, +} + +const KINDS: usize = 13; +const NAMES: [&str; KINDS] = [ + "graphics pipeline waits", + "compute pipeline waits", + "submits", + "placements", + "frame-event waits", + "presents", + "driver compiles (all threads)", + "[submit: write-watch", + "sparse copies", + "texture uploads", + "list segments", + "driver", + "after]", +]; + +static NS: [AtomicU64; KINDS] = [const { AtomicU64::new(0) }; KINDS]; +static CALLS: [AtomicU64; KINDS] = [const { AtomicU64::new(0) }; KINDS]; +/// the longest single one since the last line +static LONGEST: [AtomicU64; KINDS] = [const { AtomicU64::new(0) }; KINDS]; + +/// Adds `d` of `kind`. +pub fn add(kind: Kind, d: Duration) { + let k = kind as usize; + let ns = d.as_nanos().min(u64::MAX as u128) as u64; + NS[k].fetch_add(ns, Ordering::Relaxed); + CALLS[k].fetch_add(1, Ordering::Relaxed); + LONGEST[k].fetch_max(ns, Ordering::Relaxed); +} + +/// spans of each kind not dropped yet, and the sum of their starts (`now_ns`, wrapping) +static OPEN: [AtomicU64; KINDS] = [const { AtomicU64::new(0) }; KINDS]; +static OPEN_STARTS: [AtomicU64; KINDS] = [const { AtomicU64::new(0) }; KINDS]; +/// spans still going are in the line once they took this long in all (a frame's own short +/// waits, caught open as the line is written, are not) +const OPEN_SHOWN_NS: u64 = 500_000_000; + +/// Nanoseconds since the first span. +fn now_ns() -> u64 { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + EPOCH.get_or_init(Instant::now).elapsed().as_nanos().min(u64::MAX as u128) as u64 +} + +/// Times from now to its drop as `kind`. +pub struct Span(Kind, u64); + +pub fn span(kind: Kind) -> Span { + let at = now_ns(); + let k = kind as usize; + OPEN_STARTS[k].fetch_add(at, Ordering::Relaxed); + OPEN[k].fetch_add(1, Ordering::Relaxed); + Span(kind, at) +} + +impl Span { + /// The time since it started. + pub fn elapsed(&self) -> Duration { + Duration::from_nanos(now_ns().saturating_sub(self.1)) + } +} + +impl Drop for Span { + fn drop(&mut self) { + let k = self.0 as usize; + OPEN[k].fetch_sub(1, Ordering::Relaxed); + OPEN_STARTS[k].fetch_sub(self.1, Ordering::Relaxed); + add(self.0, self.elapsed()); + } +} + +/// The spans of kind `k` still going: how many, and their time so far in all. The two counters +/// are read one after the other while other threads change them: a pair that cannot be (more +/// time than every span running since the first) is given as none. +fn still_going(k: usize) -> (u64, u64) { + let (n, starts, now) = (OPEN[k].load(Ordering::Relaxed), OPEN_STARTS[k].load(Ordering::Relaxed), now_ns()); + let ns = n.wrapping_mul(now).wrapping_sub(starts); + if n == 0 || n > 1 << 20 || ns > n.saturating_mul(now) { (0, 0) } else { (n, ns) } +} + +/// ` ; N still going, M ms so far` for a kind's part of the line (nothing below `OPEN_SHOWN_NS`). +fn still_going_note((n, ns): (u64, u64)) -> String { + if n == 0 || ns < OPEN_SHOWN_NS { String::new() } else { format!("; {n} still going, {} ms so far", ns / 1_000_000) } +} + +/// Totals so far: (ns, calls) of each kind. +#[derive(Clone, Copy)] +pub struct Totals([(u64, u64); KINDS]); + +pub fn totals() -> Totals { + Totals(std::array::from_fn(|k| (NS[k].load(Ordering::Relaxed), CALLS[k].load(Ordering::Relaxed)))) +} + +/// The line for what was added between `before` and `now` (the longest ones start again). +pub fn line(before: Totals, now: Totals, presents: u64, secs: f64) -> String { + let mut parts = Vec::new(); + for k in 0..KINDS { + let ns = now.0[k].0.saturating_sub(before.0[k].0); + let calls = now.0[k].1.saturating_sub(before.0[k].1); + let longest = LONGEST[k].swap(0, Ordering::Relaxed); + let going = still_going_note(still_going(k)); + if calls == 0 && going.is_empty() { + continue; + } + parts.push(format!("{} {} ms ({calls}, longest {} ms{going})", NAMES[k], ns / 1_000_000, longest / 1_000_000)); + } + let frame = if presents > 0 { format!("{:.0} ms a frame", secs * 1000.0 / presents as f64) } else { "no frame".to_string() }; + let (_, failed, queued) = super::pso_async::counts(); + let (running, done) = crate::gpu::recomp::dxc::compile_counts(); + format!( + "profile ({secs:.0} s): {frame}; {}; pipelines queued {queued}, failed {failed}; DXC {running} running, {done} done", + if parts.is_empty() { "no waits".to_string() } else { parts.join(", ") } + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A span adds its time and a call to its kind; the line gives the difference since the + /// totals before, and leaves out kinds with no call. + #[test] + fn spans_add_up_by_kind_in_the_line() { + let before = totals(); + add(Kind::Placement, Duration::from_millis(30)); + add(Kind::Placement, Duration::from_millis(20)); + { + let _s = span(Kind::FrameEvent); + } + let now = totals(); + let k = Kind::Placement as usize; + assert!(now.0[k].0 - before.0[k].0 >= 50_000_000); + assert!(now.0[k].1 - before.0[k].1 >= 2); + let l = line(before, now, 4, 2.0); + assert!(l.contains("500 ms a frame"), "{l}"); + assert!(l.contains("placements "), "{l}"); + assert!(l.contains("frame-event waits "), "{l}"); + } + + /// A span that has not ended is counted as still going with its time so far, and no longer + /// once it is dropped; the line names it only when it is long. + #[test] + fn a_span_not_ended_yet_is_still_going() { + let k = Kind::SubmitAfter as usize; + let s = span(Kind::SubmitAfter); + std::thread::sleep(Duration::from_millis(5)); + let (n, ns) = still_going(k); + assert!(n >= 1 && ns >= 5_000_000, "{n} spans, {ns} ns"); + assert!(s.elapsed() >= Duration::from_millis(5)); + let calls = CALLS[k].load(Ordering::Relaxed); + drop(s); + assert!(CALLS[k].load(Ordering::Relaxed) > calls, "a dropped span is a call"); + assert_eq!(still_going_note((1, 36_000_000_000)), "; 1 still going, 36000 ms so far"); + assert_eq!(still_going_note((2, OPEN_SHOWN_NS - 1)), ""); + assert_eq!(still_going_note((0, 0)), ""); + } +} diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 63d62a7df4..6e05c358b5 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -8,9 +8,30 @@ //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. use std::collections::HashMap; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU64, AtomicU8, AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; +/// Sentinel for `Pending::waited_frame`: no frame has spent graphics wait budget on this PSO yet. +const UNWAITED: u64 = u64::MAX; + +/// Lifecycle states for tracking whether a `Pending` pipeline currently counts toward +/// `WANTED_ACTIVE_COUNT`: +/// - `WANTED_NONE` (0): not wanted yet and not finished +/// - `WANTED_ACTIVE` (1): actively wanted and still queued/building (contributes +1) +/// - `WANTED_DONE` (2): completed, dropped unstarted, or permanently gated (contributes 0) +const WANTED_NONE: u8 = 0; +const WANTED_ACTIVE: u8 = 1; +const WANTED_DONE: u8 = 2; + +/// Number of `wanted` pipelines currently queued or building on workers. While non-zero, +/// speculative `xcl-pso-pre-*` preload pauses so background builds never steal RAM/CPU from +/// pipelines the current frame actually needs. +static WANTED_ACTIVE_COUNT: AtomicUsize = AtomicUsize::new(0); + +fn wanted_active() -> usize { + WANTED_ACTIVE_COUNT.load(Ordering::Acquire) +} + struct Pending { /// the build, until a worker – or a bind that cannot wait for the queue – takes it job: Mutex>, @@ -33,7 +54,25 @@ struct Pending { late: std::sync::atomic::AtomicBool, /// its dispatches may be left out while it is built (`image_only`): binds do not wait for it spared: std::sync::atomic::AtomicBool, + /// shader issues `image_bvh*_intersect_ray`: held back without blocking until BVH builds succeed + bvh_traversal: std::sync::atomic::AtomicBool, + /// heavyweight RT/compute shader (`>= 512 KiB` DXIL / BVH traversal): lower worker queue + /// priority than normal/MS PSOs so world-entry draws finish ahead of slow RT compiles + deprioritized: std::sync::atomic::AtomicBool, + /// first frame that waited on this graphics PSO within `XCL_PSO_FRAME_BUDGET_MS` (`UNWAITED` + /// if never waited yet): later frames skip waiting while workers finish compiling it + waited_frame: AtomicU64, + /// tracks whether this entry currently contributes to `WANTED_ACTIVE_COUNT` + wanted_state: AtomicU8, demand: Mutex, + /// what its first use tells besides `used::note` (`on_first_use`) + on_use: Mutex>, +} + +impl Drop for Pending { + fn drop(&mut self) { + self.clear_wanted_active(); + } } /// Whether one of the title's threads waits for the pipeline, and the preload worker building it. @@ -79,7 +118,8 @@ fn build(p: &Arc, job: Job, preload: bool) { unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) }; } } - complete(p, job()); + // (a panic in a build ends it as a failed one: whoever waits for it is not left waiting) + complete(p, std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)).unwrap_or(0)); if preload { // (under the lock: `want` does not raise this thread after it) let mut d = p.demand.lock().unwrap(); @@ -92,35 +132,66 @@ fn build(p: &Arc, job: Job, preload: bool) { } impl Pending { + fn mark_wanted_active(&self) { + if self + .wanted_state + .compare_exchange(WANTED_NONE, WANTED_ACTIVE, Ordering::AcqRel, Ordering::Acquire) + .is_ok() + { + WANTED_ACTIVE_COUNT.fetch_add(1, Ordering::AcqRel); + } + } + + fn clear_wanted_active(&self) { + if self.wanted_state.swap(WANTED_DONE, Ordering::AcqRel) == WANTED_ACTIVE { + WANTED_ACTIVE_COUNT.fetch_sub(1, Ordering::AcqRel); + } + } + /// One of the title's threads is about to wait for it: the worker building it goes on now, /// at a normal priority. fn want(&self) { use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_PRIORITY_NORMAL, THREAD_SET_LIMITED_INFORMATION}; - let mut d = self.demand.lock().unwrap(); - if !std::mem::replace(&mut d.wanted, true) && d.preload_thread != 0 { - unsafe { - let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, d.preload_thread); - if !h.is_null() { - SetThreadPriority(h, THREAD_PRIORITY_NORMAL); - CloseHandle(h); + let became_wanted = { + let mut d = self.demand.lock().unwrap(); + let first = !std::mem::replace(&mut d.wanted, true); + if first && d.preload_thread != 0 { + unsafe { + let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, d.preload_thread); + if !h.is_null() { + SetThreadPriority(h, THREAD_PRIORITY_NORMAL); + CloseHandle(h); + } } } + first + }; + if became_wanted { + self.mark_wanted_active(); + crate::gpu::recomp::dxc::notify_wanted(); + notify_queue_wanted(); + super::real::notify_big_compile_wanted(); } } fn note_use(&self) { if self.key != 0 && !self.used.swap(true, Ordering::Relaxed) { used::note(self.key); + let on_use = self.on_use.lock().unwrap().take(); + if let Some(f) = on_use { + f(); + } } } } /// stand-in handed to the title → its real pipeline -static PENDING: Mutex>>> = Mutex::new(None); +static PENDING: std::sync::RwLock>>> = std::sync::RwLock::new(None); /// The build is done (`real`: its pipeline, 0 = failed). fn complete(p: &Pending, real: usize) { + p.clear_wanted_active(); if real == 0 { FAILED.fetch_add(1, Ordering::Relaxed); } else { @@ -278,6 +349,7 @@ fn next_needed() -> Option> { /// Drop an unstarted orphaned job outside all locks and wake any concurrent waiter. fn drop_unstarted_job(p: &Pending) { + p.clear_wanted_active(); let job = p.job.lock().unwrap().take(); if let Some(job) = job { { @@ -291,30 +363,234 @@ fn drop_unstarted_job(p: &Pending) { type Work = Box; -fn queue() -> &'static Mutex> { - static Q: OnceLock>> = OnceLock::new(); - Q.get_or_init(|| { - let (tx, rx) = mpsc::channel::(); - let rx = Arc::new(Mutex::new(rx)); +struct PsoWork { + work: Work, + pending: Option>, +} + +/// Priority work queue for `xcl-pso-*` workers: pipelines waited on by a title thread (`wanted`) +/// jump ahead of queued background builds. +struct PsoQueue { + items: Mutex>, + cv: Condvar, +} + +impl PsoQueue { + fn new() -> Self { + Self { items: Mutex::new(std::collections::VecDeque::new()), cv: Condvar::new() } + } + + fn push(&self, work: Work, pending: Option>) { + self.items.lock().unwrap().push_back(PsoWork { work, pending }); + self.cv.notify_one(); + } + + fn notify_wanted(&self) { + let _g = self.items.lock().unwrap(); + drop(_g); + self.cv.notify_all(); + } + + fn pop(&self) -> Work { + let mut g = self.items.lock().unwrap(); + loop { + if let Some(pos) = g.iter().position(|item| { + item.pending.as_ref().is_some_and(|p| { + p.compute + && !p.spared.load(Ordering::Acquire) + && !p.bvh_traversal.load(Ordering::Acquire) + && p.demand.lock().unwrap().wanted + }) + }) { + return g.remove(pos).unwrap().work; + } + if let Some(pos) = g.iter().position(|item| item.pending.as_ref().is_some_and(|p| p.demand.lock().unwrap().wanted)) { + return g.remove(pos).unwrap().work; + } + if let Some(pos) = g.iter().position(|item| !item.pending.as_ref().is_some_and(|p| p.deprioritized.load(Ordering::Acquire))) { + return g.remove(pos).unwrap().work; + } + if let Some(item) = g.pop_front() { + return item.work; + } + g = self.cv.wait(g).unwrap(); + } + } +} + +static WORK_QUEUE: OnceLock> = OnceLock::new(); + +fn notify_queue_wanted() { + if let Some(q) = WORK_QUEUE.get() { + q.notify_wanted(); + } +} + +/// Default `xcl-pso-*` worker count for a host with `logical_cpus` hardware threads and +/// `total_ram_gib` GiB of physical RAM. +/// +/// Smaller hosts (`< 16` threads or `< 24 GiB` RAM) stay capped at `2..=6` workers to avoid +/// driver LLVM commit pressure; high-core / high-RAM hosts (`>= 16` threads and `>= 24 GiB` RAM) +/// scale cleanly up to `10` workers (`logical_cpus / 2`, clamped to `6..=10`), relying on +/// `driver_compile_identified`'s commit-headroom gate to keep peak commit bounded. +fn pso_worker_threads_for(logical_cpus: usize, total_ram_gib: u64) -> usize { + if logical_cpus >= 16 && total_ram_gib >= 24 { + (logical_cpus / 2).clamp(6, 10) + } else { + logical_cpus.saturating_sub(1).clamp(2, 6) + } +} + +fn total_physical_ram_gib() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m = MEMORYSTATUSEX { dwLength: std::mem::size_of::() as u32, ..unsafe { std::mem::zeroed() } }; + (unsafe { GlobalMemoryStatusEx(&mut m) } != 0 && m.ullTotalPhys > 0).then_some(m.ullTotalPhys >> 30) +} + +/// Number of `xcl-pso-*` worker threads: honors explicit `XCL_PSO_THREADS` (or `XCL_DXC_THREADS`), +/// otherwise scales via `pso_worker_threads_for(logical_cpus, total_ram_gib)`. +fn pso_worker_threads() -> usize { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| { + std::env::var("XCL_PSO_THREADS") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|&n| n > 0) + .or_else(|| { + std::env::var("XCL_DXC_THREADS") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|&n| n > 0) + }) + .map(|n| n.clamp(1, 64)) + .unwrap_or_else(|| { + let cpus = std::thread::available_parallelism().map(usize::from).unwrap_or(4); + let ram_gib = total_physical_ram_gib().unwrap_or(0); + pso_worker_threads_for(cpus, ram_gib) + }) + }) +} + +/// Number of low-priority `xcl-pso-pre-*` preload threads (`1..=2` by default). +fn preload_worker_threads() -> usize { + (pso_worker_threads() / 3).clamp(1, 2) +} + +fn queue() -> &'static Arc { + WORK_QUEUE.get_or_init(|| { + let q = Arc::new(PsoQueue::new()); // translation recurses deeply on big programs; DXC itself runs on its own pool - let n = crate::gpu::recomp::dxc::compile_threads(); + let n = pso_worker_threads(); for k in 0..n { - let rx = rx.clone(); - let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop { - let next = rx.lock().unwrap().recv(); - let Ok(work) = next else { return }; + let q = q.clone(); + let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(16 << 20).spawn(move || loop { + while let Some(p) = next_needed() { + build_queued(&p); + } + let work = q.pop(); while let Some(p) = next_needed() { build_queued(&p); } work(); }); } - Mutex::new(tx) + q }) } fn enqueue(p: Arc) { - let _ = queue().lock().unwrap().send(Box::new(move || build_queued(&p))); + let p_q = p.clone(); + queue().push( + Box::new(move || build_queued(&p)), + Some(p_q), + ); +} + +/// Physical RAM & commit headroom thresholds (`min(ullAvailPhys, ullAvailPageFile)`) for +/// throttling background PSO compilation well before Windows starts paging out the title +/// (`XCL_PSO_MEM_THROTTLE=0`: off). +const PRELOAD_PAUSE_COMMIT: u64 = 6 << 30; +const WORKER_CAP_2_COMMIT: u64 = 5 << 30; +const WORKER_CAP_1_COMMIT: u64 = 3 << 30; + +fn mem_throttle_enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| !cfg!(test) && !std::env::var("XCL_PSO_MEM_THROTTLE").is_ok_and(|v| v.trim() == "0")) +} + +/// The system's free commit: what a driver compile can still allocate. (Free physical memory is +/// not it: a retail title's world entry dropped it to 1.3 GB for a few seconds with 12 GB of +/// commit free – the pages go to the page file – and the throttle on it held every pipeline +/// worker idle while the title waited 14 s for a compute pipeline.) +pub(super) fn avail_commit_bytes() -> 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) +} + +/// Maximum concurrent top-level PSO worker builds allowed for the current available RAM/commit: +/// `< 3 GiB` -> 1 worker (never 0, no deadlock), `< 5 GiB` -> at most 2, otherwise `max_workers`. +fn worker_cap_for_commit(avail_commit: Option, max_workers: usize) -> usize { + let max_workers = max_workers.max(1); + match avail_commit { + Some(avail) if avail < WORKER_CAP_1_COMMIT => 1, + Some(avail) if avail < WORKER_CAP_2_COMMIT => max_workers.min(2), + _ => max_workers, + } +} + +/// Pause speculative `xcl-pso-pre-*` preload builds while available RAM/commit is below 6 GiB. +fn should_pause_preload(avail_commit: Option) -> bool { + avail_commit.is_some_and(|avail| avail < PRELOAD_PAUSE_COMMIT) +} + +/// Pause speculative preload whenever ANY `wanted` pipeline is actively queued/in-flight OR +/// available RAM/commit headroom is below `PRELOAD_PAUSE_COMMIT`. +fn should_pause_preload_with_demand(avail_commit: Option, wanted: usize) -> bool { + wanted > 0 || should_pause_preload(avail_commit) +} + +struct ActiveWorkerGate { + active: Mutex, + cv: Condvar, +} + +static ACTIVE_WORKERS: ActiveWorkerGate = ActiveWorkerGate { + active: Mutex::new(0), + cv: Condvar::new(), +}; + +struct ActiveWorkerGuard; + +impl Drop for ActiveWorkerGuard { + fn drop(&mut self) { + let mut n = ACTIVE_WORKERS.active.lock().unwrap(); + *n = n.saturating_sub(1); + ACTIVE_WORKERS.cv.notify_all(); + } +} + +fn acquire_worker_slot(max_workers: usize) -> ActiveWorkerGuard { + let mut n = ACTIVE_WORKERS.active.lock().unwrap(); + loop { + let avail = mem_throttle_enabled().then(avail_commit_bytes).flatten(); + let cap = worker_cap_for_commit(avail, max_workers); + if *n < cap { + if cap < max_workers { + static LOGGED: std::sync::Once = std::sync::Once::new(); + LOGGED.call_once(|| { + crate::xlog_info!( + "D3D12.X: throttling PSO workers to {cap} under low RAM/commit headroom ({} MiB free)", + avail.unwrap_or(0) >> 20 + ); + }); + } + *n += 1; + return ActiveWorkerGuard; + } + n = ACTIVE_WORKERS.cv.wait_timeout(n, std::time::Duration::from_millis(50)).unwrap().0; + } } fn build_queued(p: &Arc) { @@ -323,6 +599,11 @@ fn build_queued(p: &Arc) { drop_unstarted_job(p); return; } + let _slot = acquire_worker_slot(pso_worker_threads()); + if p.orphan.load(Ordering::Acquire) { + drop_unstarted_job(p); + return; + } // (None: a bind took it and builds it itself) let job = p.job.lock().unwrap().take(); if let Some(job) = job { @@ -343,13 +624,16 @@ pub(super) fn build_pieces(jobs: Vec) -> Vec { }; // the helpers build for this worker's pipeline: the title waiting for it waits for them too let parent = BUILDING.with(|b| b.borrow().clone()); - for _ in 1..count.min(crate::gpu::recomp::dxc::compile_threads()) { - let (drain, parent) = (drain.clone(), parent.clone()); - let _ = queue().lock().unwrap().send(Box::new(move || { - let before = BUILDING.with(|b| b.replace(parent)); - drain(); - BUILDING.with(|b| *b.borrow_mut() = before); - })); + for _ in 1..count.min(pso_worker_threads()) { + let (drain, parent_run, parent_q) = (drain.clone(), parent.clone(), parent.clone()); + queue().push( + Box::new(move || { + let before = BUILDING.with(|b| b.replace(parent_run)); + drain(); + BUILDING.with(|b| *b.borrow_mut() = before); + }), + parent_q, + ); } drain(); let mut results = vec![0; count]; @@ -364,9 +648,24 @@ pub fn release(p: usize) { } } +/// Initial scheduling classification set atomically before a `Pending` entry is visible to +/// preload or normal workers (avoids any race where `xcl-pso-pre-*` pops a heavy/BVH pipeline +/// before its flags are applied). +#[derive(Clone, Copy, Default)] +pub struct SubmitFlags { + pub spared: bool, + pub bvh_traversal: bool, + pub deprioritized: bool, +} + /// `standin` went to the title; `job` builds the real pipeline on a worker. pub fn submit(standin: usize, compute: bool, job: Job) { - submit_as(standin, compute, job, true, 0); + submit_as(standin, compute, job, true, 0, SubmitFlags::default()); +} + +/// Like [`submit`], with initial scheduling flags applied before the entry is queued. +pub fn submit_with_flags(standin: usize, compute: bool, job: Job, flags: SubmitFlags) { + submit_as(standin, compute, job, true, 0, flags); } /// Lazy pipeline creation (`XCL_LAZY_PSO=0`: off): a title's pipelines with console shaders get @@ -382,10 +681,17 @@ pub fn lazy() -> bool { /// `submit`, sent to the workers only on its first `resolve` (`lazy`) – or now, at a low /// priority, when an earlier run used a pipeline of these shaders (`key`, 0 = none; `used`). pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) { - submit_as(standin, compute, job, false, key); + submit_as(standin, compute, job, false, key, SubmitFlags::default()); +} + +/// Like [`submit_lazy`], applying `flags` atomically before insertion and excluding heavyweight / +/// BVH / spared pipelines from speculative `xcl-pso-pre-*` preloading so `THREAD_PRIORITY_LOWEST` +/// workers never stall `BIG_COMPILES`/`GIANT_COMPILES` on unreferenced >1 MiB shaders. +pub fn submit_lazy_with_flags(standin: usize, compute: bool, job: Job, key: u64, flags: SubmitFlags) { + submit_as(standin, compute, job, false, key, flags); } -fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { +fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, flags: SubmitFlags) { let p = Arc::new(Pending { job: Mutex::new(Some(job)), sent: std::sync::atomic::AtomicBool::new(send), @@ -398,17 +704,22 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { used: Default::default(), orphan: Default::default(), late: Default::default(), - spared: Default::default(), + spared: std::sync::atomic::AtomicBool::new(flags.spared), + bvh_traversal: std::sync::atomic::AtomicBool::new(flags.bvh_traversal), + deprioritized: std::sync::atomic::AtomicBool::new(flags.deprioritized), + waited_frame: AtomicU64::new(UNWAITED), + wanted_state: AtomicU8::new(WANTED_NONE), demand: Default::default(), + on_use: Default::default(), }); - PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); + PENDING.write().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); }); if send { enqueue(p); - } else if used::known(key) { + } else if used::known(key) && !flags.deprioritized && !flags.bvh_traversal && !flags.spared { if let Some(q) = preload() { q.list.lock().unwrap().push_back(p); q.cv.notify_one(); @@ -416,12 +727,51 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { } } +/// Run on the thread of a lazy pipeline's first use, once (it is to hand work to another). +pub type OnUse = Box; + +/// What the first use of lazy pipeline `standin` tells besides `used::note`: a graphics one's +/// description for the next run's preparation (`gfx_records::note`). Told before the title has +/// the stand-in. +pub(super) fn on_first_use(standin: usize, f: OnUse) { + if let Some(p) = entry(standin) { + *p.on_use.lock().unwrap() = Some(f); + } +} + +/// 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); +} + +/// The shaders of the pipelines earlier runs used, each by its own key (`used-shaders.txt` +/// beside the DXIL cache): what a title's shader preparation translates. Empty before a run +/// with this list has used a pipeline. +pub fn earlier_used_shaders() -> std::collections::HashSet { + used::parse(&std::fs::read_to_string(crate::gpu::recomp::dxc::cache_dir().join("used-shaders.txt")).unwrap_or_default()) +} + /// The keys of the pipelines earlier runs used (`used-pipelines.txt` beside the DXIL cache): /// what `xcl shaders --precompile --used-only` builds. pub fn earlier_used_keys() -> std::collections::HashSet { used::parse(&std::fs::read_to_string(crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt")).unwrap_or_default()) } +/// Flush pending `used-pipelines.txt` keys on the background journal writer. +pub fn flush_used() { + used::flush(); +} + +/// Flush and join the `used-pipelines.txt` journal worker on normal shutdown. +pub fn shutdown_used() { + used::shutdown(); +} + +/// Best-effort bounded flush of pending `used-pipelines.txt` keys on process termination. +pub fn flush_used_bounded(timeout: std::time::Duration) { + used::flush_bounded(timeout); +} + /// The pipelines a title used, by a hash of their shaders, kept between runs /// (`used-pipelines.txt` beside the DXIL cache, a key a line). /// @@ -432,13 +782,317 @@ pub fn earlier_used_keys() -> std::collections::HashSet { /// instead of waiting for its pipeline, ~2 170 dispatches were skipped in those frames without /// this and 94 – 150 with it. mod used { - use std::collections::HashSet; - use std::io::Write; - use std::sync::{Mutex, OnceLock, RwLock}; + use std::sync::{Arc, Condvar, Mutex, OnceLock, RwLock}; + use std::{ + collections::HashSet, + fmt::Write as _, + io::Write, + path::PathBuf, + thread::JoinHandle, + time::{Duration, Instant}, + }; + + /// Coalesce first-use bursts into a single disk write off the bind lock. + const COALESCE_WINDOW: Duration = Duration::from_millis(25); + /// Flush immediately once a burst reaches this many unique keys. + const BATCH_IMMEDIATE: usize = 32; + + enum Sink { + LazyFile(PathBuf, Option), + #[cfg(test)] + Writer(Box), + } + + impl Sink { + fn write_batch(&mut self, bytes: &[u8]) { + match self { + Self::LazyFile(path, file) => { + if file.is_none() { + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + *file = std::fs::OpenOptions::new().create(true).append(true).open(&*path).ok(); + } + if file.as_mut().is_some_and(|f| f.write_all(bytes).is_err() || f.flush().is_err()) { + *file = None; + } + } + #[cfg(test)] + Self::Writer(w) => { + if w.write_all(bytes).is_ok() { + let _ = w.flush(); + } + } + } + } + } + + fn format_keys(batch: &[u64], buf: &mut String) { + buf.clear(); + buf.reserve(batch.len() * 17); + for &key in batch { + let _ = writeln!(buf, "{key:016x}"); + } + } + + fn append_to_path(path: &PathBuf, bytes: &[u8]) { + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) { + let _ = f.write_all(bytes); + let _ = f.flush(); + } + } + + #[derive(Default)] + struct JournalState { + seen: HashSet, + pending: Vec, + fallback_path: Option, + enqueued_seq: u64, + completed_seq: u64, + flush_now: bool, + closed: bool, + writer_stopped: bool, + } + + struct JournalShared { + state: Mutex, + wake_cv: Condvar, + flushed_cv: Condvar, + } + + struct StopGuard<'a>(&'a JournalShared); + impl Drop for StopGuard<'_> { + fn drop(&mut self) { + self.0.state.lock().unwrap_or_else(|e| e.into_inner()).writer_stopped = true; + self.0.flushed_cv.notify_all(); + } + } + + pub(super) struct Journal { + shared: Arc, + writer: Mutex>>, + } + + impl Journal { + fn new_shared(state: JournalState) -> Arc { + Arc::new(JournalShared { state: Mutex::new(state), wake_cv: Condvar::new(), flushed_cv: Condvar::new() }) + } + + fn in_memory(seen: HashSet) -> Self { + Self { + shared: Self::new_shared(JournalState { seen, writer_stopped: true, ..Default::default() }), + writer: Mutex::new(None), + } + } + + fn with_sink(seen: HashSet, sink: Sink, coalesce: Duration) -> Self { + let fallback_path = match &sink { + Sink::LazyFile(p, _) => Some(p.clone()), + #[cfg(test)] + Sink::Writer(_) => None, + }; + let shared = Self::new_shared(JournalState { seen, fallback_path, ..Default::default() }); + let bg = Arc::clone(&shared); + let writer = std::thread::Builder::new() + .name("xcl-pso-used".into()) + .spawn(move || writer_loop(&bg, sink, coalesce)) + .ok(); + if writer.is_none() { + shared.state.lock().unwrap().writer_stopped = true; + shared.flushed_cv.notify_all(); + } + Self { shared, writer: Mutex::new(writer) } + } + + #[cfg(test)] + pub(super) fn with_writer(w: Box, c: Duration) -> Self { + Self::with_sink(HashSet::new(), Sink::Writer(w), c) + } + + #[cfg(test)] + pub(super) fn with_file(p: PathBuf, c: Duration) -> Self { + Self::with_sink(HashSet::new(), Sink::LazyFile(p, None), c) + } + + #[cfg(test)] + pub(super) fn without_writer(p: PathBuf) -> Self { + Self { + shared: Self::new_shared(JournalState { fallback_path: Some(p), writer_stopped: true, ..Default::default() }), + writer: Mutex::new(None), + } + } + + pub(super) fn note(&self, key: u64) { + if key == 0 { + return; + } + let mut g = self.shared.state.lock().unwrap(); + if !g.seen.insert(key) || g.closed || (g.writer_stopped && g.fallback_path.is_none()) { + return; + } + g.pending.push(key); + g.enqueued_seq += 1; + if matches!(g.pending.len(), 1 | BATCH_IMMEDIATE) { + self.shared.wake_cv.notify_one(); + } + } + + #[cfg(test)] + pub(super) fn noted(&self, key: u64) -> bool { + self.shared.state.lock().unwrap().seen.contains(&key) + } + + pub(super) fn flush(&self) { + let (fallback, batch) = { + let mut g = self.shared.state.lock().unwrap(); + let target = g.enqueued_seq; + if g.completed_seq >= target || (g.writer_stopped && g.pending.is_empty()) { + return; + } + if !g.writer_stopped { + g.flush_now = true; + self.shared.wake_cv.notify_one(); + while g.completed_seq < target && !g.writer_stopped { + g = self.shared.flushed_cv.wait(g).unwrap(); + } + } + if g.pending.is_empty() { + return; + } + let batch = std::mem::take(&mut g.pending); + g.completed_seq = g.enqueued_seq; + (g.fallback_path.clone(), batch) + }; + if let Some(path) = fallback { + let mut buf = String::new(); + format_keys(&batch, &mut buf); + append_to_path(&path, buf.as_bytes()); + } + } + + pub(super) fn flush_bounded(&self, timeout: Duration) { + let (fallback, batch) = { + let mut g = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + let target = g.enqueued_seq; + if g.completed_seq >= target || (g.writer_stopped && g.pending.is_empty()) { + return; + } + g.flush_now = true; + self.shared.wake_cv.notify_one(); + let deadline = Instant::now() + timeout; + while g.completed_seq < target && !g.writer_stopped { + let Some(rem) = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) else { break }; + let (guard, res) = self.shared.flushed_cv.wait_timeout(g, rem).unwrap_or_else(|e| e.into_inner()); + g = guard; + if res.timed_out() { + break; + } + } + if g.pending.is_empty() { + return; + } + // Worker timed out (e.g. blocked on the Windows loader lock during ExitProcess) or + // failed to spawn: take the remaining keys and append them directly so none are lost. + let batch = std::mem::take(&mut g.pending); + g.completed_seq = g.enqueued_seq; + (g.fallback_path.clone(), batch) + }; + if let Some(path) = fallback { + let mut buf = String::new(); + format_keys(&batch, &mut buf); + append_to_path(&path, buf.as_bytes()); + } + } + + pub(super) fn shutdown(&self) { + { + let mut g = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + g.closed = true; + g.flush_now = true; + self.shared.wake_cv.notify_one(); + } + if let Some(h) = self.writer.lock().unwrap_or_else(|e| e.into_inner()).take() { + if h.thread().id() != std::thread::current().id() { + let _ = h.join(); + } + } else { + let mut g = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + while !g.writer_stopped { + g = self.shared.flushed_cv.wait(g).unwrap_or_else(|e| e.into_inner()); + } + } + let (fallback, batch) = { + let mut g = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + if g.pending.is_empty() { + return; + } + let batch = std::mem::take(&mut g.pending); + g.completed_seq = g.enqueued_seq; + (g.fallback_path.clone(), batch) + }; + if let Some(path) = fallback { + let mut buf = String::new(); + format_keys(&batch, &mut buf); + append_to_path(&path, buf.as_bytes()); + } + } + } + + impl Drop for Journal { + fn drop(&mut self) { + self.shutdown(); + } + } + + fn writer_loop(shared: &JournalShared, mut sink: Sink, coalesce: Duration) { + let _stop = StopGuard(shared); + let mut buf = String::new(); + loop { + let (batch, batch_seq) = { + let mut g = shared.state.lock().unwrap(); + while g.pending.is_empty() && !g.closed { + if std::mem::take(&mut g.flush_now) { + shared.flushed_cv.notify_all(); + } + g = shared.wake_cv.wait(g).unwrap(); + } + if g.pending.is_empty() && g.closed { + break; + } + if !coalesce.is_zero() { + let deadline = Instant::now() + coalesce; + while g.pending.len() < BATCH_IMMEDIATE && !g.flush_now && !g.closed { + let Some(rem) = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) else { break }; + let (guard, res) = shared.wake_cv.wait_timeout(g, rem).unwrap(); + g = guard; + if res.timed_out() { + break; + } + } + } + g.flush_now = false; + (std::mem::take(&mut g.pending), g.enqueued_seq) + }; + format_keys(&batch, &mut buf); + sink.write_batch(buf.as_bytes()); + { + let mut g = shared.state.lock().unwrap(); + g.completed_seq = g.completed_seq.max(batch_seq); + } + shared.flushed_cv.notify_all(); + } + } struct Used { earlier: RwLock>, - now: Mutex<(HashSet, Option)>, + now: Journal, + /// the shaders of each set made in this run, by the set's key; the shaders of the sets + /// used so far and `used-shaders.txt`, where they are kept for the next run + parts: Mutex>>, + shaders: Journal, } /// The keys in a `used-pipelines.txt` (lines that are not a hexadecimal key are passed over). @@ -446,26 +1100,71 @@ mod used { text.lines().filter_map(|l| u64::from_str_radix(l.trim(), 16).ok()).filter(|&k| k != 0).collect() } + static U: OnceLock = OnceLock::new(); + + extern "C" { + fn atexit(f: extern "C" fn()) -> std::ffi::c_int; + } + + extern "C" fn on_process_exit() { + shutdown(); + } + + fn init_from_path(path: PathBuf, coalesce: Duration) -> Used { + let earlier = parse(&std::fs::read_to_string(&path).unwrap_or_default()); + if !earlier.is_empty() { + crate::xlog_info!("D3D12.X: the pipelines of {} shader sets an earlier run used are built ahead of their first use", earlier.len()); + } + let shaders_path = path.with_file_name("used-shaders.txt"); + let earlier_shaders = parse(&std::fs::read_to_string(&shaders_path).unwrap_or_default()); + let now = Journal::with_sink(earlier.clone(), Sink::LazyFile(path, None), coalesce); + let shaders = Journal::with_sink(earlier_shaders, Sink::LazyFile(shaders_path, None), coalesce); + unsafe { + atexit(on_process_exit); + } + Used { earlier: RwLock::new(earlier), now, parts: Default::default(), shaders } + } + fn get() -> &'static Used { - static U: OnceLock = OnceLock::new(); U.get_or_init(|| { // (a test neither reads nor writes the user's file) if cfg!(test) { - return Used { earlier: RwLock::new(HashSet::new()), now: Mutex::new((HashSet::new(), None)) }; - } - let path = crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"); - let earlier = parse(&std::fs::read_to_string(&path).unwrap_or_default()); - if !earlier.is_empty() { - crate::xlog_info!("D3D12.X: the pipelines of {} shader sets an earlier run used are built ahead of their first use", earlier.len()); - } - if let Some(dir) = path.parent() { - let _ = std::fs::create_dir_all(dir); + #[cfg(test)] + if let Some(p) = std::env::var_os("XCL_TEST_USED_STATIC_PATH") { + return init_from_path(PathBuf::from(p), Duration::from_secs(60)); + } + return Used { + earlier: RwLock::new(HashSet::new()), + now: Journal::in_memory(HashSet::new()), + parts: Default::default(), + shaders: Journal::in_memory(HashSet::new()), + }; } - let file = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok(); - Used { now: Mutex::new((earlier.clone(), file)), earlier: RwLock::new(earlier) } + init_from_path(crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"), COALESCE_WINDOW) }) } + pub fn flush() { + if let Some(u) = U.get() { + u.now.flush(); + u.shaders.flush(); + } + } + + pub fn shutdown() { + if let Some(u) = U.get() { + u.now.shutdown(); + u.shaders.shutdown(); + } + } + + pub fn flush_bounded(timeout: Duration) { + if let Some(u) = U.get() { + u.now.flush_bounded(timeout); + u.shaders.flush_bounded(timeout); + } + } + /// An earlier run used a pipeline of these shaders. pub fn known(key: u64) -> bool { key != 0 && get().earlier.read().unwrap().contains(&key) @@ -476,18 +1175,32 @@ mod used { if key == 0 { return; } - let mut g = get().now.lock().unwrap(); - if g.0.insert(key) { - if let Some(f) = g.1.as_mut() { - let _ = writeln!(f, "{key:016x}"); - } + get().now.note(key); + // its shaders, each once (also those of a set an earlier run used: the list of + // shaders is younger than the list of sets) + let parts = get().parts.lock().unwrap().get(&key).cloned().unwrap_or_default(); + for part in parts { + get().shaders.note(part); } } + /// The shaders of the set `key`, each by its own key (`real::shader_key`). + pub fn parts(key: u64, shaders: Vec) { + if key != 0 { + get().parts.lock().unwrap().entry(key).or_insert(shaders); + } + } + + /// (tests) This run used the shader `key`. + #[cfg(test)] + pub fn shader_noted(key: u64) -> bool { + get().shaders.noted(key) + } + /// (tests) This run used a pipeline of these shaders. #[cfg(test)] pub fn noted(key: u64) -> bool { - get().now.lock().unwrap().0.contains(&key) + get().now.noted(key) } #[cfg(test)] @@ -517,9 +1230,9 @@ fn preload() -> Option<&'static Preload> { }) .as_ref()?; STARTED.call_once(|| { - let n = (crate::gpu::recomp::dxc::compile_threads() / 4).clamp(2, 4); + let n = preload_worker_threads(); for k in 0..n { - let _ = std::thread::Builder::new().name(format!("xcl-pso-pre-{k}")).stack_size(64 << 20).spawn(move || { + let _ = std::thread::Builder::new().name(format!("xcl-pso-pre-{k}")).stack_size(16 << 20).spawn(move || { unsafe { use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); @@ -540,6 +1253,41 @@ fn preload() -> Option<&'static Preload> { drop_unstarted_job(&p); continue; } + // Never speculatively compile deprioritized/heavy/BVH/spared pipelines at + // THREAD_PRIORITY_LOWEST; leave `p.job` untouched until actually bound. + if p.deprioritized.load(Ordering::Acquire) + || p.bvh_traversal.load(Ordering::Acquire) + || p.spared.load(Ordering::Acquire) + { + continue; + } + // Pause speculative preload whenever ANY `wanted` pipeline is actively + // queued/in-flight or free RAM/commit headroom is below 6 GiB; leave `p.job` + // untouched so binds can take it immediately. + while !p.orphan.load(Ordering::Acquire) + && !p.demand.lock().unwrap().wanted + && p.job.lock().unwrap().is_some() + { + let avail = mem_throttle_enabled().then(avail_commit_bytes).flatten(); + let low_mem = should_pause_preload(avail); + if !should_pause_preload_with_demand(avail, wanted_active()) { + break; + } + if low_mem { + static PAUSED_LOG: std::sync::Once = std::sync::Once::new(); + PAUSED_LOG.call_once(|| { + crate::xlog_info!( + "D3D12.X: pausing speculative PSO preload under low RAM/commit headroom (< 6 GiB, {} MiB free)", + avail.unwrap_or(0) >> 20 + ); + }); + } + std::thread::sleep(std::time::Duration::from_millis(25)); + } + if p.orphan.load(Ordering::Acquire) { + drop_unstarted_job(&p); + continue; + } // (None: a bind took it and builds it itself) let job = p.job.lock().unwrap().take(); if let Some(job) = job { @@ -560,6 +1308,20 @@ fn preload() -> Option<&'static Preload> { mod used_tests { use super::*; + /// The shaders of a set are kept when a pipeline of the set is used, each once, and not + /// before: a set that is only made keeps nothing. + #[test] + fn the_shaders_of_a_used_set_are_kept_for_the_next_run() { + let (set, other) = (0x5e70_0000_0000_0001u64, 0x5e70_0000_0000_0003u64); + let (vs, ps, cs) = (0x5e70_0000_0000_0011u64, 0x5e70_0000_0000_0013u64, 0x5e70_0000_0000_0015u64); + shaders_of(set, vec![vs, ps]); + shaders_of(other, vec![cs]); + assert!(!used::shader_noted(vs) && !used::shader_noted(ps), "made, not used yet"); + used::note(set); + assert!(used::shader_noted(vs) && used::shader_noted(ps), "the shaders of the used set"); + assert!(!used::shader_noted(cs), "the other set was not used"); + } + /// A PC call that has kept one of the title's threads for long holds the title, a short one /// does not, and the hold ends with the call. #[test] @@ -688,7 +1450,7 @@ mod used_tests { #[test] fn a_pipeline_a_submit_needs_is_built_before_the_queue() { let order = Arc::new(Mutex::new(Vec::new())); - let backlog = 8 * crate::gpu::recomp::dxc::compile_threads(); + let backlog = 8 * pso_worker_threads(); let standins: Vec = (0..=backlog).map(|i| 0x7E57_E000usize + i).collect(); for &standin in &standins { let order = order.clone(); @@ -787,27 +1549,268 @@ mod used_tests { assert!(keys.contains(&0xff) && keys.contains(&0x1a2b)); } - /// A lazy pipeline of shaders an earlier run used is built without a bind; another one is - /// built only at its first use, and that use is kept for the next run. #[test] - fn a_pipeline_an_earlier_run_used_is_built_ahead_of_its_first_use() { - let (known, unknown) = (0x7E57_7001usize, 0x7E57_7002usize); - let (known_key, unknown_key) = (0x5EED_0001u64, 0x5EED_0002u64); - used::earlier_run_used(known_key); - submit_lazy(known, false, Box::new(|| 0x4321), known_key); - submit_lazy(unknown, false, Box::new(|| 0x4322), unknown_key); - let start = std::time::Instant::now(); - while is_pending(known) && start.elapsed() < std::time::Duration::from_secs(10) { - std::thread::sleep(std::time::Duration::from_millis(5)); + fn used_note_does_not_block_on_slow_writer() { + use std::{io::Write, time::Duration}; + struct Blocking(Option>, mpsc::Receiver<()>, Arc>>); + impl Write for Blocking { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if let Some(tx) = self.0.take() { + let _ = tx.send(()); + let _ = self.1.recv(); + } + self.2.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } } - assert!(!is_pending(known), "built by the workers that build ahead, with no bind"); - assert_eq!(resolve(known), 0x4321); - assert!(is_pending(unknown), "nobody used it and no earlier run did"); - assert!(!used::noted(unknown_key)); - assert_eq!(resolve_wait(unknown), 0x4322); - assert!(used::noted(unknown_key) && used::noted(known_key), "a first use is kept for the next run"); - released(known); - released(unknown); + let ((entered_tx, entered_rx), (release_tx, release_rx)) = (mpsc::channel(), mpsc::channel()); + let out = Arc::new(Mutex::new(Vec::new())); + let j = used::Journal::with_writer(Box::new(Blocking(Some(entered_tx), release_rx, out.clone())), Duration::ZERO); + j.note(0x1111); + entered_rx.recv_timeout(Duration::from_secs(5)).expect("writer entered write_all"); + j.note(0x2222); + j.note(0x3333); + assert!(j.noted(0x1111) && j.noted(0x2222) && j.noted(0x3333), "note/noted must not block on writer I/O"); + release_tx.send(()).unwrap(); + j.flush(); + assert_eq!(used::parse(std::str::from_utf8(&out.lock().unwrap()).unwrap()), [0x1111, 0x2222, 0x3333].into()); + } + + #[test] + fn used_burst_coalesces_writes_and_deduplicates_keys() { + use std::{io::Write, time::Duration}; + struct Counting(Arc)>>); + impl Write for Counting { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let mut g = self.0.lock().unwrap(); + g.0 += 1; + g.1.extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let rec = Arc::new(Mutex::new((0usize, Vec::new()))); + let j = used::Journal::with_writer(Box::new(Counting(rec.clone())), Duration::from_millis(500)); + for k in (0u64..=40).chain(0u64..=40) { + j.note(k); + } + j.flush(); + let (writes, bytes) = { + let g = rec.lock().unwrap(); + (g.0, g.1.clone()) + }; + let text = String::from_utf8(bytes).unwrap(); + assert!(writes >= 1 && writes < 40, "expected coalesced writes (< 40), got {writes}"); + assert_eq!(text.lines().count(), 40); + assert_eq!(used::parse(&text), (1u64..=40).collect()); + } + + #[test] + fn used_flush_drop_lazy_file_and_io_error_are_graceful() { + use std::{io::Write, time::Duration}; + let dir = std::env::temp_dir().join(format!("xcl-used-journal-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("nested").join("used-pipelines.txt"); + let j = used::Journal::with_file(path.clone(), Duration::from_secs(5)); + assert!(!dir.exists() && !path.exists(), "dir/file must open lazily on first batch write"); + j.note(0xAA01); + j.note(0xAA02); + j.flush(); + assert_eq!(used::parse(&std::fs::read_to_string(&path).unwrap()), [0xAA01, 0xAA02].into()); + j.note(0xAA03); + drop(j); + assert_eq!(used::parse(&std::fs::read_to_string(&path).unwrap()), [0xAA01, 0xAA02, 0xAA03].into()); + let _ = std::fs::remove_dir_all(&dir); + + struct Failing(Arc); + impl Write for Failing { + fn write(&mut self, _: &[u8]) -> std::io::Result { + self.0.fetch_add(1, Ordering::Relaxed); + Err(std::io::Error::other("disk full")) + } + fn flush(&mut self) -> std::io::Result<()> { + Err(std::io::Error::other("disk full")) + } + } + let attempts = Arc::new(AtomicUsize::new(0)); + let j = used::Journal::with_writer(Box::new(Failing(attempts.clone())), Duration::ZERO); + j.note(0xBAD1); + j.note(0xBAD2); + j.flush(); + j.note(0xBAD3); + j.flush(); + assert!(attempts.load(Ordering::Acquire) >= 1 && j.noted(0xBAD1) && j.noted(0xBAD2) && j.noted(0xBAD3)); + } + + #[test] + fn used_static_once_lock_flushes_on_process_exit() { + use std::time::{Duration, Instant}; + if let Some(path) = std::env::var_os("XCL_TEST_USED_STATIC_PATH") { + let mode = std::env::var("XCL_TEST_USED_EXIT_MODE").unwrap_or_default(); + match mode.as_str() { + "normal" => { + used::note(0xE001); + used::note(0xE002); + return; + } + "flush" => { + used::note(0xE003); + flush_used(); + let text = std::fs::read_to_string(&path).expect("flush_used must flush pending keys"); + assert_eq!(used::parse(&text), [0xE003].into()); + return; + } + "explicit" => { + used::note(0xE004); + shutdown_used(); + let text = std::fs::read_to_string(&path).expect("shutdown_used must flush before exit"); + assert_eq!(used::parse(&text), [0xE004].into()); + shutdown_used(); + flush_used_bounded(Duration::from_millis(50)); + return; + } + "bounded" => { + used::note(0xE005); + flush_used_bounded(Duration::from_secs(5)); + let text = std::fs::read_to_string(&path).expect("flush_used_bounded must flush before termination"); + assert_eq!(used::parse(&text), [0xE005].into()); + return; + } + other => panic!("unexpected mode {other}"), + } + } + let exe = std::env::current_exe().unwrap(); + let dir = std::env::temp_dir().join(format!("xcl-used-exit-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for (mode, expected) in [ + ("normal", &[0xE001u64, 0xE002][..]), + ("flush", &[0xE003u64][..]), + ("explicit", &[0xE004u64][..]), + ("bounded", &[0xE005u64][..]), + ] { + let path = dir.join(mode).join("used-pipelines.txt"); + let start = Instant::now(); + let status = std::process::Command::new(&exe) + .args(["--exact", "hle::d3d12x::pso_async::used_tests::used_static_once_lock_flushes_on_process_exit", "--nocapture"]) + .env("XCL_TEST_USED_STATIC_PATH", &path) + .env("XCL_TEST_USED_EXIT_MODE", mode) + .status() + .unwrap(); + assert!(status.success(), "child ({mode}) failed: {status}"); + assert!(start.elapsed() < Duration::from_secs(10), "child ({mode}) waited for coalesce timer"); + let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("child ({mode}) lost keys on exit: {e}")); + assert_eq!(used::parse(&text), expected.iter().copied().collect(), "child ({mode}) keys mismatch"); + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn used_flush_bounded_timeout_and_spawn_failure_fallback_are_sound() { + use std::{io::Write, time::Duration}; + // 1. Slow writer finishing batch 1 after `flush_bounded` already drained batch 2 must not + // regress `completed_seq` below `enqueued_seq` (which would hang a later `flush()`). + struct BlockingOnce(Option>, mpsc::Receiver<()>, Option>, Arc>>); + impl Write for BlockingOnce { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if let Some(tx) = self.0.take() { + let _ = tx.send(()); + let _ = self.1.recv_timeout(Duration::from_secs(5)); + } + self.3.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + if let Some(tx) = self.2.take() { + let _ = tx.send(()); + } + Ok(()) + } + } + let ((entered_tx, entered_rx), (release_tx, release_rx), (wrote_tx, wrote_rx)) = (mpsc::channel(), mpsc::channel(), mpsc::channel()); + let out = Arc::new(Mutex::new(Vec::new())); + let j = Arc::new(used::Journal::with_writer(Box::new(BlockingOnce(Some(entered_tx), release_rx, Some(wrote_tx), out.clone())), Duration::ZERO)); + j.note(0xC001); + entered_rx.recv_timeout(Duration::from_secs(5)).expect("writer entered batch 1"); + j.note(0xC002); + j.flush_bounded(Duration::from_millis(20)); + release_tx.send(()).unwrap(); + wrote_rx.recv_timeout(Duration::from_secs(5)).expect("writer finished batch 1"); + std::thread::sleep(Duration::from_millis(25)); + let (done_tx, done_rx) = mpsc::channel(); + let j2 = Arc::clone(&j); + let flusher = std::thread::spawn(move || { + j2.flush(); + let _ = done_tx.send(()); + }); + done_rx.recv_timeout(Duration::from_secs(5)).expect("flush() must not hang when completed_seq stays monotonic"); + flusher.join().unwrap(); + drop(j); + assert!(used::parse(std::str::from_utf8(&out.lock().unwrap()).unwrap()).contains(&0xC001)); + + // 2. When writer spawn fails (`writer_stopped == true` with `fallback_path`), `note()` + // still queues keys so `flush_bounded()` and `shutdown()` persist them directly. + let dir = std::env::temp_dir().join(format!("xcl-used-nospawn-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let p_bounded = dir.join("bounded").join("used-pipelines.txt"); + let j_b = used::Journal::without_writer(p_bounded.clone()); + j_b.note(0xF001); + j_b.note(0xF002); + j_b.flush_bounded(Duration::from_millis(20)); + assert_eq!(used::parse(&std::fs::read_to_string(&p_bounded).unwrap()), [0xF001, 0xF002].into()); + + let p_shutdown = dir.join("shutdown").join("used-pipelines.txt"); + let j_s = used::Journal::without_writer(p_shutdown.clone()); + j_s.note(0xF003); + j_s.shutdown(); + assert_eq!(used::parse(&std::fs::read_to_string(&p_shutdown).unwrap()), [0xF003].into()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A lazy pipeline of shaders an earlier run used is built without a bind; another one is + /// built only at its first use, and that use is kept for the next run. + #[test] + fn a_pipeline_an_earlier_run_used_is_built_ahead_of_its_first_use() { + let (known, unknown) = (0x7E57_7001usize, 0x7E57_7002usize); + let (known_key, unknown_key) = (0x5EED_0001u64, 0x5EED_0002u64); + used::earlier_run_used(known_key); + submit_lazy(known, false, Box::new(|| 0x4321), known_key); + submit_lazy(unknown, false, Box::new(|| 0x4322), unknown_key); + let start = std::time::Instant::now(); + while is_pending(known) && start.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(!is_pending(known), "built by the workers that build ahead, with no bind"); + assert_eq!(resolve(known), 0x4321); + assert!(is_pending(unknown), "nobody used it and no earlier run did"); + assert!(!used::noted(unknown_key)); + assert_eq!(resolve_wait(unknown), 0x4322); + assert!(used::noted(unknown_key) && used::noted(known_key), "a first use is kept for the next run"); + released(known); + released(unknown); + } + + /// What a pipeline's first use tells (a graphics one's description: `gfx_records`) is told + /// once, at that use, not when it is made or built. + #[test] + fn a_first_use_is_told_once() { + let (standin, key) = (0x7E57_7011usize, 0x5EED_0011u64); + let told = Arc::new(AtomicUsize::new(0)); + submit_lazy(standin, true, Box::new(|| 0x4331), key); + let t = told.clone(); + on_first_use(standin, Box::new(move || { t.fetch_add(1, Ordering::SeqCst); })); + assert_eq!(told.load(Ordering::SeqCst), 0, "not at its making"); + assert_eq!(resolve_wait(standin), 0x4331); + assert_eq!(told.load(Ordering::SeqCst), 1); + assert_eq!(resolve(standin), 0x4331); + assert_eq!(resolve_wait(standin), 0x4331); + assert_eq!(told.load(Ordering::SeqCst), 1, "once"); + on_first_use(0x7E57_7012, Box::new(|| unreachable!("no such pipeline"))); + released(standin); } static WORKER_SATURATION_LOCK: Mutex<()> = Mutex::new(()); @@ -827,7 +1830,7 @@ mod used_tests { } } - let n = crate::gpu::recomp::dxc::compile_threads(); + let n = pso_worker_threads(); let (started_tx, started_rx) = mpsc::channel(); let gate = Arc::new((Mutex::new(false), Condvar::new())); let mut blockers = Vec::with_capacity(n); @@ -914,6 +1917,112 @@ mod used_tests { calls.end(5, 9, t_stale); } + /// With `XCL_PSO_WAIT_MS`, a submit's wait for a late pipeline that no worker can start (all + /// are busy) neither ends with the stand-in nor waits for a free worker: after the budget it + /// builds the pipeline itself. + #[test] + fn a_submit_builds_a_late_pipeline_no_worker_has_started() { + let _sat = WORKER_SATURATION_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use std::time::{Duration, Instant}; + let n = pso_worker_threads(); + let (started_tx, started_rx) = mpsc::channel(); + let gate = Arc::new((Mutex::new(false), Condvar::new())); + let mut blockers = Vec::with_capacity(n); + for k in 0..n { + let standin = 0x7E57_A500usize + k; + let (tx, g) = (started_tx.clone(), gate.clone()); + submit(standin, false, Box::new(move || { + let _ = tx.send(()); + let mut open = g.0.lock().unwrap(); + while !*open { + open = g.1.wait(open).unwrap(); + } + 0xA500 + k + })); + blockers.push(standin); + } + for _ in 0..n { + started_rx.recv_timeout(Duration::from_secs(10)).expect("workers saturated"); + } + let target = 0x7E57_A5FFusize; + submit(target, true, Box::new(|| 0xA5FF)); + set_wait_budget_for_test(Some(Duration::from_millis(30))); + assert_eq!(resolve_wait(target), target, "a bind as the title records: past the budget, late"); + let t = Instant::now(); + wait_for_submit(target); + let took = t.elapsed(); + set_wait_budget_for_test(None); + let built = resolve(target); + *gate.0.lock().unwrap() = true; + gate.1.notify_all(); + for standin in blockers { + let start = Instant::now(); + while is_pending(standin) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(2)); + } + let _ = released(standin); + } + let _ = released(target); + assert_eq!(built, 0xA5FF, "the submit's wait ended without the pipeline"); + assert!(took < Duration::from_secs(5), "the submit waited for a free worker ({took:?})"); + } + + /// With `XCL_PSO_WAIT_MS`, a submit waits for a pipeline a worker is building at most + /// `SUBMIT_WAIT_MOST`, then goes on (with the stand-in) and counts it. + #[test] + fn a_submit_waits_for_a_build_on_a_worker_no_longer_than_its_bound() { + let _sat = WORKER_SATURATION_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use std::time::{Duration, Instant}; + let standin = 0x7E57_A600usize; + let (started_tx, started_rx) = mpsc::channel(); + let gate = Arc::new((Mutex::new(false), Condvar::new())); + let g = gate.clone(); + submit(standin, true, Box::new(move || { + let _ = started_tx.send(()); + let mut open = g.0.lock().unwrap(); + while !*open { + open = g.1.wait(open).unwrap(); + } + 0xA600 + })); + started_rx.recv_timeout(Duration::from_secs(10)).expect("a worker builds it"); + set_wait_budget_for_test(Some(Duration::from_millis(20))); + set_submit_wait_for_test(Some(Duration::from_millis(300))); + let gave_up = SUBMIT_GAVE_UP.load(Ordering::Relaxed); + let t = Instant::now(); + wait_for_submit(standin); + let took = t.elapsed(); + let pending = is_pending(standin); + let counted = SUBMIT_GAVE_UP.load(Ordering::Relaxed) > gave_up; + set_wait_budget_for_test(None); + set_submit_wait_for_test(None); + *gate.0.lock().unwrap() = true; + gate.1.notify_all(); + let start = Instant::now(); + while is_pending(standin) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(2)); + } + let _ = released(standin); + assert!(pending, "the build ended before the bound"); + assert!(took >= Duration::from_millis(300) && took < Duration::from_secs(5), "the submit waited {took:?}"); + assert!(counted, "the submit that went on without its pipeline was not counted"); + } + + /// A build that panics on a worker ends as a failed one: binds and submits waiting for it go on. + #[test] + fn a_build_that_panics_on_a_worker_ends_as_failed() { + use std::time::{Duration, Instant}; + let standin = 0x7E57_A700usize; + submit(standin, true, Box::new(|| panic!("a build that panics (test)"))); + let start = Instant::now(); + while is_pending(standin) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(2)); + } + let pending = is_pending(standin); + let _ = released(standin); + assert!(!pending, "the panicked build never ended"); + } + #[test] fn released_queued_pipeline_drops_job_immediately_before_workers_drain() { let _sat = WORKER_SATURATION_LOCK.lock().unwrap_or_else(|e| e.into_inner()); @@ -935,7 +2044,7 @@ mod used_tests { } // Saturate normal workers and verify released() drops the queued job immediately. - let n = crate::gpu::recomp::dxc::compile_threads(); + let n = pso_worker_threads(); let (started_tx, started_rx) = mpsc::channel(); let gate = Arc::new((Mutex::new(false), Condvar::new())); let open_normal = OpenGate(gate.clone()); @@ -977,7 +2086,7 @@ mod used_tests { } // Saturate preload workers and verify released() drops the preloaded job immediately. - let m = (crate::gpu::recomp::dxc::compile_threads() / 4).clamp(2, 4); + let m = preload_worker_threads(); let (p_tx, p_rx) = mpsc::channel(); let p_gate = Arc::new((Mutex::new(false), Condvar::new())); let open_pre = OpenGate(p_gate.clone()); @@ -1025,7 +2134,7 @@ mod used_tests { } fn entry(pso: usize) -> Option> { - PENDING.lock().unwrap().as_ref()?.get(&pso).cloned() + PENDING.read().unwrap().as_ref()?.get(&pso).cloned() } impl Pending { @@ -1038,6 +2147,35 @@ impl Pending { } } +/// Register a permanently gated stand-in pipeline (e.g. RT compute held back under +/// `XCL_RT_GATE=hold`) with `done = true`, `job = None`, `sent = true`, and `real = 0`. +/// Never enqueues a worker job, never translates or calls `CreateComputePipelineState`, maps +/// `standin -> driver` cleanly via `stand()` for `SetPipelineState`/`resolve`/`resolve_wait`, +/// reports `is_pending(standin) == false`, and releases cleanly via `released()`. +pub fn submit_gated(standin: usize, driver: usize) { + let p = Arc::new(Pending { + job: Mutex::new(None), + sent: std::sync::atomic::AtomicBool::new(true), + real: AtomicUsize::new(0), + driver: AtomicUsize::new(driver), + done: Mutex::new(true), + cv: Condvar::new(), + compute: true, + key: 0, + used: Default::default(), + orphan: Default::default(), + late: std::sync::atomic::AtomicBool::new(true), + spared: std::sync::atomic::AtomicBool::new(false), + bvh_traversal: std::sync::atomic::AtomicBool::new(true), + deprioritized: std::sync::atomic::AtomicBool::new(true), + waited_frame: AtomicU64::new(UNWAITED), + wanted_state: AtomicU8::new(WANTED_DONE), + demand: Default::default(), + on_use: Default::default(), + }); + PENDING.write().unwrap().get_or_insert_with(HashMap::new).insert(standin, p); +} + /// Stand-in `standin` is no driver object (`standin::shell`): binds get `driver` in its place. /// Told before the title has the stand-in. pub fn shared(standin: usize, driver: usize) { @@ -1053,8 +2191,12 @@ pub fn resolve(pso: usize) -> usize { p.note_use(); match p.real.load(Ordering::Acquire) { 0 => { - // a lazy one is wanted now: to the workers + // a lazy one is wanted now: to the workers (unless RT-gated while BVH traversal is + // held back, so gated RT shaders never enqueue or burn driver compile RAM) let stand = p.stand(pso); + if p.bvh_traversal.load(Ordering::Acquire) && !super::real::bvh_traversal_allowed() { + return stand; + } if !p.sent.swap(true, Ordering::AcqRel) { enqueue(p); } @@ -1064,48 +2206,338 @@ pub fn resolve(pso: usize) -> usize { } } -/// `resolve`, waiting for a pipeline still being built – built here if no worker has started -/// it yet (a queue of a title's hundreds of pipelines must not hold up the one it binds now). +/// `resolve`, waiting for a pipeline still being built: +/// - non-spared memory-writing producer compute pipelines always wait (never skipped by +/// `XCL_PSO_FRAME_BUDGET_MS`, because skipping a producer compute dispatch corrupts title memory); +/// - graphics pipelines wait within the per-frame graphics window (`XCL_PSO_FRAME_BUDGET_MS`, +/// default 12 s) and stamp `waited_frame` so a slow graphics PSO stalls at most one frame; +/// - `spared` (`image_only`) and `bvh_traversal` compute pipelines use `resolve_spared`. pub fn resolve_wait(pso: usize) -> usize { resolve_wait_for(pso, wait_budget()) } -/// `resolve_wait`, waiting at most `budget` (None: until the pipeline is built). +/// A call put off to the submit is recorded now: wait for its compute pipeline to be built, +/// whether a bind already found it `late` or not. Its segment lies between the list's other work, +/// whose labels and fence signals the title reads as "done": recorded with the stand-in, the +/// dispatch is left out while they still fire. The submitting thread is held for that time +/// (`title_held`), as a bind's wait holds it. A build that fails still gives the stand-in, and a +/// program binds do not wait for (`image_only`) is not waited for. +/// +/// Unset `XCL_PSO_WAIT_MS`: until the pipeline is built, as a bind waits. Set: the build is left +/// to the workers for that long first, as a bind leaves it (their turns for big compiles); one no +/// worker has started by then is built here. One a worker builds is waited for at most +/// `SUBMIT_WAIT_MOST`, and the call then goes on with the stand-in (logged and counted): +/// `title_held` stops only `kernelx::Sleep` and the GPU-wait watchdog, not every clock a title +/// reads. +pub fn wait_for_submit(pso: usize) { + let Some(budget) = wait_budget() else { + let _ = resolve_wait_for(pso, None); + return; + }; + let Some(p) = entry(pso) else { return }; + if !p.compute || p.spared.load(Ordering::Acquire) || *p.done.lock().unwrap() { + return; + } + p.note_use(); + let _held = Held::new(); + let _prof = super::prof::span(super::prof::Kind::ComputePipelineWait); + if !p.sent.swap(true, Ordering::AcqRel) { + enqueue(p.clone()); + } + p.want(); + let built = |p: &Pending, most: std::time::Duration| *p.cv.wait_timeout_while(p.done.lock().unwrap(), most, |d| !*d).unwrap().0; + if built(&p, budget) { + return; + } + // no worker has started it: built here, as without the budget + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + return complete(&p, job()); + } + let most = submit_wait_most(); + if !built(&p, most) { + let n = SUBMIT_GAVE_UP.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 16 || n.is_power_of_two() { + crate::xlog_warn!("D3D12.X: deferred dispatch skipped after waiting {} s for its pipeline ({n} so far)", most.as_secs_f32()); + } + } +} + +/// put-off calls that went on with the stand-in after `SUBMIT_WAIT_MOST` +static SUBMIT_GAVE_UP: AtomicUsize = AtomicUsize::new(0); + +/// How long a submit waits for a pipeline a worker builds, with `XCL_PSO_WAIT_MS` set: as long as +/// a retail title's watchdog lets its main thread stand still (30 s, #891). +const SUBMIT_WAIT_MOST: std::time::Duration = std::time::Duration::from_secs(30); + +fn submit_wait_most() -> std::time::Duration { + #[cfg(test)] + if let Some(b) = SUBMIT_WAIT_FOR_TEST.with(|b| b.get()) { + return b; + } + SUBMIT_WAIT_MOST +} + +#[cfg(test)] +thread_local! { + /// `SUBMIT_WAIT_MOST` for the submits of this test thread + static SUBMIT_WAIT_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +fn set_submit_wait_for_test(most: Option) { + SUBMIT_WAIT_FOR_TEST.with(|b| b.set(most)); +} + +/// `resolve_wait`, waiting at most `budget` per pipeline (and for graphics pipelines, at most +/// the remaining per-frame graphics window). fn resolve_wait_for(pso: usize, budget: Option) -> usize { let Some(p) = entry(pso) else { return pso }; p.note_use(); - if p.spared.load(Ordering::Acquire) { + if p.spared.load(Ordering::Acquire) || p.bvh_traversal.load(Ordering::Acquire) { return resolve_spared(&p, pso); } - // (the title's thread is held from here until the pipeline is built or the budget is over) - let _held = (!*p.done.lock().unwrap()).then(Held::new); - if let Some(budget) = budget { - return resolve_within(&p, pso, budget); + let frame = super::present::presents(); + // Memory-writing producer compute PSOs (`!spared && !bvh_traversal`) are never skipped by the + // per-frame graphics wait window: skipping a producer dispatch leaves title memory/tables + // uninitialized and causes Window-3 pointer corruption several frames later. + let fcap = frame_budget_for_kind(frame_budget_policy(), p.compute, frame); + resolve_wait_in(&p, pso, budget, fcap, frame, &FRAME_BUDGET_GFX) +} + +/// Default per-frame graphics pipeline wait window (`12 s`). +const DEFAULT_FRAME_BUDGET_MS: u64 = 12_000; +/// Presented-frame threshold after which an opt-in `XCL_GFX_PSO_FRAME_BUDGET_MS` cap takes effect +/// for graphics-only bind waits, leaving initial boot/menu frames at `DEFAULT_FRAME_BUDGET_MS`. +const GAMEPLAY_FRAME_BUDGET_START_FRAME: u64 = 60; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum FrameBudgetPolicy { + /// Default policy when neither env var is set: keeps `DEFAULT_FRAME_BUDGET_MS` (`12 s`) + /// across all frames so cold graphics pipelines are never prematurely skipped during loading. + Default, + /// Explicit override via `XCL_PSO_FRAME_BUDGET_MS`: applies uniformly across all frames. + Explicit(Option), + /// Opt-in override via `XCL_GFX_PSO_FRAME_BUDGET_MS`: keeps `DEFAULT_FRAME_BUDGET_MS` while + /// `frame < GAMEPLAY_FRAME_BUDGET_START_FRAME`, then caps graphics-only bind waits. + OptInGameplay(Option), +} + +fn parse_budget_override(val: Option<&str>) -> Option> { + let raw = val.map(str::trim).filter(|s| !s.is_empty())?; + if raw.eq_ignore_ascii_case("off") || raw.eq_ignore_ascii_case("none") { + return Some(None); } - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - complete(&p, job()); + raw.parse::().ok().map(|ms| Some(std::time::Duration::from_millis(ms))) +} + +/// Parses `XCL_PSO_FRAME_BUDGET_MS` (uniform override) and `XCL_GFX_PSO_FRAME_BUDGET_MS` +/// (opt-in post-boot graphics cap) into a `FrameBudgetPolicy`. +fn parse_frame_budget_policy_from(pso_env: Option<&str>, gfx_env: Option<&str>) -> FrameBudgetPolicy { + if let Some(cap) = parse_budget_override(pso_env) { + return FrameBudgetPolicy::Explicit(cap); } - p.want(); - let mut done = p.done.lock().unwrap(); - while !*done { - done = p.cv.wait(done).unwrap(); + if let Some(cap) = parse_budget_override(gfx_env) { + return FrameBudgetPolicy::OptInGameplay(cap); } - match p.real.load(Ordering::Acquire) { + FrameBudgetPolicy::Default +} + +/// Effective graphics pipeline wait window for `frame` under `policy`. +fn frame_budget_for(policy: FrameBudgetPolicy, frame: u64) -> Option { + match policy { + FrameBudgetPolicy::Default => Some(std::time::Duration::from_millis(DEFAULT_FRAME_BUDGET_MS)), + FrameBudgetPolicy::Explicit(cap) => cap, + FrameBudgetPolicy::OptInGameplay(cap) => { + if frame < GAMEPLAY_FRAME_BUDGET_START_FRAME { + Some(std::time::Duration::from_millis(DEFAULT_FRAME_BUDGET_MS)) + } else { + cap + } + } + } +} + +/// Effective per-frame wait cap for a pipeline bind: producer compute pipelines are never capped. +fn frame_budget_for_kind(policy: FrameBudgetPolicy, compute: bool, frame: u64) -> Option { + if compute { None } else { frame_budget_for(policy, frame) } +} + +/// Parses `XCL_PSO_FRAME_BUDGET_MS` for frame 0 (boot/default): unset/empty defaults to +/// `12_000 ms` (`12 s`), `0` skips waiting immediately, `off` / `none` disables the per-frame cap, +/// and a positive integer sets the per-frame graphics wait window in milliseconds. +#[cfg(test)] +fn parse_frame_budget(val: Option<&str>) -> Option { + frame_budget_for(parse_frame_budget_policy_from(val, None), 0) +} + +fn frame_budget_policy() -> FrameBudgetPolicy { + static B: OnceLock = OnceLock::new(); + *B.get_or_init(|| { + let pso_env = std::env::var("XCL_PSO_FRAME_BUDGET_MS").ok(); + let gfx_env = std::env::var("XCL_GFX_PSO_FRAME_BUDGET_MS").ok(); + parse_frame_budget_policy_from(pso_env.as_deref(), gfx_env.as_deref()) + }) +} + +static FRAME_BUDGET_GFX: Mutex = Mutex::new(FrameWaitBudget::new()); + +/// Waits for `p` within both an optional per-PSO cap (`budget`) and an optional per-frame +/// graphics window (`frame_cap` tracked in `frame_state` for `frame`). Builds run on +/// `xcl-pso-*` workers (prioritized as `wanted`) so the caller always wakes when the window +/// expires; once a graphics PSO has spent budget on a frame (`waited_frame`), subsequent frames +/// skip waiting on it immediately until workers complete it. Non-spared memory-writing producer +/// compute pipelines pass `frame_cap = None` and always wait to completion. +fn resolve_wait_in( + p: &Arc, + pso: usize, + budget: Option, + frame_cap: Option, + frame: u64, + frame_state: &Mutex, +) -> usize { + let built = |p: &Pending| match p.real.load(Ordering::Acquire) { 0 => p.stand(pso), r => r, + }; + let r = p.real.load(Ordering::Acquire); + if r != 0 { + return r; + } + if *p.done.lock().unwrap() { + return built(p); } + if budget.is_some() && p.late.load(Ordering::Acquire) { + if !p.sent.swap(true, Ordering::AcqRel) { + enqueue(p.clone()); + } + return p.stand(pso); + } + // Recursive resolve on a worker thread: run inline to avoid worker-pool deadlock. + if building_here() { + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + complete(p, job()); + } + p.want(); + let mut done = p.done.lock().unwrap(); + while !*done { + done = p.cv.wait(done).unwrap(); + } + return built(p); + } + // Mark wanted BEFORE enqueueing so `PsoQueue::pop` jumps this pipeline ahead of background + // and deprioritized builds and preload workers raise priority immediately. + p.want(); + if !p.sent.swap(true, Ordering::AcqRel) { + enqueue(p.clone()); + } + let Some(fcap) = frame_cap else { + let _held = Held::new(); + let _prof = super::prof::span(if p.compute { super::prof::Kind::ComputePipelineWait } else { super::prof::Kind::GraphicsPipelineWait }); + if let Some(b) = budget { + return resolve_within(p, pso, b); + } + if !p.deprioritized.load(Ordering::Acquire) { + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + complete(p, job()); + } + } + let mut done = p.done.lock().unwrap(); + while !*done { + done = p.cv.wait(done).unwrap(); + } + return built(p); + }; + // A slow graphics PSO that already got its wait turn on an earlier frame keeps compiling in + // the background without re-burning `frame`'s graphics wait window every frame. + let prev_waited = p.waited_frame.load(Ordering::Acquire); + if prev_waited != UNWAITED && prev_waited != frame { + return p.stand(pso); + } + let rem = frame_state.lock().unwrap().begin_wait(frame, fcap, std::time::Instant::now()); + if rem.is_zero() { + return p.stand(pso); + } + let _ = p.waited_frame.compare_exchange(UNWAITED, frame, Ordering::AcqRel, Ordering::Acquire); + let (wait_for, per_pso_binding) = match budget { + Some(b) if b <= rem => (b, true), + _ => (rem, false), + }; + let _held = Held::new(); + let _prof = super::prof::span(if p.compute { super::prof::Kind::ComputePipelineWait } else { super::prof::Kind::GraphicsPipelineWait }); + let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), wait_for, |d| !*d).unwrap(); + let finished = *done; + drop(done); + let frame_timed_out = !finished && !per_pso_binding; + frame_state.lock().unwrap().end_wait(frame, fcap, std::time::Instant::now(), frame_timed_out); + if finished { + return built(p); + } + if per_pso_binding { + p.late.store(true, Ordering::Release); + static N: AtomicUsize = AtomicUsize::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + 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)", + wait_for.as_millis(), + n + 1 + ); + } + } else { + static N_GFX: AtomicUsize = AtomicUsize::new(0); + let n = N_GFX.fetch_add(1, Ordering::Relaxed); + if n < 16 || n.is_power_of_two() { + crate::xlog_warn!( + "D3D12.X: graphics pipeline wait window ({} ms) spent on frame {frame}: skipping remaining unready graphics work until next frame ({} so far)", + fcap.as_millis(), + n + 1 + ); + } + } + p.stand(pso) } /// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; unset or 0: until /// it is built). A retail game builds compute programs on its own threads: the driver takes up to /// 30 s for the biggest translated ones, and the title's watchdog ends it when its main thread -/// has been held 30 s. +/// has been held 30 s. It bounds binds as the title records; a call put off to the submit waits +/// there until its pipeline is built (`wait_for_submit`). fn wait_budget() -> Option { + #[cfg(test)] + if let Some(b) = BUDGET_FOR_TEST.with(|b| b.get()) { + return Some(b); + } static B: OnceLock> = OnceLock::new(); *B.get_or_init(|| std::env::var("XCL_PSO_WAIT_MS").ok().and_then(|v| v.trim().parse::().ok()).filter(|&ms| ms > 0).map(std::time::Duration::from_millis)) } +#[cfg(test)] +thread_local! { + /// `XCL_PSO_WAIT_MS` for the binds of this test thread + static BUDGET_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Binds on this thread wait at most `budget` (None: as `XCL_PSO_WAIT_MS` says). +#[cfg(test)] +pub(super) fn set_wait_budget_for_test(budget: Option) { + BUDGET_FOR_TEST.with(|b| b.set(budget)); +} + +/// Binds wait at most `XCL_PSO_WAIT_MS`: a dispatch is then not put off to the submit +/// (`list_x::defer`), where it would only wait as long. +pub fn waits_bounded() -> bool { + wait_budget().is_some() +} + +/// `pso` is a stand-in marked `spared` (`image_only`) or `bvh_traversal`, whose dispatches do +/// not block or defer to submit segments. +pub fn is_spared(pso: usize) -> bool { + entry(pso).is_some_and(|p| p.spared.load(Ordering::Acquire) || p.bvh_traversal.load(Ordering::Acquire)) +} + /// `resolve_wait` for at most `budget`: the build goes to the workers (not this thread), and a /// pipeline not built by then is `late` – it and later binds of it get the stand-in (their /// dispatches are skipped) until a worker has built it. @@ -1159,20 +2591,169 @@ pub fn image_only(standin: usize) { } } -/// `resolve_wait` for a pipeline binds do not wait for (`image_only`): the real one once built, -/// else the stand-in, with the build sent to the workers. Nobody waits, so the build is not -/// `wanted`: a big one takes its turn among the driver's compiles and waits for free commit. +/// Whether heavyweight compute shaders (`>= 512 KiB` DXIL / `>= 24 KiB` console code) compile +/// asynchronously off title threads (default on, `XCL_ASYNC_HEAVY_COMPUTE=0` to disable). +pub fn async_heavy_compute() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_ASYNC_HEAVY_COMPUTE").is_ok_and(|v| v.trim() == "0")) +} + +/// The compute pipeline behind stand-in `standin` is a heavyweight shader (`>= 24 KiB` console +/// code): never compile it synchronously on title threads — queue it deprioritized behind +/// normal/MS PSOs so `xcl-pso-*` workers compile it under `BIG_COMPILES` gating. Does NOT mark +/// `spared`, so non-RT producer compute shaders that write memory are NEVER skipped (call +/// `image_only` or `bvh_traversal` separately only for pure image-writing or BVH RT shaders). +pub fn heavy_compute(standin: usize) { + if let Some(p) = entry(standin) { + p.deprioritized.store(true, Ordering::Release); + } +} + +/// The compute pipeline behind stand-in `standin` issues `image_bvh*_intersect_ray`: binds never +/// compile it synchronously on title threads; queue it deprioritized behind normal/MS PSOs. +pub fn bvh_traversal(standin: usize) { + if let Some(p) = entry(standin) { + p.deprioritized.store(true, Ordering::Release); + p.bvh_traversal.store(true, Ordering::Release); + } +} + +/// Per-frame wait cap for non-critical spared compute PSOs (`XCL_PSO_FRAME_WAIT_MS`, default 24 ms, +/// `0` = never wait). Lets fast warm `.plib` hits finish on their first bind without stalling +/// `PresentX` past 24 ms/frame on cold compiles; never applies to memory-writing producer shaders. +fn frame_wait_budget() -> Option { + static B: OnceLock> = OnceLock::new(); + *B.get_or_init(|| { + let ms = std::env::var("XCL_PSO_FRAME_WAIT_MS") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(24); + (ms > 0).then(|| std::time::Duration::from_millis(ms)) + }) +} + +struct FrameWaitBudget { + frame: u64, + spent: std::time::Duration, + active_waiters: usize, + active_since: Option, +} + +impl FrameWaitBudget { + const fn new() -> Self { + Self { frame: 0, spent: std::time::Duration::ZERO, active_waiters: 0, active_since: None } + } + + fn advance(&mut self, frame: u64, now: std::time::Instant) { + if frame > self.frame { + self.frame = frame; + self.spent = std::time::Duration::ZERO; + self.active_since = (self.active_waiters > 0).then_some(now); + } + } + + fn effective_spent(&self, now: std::time::Instant) -> std::time::Duration { + let in_flight = self.active_since.map_or(std::time::Duration::ZERO, |s| now.saturating_duration_since(s)); + self.spent.saturating_add(in_flight) + } + + #[cfg(test)] + fn remaining_at(&mut self, frame: u64, cap: std::time::Duration, now: std::time::Instant) -> std::time::Duration { + self.advance(frame, now); + cap.saturating_sub(self.effective_spent(now)) + } + + /// Reserve a wait slot on `frame`: tracks wall-clock overlap across concurrent threads so + /// staggered callers share one hard `cap` ceiling per frame and can never cascade past `cap`. + fn begin_wait(&mut self, frame: u64, cap: std::time::Duration, now: std::time::Instant) -> std::time::Duration { + self.advance(frame, now); + let rem = cap.saturating_sub(self.effective_spent(now)); + if rem.is_zero() { + return std::time::Duration::ZERO; + } + if self.active_waiters == 0 { + self.active_since = Some(now); + } + self.active_waiters += 1; + rem + } + + fn end_wait(&mut self, frame: u64, cap: std::time::Duration, now: std::time::Instant, frame_timed_out: bool) { + self.advance(frame, now); + if self.active_waiters > 0 { + self.active_waiters -= 1; + if self.active_waiters == 0 { + if let Some(since) = self.active_since.take() { + self.spent = self.spent.saturating_add(now.saturating_duration_since(since)); + } + } + } + if frame_timed_out && frame == self.frame { + self.spent = self.spent.max(cap); + } + } + + #[cfg(test)] + fn remaining(&mut self, frame: u64, cap: std::time::Duration) -> std::time::Duration { + self.remaining_at(frame, cap, std::time::Instant::now()) + } + + #[cfg(test)] + fn record(&mut self, frame: u64, elapsed: std::time::Duration) { + if frame > self.frame { + self.frame = frame; + self.spent = elapsed; + } else if frame == self.frame { + self.spent = self.spent.saturating_add(elapsed); + } + } +} + +static FRAME_WAIT: Mutex = Mutex::new(FrameWaitBudget::new()); + +/// `resolve_wait` for a pipeline binds do not wait for (`image_only` or `bvh_traversal`): the real +/// one once built, else the stand-in, with the build sent to the workers. For non-BVH `spared` +/// pipelines (e.g. pure image-only shaders), waits up to the remaining per-frame `frame_wait_budget` +/// (`XCL_PSO_FRAME_WAIT_MS`, default 24 ms) so fast warm `.plib` loads complete on first bind +/// without ever freezing `PresentX`. Nobody marks the build `wanted`, so cold big compiles stay +/// strictly behind critical work and commit headroom. fn resolve_spared(p: &Arc, pso: usize) -> usize { match p.real.load(Ordering::Acquire) { 0 => { + if p.bvh_traversal.load(Ordering::Acquire) && !super::real::bvh_traversal_allowed() { + return p.stand(pso); + } if !p.sent.swap(true, Ordering::AcqRel) { enqueue(p.clone()); } + if !p.bvh_traversal.load(Ordering::Acquire) && !p.late.load(Ordering::Acquire) { + if let Some(cap) = frame_wait_budget() { + let frame = super::present::presents(); + let rem = FRAME_WAIT.lock().unwrap().begin_wait(frame, cap, std::time::Instant::now()); + if !rem.is_zero() { + let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), rem, |d| !*d).unwrap(); + let finished = *done; + drop(done); + FRAME_WAIT.lock().unwrap().end_wait(frame, cap, std::time::Instant::now(), !finished); + if finished { + return match p.real.load(Ordering::Acquire) { + 0 => p.stand(pso), + r => r, + }; + } + } + } + } if !*p.done.lock().unwrap() && !p.late.swap(true, Ordering::AcqRel) { 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); + let kind = if p.bvh_traversal.load(Ordering::Acquire) { + "a BVH ray-tracing compute program" + } else { + "a compute program that writes only images" + }; + crate::xlog_info!("D3D12.X: {kind} is still being built: its dispatches are left out until it is ({} so far)", n + 1); } } p.stand(pso) @@ -1181,11 +2762,12 @@ fn resolve_spared(p: &Arc, pso: usize) -> usize { } } -/// For binding: compute pipelines are waited for, graphics ones are not. +/// For binding: both graphics and compute pipelines wait within their own per-frame wait window +/// (`XCL_PSO_FRAME_BUDGET_MS`, default 12 s per kind per frame). Once a frame's window for that +/// kind is spent, remaining unready draws/dispatches get the stand-in and retry on the next frame. pub fn resolve_for_bind(pso: usize) -> usize { match entry(pso) { - Some(p) if p.compute => resolve_wait(pso), - Some(_) => resolve(pso), + Some(_) => resolve_wait(pso), None => pso, } } @@ -1194,7 +2776,7 @@ pub fn resolve_for_bind(pso: usize) -> usize { /// another object) and return its real pipeline to release (0: none, or still being built – /// the worker's result is then released when it arrives). pub fn released(pso: usize) -> usize { - let Some(p) = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)) else { return 0 }; + let Some(p) = PENDING.write().unwrap().as_mut().and_then(|m| m.remove(&pso)) else { return 0 }; { let done = p.done.lock().unwrap(); if *done { @@ -1212,6 +2794,24 @@ pub fn is_pending(pso: usize) -> bool { entry(pso).is_some_and(|p| !*p.done.lock().unwrap()) } +/// `pso` is a stand-in with no real pipeline yet (still building or build failed: draws nothing). +pub fn is_stand_in(pso: usize) -> bool { + entry(pso).is_some_and(|p| p.real.load(Ordering::Acquire) == 0) +} + +/// Whether `bound` (returned by `resolve*` for `standin`) is an unbuilt stand-in rather than the +/// real pipeline — remains `true` even if a worker finishes building `standin` between `resolve*` +/// and the caller's check (`#2598`), while returning `false` if the build failed (`real == 0`). +pub fn bound_unbuilt(standin: usize, bound: usize) -> bool { + entry(standin).is_some_and(|p| { + if !*p.done.lock().unwrap() { + return true; + } + let real = p.real.load(Ordering::Acquire); + real != 0 && bound != real + }) +} + /// One of the title's threads is about to wait for `pso`. pub fn want(pso: usize) { if let Some(p) = entry(pso) { @@ -1219,17 +2819,480 @@ pub fn want(pso: usize) { } } -/// A call with `pso` was put off to the submit: its build goes before the workers' queue. +/// A call with `pso` was put off to the submit: its build goes before the workers' queue +/// and is immediately marked wanted so DXC / big-compile gates and preload threads prioritize it. pub fn need_by_submit(pso: usize) { let Some(p) = entry(pso) else { return }; + p.want(); if !std::mem::replace(&mut p.demand.lock().unwrap().by_submit, true) { NEEDED.lock().unwrap().push_back(p); - let _ = queue().lock().unwrap().send(Box::new(|| ())); + queue().push(Box::new(|| ()), None); } } /// (built in the background, failed, still building) pub fn counts() -> (usize, usize, usize) { - let pending = PENDING.lock().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.done.lock().unwrap()).count()); + let pending = PENDING.read().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.done.lock().unwrap()).count()); (BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), pending) } + +#[cfg(test)] +mod pso_queue_tests { + use super::*; + + fn dummy_pending(wanted: bool, deprioritized: bool) -> Arc { + Arc::new(Pending { + job: Mutex::new(None), + sent: std::sync::atomic::AtomicBool::new(true), + real: AtomicUsize::new(0), + driver: AtomicUsize::new(0), + done: Mutex::new(false), + cv: Condvar::new(), + compute: false, + key: 0, + used: Default::default(), + orphan: Default::default(), + late: Default::default(), + spared: Default::default(), + bvh_traversal: Default::default(), + deprioritized: std::sync::atomic::AtomicBool::new(deprioritized), + waited_frame: AtomicU64::new(UNWAITED), + wanted_state: AtomicU8::new(WANTED_NONE), + demand: Mutex::new(Demand { wanted, by_submit: false, preload_thread: 0 }), + on_use: Default::default(), + }) + } + + fn dummy_compute_pending(wanted: bool, spared: bool) -> Arc { + Arc::new(Pending { + job: Mutex::new(None), + sent: std::sync::atomic::AtomicBool::new(true), + real: AtomicUsize::new(0), + driver: AtomicUsize::new(0), + done: Mutex::new(false), + cv: Condvar::new(), + compute: true, + key: 0, + used: Default::default(), + orphan: Default::default(), + late: Default::default(), + spared: std::sync::atomic::AtomicBool::new(spared), + bvh_traversal: Default::default(), + deprioritized: Default::default(), + waited_frame: AtomicU64::new(UNWAITED), + wanted_state: AtomicU8::new(WANTED_NONE), + demand: Mutex::new(Demand { wanted, by_submit: false, preload_thread: 0 }), + on_use: Default::default(), + }) + } + + #[test] + fn pso_queue_prioritizes_wanted_producer_compute_over_wanted_graphics() { + let q = PsoQueue::new(); + let order = Arc::new(Mutex::new(Vec::<&'static str>::new())); + let push = |name: &'static str, p: Arc| { + let o = order.clone(); + q.push(Box::new(move || o.lock().unwrap().push(name)), Some(p)); + }; + push("gfx_wanted", dummy_pending(true, false)); + push("cs_spared_wanted", dummy_compute_pending(true, true)); + push("cs_producer_wanted", dummy_compute_pending(true, false)); + for _ in 0..3 { + (q.pop())(); + } + assert_eq!(*order.lock().unwrap(), ["cs_producer_wanted", "gfx_wanted", "cs_spared_wanted"]); + } + + #[test] + fn pso_queue_dequeues_wanted_then_normal_ahead_of_deprioritized() { + let q = PsoQueue::new(); + let order = Arc::new(Mutex::new(Vec::<&'static str>::new())); + let push = |name: &'static str, p: Arc| { + let o = order.clone(); + q.push(Box::new(move || o.lock().unwrap().push(name)), Some(p)); + }; + let heavy1 = dummy_pending(false, true); + let bg1 = dummy_pending(false, false); + let promoted = dummy_pending(false, false); + let wanted_now = dummy_pending(true, false); + let heavy2 = dummy_pending(false, true); + push("heavy1", heavy1); + push("bg1", bg1); + push("promoted", promoted.clone()); + push("wanted", wanted_now); + push("heavy2", heavy2); + promoted.demand.lock().unwrap().wanted = true; + q.notify_wanted(); + for _ in 0..5 { + (q.pop())(); + } + assert_eq!(*order.lock().unwrap(), ["promoted", "wanted", "bg1", "heavy1", "heavy2"]); + } + + #[test] + fn heavy_compute_producer_runs_on_worker_and_is_never_skipped() { + let standin = 0x7E57_B0C1usize; + let (tx, rx) = mpsc::channel(); + submit_lazy(standin, true, Box::new(move || { + let on_worker = std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso-")); + let _ = tx.send(on_worker); + 0x5C5C + }), 0); + heavy_compute(standin); + // Must wait for the worker and return the real PSO (never skip a memory-writing producer). + assert_eq!(resolve_wait_for(standin, None), 0x5C5C); + assert!(rx.recv_timeout(std::time::Duration::from_secs(10)).expect("ran on worker"), "heavy producer must compile on xcl-pso worker"); + let _ = released(standin); + } + + #[test] + fn commit_headroom_throttles_workers_and_pauses_preload() { + assert_eq!(PRELOAD_PAUSE_COMMIT, 6 << 30); + assert_eq!(WORKER_CAP_2_COMMIT, 5 << 30); + assert_eq!(WORKER_CAP_1_COMMIT, 3 << 30); + + assert_eq!(worker_cap_for_commit(None, 6), 6); + assert_eq!(worker_cap_for_commit(Some(7 << 30), 6), 6); + assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_2_COMMIT), 6), 6); + assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_2_COMMIT - 1), 6), 2); + assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_1_COMMIT), 6), 2); + assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_1_COMMIT - 1), 6), 1); + assert_eq!(worker_cap_for_commit(Some(0), 6), 1, "must never drop to 0 workers"); + assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_2_COMMIT - 1), 1), 1); + + assert!(!should_pause_preload(None)); + assert!(!should_pause_preload(Some(PRELOAD_PAUSE_COMMIT))); + assert!(should_pause_preload(Some(PRELOAD_PAUSE_COMMIT - 1))); + assert!(should_pause_preload(Some(0))); + + // Any active wanted pipeline pauses speculative preload even with ample free RAM. + assert!(!should_pause_preload_with_demand(Some(16 << 30), 0)); + assert!(should_pause_preload_with_demand(Some(16 << 30), 1)); + assert!(should_pause_preload_with_demand(None, 2)); + assert!(should_pause_preload_with_demand(Some(PRELOAD_PAUSE_COMMIT - 1), 0)); + + // Preload worker pool stays tightly bounded (1..=2). + let m = preload_worker_threads(); + assert!((1..=2).contains(&m), "expected preload_worker_threads in 1..=2, got {m}"); + + // Active wanted counter transitions cleanly without leaking on complete/drop. + let p = dummy_pending(false, false); + p.mark_wanted_active(); + p.mark_wanted_active(); // idempotent + assert!(wanted_active() >= 1); + p.clear_wanted_active(); + p.clear_wanted_active(); // idempotent + p.mark_wanted_active(); // post-DONE must not re-increment + assert_eq!(p.wanted_state.load(Ordering::Acquire), WANTED_DONE); + } + + #[test] + fn heavy_and_bvh_pipelines_are_not_speculatively_preloaded() { + let heavy_standin = 0x7E57_B0D1usize; + let heavy_key = 0x5EED_B0D1u64; + used::earlier_run_used(heavy_key); + let ran = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let ran_job = ran.clone(); + submit_lazy_with_flags( + heavy_standin, + true, + Box::new(move || { + ran_job.store(true, Ordering::Release); + 0x5D5D + }), + heavy_key, + SubmitFlags { spared: false, bvh_traversal: false, deprioritized: true }, + ); + std::thread::sleep(std::time::Duration::from_millis(80)); + assert!(!ran.load(Ordering::Acquire), "heavy deprioritized PSO must not be speculatively preloaded"); + assert!(is_pending(heavy_standin)); + // Once actually bound, resolve_wait compiles it on a worker and returns the real PSO. + assert_eq!(resolve_wait_for(heavy_standin, None), 0x5D5D); + assert!(ran.load(Ordering::Acquire)); + let _ = released(heavy_standin); + } + + #[test] + fn frame_wait_budget_caps_per_frame_and_resets_on_new_frame() { + let cap = std::time::Duration::from_millis(24); + let mut b = FrameWaitBudget::new(); + assert_eq!(b.remaining(1, cap), cap); + b.record(1, std::time::Duration::from_millis(10)); + assert_eq!(b.remaining(1, cap), std::time::Duration::from_millis(14)); + b.record(1, std::time::Duration::from_millis(20)); + assert_eq!(b.remaining(1, cap), std::time::Duration::ZERO); + // Advancing to frame 2 resets the budget cleanly. + assert_eq!(b.remaining(2, cap), cap); + // Stale lower frame number must not clear frame 2's spent budget. + b.record(2, std::time::Duration::from_millis(12)); + b.record(1, std::time::Duration::from_millis(5)); + assert_eq!(b.remaining(2, cap), std::time::Duration::from_millis(12)); + } + + #[test] + fn submit_gated_maps_driver_without_pending_or_enqueue() { + let standin = 0x7E57_9A7Eu64 as usize; + let driver = 0x7E57_D12Eu64 as usize; + submit_gated(standin, driver); + assert!(!is_pending(standin), "gated stand-in must not appear pending"); + assert_eq!(resolve(standin), driver); + assert_eq!(resolve_wait(standin), driver); + assert_eq!(resolve_for_bind(standin), driver); + assert_eq!(released(standin), 0); + assert_eq!(resolve(standin), standin); + } + + #[test] + fn frame_budget_env_parsing() { + let ms = std::time::Duration::from_millis; + assert_eq!(parse_frame_budget(None), Some(ms(12_000))); + assert_eq!(parse_frame_budget(Some("")), Some(ms(12_000))); + assert_eq!(parse_frame_budget(Some("0")), Some(ms(0))); + assert_eq!(parse_frame_budget(Some("5000")), Some(ms(5000))); + assert_eq!(parse_frame_budget(Some("off")), None); + assert_eq!(parse_frame_budget(Some("none")), None); + assert_eq!(parse_frame_budget(Some("bad")), Some(ms(12_000))); + } + + #[test] + fn frame_budget_waits_within_window_stamps_slow_gfx_once_and_never_skips_producer_compute() { + use std::time::{Duration, Instant}; + + let gfx_budget = Mutex::new(FrameWaitBudget::new()); + let cap = Some(Duration::from_millis(60)); + + let (g_fast, g_slow1, g_slow2, c_prod) = (0x7E57_F001usize, 0x7E57_F002usize, 0x7E57_F003usize, 0x7E57_F004usize); + let (go_tx, go_rx) = mpsc::channel::<()>(); + let (go2_tx, go2_rx) = mpsc::channel::<()>(); + submit_lazy(g_fast, false, Box::new(|| { + std::thread::sleep(Duration::from_millis(10)); + 0xF101 + }), 0); + submit_lazy(g_slow1, false, Box::new(move || { + let _ = go_rx.recv(); + 0xF102 + }), 0); + submit_lazy(g_slow2, false, Box::new(move || { + let _ = go2_rx.recv(); + 0xF103 + }), 0); + submit_lazy(c_prod, true, Box::new(|| { + std::thread::sleep(Duration::from_millis(90)); + 0xF104 + }), 0); + heavy_compute(c_prod); + + // Frame 1: fast graphics PSO finishes within the 60 ms graphics window. + let p_fast = entry(g_fast).unwrap(); + assert_eq!(resolve_wait_in(&p_fast, g_fast, None, cap, 1, &gfx_budget), 0xF101); + + // Frame 1: slow graphics PSO spends the rest of frame 1's graphics window, stamps + // waited_frame = 1, and skips. + let p_slow1 = entry(g_slow1).unwrap(); + assert_eq!(resolve_wait_in(&p_slow1, g_slow1, None, cap, 1, &gfx_budget), g_slow1); + + // Frame 1: second unready graphics PSO sees 0 ms remaining and skips immediately WITHOUT + // stamping waited_frame (so it gets a fresh turn on Frame 2). + let p_slow2 = entry(g_slow2).unwrap(); + let t0 = Instant::now(); + assert_eq!(resolve_wait_in(&p_slow2, g_slow2, None, cap, 1, &gfx_budget), g_slow2); + assert!(t0.elapsed() < Duration::from_millis(25), "spent frame budget must skip immediately ({:?})", t0.elapsed()); + assert_eq!(p_slow2.waited_frame.load(Ordering::Acquire), UNWAITED); + + // Non-spared producer compute PSO (`!spared`, longer than 60 ms graphics window) MUST wait + // to completion instead of being skipped! + assert!(!is_spared(c_prod)); + assert_eq!(resolve_wait_for(c_prod, None), 0xF104); + + // Frame 2: g_slow1 already spent its wait turn on Frame 1 -> skips immediately without + // burning Frame 2's graphics budget! + let t1 = Instant::now(); + assert_eq!(resolve_wait_in(&p_slow1, g_slow1, None, Some(Duration::from_secs(5)), 2, &gfx_budget), g_slow1); + assert!(t1.elapsed() < Duration::from_millis(25), "already-waited slow graphics PSO must skip immediately on next frame ({:?})", t1.elapsed()); + + // Frame 2: g_slow2 never waited yet, so it gets Frame 2's full window and resolves once ready! + go2_tx.send(()).unwrap(); + assert_eq!(resolve_wait_in(&p_slow2, g_slow2, None, Some(Duration::from_secs(5)), 2, &gfx_budget), 0xF103); + + // Once g_slow1's worker completes, it immediately resolves to its real pipeline! + go_tx.send(()).unwrap(); + let wait_start = Instant::now(); + while is_pending(g_slow1) && wait_start.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!(resolve_wait_in(&p_slow1, g_slow1, None, Some(Duration::from_secs(5)), 3, &gfx_budget), 0xF102); + + for s in [g_fast, g_slow1, g_slow2, c_prod] { + let _ = released(s); + } + } + + #[test] + fn wall_clock_frame_budget_prevents_staggered_multithread_cascade() { + use std::time::{Duration, Instant}; + + let cap = Duration::from_secs(12); + let t0 = Instant::now(); + let mut b = FrameWaitBudget::new(); + + // Thread 1 starts waiting at t=0: full 12 s. + assert_eq!(b.begin_wait(1467, cap, t0), Duration::from_secs(12)); + // Thread 2 arrives staggered at t=10 s while thread 1 is still waiting: only 2 s left! + assert_eq!(b.begin_wait(1467, cap, t0 + Duration::from_secs(10)), Duration::from_secs(2)); + // Thread 3 arrives at t=11.5 s: only 0.5 s left! + assert_eq!(b.begin_wait(1467, cap, t0 + Duration::from_millis(11_500)), Duration::from_millis(500)); + // Thread 4 arrives at t=12.0 s: 0 ms left immediately (no cascade!). + assert_eq!(b.begin_wait(1467, cap, t0 + Duration::from_secs(12)), Duration::ZERO); + + // All 3 active waiters finish at t=12 s -> budget spent on frame 1467. + b.end_wait(1467, cap, t0 + Duration::from_secs(12), true); + b.end_wait(1467, cap, t0 + Duration::from_secs(12), true); + b.end_wait(1467, cap, t0 + Duration::from_secs(12), true); + assert_eq!(b.remaining_at(1467, cap, t0 + Duration::from_secs(12)), Duration::ZERO); + + // Advancing to frame 1468 resets the wall-clock window cleanly. + assert_eq!(b.begin_wait(1468, cap, t0 + Duration::from_secs(13)), Duration::from_secs(12)); + b.end_wait(1468, cap, t0 + Duration::from_secs(14), false); + assert_eq!(b.remaining_at(1468, cap, t0 + Duration::from_secs(14)), Duration::from_secs(11)); + } + + #[test] + fn bound_unbuilt_detects_standin_even_after_worker_finishes() { + let (standin_ok, standin_fail, native) = (0x7E57_9801usize, 0x7E57_9802usize, 0x7E57_9803usize); + let (tx, rx) = mpsc::channel::<()>(); + submit_lazy(standin_ok, false, Box::new(move || { + let _ = rx.recv(); + 0x9801 + }), 0); + // While pending: bound stand-in is unbuilt. + assert!(bound_unbuilt(standin_ok, standin_ok)); + // Finish the build after the caller already got `standin_ok`. + let _ = resolve(standin_ok); + tx.send(()).unwrap(); + let t0 = std::time::Instant::now(); + while is_pending(standin_ok) && t0.elapsed() < std::time::Duration::from_secs(5) { + std::thread::sleep(std::time::Duration::from_millis(2)); + } + assert!(!is_pending(standin_ok)); + assert!(bound_unbuilt(standin_ok, standin_ok), "stale stand-in must still read unbuilt after worker completes"); + assert!(!bound_unbuilt(standin_ok, 0x9801), "resolved real pipeline must not read unbuilt"); + + // Failed build (real == 0) is not treated as an in-flight unbuilt stand-in. + submit(standin_fail, true, Box::new(|| 0)); + assert_eq!(resolve_wait(standin_fail), standin_fail); + assert!(!bound_unbuilt(standin_fail, standin_fail)); + + // Unknown / native PC pipeline is never unbuilt. + assert!(!bound_unbuilt(native, native)); + + let _ = released(standin_ok); + let _ = released(standin_fail); + } + + #[test] + fn frame_cap_none_waits_for_graphics_pso_instead_of_skipping() { + use std::time::{Duration, Instant}; + + let gfx_budget = Mutex::new(FrameWaitBudget::new()); + + // Graphics PSO with `frame_cap == None` and no per-PSO budget waits to completion. + let g_wait = 0x7E57_F101usize; + submit_lazy(g_wait, false, Box::new(|| { + std::thread::sleep(Duration::from_millis(25)); + 0xF201 + }), 0); + let p_wait = entry(g_wait).unwrap(); + assert_eq!(resolve_wait_in(&p_wait, g_wait, None, None, 1, &gfx_budget), 0xF201); + + // Graphics PSO with `frame_cap == None` and a per-PSO budget respects `budget` + // instead of skipping with 0 ms wait. + let g_budget = 0x7E57_F102usize; + let (go_tx, go_rx) = mpsc::channel::<()>(); + submit_lazy(g_budget, false, Box::new(move || { + let _ = go_rx.recv(); + 0xF202 + }), 0); + let p_budget = entry(g_budget).unwrap(); + let t0 = Instant::now(); + assert_eq!( + resolve_wait_in(&p_budget, g_budget, Some(Duration::from_millis(30)), None, 1, &gfx_budget), + g_budget + ); + assert!( + t0.elapsed() >= Duration::from_millis(15), + "must wait for budget instead of skipping immediately ({:?})", + t0.elapsed() + ); + assert!(p_budget.late.load(Ordering::Acquire)); + go_tx.send(()).unwrap(); + let wait_start = Instant::now(); + while is_pending(g_budget) && wait_start.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!( + resolve_wait_in(&p_budget, g_budget, Some(Duration::from_millis(30)), None, 1, &gfx_budget), + 0xF202 + ); + + for s in [g_wait, g_budget] { + let _ = released(s); + } + } + + #[test] + fn frame_budget_keeps_default_12s_and_honors_opt_in_gfx_and_explicit_overrides() { + let ms = std::time::Duration::from_millis; + + // Default (unset/empty/invalid): keeps 12 s across all frames (even >60) so cold + // graphics PSOs during menus or world entry are never prematurely skipped. + let default_policy = parse_frame_budget_policy_from(None, None); + assert_eq!(default_policy, FrameBudgetPolicy::Default); + assert_eq!(parse_frame_budget_policy_from(Some(""), Some("")), FrameBudgetPolicy::Default); + assert_eq!(parse_frame_budget_policy_from(Some("bad"), Some("bad")), FrameBudgetPolicy::Default); + for frame in [0, GAMEPLAY_FRAME_BUDGET_START_FRAME - 1, GAMEPLAY_FRAME_BUDGET_START_FRAME, 10_000] { + assert_eq!(frame_budget_for_kind(default_policy, false, frame), Some(ms(DEFAULT_FRAME_BUDGET_MS))); + assert_eq!(frame_budget_for_kind(default_policy, true, frame), None); + } + + // Opt-in XCL_GFX_PSO_FRAME_BUDGET_MS=32: keeps 12 s before frame 60, caps graphics to + // 32 ms from frame 60 onward, while leaving producer compute pipelines uncapped. + let opt_in_32 = parse_frame_budget_policy_from(None, Some("32")); + assert_eq!(opt_in_32, FrameBudgetPolicy::OptInGameplay(Some(ms(32)))); + assert_eq!(frame_budget_for_kind(opt_in_32, false, 0), Some(ms(DEFAULT_FRAME_BUDGET_MS))); + assert_eq!(frame_budget_for_kind(opt_in_32, false, GAMEPLAY_FRAME_BUDGET_START_FRAME - 1), Some(ms(DEFAULT_FRAME_BUDGET_MS))); + assert_eq!(frame_budget_for_kind(opt_in_32, false, GAMEPLAY_FRAME_BUDGET_START_FRAME), Some(ms(32))); + assert_eq!(frame_budget_for_kind(opt_in_32, false, 10_000), Some(ms(32))); + assert_eq!(frame_budget_for_kind(opt_in_32, true, GAMEPLAY_FRAME_BUDGET_START_FRAME), None); + assert_eq!(frame_budget_for_kind(opt_in_32, true, 10_000), None); + + // Explicit XCL_PSO_FRAME_BUDGET_MS applies uniformly across all frames and overrides opt-in. + let explicit_500 = parse_frame_budget_policy_from(Some("500"), Some("32")); + assert_eq!(frame_budget_for_kind(explicit_500, false, 0), Some(ms(500))); + assert_eq!(frame_budget_for_kind(explicit_500, false, 10_000), Some(ms(500))); + assert_eq!(frame_budget_for_kind(explicit_500, true, 10_000), None); + let explicit_zero = parse_frame_budget_policy_from(Some("0"), None); + assert_eq!(frame_budget_for_kind(explicit_zero, false, 0), Some(ms(0))); + assert_eq!(frame_budget_for_kind(explicit_zero, false, 10_000), Some(ms(0))); + let explicit_off = parse_frame_budget_policy_from(Some("off"), Some("32")); + assert_eq!(frame_budget_for_kind(explicit_off, false, 0), None); + assert_eq!(frame_budget_for_kind(explicit_off, false, 10_000), None); + } + + #[test] + fn pso_worker_threads_scales_with_cpus_and_ram() { + // Smaller hosts (< 16 threads or < 24 GiB RAM) stay capped at 2..=6. + assert_eq!(pso_worker_threads_for(2, 16), 2); + assert_eq!(pso_worker_threads_for(4, 16), 3); + assert_eq!(pso_worker_threads_for(8, 16), 6); + assert_eq!(pso_worker_threads_for(8, 32), 6); + assert_eq!(pso_worker_threads_for(16, 16), 6); + assert_eq!(pso_worker_threads_for(24, 16), 6); + + // High-core / high-RAM hosts (>= 16 threads and >= 24 GiB RAM) scale cleanly up to 10. + assert_eq!(pso_worker_threads_for(16, 24), 8); + assert_eq!(pso_worker_threads_for(16, 32), 8); + assert_eq!(pso_worker_threads_for(20, 32), 10); + assert_eq!(pso_worker_threads_for(24, 32), 10); + assert_eq!(pso_worker_threads_for(32, 64), 10); + } +} 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..4ec4839596 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/pso_library.rs @@ -0,0 +1,835 @@ +//! 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::{AtomicU64, Ordering}; +use std::sync::{mpsc, Arc, OnceLock}; +use std::time::{Duration, Instant}; + +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 file's bytes with room after them, where it is not mapped (`open`). + copy: Vec, +} + +// 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; + }; + // AMD's driver reads a dword at the end of the blob in CreatePipelineLibrary + // (amdxc64.dll+0x176cd5). A view ends with its file's last page, so where the file + // ends less than 4 bytes before that, the read runs into the unmapped page after it. + // Such a file (4 lengths in 4096) is read into memory with room after it. + const PAGE: usize = 4096; + if (PAGE - len % PAGE) % PAGE < 4 { + CloseHandle(file); + let mut copy = std::fs::read(path).ok().filter(|c| c.len() == len)?; + copy.extend_from_slice(&[0; 4]); + return Some(Self { path: path.to_path_buf(), file: std::ptr::null_mut(), mapping: std::ptr::null_mut(), view: copy.as_ptr(), len, copy }); + } + 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, + copy: Vec::new(), + }) + } + } + + 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() && self.copy.is_empty() { + 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); + } + } +} + +/// 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); +/// Maximum time `flush()` waits on shutdown so exit can never hang behind a slow driver call. +const FLUSH_TIMEOUT: Duration = Duration::from_secs(5); + +/// 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 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) +} + +struct SendPso(ID3D12PipelineState); +unsafe impl Send for SendPso {} + +struct SendLib(ID3D12PipelineLibrary1); +unsafe impl Send for SendLib {} + +enum SaveCmd { + Store(String, SendPso), + Flush(mpsc::SyncSender>), +} + +unsafe fn create_empty_library(dev1: &ID3D12Device1) -> Option { + // 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()?; + lib +} + +/// Maximum idle read-only `ID3D12PipelineLibrary1` handles kept in `read_pool`. Each handle +/// borrows the same startup `MappedBlob` (zero extra blob RAM) so concurrent `Load*` callers +/// never share an `ID3D12PipelineLibrary1` instance and never stall behind one another. +const MAX_POOLED_READ_HANDLES: usize = 16; + +struct ReadHandleGuard<'a> { + pool: &'a std::sync::Mutex>, + lib: Option, +} + +impl ReadHandleGuard<'_> { + fn handle(&self) -> &ID3D12PipelineLibrary1 { + self.lib.as_ref().unwrap() + } +} + +impl Drop for ReadHandleGuard<'_> { + fn drop(&mut self) { + if let Some(lib) = self.lib.take() { + let mut pool = self.pool.lock().unwrap(); + if pool.len() < MAX_POOLED_READ_HANDLES { + pool.push(lib); + } + } + } +} + +/// Process-wide D3D12 pipeline library split into: +/// - `read_pool`: checked-out pool of independent read-only `ID3D12PipelineLibrary1` handles +/// opened from the startup `MappedBlob`. Windows `D3D12Core.dll` mutates internal state during +/// `Load*` and crashes (`D3D12Core.dll+0x7dfa`) when two threads call `Load*` concurrently on +/// the same `ID3D12PipelineLibrary1` instance; checking out an exclusive handle per caller keeps +/// every handle strictly single-threaded while preserving lock-free concurrent `Load*` scaling. +/// - `write_lib`: owned exclusively by the dedicated `xcl-plib-save` worker thread, fed via an +/// `mpsc` channel so `store()` returns in ~1 µs with zero lock contention on compile workers and +/// `D3D12Core.dll` never sees concurrent `StorePipeline` + `Load*` or `Serialize` races. +pub struct MmapPipelineLibrary { + /// Declared BEFORE `read_backing` and `dev1` so Rust drops every pooled handle before + /// unmapping `read_backing` or releasing `dev1`. + read_pool: std::sync::Mutex>, + /// Kept alive for the entire lifetime of `read_pool` handles because D3D12 requires the + /// initial blob memory to remain valid until every `ID3D12PipelineLibrary` is destroyed. + read_backing: Option>, + /// Free-threaded D3D12 device used to lazily open additional read-only handles from + /// `read_backing` when multiple threads call `Load*` concurrently. + dev1: ID3D12Device1, + /// Async command channel to the dedicated `xcl-plib-save` thread owning `write_lib`. + /// The mutex protects only the ~50 ns `mpsc::Sender::send` (never any D3D12 call). + save_tx: Option>>, + dirty: Arc, +} + +// Every `ID3D12PipelineLibrary1` in `read_pool` is exclusively owned by one thread at a time via +// `ReadHandleGuard`; `dev1.CreatePipelineLibrary` is free-threaded per D3D12 spec; `read_backing` +// is read-only immutable memory; `save_tx` is synchronized by its Mutex. +unsafe impl Sync for MmapPipelineLibrary {} +unsafe impl Send 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); + let mut initial_read_handles: Vec = Vec::new(); + let mut backing: Option> = None; + + 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 {})", + blob.len() as f64 / (1024.0 * 1024.0), + if blob.copy.is_empty() { "file-backed" } else { "read into memory: the file ends at a page boundary" } + ); + initial_read_handles.push(lib); + backing = Some(Arc::new(blob)); + } + 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" + ); + } + } + } + + // Open a separate write-only `ID3D12PipelineLibrary1` from the same read-only `MappedBlob` + // (zero extra RAM) so `xcl-plib-save` exclusively owns `StorePipeline` + `Serialize`. + // If a valid `backing` exists and the 2nd handle fails to open, disable saving for this + // run rather than overwriting the valid `.plib` with an empty generation. + let write_lib = match &backing { + Some(blob) => dev1.CreatePipelineLibrary::(blob.as_slice()).ok(), + None => create_empty_library(&dev1), + }; + if initial_read_handles.is_empty() && write_lib.is_none() { + return None; + } + + let dirty = Arc::new(AtomicU64::new(0)); + let save_tx = write_lib.map(|wlib| { + let (tx, rx) = mpsc::channel::(); + let write_backing = backing.clone(); + let dirty_worker = dirty.clone(); + let send_lib = SendLib(wlib); + let _ = std::thread::Builder::new().name("xcl-plib-save".into()).spawn(move || { + run_save_worker(send_lib, write_backing, store, rx, dirty_worker); + }); + std::sync::Mutex::new(tx) + }); + + Some(Self { + read_pool: std::sync::Mutex::new(initial_read_handles), + read_backing: backing, + dev1, + save_tx, + dirty, + }) + } + + /// Check out exclusive ownership of a read-only `ID3D12PipelineLibrary1` handle backed by + /// `read_backing`, lazily opening a new handle from the same mmap when concurrent threads + /// overlap. Never holds `read_pool`'s mutex across any D3D12 driver call. + unsafe fn checkout_read_handle(&self) -> Option> { + let blob = self.read_backing.as_ref()?; + if let Some(lib) = self.read_pool.lock().unwrap().pop() { + return Some(ReadHandleGuard { pool: &self.read_pool, lib: Some(lib) }); + } + let lib = self.dev1.CreatePipelineLibrary::(blob.as_slice()).ok()?; + Some(ReadHandleGuard { pool: &self.read_pool, lib: Some(lib) }) + } + + 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 guard = self.checkout_read_handle()?; + let name = HSTRING::from(key); + guard.handle().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 guard = self.checkout_read_handle()?; + let name = HSTRING::from(key); + guard.handle().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 guard = self.checkout_read_handle()?; + let name = HSTRING::from(key); + guard.handle().LoadPipeline(&name, desc).ok() + } + + /// Enqueue `(key, pso)` for the dedicated `xcl-plib-save` worker thread. Returns immediately + /// (~1 µs) with zero driver lock contention on compile workers. + pub unsafe fn store(&self, key: &str, pso: &ID3D12PipelineState) -> bool { + if key.is_empty() { + return false; + } + let Some(tx) = self.save_tx.as_ref() else { return false }; + tx.lock().unwrap().send(SaveCmd::Store(key.to_string(), SendPso(pso.clone()))).is_ok() + } + + pub fn dirty_count(&self) -> u64 { + self.dirty.load(Ordering::Relaxed) + } + + /// Blocking shutdown flush (e.g. `WM_CLOSE` or `XCL_RUN_SECONDS`): asks `xcl-plib-save` to + /// drain any queued `StorePipeline` calls and write a fresh `.plib` generation (bounded by + /// `FLUSH_TIMEOUT` so shutdown can never hang). + pub unsafe fn flush(&self) -> Option { + let tx = self.save_tx.as_ref()?; + let (reply_tx, reply_rx) = mpsc::sync_channel(1); + if tx.lock().unwrap().send(SaveCmd::Flush(reply_tx)).is_err() { + return None; + } + reply_rx.recv_timeout(FLUSH_TIMEOUT).ok().flatten() + } +} + +fn run_save_worker( + write_lib: SendLib, + _backing: Option>, + store: LibraryStore, + rx: mpsc::Receiver, + dirty_counter: Arc, +) { + let lib = write_lib.0; + let epoch = Instant::now(); + let now_ms = || epoch.elapsed().as_millis() as u64; + let mut dirty: u64 = 0; + let mut last_store_ms: u64 = 0; + let mut last_save_ms: u64 = 0; + + let save_now = |dirty: &mut u64, last_save_ms: &mut u64| -> Option { + if *dirty == 0 { + return None; + } + let count = *dirty; + let size = unsafe { lib.GetSerializedSize() }; + let saved = if size > 0 { + store.write_generation(size, |buf| unsafe { lib.Serialize(buf) }.is_ok()) + } else { + None + }; + if let Some((gen, path)) = saved { + *dirty = 0; + dirty_counter.store(0, Ordering::Release); + *last_save_ms = now_ms(); + crate::xlog_info!( + "D3D12.X: saved pipeline library gen-{gen:08x} ({:.1} MiB, {} new pipelines)", + size as f64 / (1024.0 * 1024.0), + count + ); + Some(path) + } else { + None + } + }; + + let apply_store = |key: String, pso: SendPso, dirty: &mut u64, last_store_ms: &mut u64| { + let name = HSTRING::from(key); + if unsafe { lib.StorePipeline(&name, &pso.0) }.is_ok() { + *dirty += 1; + dirty_counter.store(*dirty, Ordering::Release); + *last_store_ms = now_ms(); + } + drop(pso); + }; + + loop { + match rx.recv_timeout(Duration::from_secs(2)) { + Ok(SaveCmd::Store(key, pso)) => { + apply_store(key, pso, &mut dirty, &mut last_store_ms); + // Drain any burst of queued stores before checking periodic save. + let mut pending_flush = None; + while let Ok(cmd) = rx.try_recv() { + match cmd { + SaveCmd::Store(k, p) => apply_store(k, p, &mut dirty, &mut last_store_ms), + SaveCmd::Flush(reply) => { + pending_flush = Some(reply); + break; + } + } + } + if let Some(reply) = pending_flush { + let saved = save_now(&mut dirty, &mut last_save_ms); + let _ = reply.send(saved); + } else if should_background_save(dirty, now_ms(), last_store_ms, last_save_ms) { + save_now(&mut dirty, &mut last_save_ms); + } + } + Ok(SaveCmd::Flush(reply)) => { + let mut extra_flushes = Vec::new(); + while let Ok(cmd) = rx.try_recv() { + match cmd { + SaveCmd::Store(k, p) => apply_store(k, p, &mut dirty, &mut last_store_ms), + SaveCmd::Flush(r) => extra_flushes.push(r), + } + } + let saved = save_now(&mut dirty, &mut last_save_ms); + let _ = reply.send(saved.clone()); + for r in extra_flushes { + let _ = r.send(saved.clone()); + } + } + Err(mpsc::RecvTimeoutError::Timeout) => { + if should_background_save(dirty, now_ms(), last_store_ms, last_save_ms) { + save_now(&mut dirty, &mut last_save_ms); + } + } + Err(mpsc::RecvTimeoutError::Disconnected) => { + let _ = save_now(&mut dirty, &mut last_save_ms); + break; + } + } + } +} + +#[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()); + } + + /// The driver reads a dword at the end of the blob: it is readable whatever the file's length, + /// also where the file ends with its last page or less than 4 bytes before. + #[test] + fn mapped_blob_has_a_readable_dword_after_its_end() { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + let dir = TempDir::new("end"); + for len in [4096usize, 8190, 8191, 4093, 4092, 100] { + let path = dir.0.join(format!("{len}.plib")); + let payload: Vec = (0..len).map(|i| (i * 7) as u8 | 1).collect(); + std::fs::write(&path, &payload).unwrap(); + let blob = MappedBlob::open(&path).unwrap(); + assert_eq!(blob.as_slice(), payload.as_slice(), "{len}"); + let end = blob.as_ptr() as usize + len; + for p in [end, end + 3] { + let mut i: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + assert!(unsafe { VirtualQuery(p as *const c_void, &mut i, std::mem::size_of_val(&i)) } != 0 && i.State == MEM_COMMIT, "{len}"); + } + assert_eq!(unsafe { (end as *const u32).read_unaligned() }, 0, "{len}"); + } + } + + #[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 91085d3933..94b47c12c6 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -138,6 +138,9 @@ static FALLBACK_PSO: AtomicU64 = AtomicU64::new(0); static FAILED_PSO: AtomicU64 = AtomicU64::new(0); static FALLBACK_RS: AtomicU64 = AtomicU64::new(0); static TRANSLATED_PSO: AtomicU64 = AtomicU64::new(0); +/// console MS containers moved from the AS slot and translated (logged sparsely: a title +/// creates tens of thousands of these pipelines during boot) +static AS_SLOT_MS: AtomicU64 = AtomicU64::new(0); static TRANSLATE_ERRORS: Mutex> = Mutex::new(Vec::new()); /// XCL shader ABI root signature on the backend device (raw, kept for the process lifetime) static ABI_RS: AtomicUsize = AtomicUsize::new(0); @@ -169,22 +172,29 @@ pub fn abi_root_signature() -> Option { /// Each UMA window as one D3D12 buffer (placed in a heap opened over the process memory): /// `mem`, `mem1`.. of recompiled shaders. (buffer, GPU VA) per window, kept for the process /// lifetime. -static UMA_BUFFER: Mutex> = Mutex::new(Vec::new()); +static UMA_BUFFER: std::sync::RwLock> = std::sync::RwLock::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()); + +/// Bytes of the coherent windows imported into D3D12 (`OpenExistingHeapFromAddress`): those DXGI +/// counts. 0 before, or when the import failed (the windows are then CPU memory only). +pub fn uma_imported_bytes() -> u64 { + let Some(u) = crate::gpu::uma::get() else { return 0 }; + UMA_HEAPS.lock().unwrap().iter().enumerate().filter(|(_, h)| h.is_some()).map(|(k, _)| u.window(k).1 as u64).sum() +} /// 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); -static UMA_BUFFERS: Mutex>> = Mutex::new(None); +static UMA_BUFFERS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// Where a console-created buffer lives in unified memory (its console GPU address). pub fn console_buffer(res: usize) -> Option<(usize, usize)> { - UMA_BUFFERS.lock().unwrap().as_ref()?.get(&res).map(|&(p, n, _)| (p, n)) + UMA_BUFFERS.read().unwrap().as_ref()?.get(&res).map(|&(p, n, _)| (p, n)) } /// Number of live console buffers in unified memory. pub fn console_buffers() -> usize { - UMA_BUFFERS.lock().unwrap().as_ref().map_or(0, |m| m.len()) + UMA_BUFFERS.read().unwrap().as_ref().map_or(0, |m| m.len()) } static UMA_ERROR: Mutex = Mutex::new(String::new()); @@ -195,7 +205,7 @@ pub fn uma_gpu_va() -> u64 { /// GPU virtual addresses of the UMA window buffers (`u2`, `u3`.. of the shader ABI). pub fn uma_window_vas() -> Vec { - UMA_BUFFER.lock().map(|g| g.iter().map(|b| b.1).collect()).unwrap_or_default() + UMA_BUFFER.read().map(|g| g.iter().map(|b| b.1).collect()).unwrap_or_default() } /// The window buffer holding `len` bytes at UMA address `p`, and their offset in it. @@ -206,14 +216,16 @@ pub(super) fn uma_window_buffer(p: usize, len: usize) -> Option<(usize, u64)> { if p - base + len > size { return None; } - Some((UMA_BUFFER.lock().ok()?.get(k)?.0, (p - base) as u64)) + let buf = UMA_BUFFER.read().ok()?.get(k)?.0; + (buf != 0).then(|| (buf, (p - base) as u64)) } /// GPU virtual address of a UMA address (None: not in UMA or not open on the GPU). pub fn uma_va_of(p: usize) -> Option { let u = crate::gpu::uma::get()?; let k = u.window_of(p)?; - Some(*uma_window_vas().get(k)? + (p - u.window(k).0) as u64) + let base = *uma_window_vas().get(k)?; + (base != 0).then(|| base + (p - u.window(k).0) as u64) } /// What the start-up check of the coherent UMA windows found (`check_uma_import`): empty – not @@ -374,12 +386,12 @@ unsafe fn open_uma(device: &ID3D12Device) { crate::xlog_info!("D3D12.X: memory windows from the shared descriptor heap (no per-access switch)"); } } - *UMA_BUFFER.lock().unwrap() = bufs; + *UMA_BUFFER.write().unwrap() = bufs; } pub fn stats() -> D3d12Stats { let classes = CLASSES - .lock() + .read() .map(|g| { g.iter() .map(|c| ClassStat { interface: c.iface.name.to_string(), public_methods: c.public, internal_slots: c.scanned - c.public }) @@ -440,6 +452,23 @@ pub fn video_memory() -> Option<(u64, u64)> { } } +/// The process's video memory on the device's adapter against its budget: (local, non-local). +pub fn video_budget() -> Option<(windows::Win32::Graphics::Dxgi::DXGI_QUERY_VIDEO_MEMORY_INFO, windows::Win32::Graphics::Dxgi::DXGI_QUERY_VIDEO_MEMORY_INFO)> { + use windows::Win32::Graphics::Dxgi::*; + let raw = device_raw(); + let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }?; + unsafe { + let luid = dev.GetAdapterLuid(); + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let adapter: IDXGIAdapter3 = factory.EnumAdapterByLuid(luid).ok()?; + let mut local = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut non_local = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + adapter.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut local).ok()?; + adapter.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut non_local).ok()?; + Some((local, non_local)) + } +} + /// The device runs only 32-lane waves: wave64 compute, mesh and geometry programs need the /// split form (`Options::split_wave64`). Unknown device: assume so. fn wave32_only(device: *mut c_void) -> bool { @@ -452,6 +481,48 @@ fn wave32_only(device: *mut c_void) -> bool { } } +/// Whether `device` runs on an AMD adapter (PCI vendor ID `0x1002`), cached per device pointer. +fn is_amd_device(device: *mut c_void) -> bool { + use windows::Win32::Graphics::Dxgi::*; + if device.is_null() { + return false; + } + static CACHE: Mutex>> = Mutex::new(None); + let key = device as usize; + if let Some(&v) = CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key)) { + return v; + } + let amd = unsafe { + ID3D12Device::from_raw_borrowed(&device) + .and_then(|dev| { + let luid = dev.GetAdapterLuid(); + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let adapter: IDXGIAdapter1 = factory.EnumAdapterByLuid(luid).ok()?; + let desc = adapter.GetDesc1().ok()?; + Some(desc.VendorId == 0x1002) + }) + .unwrap_or(false) + }; + CACHE.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, amd); + amd +} + +/// Serialize driver `Create*PipelineState` calls when explicitly requested (`XCL_AMD_SERIAL_PSO=1` +/// forces on all vendors; `=auto` serializes on AMD adapters). Default is off because +/// `big_compile_turn` already gates huge background compiles without blocking urgent title-thread +/// and cached PSO creation behind multi-minute background shader builds. +fn serialize_driver_pso(device: *mut c_void) -> bool { + static OVERRIDE: OnceLock> = OnceLock::new(); + match *OVERRIDE.get_or_init(|| match std::env::var("XCL_AMD_SERIAL_PSO").ok().as_deref().map(str::trim) { + Some("1") => Some(true), + Some("auto") => None, + _ => Some(false), + }) { + Some(v) => v, + None => is_amd_device(device), + } +} + /// A wave64 VS / PS may run in 32-lane waves here (`pso::graphics_wave32`: the driver picks /// the wave size of graphics shaders): the split flag for VS / PS translation. Unknown /// device: assume so. @@ -497,7 +568,7 @@ pub fn init() -> Result { // `XCL_DRED=1`: on a device removal the faulting address and the last GPU operations // (logged by `log_device_removed`); no debug layer needed. Opt-in: with it XDefiant // stalled in its first seconds twice. - if std::env::var_os("XCL_DRED").is_some() { + if dred_on() { match crate::gpu::agility::configuration_interface::( &CLSID_D3D12DeviceRemovedExtendedData, ) { @@ -522,6 +593,8 @@ pub fn init() -> Result { } for (adapter, desc) in list { if let Ok(dev) = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0) { + driver_cache::note_vendor(desc.VendorId); + super::gpu_awake::start(&dev, desc.VendorId); device = Some(dev); name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20); break; @@ -618,10 +691,14 @@ struct Class { iface: &'static Iface, public: usize, scanned: usize, + /// When `orig` lies outside any loaded module (e.g., Agility SDK 1.620+ heap-allocated open + /// command-list vtables, #2588), snapshot the copied runtime method slots so `class_for` only + /// reuses `ext` while the live table at `orig` still holds the exact same methods. + copied: Option>, } -static CLASSES: Mutex> = Mutex::new(Vec::new()); -static EXTS: Mutex>> = Mutex::new(None); +static CLASSES: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); +static EXTS: std::sync::RwLock>> = std::sync::RwLock::new(None); unsafe fn vt(obj: *mut c_void) -> *const usize { *(obj as *const *const usize) @@ -679,11 +756,11 @@ pub(super) unsafe fn this_first(a: *mut c_void, b: *mut c_void) -> bool { } fn is_ext(v: usize) -> bool { - EXTS.lock().map(|g| g.as_ref().map(|s| s.contains(&v)).unwrap_or(false)).unwrap_or(false) + EXTS.read().map(|g| g.as_ref().map(|s| s.contains(&v)).unwrap_or(false)).unwrap_or(false) } fn kind_of(ext: usize) -> Option { - CLASSES.lock().unwrap().iter().find(|c| c.ext == ext).map(|c| c.kind) + CLASSES.read().unwrap().iter().find(|c| c.ext == ext).map(|c| c.kind) } /// If a native D3D12 method (such as `Close` or `Reset` on Agility SDK 1.620+, or copy-list @@ -725,11 +802,25 @@ pub unsafe fn adopt(obj: *mut c_void, kind: Kind) { *(obj as *mut usize) = ext; } +unsafe fn find_matching_class(classes: &[Class], orig: usize, kind: Kind, ot: *const usize) -> Option { + classes + .iter() + .rev() + .find(|c| { + c.orig == orig + && c.kind == kind + && c.copied.as_ref().is_none_or(|saved| { + saved.iter().enumerate().all(|(i, &want)| *ot.add(i) == want) + }) + }) + .map(|c| c.ext) +} + unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { - if let Some(c) = CLASSES.lock().unwrap().iter().find(|c| c.orig == orig && c.kind == kind) { - return c.ext; - } let ot = orig as *const usize; + if let Some(ext) = find_matching_class(&CLASSES.read().unwrap(), orig, kind, ot) { + return ext; + } // most derived PC interface this object implements let chain = layout::chain(kind.base()); let qi: QiFn = std::mem::transmute(*ot); @@ -832,16 +923,21 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { v[1 + i] = super::guard::make_tracer(v[1 + i], name); } } + let copied = (module_of(orig) == 0).then(|| (0..scanned).map(|i| *ot.add(i)).collect::>().into_boxed_slice()); + let mut classes = CLASSES.write().unwrap(); + if let Some(ext) = find_matching_class(&classes, orig, kind, ot) { + return ext; + } let leaked: &'static [usize] = Box::leak(v.into_boxed_slice()); let ext = leaked.as_ptr() as usize + 8; - EXTS.lock().unwrap().get_or_insert_with(HashSet::new).insert(ext); + EXTS.write().unwrap().get_or_insert_with(HashSet::new).insert(ext); crate::xlog_info!( "D3D12.X: {} – {public} PC methods, {} internal slots under the guard, +{EXTRA_SLOTS} stubs ({kind:?}, PC vtable {})", iface.name, scanned - public, crate::modules::describe_address(orig) ); - CLASSES.lock().unwrap().push(Class { orig, kind, ext, iface, public, scanned }); + classes.push(Class { orig, kind, ext, iface, public, scanned, copied }); ext } @@ -1037,6 +1133,7 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (90, l::write32_bottom_of_shader_x as usize), (93, l::kickoff_x as usize), (94, l::set_depth_bias_x as usize), + (127, b::dispatch_mesh as usize), // console compute/BVH builder extensions (`XboxBvhBuilder.dll`) (146, l::uav_barrier_x as usize), (148, b::allocate_upload_memory as usize), @@ -1089,7 +1186,8 @@ unsafe extern "system" fn dev_create_descriptor_heap_x(this: *mut c_void, desc: let flags = if shared { d[2] & !(D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32) } else { d[2] }; let pc = [d[0], pc_n, flags, d[3]]; let hr = dev_create_descriptor_heap(this, pc.as_ptr() as usize, riid, ppv); - if hr >= 0 { + // a null `ppv` is D3D12's validation call: S_FALSE and no heap to register + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { let raw = *ppv; let heap = ID3D12DescriptorHeap::from_raw_borrowed(&raw).unwrap(); let dev = ID3D12Device::from_raw_borrowed(&this).unwrap(); @@ -1172,7 +1270,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 { @@ -1198,6 +1296,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]> { @@ -1251,14 +1359,246 @@ fn resource_dim_to_view(r: &D3D12_RESOURCE_DESC) -> i32 { } static NON_UMA_BUFFER_VIEWS: AtomicU64 = AtomicU64::new(0); +static GPU_VIEW_BUFFER_HITS: AtomicU64 = AtomicU64::new(0); + +/// Default total VRAM-only sparse backing cap for GPU-writable buffers placed at unresolved +/// addresses outside the UMA windows (`0xc_..–0x13_..` GPU views or outside-window reservations). +/// Override with `XCL_OUTSIDE_BUFFER_MB` (`0` or `XCL_OUTSIDE_BUFFERS=0` disables). +const OUTSIDE_BUFFER_DEFAULT_MB: usize = 256; +const OUTSIDE_BUFFER_MAX_ITEM: usize = 64 << 20; +const OUTSIDE_TILE: usize = 0x1_0000; + +fn outside_buffer_cap_bytes() -> usize { + static CAP: OnceLock = OnceLock::new(); + *CAP.get_or_init(|| { + if std::env::var("XCL_OUTSIDE_BUFFERS").is_ok_and(|v| v.trim() == "0") { + return 0; + } + std::env::var("XCL_OUTSIDE_BUFFER_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(OUTSIDE_BUFFER_DEFAULT_MB) + .saturating_mul(1 << 20) + }) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct OutsideEntry { + title_base: usize, + title_end: usize, + uma_base: usize, + refs: usize, + pinned_uav: bool, +} + +#[derive(Default)] +struct OutsideBufferTable { + entries: Vec, + total_bytes: usize, +} + +impl OutsideBufferTable { + fn lookup(&self, va: usize, len: usize) -> Option { + let end = va.checked_add(len)?; + self.entries + .iter() + .find(|e| e.title_base <= va && end <= e.title_end) + .map(|e| e.uma_base + (va - e.title_base)) + } + + fn retain_existing(&mut self, va: usize, len: usize, add_ref: bool, pin_uav: bool) -> Option<(usize, usize)> { + let end = va.checked_add(len)?; + let e = self.entries.iter_mut().find(|e| e.title_base <= va && end <= e.title_end)?; + if add_ref { + e.refs = e.refs.saturating_add(1); + } + if pin_uav { + e.pinned_uav = true; + } + Some((e.title_base, e.uma_base + (va - e.title_base))) + } + + fn can_insert(&self, title_base: usize, title_end: usize, cap_bytes: usize) -> bool { + if cap_bytes == 0 || title_end <= title_base { + return false; + } + let span = title_end - title_base; + if span > OUTSIDE_BUFFER_MAX_ITEM || self.total_bytes.saturating_add(span) > cap_bytes { + return false; + } + !self.entries.iter().any(|e| e.title_base < title_end && title_base < e.title_end) + } + + fn insert(&mut self, title_base: usize, title_end: usize, uma_base: usize, add_ref: bool, pin_uav: bool, cap_bytes: usize) -> bool { + if !self.can_insert(title_base, title_end, cap_bytes) { + return false; + } + self.total_bytes = self.total_bytes.saturating_add(title_end - title_base); + self.entries.push(OutsideEntry { + title_base, + title_end, + uma_base, + refs: usize::from(add_ref), + pinned_uav: pin_uav, + }); + true + } + + fn release_ref(&mut self, title_base: usize) -> Option { + let idx = self.entries.iter().position(|e| e.title_base == title_base)?; + let e = &mut self.entries[idx]; + e.refs = e.refs.saturating_sub(1); + if e.refs == 0 && !e.pinned_uav { + let gone = self.entries.swap_remove(idx); + self.total_bytes = self.total_bytes.saturating_sub(gone.title_end - gone.title_base); + Some(gone.uma_base) + } else { + None + } + } +} + +static OUTSIDE_BUFFERS: std::sync::RwLock = std::sync::RwLock::new(OutsideBufferTable { entries: Vec::new(), total_bytes: 0 }); +static OUTSIDE_RES: Mutex>> = Mutex::new(None); +static HAS_OUTSIDE_BUFFERS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +fn lookup_outside_buffer(va: usize, len: usize) -> Option { + if !HAS_OUTSIDE_BUFFERS.load(Ordering::Acquire) { + return None; + } + OUTSIDE_BUFFERS.read().unwrap().lookup(va, len) +} + +unsafe fn ensure_outside_buffer(va: usize, len: usize, add_ref: bool, pin_uav: bool) -> Option<(usize, usize)> { + let cap = outside_buffer_cap_bytes(); + if cap == 0 || va == 0 || len == 0 || len > OUTSIDE_BUFFER_MAX_ITEM { + return None; + } + if let Some(hit) = OUTSIDE_BUFFERS.write().unwrap().retain_existing(va, len, add_ref, pin_uav) { + return Some(hit); + } + let title_base = va & !(OUTSIDE_TILE - 1); + let title_end = va.checked_add(len)?.checked_next_multiple_of(OUTSIDE_TILE)?; + let span = title_end - title_base; + if !OUTSIDE_BUFFERS.read().unwrap().can_insert(title_base, title_end, cap) { + return None; + } + // Allocate VRAM-only sparse backing OUTSIDE `OUTSIDE_BUFFERS` lock (zero lock-order hazard). + let (uma_base, _) = super::sparse::alloc_vram_only(span, OUTSIDE_TILE)?; + let inserted = { + let mut t = OUTSIDE_BUFFERS.write().unwrap(); + if let Some(hit) = t.retain_existing(va, len, add_ref, pin_uav) { + drop(t); + super::sparse::free_vram_only(uma_base); + return Some(hit); + } + t.insert(title_base, title_end, uma_base, add_ref, pin_uav, cap) + }; + if !inserted { + super::sparse::free_vram_only(uma_base); + return None; + } + HAS_OUTSIDE_BUFFERS.store(true, Ordering::Release); + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: shared GPU-writable backing for outside-UMA buffer {va:#x} ({len} B) -> sparse UMA {:#x} (#{n})", + uma_base + (va - title_base) + ); + } + Some((title_base, uma_base + (va - title_base))) +} + +unsafe fn release_outside_ref(title_base: usize) { + let free_uma = OUTSIDE_BUFFERS.write().unwrap().release_ref(title_base); + if let Some(uma_base) = free_uma { + super::sparse::free_vram_only(uma_base); + } +} + +unsafe fn forget_outside_resource(res: usize) { + if !HAS_OUTSIDE_BUFFERS.load(Ordering::Relaxed) { + return; + } + let title_base = OUTSIDE_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&res)); + if let Some(tb) = title_base { + release_outside_ref(tb); + } +} + +fn is_gpu_writable_placed_buffer(d: &D3D12_RESOURCE_DESC, state: u32) -> bool { + const WRITABLE_STATES: u32 = D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32 + | D3D12_RESOURCE_STATE_COPY_DEST.0 as u32 + | D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32; + (d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0) || (state & WRITABLE_STATES != 0) +} + +/// Resolve a console GPU virtual address range `[va, va + len)` to a shader-readable UMA address. +/// Fast path: addresses already inside UMA return as-is. +/// Fallback: checks shared GPU-writable outside-UMA backings (`OUTSIDE_BUFFERS`), then consults +/// `kernelx::mirrors::mapped_source` (and paired CPU view `mirrors::source`), verifying every +/// 64 KiB page across `len` maps contiguously into UMA so direct zero-copy SRV/CBV/UAV access +/// never aliases scattered physical pages. +pub(super) fn resolve_uma_va(va: u64, len: usize) -> Option { + if va == 0 { + return None; + } + let u = crate::gpu::uma::get()?; + let start = va as usize; + if u.contains(start) { + if len == 0 || start.checked_add(len - 1).is_some_and(|e| u.contains(e)) { + return Some(va); + } + return None; + } + if let Some(mapped) = lookup_outside_buffer(start, len) { + return Some(mapped as u64); + } + const MAX_CHECK: usize = 256 << 20; + if len > MAX_CHECK { + return None; + } + let resolve_byte = |addr: usize| -> Option { + match crate::hle::kernelx::mirrors::mapped_source(addr) { + Some(Some(backing)) => Some(backing), + Some(None) => None, + None => crate::hle::kernelx::mirrors::source(addr), + } + }; + let resolved = resolve_byte(start)?; + if !u.contains(resolved) { + return None; + } + if len > 0 { + let end = start.checked_add(len - 1)?; + let resolved_end = resolved.checked_add(len - 1)?; + if !u.contains(resolved_end) { + return None; + } + const PAGE: usize = crate::hle::kernelx::mirrors::PAGE; + let mut page = (start & !(PAGE - 1)).checked_add(PAGE); + while let Some(p) = page { + if p > end { + break; + } + let expected = resolved.checked_add(p - start)?; + if resolve_byte(p) != Some(expected) { + return None; + } + page = p.checked_add(PAGE); + } + } + let n = GPU_VIEW_BUFFER_HITS.fetch_add(1, Ordering::Relaxed); + if n < 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: resolved GPU-view buffer/root VA {va:#x} -> UMA {resolved:#x} ({len} B, {} resolved)", n + 1); + } + Some(resolved as u64) +} /// 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. -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 { - note_buffer_view(); - return [0; 4]; - }; +fn buffer_view(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool, read_only: bool) -> [u32; 4] { let fmt = crate::gpu::desc::gfx10_format(format).unwrap_or(22); let (stride, elem) = if raw { (0, 4) @@ -1268,10 +1608,36 @@ fn buffer_view(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_ let e = crate::gpu::desc::format_bytes(fmt); (e, e) }; - let base = at as u64 + first * elem as u64; - let room = (bytes as u64).saturating_sub(first * elem as u64); - let records = if stride == 0 { (n as u64 * 4).min(room) } else { (n as u64).min(room / stride as u64) }; - crate::gpu::desc::buffer_words(base, stride, records as u32, fmt) + if let Some((at, bytes)) = console_buffer(res) { + let base = at as u64 + first * elem as u64; + let room = (bytes as u64).saturating_sub(first * elem as u64); + let records = if stride == 0 { (n as u64 * 4).min(room) } else { (n as u64).min(room / stride as u64) }; + return crate::gpu::desc::buffer_words(base, stride, records as u32, fmt); + } + if let Some((ta, width)) = title_address(res).and_then(|ta| { + let raw_ptr = res as *mut c_void; + let w = unsafe { ID3D12Resource::from_raw_borrowed(&raw_ptr) }.map(|r| unsafe { r.GetDesc().Width as usize })?; + Some((ta, w)) + }) { + let off = first.saturating_mul(elem as u64); + let room = (width as u64).saturating_sub(off); + let records = if stride == 0 { (n as u64 * 4).min(room) } else { (n as u64).min(room / stride as u64) }; + let view_bytes = if stride == 0 { records } else { records.saturating_mul(stride as u64) } as usize; + let target = (ta as u64).saturating_add(off); + let resolved = resolve_uma_va(target, view_bytes) + .or_else(|| { + if read_only { + super::sparse::gpu_view::base_for(target as usize, view_bytes).map(|b| b as u64) + } else { + unsafe { ensure_outside_buffer(target as usize, view_bytes, false, true).map(|(_, u)| u as u64) } + } + }); + if let Some(base) = resolved { + return crate::gpu::desc::buffer_words(base, stride, records as u32, fmt); + } + } + note_buffer_view(); + [0; 4] } /// Console buffer → a placed resource in the unified memory heap, so its console address is @@ -1322,7 +1688,10 @@ unsafe fn place_console_texture(this: *mut c_void, desc: usize, state: usize, cl u.free(p); return None; } - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, size as usize, true)); + UMA_BUFFERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, size as usize, true)); + if dred_on() { + name_resource(*ppv, &format!("xcl uma_tex p={p:#x}")); + } Some(hr) } @@ -1346,10 +1715,10 @@ fn has_coherent_headroom(u: &crate::gpu::uma::Uma, rounded: usize) -> bool { /// Sparse-backed buffers whose `Map(0, NULL, ...)` should read back their full range from VRAM /// (readback buffers that spilled to sparse VRAM or `COPY_DEST` buffers in `CUSTOM + WRITE_BACK`). -static SPARSE_READBACK: Mutex>> = Mutex::new(None); +static SPARSE_READBACK: std::sync::RwLock>> = std::sync::RwLock::new(None); fn note_sparse_readback(res: usize) { - SPARSE_READBACK.lock().unwrap().get_or_insert_with(HashSet::new).insert(res); + SPARSE_READBACK.write().unwrap().get_or_insert_with(HashSet::new).insert(res); } /// Whether `props` asks for CPU-cached readback memory. On Xbox UMA, `D3D12_HEAP_TYPE_CUSTOM` @@ -1378,9 +1747,12 @@ fn is_cpu_readback_buffer(props: &D3D12_HEAP_PROPERTIES, state: u32, flags: D3D1 unsafe fn place_console_buffer_sparse(this: *mut c_void, d: &D3D12_RESOURCE_DESC, bytes: usize, state: u32, readback_on_null_map: bool, riid: *const GUID, ppv: *mut *mut c_void) -> Option { let (p, _) = super::sparse::alloc(bytes, 0x1_0000)?; if let Some((hr, delta)) = super::sparse::place_buffer(this, p, d, state, riid, ppv) { - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); + UMA_BUFFERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); + if dred_on() { + name_resource(*ppv, &format!("xcl sparse_buf p={p:#x} sz={bytes:#x}")); + } if delta != 0 { - BUFFER_DELTA.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); + BUFFER_DELTA.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); } if readback_on_null_map { note_sparse_readback(*ppv as usize); @@ -1403,7 +1775,7 @@ fn sanitize_coherent_buffer(desc: &D3D12_RESOURCE_DESC, state: usize) -> (D3D12_ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> Option { let u = crate::gpu::uma::get()?; - if UMA_BUFFER.lock().unwrap().is_empty() || ppv.is_null() { + if UMA_BUFFER.read().unwrap().is_empty() || ppv.is_null() { return None; } let d: D3D12_RESOURCE_DESC = std::ptr::read(desc as *const D3D12_RESOURCE_DESC); @@ -1444,7 +1816,10 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta } return None; } - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); + UMA_BUFFERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); + if dred_on() { + name_resource(*ppv, &format!("xcl uma_buf p={p:#x} sz={bytes:#x}")); + } // Map must hand out the same memory the shaders read (checked once) static CHECKED: AtomicU64 = AtomicU64::new(0); if CHECKED.fetch_add(1, Ordering::Relaxed) == 0 { @@ -1469,53 +1844,100 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta /// title's allocation stays the title's. pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: &[u8; 0x38], state: u32, clear: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { let u = crate::gpu::uma::get()?; - let k = u.window_of(va)?; - let (base, size) = u.window(k); let mut d: D3D12_RESOURCE_DESC = std::ptr::read_unaligned(desc.as_ptr() as *const D3D12_RESOURCE_DESC); let bytes = d.Width as usize; + if bytes == 0 { + return None; + } + let (va, outside_base) = match u.window_of(va) { + Some(_) => (va, None), + None => { + if let Some(resolved) = resolve_uma_va(va as u64, bytes) { + let tb = OUTSIDE_BUFFERS.write().unwrap().retain_existing(va, bytes, true, false).map(|(tb, _)| tb); + (resolved as usize, tb) + } else if u.has_sparse() && is_gpu_writable_placed_buffer(&d, state) { + let (tb, mapped) = ensure_outside_buffer(va, bytes, true, false)?; + (mapped, Some(tb)) + } else { + return None; + } + } + }; + let k = match u.window_of(va) { + Some(k) => k, + None => { + if let Some(tb) = outside_base { + release_outside_ref(tb); + } + return None; + } + }; + let (base, size) = u.window(k); // 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`) let start = va & !0xFFFF; let delta = va - start; - if bytes == 0 || va - base + bytes > size { + if va - base + bytes > size { + if let Some(tb) = outside_base { + release_outside_ref(tb); + } return None; } // the title's own memory (a sparse window): a resource over its video-memory tiles if u.is_sparse(va) { - let (hr, delta) = super::sparse::place_buffer(this, va, &d, state, riid, ppv)?; - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false)); + let Some((hr, delta)) = super::sparse::place_buffer(this, va, &d, state, riid, ppv) else { + if let Some(tb) = outside_base { + release_outside_ref(tb); + } + return None; + }; + UMA_BUFFERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false)); + if let Some(tb) = outside_base { + OUTSIDE_RES.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, tb); + } if delta != 0 { - BUFFER_DELTA.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); + BUFFER_DELTA.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); } return Some(hr); } - let heap = (*UMA_HEAPS.lock().unwrap().get(k)?)?; + let Some(heap) = UMA_HEAPS.lock().unwrap().get(k).copied().flatten() else { + if let Some(tb) = outside_base { + release_outside_ref(tb); + } + return None; + }; 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); if hr < 0 || (*ppv).is_null() { + if let Some(tb) = outside_base { + release_outside_ref(tb); + } return None; } - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false)); + UMA_BUFFERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false)); + if let Some(tb) = outside_base { + OUTSIDE_RES.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, tb); + } if delta != 0 { - BUFFER_DELTA.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); + BUFFER_DELTA.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); } Some(hr) } /// buffers placed below their console address: resource → bytes before it -static BUFFER_DELTA: Mutex>> = Mutex::new(None); +static BUFFER_DELTA: std::sync::RwLock>> = std::sync::RwLock::new(None); /// Where offset 0 of a console buffer is in its PC resource (0 for most). pub fn buffer_delta(res: usize) -> u64 { - BUFFER_DELTA.lock().unwrap().as_ref().and_then(|m| m.get(&res).copied()).unwrap_or(0) + BUFFER_DELTA.read().unwrap().as_ref().and_then(|m| m.get(&res).copied()).unwrap_or(0) } #[cfg(test)] pub(super) fn set_test_buffer_delta(res: usize, delta: Option) { - let mut g = BUFFER_DELTA.lock().unwrap(); + let mut g = BUFFER_DELTA.write().unwrap(); match delta { Some(d) => { g.get_or_insert_with(HashMap::new).insert(res, d); @@ -1560,6 +1982,9 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v // the start of the PC resource, before the address for a buffer placed below it) if let Some((p, bytes)) = console_buffer(this as usize) { if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(p)) { + // If this buffer uses a lazy VRAM-only sparse backing (`alloc_vram_only`, #2582), + // commit its CPU pages before readback or returning the pointer to the title. + let _opened = crate::hle::kernelx::lazy::ensure(p, bytes); if !range.is_null() { let r = *(range as *const D3D12_RANGE); if r.End > r.Begin { @@ -1569,14 +1994,14 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v super::sparse::readback_now(p + begin, end - begin); } } - } else if SPARSE_READBACK.lock().unwrap().as_ref().is_some_and(|s| s.contains(&(this as usize))) { + } else if SPARSE_READBACK.read().unwrap().as_ref().is_some_and(|s| s.contains(&(this as usize))) { super::sparse::readback_now(p, bytes); } } if !data.is_null() { *data = p as *mut c_void; } - UNMAPPABLE.lock().unwrap().get_or_insert_with(HashSet::new).insert(this as usize); + UNMAPPABLE.write().unwrap().get_or_insert_with(HashSet::new).insert(this as usize); return S_OK; } // the PC's Map only on a resource it can map: on a reserved one or one without CPU pages it is @@ -1590,12 +2015,12 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v if hr >= 0 { return hr; } - match super::title_textures::address(this as usize).or_else(|| TITLE_ADDRESS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied())) { + match super::title_textures::address(this as usize).or_else(|| TITLE_ADDRESS.read().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied())) { Some(p) => { if !data.is_null() { *data = p as *mut c_void; } - UNMAPPABLE.lock().unwrap().get_or_insert_with(HashSet::new).insert(this as usize); + UNMAPPABLE.write().unwrap().get_or_insert_with(HashSet::new).insert(this as usize); S_OK } None => { @@ -1632,22 +2057,22 @@ unsafe extern "system" fn res_write_to_subresource(this: *mut c_void, sub: u32, /// resources the title placed at its own address that got a PC resource of their own: on the /// console Map gives that address (the CPU's view of the resource) -static TITLE_ADDRESS: Mutex>> = Mutex::new(None); +static TITLE_ADDRESS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// The title address a resource stands for (buffers in unified memory, placed resources). 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())) + console_buffer(res).map(|b| b.0).or_else(|| TITLE_ADDRESS.read().unwrap().as_ref().and_then(|m| m.get(&res).copied())) } pub(super) fn note_title_address(res: usize, va: usize) { - TITLE_ADDRESS.lock().unwrap().get_or_insert_with(HashMap::new).insert(res, va); + TITLE_ADDRESS.write().unwrap().get_or_insert_with(HashMap::new).insert(res, va); } /// resources whose Map gave their unified-memory address (no PC mapping to undo) -static UNMAPPABLE: Mutex>> = Mutex::new(None); +static UNMAPPABLE: std::sync::RwLock>> = std::sync::RwLock::new(None); 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))) { + if UNMAPPABLE.read().unwrap().as_ref().is_some_and(|s| s.contains(&(this as usize))) { return; } let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void) = std::mem::transmute(orig_fn(this, slot_of(this, "Unmap"))); @@ -1673,38 +2098,60 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { } else { f(this) }; + let mut uma_to_free: Option<(usize, bool)> = None; if n == 0 { - if let Some(s) = UNMAPPABLE.lock().unwrap().as_mut() { + uma_to_free = forget_released_resource(this, held); + } + if held { + super::late_release::hold(this as usize); + } + if let Some((p, sparse)) = uma_to_free { + super::late_release::hold_uma(p, sparse); + } + n +} + +/// What XCL keeps of a resource the title released for good, forgotten; its unified memory, if +/// any, to give back (address, whether in a sparse window). +unsafe fn forget_released_resource(this: *mut c_void, held: bool) -> Option<(usize, bool)> { + let mut uma_to_free: Option<(usize, bool)> = None; + { + if let Some((k, bytes)) = LIVE_COMMITTED.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))) { + LIVE_BYTES[k].fetch_sub(bytes, Ordering::Relaxed); + LIVE_COUNT[k].fetch_sub(1, Ordering::Relaxed); + } + if let Some(s) = UNMAPPABLE.write().unwrap().as_mut() { s.remove(&(this as usize)); } - if let Some(s) = SPARSE_READBACK.lock().unwrap().as_mut() { + if let Some(s) = SPARSE_READBACK.write().unwrap().as_mut() { s.remove(&(this as usize)); } - if let Some(s) = RESERVED.lock().unwrap().as_mut() { + if let Some(s) = RESERVED.write().unwrap().as_mut() { s.remove(&(this as usize)); } - if let Some(m) = BUFFER_DELTA.lock().unwrap().as_mut() { + if let Some(m) = BUFFER_DELTA.write().unwrap().as_mut() { m.remove(&(this as usize)); } - if let Some(m) = TITLE_ADDRESS.lock().unwrap().as_mut() { + if let Some(m) = TITLE_ADDRESS.write().unwrap().as_mut() { m.remove(&(this as usize)); } super::sparse::forget_buffer(this as usize); - super::vram::forget(this as usize); - super::title_textures::forget(this as usize); - let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); + let recycle = super::vram::forget_for_recycle(this as usize, held); + let final_state = super::title_textures::forget(this as usize); + if let (Some(info), Some(state)) = (recycle, final_state) { + super::vram::park_recyclable(this as usize, info, state.0 as u32); + } + super::depth_uav::forget(this as usize); + super::format_alias::forget(this as usize); + super::cpu_writes::unregister_water_readback(this as usize); + super::ambient::forget_resource(this as usize); + forget_outside_resource(this as usize); + let gone = UMA_BUFFERS.write().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { - if u.is_sparse(p) { - super::sparse::free(p); - } else { - u.free(p); - } + uma_to_free = Some((p, u.is_sparse(p))); } } - if held { - super::late_release::hold(this as usize); - } - n + uma_to_free } /// A stand-in that is no driver object (`standin`) was released for good. @@ -1715,9 +2162,19 @@ pub(super) fn standin_released(pso: usize) { /// A stand-in pipeline released for good takes its background-built real pipeline with it. unsafe extern "system" fn pso_release(this: *mut c_void) -> u32 { + let add: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + // The last reference: forgotten while the object has its address. A pipeline another thread + // makes can get that address as soon as it is free, and must keep its own entries. + let last = add(this) == 2; + if last { + forget_pso(this as usize); + super::pso_async::release(super::pso_async::released(this as usize)); + } + f(this); let n = f(this); - if n == 0 { + // (two last-but-one releases at once: neither saw itself as the last) + if n == 0 && !last { forget_pso(this as usize); super::pso_async::release(super::pso_async::released(this as usize)); } @@ -1727,94 +2184,260 @@ unsafe extern "system" fn pso_release(this: *mut c_void) -> u32 { /// A pipeline state is gone: drop what XCL keeps by its address (a later pipeline may get the /// same address and must not inherit its root signature or compute pass). /// compute pipelines that run a translated console shader -static TRANSLATED_COMPUTE: Mutex>> = Mutex::new(None); +static TRANSLATED_COMPUTE: std::sync::RwLock>> = std::sync::RwLock::new(None); /// graphics pipelines built from translated console shaders -static TRANSLATED_GRAPHICS: Mutex>> = Mutex::new(None); +static TRANSLATED_GRAPHICS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// Whether `pso` is a graphics pipeline of translated console shaders. /// `XCL_TRACE_FRAME`: the console VS and PS (their dump names' hashes) of a translated PSO. -static PSO_SHADERS: Mutex>> = Mutex::new(None); +static PSO_SHADERS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// translated pipeline → its input layout as text (`XCL_TRACE_FRAME`) -static PSO_LAYOUTS: Mutex>> = Mutex::new(None); +static PSO_LAYOUTS: std::sync::RwLock>> = std::sync::RwLock::new(None); pub fn pso_layout(pso: usize) -> Option { - PSO_LAYOUTS.lock().unwrap().as_ref()?.get(&pso).cloned() + PSO_LAYOUTS.read().unwrap().as_ref()?.get(&pso).cloned() } pub fn pso_shaders(pso: usize) -> Option<(u64, u64)> { - PSO_SHADERS.lock().unwrap().as_ref()?.get(&pso).copied() + PSO_SHADERS.read().unwrap().as_ref()?.get(&pso).copied() } pub fn is_translated_graphics(pso: usize) -> bool { - pso != 0 && TRANSLATED_GRAPHICS.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) + pso != 0 && TRANSLATED_GRAPHICS.read().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) } /// graphics pipelines given the generated rect list GS (`rect_list_gs`) -static RECT_LIST_GS: Mutex>> = Mutex::new(None); +static RECT_LIST_GS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// Whether `pso` (as `is_translated_graphics` takes it: a stand-in resolved) draws rect lists /// whole with the generated GS. Its draws must not be expanded to two triangles a rect as well: /// each half is three corners of the rect and the GS would complete both. pub fn has_rect_list_gs(pso: usize) -> bool { - pso != 0 && RECT_LIST_GS.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) + pso != 0 && RECT_LIST_GS.read().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) } /// Note `pso`, made from `copy`, if it kept the generated rect list GS (`rect_gs`; a pipeline /// made again without it, `retry_without_rect_gs`, did not). fn note_rect_list_gs(pso: usize, copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, rect_gs: bool) { if pso != 0 && rect_gs && !copy.GS.pShaderBytecode.is_null() { - RECT_LIST_GS.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + RECT_LIST_GS.write().unwrap().get_or_insert_with(HashSet::new).insert(pso); + } +} + +/// Thread-group dimensions `[x, y, z]` of console compute PSOs (stand-in and real) for +/// `DispatchX` with `USE_THREAD_DIMENSIONS` (`0x20`). +static PSO_COMPUTE_THREADS: std::sync::RwLock>> = std::sync::RwLock::new(None); +/// Compute PSOs (stand-in and real) that issue `image_bvh*_intersect_ray`. +static BVH_TRAVERSAL_PSOS: std::sync::RwLock>> = std::sync::RwLock::new(None); +/// At least one `DispatchX(..., 0x20)` BVH builder pass succeeded with no failed builder PSOs. +static BVH_BUILD_READY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// At least one `DispatchX(..., 0x20)` BVH builder PSO failed or stayed pending: gate stays closed. +static BVH_BUILD_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Policy for gating RT traversal (`image_bvh*_intersect_ray`) and RT companion compute shaders +/// (`XCL_RT_GATE`): +/// - `hold` / `1` / unset (default): hold RT shaders back without translating, enqueueing, or +/// compiling them (0 ms compile, 0 MB RAM, no unguarded null-BVH traversal faults). Pairs +/// cleanly with `XCL_AMBIENT=auto` (`!bvh_traversal_allowed()`). +/// - `auto`: hold back RT shaders until a `DispatchX(..., 0x20)` BVH builder pass succeeds with +/// zero failed builder PSOs. +/// - `0` / `off` / `allow`: disable gating; compile and run RT shaders freely. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RtGateMode { + Off, + Auto, + Hold, +} + +fn parse_rt_gate_mode(raw: Option<&str>) -> RtGateMode { + match raw.map(|s| s.trim().to_ascii_lowercase()).as_deref() { + // `miss`: run, with every ray missing (`dxil::kernel::rt_all_miss`) + Some("0" | "off" | "false" | "allow" | "miss") => RtGateMode::Off, + Some("auto") => RtGateMode::Auto, + _ => RtGateMode::Hold, + } +} + +fn rt_gate_mode() -> RtGateMode { + static MODE: OnceLock = OnceLock::new(); + *MODE.get_or_init(|| parse_rt_gate_mode(std::env::var("XCL_RT_GATE").ok().as_deref())) +} + +fn bvh_gate_enabled() -> bool { + rt_gate_mode() != RtGateMode::Off +} + +/// Whether BVH traversal compute shaders (`image_bvh*_intersect_ray`) are allowed to run. +pub(super) fn bvh_traversal_allowed() -> bool { + match rt_gate_mode() { + RtGateMode::Off => true, + RtGateMode::Hold => false, + RtGateMode::Auto => BVH_BUILD_READY.load(Ordering::Acquire) && !BVH_BUILD_FAILED.load(Ordering::Acquire), + } +} + +/// Whether any BVH builder pass failed (all-or-nothing gate disables further partial builds). +pub(super) fn bvh_builder_failed() -> bool { + bvh_gate_enabled() && BVH_BUILD_FAILED.load(Ordering::Acquire) +} + +pub(super) fn note_bvh_builder_dispatched() { + if !BVH_BUILD_FAILED.load(Ordering::Acquire) && !BVH_BUILD_READY.swap(true, Ordering::AcqRel) { + if rt_gate_mode() == RtGateMode::Auto { + crate::xlog_info!("D3D12.X: BVH builder dispatch ready — enabling RT traversal shaders"); + } + } +} + +pub(super) fn note_bvh_builder_failed(pso: usize) { + BVH_BUILD_READY.store(false, Ordering::Release); + if !BVH_BUILD_FAILED.swap(true, Ordering::AcqRel) { + crate::xlog_warn!("D3D12.X: BVH builder PSO {pso:#x} unavailable — holding back partial BVH builds and RT traversal (XCL_RT_GATE=0 to override)"); + } +} + +pub(super) fn pso_compute_threads(pso: usize) -> Option<[u32; 3]> { + if pso == 0 { + return None; + } + PSO_COMPUTE_THREADS.read().unwrap().as_ref()?.get(&pso).copied() +} + +fn note_compute_threads(pso: usize, cs: &[u8]) { + if pso != 0 { + if let Some(t) = crate::gpu::recomp::pso::compute_threads(cs) { + PSO_COMPUTE_THREADS.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, t); + } + } +} + +/// Compute shaders that feed RT ray-tracing passes without directly issuing +/// `image_bvh*_intersect_ray` (e.g. giant screen-probe ray-activation passes). Gating them +/// alongside BVH traversal under `XCL_RT_GATE` avoids >100 s compile freezes on world entry +/// and prevents them from clearing lighting/shadow/reflection buffers before RT traversal is ready. +const RT_COMPANION_CS_HASHES: &[u64] = &[ + 0x95cc_1328_8a27_a96e, +]; + +/// Generic RT companion compute shader name fragments matched in container metadata (`PRIV`/`ILDN`). +const RT_COMPANION_CS_NAMES: &[&[u8]] = &[ + b"RaytracingResolve", + b"ScreenProbes_ActivateRays", + b"IrradianceCache_Shade", +]; + +fn parse_rt_skip_hashes(raw: &str) -> HashSet { + raw.split(|c: char| c == ',' || c == ';' || c.is_ascii_whitespace()) + .filter_map(|tok| { + let t = tok.trim().trim_start_matches("0x").trim_start_matches("0X"); + (!t.is_empty()).then(|| u64::from_str_radix(t, 16).ok()).flatten() + }) + .collect() +} + +/// Optional extra 64-bit shader hashes to gate under `XCL_RT_GATE` (`XCL_RT_SKIP_HASHES=hex1,hex2`). +fn extra_rt_skip_hashes() -> &'static HashSet { + static SET: OnceLock> = OnceLock::new(); + SET.get_or_init(|| std::env::var("XCL_RT_SKIP_HASHES").map_or_else(|_| HashSet::new(), |v| parse_rt_skip_hashes(&v))) +} + +fn is_rt_gated_cs_hash(hash: u64) -> bool { + RT_COMPANION_CS_HASHES.contains(&hash) || extra_rt_skip_hashes().contains(&hash) +} + +/// Whether a console compute shader container is a ray-tracing program (traversal or companion), +/// whatever `XCL_RT_GATE` does with it. +pub(crate) fn rt_gated_program(cs: &[u8]) -> bool { + is_rt_gated_cs(cs) +} + +fn is_rt_gated_cs(cs: &[u8]) -> bool { + is_rt_gated_cs_hash(crate::gpu::shader::fnv64(cs)) + || crate::gpu::effects::container_contains_ascii_any(cs, RT_COMPANION_CS_NAMES) + || crate::gpu::effects::uses_bvh_intersect(cs) +} + +/// Whether a console compute shader container is currently held back without compiling under +/// `XCL_RT_GATE=hold` (default). Shared by offline `xcl shaders --precompile` so prebuilds skip +/// the exact same RT traversal and RT companion shaders that runtime holds back. +pub(crate) fn rt_gated_compute_held(cs: &[u8]) -> bool { + rt_gate_mode() == RtGateMode::Hold && is_rt_gated_cs(cs) +} + +fn note_bvh_traversal(pso: usize, cs: &[u8]) { + if pso != 0 && is_rt_gated_cs(cs) { + BVH_TRAVERSAL_PSOS.write().unwrap().get_or_insert_with(HashSet::new).insert(pso); } } -/// Whether `pso` runs a translated console compute shader. +fn is_bvh_traversal_pso(pso: usize) -> bool { + pso != 0 && BVH_TRAVERSAL_PSOS.read().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) +} + +/// Raw check without BVH traversal hold-back (used by `DispatchX` builder passes). +pub(super) fn is_translated_compute_raw(pso: usize) -> bool { + pso != 0 && TRANSLATED_COMPUTE.read().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) +} + +/// Whether `pso` runs a translated console compute shader (holding back BVH traversal shaders +/// until a full BVH build has succeeded with zero failed builder passes). pub fn is_translated_compute(pso: usize) -> bool { - pso != 0 && TRANSLATED_COMPUTE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) + if !is_translated_compute_raw(pso) { + return false; + } + if bvh_gate_enabled() && is_bvh_traversal_pso(pso) && !bvh_traversal_allowed() { + static LOGGED: std::sync::Once = std::sync::Once::new(); + LOGGED.call_once(|| { + crate::xlog_info!("D3D12.X: holding back BVH traversal compute dispatches until BVH builders succeed (XCL_RT_GATE=0 to disable)"); + }); + return false; + } + true } /// compute pipelines the title made from a console shader that runs untranslated: a background /// build's stand-in (until it is resolved) and the fallback of a console shader that failed -static CONSOLE_COMPUTE: Mutex>> = Mutex::new(None); +static CONSOLE_COMPUTE: std::sync::RwLock>> = std::sync::RwLock::new(None); unsafe fn note_console_compute(hr: HRESULT, ppv: *mut *mut c_void) { if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { - CONSOLE_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + CONSOLE_COMPUTE.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); } } /// Whether `pso` was made from a console compute shader (translated or not); a native PC /// compute pipeline is not. pub fn is_console_compute(pso: usize) -> bool { - pso != 0 && CONSOLE_COMPUTE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) + pso != 0 && CONSOLE_COMPUTE.read().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) } #[cfg(test)] pub(super) fn register_console_compute_for_test(pso: usize) { if pso != 0 { - CONSOLE_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + CONSOLE_COMPUTE.write().unwrap().get_or_insert_with(HashSet::new).insert(pso); } } #[cfg(test)] pub(super) fn register_translated_compute_for_test(pso: usize) { if pso != 0 { - TRANSLATED_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + TRANSLATED_COMPUTE.write().unwrap().get_or_insert_with(HashSet::new).insert(pso); } } #[cfg(test)] pub(super) fn register_rect_list_gs_for_test(pso: usize) { if pso != 0 { - RECT_LIST_GS.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + RECT_LIST_GS.write().unwrap().get_or_insert_with(HashSet::new).insert(pso); } } #[cfg(test)] pub(super) fn register_translated_graphics_for_test(pso: usize) { if pso != 0 { - TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + TRANSLATED_GRAPHICS.write().unwrap().get_or_insert_with(HashSet::new).insert(pso); } } @@ -1824,29 +2447,35 @@ pub(super) fn forget_pso_for_test(pso: usize) { } fn forget_pso(pso: usize) { - super::dred::forget_pso(pso); dispatch_chain::forget(pso); - if let Some(s) = TRANSLATED_COMPUTE.lock().unwrap().as_mut() { + super::dred::forget_pso(pso); + if let Some(s) = TRANSLATED_COMPUTE.write().unwrap().as_mut() { s.remove(&pso); } - if let Some(s) = CONSOLE_COMPUTE.lock().unwrap().as_mut() { + if let Some(s) = CONSOLE_COMPUTE.write().unwrap().as_mut() { s.remove(&pso); } - if let Some(s) = TRANSLATED_GRAPHICS.lock().unwrap().as_mut() { + if let Some(s) = TRANSLATED_GRAPHICS.write().unwrap().as_mut() { s.remove(&pso); } - if let Some(s) = RECT_LIST_GS.lock().unwrap().as_mut() { + if let Some(s) = RECT_LIST_GS.write().unwrap().as_mut() { s.remove(&pso); } - if let Some(m) = PSO_RS.lock().unwrap().as_mut() { + if let Some(m) = PSO_RS.write().unwrap().as_mut() { + m.remove(&pso); + } + if let Some(m) = PSO_USER_SGPRS.write().unwrap().as_mut() { m.remove(&pso); } - if let Some(m) = PSO_USER_SGPRS.lock().unwrap().as_mut() { + if let Some(m) = PSO_COMPUTE_THREADS.write().unwrap().as_mut() { m.remove(&pso); } + if let Some(s) = BVH_TRAVERSAL_PSOS.write().unwrap().as_mut() { + s.remove(&pso); + } super::device_x::forget_base(pso); // the compute pass goes with the last user of its entry (`Drop for TwoPassPso`) - let gone = TWO_PASS.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)); + let gone = TWO_PASS.write().unwrap().as_mut().and_then(|m| m.remove(&pso)); drop(gone); } @@ -1861,7 +2490,7 @@ unsafe extern "system" fn res_gpu_va_x(this: *mut c_void) -> u64 { // through it: with 0 it wrote 256 KB at address 0): the title's address it was placed at match f(this) { 0 => { - let placed = TITLE_ADDRESS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied()); + let placed = TITLE_ADDRESS.read().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied()); placed.or_else(|| texture_memory(this)).unwrap_or(0) as u64 } va => va, @@ -1878,7 +2507,7 @@ unsafe fn texture_memory(res: *mut c_void) -> Option { use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_RESERVE, PAGE_READWRITE}; static LOCK: Mutex<()> = Mutex::new(()); let _g = LOCK.lock().unwrap(); - if let Some(p) = TITLE_ADDRESS.lock().unwrap().as_ref().and_then(|m| m.get(&(res as usize)).copied()) { + if let Some(p) = TITLE_ADDRESS.read().unwrap().as_ref().and_then(|m| m.get(&(res as usize)).copied()) { return Some(p); } let d = ID3D12Resource::from_raw_borrowed(&res)?.GetDesc(); @@ -1927,11 +2556,15 @@ unsafe extern "system" fn dev_create_cbv_x(this: *mut c_void, desc: *const D3D12 return f(this, desc, cpu); }; let (va, size) = desc.as_ref().map_or((0, 0), |d| (d.BufferLocation, d.SizeInBytes)); - let in_uma = crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize)); - if !in_uma { - note_buffer_view(); - } - let (va, size) = if in_uma { (va, size) } else { (0, 0) }; + let resolved = resolve_uma_va(va, size as usize) + .or_else(|| super::sparse::gpu_view::base_for(va as usize, size as usize).map(|b| b as u64)); + let (va, size) = match resolved { + Some(b) => (b, size), + None => { + note_buffer_view(); + (0, 0) + } + }; super::console_heap::write(&slot, &crate::gpu::desc::cbv_words(va, size)); } @@ -1948,21 +2581,19 @@ pub(super) unsafe extern "system" fn dev_create_sampler_x(this: *mut c_void, des /// Copy `n` console slots from `src` to `dst` (both in console heaps of one kind): the PC /// descriptors (2 per view slot) and the slots. False: not two console ranges. unsafe fn copy_console_slots(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) -> bool { - use super::console_heap::{copy_words, slot, SAMPLER_SLOT, SLOT}; - let (Some(d0), Some(s0)) = (slot(dst), slot(src)) else { return false }; + use super::console_heap::{copy_words_range, slot_pair}; + let Some((d0, s0)) = slot_pair(dst, src) else { return false }; if d0.sampler != s0.sampler { return false; } + if n == 0 || d0.at == s0.at { + return true; + } let ty = pc_heap_type(ty); let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24)); f(this, if d0.sampler { n } else { 2 * n }, d0.pc_srv, s0.pc_srv, ty); super::console_heap::publish_range(&d0, n); - let step = if d0.sampler { SAMPLER_SLOT } else { SLOT } as u64; - 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); - } - } + copy_words_range(dst, src, n); true } @@ -1987,6 +2618,9 @@ fn note_mixed_copy() { unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) { let ty = pc_heap_type(ty); note_copy_call("CopyDescriptorsSimple", n, dst, src); + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_RTV.0 as u32 || ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 { + super::list_x::bump_rt_desc_gen(); + } if copy_console_slots(this, n, dst, src, ty) { return; } @@ -1996,6 +2630,11 @@ unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u3 } let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24)); f(this, n, dst, src, ty); + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 && n > 0 && super::depth_uav::any() { + let get_inc: unsafe extern "system" fn(*mut c_void, u32) -> u32 = std::mem::transmute(orig_fn(this, 15)); + let inc = get_inc(this, ty) as usize; + super::depth_uav::copy_dsv(dst as usize, src as usize, n, inc); + } } /// #23 CopyDescriptors(dst ranges, src ranges, type): range by range over console slots. @@ -2003,6 +2642,9 @@ 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 }); + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_RTV.0 as u32 || ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 { + super::list_x::bump_rt_desc_gen(); + } use super::console_heap::{slot, SAMPLER_SLOT, SLOT}; let console = !dsts.is_null() && !srcs.is_null() && nd > 0 && slot(*dsts).is_some(); if !console { @@ -2012,33 +2654,77 @@ unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dst } type F = unsafe extern "system" fn(*mut c_void, u32, *const u64, *const u32, u32, *const u64, *const u32, u32); let f: F = std::mem::transmute(orig_fn(this, 23)); - return f(this, nd, dsts, dsizes, ns, srcs, ssizes, ty); + f(this, nd, dsts, dsizes, ns, srcs, ssizes, ty); + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 && !dsts.is_null() && !srcs.is_null() && nd > 0 && ns > 0 && super::depth_uav::any() { + let get_inc: unsafe extern "system" fn(*mut c_void, u32) -> u32 = std::mem::transmute(orig_fn(this, 15)); + let inc = get_inc(this, ty) as usize; + let (mut di, mut si) = (0usize, 0usize); + let (mut d_rem, mut s_rem) = (0u32, 0u32); + let (mut d_cur, mut s_cur) = (0u64, 0u64); + loop { + while d_rem == 0 { + if di >= nd as usize { + return; + } + d_cur = *dsts.add(di); + d_rem = if dsizes.is_null() { 1 } else { *dsizes.add(di) }; + di += 1; + } + while s_rem == 0 { + if si >= ns as usize { + return; + } + s_cur = *srcs.add(si); + s_rem = if ssizes.is_null() { 1 } else { *ssizes.add(si) }; + si += 1; + } + let run = d_rem.min(s_rem); + super::depth_uav::copy_dsv(d_cur as usize, s_cur as usize, run, inc); + d_cur = d_cur.wrapping_add(run as u64 * inc as u64); + s_cur = s_cur.wrapping_add(run as u64 * inc as u64); + d_rem -= run; + s_rem -= run; + } + } + return; } - // every descriptor as (dst, src) handle, ranges walked in step + // Walk (dst, src) ranges in lockstep with zero heap allocations, batching each maximal + // contiguous overlap into a single `copy_console_slots` call. let step = if ty == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32 { SAMPLER_SLOT } else { SLOT } as u64; - let expand = |starts: *const u64, sizes: *const u32, n: u32| -> Vec { - (0..n as usize).flat_map(|r| { - let (h, len) = (*starts.add(r), if sizes.is_null() { 1 } else { *sizes.add(r) }); - (0..len as u64).map(move |k| h + k * step) - }) - .collect() - }; - let (d, s) = (expand(dsts, dsizes, nd), expand(srcs, ssizes, ns)); - for (a, b) in d.iter().zip(s.iter()) { - if !copy_console_slots(this, 1, *a, *b, ty) { + let (mut di, mut si) = (0usize, 0usize); + let (mut d_rem, mut s_rem) = (0u32, 0u32); + let (mut d_cur, mut s_cur) = (0u64, 0u64); + loop { + while d_rem == 0 { + if di >= nd as usize { + return; + } + d_cur = *dsts.add(di); + d_rem = if dsizes.is_null() { 1 } else { *dsizes.add(di) }; + di += 1; + } + while s_rem == 0 { + if si >= ns as usize { + return; + } + s_cur = *srcs.add(si); + s_rem = if ssizes.is_null() { 1 } else { *ssizes.add(si) }; + si += 1; + } + let run = d_rem.min(s_rem); + if !copy_console_slots(this, run, d_cur, s_cur, ty) { note_mixed_copy(); } + d_cur = d_cur.wrapping_add(run as u64 * step); + s_cur = s_cur.wrapping_add(run as u64 * step); + d_rem -= run; + s_rem -= run; } } /// descriptor heap Release (every caller): a console heap's slots go with it unsafe extern "system" fn heap_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); - if n == 0 { - super::console_heap::unregister(this as usize); - } - n + release_taking_first(this, || super::console_heap::take(this as usize), |h| h.into_iter().for_each(super::console_heap::free)) } /// Default UAV dimension for a texture resource when `CreateUnorderedAccessView` receives a NULL desc. @@ -2114,12 +2800,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 { @@ -2142,7 +2823,10 @@ unsafe extern "system" fn dev_create_dsv_x(this: *mut c_void, res: *mut c_void, if copy.is_none() { copy = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| default_dsv(&r.GetDesc())); } - f(this, res, copy.as_ref().map_or(desc, |c| c as *const _), cpu) + let dsv_flags = copy.as_ref().map_or(0, |c| c.Flags.0 as u32); + f(this, res, copy.as_ref().map_or(desc, |c| c as *const _), cpu); + super::list_x::bump_rt_desc_gen(); + super::depth_uav::note_dsv(cpu as usize, res as usize, dsv_flags); } /// The view a DSV without a description has, for a depth buffer `pc_resource_desc` made @@ -2236,7 +2920,8 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } // a depth buffer's view in the formats the PC has for it (a D24S8 format itself, R16_UNORM of // a D16S8 buffer …: an invalid call, the device removed) - if let Some(v) = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| pc_srv(&r.GetDesc(), copy.as_ref())) { + let rdesc_opt = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()); + if let Some(v) = rdesc_opt.as_ref().and_then(|rd| pc_srv(rd, copy.as_ref())) { copy = Some(v); } let desc = copy.as_ref().map_or(desc, |c| c as *const _); @@ -2283,15 +2968,16 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, if super::present::trace_frame() && super::title_textures::address(res as usize).is_some() { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 24 { - let rd = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()); let v = desc.as_ref().map(|v| (v.Format.0, v.ViewDimension.0, v.Shader4ComponentMapping, v.Anonymous.Texture2D.MostDetailedMip, v.Anonymous.Texture2D.MipLevels, v.Anonymous.Texture2D.ResourceMinLODClamp)); crate::xlog_info!( "frame trace: SRV of title texture {res:p} {:?}: view (format, dimension, mapping, mip, mips, clamp) {v:x?}", - rd.map(|d| (d.Width, d.Height, d.Format.0, d.MipLevels, d.Flags.0)) + rdesc_opt.map(|d| (d.Width, d.Height, d.Format.0, d.MipLevels, d.Flags.0)) ); } } - let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else { + let amb_idx = if slot.shared_srv != 0 { slot.index } else { 0 }; + let Some(rdesc) = rdesc_opt else { + super::ambient::note_descriptor(slot.at, amb_idx, 0, 0, 0, false); // 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. @@ -2305,11 +2991,13 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, return super::console_heap::write(&slot, &[0; 8]); }; 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)); + return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, true)); } - 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); match srv_tsharp_from_desc(slot.index, &rdesc, desc.as_ref()) { Some(t) => super::console_heap::write(&slot, &t), None => { @@ -2341,33 +3029,6 @@ fn cube_as_cube_array(v: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> Option *mut c_void { - type Key = (u64, [u8; 0x38]); - static MADE: Mutex>> = Mutex::new(None); - if desc.is_null() || va == 0 || !crate::gpu::shader::readable(desc as usize, 0x38) { - return std::ptr::null_mut(); - } - // the PC part of the desc; the flags (@0x30) are its last dword, padding follows - let mut x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); - x[0x34..].fill(0); - if let Some(&r) = MADE.lock().unwrap().get_or_insert_with(HashMap::new).get(&(va, x)) { - return r as *mut c_void; - } - let mut r = std::ptr::null_mut(); - let hr = super::device_x::create_placed_resource_x(this, va, x.as_ptr(), 0, std::ptr::null(), &ID3D12Resource::IID as *const _ as *const 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: view at {va:#x}: the resource cannot be made ({hr:#x}); desc {x:02x?}"); - } - r = std::ptr::null_mut(); - } - MADE.lock().unwrap().get_or_insert_with(HashMap::new).insert((va, x), r as usize); - r -} - /// device #70 (a retail game): a shader resource view of memory, without a resource object: /// (resource desc, { the PC's SRV desc; GPU address @0x28; … }, destination). unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u8, view: *const u8, cpu: u64) { @@ -2380,10 +3041,13 @@ unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u let Some(slot) = super::console_heap::slot(cpu) else { return }; let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; - let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, true); 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; @@ -2396,16 +3060,22 @@ 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); + super::depth_uav::clear_uav_twin(slot.pc_uav as usize); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; - let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, false); 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`. -fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool) -> [u32; 4] { +/// (`read_only`: a view of a GPU view may get a readable address, `sparse::gpu_view`) +fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool, read_only: bool) -> [u32; 4] { let fmt = crate::gpu::desc::gfx10_format(format).unwrap_or(22); let (stride, elem) = match (raw, stride) { (true, _) => (0, 4), @@ -2416,7 +3086,18 @@ fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI (false, s) => (s, s), }; let records = if stride == 0 { n.saturating_mul(4) } else { n }; - crate::gpu::desc::buffer_words(va + first * elem as u64, stride, records, fmt) + let target = va.saturating_add(first.saturating_mul(elem as u64)); + let len = (n as u64).saturating_mul(elem as u64) as usize; + let base = resolve_uma_va(target, len) + .or_else(|| { + if read_only { + super::sparse::gpu_view::base_for(target as usize, len).map(|b| b as u64) + } else { + unsafe { ensure_outside_buffer(target as usize, len, false, true).map(|(_, u)| u as u64) } + } + }) + .unwrap_or(target); + crate::gpu::desc::buffer_words(base, stride, records, fmt) } fn resolve_uav_array_size(array_size: u32, total_slices: u32, first_slice: u32) -> u32 { @@ -2436,9 +3117,15 @@ 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 { + 1 => D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + ..Default::default() + }, 2 => D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_FLOAT, ViewDimension: D3D12_UAV_DIMENSION_TEXTURE1D, @@ -2451,7 +3138,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 { @@ -2473,6 +3160,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`), @@ -2512,7 +3230,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) @@ -2539,6 +3257,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, @@ -2562,7 +3281,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, @@ -2570,7 +3289,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, @@ -2585,6 +3310,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, @@ -2601,25 +3334,200 @@ 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), + _ => crate::gpu::desc::gfx10_format(fmt) + .filter(|&g| (1..=77).contains(&g)) + .map(|g| crate::gpu::desc::format_bytes(g) as u64), + } +} + +/// Element byte size for a buffer UAV (`None` when the typed format is unknown). +fn buffer_uav_element_bytes(desc: &D3D12_UNORDERED_ACCESS_VIEW_DESC) -> Option { + // SAFETY: caller ensures `desc.ViewDimension == D3D12_UAV_DIMENSION_BUFFER`. + 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`). +/// - `Ok(None)`: no delta adjustment needed. +/// - `Ok(Some(patched))`: aligned delta applied (`FirstElement += res_delta / elem`, +/// `CounterOffsetInBytes += ctr_delta`). +/// - `Err(())`: delta buffer UAV cannot be safely shifted on PC (null desc, unknown element size, +/// unaligned `res_delta % elem != 0`, or unaligned counter offset mod 4096) — bind a null PC UAV +/// so PC `ClearUnorderedAccessView*` / pipelines never overwrite `[va & !0xFFFF, va)`. +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; + // SAFETY: `ViewDimension == D3D12_UAV_DIMENSION_BUFFER` verified above. + 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)) +} + 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 orig_desc = desc.as_ref().copied(); + // Route depth+UAV textures (`ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS`) to their + // writable color twin so compute writes land on a real UAV instead of a null view. + let depth_twin = super::depth_uav::resolve_uav(this, res, orig_desc.as_ref()); // the view's format as the PC's for the resource (B5G5R5A1 of a target made R8G8B8A8, // `device_x::pc_resource_desc`: an invalid call, the device removed) - let mut copy = desc.as_ref().copied(); - if let Some(c) = copy.as_mut() { - if let Some(r) = ID3D12Resource::from_raw_borrowed(&res) { - let rf = 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); - } 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() { - c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT; + let mut copy = orig_desc; + if depth_twin.is_none() { + if let Some(c) = copy.as_mut() { + if let Some(r) = ID3D12Resource::from_raw_borrowed(&res) { + let rf = 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); + } 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() { + c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT; + } } } } - let desc = copy.as_ref().map_or(desc, |c| c as *const _); + let (uav_res, uav_desc) = match &depth_twin { + Some((twin_res, patched)) => (*twin_res, patched as *const D3D12_UNORDERED_ACCESS_VIEW_DESC), + None => (res, copy.as_ref().map_or(desc, |c| c as *const _)), + }; super::present::note_use(res as usize, super::present::USE_UAV); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 19)); let rd_opt = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()); @@ -2630,35 +3538,79 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, "frame trace: UAV of render target {res:p} {:?} at {cpu:#x}: console slot {:?}, view {:?}", rd_opt.map(|d| (d.Width, d.Height, d.Format.0)), s.as_ref().map(|s| (s.index, s.pc_uav, s.at)), - desc.as_ref().map(|v| (v.Format.0, v.ViewDimension.0)) + uav_desc.as_ref().map(|v| (v.Format.0, v.ViewDimension.0)) ); } } - // a resource without ALLOW_UNORDERED_ACCESS (a console depth buffer that also had it: the PC - // 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); - let null_desc = null_uav_desc(desc.as_ref(), rd_opt.as_ref()); + // a resource without ALLOW_UNORDERED_ACCESS (a console depth buffer without a twin or + // another non-UAV resource): a null view – a UAV of it is an invalid call (0x887A0001) + let uav_rd_opt = if uav_res == res { rd_opt } else { ID3D12Resource::from_raw_borrowed(&uav_res).map(|r| r.GetDesc()) }; + let no_uav = 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(uav_res as usize); + let ctr_delta = if counter.is_null() { 0 } else { buffer_delta(counter as usize) }; + let is_buf_res = uav_rd_opt.is_some_and(|d| d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER); + let (pc_uav_desc_patched, unaligned_delta) = if depth_twin.is_none() && !no_uav { + match patch_buffer_uav_delta(uav_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(uav_desc, |d| d as *const _); + let null_desc = null_uav_desc(uav_desc.as_ref(), uav_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 let Some((twin_res, _)) = &depth_twin { + super::depth_uav::note_uav_twin(at as usize, *twin_res as usize); + } else { + super::depth_uav::clear_uav_twin(at as usize); + } if no_uav { static N: AtomicU64 = AtomicU64::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: a UAV of a resource that cannot have one on the PC (a depth buffer) – a null view"); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + if let Some(d) = uav_rd_opt { + crate::xlog_warn!( + "D3D12.X: a UAV of a resource that cannot have one on the PC (res {res:p}, fmt {}, {}x{}, samples {}, flags {:#x}) – a null view", + d.Format.0, d.Width, d.Height, d.SampleDesc.Count, d.Flags.0 + ); + } else { + crate::xlog_warn!("D3D12.X: a UAV of a resource that cannot have one on the PC (res {res:p}) – 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, uav_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::console_heap::publish(&slot, true); super::console_heap::note_resource(&slot, res as usize); - let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else { + let amb_idx = if slot.shared_srv != 0 { slot.index } else { 0 }; + let Some(r) = ID3D12Resource::from_raw_borrowed(&uav_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]`. - if let Some(v) = desc.as_ref() { + if let Some(v) = uav_desc.as_ref() { if let Some(ty) = view_dim_to_image_type(v.ViewDimension.0) { if let Some(srv) = uav_companion_srv(None, Some(v), true) { let g: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); @@ -2671,14 +3623,15 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, } return super::console_heap::write(&slot, &[0; 8]); }; - let rd = rd_opt.unwrap(); - if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER) { + let rd = uav_rd_opt.unwrap(); + if let Some(v) = uav_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)); + return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, false)); } // 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() { + let (format, dim, array, mip) = match uav_desc.as_ref() { Some(v) => { let a = &v.Anonymous; let (array, mip) = match v.ViewDimension.0 { @@ -2693,15 +3646,18 @@ 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, uav_res as usize, amb_fmt, rd.Format.0, true); let Some((fmt, ty, w, h, d, _)) = view_shape(r, format, dim, array, 1) else { note_buffer_view(); return super::console_heap::write(&slot, &[0; 8]); }; // RDNA images have no SRV / UAV distinction: console shaders may read any image UAV slot // (`image_load`, `image_sample_*`, `image_get_resinfo` all index `ResourceDescriptorHeap[slot.index]`). + // Use `uav_res` / `uav_desc` so Depth+UAV routed slots pair their SRV against the color twin. let deny_srv = rd.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 != 0; - if let Some(srv) = uav_companion_srv(Some(&rd), desc.as_ref(), deny_srv) { - let srv_res = if deny_srv { std::ptr::null_mut() } else { res }; + if let Some(srv) = uav_companion_srv(Some(&rd), uav_desc.as_ref(), deny_srv) { + let srv_res = if deny_srv { std::ptr::null_mut() } else { uav_res }; let g: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); g(this, srv_res, &srv, slot.pc_srv); super::console_heap::publish(&slot, false); @@ -2803,8 +3759,8 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro // not placed in unified memory (e.g. its coherent window kept for readback heaps): a PC // resource of the PC's description – the console's flag bits (0x1000000, 0x300000 …) and // alignments made the PC refuse Fortnite's 3264x1836 scene targets (E_INVALIDARG, a crash) - let pc_full = (console_desc != 0 && crate::gpu::shader::readable(console_desc, 0x38)) - .then(|| super::device_x::pc_resource_desc_for_device(this, &(console_desc as *const [u8; 0x38]).read_unaligned())); + let console_raw = (console_desc != 0 && crate::gpu::shader::readable(console_desc, 0x38)).then(|| (console_desc as *const [u8; 0x38]).read_unaligned()); + let pc_full = console_raw.as_ref().map(|raw| super::device_x::pc_resource_desc_for_device(this, raw)); let desc = pc_full.as_ref().map_or(desc, |d| d.as_ptr() as usize); let mut clear_buf = [0u8; 24]; let clear = match pc_full.as_ref() { @@ -2819,6 +3775,11 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro super::device_x::pc_initial_state_for_desc(orig_flags, pc_flags, state as u32) }); let hr = dev_create_committed_resource(this, props, flags, desc, st as usize, clear, riid, ppv); + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + if let Some(ref raw_x) = console_raw { + super::depth_uav::register_if_depth_uav(this, *ppv, raw_x, st, state as u32); + } + } if hr < 0 { let pw = |o: usize| if props == 0 { 0 } else { *((props + o) as *const u32) }; crate::xlog_warn!( @@ -2922,7 +3883,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { /// Slot of `method` in the class of an adopted object. unsafe fn slot_of(this: *mut c_void, method: &str) -> usize { let ext = vt(this) as usize; - let g = CLASSES.lock().unwrap(); + let g = CLASSES.read().unwrap(); let c = g.iter().find(|c| c.ext == ext).expect("adopted class"); layout::slot(c.iface, method).expect("method in layout") } @@ -2970,6 +3931,9 @@ unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { let f: RefFn = std::mem::transmute(orig_fn(this, slot_of(this, "Close"))); let hr = f(this) as HRESULT; preserve_vtable(this, ext); + if hr >= 0 && !super::title_textures::is_own_work() { + super::title_textures::note_list_closed(this); + } if hr < 0 { let ty: RefFn = std::mem::transmute(orig_fn(this, slot_of(this, "GetType"))); crate::xlog_warn!("D3D12.X: command list {this:p} (type {}) Close → {:#x}", ty(this), hr as u32); @@ -3136,7 +4100,9 @@ macro_rules! creator { if IN_CREATOR.with(|c| c.replace(true)) { return f(this, $($a,)* riid, ppv); } + let made_at = std::time::Instant::now(); let mut hr = f(this, $($a,)* riid, ppv); + super::flight::made($method, 0, made_at.elapsed()); IN_CREATOR.with(|c| c.set(false)); if hr == E_NOINTERFACE { let iid = pc_iid($kind); @@ -3151,12 +4117,87 @@ macro_rules! creator { } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { adopt(*ppv, $kind); + if $method.starts_with("CreateCommittedResource") { + note_committed(this, *ppv); + } } hr } }; } +/// local: what was committed (resources of their own heap), by shape: (heap type, dimension, +/// width, height, format) -> (made, bytes) +static COMMITTED: Mutex>> = Mutex::new(None); + +unsafe fn note_committed(dev: *mut c_void, res: *mut c_void) { + let (Some(dev), Some(r)) = (ID3D12Device::from_raw_borrowed(&dev), ID3D12Resource::from_raw_borrowed(&res)) else { return }; + let d = r.GetDesc(); + let (mut props, mut flags) = (D3D12_HEAP_PROPERTIES::default(), D3D12_HEAP_FLAGS::default()); + let _ = r.GetHeapProperties(Some(&mut props), Some(&mut flags)); + let bytes = dev.GetResourceAllocationInfo(0, &[d]).SizeInBytes; + let mut g = COMMITTED.lock().unwrap(); + let e = g.get_or_insert_with(HashMap::new).entry((props.Type.0, d.Dimension.0, d.Width, d.Height, d.Format.0)).or_default(); + e.0 += 1; + if bytes != u64::MAX { + e.1 += bytes; + // (live: until its last release, `forget_released_resource`) + let k = live_kind(props.Type.0, props.MemoryPoolPreference.0, d.Dimension.0); + LIVE_COMMITTED.lock().unwrap().get_or_insert_with(HashMap::new).insert(res as usize, (k, bytes)); + LIVE_BYTES[k].fetch_add(bytes, Ordering::Relaxed); + LIVE_COUNT[k].fetch_add(1, Ordering::Relaxed); + } +} + +/// The title's committed resources alive, by kind (`live_kind`): resource → (kind, bytes). +static LIVE_COMMITTED: Mutex>> = Mutex::new(None); +static LIVE_BYTES: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; +static LIVE_COUNT: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; +const LIVE_NAMES: [&str; 6] = ["in title memory", "video buffers", "video textures", "upload", "readback", "custom system"]; + +/// What a committed resource is for the memory line: one XCL placed in the title's memory (no +/// heap of its own), a buffer or texture in video memory, an upload or readback heap, or a +/// custom heap in system memory. +fn live_kind(heap_type: i32, pool: i32, dimension: i32) -> usize { + match (heap_type, pool) { + (0, _) => 0, + (1, _) | (4, 2) => { + if dimension == 1 { + 1 + } else { + 2 + } + } + (2, _) => 3, + (3, _) => 4, + _ => 5, + } +} + +/// The title's committed resources alive (`note_committed`), by kind: "name MB (count)". +pub fn live_committed_line() -> String { + (0..6) + .map(|k| format!("{} {} ({})", LIVE_NAMES[k], LIVE_BYTES[k].load(Ordering::Relaxed) >> 20, LIVE_COUNT[k].load(Ordering::Relaxed))) + .collect::>() + .join(", ") +} + +/// local: the committed shapes that were made since the last report, biggest first +pub fn committed_report() -> Option { + static LAST: Mutex>> = Mutex::new(None); + let now = COMMITTED.lock().unwrap().clone()?; + let mut last = LAST.lock().unwrap(); + let before = last.replace(now.clone()).unwrap_or_default(); + let mut d: Vec<_> = now.iter().map(|(k, v)| (k, v.0 - before.get(k).map_or(0, |b| b.0), v.1 - before.get(k).map_or(0, |b| b.1))).filter(|x| x.1 > 0).collect(); + d.sort_by_key(|x| std::cmp::Reverse(x.2)); + let total: u64 = d.iter().map(|x| x.2).sum(); + if total < 64 << 20 { + return None; + } + let top: Vec = d.iter().take(6).map(|(k, n, b)| format!("{n}x heap {} dim {} {}x{} fmt {}: {} MB", k.0, k.1, k.2, k.3, k.4, b >> 20)).collect(); + Some(format!("{} MB in {} resources: {}", total >> 20, d.iter().map(|x| x.1).sum::(), top.join("; "))) +} + creator!(dev_create_command_queue, "CreateCommandQueue", Kind::CommandQueue, [a1]); creator!(dev_create_command_queue1, "CreateCommandQueue1", Kind::CommandQueue, [a1, a2]); creator!(dev_create_command_allocator, "CreateCommandAllocator", Kind::CommandAllocator, [a1]); @@ -3264,7 +4305,11 @@ pub(super) unsafe extern "system" fn dev_create_placed_resource_x(this: *mut c_v u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u(0x20), u(0x2C), u(0x30) ); } - hr3.unwrap_or(hr2) + let out_hr = hr3.unwrap_or(hr2); + if out_hr >= 0 && is_texture && !ppv.is_null() && !(*ppv).is_null() { + super::depth_uav::register_if_depth_uav(this, *ppv, &x, st, state as u32); + } + out_hr } /// A texture the title placed in a heap by the console's size (`get_resource_allocation_info_x` @@ -3291,14 +4336,19 @@ unsafe fn own_memory_if_larger_on_the_pc(this: *mut c_void, heap: usize, offset: } let h = pc_heap_desc(heap)?; let st = super::device_x::pc_initial_state(u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()), state as u32); + let mut effective_st = st; let mut clear_buf = [0u8; 24]; let clear = super::device_x::pc_clear_for_desc(clear as *const c_void, u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()), &mut clear_buf) as usize; let mut hr = dev_create_committed_resource(this, &h.Properties as *const _ as usize, 0, d.as_ptr() as usize, st as usize, clear, riid, ppv); if hr < 0 && st != 0 { // as in the past-the-end fallback: a state the PC refuses for this desc (e.g. UAV // without the UAV flag) – COMMON rather than falling back to the overlapping placement + effective_st = 0; hr = dev_create_committed_resource(this, &h.Properties as *const _ as usize, 0, d.as_ptr() as usize, 0, clear, riid, ppv); } + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + super::depth_uav::register_if_depth_uav(this, *ppv, &x, effective_st, state as u32); + } static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 8 { let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); @@ -3346,23 +4396,23 @@ creator!(pc_create_reserved_resource1, "CreateReservedResource1", Kind::Resource /// `res_map` asks none of them (GetHeapProperties on one is an invalid call too, debug layer /// 901). The description guards against an address a later resource reuses without the last /// Release having been seen. -static RESERVED: Mutex>> = Mutex::new(None); +static RESERVED: std::sync::RwLock>> = std::sync::RwLock::new(None); 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); + RESERVED.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, d); } } hr } 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()); + let kept = RESERVED.read().unwrap().as_ref().and_then(|m| m.get(&(res as usize)).copied()); kept.is_some_and(|k| desc_of(res) == Some(k)) } @@ -3439,7 +4489,7 @@ struct HeapUma { /// heap → its backing block (allocated lazily on the first placed buffer; sparse VRAM for /// DEFAULT/UPLOAD/CUSTOM heaps, coherent committed window for small explicit READBACK heaps) -static HEAP_UMA: Mutex>> = Mutex::new(None); +static HEAP_UMA: std::sync::RwLock>> = std::sync::RwLock::new(None); /// A heap the title made that may hold buffers: a block of unified memory as large stands for /// it. On the console every heap is memory the CPU and the GPU address alike, and console code @@ -3456,13 +4506,13 @@ unsafe fn note_heap_uma(desc: usize, ppv: *mut *mut c_void) { return; } let d: D3D12_HEAP_DESC = std::ptr::read_unaligned(desc as *const D3D12_HEAP_DESC); - if d.Flags.0 & DENY_BUFFERS != 0 || d.SizeInBytes == 0 || UMA_BUFFER.lock().unwrap().is_empty() { + if d.Flags.0 & DENY_BUFFERS != 0 || d.SizeInBytes == 0 || UMA_BUFFER.read().unwrap().is_empty() { return; } let size = d.SizeInBytes as usize; let is_rb = d.Properties.Type == D3D12_HEAP_TYPE_READBACK; let is_custom_wb = d.Properties.Type == D3D12_HEAP_TYPE_CUSTOM && d.Properties.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; - HEAP_UMA.lock().unwrap().get_or_insert_with(HashMap::new).insert( + HEAP_UMA.write().unwrap().get_or_insert_with(HashMap::new).insert( *ppv as usize, HeapUma { size, @@ -3478,7 +4528,7 @@ unsafe fn note_heap_uma(desc: usize, ppv: *mut *mut c_void) { /// (taken now if it has none yet; None: not a heap that takes one, or unified memory is full). fn heap_block(heap: usize) -> Option<(usize, bool)> { let (size, align, prefer_coherent, cpu_readback) = { - let g = HEAP_UMA.lock().unwrap(); + let g = HEAP_UMA.read().unwrap(); let e = g.as_ref()?.get(&heap)?; if let Some(p) = e.block { return Some((p, e.cpu_readback)); @@ -3508,7 +4558,7 @@ fn heap_block(heap: usize) -> Option<(usize, bool)> { } return None; }; - let mut g = HEAP_UMA.lock().unwrap(); + let mut g = HEAP_UMA.write().unwrap(); let Some(e) = g.as_mut().and_then(|m| m.get_mut(&heap)) else { drop(g); if u.is_sparse(p) { @@ -3538,21 +4588,18 @@ fn heap_block(heap: usize) -> Option<(usize, bool)> { Some((p, cpu_readback)) } -/// ID3D12Heap::Release: its block of unified memory goes with it. +/// ID3D12Heap::Release: its block of unified memory goes with it (deferred until active GPU +/// queues finish so in-flight lists never lose their backing block). unsafe extern "system" fn mem_heap_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); - if n == 0 { - let gone = HEAP_UMA.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))).and_then(|e| e.block); - if let (Some(p), Some(u)) = (gone, crate::gpu::uma::get()) { - if u.is_sparse(p) { - super::sparse::free(p); - } else { - u.free(p); + release_taking_first( + this, + || HEAP_UMA.write().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))).and_then(|e| e.block), + |gone| { + if let (Some(p), Some(u)) = (gone, crate::gpu::uma::get()) { + super::late_release::hold_uma(p, u.is_sparse(p)); } - } - } - n + }, + ) } creator!(dev_create_fence_pc, "CreateFence", Kind::Fence, [a1, a2]); @@ -3607,6 +4654,7 @@ pub fn end_title(code: u32) -> ! { } } drain_gpu(); + crate::hle::kernelx::restore_fine_timer(); crate::log::flush(); windows_sys::Win32::System::Threading::TerminateProcess(windows_sys::Win32::System::Threading::GetCurrentProcess(), code); } @@ -3800,9 +4848,21 @@ pub fn switch_form_retries() -> u64 { /// A driver pipeline call; E_OUTOFMEMORY while this thread translates with heap windows is /// noted for `with_switch_fallback`. unsafe fn driver_pso(f: PsoFn, this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + static AMD_DRIVER_PSO_LOCK: Mutex<()> = Mutex::new(()); let heap = crate::gpu::recomp::pso::mem_windows() & crate::gpu::recomp::HEAP_WINDOWS != 0; let injected = heap && INJECTED_OOM.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)).is_ok(); - let hr = if injected { E_OUTOFMEMORY } else { f(this, desc, riid, ppv) }; + let hr = if injected { + E_OUTOFMEMORY + } else if serialize_driver_pso(this) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + crate::xlog_info!("D3D12.X: serializing driver Create*PipelineState on AMD adapter (XCL_AMD_SERIAL_PSO=0 to disable)"); + }); + let _guard = AMD_DRIVER_PSO_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + f(this, desc, riid, ppv) + } else { + f(this, desc, riid, ppv) + }; if hr == E_OUTOFMEMORY && heap { HEAP_WINDOW_OOM.with(|o| o.set(true)); } @@ -3874,32 +4934,32 @@ unsafe fn shader_bytes<'a>(b: &D3D12_SHADER_BYTECODE) -> Option<&'a [u8]> { /// Root signature of every pipeline built from translated console shaders (static samplers /// make it per pipeline): the draw binds it instead of the title's. -static PSO_RS: Mutex>> = Mutex::new(None); +static PSO_RS: std::sync::RwLock>> = std::sync::RwLock::new(None); fn note_pso_rs(pso: *mut c_void, rs: *mut c_void) { if !pso.is_null() { - PSO_RS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso as usize, rs as usize); + PSO_RS.write().unwrap().get_or_insert_with(HashMap::new).insert(pso as usize, rs as usize); } } /// user SGPRs of the console CS of a translated compute pipeline -static PSO_USER_SGPRS: Mutex>> = Mutex::new(None); +static PSO_USER_SGPRS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// How many user SGPRs the console compute shader of a translated pipeline has (None: not /// known). What is above the driver's four holds root arguments (`console_list::inline_for`). pub fn pso_user_sgprs(pso: usize) -> Option { let pso = super::pso_async::resolve(pso); - PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).copied() + PSO_USER_SGPRS.read().unwrap().as_ref()?.get(&pso).copied() } /// The root signature a translated pipeline state was created with. pub fn pso_root_signature(pso: usize) -> Option { let pso = super::pso_async::resolve(pso); - PSO_RS.lock().unwrap().as_ref()?.get(&pso).copied() + PSO_RS.read().unwrap().as_ref()?.get(&pso).copied() } /// ABI root signatures with static samplers, by sampler set (owned here, never released). -static ABI_RS_SAMPLERS: Mutex, usize>>> = Mutex::new(None); +static ABI_RS_SAMPLERS: std::sync::RwLock, usize>>> = std::sync::RwLock::new(None); /// The XCL ABI root signature with a pipeline's static samplers (the plain one without). unsafe fn abi_rs_for(this: *mut c_void, samplers: &[crate::gpu::recomp::pso::StaticSampler]) -> Option<*mut c_void> { @@ -3907,7 +4967,10 @@ unsafe fn abi_rs_for(this: *mut c_void, samplers: &[crate::gpu::recomp::pso::Sta return abi_rs_raw(this); } let key: Vec = samplers.iter().flat_map(|(w, c)| w.iter().copied().chain([*c as u32])).collect(); - let mut g = ABI_RS_SAMPLERS.lock().unwrap(); + if let Some(&rs) = ABI_RS_SAMPLERS.read().unwrap().as_ref().and_then(|m| m.get(&key)) { + return Some(rs as *mut c_void); + } + let mut g = ABI_RS_SAMPLERS.write().unwrap(); let map = g.get_or_insert_with(HashMap::new); if let Some(&rs) = map.get(&key) { return Some(rs as *mut c_void); @@ -3968,12 +5031,15 @@ fn huge_pso_bytes() -> usize { } /// Huge driver compiles at once on the workers (default 1, `XCL_HUGE_PSO_CONCURRENCY`). +/// Applies to `>= 512 KiB` heavyweights (`BIG_COMPILES`); `256 KiB..512 KiB` medium-large compiles +/// (such as two-pass world MS PSOs) use `MEDIUM_COMPILES` so a multi-minute RT compute compile +/// cannot serialize them. 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)) } -/// Hard cap on concurrent huge (`>= 256 KB`) driver compiles even when wanted by a title bind +/// Hard cap on concurrent huge (`>= 512 KiB`) 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. @@ -3985,28 +5051,82 @@ fn huge_pso_wanted_concurrency() -> usize { }) } +/// Total physical RAM in bytes (`None` if the OS query fails). +fn total_physical_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 && m.ullTotalPhys > 0).then_some(m.ullTotalPhys) } +} + +/// Default `(background, wanted)` concurrency for `256 KiB..512 KiB` medium-large driver compiles +/// (`MEDIUM_COMPILES`): 3/4 on `>= 32 GiB` hosts (or unknown), 2/3 on smaller-RAM hosts. +fn medium_pso_defaults(total_phys_bytes: Option) -> (usize, usize) { + match total_phys_bytes { + Some(bytes) if bytes < (32u64 << 30) => (2, 3), + _ => (3, 4), + } +} + +/// Medium-large (`256 KiB..512 KiB`) background driver compiles at once (`XCL_MEDIUM_PSO_CONCURRENCY`). +fn medium_pso_concurrency() -> usize { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| { + let (def, _) = medium_pso_defaults(total_physical_ram()); + env_count(std::env::var("XCL_MEDIUM_PSO_CONCURRENCY").ok().as_deref(), def, 1, 64) + }) +} + +/// Medium-large (`256 KiB..512 KiB`) wanted driver compiles at once (`XCL_MEDIUM_PSO_WANTED_CONCURRENCY`). +fn medium_pso_wanted_concurrency() -> usize { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| { + let base = medium_pso_concurrency(); + let (_, def) = medium_pso_defaults(total_physical_ram()); + env_count(std::env::var("XCL_MEDIUM_PSO_WANTED_CONCURRENCY").ok().as_deref(), def.max(base), base, 64) + }) +} + /// A count from the environment: `default` when unset or not a number, clamped to the /// inclusive range `min..=max`. fn env_count(v: Option<&str>, default: usize, min: usize, max: usize) -> usize { v.and_then(|v| v.trim().parse::().ok()).unwrap_or(default).clamp(min, max) } -/// A counting semaphore: background driver compiles of big programs at once (`most` 0: the -/// `huge_pso_concurrency` of the environment; `wanted_most` 0: `huge_pso_wanted_concurrency`). +#[derive(Clone, Copy)] +enum SlotLimit { + Medium, + Big, + Fixed(usize, usize), +} + +/// A counting semaphore: background driver compiles of big programs at once. struct Slots { n: Mutex, + wanted_waiters: AtomicUsize, cv: std::sync::Condvar, - most: usize, - wanted_most: usize, + limit: SlotLimit, } impl Slots { + const fn fixed(most: usize, wanted_most: usize) -> Self { + Self { n: Mutex::new(0), wanted_waiters: AtomicUsize::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Fixed(most, wanted_most) } + } + fn most(&self) -> usize { - if self.most == 0 { huge_pso_concurrency() } else { self.most } + match self.limit { + SlotLimit::Medium => medium_pso_concurrency(), + SlotLimit::Big => huge_pso_concurrency(), + SlotLimit::Fixed(most, _) => most, + } } fn wanted_most(&self) -> usize { - if self.wanted_most == 0 { huge_pso_wanted_concurrency() } else { self.wanted_most } + match self.limit { + SlotLimit::Medium => medium_pso_wanted_concurrency(), + SlotLimit::Big => huge_pso_wanted_concurrency(), + SlotLimit::Fixed(_, wanted_most) => wanted_most, + } } } @@ -4019,17 +5139,82 @@ impl Drop for SlotGuard { } } -static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 0, wanted_most: 0 }; -const GIANT_DRIVER_COMPILE: usize = 4 << 20; -static GIANT_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 1 }; +struct WantedWaiterGuard { + slots: &'static Slots, + registered: bool, +} + +impl WantedWaiterGuard { + fn new(slots: &'static Slots) -> Self { + Self { slots, registered: false } + } + + fn set(&mut self, active: bool) { + if active && !self.registered { + self.slots.wanted_waiters.fetch_add(1, Ordering::AcqRel); + self.registered = true; + } else if !active && self.registered { + self.slots.wanted_waiters.fetch_sub(1, Ordering::AcqRel); + self.registered = false; + } + } +} + +impl Drop for WantedWaiterGuard { + fn drop(&mut self) { + self.set(false); + } +} + +/// Compute DXIL compiles (`128 KiB..256 KiB`, e.g. per-instruction fallback CS) take tens of +/// seconds and >1 GiB each in `amdxc64` when 16 `xcl-pso*` workers compile them simultaneously; +/// gate them into `MEDIUM_COMPILES` while keeping `huge_pso_bytes()` (default `256 KiB`) for +/// graphics pipelines and title-thread deferral. +const MEDIUM_COMPUTE_DRIVER_COMPILE: usize = 128 << 10; +const LARGE_DRIVER_COMPILE: usize = 512 << 10; +static MEDIUM_COMPILES: Slots = Slots { n: Mutex::new(0), wanted_waiters: AtomicUsize::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Medium }; +static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), wanted_waiters: AtomicUsize::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Big }; +/// True giant DXIL shaders (`>= 900 KiB`, e.g. >1 MiB RT/compute shaders that can take >60-140s +/// in the driver compiler) get their own dedicated 1-slot lane so they never starve `MEDIUM_COMPILES` +/// (`128-512 KiB`) or `BIG_COMPILES` (`512-900 KiB`). +const GIANT_DRIVER_COMPILE: usize = 900 << 10; +static GIANT_COMPILES: Slots = Slots::fixed(1, 1); + +fn driver_compile_gate_bytes(kind: &str, huge_bytes: usize) -> usize { + if kind == "compute" || kind == "compute retry" { + huge_bytes.min(MEDIUM_COMPUTE_DRIVER_COMPILE) + } else { + huge_bytes + } +} + +fn is_preload_worker() -> bool { + std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso-pre-")) +} fn compile_slots(bytes: usize) -> &'static Slots { - if bytes >= GIANT_DRIVER_COMPILE { &GIANT_COMPILES } else { &BIG_COMPILES } + if bytes >= GIANT_DRIVER_COMPILE { + &GIANT_COMPILES + } else if bytes >= LARGE_DRIVER_COMPILE { + &BIG_COMPILES + } else { + &MEDIUM_COMPILES + } +} + +/// Wake workers waiting in `big_compile_turn` when a queued pipeline becomes wanted by a title thread. +pub(super) fn notify_big_compile_wanted() { + for slots in [&MEDIUM_COMPILES, &BIG_COMPILES, &GIANT_COMPILES] { + let _g = slots.n.lock().unwrap(); + drop(_g); + slots.cv.notify_all(); + } } /// A driver compile of `bytes` of DXIL through `build`: a huge one on an `xcl-pso*` worker /// waits for its slot first (`big_compile_turn`; not a title thread's, nor one the title waits /// for). Logs its time, size and whether it was gated. +#[cfg(test)] fn driver_compile(kind: &str, bytes: usize, gate: bool, build: impl FnOnce() -> R) -> R { driver_compile_identified(kind, bytes, gate, None, build).0 } @@ -4044,24 +5229,35 @@ 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 huge_bytes = huge_pso_bytes(); + let gate_bytes = driver_compile_gate_bytes(kind, huge_bytes); + let gated = gate && bytes >= gate_bytes && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); let waited = std::time::Instant::now(); - let _slot = huge.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)); + let _slot = gated.then(|| big_compile_turn_with(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted, is_preload_worker())); let waited = waited.elapsed(); static SEQUENCE: AtomicU64 = AtomicU64::new(0); let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1; - let log = pso_trace() || bytes >= huge_pso_bytes(); - if log { - let record = record.map_or_else(String::new, |(hash, cached)| { + const SLOW_COMPILE_LOG_MS: u128 = 500; + let log = pso_trace() || bytes >= huge_bytes; + let record_note = |record: Option<(u64, bool)>| { + record.map_or_else(String::new, |(hash, cached)| { format!(", record {hash:016x}, driver blob {}", if cached { "supplied" } else { "absent" }) - }); - crate::xlog_info!("D3D12.X: driver compile start #{sequence}: {kind} PSO, {bytes} B DXIL{record}"); + }) + }; + if log { + crate::xlog_info!("D3D12.X: driver compile start #{sequence}: {kind} PSO, {bytes} B DXIL{}", record_note(record)); } - let started = std::time::Instant::now(); + let prof = super::prof::span(super::prof::Kind::DriverCompile); let r = build(); - let took = started.elapsed(); - if log { - crate::xlog_info!("D3D12.X: driver compile finish #{sequence}: {kind} PSO, {bytes} B DXIL, {} ms{}", took.as_millis(), gate_note(bytes >= huge_pso_bytes(), huge, waited)); + let took = prof.elapsed(); + drop(prof); + if log || took.as_millis() >= SLOW_COMPILE_LOG_MS { + crate::xlog_info!( + "D3D12.X: driver compile finish #{sequence}: {kind} PSO, {bytes} B DXIL{}, {} ms{}", + record_note(record), + took.as_millis(), + gate_note(bytes >= huge_bytes || gated, gated, waited) + ); } (r, took) } @@ -4075,10 +5271,20 @@ fn gate_note(huge_size: bool, gated: bool, waited: std::time::Duration) -> Strin } } -/// A cached-blob attempt should be quick and must not take a cold-compile slot. Its retry -/// without the rejected blob is a cold compile and does take one. -fn gate_compute_driver_compile(has_cached_blob: bool) -> bool { - !has_cached_blob +/// Minimum `GetCachedBlob` size (4 KiB) to treat a cached PSO blob as containing compiled +/// driver ISA rather than a tiny metadata stub header (some drivers emit <= 1 KiB stub blobs +/// that still trigger a full cold compile on reload). +const MIN_ISA_CACHED_BLOB_BYTES: usize = 4096; + +fn cached_blob_has_isa(blob: Option<&[u8]>) -> bool { + blob.is_some_and(|b| b.len() >= MIN_ISA_CACHED_BLOB_BYTES) +} + +/// A cached-blob attempt with compiled driver ISA should be quick and must not take a +/// cold-compile slot. Tiny stub blobs (`< MIN_ISA_CACHED_BLOB_BYTES`) and retries without +/// a rejected blob are cold compiles and do take one. +fn gate_compute_driver_compile(has_isa_cached_blob: bool) -> bool { + !has_isa_cached_blob } /// Before a big driver compile in the background: its turn – unwanted builds wait for both @@ -4088,13 +5294,34 @@ fn gate_compute_driver_compile(has_cached_blob: bool) -> bool { /// `slots.wanted_most()` (default 2 for `>= 256 KB`, 1 for `>= 4 MiB` giant shaders) so a wanted /// build is not stuck behind 1 background build while a burst of lazy binds still cannot spike /// driver compiler commit into OOM. +#[cfg(test)] fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wanted: impl Fn() -> bool) -> SlotGuard { + big_compile_turn_with(slots, commit_free, wanted, false) +} + +fn big_compile_turn_with(slots: &'static Slots, commit_free: impl Fn() -> bool, wanted: impl Fn() -> bool, is_preload: bool) -> SlotGuard { const LOOK: std::time::Duration = std::time::Duration::from_millis(50); + let mut waiter = WantedWaiterGuard::new(slots); let mut n = slots.n.lock().unwrap(); loop { let is_wanted = wanted(); + waiter.set(is_wanted); let cap = if is_wanted { slots.wanted_most() } else { slots.most() }; - if *n < cap && (is_wanted || commit_free()) { + let ok = if is_wanted { + // Always allow the first 2 wanted slots (never deadlock under tight commit); extra + // wanted slots on wider tiers (e.g. MEDIUM_COMPILES cap 4) require commit headroom. + *n < cap && (*n < 2 || commit_free()) + } else if is_preload { + // Speculative `xcl-pso-pre-*` preload threads (`THREAD_PRIORITY_LOWEST`) may hold at + // most 1 slot in a lane (`*n == 0`) and yield whenever any foreground `wanted` compile + // is waiting or commit headroom is tight — leaving >= 1 tight-commit slot (and all + // extra wanted slots) exclusively for foreground compiles like two-pass MS PSOs. + *n == 0 && slots.wanted_waiters.load(Ordering::Acquire) == 0 && commit_free() + } else { + *n < cap && slots.wanted_waiters.load(Ordering::Acquire) == 0 && commit_free() + }; + if ok { + waiter.set(false); *n += 1; return SlotGuard(slots); } @@ -4111,12 +5338,15 @@ fn big_compile_headroom(dxil_len: usize) -> u64 { (3u64 << 30).max(dxil_len as u64 * 512) } -/// That much commit is free (true when that is not known). +/// That much commit is free (true when that is not known). Free physical memory is not the +/// measure, as for the pipeline workers (`pso_async::avail_commit_bytes`): under Wine it is the +/// whole machine's, and at 1–2 GB it held every worker here while the title waited for one. fn big_compile_commit_free(need: u64) -> bool { - 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 || m.ullAvailPageFile >= need } + big_compile_room(super::pso_async::avail_commit_bytes(), need) +} + +fn big_compile_room(avail_commit: Option, need: u64) -> bool { + avail_commit.map_or(true, |avail| avail >= need) } #[cfg(test)] @@ -4125,9 +5355,19 @@ mod big_compile_tests { use std::sync::atomic::AtomicBool; use std::time::{Duration, Instant}; + #[test] + fn big_compile_room_is_free_commit_not_free_ram() { + let need = big_compile_headroom(0); + assert!(big_compile_room(Some(need), need)); + assert!(!big_compile_room(Some(need - 1), need)); + // a world load: 1.3 GB of RAM free, 12 GB of commit – the compile may start + assert!(big_compile_room(Some(12 << 30), need)); + assert!(big_compile_room(None, need)); + } + #[test] fn wanted_builds_bypass_commit_and_unwanted_slot_but_respect_hard_cap() { - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 2 }; + static S: Slots = Slots::fixed(1, 2); let held = big_compile_turn(&S, || true, || false); assert_eq!(*S.n.lock().unwrap(), 1); // Unwanted slot is full, but a wanted build immediately takes the 2nd (wanted) slot and @@ -4165,7 +5405,7 @@ mod big_compile_tests { // Mirrors GIANT_COMPILES (`most == 1, wanted_most == 1`) under low commit (< 3 GiB): // an unwanted compile waiting on commit headroom must never hold the slot and deadlock a // wanted compile. - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 1 }; + static S: Slots = Slots::fixed(1, 1); static FREE: AtomicBool = AtomicBool::new(false); let bg = std::thread::spawn(|| { let _g = big_compile_turn(&S, || FREE.load(Ordering::Acquire), || false); @@ -4186,7 +5426,7 @@ mod big_compile_tests { #[test] fn wanted_burst_is_hard_capped_to_wanted_most() { use std::sync::atomic::AtomicUsize; - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 2 }; + static S: Slots = Slots::fixed(1, 2); static IN: AtomicUsize = AtomicUsize::new(0); static PEAK: AtomicUsize = AtomicUsize::new(0); let t: Vec<_> = (0..12) @@ -4225,20 +5465,99 @@ mod big_compile_tests { #[test] fn giant_driver_compiles_have_their_own_lane() { + assert!(std::ptr::eq(compile_slots(LARGE_DRIVER_COMPILE - 1), &MEDIUM_COMPILES)); + assert!(std::ptr::eq(compile_slots(LARGE_DRIVER_COMPILE), &BIG_COMPILES)); + assert!(std::ptr::eq(compile_slots(729_672), &BIG_COMPILES)); assert!(std::ptr::eq(compile_slots(GIANT_DRIVER_COMPILE - 1), &BIG_COMPILES)); assert!(std::ptr::eq(compile_slots(GIANT_DRIVER_COMPILE), &GIANT_COMPILES)); + assert!(std::ptr::eq(compile_slots(1_061_720), &GIANT_COMPILES)); + assert!(is_rt_gated_cs_hash(0x95cc_1328_8a27_a96e)); + assert!(!is_rt_gated_cs_hash(0xef5e_ce92_2dc3_3bfe)); + let parsed = parse_rt_skip_hashes("0x39f0e9aeb156a61c, 73fb752d7f62c3a5; bad"); + assert!(parsed.contains(&0x39f0_e9ae_b156_a61c)); + assert!(parsed.contains(&0x73fb_752d_7f62_c3a5)); + assert_eq!(parsed.len(), 2); + assert!(is_rt_gated_cs(b"HDR\0CS_RaytracingResolve_01\0")); + assert!(is_rt_gated_cs(b"HDR\0CS_IrradianceCache_Shade_Low\0")); + assert_eq!(parse_rt_gate_mode(None), RtGateMode::Hold); + assert_eq!(parse_rt_gate_mode(Some("")), RtGateMode::Hold); + assert_eq!(parse_rt_gate_mode(Some("1")), RtGateMode::Hold); + assert_eq!(parse_rt_gate_mode(Some("hold")), RtGateMode::Hold); + assert_eq!(parse_rt_gate_mode(Some("AUTO")), RtGateMode::Auto); + assert_eq!(parse_rt_gate_mode(Some("0")), RtGateMode::Off); + assert_eq!(parse_rt_gate_mode(Some("off")), RtGateMode::Off); + assert_eq!(parse_rt_gate_mode(Some("allow")), RtGateMode::Off); + } + + #[test] + fn preload_never_takes_second_slot_or_starves_wanted_compile() { + static S: Slots = Slots::fixed(3, 4); + let p1 = big_compile_turn_with(&S, || true, || false, true); + assert_eq!(*S.n.lock().unwrap(), 1); + // A second speculative preload compile must wait even though `most == 3`, so preload + // never occupies both tight-commit slots (`*n < 2`) and starves foreground builds. + let p2 = std::thread::spawn(|| { + let _g = big_compile_turn_with(&S, || true, || false, true); + }); + std::thread::sleep(Duration::from_millis(120)); + assert!(!p2.is_finished(), "second preload compile must wait behind the first"); + // A foreground wanted compile enters immediately even when commit headroom is tight! + let t0 = Instant::now(); + let w1 = big_compile_turn_with(&S, || false, || true, false); + assert!(t0.elapsed() < Duration::from_secs(1), "wanted compile must not wait behind preload"); + assert_eq!(*S.n.lock().unwrap(), 2); + drop((w1, p1)); + p2.join().unwrap(); + assert_eq!(*S.n.lock().unwrap(), 0); + } + + #[test] + fn medium_tier_defaults_scale_with_ram_and_throttle_above_two_when_commit_tight() { + assert_eq!(medium_pso_defaults(Some(16u64 << 30)), (2, 3)); + assert_eq!(medium_pso_defaults(Some(32u64 << 30)), (3, 4)); + assert_eq!(medium_pso_defaults(Some(64u64 << 30)), (3, 4)); + assert_eq!(medium_pso_defaults(None), (3, 4)); + + // With commit free: 4 wanted medium compiles run concurrently. + static S: Slots = Slots::fixed(3, 4); + let g1 = big_compile_turn(&S, || true, || true); + let g2 = big_compile_turn(&S, || true, || true); + let g3 = big_compile_turn(&S, || true, || true); + let g4 = big_compile_turn(&S, || true, || true); + assert_eq!(*S.n.lock().unwrap(), 4); + drop((g1, g2, g3, g4)); + + // Without commit free: wanted burst still gets 2 slots (no deadlock) but pauses slots 3..4. + let w1 = big_compile_turn(&S, || false, || true); + let w2 = big_compile_turn(&S, || false, || true); + assert_eq!(*S.n.lock().unwrap(), 2); + let t = std::thread::spawn(|| { + let _g = big_compile_turn(&S, || false, || true); + }); + std::thread::sleep(Duration::from_millis(120)); + assert!(!t.is_finished(), "3rd wanted slot must wait when commit headroom is exhausted"); + drop((w1, w2)); + t.join().unwrap(); + assert_eq!(*S.n.lock().unwrap(), 0); } #[test] fn only_a_cold_compute_compile_takes_a_slot() { assert!(!gate_compute_driver_compile(true), "the cached-blob attempt bypasses the gate"); assert!(gate_compute_driver_compile(false), "a cold attempt, including a retry, is gated"); + assert!(!cached_blob_has_isa(None), "missing blob has no compiled ISA"); + assert!(!cached_blob_has_isa(Some(&[])), "empty blob has no compiled ISA"); + assert!(!cached_blob_has_isa(Some(&[0u8; 930])), "tiny driver stub header must stay gated as cold compile"); + assert!(!cached_blob_has_isa(Some(&[0u8; MIN_ISA_CACHED_BLOB_BYTES - 1])), "sub-4 KiB blob must stay gated"); + assert!(cached_blob_has_isa(Some(&[0u8; MIN_ISA_CACHED_BLOB_BYTES])), ">= 4 KiB blob counts as compiled ISA"); + assert!(gate_compute_driver_compile(cached_blob_has_isa(Some(&[0u8; 930])))); + assert!(!gate_compute_driver_compile(cached_blob_has_isa(Some(&[0u8; MIN_ISA_CACHED_BLOB_BYTES])))); } #[test] fn the_concurrency_limit_holds_and_all_finish() { use std::sync::atomic::AtomicUsize; - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 2, wanted_most: 2 }; + static S: Slots = Slots::fixed(2, 2); static IN: AtomicUsize = AtomicUsize::new(0); static PEAK: AtomicUsize = AtomicUsize::new(0); // the two holders of the slots meet here: both are inside at once, deterministically @@ -4262,12 +5581,16 @@ mod big_compile_tests { assert_eq!(*S.n.lock().unwrap(), 0); } + static GLOBAL_SLOTS_TEST_LOCK: Mutex<()> = Mutex::new(()); + #[test] fn small_and_title_thread_compiles_bypass_the_gate() { + let _lock = GLOBAL_SLOTS_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); // every slot taken: a small compile on a worker, and a huge one on an unnamed (title) // thread, both go on at once - // (both lanes: a huge compile of any size would block on a gate it should bypass) - let mut held: Vec<_> = (0..huge_pso_concurrency()).map(|_| big_compile_turn(&BIG_COMPILES, || true, || false)).collect(); + // (all three lanes: a huge compile of any size would block on a gate it should bypass) + let mut held: Vec<_> = (0..medium_pso_concurrency()).map(|_| big_compile_turn(&MEDIUM_COMPILES, || true, || false)).collect(); + held.extend((0..huge_pso_concurrency()).map(|_| big_compile_turn(&BIG_COMPILES, || true, || false))); held.push(big_compile_turn(&GIANT_COMPILES, || true, || false)); let small = std::thread::Builder::new() .name("xcl-pso-test".into()) @@ -4282,6 +5605,51 @@ mod big_compile_tests { drop(held); } + #[test] + fn medium_compute_gate_threshold_applies_only_to_compute() { + assert_eq!(driver_compile_gate_bytes("compute", 256 << 10), MEDIUM_COMPUTE_DRIVER_COMPILE); + assert_eq!(driver_compile_gate_bytes("compute retry", 256 << 10), MEDIUM_COMPUTE_DRIVER_COMPILE); + assert_eq!(driver_compile_gate_bytes("compute", 64 << 10), 64 << 10); + assert_eq!(driver_compile_gate_bytes("graphics", 256 << 10), 256 << 10); + assert_eq!(driver_compile_gate_bytes("test", 256 << 10), 256 << 10); + assert!(std::ptr::eq(compile_slots(128 << 10), &MEDIUM_COMPILES)); + assert!(std::ptr::eq(compile_slots(179 << 10), &MEDIUM_COMPILES)); + assert!(std::ptr::eq(compile_slots(217 << 10), &MEDIUM_COMPILES)); + } + + #[test] + fn medium_compute_worker_compiles_are_gated_in_medium_lane() { + let _lock = GLOBAL_SLOTS_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let held: Vec<_> = (0..medium_pso_concurrency()) + .map(|_| big_compile_turn(&MEDIUM_COMPILES, || true, || false)) + .collect(); + + // < 128 KiB compute, cached (`gate = false`) 180 KiB compute, and title-thread 180 KiB + // compute all bypass `MEDIUM_COMPILES` immediately. + let small_cs = std::thread::Builder::new() + .name("xcl-pso-test".into()) + .spawn(|| driver_compile("compute", MEDIUM_COMPUTE_DRIVER_COMPILE - 1, true, || 11)) + .unwrap(); + let cached_cs = std::thread::Builder::new() + .name("xcl-pso-test".into()) + .spawn(|| driver_compile("compute", 180 << 10, false, || 12)) + .unwrap(); + let title_cs = std::thread::spawn(|| driver_compile("compute", 180 << 10, true, || 13)); + assert_eq!(small_cs.join().unwrap(), 11); + assert_eq!(cached_cs.join().unwrap(), 12); + assert_eq!(title_cs.join().unwrap(), 13); + + // A cold 180 KiB compute compile on an `xcl-pso*` worker waits until a `MEDIUM_COMPILES` slot frees. + let gated_cs = std::thread::Builder::new() + .name("xcl-pso-test".into()) + .spawn(|| driver_compile("compute", 180 << 10, true, || 14)) + .unwrap(); + std::thread::sleep(Duration::from_millis(120)); + assert!(!gated_cs.is_finished(), "cold 180 KiB compute worker compile must wait on MEDIUM_COMPILES"); + drop(held); + assert_eq!(gated_cs.join().unwrap(), 14); + } + #[test] fn headroom_is_the_3_gb_floor_until_512_times_the_dxil_exceeds_it() { // the class from huge_pso_bytes() up to 6 MiB of DXIL: the floor, unchanged @@ -4295,7 +5663,7 @@ mod big_compile_tests { #[test] fn unwanted_builds_go_one_at_a_time_when_the_commit_is_there() { - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 2 }; + static S: Slots = Slots::fixed(1, 2); let first = big_compile_turn(&S, || true, || false); let t = std::thread::spawn(|| { let _g = big_compile_turn(&S, || true, || false); @@ -4322,6 +5690,11 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const if !is_console(cs) { return None; } + // Under `XCL_RT_GATE=hold` (default), RT traversal and RT companion shaders are held back + // without translating or compiling on the driver (belt-and-suspenders guard for direct paths). + if rt_gate_mode() == RtGateMode::Hold && is_rt_gated_cs(cs) { + return Some(Err(())); + } // made when first bound (`pso_async::lazy`): not even translated now if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { return Some(Err(())); @@ -4343,13 +5716,16 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } let record = crate::gpu::shader::fnv64(cs); if let Some(plan) = compiled.dispatch_chain { - 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, dxil.clone(), &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))]); + super::dred::label_text(*ppv as usize, || format!("cs {record:016x} piece 0")); if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + PSO_USER_SGPRS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); } + note_compute_threads(*ppv as usize, cs); + note_bvh_traversal(*ppv as usize, cs); + super::ambient::note_compute_pso(*ppv as usize, cs); note_translated_compute(0, ppv); TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); return Some(Ok(0)); @@ -4357,6 +5733,24 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } let Some(rs) = abi_rs_for(this, &compiled.samplers) else { return Some(Err(())) }; LAST_COMPUTE_RS.with(|c| c.set(rs as usize)); + let lib_key = pso_lib::compute_key(&dxil, &compiled.samplers, d.Flags.0); + let mut lib_copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(d); + lib_copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); + lib_copy.CS = bytecode(&dxil); + lib_copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + if pso_lib::try_load_compute(this, &lib_key, &lib_copy, riid, ppv) { + TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + note_pso_rs(*ppv, rs); + super::dred::label(*ppv as usize, &[("cs", Some(cs))]); + if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { + PSO_USER_SGPRS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + } + note_compute_threads(*ppv as usize, cs); + note_bvh_traversal(*ppv as usize, cs); + super::ambient::note_compute_pso(*ppv as usize, cs); + note_translated_compute(S_OK, ppv); + return Some(Ok(S_OK)); + } let (hr, in_driver, reused) = compute_container(this, f, d, rs, &dxil, record, riid, ppv, false); if hr < 0 { // A huge program's verdict in the log itself: `note_translation_error` goes to the @@ -4377,11 +5771,15 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const return Some(Err(())); } TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + pso_lib::store_pipeline(this, &lib_key, *ppv); note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + PSO_USER_SGPRS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); } + note_compute_threads(*ppv as usize, cs); + note_bvh_traversal(*ppv as usize, cs); + super::ambient::note_compute_pso(*ppv as usize, cs); note_translated_compute(hr, ppv); crate::xlog_info!( "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", @@ -4397,6 +5795,44 @@ pub(crate) use dispatch_chain::log_counts as log_dispatch_chain_counts; /// `chained`: built with the dispatch chain's root signature (`dispatch_chain`), whose driver blobs /// are kept apart on disk from the same DXIL's under the title's. +/// `XCL_PSO_MAX_KB`: a compute program of more KiB of DXIL that no earlier run left a driver blob +/// for is refused at once, as a driver that runs out of memory on it would after minutes (its +/// dispatches are skipped). 0 or unset: off. +fn build_cap_bytes() -> usize { + static V: OnceLock = OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_PSO_MAX_KB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0usize).saturating_mul(1024)) +} + +/// `XCL_PSO_MAX_CACHED=1`: `XCL_PSO_MAX_KB` also holds for a program with a saved driver blob (one +/// of ~1 MB of DXIL takes ~50 MB of commit once made, however quickly). +fn cap_holds_for_cached() -> bool { + static V: OnceLock = OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_PSO_MAX_CACHED").is_ok_and(|v| v.trim() == "1")) +} + +/// local: records (16 hex digits a line) in the file `XCL_PSO_SKIP_FILE` names +fn skip_listed(record: u64) -> bool { + static L: OnceLock> = OnceLock::new(); + L.get_or_init(|| { + let Some(p) = std::env::var_os("XCL_PSO_SKIP_FILE") else { return Default::default() }; + std::fs::read_to_string(p).unwrap_or_default().lines().filter_map(|l| u64::from_str_radix(l.trim(), 16).ok()).collect() + }) + .contains(&record) +} + +fn over_build_cap(dxil: usize, cap: usize) -> bool { + cap != 0 && dxil > cap +} + +#[cfg(test)] +mod build_cap_tests { + #[test] + fn only_a_program_over_a_set_cap_is_refused() { + assert!(!super::over_build_cap(usize::MAX, 0), "off"); + assert!(!super::over_build_cap(2048, 2048) && super::over_build_cap(2049, 2048)); + } +} + 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, chained: bool) -> (HRESULT, std::time::Duration, bool) { let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(d); @@ -4411,24 +5847,53 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL let disk = driver_cache::path_for(dxil, copy.Flags.0, chained); let from_disk = cached.is_none(); if from_disk { - cached = disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + cached = disk + .as_deref() + .and_then(driver_cache::load) + .filter(|b| cached_blob_has_isa(Some(b))) + .map(std::sync::Arc::new); } - if let Some(b) = &cached { - copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; + let has_isa_blob = cached_blob_has_isa(cached.as_deref().map(Vec::as_slice)); + if has_isa_blob { + if let Some(b) = &cached { + copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; + } + } + if skip_listed(record) { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 3 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: compute PSO of record {record:016x} not built: in the skip list ({} so far)", n + 1); + } + return (E_OUTOFMEMORY, std::time::Duration::ZERO, false); + } + if (!has_isa_blob || cap_holds_for_cached()) && over_build_cap(dxil.len(), build_cap_bytes()) { + crate::xlog_warn!("D3D12.X: compute PSO of record {record:016x} ({} B DXIL) not built: over XCL_PSO_MAX_KB{}", dxil.len(), if !has_isa_blob { " and without a saved blob" } else { " (it has a saved blob)" }); + return (E_OUTOFMEMORY, std::time::Duration::ZERO, false); } + // one the driver crashed on in an earlier run, here or in a preparation worker, is not + // given to it again (`driver_crash`): its dispatches are left out like a refused program's + let crash_key = super::driver_crash::compute_key(record); + if super::driver_crash::blocked(&crash_key) { + note_translation_error(format!("the driver crashed building the compute pipeline of record {record:016x} in an earlier run (driver-crashes.txt beside the DXIL cache) – not built")); + return (E_OUTOFMEMORY, std::time::Duration::ZERO, false); + } + let _building = super::driver_crash::building(&crash_key, &[("cs.dxil".to_string(), dxil)]); // in the background, a few at a time and within the commit headroom the program asks for let (mut hr, mut in_driver) = driver_compile_identified( "compute", dxil.len(), - gate_compute_driver_compile(cached.is_some()), - Some((record, cached.is_some())), + gate_compute_driver_compile(has_isa_blob), + Some((record, has_isa_blob)), || finish_pso(this, f, © as *const _ as *const c_void, riid, ppv), ); - if hr < 0 && cached.is_some() { + if hr < 0 && has_isa_blob { // a blob the driver does not take (another root signature at the same address…): compiled - forget_compute_blob(key); - if from_disk { - driver_cache::note(false, disk.as_deref()); + if driver_cache::refused(hr) { + forget_compute_blob(key); + if from_disk { + driver_cache::note(false, disk.as_deref()); + } } copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let (retried, took) = driver_compile_identified( @@ -4443,8 +5908,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL } let reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; if hr >= 0 && !reused { - keep_compute_blob(key, *ppv, dxil.len()); - if let (Some(p), Some(b)) = (disk.as_deref(), compute_blob(key)) { + if let (Some(p), Some(b)) = (disk.as_deref(), keep_compute_blob(key, *ppv, dxil.len())) { driver_cache::keep(p, &b, in_driver); } } else if reused && from_disk { @@ -4465,7 +5929,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL /// and the program compiled as before). `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); @@ -4473,6 +5937,10 @@ pub(crate) mod driver_cache { static STALE: AtomicU64 = AtomicU64::new(0); static STORED: AtomicU64 = AtomicU64::new(0); + pub fn stats() -> (u64, u64, u64) { + (HITS.load(Ordering::Relaxed), STALE.load(Ordering::Relaxed), STORED.load(Ordering::Relaxed)) + } + /// The file of the pipeline made from `dxil` with `flags`. pub fn name(dxil: &[u8], flags: i32) -> String { name_for(dxil, flags, false) @@ -4490,9 +5958,37 @@ pub(crate) mod driver_cache { format!("gfx-{hash:016x}-{bytes:x}.pso") } + /// On AMD (`0x1002`), `ID3D12PipelineState::GetCachedBlob` hands out ~954-byte references into + /// the driver's own shader cache rather than self-contained ISA (#2512). A stale reference left + /// by a crashed or killed run can remove the device when passed back in `CachedPSO`. Skip + /// on-disk `.pso` blobs on AMD unless explicitly opted in with `XCL_PSO_DISK_CACHE=1`. + static STUBS: AtomicBool = AtomicBool::new(false); + + /// Record the chosen adapter's PCI vendor ID (`DXGI_ADAPTER_DESC1::VendorId`). + pub fn note_vendor(vendor: u32) { + let stubs = stub_vendor(vendor); + let was = STUBS.swap(stubs, Ordering::Relaxed); + if stubs && !was && !enabled() { + crate::xlog_info!("D3D12.X: an AMD driver's pipeline blobs only name entries of its own cache – none kept on disk (XCL_PSO_DISK_CACHE=1 keeps them)"); + } + } + + fn stub_vendor(vendor: u32) -> bool { + vendor == 0x1002 + } + + /// `XCL_PSO_DISK_CACHE`: "0" off, "1" on, unset: on unless the driver's blobs are references. + fn env_setting() -> Option { + static ON: std::sync::OnceLock> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PSO_DISK_CACHE").ok().map(|v| v.trim() != "0")) + } + + fn enabled_with(setting: Option, stubs: bool) -> bool { + setting.unwrap_or(!stubs) + } + 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(), STUBS.load(Ordering::Relaxed)) } pub fn path(dxil: &[u8], flags: i32) -> Option { @@ -4511,6 +6007,16 @@ pub(crate) mod driver_cache { std::fs::read(p).ok().filter(|b| !b.is_empty()) } + /// Whether a create that failed with `hr` refused the blob it was given. A removed or hung + /// device and a driver out of memory fail every create, with a blob or without one, and + /// say nothing about the blob: it is kept. (A retail title's run that ended in a device + /// removal dropped the blobs of 15 large compute programs in its last two seconds; the next + /// run built them again, 10 – 18 s each.) + pub fn refused(hr: crate::util::HRESULT) -> bool { + use windows::Win32::Graphics::Dxgi::{DXGI_ERROR_DEVICE_HUNG, DXGI_ERROR_DEVICE_REMOVED, DXGI_ERROR_DEVICE_RESET}; + hr < 0 && ![DXGI_ERROR_DEVICE_REMOVED.0, DXGI_ERROR_DEVICE_HUNG.0, DXGI_ERROR_DEVICE_RESET.0, crate::util::E_OUTOFMEMORY].contains(&hr) + } + /// A pipeline was made from a kept blob (`ok`), or the driver refused the blob: dropped. pub fn note(ok: bool, p: Option<&Path>) { if ok { @@ -4583,6 +6089,16 @@ pub(crate) mod driver_cache { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } + #[test] + fn blobs_are_kept_on_disk_unless_they_are_references() { + assert!(stub_vendor(0x1002), "AMD"); + assert!(!stub_vendor(0x10DE) && !stub_vendor(0x8086) && !stub_vendor(0x1414), "NVIDIA, Intel, WARP"); + assert!(enabled_with(None, false)); + assert!(!enabled_with(None, true)); + assert!(enabled_with(Some(true), true), "XCL_PSO_DISK_CACHE=1 keeps them"); + assert!(!enabled_with(Some(false), false), "XCL_PSO_DISK_CACHE=0 turns them off"); + } + #[test] fn a_file_is_named_after_its_dxil_and_flags() { assert_eq!(name(b"abc", 0), name(b"abc", 0)); @@ -4615,6 +6131,19 @@ pub(crate) mod driver_cache { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn a_lost_device_or_no_memory_does_not_refuse_a_blob() { + use crate::util::{E_INVALIDARG, E_OUTOFMEMORY}; + use windows::Win32::Graphics::Dxgi::{DXGI_ERROR_DEVICE_HUNG, DXGI_ERROR_DEVICE_REMOVED, DXGI_ERROR_DEVICE_RESET}; + // the driver's answers to a blob of another driver, adapter or root signature + for hr in [E_INVALIDARG, 0x887E_0001u32 as i32, 0x887E_0002u32 as i32, 0x8000_4005u32 as i32] { + assert!(refused(hr), "{hr:#x}"); + } + for hr in [DXGI_ERROR_DEVICE_REMOVED.0, DXGI_ERROR_DEVICE_HUNG.0, DXGI_ERROR_DEVICE_RESET.0, E_OUTOFMEMORY, 0, 1] { + assert!(!refused(hr), "{hr:#x}"); + } + } + #[test] fn an_overlapping_writer_cannot_modify_the_published_blob() { use std::io::Write; @@ -4705,6 +6234,56 @@ mod compute_blob_tests { assert!(super::compute_blob(key).is_none()); assert_eq!(super::COMPUTE_BLOBS.lock().unwrap().as_ref().unwrap().1, before - 3); } + + #[test] + fn duplicate_blob_publishes_charge_budget_once_and_free_cleanly() { + let cache: super::Mutex>>, usize)>> = + super::Mutex::new(None); + // Four racing publishers of the same 16-byte key must charge 16 bytes, not 64. + assert!(super::insert_cached_blob(&cache, 64, 1, vec![0xAA; 16])); + for _ in 0..3 { + assert!(!super::insert_cached_blob(&cache, 64, 1, vec![0xBB; 16])); + } + assert_eq!(cache.lock().unwrap().as_ref().unwrap().1, 16); + // Three more distinct 16-byte keys must still fit inside the 64-byte budget. + for k in 2..=4 { + assert!(super::insert_cached_blob(&cache, 64, k, vec![k as u8; 16])); + } + assert_eq!(cache.lock().unwrap().as_ref().unwrap().1, 64); + assert!(!super::insert_cached_blob(&cache, 64, 5, vec![5; 16])); + // Removing all four keys returns accounted bytes to zero. + let mut g = cache.lock().unwrap(); + let (m, total) = g.as_mut().unwrap(); + for k in 1..=4 { + let b = m.remove(&k).unwrap(); + *total -= b.len(); + } + assert_eq!(*total, 0); + } + + /// A blob the in-memory store has no room for still goes back to its caller (which writes + /// it to the disk cache); one that fits is kept in memory as well. + #[test] + fn a_blob_over_the_memory_budget_still_reaches_its_caller() { + let mut store = (super::HashMap::new(), 0usize); + let fits = super::remember_compute_blob(&mut store, (1, 2, 0), vec![7u8; 64]).expect("a blob that fits"); + assert_eq!(fits.len(), 64); + assert_eq!(store.1, 64); + assert!(store.0.contains_key(&(1, 2, 0))); + let duplicate = super::remember_compute_blob(&mut store, (1, 2, 0), vec![3; 64]).unwrap(); + assert!(std::sync::Arc::ptr_eq(&fits, &duplicate)); + assert_eq!(store.1, 64, "a concurrent insertion of the same blob is charged once"); + + // the store is full: nothing more is kept in memory … + store.1 = super::COMPUTE_BLOBS_MAX; + let over = super::remember_compute_blob(&mut store, (3, 4, 0), vec![9u8; 128]); + assert!(!store.0.contains_key(&(3, 4, 0))); + assert_eq!(store.1, super::COMPUTE_BLOBS_MAX, "a blob that is not kept is not charged"); + // … but the caller gets it for the disk + assert_eq!(over.expect("the blob for the disk cache").as_slice(), &[9u8; 128][..]); + + assert!(super::remember_compute_blob(&mut store, (5, 6, 0), Vec::new()).is_none(), "an empty blob is nothing to keep"); + } } /// Read `GetCachedBlob` from either an adopted or raw PC `ID3D12PipelineState`. @@ -4723,27 +6302,67 @@ unsafe fn read_pso_cached_blob(pso: *mut c_void) -> Option> { } else { let p = ID3D12PipelineState::from_raw_borrowed(&pso)?; let blob = p.GetCachedBlob().ok()?; - return Some(std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec()); + let bytes = std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec(); + return cached_blob_has_isa(Some(&bytes)).then_some(bytes); }; let blob = ID3DBlob::from_raw(raw); let bytes = std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec(); - (!bytes.is_empty()).then_some(bytes) + cached_blob_has_isa(Some(&bytes)).then_some(bytes) } -/// The driver's blob of the PSO just built (works on both adopted title PSOs and raw PC compute -/// passes owned by `TwoPassPso`). -unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: usize) { - if dxil_len < COMPUTE_BLOB_MIN_DXIL || pso.is_null() || compute_blob(key).is_some() { - return; +fn insert_cached_blob( + cache: &Mutex>>, usize)>>, + limit: usize, + key: K, + bytes: Vec, +) -> bool { + if bytes.is_empty() { + return false; } - let Some(bytes) = read_pso_cached_blob(pso) else { return }; - let mut g = COMPUTE_BLOBS.lock().unwrap(); + let mut g = cache.lock().unwrap(); let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); - if bytes.is_empty() || *total + bytes.len() > COMPUTE_BLOBS_MAX { - return; + let std::collections::hash_map::Entry::Vacant(slot) = m.entry(key) else { + return false; + }; + if *total + bytes.len() > limit { + return false; } *total += bytes.len(); - m.insert(key, std::sync::Arc::new(bytes)); + slot.insert(std::sync::Arc::new(bytes)); + true +} + +/// The driver's blob of the PSO just built (works on both adopted title PSOs and raw PC compute +/// passes owned by `TwoPassPso`), for the disk cache; kept in memory too while `COMPUTE_BLOBS_MAX` +/// has room. +unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: usize) -> Option>> { + if dxil_len < COMPUTE_BLOB_MIN_DXIL || pso.is_null() { + return None; + } + if let Some(b) = compute_blob(key) { + return Some(b); + } + let bytes = read_pso_cached_blob(pso)?; + let mut g = COMPUTE_BLOBS.lock().unwrap(); + remember_compute_blob(g.get_or_insert_with(|| (HashMap::new(), 0)), key, bytes) +} + +/// `bytes`, the driver's blob of the pipeline `key`, for its caller – and in `store` (the blobs +/// kept in memory and their bytes in all) while `COMPUTE_BLOBS_MAX` has room. The blob is +/// returned either way so once the RAM store fills, slower pipelines still persist to disk. +fn remember_compute_blob(store: &mut (HashMap<(u64, usize, i32), std::sync::Arc>>, usize), key: (u64, usize, i32), bytes: Vec) -> Option>> { + if let Some(current) = store.0.get(&key) { + return Some(current.clone()); + } + if bytes.is_empty() { + return None; + } + let bytes = std::sync::Arc::new(bytes); + if bytes.len() <= COMPUTE_BLOBS_MAX.saturating_sub(store.1) { + store.1 += bytes.len(); + store.0.insert(key, bytes.clone()); + } + Some(bytes) } /// The driver's compiled form of translated graphics pipelines (`GetCachedBlob`), @@ -4763,24 +6382,39 @@ fn forget_graphics_blob(key: (u64, usize)) { } } -unsafe fn keep_graphics_blob(key: (u64, usize), pso: *mut c_void, dxil_len: usize) { - if dxil_len < COMPUTE_BLOB_MIN_DXIL || pso.is_null() || graphics_blob(key).is_some() { - return; +/// The driver's blob of the graphics pipeline just built, for its caller (the disk cache), and +/// in memory while `GRAPHICS_BLOBS_MAX` has room (as `remember_compute_blob`: one the store has +/// no room for must still reach the disk). +unsafe fn keep_graphics_blob(key: (u64, usize), pso: *mut c_void, dxil_len: usize) -> Option>> { + let preparing = PREPARING.load(Ordering::Relaxed); + if (dxil_len < COMPUTE_BLOB_MIN_DXIL && !preparing) || pso.is_null() { + return None; + } + if let Some(b) = graphics_blob(key) { + return Some(b); + } + let bytes = read_pso_cached_blob(pso)?; + if bytes.is_empty() { + return None; + } + let bytes = std::sync::Arc::new(bytes); + // (a preparation worker builds each pipeline once: for the disk only) + if preparing { + return Some(bytes); } - let Some(bytes) = read_pso_cached_blob(pso) else { return }; let mut g = GRAPHICS_BLOBS.lock().unwrap(); let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); - if bytes.is_empty() || *total + bytes.len() > GRAPHICS_BLOBS_MAX { - return; + if *total + bytes.len() <= GRAPHICS_BLOBS_MAX { + *total += bytes.len(); + m.insert(key, bytes.clone()); } - *total += bytes.len(); - m.insert(key, std::sync::Arc::new(bytes)); + Some(bytes) } /// Deterministic FNV-1a digest of every field in a translated PC graphics PSO (shaders, static /// samplers, blend/rasterizer/depth-stencil state, input layout, render target / depth formats, /// sample desc, topology, flags) for in-memory and on-disk driver blob caching. -unsafe fn graphics_blob_key( +pub(super) unsafe fn graphics_blob_key( copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, vs_dxil: &[u8], ps_dxil: Option<&[u8]>, @@ -5006,6 +6640,29 @@ mod graphics_blob_tests { assert_eq!((attempts[1].0.as_str(), attempts[1].1, attempts[1].2), ("graphics retry", false, 0)); } + #[test] + fn cached_graphics_blob_is_kept_when_the_device_is_removed() { + let removed = windows::Win32::Graphics::Dxgi::DXGI_ERROR_DEVICE_REMOVED.0; + let blob = [0xEFu8; 32]; + let mut copy = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let mut calls = 0usize; + let build = create_graphics_pso_cached( + &mut copy, + Some(&blob), + false, + || panic!("a removed device says nothing about the blob: it must not be evicted"), + |_, _, f| (f(), std::time::Duration::from_millis(1)), + |_| { + calls += 1; + removed + }, + ); + assert_eq!(build.hr, removed); + assert_eq!(calls, 2, "with the blob, then without it"); + assert!(!build.reused); + assert!(!build.cache_eligible); + } + #[test] fn rect_list_gs_fallback_does_not_cache_under_with_gs_key() { const E_INVALIDARG: HRESULT = -2147024809; @@ -5085,7 +6742,9 @@ fn create_graphics_pso_cached( if hr >= 0 { return GraphicsPsoBuild { hr, in_driver, reused: true, cache_eligible: false }; } - on_stale_cache(); + if driver_cache::refused(hr) { + on_stale_cache(); + } copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let (retried, took) = run("graphics retry", false, &mut || retry_without_rect_gs(copy, rect_gs, &mut create)); let dropped_rect_gs = rect_gs && copy.GS.pShaderBytecode.is_null(); @@ -5156,14 +6815,21 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const return None; } }, - Some(p) => Some(p.to_vec()), + Some(p) => Some(p.to_vec().into()), None => None, }; + // Large translated graphics pipelines (>= huge_pso_bytes) defer off the title thread when + // `dxc::defer()` is active, matching `translated_compute_pso_once` so cold >= 256 KiB graphics + // PSOs never stall title threads even when `XCL_LAZY_PSO=0`. + let big = vs_dxil.len() + ps_dxil.as_ref().map_or(0, |v| v.len()) >= huge_pso_bytes(); + if big && crate::gpu::recomp::dxc::defer() { + return None; + } let rs = abi_rs_for(this, &samplers)?; let mut copy: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::ptr::read(d); copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); copy.VS = bytecode(&vs_dxil); - copy.PS = ps_dxil.as_deref().map(bytecode).unwrap_or_default(); + copy.PS = ps_dxil.as_deref().map(|v| bytecode(v)).unwrap_or_default(); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); // a rect list pipeline: the fourth corner of each rect comes from a generated GS; without // it each rect is drawn as the triangle of its three vertices @@ -5177,23 +6843,66 @@ 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); + let lib_key = (!debug_override).then(|| pso_lib::graphics_key(©, &vs_dxil, ps_dxil.as_deref().map(Vec::as_slice), rect_gs.as_deref(), &samplers)); + if let Some(key) = lib_key.as_deref() { + if pso_lib::try_load_graphics(this, key, ©, riid, 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))]); + super::ambient::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); + TRANSLATED_GRAPHICS.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); + if super::present::trace_frame() { + PSO_SHADERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps_hash)); + } + if n < 5 || n % 1000 == 0 { + crate::xlog_info!("D3D12.X: graphics PSO loaded from memory-mapped pipeline library (#{})", n + 1); + } + return Some(S_OK); + } + } if debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash) { copy.DepthStencilState.StencilEnable = false.into(); } if debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash) { copy.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; } - 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); + let bytes = vs_dxil.len() + ps_dxil.as_ref().map_or(0, |v| v.len()) + rect_gs.as_ref().map_or(0, Vec::len); + let gkey = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref().map(Vec::as_slice), rect_gs.as_deref(), &samplers); let mut cached = graphics_blob(gkey); - let disk = driver_cache::graphics_path(gkey.0, gkey.1); + let driver = driver_identity(this); + let disk = driver.and_then(|id| { + let mut h = Fnv64::new(); + h.u64(gkey.0); + h.u64(gkey.1 as u64); + h.u64(id); + h.u32(crate::gpu::recomp::pso::mem_windows()); + driver_cache::graphics_path(h.finish(), bytes) + }); let from_disk = cached.is_none(); if from_disk { - cached = disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + cached = disk + .as_deref() + .and_then(driver_cache::load) + .filter(|b| cached_blob_has_isa(Some(b))) + .map(std::sync::Arc::new); + } + let has_isa_blob = cached_blob_has_isa(cached.as_deref().map(Vec::as_slice)); + // a pipeline the driver crashed on in an earlier run, here or in a preparation worker, is not + // given to it again (`driver_crash`): its draws are left out like a refused pipeline's + let crash_key = format!("g-{:016x}-{:x}", gkey.0, gkey.1); + if super::driver_crash::blocked(&crash_key) { + note_translation_error(format!("the driver crashed building the graphics pipeline {crash_key} in an earlier run (driver-crashes.txt beside the DXIL cache) – not built")); + return Some(E_INVALIDARG); } + let mut crash_shaders: Vec<(String, &[u8])> = vec![("vs.dxil".to_string(), &vs_dxil[..])]; + crash_shaders.extend(ps_dxil.as_deref().map(|p| ("ps.dxil".to_string(), &p[..]))); + crash_shaders.extend(rect_gs.as_deref().map(|g| ("gs.dxil".to_string(), g))); + let _building = super::driver_crash::building(&crash_key, &crash_shaders); let build = create_graphics_pso_cached( &mut copy, - cached.as_deref().map(Vec::as_slice), + has_isa_blob.then(|| cached.as_deref().map(Vec::as_slice)).flatten(), rect_gs.is_some(), || { forget_graphics_blob(gkey); @@ -5201,14 +6910,22 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const driver_cache::note(false, disk.as_deref()); } }, - |label, has_cached, f| driver_compile_identified(label, bytes, gate_compute_driver_compile(has_cached), Some((ps_hash, has_cached)), f), + |label, has_cached, f| { + let gated_cached = has_cached && has_isa_blob; + driver_compile_identified(label, bytes, gate_compute_driver_compile(gated_cached), Some((ps_hash, gated_cached)), f) + }, |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv), ); let hr = build.hr; if build.cache_eligible { - keep_graphics_blob(gkey, *ppv, bytes); - if let (Some(p), Some(b)) = (disk.as_deref(), graphics_blob(gkey)) { - driver_cache::keep(p, &b, build.in_driver); + if let Some(b) = keep_graphics_blob(gkey, *ppv, bytes) { + if let Some(p) = disk.as_deref() { + if PREPARING.load(Ordering::Relaxed) { + driver_cache::write(p, &b); + } else { + driver_cache::keep(p, &b, build.in_driver); + } + } } } else if build.reused && from_disk { driver_cache::note(true, None); @@ -5225,13 +6942,22 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const return None; } let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + if let Some(key) = lib_key { + let final_key = if rect_gs.is_some() && copy.GS.pShaderBytecode.is_null() { + pso_lib::graphics_key(©, &vs_dxil, ps_dxil.as_deref().map(Vec::as_slice), None, &samplers) + } else { + key + }; + pso_lib::store_pipeline(this, &final_key, *ppv); + } note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", shader_bytes(&d.PS))]); - TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + super::ambient::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); + TRANSLATED_GRAPHICS.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); if super::present::trace_frame() { let ps = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); - PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps)); + PSO_SHADERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps)); // the input layout (semantic index, format, slot, offset) – what the vertices are read as let il = &d.InputLayout; let elems: Vec = if il.NumElements > 0 && !il.pInputElementDescs.is_null() { @@ -5242,7 +6968,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const } else { Vec::new() }; - PSO_LAYOUTS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, elems.join(", ")); + PSO_LAYOUTS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, elems.join(", ")); static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 400 { let b = &d.BlendState.RenderTarget[0]; @@ -5297,25 +7023,75 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const /// The root signature pointer is kept as is (the translated paths replace it). #[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), +} + +/// A pipeline's copy of one of its console shaders, shared with every pipeline that copied the +/// same bytes (`intern_blob`). +type Blob = std::sync::Arc<[u8]>; + +/// The copies kept: (title address, length) → the copy, while a pipeline holds it. +static BLOBS: Mutex>, usize)>> = Mutex::new(None); + +/// The copy of the shader `bytes` a pipeline keeps until it is built: the one an earlier +/// pipeline made of the same bytes at the same address, or a new one. A retail title makes +/// ~80 000 pipelines in its first minute from a few thousand shaders, and every one waiting to +/// be built (`pso_async::lazy`) held copies of its own. (Equal bytes are checked: an address +/// the title used again for another shader gets a copy of its own.) +fn intern_blob(bytes: &[u8]) -> Blob { + let key = (bytes.as_ptr() as usize, bytes.len()); + let mut g = BLOBS.lock().unwrap(); + let (m, since_prune) = g.get_or_insert_with(|| (HashMap::new(), 0)); + if let Some(b) = m.get(&key).and_then(std::sync::Weak::upgrade) { + if *b == *bytes { + return b; + } + } + let b: Blob = std::sync::Arc::from(bytes); + m.insert(key, std::sync::Arc::downgrade(&b)); + *since_prune += 1; + if *since_prune >= 4096 { + *since_prune = 0; + m.retain(|_, w| w.strong_count() > 0); + } + b +} + +/// The shader copies pipelines hold (`intern_blob`): how many and their bytes. +pub fn pipeline_blob_bytes() -> (usize, usize) { + BLOBS.lock().unwrap().as_ref().map_or((0, 0), |(m, _)| { + m.values().filter_map(std::sync::Weak::upgrade).fold((0, 0), |(n, b), x| (n + 1, b + x.len())) + }) } unsafe impl Send for OwnedDesc {} /// A hash of a pipeline's shaders in their order (never 0): what `pso_async` knows a used /// pipeline by in the next run. -pub(crate) fn shaders_key(blobs: &[Vec]) -> u64 { +/// `shaders_key` of the one shader `blob`. +pub(crate) fn shader_key(blob: &[u8]) -> u64 { + ((0xcbf2_9ce4_8422_2325u64 ^ crate::gpu::shader::fnv64(blob)).wrapping_mul(0x0000_0100_0000_01b3)) | 1 +} + +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 } #[cfg(test)] mod shaders_key_tests { + #[test] + fn the_key_of_one_shader_is_the_key_of_a_set_of_it() { + let a = vec![1u8, 2, 3]; + assert_eq!(super::shader_key(&a), super::shaders_key(&[a.clone()])); + assert_ne!(super::shader_key(&a), super::shader_key(&[4u8, 5])); + } + #[test] fn a_key_follows_the_shaders_and_their_order_and_is_never_zero() { let (a, b) = (vec![1u8, 2, 3], vec![4u8, 5]); @@ -5324,17 +7100,39 @@ 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); } } impl OwnedDesc { - fn shaders_key(&self) -> u64 { - shaders_key(match self { + /// The key of its shaders, and each shader's (`shader_key`, in its own order). + fn shaders_key(&self) -> (u64, Vec) { + let blobs = match self { OwnedDesc::Compute(_, b) => b, OwnedDesc::Graphics(_, b, ..) => b, OwnedDesc::Stream(_, _, b) => b, - }) + }; + let key = shaders_key(blobs); + // each shader by itself too: what a title's shader preparation translates before the + // next run (`pso_async::earlier_used_shaders`) + let parts: Vec = blobs.iter().map(|b| shader_key(b)).collect(); + super::pso_async::shaders_of(key, parts.clone()); + (key, parts) + } + + /// A graphics pipeline's entry for the next run's preparation (`gfx_records`), of the set + /// `key` whose shaders' keys are `parts`; None for any other. + unsafe fn record(&self, key: u64, parts: &[u64]) -> Option> { + let OwnedDesc::Graphics(d, ..) = self else { return None }; + // (`own_graphics` copied the stages it has, in this order) + let mut parts = parts.iter(); + let mut shaders = [0u64; 5]; + for (s, b) in shaders.iter_mut().zip([&d.VS, &d.PS, &d.DS, &d.HS, &d.GS]) { + if !b.pShaderBytecode.is_null() && b.BytecodeLength != 0 { + *s = *parts.next()?; + } + } + Some(super::gfx_records::encode(key, shaders, d)) } fn ptr(&self) -> *const c_void { @@ -5346,10 +7144,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>) { +/// Copy a shader blob into `blobs` (`intern_blob`) and point `b` at the 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_blob(bytes)); let v = blobs.last().unwrap(); *b = bytecode(v); } else { @@ -5402,7 +7200,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()?); @@ -5419,7 +7217,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_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; @@ -5559,9 +7357,27 @@ unsafe fn go_background( return None; } let dev = Dev(this as usize, f as usize); - let key = owned.shaders_key(); + let (key, parts) = owned.shaders_key(); + // (a graphics pipeline used in this run is built before the next starts: `gfx_records`) + let described = if super::pso_async::lazy() { owned.record(key, &parts) } else { None }; // 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))); + let big_image_only = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); + let image_only = big_image_only && super::pso_async::image_skip(); + let bvh_trav = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| is_rt_gated_cs(b))); + let heavy_compute = compute + && super::pso_async::async_heavy_compute() + && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::compute_code_len(b).is_some_and(|n| n >= crate::gpu::effects::HEAVY_CODE))); + let ambient_cs = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| super::ambient::is_ambient_compute(b))); + if compute { + if let OwnedDesc::Compute(_, b) = &owned { + if let Some(cs) = b.first() { + note_compute_threads(*ppv as usize, cs); + } + } + if bvh_trav { + BVH_TRAVERSAL_PSOS.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + } + } let job: super::pso_async::Job = Box::new(move || { let mut out: *mut c_void = std::ptr::null_mut(); if unsafe { build(dev, &owned, &mut out) } && !out.is_null() { @@ -5570,17 +7386,25 @@ unsafe fn go_background( 0 } }); + // Only pure image-writing compute shaders (zero buffer/global/GDS writes) or BVH RT traversal + // shaders may ever be spared/skipped while building. Heavy producer compute shaders that write + // memory and stand-in ambient resolve/reflection passes are never skipped when bound. + let flags = super::pso_async::SubmitFlags { + spared: !ambient_cs && (image_only || (heavy_compute && big_image_only)), + bvh_traversal: bvh_trav && bvh_gate_enabled(), + deprioritized: heavy_compute || (bvh_trav && bvh_gate_enabled()), + }; if super::pso_async::lazy() { - super::pso_async::submit_lazy(*ppv as usize, compute, job, key); + super::pso_async::submit_lazy_with_flags(*ppv as usize, compute, job, key, flags); + if let Some(entry) = described { + super::pso_async::on_first_use(*ppv as usize, Box::new(move || super::gfx_records::note(entry))); + } } else { - super::pso_async::submit(*ppv as usize, compute, job); + super::pso_async::submit_with_flags(*ppv as usize, compute, job, flags); } if driver != 0 { super::pso_async::shared(*ppv as usize, driver); } - if image_only { - super::pso_async::image_only(*ppv as usize); - } Some(hr) } @@ -5589,6 +7413,33 @@ unsafe fn build_graphics(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool matches!(translated_graphics_pso(dev.0 as *mut c_void, std::mem::transmute::(dev.1), d.ptr(), &iid, out), Some(hr) if hr >= 0) } +/// This process is a shader preparation worker (`prepare_device`): it keeps the driver's blob of +/// every graphics pipeline it builds on disk, whatever its size and time, and none in memory. +static PREPARING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// A shader preparation worker's device (`shaders::graphics_worker`), made on the title's adapter: +/// adopted as the title's is, so `prepare_graphics` takes the title's path. Raw, kept for the +/// process. +pub(crate) fn prepare_device(device: ID3D12Device) -> usize { + PREPARING.store(true, Ordering::Relaxed); + let raw = device.into_raw(); + unsafe { adopt(raw, Kind::Device) }; + raw as usize +} + +/// A title's graphics pipeline `desc` (`gfx_records::Record::desc`) built on `device` +/// (`prepare_device`) as the title's background build makes it (`build_graphics`): the +/// translation, DXC and driver blob caches on disk get what the title will ask for. The pipeline +/// is released; false: not made (noted in the log as the title's would be). +pub(crate) unsafe fn prepare_graphics(device: usize, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> bool { + let this = device as *mut c_void; + let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateGraphicsPipelineState"))); + let mut out: *mut c_void = std::ptr::null_mut(); + let made = matches!(translated_graphics_pso(this, f, desc as *const _ as *const c_void, &pc_iid(Kind::PipelineState), &mut out), Some(hr) if hr >= 0) && !out.is_null(); + super::pso_async::release(out as usize); + made +} + unsafe fn build_compute(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { let iid = pc_iid(Kind::PipelineState); matches!(translated_compute_pso(dev.0 as *mut c_void, std::mem::transmute::(dev.1), d.ptr(), &iid, out), Some(Ok(hr)) if hr >= 0) @@ -5645,13 +7496,91 @@ unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID unsafe fn note_translated_compute(hr: HRESULT, ppv: *mut *mut c_void) { if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { - TRANSLATED_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + TRANSLATED_COMPUTE.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); } } unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let hr = create_compute_pso(this, desc, riid, ppv); + if hr >= 0 && !ppv.is_null() { + super::culprit::note_compute(*ppv as usize, desc); + } + hr +} + +/// When `XCL_RT_GATE` is in `Hold` mode (default), RT traversal and RT companion compute shaders +/// (`is_rt_gated_cs`) receive a lightweight stand-in pipeline immediately without translating, +/// enqueueing a worker job, or calling `CreateComputePipelineState` on the console shader. +/// Eliminates multi-minute / multi-GB driver compiles (e.g. >1 MiB ray-activation passes) and +/// prevents unguarded `image_bvh*_intersect_ray` dispatches from faulting before null-BVH guards +/// land. `is_translated_compute` stays `false` while `is_console_compute` is `true`, so `Dispatch` +/// and `ExecuteIndirect` skip them cleanly with zero work. +unsafe fn maybe_rt_gated_compute_pso( + this: *mut c_void, + f: PsoFn, + desc: *const c_void, + riid: *const GUID, + ppv: *mut *mut c_void, +) -> Option { + if rt_gate_mode() != RtGateMode::Hold { + return None; + } + if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return None; + } + let d = &*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC); + let cs = shader_bytes(&d.CS)?; + if !crate::gpu::recomp::pso::is_console(cs) || !is_rt_gated_cs(cs) { + return None; + } + let key = if super::standin::enabled() && !ppv.is_null() { compute_key(this, desc) } else { None }; + let mut driver = 0usize; + let hr = match key { + Some(key) => { + let made = super::standin::shell(key, || { + let mut out = std::ptr::null_mut(); + let hr = standin_compute(this, f, desc, &pc_iid(Kind::PipelineState), &mut out); + if hr < 0 || out.is_null() { Err(hr) } else { Ok(out as usize) } + }); + match made { + Ok((shell, d)) => { + *ppv = shell; + driver = d; + S_OK + } + Err(hr) => hr, + } + } + None => standin_compute(this, f, desc, riid, ppv), + }; + if hr < 0 || ppv.is_null() || (*ppv).is_null() { + return None; + } + if driver != 0 { + super::pso_async::submit_gated(*ppv as usize, driver); + } + let record = crate::gpu::shader::fnv64(cs); + static GATED_COUNT: AtomicU64 = AtomicU64::new(0); + let n = GATED_COUNT.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: RT-gated compute PSO {record:016x} held back without compiling ({n} so far; XCL_RT_GATE=hold, set XCL_RT_GATE=auto or 0 to enable)" + ); + } + LAST_COMPUTE_TRANSLATED.with(|c| c.set(false)); + LAST_COMPUTE_RS.with(|c| c.set(0)); + note_compute_threads(*ppv as usize, cs); + note_bvh_traversal(*ppv as usize, cs); + note_console_compute(hr, ppv); + Some(hr) +} + +unsafe fn create_compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { super::null::capture_compute_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); + if let Some(hr) = maybe_rt_gated_compute_pso(this, f, desc, riid, ppv) { + return hr; + } 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) }; 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)) { @@ -5718,28 +7647,28 @@ impl Drop for TwoPassPso { } } -static TWO_PASS: Mutex>>> = Mutex::new(None); +static TWO_PASS: std::sync::RwLock>>> = std::sync::RwLock::new(None); /// The compute pass of a pipeline state XCL built from console MS / GS code. pub fn two_pass_of(pso: usize) -> Option> { let pso = super::pso_async::resolve(pso); - TWO_PASS.lock().unwrap().as_ref()?.get(&pso).cloned() + TWO_PASS.read().unwrap().as_ref()?.get(&pso).cloned() } pub fn two_pass_count() -> usize { - TWO_PASS.lock().unwrap().as_ref().map_or(0, |m| m.len()) + TWO_PASS.read().unwrap().as_ref().map_or(0, |m| m.len()) } #[cfg(test)] pub(super) fn register_two_pass_for_test(pso: usize, kind: &'static str) { if pso != 0 { - TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert( + TWO_PASS.write().unwrap().get_or_insert_with(HashMap::new).insert( pso, std::sync::Arc::new(TwoPassPso { 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, }), @@ -5899,39 +7828,144 @@ fn passthrough_mesh_stream_accepts_a_triangle_driver_blob() { #[allow(dead_code)] // Consumed by the stacked driver-cache integration. mod two_pass_identity; +use two_pass_identity::Fnv64; + +/// Persistent driver-cache counters for the current process: (hits, rejected, saved). +#[doc(hidden)] +pub fn driver_cache_stats() -> (u64, u64, u64) { + driver_cache::stats() +} + +/// The adapter of `device` and its driver (vendor, device, subsystem, revision, user-mode +/// driver version), for the names of the driver blobs kept on disk: the driver refuses another +/// one's blob (it is compiled again), and two adapters sharing the cache (a GPU and the +/// software one) would take turns overwriting each other's files. None: not known (no blob of +/// its pipelines is kept on disk). +fn driver_identity(device: *mut c_void) -> Option { + use windows::Win32::Graphics::Dxgi::*; + let dev = unsafe { ID3D12Device::from_raw_borrowed(&device) }?; + let luid = unsafe { dev.GetAdapterLuid() }; + let key = (luid.HighPart, luid.LowPart); + static IDS: OnceLock>>> = OnceLock::new(); + let mut ids = IDS.get_or_init(Default::default).lock().unwrap(); + *ids.entry(key).or_insert_with(|| unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let adapter: IDXGIAdapter = factory.EnumAdapterByLuid(luid).ok()?; + let desc = adapter.GetDesc().ok()?; + let version = adapter.CheckInterfaceSupport(&IDXGIDevice::IID).ok()?; + let mut h = Fnv64::new(); + h.u32(desc.VendorId); + h.u32(desc.DeviceId); + h.u32(desc.SubSysId); + h.u32(desc.Revision); + h.u64(version as u64); + Some(h.finish()) + }) +} /// The console PS of a two-pass pipeline (a PC PS passes as it is). /// The PS of a two-pass pipeline (DXIL, static samplers – a PC PS passes as it is). -fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool) -> Result<(Option>, Vec), String> { +fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool) -> Result<(Option>>, Vec), String> { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; match ps { Some(p) if is_console(p) => console_to_dxil_for(p, Stage::Pixel, 0, split_wave64).map(|c| (Some(c.dxil), c.samplers)).map_err(|e| format!("PS: {e}")), - Some(p) => Ok((Some(p.to_vec()), Vec::new())), + Some(p) => Ok((Some(p.to_vec().into()), Vec::new())), None => Ok((None, Vec::new())), } } +/// A pipeline state stream (its state; the pointers in it mean nothing later) and its shaders, +/// each with the ending of the file `driver_crash` dumps it to, then the console shaders they +/// were translated from (`console`: stage, container). +unsafe fn crash_dump_shaders<'a>(stream: &'a [u8], console: &[(&str, Option<&'a [u8]>)]) -> Vec<(String, &'a [u8])> { + let mut shaders = vec![("stream.bin".to_string(), stream)]; + for (ty, payload) in stream_subobjects(stream).unwrap_or_default() { + if !SHADER_SUBOBJECTS.iter().any(|t| t.0 as u32 == ty) { + continue; + } + let stage = match D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(ty as i32) { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS => "ms".to_string(), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS => "ps".to_string(), + _ => format!("stage{ty}"), + }; + if let Some(code) = payload_shader(payload) { + shaders.push((format!("{stage}.dxil"), code)); + } + } + shaders.extend(console.iter().filter_map(|(stage, code)| Some((format!("console-{stage}.bin"), (*code)?)))); + shaders +} + /// Create the mesh pipeline (`stream`, RS and shaders already in it) and the compute pass; -/// the title gets the mesh pipeline state. +/// the title gets the mesh pipeline state. `console`: the title's shaders it is made from (for +/// `driver_crash`). #[allow(clippy::too_many_arguments)] -unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, kind: &'static str, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { +unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, kind: &'static str, console: &[(&str, Option<&[u8]>)], riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let Some(rs) = abi_rs_for(this, &tp.samplers) else { return E_INVALIDARG }; let fs: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); let desc: [usize; 2] = [stream.0.len(), stream.0.as_ptr() as usize]; - // the mesh pass and its compute pass: one turn for both + let mesh_lib_key = pso_lib::stream_key(&stream.0, mesh_rs as usize, stream.shader_bytes()); + if super::driver_crash::blocked(&mesh_lib_key) { + note_translation_error(format!("the driver crashed building the mesh pipeline {mesh_lib_key} from the console {kind} in an earlier run (driver-crashes.txt beside the DXIL cache) – not built")); + return E_INVALIDARG; + } + let cs_lib_key = pso_lib::compute_key(&tp.cs, &tp.samplers, 0); + // Try loading both halves from the memory-mapped pipeline library before acquiring any cold + // compile slot so warm runs bypass `big_compile_turn` and commit waits completely. + let mesh_loaded = pso_lib::try_load_stream(this, &mesh_lib_key, &stream.0, riid, ppv); + if mesh_loaded { + let mesh_pso = *ppv; + if let Some(compute) = pso_lib::try_load_compute_raw(this, &cs_lib_key, rs, &tp.cs) { + note_pso_rs(mesh_pso, mesh_rs); + TWO_PASS.write().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); + let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + if n < 5 || n % 1000 == 0 { + crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (loaded from memory-mapped library)"); + } + return S_OK; + } + } + // At least one half missed the pipeline library: take one turn for the cold compile(s). let bytes = stream.shader_bytes() + tp.cs.len(); - let gate = bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); + let huge_bytes = huge_pso_bytes(); + let gate = (bytes >= huge_bytes || tp.cs.len() >= driver_compile_gate_bytes("compute", huge_bytes)) + && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); let waited = std::time::Instant::now(); - let _slot = gate.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)); + let _slot = gate.then(|| big_compile_turn_with(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted, is_preload_worker())); if gate { crate::xlog_info!("D3D12.X: two-pass {kind} PSO ({bytes} B DXIL) gated, waited {} ms", waited.elapsed().as_millis()); } - let hr = driver_compile(kind, stream.shader_bytes(), false, || finish_pso(this, fs, desc.as_ptr() as *const c_void, riid, ppv)); + let two_pass_record = console + .iter() + .find_map(|(_, code)| code.map(crate::gpu::shader::fnv64)) + .unwrap_or_else(|| crate::gpu::shader::fnv64(&tp.cs)); + let hr = if mesh_loaded { + S_OK + } else { + let _building = super::driver_crash::building(&mesh_lib_key, &crash_dump_shaders(&stream.0, console)); + driver_compile_identified(kind, stream.shader_bytes(), false, Some((two_pass_record, false)), || { + finish_pso(this, fs, desc.as_ptr() as *const c_void, riid, ppv) + }) + .0 + }; if hr < 0 || ppv.is_null() || (*ppv).is_null() { note_translation_error(format!("the driver rejected the mesh pipeline from the console {kind} ({hr:#x})")); return E_INVALIDARG; } let mesh_pso = *ppv; + if !mesh_loaded { + pso_lib::store_pipeline(this, &mesh_lib_key, mesh_pso); + if let Some(compute) = pso_lib::try_load_compute_raw(this, &cs_lib_key, rs, &tp.cs) { + drop(_slot); + note_pso_rs(mesh_pso, mesh_rs); + TWO_PASS.write().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); + let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + if n < 5 || n % 1000 == 0 { + crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (compute pass loaded from memory-mapped library)"); + } + return hr; + } + } let fc: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); cdesc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); @@ -5943,33 +7977,41 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let cdisk = driver_cache::path(&tp.cs, 0); let cfrom_disk = ccached.is_none(); if cfrom_disk { - ccached = cdisk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + ccached = cdisk + .as_deref() + .and_then(driver_cache::load) + .filter(|b| cached_blob_has_isa(Some(b))) + .map(std::sync::Arc::new); } - if let Some(b) = &ccached { - cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; + let chas_isa_blob = cached_blob_has_isa(ccached.as_deref().map(Vec::as_slice)); + if chas_isa_blob { + if let Some(b) = &ccached { + cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; + } } let iid = pc_iid(Kind::PipelineState); let mut compute: *mut c_void = std::ptr::null_mut(); - let (mut hc, mut cin_driver) = driver_compile_identified("compute pass", tp.cs.len(), false, None, || { + let (mut hc, mut cin_driver) = driver_compile_identified("compute pass", tp.cs.len(), false, Some((two_pass_record, chas_isa_blob)), || { driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) }); - if hc < 0 && ccached.is_some() { - forget_compute_blob(ckey); - if cfrom_disk { - driver_cache::note(false, cdisk.as_deref()); + if hc < 0 && chas_isa_blob { + if driver_cache::refused(hc) { + forget_compute_blob(ckey); + if cfrom_disk { + driver_cache::note(false, cdisk.as_deref()); + } } cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); compute = std::ptr::null_mut(); - let (retried, took) = driver_compile_identified("compute pass retry", tp.cs.len(), false, None, || { + let (retried, took) = driver_compile_identified("compute pass retry", tp.cs.len(), false, Some((two_pass_record, false)), || { driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) }); hc = retried; cin_driver += took; } - let creused = hc >= 0 && ccached.is_some() && cdesc.CachedPSO.CachedBlobSizeInBytes != 0; + let creused = hc >= 0 && chas_isa_blob && cdesc.CachedPSO.CachedBlobSizeInBytes != 0; if hc >= 0 && !creused && !compute.is_null() { - keep_compute_blob(ckey, compute, tp.cs.len()); - if let (Some(p), Some(b)) = (cdisk.as_deref(), compute_blob(ckey)) { + if let (Some(p), Some(b)) = (cdisk.as_deref(), keep_compute_blob(ckey, compute, tp.cs.len())) { driver_cache::keep(p, &b, cin_driver); } } else if creused && cfrom_disk { @@ -5983,8 +8025,9 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: *ppv = std::ptr::null_mut(); return E_INVALIDARG; } + pso_lib::store_pipeline(this, &cs_lib_key, compute); note_pso_rs(mesh_pso, mesh_rs); - TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); + TWO_PASS.write().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); if n < 5 || n % 1000 == 0 { crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (compute {} B + mesh {} B DXIL)", tp.cs.len(), tp.ms.len()); @@ -5992,6 +8035,149 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: hr } +/// The mesh and amplification shaders of a stream, as XCL translates them: a console MS +/// container in the AS slot with no MS subobject (a retail game's minimap pipelines) is the +/// mesh shader it says it is. It used to be refused – translated, the title rendered nothing +/// from then on, which was the translated mesh shaders failing their output budget (ms_6_6), +/// not the slot. With the chunk budget fixed they translate and the title keeps rendering. +/// Returns (MS to translate, AS left): the moved shader is not an AS any more. +fn mesh_shader_slots<'a>(ms_slot: Option<&'a [u8]>, as_slot: Option<&'a [u8]>) -> (Option<&'a [u8]>, Option<&'a [u8]>) { + use crate::gpu::recomp::pso::is_console; + match (ms_slot, as_slot) { + (None, Some(a)) if is_console(a) && crate::gpu::xbox::parse(a).is_some_and(|sh| sh.stage == "MS") => (Some(a), None), + (ms, a) => (ms, a), + } +} + +#[cfg(test)] +mod mesh_slot_tests { + use super::{console_ms_in_as_slot, fallback_stream, mesh_shader_slots}; + use crate::gpu::xbox::tests::{sample, fssm, CODE}; + + /// A stream subobject: its type, then the payload at 4 (align 4) or 8 (align 8). + fn sub(ty: u32, payload: &[u8]) -> Vec { + let (_, palign) = super::super::null::subobject_payload(ty).unwrap(); + let poff = if palign == 8 { 8 } else { 4 }; + let mut b = vec![0u8; (poff + payload.len() + 7) & !7]; + b[..4].copy_from_slice(&ty.to_le_bytes()); + b[poff..poff + payload.len()].copy_from_slice(payload); + b + } + + fn bytecode(s: &[u8]) -> Vec { + let mut b = Vec::new(); + b.extend_from_slice(&(s.as_ptr() as u64).to_le_bytes()); + b.extend_from_slice(&(s.len() as u64).to_le_bytes()); + b + } + + /// The stream the retail title's AS-slot MS pipelines have: a console MS container in the + /// AS subobject, no MS subobject, a PS and the graphics state (`mesh_shader_slots` moves it). + fn as_slot_ms_stream(ms: &[u8], ps: &[u8]) -> Vec { + let mut s = sub(0, &0u64.to_le_bytes()); // ROOT_SIGNATURE: null + s.extend_from_slice(&sub(24, &bytecode(ms))); + s.extend_from_slice(&sub(2, &bytecode(ps))); + s.extend_from_slice(&sub(8, &vec![0u8; 328])); // BLEND + s.extend_from_slice(&sub(9, &u32::MAX.to_le_bytes())); // SAMPLE_MASK + s.extend_from_slice(&sub(10, &vec![0u8; 44])); // RASTERIZER + s.extend_from_slice(&sub(11, &vec![0u8; 52])); // DEPTH_STENCIL + s.extend_from_slice(&sub(15, &vec![0u8; 36])); // RENDER_TARGET_FORMATS + s.extend_from_slice(&sub(17, &[1, 0, 0, 0, 0, 0, 0, 0])); // SAMPLE_DESC + s + } + + /// The stand-in for a console MS alone in the AS slot is a mesh pipeline: the subobject is + /// retyped to MS with the dummy MS (as `translated_mesh_stream` reads the title's stream), + /// the PS is the dummy PS. Left an empty AS and a PS, the stream had neither an MS nor a VS + /// and the driver refused it (E_INVALIDARG, NishantParajuli's and Chrysana's runs). + #[test] + fn the_stand_in_of_a_moved_ms_is_a_mesh_pipeline() { + let ms = sample(13, &[fssm(&CODE, &[(8, 13)])]); + let ps = b"DXBC-a-pixel-shader".to_vec(); + let stream = as_slot_ms_stream(&ms, &ps); + let desc = [stream.len(), stream.as_ptr() as usize]; + let subs = super::stream_subobjects(&stream).unwrap(); + assert!(unsafe { console_ms_in_as_slot(&subs) }); + let (buf, _) = unsafe { fallback_stream(desc.as_ptr() as *const u8) }.expect("a stand-in stream"); + let out = super::stream_subobjects(&buf).unwrap(); + assert!(!out.iter().any(|s| s.0 == 24), "no AS subobject left"); + let m = out.iter().find(|s| s.0 == 25).expect("an MS subobject"); + let dm = super::dummy_mesh().expect("DXC for the stand-in shaders"); + let got = unsafe { super::payload_shader(m.1) }.unwrap(); + assert_eq!(got, dm.0.as_slice(), "the dummy MS"); + let p = out.iter().find(|s| s.0 == 2).unwrap(); + assert_eq!(unsafe { super::payload_shader(p.1) }.unwrap(), dm.1.as_slice(), "the dummy PS"); + // a real AS with no MS is not moved, and its stand-in keeps the AS slot empty + let as_ = sample(14, &[fssm(&CODE, &[(8, 14)])]); + let stream = as_slot_ms_stream(&as_, &ps); + let desc = [stream.len(), stream.as_ptr() as usize]; + assert!(!unsafe { console_ms_in_as_slot(&super::stream_subobjects(&stream).unwrap()) }); + let (buf, _) = unsafe { fallback_stream(desc.as_ptr() as *const u8) }.unwrap(); + let out = super::stream_subobjects(&buf).unwrap(); + assert!(out.iter().any(|s| s.0 == 24) && !out.iter().any(|s| s.0 == 25)); + } + + /// The stand-in's target formats are the PC's, as the real pipeline's: the console's + /// D16_UNORM_S8_UINT (118) is D24_UNORM_S8_UINT (45) and a B4G4R4A4 target (115) is + /// R8G8B8A8 (28). With the console's the driver refuses the stand-in (the title's depth-only + /// mesh pipelines; NishantParajuli's follow-up, reproduced natively by thehollowedone). + #[test] + fn the_stand_in_of_a_stream_has_the_pcs_target_formats() { + let mut s = sub(15, &{ + let mut p = Vec::new(); + for f in [115u32, 28, 0, 0, 0, 0, 0, 0, 2] { + p.extend_from_slice(&f.to_le_bytes()); + } + p + }); + s.extend_from_slice(&sub(16, &118u32.to_le_bytes())); + let desc = [s.len(), s.as_ptr() as usize]; + let (out, _) = unsafe { fallback_stream(desc.as_ptr() as *const u8) }.expect("a stand-in stream"); + let subs = super::stream_subobjects(&out).unwrap(); + let word = |p: &[u8], k: usize| u32::from_le_bytes(p[4 * k..4 * k + 4].try_into().unwrap()); + assert_eq!((subs[0].0, word(subs[0].1, 0), word(subs[0].1, 1), word(subs[0].1, 8)), (15, 28, 28, 2)); + assert_eq!((subs[1].0, word(subs[1].1, 0)), (16, 45)); + } + + /// A console MS container alone in the AS slot becomes the MS; a real AS (console or PC), + /// an MS already present, or a PC shader in the AS slot are left as they are. + #[test] + fn a_console_ms_in_the_as_slot_is_the_mesh_shader() { + let ms = sample(13, &[fssm(&CODE, &[(8, 13)])]); + let as_ = sample(14, &[fssm(&CODE, &[(8, 14)])]); + let pc = b"DXBC-not-a-console-container".to_vec(); + // MS in the AS slot, no MS: moved, and not an AS any more + let (m, a) = mesh_shader_slots(None, Some(&ms)); + assert!(m.is_some_and(|m| std::ptr::eq(m, ms.as_slice())) && a.is_none()); + // an MS present: both slots untouched, whatever the AS holds + let (m, a) = mesh_shader_slots(Some(&ms), Some(&as_)); + assert!(m.is_some_and(|m| std::ptr::eq(m, ms.as_slice())) && a.is_some_and(|a| std::ptr::eq(a, as_.as_slice()))); + // a console AS (not an MS) stays in the AS slot + let (m, a) = mesh_shader_slots(None, Some(&as_)); + assert!(m.is_none() && a.is_some_and(|a| std::ptr::eq(a, as_.as_slice()))); + // a PC shader in the AS slot stays too + let (m, a) = mesh_shader_slots(None, Some(&pc)); + assert!(m.is_none() && a.is_some()); + // nothing: nothing + assert!(mesh_shader_slots(None, None) == (None, None)); + } + + /// The cached-only attempt defers a moved MS like a console compute pipeline: `defer` + /// marks the attempt missed, so `dev_create_pipeline_state` takes the background path + /// (stand-in now, translation on the worker / first bind) instead of translating on the + /// title's thread – tens of thousands of these pipelines during boot delayed the intro + /// by seconds on NVIDIA and past a minute on AMD wave64. Outside the attempt (the + /// worker's build) nothing is deferred. + #[test] + fn a_moved_ms_defers_in_the_attempt_only() { + let (_, missed) = crate::gpu::recomp::dxc::cached_only(|| { + assert!(crate::gpu::recomp::dxc::defer(), "inside the attempt: deferred"); + }); + assert!(missed, "the attempt is missed: the caller takes the background path"); + assert!(!crate::gpu::recomp::dxc::defer(), "outside: the build translates"); + } +} + /// CreatePipelineState with a console MS: Some(hr) when it was a console mesh pipeline /// (translated, or E_INVALIDARG – console bytecode must not reach the driver). unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { @@ -6010,17 +8196,11 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri let subs = stream_subobjects(std::slice::from_raw_parts(base as *const u8, size))?; let as_slot = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS.0 as u32).and_then(|s| payload_shader(s.1)); let ms_slot = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32).and_then(|s| payload_shader(s.1)); - // A console MS container in the AS slot and no MS subobject (a retail game's minimap - // pipelines): refused. Translated as the mesh shader they are, the title rendered nothing - // from then on (a black screen every run); refused, it goes on to its menus. What it - // expects of them is not known yet. - if let (None, Some(a)) = (ms_slot, as_slot) { - if is_console(a) && crate::gpu::xbox::parse(a).is_some_and(|sh| sh.stage == "MS") { - note_translation_error(format!("mesh pipeline with its MS {:016x} in the AS slot – refused", crate::gpu::shader::fnv64(a))); - return Some(E_INVALIDARG); - } - } - let ms = ms_slot?; + // a console MS in the AS slot with no MS subobject: moved, and translated when first + // bound (below), not on the title's thread for each of tens of thousands + let moved = ms_slot.is_none(); + let (ms, as_slot) = mesh_shader_slots(ms_slot, as_slot); + let Some(ms) = ms else { return None }; if !is_console(ms) { return None; } @@ -6037,6 +8217,12 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { return None; } + if moved { + let n = AS_SLOT_MS.fetch_add(1, Ordering::Relaxed); + if n < 5 || n % 1000 == 0 { + crate::xlog_info!("D3D12.X: mesh pipeline with its MS {:016x} in the AS slot – translated as MS (#{})", crate::gpu::shader::fnv64(ms), n + 1); + } + } let ps = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32).and_then(|s| payload_shader(s.1)); let console_ps = ps; let (tp, (ps, ps_samplers)) = match (console_mesh(ms, ps, wave32_only(this)), two_pass_ps(ps, graphics_wave32(this))) { @@ -6050,9 +8236,13 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri return Some(E_INVALIDARG); } }; + let big = tp.ms.len() + tp.cs.len() + ps.as_ref().map_or(0, |v| v.len()) >= huge_pso_bytes(); + if big && crate::gpu::recomp::dxc::defer() { + return None; + } let Some(rs) = abi_rs_for(this, &ps_samplers) else { return Some(E_INVALIDARG) }; // the title's state (blend, rasteriser, depth, formats …) with XCL's RS and shaders - let mut out = two_pass_mesh_stream(rs, &tp.ms, ps.as_deref()); + let mut out = two_pass_mesh_stream(rs, &tp.ms, ps.as_deref().map(Vec::as_slice)); // Extract PC-mapped render target formats upfront so BLEND (type 8) can be sanitized for // integer RTVs regardless of subobject order in the stream. let mut rt_count = 0u32; @@ -6092,9 +8282,13 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri out.raw(*ty, payload, palign == 8); } } - let hr = finish_two_pass(this, &out, tp, rs, "MS", riid, ppv); + let hr = finish_two_pass(this, &out, tp, rs, "MS", &[("ms", Some(ms)), ("ps", console_ps)], riid, ppv); if hr >= 0 { super::dred::label(*ppv as usize, &[("ms", Some(ms)), ("ps", console_ps)]); + super::ambient::note_graphics_pso(*ppv as usize, console_ps); + if let Some(tp) = two_pass_of(*ppv as usize) { + super::dred::label_text(tp.compute, || format!("compute pass of ms {:016x}", crate::gpu::shader::fnv64(ms))); + } } Some(hr) } @@ -6148,7 +8342,7 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE } }; let Some(rs) = abi_rs_for(this, &ps_samplers) else { return E_INVALIDARG }; - let mut out = two_pass_mesh_stream(rs, &tp.ms, ps.as_deref()); + let mut out = two_pass_mesh_stream(rs, &tp.ms, ps.as_deref().map(Vec::as_slice)); let mut rt = D3D12_RT_FORMAT_ARRAY { NumRenderTargets: d.NumRenderTargets, RTFormats: d.RTVFormats }; for f in rt.RTFormats.iter_mut() { *f = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_target_format(f.0 as u32) as i32); @@ -6167,13 +8361,21 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE if d.Flags.0 != 0 { out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, &d.Flags); } - let hr = finish_two_pass(this, &out, tp, rs, "GS", riid, ppv); + let hr = finish_two_pass(this, &out, tp, rs, "GS", &[("vs", Some(vs)), ("gs", Some(gs)), ("ps", shader_bytes(&d.PS))], riid, ppv); if hr >= 0 { super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("gs", Some(gs)), ("ps", shader_bytes(&d.PS))]); + super::ambient::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); } hr } +/// A console MS container in the stream's AS subobject and no MS subobject (`mesh_shader_slots`). +unsafe fn console_ms_in_as_slot(subs: &[(u32, &[u8])]) -> bool { + let shader = |ty: i32| subs.iter().find(|s| s.0 == ty as u32).and_then(|s| payload_shader(s.1)); + shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0).is_none() + && shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS.0).is_some_and(|a| crate::gpu::recomp::pso::is_console(a) && crate::gpu::xbox::parse(a).is_some_and(|sh| sh.stage == "MS")) +} + /// Rewrite a pipeline state stream with stand-in shaders. None if not possible. unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { let size = *(desc as *const usize); @@ -6183,12 +8385,15 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { } let mut buf = std::slice::from_raw_parts(base as *const u8, size).to_vec(); let d = dummy(); + // a console MS alone in the AS slot is the stream's mesh shader (`mesh_shader_slots`): its + // stand-in is a mesh pipeline too + let ms_in_as = stream_subobjects(&buf).is_some_and(|subs| console_ms_in_as_slot(&subs)); let (mesh, rt_count, rt_formats) = { let mut mesh = false; let mut rt_count = 0u32; let mut rt_formats = [windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(0); 8]; if let Some(subs) = stream_subobjects(&buf) { - mesh = subs.iter().any(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32); + mesh = ms_in_as || subs.iter().any(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32); if let Some((_, p)) = subs.iter().find(|(ty, p)| *ty == 15 && p.len() >= 36) { for k in 0..8 { let f = super::device_x::pc_target_format(u32::from_le_bytes(p[4 * k..4 * k + 4].try_into().unwrap())); @@ -6220,6 +8425,10 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { 1 => put(&mut buf, &d.vs), 2 => put(&mut buf, dm.map_or(&d.ps[..], |m| &m.1[..])), 6 => put(&mut buf, &d.cs), + 24 if ms_in_as => { + buf[off..off + 4].copy_from_slice(&(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32).to_le_bytes()); + put(&mut buf, &dm?.0) + } 3 | 4 | 5 | 24 => put(&mut buf, &[]), 25 => put(&mut buf, &dm?.0), 8 if psize >= std::mem::size_of::() => { @@ -6554,14 +8763,94 @@ 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)); } -} - -enum StreamPipeline { - Graphics(Box), - Compute(Box), - /// neither with console shaders (or not readable) - Unknown, -} + + /// 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 { + Graphics(Box), + Compute(Box), + /// neither with console shaders (or not readable) + Unknown, +} /// A pipeline stream with a console VS (+ PS / GS) or CS as the plain pipeline desc, which is /// translated like any other (`dev_create_graphics_pso`). The stream itself must not reach the @@ -6817,6 +9106,7 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de } let desc = copy.as_ref().map_or(desc, |c| c as *const _ as *const c_void); f(this, res, desc, handle); + super::list_x::bump_rt_desc_gen(); super::present::note_rtv(handle, res); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); @@ -6844,6 +9134,12 @@ unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *co } unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rtvs: *const usize, single: i32, dsv: *const usize) { + if !dsv.is_null() { + super::depth_uav::before_bind_dsv(this, *dsv); + } + if super::list_x::skip_redundant_render_targets(this, n, rtvs, single, dsv) { + return; + } type F = unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "OMSetRenderTargets"))); f(this, n, rtvs, single, dsv); @@ -6875,12 +9171,15 @@ pub(super) unsafe fn bind_pipeline(this: *mut c_void, pso: *mut c_void) { } unsafe extern "system" fn cl_set_pipeline_state(this: *mut c_void, pso: *mut c_void) { + let bound = super::pso_async::resolve(pso as usize); + if super::list_x::skip_redundant_pso_bind(this, pso as usize, bound) { + return; + } type F = unsafe extern "system" fn(*mut c_void, *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "SetPipelineState"))); - let bound = super::pso_async::resolve(pso as usize); f(this, bound as *mut c_void); super::dred::mark_pipeline(this, pso as usize, bound); - super::list_x::on_set_pipeline_state(this, pso as usize); + super::list_x::on_set_pipeline_state_bound(this, pso as usize, bound); } /// The title's markers are counted for `XCL_DRED=1`'s pipeline labels (`dred`). @@ -6944,22 +9243,77 @@ unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 { n } -unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { +/// Release `this` through its driver vtable. When this call drops the last reference, `take` +/// runs first, while the call still holds one: once the driver has freed the object, another +/// thread can get a new one at the same address and record its own entries there, which `take` +/// would then remove. What `take` returns goes to `after` once the object is gone (memory the +/// object was made on is freed after it). Two last-but-one releases at once both miss +/// `AddRef == 2`; the one whose `Release` ends at 0 then runs `take` after the object is gone, +/// as before. +unsafe fn release_taking_first(this: *mut c_void, take: impl FnOnce() -> T, after: impl FnOnce(T)) -> u32 { + let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + let mut take = Some(take); + let taken = if add_ref(this) == 2 { take.take().map(|t| t()) } else { None }; + f(this); let n = f(this); - if n == 0 { - super::list_x::on_queue_release(this as usize); + let taken = taken.or_else(|| if n == 0 { take.take().map(|t| t()) } else { None }); + if let Some(t) = taken { + after(t); } n } +unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { + release_taking_first(this, || super::list_x::on_queue_release(this as usize), drop) +} + 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 } @@ -6969,21 +9323,21 @@ 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 hr = f(raw); - if hr >= 0 { dispatch_chain::allocator_reset(raw as usize); } + if hr >= 0 { + // Only now is the GPU done with recordings backed by `raw` (`alloc_pool` may have put + // an older backing allocator aside during a title `Reset` while its submits still run). + dispatch_chain::allocator_reset(raw as usize); + super::console_list::allocator_reset(raw); + } hr } unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { // (lists may still hold recordings on it that the title submits again: `alloc_pool`) - let hr = match super::alloc_pool::title_reset(this) { + match super::alloc_pool::title_reset(this) { Some(hr) => hr, None => reset_pc_allocator(this), - }; - if hr >= 0 { - // the GPU is done with what lists recorded from this allocator used - super::console_list::allocator_reset(this); } - hr } // --------------------------------------------------------------------------------------- @@ -7024,9 +9378,21 @@ static QUEUE_OLDER: AtomicBool = AtomicBool::new(false); /// command list slots of the newer layout → the older layout's slot of the same method /// (`DispatchMesh` sits at newer #129 after #126 RSSetShadingRate, #127 RSSetShadingRateImage, -/// and #128 Scarlett-only shading-rate/color struct; older #127, two slots before as the others). +/// and #128 Scarlett-only shading-rate/color struct: the older #127, two slots before as the rest). const NEWER_LIST_SLOTS: [(usize, usize); 22] = [(61, 59), (62, 60), (63, 61), (64, 62), (65, 63), (70, 68), (71, 69), (72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (129, 127), (139, 10)]; +pub(super) unsafe fn list_device(list: *mut c_void) -> Option { + type F = unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(list, 7)); + let iid = pc_iid(Kind::Device); + let mut raw: *mut c_void = std::ptr::null_mut(); + if f(list, &iid, &mut raw) >= 0 && !raw.is_null() { + Some(ID3D12Device::from_raw(raw)) + } else { + None + } +} + /// The title called device method `slot`, which only runtimes with the newer layouts have (a retail game /// records its first lists before any queue call could tell). pub(super) fn note_newer_device_method(slot: usize) { @@ -7108,6 +9474,7 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a f(this, a1) } 23 => q_signal_x(this, a1 as *mut c_void, a2 as u64, a3 as u32) as u32 as usize, + 29 => 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, // 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 @@ -7154,6 +9521,57 @@ 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); +/// command queue #29 (#31 in the newer layout) `CopyPageMappingsBatchX(count, batches, pool, +/// pool pages, flags)`: the title maps pages of its memory into GPU views – a retail game the +/// pages its texture streaming fills (a 6 GB pool) into the GPU views its textures are in, +/// tens of thousands of them while its world loads. Recorded per page (`kernelx::mirrors`); +/// as a stub every mapping was dropped (#1031). +unsafe fn q_copy_page_mappings(count: u32, batches: usize, pool: usize, pool_pages: u32) -> HRESULT { + static CALLS: AtomicU64 = AtomicU64::new(0); + static MAPPED: AtomicU64 = AtomicU64::new(0); + static UNMAPPED: AtomicU64 = AtomicU64::new(0); + static ELSEWHERE: AtomicU64 = AtomicU64::new(0); + static PHYSICAL: AtomicU64 = AtomicU64::new(0); + let n = CALLS.fetch_add(1, Ordering::Relaxed) + 1; + // physical pages alias (`XCL_PAGE_ALIAS`): the GPU-view pages show the pool pages' physical + // pages for real, instead of a record of them + if crate::hle::kernelx::alias::enabled() { + static EMPTY: AtomicU64 = AtomicU64::new(0); + let done = crate::hle::kernelx::mirrors::decode_batches(count, batches, pool, pool_pages).and_then(|changes| { + crate::hle::kernelx::note_gpu_view_mapping(changes.first().map_or(0, |c| c.0)); + crate::hle::kernelx::alias::apply_page_mappings(&changes) + }); + match done { + Some(d) => { + let add = |total: &AtomicU64, k: u64| total.fetch_add(k, Ordering::Relaxed) + k; + let (m, u, e) = (add(&MAPPED, d.mapped), add(&UNMAPPED, d.unmapped), add(&EMPTY, d.empty_pool)); + if n == 1 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: queue CopyPageMappingsBatchX: {n} calls; pages mapped so far: {m} showing a physical page, {u} unmapped ({e} of them for a pool page with nothing mapped; pool {pool:#x}, {pool_pages} pages of 64 KiB)"); + } + } + None => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: queue CopyPageMappingsBatchX({count}, {batches:#x}, {pool:#x}, {pool_pages}): a batch or range is unreadable or leaves the pool, or a page could not be mapped")); + } + } + return S_OK; + } + match crate::hle::kernelx::mirrors::apply_batches(count, batches, pool, pool_pages) { + Some(d) => { + let add = |total: &AtomicU64, k: u64| total.fetch_add(k, Ordering::Relaxed) + k; + let (m, p, u, e) = (add(&MAPPED, d.mapped), add(&PHYSICAL, d.physical), add(&UNMAPPED, d.unmapped), add(&ELSEWHERE, d.elsewhere)); + if n == 1 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: queue CopyPageMappingsBatchX: {n} calls; GPU-view pages so far: {m} mapped ({p} to a physical page the title mapped there), {u} unmapped; {e} pages elsewhere ignored (pool {pool:#x}, {pool_pages} pages of 64 KiB)"); + } + } + None => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: queue CopyPageMappingsBatchX({count}, {batches:#x}, {pool:#x}, {pool_pages}): a batch or range is unreadable or leaves the pool – the call is ignored")); + } + } + S_OK +} + /// command queue #23 SignalX(fence, value, flush flags): Signal with the console's cache flush /// options – the PC's Signal makes the queue's writes visible itself. (A stub that signalled /// nothing left Fortnite's render fences pending: its render thread waited, textures were @@ -7181,20 +9599,31 @@ 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, slot_of(this, "ExecuteCommandLists"))); - if n == 0 || lists.is_null() { + // Internal XCL submits (`sparse` uploads/readbacks, `title_textures` uploads, tile zeroing) + // run inside `own_work()` — sometimes while holding internal locks (`sparse::STATE`, + // `vram::PAGES`). Forwarding them straight to PC `ExecuteCommandLists` skips + // `present::note_execute` -> `late_release::drain_known` -> `vram::recycle_ready`, preventing + // re-entrant lock self-deadlocks and keeping internal queues out of `present::QUEUES`. + if n == 0 || lists.is_null() || super::title_textures::is_own_work() { f(this, n, lists); stop_if_device_removed(); return; } + super::pcores::pin_current_thread_fast(); + super::gpu_awake::note_activity(); // 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(); + let _prof = super::prof::span(super::prof::Kind::Submit); + // whether these lists need a write-watch look of their own (`title_textures::decide_look`) + super::title_textures::decide_look(std::slice::from_raw_parts(lists, n as usize)); // textures in title memory the CPU wrote since: uploaded again first super::title_textures::refresh(this); // 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); + let record_prof = super::prof::span(super::prof::Kind::SubmitRecord); for &l in std::slice::from_raw_parts(lists, n as usize) { if let Some(pc) = super::console_list::pc_list(l) { mapped.push(pc); @@ -7205,10 +9634,18 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis } } } + drop(record_prof); super::list_x::note_queue_for_lists(this as usize, &mapped); super::list_x::execute_with_waits_on(this, &mapped, |chunk| { - let _ = super::alloc_pool::note_resubmits(this, chunk); + // a list still on the GPU from its previous submit: that one first (the PC does not take + // a list again before then) + if super::alloc_pool::note_resubmits(this, chunk) > 0 { + super::alloc_pool::wait_for_previous_submits(chunk); + } + let driver_prof = super::prof::span(super::prof::Kind::SubmitDriver); f(this, chunk.len() as u32, chunk.as_ptr()); + drop(driver_prof); + let _after = super::prof::span(super::prof::Kind::SubmitAfter); super::list_x::copy_scratch_submitted(this, chunk); super::alloc_pool::executed(this, chunk); super::list_x::signal_write64_fences(this, chunk); @@ -7245,6 +9682,7 @@ pub fn drain_gpu() { Err(e) => { crate::xlog_error!("D3D12 queue drain: {e}"); if matches!(e, FenceError::Removed(_)) { + log_device_removed(); return; } } @@ -7258,6 +9696,9 @@ pub fn drain_gpu() { Ok(value) => pending |= value < 1, Err(e) => { crate::xlog_error!("D3D12 queue drain: {e}"); + if matches!(e, FenceError::Removed(_)) { + log_device_removed(); + } return; } } @@ -7274,6 +9715,49 @@ pub fn drain_gpu() { } } +/// Whether DRED diagnostics were requested via `XCL_DRED=1`. +pub(super) fn dred_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("XCL_DRED").is_some()) +} + +/// Name an `ID3D12Resource` when `XCL_DRED=1` so DRED page-fault output identifies which internal +/// or placed allocation owns the faulting GPU VA. +pub(super) unsafe fn name_resource(res: *mut c_void, label: &str) { + if !dred_on() || res.is_null() { + return; + } + if let Some(r) = ID3D12Resource::from_raw_borrowed(&res) { + let _ = r.SetName(&windows::core::HSTRING::from(label)); + } +} + +/// Name an `ID3D12Heap` when `XCL_DRED=1` so DRED page-fault output identifies backing pool heaps. +pub(super) unsafe fn name_heap(heap: *mut c_void, label: &str) { + if !dred_on() || heap.is_null() { + return; + } + if let Some(h) = ID3D12Heap::from_raw_borrowed(&heap) { + let _ = h.SetName(&windows::core::HSTRING::from(label)); + } +} + +/// Read a DRED allocation node's debug name, preferring `ObjectNameW` (populated by +/// `ID3D12Object::SetName`) and falling back to `ObjectNameA`. +unsafe fn format_dred_allocation_name(name_w: windows::core::PCWSTR, name_a: *const u8) -> String { + if !name_w.is_null() { + if let Ok(s) = name_w.to_string() { + if !s.is_empty() { + return s; + } + } + } + if !name_a.is_null() { + return std::ffi::CStr::from_ptr(name_a as *const std::ffi::c_char).to_string_lossy().into_owned(); + } + String::new() +} + /// DRED gives us a linked list in driver order. Keep the diagnostic bounded even on a /// long chain, with room in the log for work that the GPU had already started. unsafe fn report_dred_lists(head: *const D3D12_AUTO_BREADCRUMB_NODE, mut report: impl FnMut(&D3D12_AUTO_BREADCRUMB_NODE, usize)) { @@ -7317,6 +9801,19 @@ mod dred_tests { assert_eq!((node, done), (std::ptr::from_ref(&nodes[i]), 0)); } } + + #[test] + fn format_dred_allocation_name_prefers_wide_and_falls_back_to_ansi() { + let wide: Vec = "wide_name".encode_utf16().chain([0]).collect(); + let empty_wide: [u16; 1] = [0]; + let ansi = b"ansi_name\0"; + unsafe { + assert_eq!(format_dred_allocation_name(windows::core::PCWSTR(wide.as_ptr()), ansi.as_ptr()), "wide_name"); + assert_eq!(format_dred_allocation_name(windows::core::PCWSTR::null(), ansi.as_ptr()), "ansi_name"); + assert_eq!(format_dred_allocation_name(windows::core::PCWSTR(empty_wide.as_ptr()), ansi.as_ptr()), "ansi_name"); + assert_eq!(format_dred_allocation_name(windows::core::PCWSTR::null(), std::ptr::null()), ""); + } + } } /// If the device was removed: the reason, DRED's page fault (address, the allocations around @@ -7330,22 +9827,47 @@ pub fn log_device_removed() { return; } crate::xlog_error!("D3D12 device removed: {:#x} {}", e.code().0 as u32, e.message()); + // which of XCL's queues stopped first, and what went before (`flight`) + super::flight::dump("device removed"); + super::culprit::on_device_removed(); unsafe { + let mut pf_logged = false; + if let Ok(dred1) = dev.cast::() { + if let Ok(pf) = dred1.GetPageFaultAllocationOutput1() { + let names = |mut n: *const D3D12_DRED_ALLOCATION_NODE1| { + let mut v = Vec::new(); + while !n.is_null() && v.len() < 8 { + let a = &*n; + let name = format_dred_allocation_name(a.ObjectNameW, a.ObjectNameA); + let ptr = (&*a.pObject).as_ref().map(|obj| format!(" ptr={:#x}", obj.as_raw() as usize)).unwrap_or_default(); + v.push(format!("type {} {}{}", a.AllocationType.0, name, ptr)); + n = a.pNext; + } + 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(); + crate::xlog_error!("DRED page fault at GPU VA {va:#x}{window}; allocations there: [{}]; recently freed: [{}]", names(pf.pHeadExistingAllocationNode), names(pf.pHeadRecentFreedAllocationNode)); + pf_logged = true; + } + } let Ok(dred) = dev.cast::() else { return }; - if let Ok(pf) = dred.GetPageFaultAllocationOutput() { - let names = |mut n: *const D3D12_DRED_ALLOCATION_NODE| { - let mut v = Vec::new(); - while !n.is_null() && v.len() < 8 { - let a = &*n; - let name = if a.ObjectNameA.is_null() { String::new() } else { std::ffi::CStr::from_ptr(a.ObjectNameA as *const std::ffi::c_char).to_string_lossy().into_owned() }; - v.push(format!("type {} {}", a.AllocationType.0, name)); - n = a.pNext; - } - 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(); - crate::xlog_error!("DRED page fault at GPU VA {va:#x}{window}; allocations there: [{}]; recently freed: [{}]", names(pf.pHeadExistingAllocationNode), names(pf.pHeadRecentFreedAllocationNode)); + if !pf_logged { + if let Ok(pf) = dred.GetPageFaultAllocationOutput() { + let names = |mut n: *const D3D12_DRED_ALLOCATION_NODE| { + let mut v = Vec::new(); + while !n.is_null() && v.len() < 8 { + let a = &*n; + let name = format_dred_allocation_name(a.ObjectNameW, a.ObjectNameA); + v.push(format!("type {} {}", a.AllocationType.0, name)); + n = a.pNext; + } + 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(); + crate::xlog_error!("DRED page fault at GPU VA {va:#x}{window}; allocations there: [{}]; recently freed: [{}]", names(pf.pHeadExistingAllocationNode), names(pf.pHeadRecentFreedAllocationNode)); + } } if let Ok(bc) = dred.GetAutoBreadcrumbsOutput() { report_dred_lists(bc.pHeadAutoBreadcrumbNode, |node, done| { @@ -7507,7 +10029,7 @@ mod this_first_tests { let pc = [0usize; 32]; let ext = [pc.as_ptr() as usize, 0]; let vtbl = ext.as_ptr() as usize + 8; - EXTS.lock().unwrap().get_or_insert_with(HashSet::new).insert(vtbl); + EXTS.write().unwrap().get_or_insert_with(HashSet::new).insert(vtbl); let plain = 0x1234_5678usize; let p = &plain as *const usize as *mut c_void; // an object off the stack (as a real device is), and a stack buffer holding a stale copy @@ -7535,7 +10057,7 @@ mod this_first_tests { assert!(this_first(b, s) && this_first(s, b)); drop(Box::from_raw(obj as *mut [usize; 1])); } - if let Some(g) = EXTS.lock().unwrap().as_mut() { + if let Some(g) = EXTS.write().unwrap().as_mut() { g.remove(&vtbl); } } @@ -7870,6 +10392,76 @@ mod queue_tests { assert!(NEWER_LIST_SLOTS.contains(&(129, 127)), "DispatchMesh must map to newer slot #129"); assert!(!NEWER_LIST_SLOTS.iter().any(|&(newer, _)| newer == 128), "newer slot #128 must not map to DispatchMesh"); } + + #[test] + fn own_work_execute_command_lists_bypasses_note_execute_and_drain() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + static CALLED: AtomicUsize = AtomicUsize::new(0); + unsafe extern "system" fn fake_qi(_this: *mut c_void, _iid: *const GUID, out: *mut *mut c_void) -> HRESULT { + if !out.is_null() { + *out = std::ptr::null_mut(); + } + -2147467262 // E_NOINTERFACE + } + unsafe extern "system" fn fake_ref(_this: *mut c_void) -> u32 { 1 } + unsafe extern "system" fn fake_noop(_this: *mut c_void) {} + unsafe extern "system" fn fake_execute(_this: *mut c_void, n: u32, _lists: *const *mut c_void) { + CALLED.fetch_add(n as usize, Ordering::SeqCst); + } + + let iface = layout::find("ID3D12CommandQueue").expect("ID3D12CommandQueue layout"); + let exec_slot = layout::slot(iface, "ExecuteCommandLists").expect("ExecuteCommandLists slot"); + let n = iface.methods.len(); + let mut fake_vtbl = vec![fake_noop as usize; n + 1]; + fake_vtbl[0] = fake_qi as usize; + fake_vtbl[1] = fake_ref as usize; + fake_vtbl[2] = fake_ref as usize; + fake_vtbl[exec_slot] = fake_execute as usize; + fake_vtbl[n] = 0; + let orig = fake_vtbl.as_ptr() as usize; + + struct ClassCleanup(usize); + impl Drop for ClassCleanup { + fn drop(&mut self) { + let mut exts = Vec::new(); + CLASSES.write().unwrap().retain(|c| { + if c.orig == self.0 { + exts.push(c.ext); + false + } else { + true + } + }); + if let Some(set) = EXTS.write().unwrap().as_mut() { + for e in exts { + set.remove(&e); + } + } + } + } + let _cleanup = ClassCleanup(orig); + + let mut obj = orig; + let obj_ptr = &mut obj as *mut usize as *mut c_void; + let ext = unsafe { class_for(obj_ptr, orig, Kind::CommandQueue) }; + unsafe { *(obj_ptr as *mut usize) = ext; } + + let mut dummy_list = std::ptr::null_mut::(); + let queues_before = crate::hle::d3d12x::present::known_queues(); + let before_called = CALLED.load(Ordering::SeqCst); + unsafe { + crate::hle::d3d12x::title_textures::own_work(|| { + q_execute_command_lists(obj_ptr, 1, &mut dummy_list as *mut *mut c_void); + }); + } + assert_eq!(CALLED.load(Ordering::SeqCst), before_called + 1, "original ExecuteCommandLists must still run"); + assert!( + !crate::hle::d3d12x::present::known_queues().contains(&(obj_ptr as usize)), + "own_work submit must not register queue in present::QUEUES" + ); + assert_eq!(crate::hle::d3d12x::present::known_queues().len(), queues_before.len()); + } } #[cfg(test)] @@ -8157,9 +10749,9 @@ mod map_tests { // is not taken for it (its description differs) let upload = buffer(heap(D3D12_HEAP_TYPE_UPLOAD), D3D12_RESOURCE_STATE_GENERIC_READ); let stale = desc_of(r.as_raw()).unwrap(); - RESERVED.lock().unwrap().as_mut().unwrap().insert(upload.as_raw() as usize, stale); + RESERVED.write().unwrap().as_mut().unwrap().insert(upload.as_raw() as usize, stale); assert!(!is_reserved(upload.as_raw()) && mappable(&upload)); - let mut g = RESERVED.lock().unwrap(); + let mut g = RESERVED.write().unwrap(); let m = g.as_mut().unwrap(); m.remove(&(raw as usize)); m.remove(&(upload.as_raw() as usize)); @@ -8282,7 +10874,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[..]); 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); @@ -8291,12 +10883,16 @@ mod mesh_stream_tests { } } + /// calls of `fake_create_pso_null_ok` + static FAKE_PSO_CALLS: AtomicU64 = AtomicU64::new(0); + unsafe extern "system" fn fake_create_pso_null_ok( _: *mut c_void, _: *const c_void, _: *const GUID, ppv: *mut *mut c_void, ) -> HRESULT { + FAKE_PSO_CALLS.fetch_add(1, Ordering::SeqCst); if !ppv.is_null() { *ppv = std::ptr::null_mut(); } @@ -8336,27 +10932,28 @@ mod mesh_stream_tests { } impl Drop for Cleanup { fn drop(&mut self) { - CLASSES.lock().unwrap().retain(|c| c.ext != self.ext); - if let Some(m) = ABI_RS_SAMPLERS.lock().unwrap().as_mut() { + CLASSES.write().unwrap().retain(|c| c.ext != self.ext); + if let Some(m) = ABI_RS_SAMPLERS.write().unwrap().as_mut() { m.remove(&self.key); } } } - CLASSES.lock().unwrap().push(Class { + CLASSES.write().unwrap().push(Class { orig: pc.as_ptr() as usize, kind: Kind::Device, ext: ext_vtbl, iface, public: iface.methods.len(), scanned: iface.methods.len(), + copied: None, }); - ABI_RS_SAMPLERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(key.clone(), 0x1234_5678); + ABI_RS_SAMPLERS.write().unwrap().get_or_insert_with(HashMap::new).insert(key.clone(), 0x1234_5678); let _cleanup = Cleanup { ext: ext_vtbl, key }; let make_tp = || crate::gpu::recomp::pso::TwoPass { - cs: vec![0; 16], + cs: vec![0; 16].into(), 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], }; @@ -8366,13 +10963,22 @@ mod mesh_stream_tests { unsafe { // Case 1: driver returns S_OK but leaves *ppv == null let mut out: *mut c_void = std::ptr::null_mut(); - let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, "MS", &iid, &mut out); + let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, "MS", &[], &iid, &mut out); assert_eq!(hr, E_INVALIDARG); assert!(out.is_null()); // Case 2: caller passes ppv == null - let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, "MS", &iid, std::ptr::null_mut()); + let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, "MS", &[], &iid, std::ptr::null_mut()); assert_eq!(hr, E_INVALIDARG); + + // Case 3: the driver crashed on this pipeline in an earlier run – it is not given to it + let calls = FAKE_PSO_CALLS.load(Ordering::SeqCst); + assert!(calls >= 2, "the driver was asked in cases 1 and 2"); + super::super::driver_crash::block(&pso_lib::stream_key(&stream.0, 0x1234_5678, stream.shader_bytes())); + let mut out: *mut c_void = std::ptr::null_mut(); + let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, "MS", &[], &iid, &mut out); + assert_eq!(hr, E_INVALIDARG); + assert_eq!(FAKE_PSO_CALLS.load(Ordering::SeqCst), calls, "a pipeline of driver-crashes.txt reached the driver"); } } } @@ -8903,5 +11509,1145 @@ void main() { ); } } + + #[test] + fn uav_companion_srv_msaa_typeless_and_null_uav_dimensions() { + use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM, + DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_TYPELESS, + DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_UNKNOWN, + }; + + let msaa_tex = |slices: u16, fmt: DXGI_FORMAT| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 32, + Height: 32, + DepthOrArraySize: slices, + MipLevels: 1, + Format: fmt, + SampleDesc: DXGI_SAMPLE_DESC { Count: 4, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + + // MSAA 2D texture -> TEXTURE2DMS (both default desc and explicit Texture2D UAV desc) + let ms2d = msaa_tex(1, DXGI_FORMAT_R8G8B8A8_UNORM); + let srv_ms2d_def = uav_companion_srv(Some(&ms2d), None, false).expect("MSAA 2D default companion SRV"); + assert_eq!((srv_ms2d_def.ViewDimension, srv_ms2d_def.Format), (D3D12_SRV_DIMENSION_TEXTURE2DMS, DXGI_FORMAT_R8G8B8A8_UNORM)); + let u2d = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let srv_ms2d = uav_companion_srv(Some(&ms2d), Some(&u2d), false).expect("MSAA 2D companion SRV"); + assert_eq!((srv_ms2d.ViewDimension, srv_ms2d.Format), (D3D12_SRV_DIMENSION_TEXTURE2DMS, DXGI_FORMAT_R8G8B8A8_UNORM)); + + // MSAA 2DArray texture -> TEXTURE2DMSARRAY with resolved slice range + let ms2da = msaa_tex(4, DXGI_FORMAT_R16G16B16A16_FLOAT); + let u2da = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_UAV { MipSlice: 0, FirstArraySlice: 1, ArraySize: u32::MAX, PlaneSlice: 0 }, + }, + }; + let srv_ms2da = uav_companion_srv(Some(&ms2da), Some(&u2da), false).expect("MSAA 2DArray companion SRV"); + assert_eq!((srv_ms2da.ViewDimension, srv_ms2da.Format), (D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY, DXGI_FORMAT_R16G16B16A16_FLOAT)); + assert_eq!(unsafe { (srv_ms2da.Anonymous.Texture2DMSArray.FirstArraySlice, srv_ms2da.Anonymous.Texture2DMSArray.ArraySize) }, (1, 3)); + + // Non-depth *_TYPELESS resources with desc == None / Format == UNKNOWN resolve to concrete same-family formats + for (typeless, want) in [ + (DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM), + (DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_FLOAT), + (DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_UNORM), + (DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM), + ] { + let rd = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 1, 1, typeless, D3D12_RESOURCE_FLAG_NONE); + let s_def = uav_companion_srv(Some(&rd), None, false).expect("typeless default SRV"); + assert_eq!(s_def.Format, want, "default SRV for {typeless:?}"); + let u_unk = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let s_unk = uav_companion_srv(Some(&rd), Some(&u_unk), false).expect("typeless UNKNOWN-format SRV"); + assert_eq!(s_unk.Format, want, "UNKNOWN-format SRV for {typeless:?}"); + } + + // Null-resource companion SRV never emits a typeless or depth format + let u_null_typeless = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + assert_eq!(uav_companion_srv(None, Some(&u_null_typeless), true).unwrap().Format, DXGI_FORMAT_R8G8B8A8_UNORM); + let u_null_depth = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_D32_FLOAT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + assert_eq!(uav_companion_srv(None, Some(&u_null_depth), true).unwrap().Format, DXGI_FORMAT_R32_FLOAT); + + // null_uav_desc sets valid non-zero ArraySize / WSize and falls back to rd when ViewDimension == UNKNOWN + let rd1da = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE1D, 16, 1, 3, 1, DXGI_FORMAT_R8G8B8A8_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + let rd2da = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 3, 1, DXGI_FORMAT_R8G8B8A8_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + let rd3d = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE3D, 8, 8, 4, 1, DXGI_FORMAT_R8G8B8A8_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + let n1da = null_uav_desc(None, Some(&rd1da)); + let n2da = null_uav_desc(None, Some(&rd2da)); + let n3d = null_uav_desc(None, Some(&rd3d)); + assert_eq!((n1da.ViewDimension, unsafe { n1da.Anonymous.Texture1DArray.ArraySize }), (D3D12_UAV_DIMENSION_TEXTURE1DARRAY, 1)); + assert_eq!((n2da.ViewDimension, unsafe { n2da.Anonymous.Texture2DArray.ArraySize }), (D3D12_UAV_DIMENSION_TEXTURE2DARRAY, 1)); + assert_eq!((n3d.ViewDimension, unsafe { n3d.Anonymous.Texture3D.WSize }), (D3D12_UAV_DIMENSION_TEXTURE3D, 1)); + let unk_dim = D3D12_UNORDERED_ACCESS_VIEW_DESC::default(); + let n_unk = null_uav_desc(Some(&unk_dim), Some(&rd3d)); + assert_eq!((n_unk.ViewDimension, unsafe { n_unk.Anonymous.Texture3D.WSize }), (D3D12_UAV_DIMENSION_TEXTURE3D, 1)); + } + + /// D3D12 debug layer: verify `dev_create_uav_checked_x` null UAV fallback on Texture1DArray / + /// Texture2DArray / Texture3D and `dev_create_uav_x` companion SRVs on MSAA and non-depth + /// `*_TYPELESS` textures produce zero D3D12 validation errors (#2461). + #[test] + fn gpu_uav_null_fallback_and_msaa_typeless_companion_srv_debug_layer() { + const CHILD: &str = "XCL_TEST_UAV_DEBUG_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::real::uav_companion_srv_tests::gpu_uav_null_fallback_and_msaa_typeless_companion_srv_debug_layer", "--nocapture"]) + .env(CHILD, "1") + .env("XCL_UMA_MB", "64") + .env("XCL_COHERENT_MB", "64") + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + for line in stderr.lines().filter(|l| l.starts_with("SKIPPED ")) { + eprintln!("{line}"); + } + assert!( + output.status.success(), + "child failed ({:?}):\nstdout:\n{}\nstderr:\n{}", + output.status, + String::from_utf8_lossy(&output.stdout), + stderr + ); + return; + } + + unsafe { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_UNKNOWN, + }; + + match crate::gpu::agility::configuration_interface::(&CLSID_D3D12Debug) { + Ok(d) => d.EnableDebugLayer(), + Err(e) => { + crate::gpu::recomp::runner::skip_test(&format!("no D3D12 debug layer ({e})")); + return; + } + } + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Ok(iq) = dev.cast::() else { + crate::gpu::recomp::runner::skip_test("device has no D3D12InfoQueue"); + return; + }; + let take_errors = |q: &ID3D12InfoQueue| -> Vec { + let mut out = Vec::new(); + for i in 0..q.GetNumStoredMessages() { + let mut len = 0usize; + if q.GetMessage(i, None, &mut len).is_err() || len == 0 { + continue; + } + let mut buf = vec![0u64; len.div_ceil(8)]; + let m = buf.as_mut_ptr() as *mut D3D12_MESSAGE; + if q.GetMessage(i, Some(m), &mut len).is_ok() + && matches!((*m).Severity, D3D12_MESSAGE_SEVERITY_ERROR | D3D12_MESSAGE_SEVERITY_CORRUPTION) + { + let d = std::slice::from_raw_parts((*m).pDescription as *const u8, (*m).DescriptionByteLength.saturating_sub(1)); + out.push(String::from_utf8_lossy(d).into_owned()); + } + } + q.ClearStoredMessages(); + out + }; + + assert!(crate::gpu::uma::get().is_some(), "UMA init failed in test subprocess"); + adopt(dev.as_raw(), Kind::Device); + + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + let heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 32, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }) + .expect("CPU descriptor heap"); + let heap_key = heap.as_raw() as usize; + assert!(super::super::console_heap::register( + heap_key, + 16, + heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, + 0, + inc, + false, + false, + false, + )); + let base_cpu = super::super::console_heap::start(heap_key).expect("console heap start"); + let slot_cpu = |k: u64| base_cpu + k * super::super::console_heap::SLOT as u64; + + let default_heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let make_tex = |desc: &D3D12_RESOURCE_DESC| -> ID3D12Resource { + let mut r: Option = None; + dev.CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r) + .expect("CreateCommittedResource"); + r.unwrap() + }; + + let uav_flag = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + let t1da_typeless = make_tex(&tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE1D, 16, 1, 3, 1, DXGI_FORMAT_R8G8B8A8_TYPELESS, uav_flag)); + let t2da_typeless = make_tex(&tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 3, 1, DXGI_FORMAT_R8G8B8A8_TYPELESS, uav_flag)); + let t3d_typeless = make_tex(&tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE3D, 8, 8, 4, 1, DXGI_FORMAT_R8G8B8A8_TYPELESS, uav_flag)); + let t2d_typeless_nouav = make_tex(&tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 1, 1, DXGI_FORMAT_R8G8B8A8_TYPELESS, D3D12_RESOURCE_FLAG_NONE)); + let msaa_desc = |slices: u16, fmt: DXGI_FORMAT| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 16, + Height: 16, + DepthOrArraySize: slices, + MipLevels: 1, + Format: fmt, + SampleDesc: DXGI_SAMPLE_DESC { Count: 4, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let ms2d = make_tex(&msaa_desc(1, DXGI_FORMAT_R8G8B8A8_UNORM)); + let ms2da = make_tex(&msaa_desc(3, DXGI_FORMAT_R16G16B16A16_FLOAT)); + + iq.ClearStoredMessages(); + + // 1. `dev_create_uav_checked_x` unsupported typed UAV fallback on 1DArray, 2DArray, 3D + dev_create_uav_checked_x(dev.as_raw(), t1da_typeless.as_raw(), std::ptr::null_mut(), std::ptr::null(), slot_cpu(0)); + dev_create_uav_checked_x(dev.as_raw(), t2da_typeless.as_raw(), std::ptr::null_mut(), std::ptr::null(), slot_cpu(1)); + dev_create_uav_checked_x(dev.as_raw(), t3d_typeless.as_raw(), std::ptr::null_mut(), std::ptr::null(), slot_cpu(2)); + let errs1 = take_errors(&iq); + assert!(errs1.is_empty(), "dev_create_uav_checked_x null UAV fallback debug errors: {errs1:#?}"); + + // 2. `dev_create_uav_x` companion SRV on MSAA 2D and MSAA 2DArray (no ALLOW_UNORDERED_ACCESS) + dev_create_uav_x(dev.as_raw(), ms2d.as_raw(), std::ptr::null_mut(), std::ptr::null(), slot_cpu(3)); + let u_ms2da = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_UAV { MipSlice: 0, FirstArraySlice: 1, ArraySize: u32::MAX, PlaneSlice: 0 }, + }, + }; + dev_create_uav_x(dev.as_raw(), ms2da.as_raw(), std::ptr::null_mut(), &u_ms2da, slot_cpu(4)); + let errs2 = take_errors(&iq); + assert!(errs2.is_empty(), "MSAA companion SRV debug errors: {errs2:#?}"); + + // 3. `dev_create_uav_x` companion SRV on non-depth *_TYPELESS texture with desc == NULL and Format == UNKNOWN + dev_create_uav_x(dev.as_raw(), t2d_typeless_nouav.as_raw(), std::ptr::null_mut(), std::ptr::null(), slot_cpu(5)); + let u_unk = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + dev_create_uav_x(dev.as_raw(), t2d_typeless_nouav.as_raw(), std::ptr::null_mut(), &u_unk, slot_cpu(6)); + let errs3 = take_errors(&iq); + assert!(errs3.is_empty(), "typeless companion SRV debug errors: {errs3:#?}"); + + super::super::console_heap::unregister(heap_key); + } + } +} + + +/// Flush any newly compiled pipelines in the memory-mapped `ID3D12PipelineLibrary1` to a fresh +/// generational `.plib` file (called on clean shutdown; never truncates the open mapping). +pub fn flush_pipeline_library() { + pso_lib::flush_now(); +} + +/// Deterministic cross-run `.plib` key for a translated compute pipeline (`c-...` for standard +/// 6-parameter ABI root signatures, `sc-...` for 8-parameter `dispatch_chain` root signatures), +/// shared between runtime PSO creation and offline `xcl shaders --precompile --pipelines`. +pub(crate) fn compute_library_key( + dxil: &[u8], + samplers: &[crate::gpu::recomp::pso::StaticSampler], + flags: i32, + chained: bool, +) -> String { + let key = pso_lib::compute_key(dxil, samplers, flags); + if chained { format!("s{key}") } else { key } +} + +/// 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; + #[cfg(test)] + use crate::hle::d3d12x::pso_library::should_background_save; + use std::sync::Arc; + + struct LibState { + device: usize, + lib: Option>, + stored_keys: HashSet, + hits: u64, + stores: u64, + } + + static LIB_STATE: Mutex> = Mutex::new(None); + + unsafe fn library_for(device: *mut c_void) -> Option> { + if cfg!(test) || 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, + }); + 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 { + unsafe { + let _ = lib.flush(); + } + } + } + + 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 + } + + fn abi_rs_samplers_digest(rs: usize) -> u64 { + let g = ABI_RS_SAMPLERS.read().unwrap(); + let Some(map) = g.as_ref() else { + return 0; + }; + let Some((words, _)) = map.iter().find(|(_, &v)| v == rs) else { + return 0; + }; + let mut h = 0xcbf2_9ce4_8422_2325u64; + fnv_feed(&mut h, &(words.len() as u64).to_le_bytes()); + for &w in words { + fnv_feed(&mut h, &w.to_le_bytes()); + } + h + } + + /// Deterministic cross-run key for a translated compute pipeline. + pub(super) fn compute_key(dxil: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], flags: i32) -> String { + format!( + "c-{:016x}-{:x}-{:016x}-{:x}", + crate::gpu::shader::fnv64(dxil), + dxil.len(), + samplers_digest(samplers), + flags as u32 + ) + } + + /// Deterministic cross-run key for a sanitized translated graphics pipeline (depends on effective + /// blend/rasterizer/depth-stencil state, input layout semantics, formats, shaders, and samplers). + pub(super) unsafe fn graphics_key( + copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + vs_dxil: &[u8], + ps_dxil: Option<&[u8]>, + rect_gs: Option<&[u8]>, + samplers: &[crate::gpu::recomp::pso::StaticSampler], + ) -> String { + let mut h = 0xcbf2_9ce4_8422_2325u64; + let feed_u32 = |h: &mut u64, v: u32| fnv_feed(h, &v.to_le_bytes()); + let feed_u64 = |h: &mut u64, v: u64| fnv_feed(h, &v.to_le_bytes()); + let feed_slice = |h: &mut u64, s: Option<&[u8]>| match s { + Some(b) => { + feed_u64(h, crate::gpu::shader::fnv64(b)); + feed_u64(h, b.len() as u64); + } + None => feed_u64(h, 0), + }; + feed_slice(&mut h, Some(vs_dxil)); + feed_slice(&mut h, ps_dxil); + feed_slice(&mut h, rect_gs); + feed_u64(&mut h, samplers_digest(samplers)); + + // Sanitized BlendState (effective integer-RT BlendEnable/LogicOpEnable already applied) + feed_u32(&mut h, copy.BlendState.AlphaToCoverageEnable.0 as u32); + feed_u32(&mut h, copy.BlendState.IndependentBlendEnable.0 as u32); + for rt in ©.BlendState.RenderTarget { + feed_u32(&mut h, rt.BlendEnable.0 as u32); + feed_u32(&mut h, rt.LogicOpEnable.0 as u32); + feed_u32(&mut h, rt.SrcBlend.0 as u32); + feed_u32(&mut h, rt.DestBlend.0 as u32); + feed_u32(&mut h, rt.BlendOp.0 as u32); + feed_u32(&mut h, rt.SrcBlendAlpha.0 as u32); + feed_u32(&mut h, rt.DestBlendAlpha.0 as u32); + feed_u32(&mut h, rt.BlendOpAlpha.0 as u32); + feed_u32(&mut h, rt.LogicOp.0 as u32); + fnv_feed(&mut h, &[rt.RenderTargetWriteMask]); + } + feed_u32(&mut h, copy.SampleMask); + + // RasterizerState + let r = ©.RasterizerState; + feed_u32(&mut h, r.FillMode.0 as u32); + feed_u32(&mut h, r.CullMode.0 as u32); + feed_u32(&mut h, r.FrontCounterClockwise.0 as u32); + feed_u32(&mut h, r.DepthBias as u32); + feed_u32(&mut h, r.DepthBiasClamp.to_bits()); + feed_u32(&mut h, r.SlopeScaledDepthBias.to_bits()); + feed_u32(&mut h, r.DepthClipEnable.0 as u32); + feed_u32(&mut h, r.MultisampleEnable.0 as u32); + feed_u32(&mut h, r.AntialiasedLineEnable.0 as u32); + feed_u32(&mut h, r.ForcedSampleCount); + feed_u32(&mut h, r.ConservativeRaster.0 as u32); + + // DepthStencilState + let ds = ©.DepthStencilState; + feed_u32(&mut h, ds.DepthEnable.0 as u32); + feed_u32(&mut h, ds.DepthWriteMask.0 as u32); + feed_u32(&mut h, ds.DepthFunc.0 as u32); + feed_u32(&mut h, ds.StencilEnable.0 as u32); + fnv_feed(&mut h, &[ds.StencilReadMask, ds.StencilWriteMask]); + for face in [&ds.FrontFace, &ds.BackFace] { + feed_u32(&mut h, face.StencilFailOp.0 as u32); + feed_u32(&mut h, face.StencilDepthFailOp.0 as u32); + feed_u32(&mut h, face.StencilPassOp.0 as u32); + feed_u32(&mut h, face.StencilFunc.0 as u32); + } + + // InputLayout + let il = ©.InputLayout; + feed_u32(&mut h, il.NumElements); + if il.NumElements > 0 && !il.pInputElementDescs.is_null() { + for e in std::slice::from_raw_parts(il.pInputElementDescs, il.NumElements as usize) { + if !e.SemanticName.0.is_null() { + let s = std::ffi::CStr::from_ptr(e.SemanticName.0 as *const std::ffi::c_char); + fnv_feed(&mut h, s.to_bytes_with_nul()); + } else { + fnv_feed(&mut h, &[0]); + } + feed_u32(&mut h, e.SemanticIndex); + feed_u32(&mut h, e.Format.0 as u32); + feed_u32(&mut h, e.InputSlot); + feed_u32(&mut h, e.AlignedByteOffset); + feed_u32(&mut h, e.InputSlotClass.0 as u32); + feed_u32(&mut h, e.InstanceDataStepRate); + } + } + + feed_u32(&mut h, copy.IBStripCutValue.0 as u32); + feed_u32(&mut h, copy.PrimitiveTopologyType.0 as u32); + feed_u32(&mut h, copy.NumRenderTargets); + for f in ©.RTVFormats { + feed_u32(&mut h, f.0 as u32); + } + feed_u32(&mut h, copy.DSVFormat.0 as u32); + feed_u32(&mut h, copy.SampleDesc.Count); + feed_u32(&mut h, copy.SampleDesc.Quality); + feed_u32(&mut h, copy.NodeMask); + feed_u32(&mut h, copy.Flags.0 as u32); + + let total = vs_dxil.len() + ps_dxil.map_or(0, <[u8]>::len) + rect_gs.map_or(0, <[u8]>::len); + format!("g-{h:016x}-{total:x}") + } + + /// Deterministic cross-run key for a translated mesh/GS pipeline state stream: hashes shader + /// bytecodes by content, root signature by static-sampler digest, and pointer-bearing subobjects + /// (`INPUT_LAYOUT`, `STREAM_OUTPUT`, `VIEW_INSTANCING`) by pointed-to content (never raw pointers). + pub(super) unsafe fn stream_key(stream_bytes: &[u8], mesh_rs: usize, shader_bytes: usize) -> String { + let mut h = 0xcbf2_9ce4_8422_2325u64; + fnv_feed(&mut h, &abi_rs_samplers_digest(mesh_rs).to_le_bytes()); + if let Some(subs) = stream_subobjects(stream_bytes) { + for (ty, payload) in subs { + fnv_feed(&mut h, &ty.to_le_bytes()); + if ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE.0 as u32 + || ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO.0 as u32 + { + continue; + } + if SHADER_SUBOBJECTS.iter().any(|t| t.0 as u32 == ty) { + if let Some(code) = payload_shader(payload) { + fnv_feed(&mut h, &crate::gpu::shader::fnv64(code).to_le_bytes()); + fnv_feed(&mut h, &(code.len() as u64).to_le_bytes()); + } else { + fnv_feed(&mut h, &0u64.to_le_bytes()); + } + continue; + } + if ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0 as u32 + && payload.len() >= std::mem::size_of::() + { + let il = std::ptr::read_unaligned(payload.as_ptr() as *const D3D12_INPUT_LAYOUT_DESC); + fnv_feed(&mut h, &il.NumElements.to_le_bytes()); + if il.NumElements > 0 && !il.pInputElementDescs.is_null() { + for e in std::slice::from_raw_parts(il.pInputElementDescs, il.NumElements as usize) { + if !e.SemanticName.0.is_null() { + fnv_feed(&mut h, std::ffi::CStr::from_ptr(e.SemanticName.0 as *const i8).to_bytes()); + } + fnv_feed(&mut h, &[0u8]); + fnv_feed(&mut h, &e.SemanticIndex.to_le_bytes()); + fnv_feed(&mut h, &e.Format.0.to_le_bytes()); + fnv_feed(&mut h, &e.InputSlot.to_le_bytes()); + fnv_feed(&mut h, &e.AlignedByteOffset.to_le_bytes()); + fnv_feed(&mut h, &e.InputSlotClass.0.to_le_bytes()); + fnv_feed(&mut h, &e.InstanceDataStepRate.to_le_bytes()); + } + } + continue; + } + if ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT.0 as u32 + && payload.len() >= std::mem::size_of::() + { + let so = std::ptr::read_unaligned(payload.as_ptr() as *const D3D12_STREAM_OUTPUT_DESC); + fnv_feed(&mut h, &so.NumEntries.to_le_bytes()); + fnv_feed(&mut h, &so.NumStrides.to_le_bytes()); + fnv_feed(&mut h, &so.RasterizedStream.to_le_bytes()); + if so.NumEntries > 0 && !so.pSODeclaration.is_null() { + for d in std::slice::from_raw_parts(so.pSODeclaration, so.NumEntries as usize) { + fnv_feed(&mut h, &d.Stream.to_le_bytes()); + if !d.SemanticName.0.is_null() { + fnv_feed(&mut h, std::ffi::CStr::from_ptr(d.SemanticName.0 as *const i8).to_bytes()); + } + fnv_feed(&mut h, &[0u8, d.StartComponent, d.ComponentCount, d.OutputSlot]); + fnv_feed(&mut h, &d.SemanticIndex.to_le_bytes()); + } + } + if so.NumStrides > 0 && !so.pBufferStrides.is_null() { + for &s in std::slice::from_raw_parts(so.pBufferStrides, so.NumStrides as usize) { + fnv_feed(&mut h, &s.to_le_bytes()); + } + } + continue; + } + if ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING.0 as u32 + && payload.len() >= std::mem::size_of::() + { + let vi = std::ptr::read_unaligned(payload.as_ptr() as *const D3D12_VIEW_INSTANCING_DESC); + fnv_feed(&mut h, &vi.ViewInstanceCount.to_le_bytes()); + fnv_feed(&mut h, &vi.Flags.0.to_le_bytes()); + if vi.ViewInstanceCount > 0 && !vi.pViewInstanceLocations.is_null() { + for l in std::slice::from_raw_parts(vi.pViewInstanceLocations, vi.ViewInstanceCount as usize) { + fnv_feed(&mut h, &l.ViewportArrayIndex.to_le_bytes()); + fnv_feed(&mut h, &l.RenderTargetArrayIndex.to_le_bytes()); + } + } + continue; + } + fnv_feed(&mut h, payload); + } + } + format!("s-{h:016x}-{shader_bytes:x}") + } + + unsafe fn deliver_adopted(pso: ID3D12PipelineState, _riid: *const GUID, ppv: *mut *mut c_void) -> bool { + if ppv.is_null() { + return false; + } + // `pso` is already an `ID3D12PipelineState` matching `pc_iid(Kind::PipelineState)`; do not + // pass console IIDs through PC COM `QueryInterface`. + let out = pso.into_raw(); + adopt(out, Kind::PipelineState); + *ppv = out; + true + } + + fn note_hit() { + if let Some(s) = LIB_STATE.lock().unwrap().as_mut() { + s.hits += 1; + if s.hits == 1 || s.hits % 500 == 0 { + crate::xlog_info!("D3D12.X: memory-mapped pipeline library hits: {}", s.hits); + } + } + } + + 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 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 deliver_adopted(pso, riid, ppv) { + note_hit(); + 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 cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + cdesc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); + cdesc.CS = bytecode(cs); + let pso = lib.load_compute(key, &cdesc)?; + note_hit(); + 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 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 deliver_adopted(pso, riid, ppv) { + note_hit(); + 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 ppv.is_null() || stream_bytes.is_empty() { + return false; + } + let Some(lib) = library_for(device) else { return false }; + let sdesc = 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, &sdesc) else { return false }; + if deliver_adopted(pso, riid, ppv) { + note_hit(); + true + } else { + false + } + } + + pub(super) unsafe fn store_pipeline(device: *mut c_void, key: &str, pso_raw: *mut c_void) { + if pso_raw.is_null() { + return; + } + let Some(lib) = library_for(device) else { return }; + { + let mut g = LIB_STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if !s.stored_keys.insert(key.to_string()) { + return; + } + } + let Some(pso) = ID3D12PipelineState::from_raw_borrowed(&pso_raw) else { return }; + if lib.store(key, pso) { + if let Some(s) = LIB_STATE.lock().unwrap().as_mut() { + s.stores += 1; + } + } + } + + #[cfg(test)] + mod tests { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::*; + + #[test] + fn pipeline_library_keys_are_deterministic_and_sensitive_to_effective_state() { + let s1 = [([1u32, 2, 3, 4], false)]; + let s2 = [([1u32, 2, 3, 4], true)]; + let ck1 = compute_key(b"dxil-cs", &s1, 0); + assert_eq!(ck1, compute_key(b"dxil-cs", &s1, 0)); + assert_ne!(ck1, compute_key(b"dxil-cs", &s2, 0), "sampler change must change key"); + assert_ne!(ck1, compute_key(b"dxil-cs", &s1, 1), "flags change must change key"); + assert_ne!(ck1, compute_key(b"dxil-c2", &s1, 0), "shader change must change key"); + + // Graphics key reflects pc_topology_type's normalized topology and PC target format. + unsafe { + let mut g1: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::mem::zeroed(); + g1.NumRenderTargets = 1; + g1.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let mut g2 = g1.clone(); + g2.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + assert_ne!( + graphics_key(&g1, b"vs", Some(b"ps"), None, &[]), + graphics_key(&g2, b"vs", Some(b"ps"), None, &[]) + ); + pc_topology_type(&mut g1); + pc_topology_type(&mut g2); + assert_eq!( + graphics_key(&g1, b"vs", Some(b"ps"), None, &[]), + graphics_key(&g2, b"vs", Some(b"ps"), None, &[]), + "normalized graphics PSOs must share the same library key" + ); + } + + // Stream key hashes shader content, not pointer addresses. + unsafe { + let ms_a = b"mesh-shader-dxil-payload".to_vec(); + let ms_b = ms_a.clone(); + assert_ne!(ms_a.as_ptr(), ms_b.as_ptr()); + let ps = b"pixel-shader-dxil".to_vec(); + let build = |ms: &[u8], rs_ptr: usize| { + let mut out = StreamOut::default(); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &rs_ptr); + out.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms); + out.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, &ps); + let rt = D3D12_RT_FORMAT_ARRAY { + RTFormats: [DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN], + NumRenderTargets: 1, + }; + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, &rt); + out + }; + let sa = build(&ms_a, 0x1000); + let sb = build(&ms_b, 0x2000); + assert_eq!( + stream_key(&sa.0, 0x1000, sa.shader_bytes()), + stream_key(&sb.0, 0x2000, sb.shader_bytes()), + "stream key must depend on shader content, not transient pointers" + ); + let ms_diff = b"mesh-shader-dxil-DIFF!!!".to_vec(); + let sc = build(&ms_diff, 0x1000); + assert_ne!( + stream_key(&sa.0, 0x1000, sa.shader_bytes()), + stream_key(&sc.0, 0x1000, sc.shader_bytes()), + ); + } + } + + #[test] + fn background_save_scheduler_batches_bursts_and_flushes_idle_tail() { + assert!(!should_background_save(0, 60_000, 10_000, 0)); + // Below batch threshold during active burst (< 5s idle) -> wait. + assert!(!should_background_save(10, 12_000, 10_000, 0)); + // At batch threshold (>= 32) but < 15s since last save -> wait. + assert!(!should_background_save(32, 20_000, 19_000, 10_000)); + // At batch threshold (>= 32) and >= 15s since last save -> save! + assert!(should_background_save(32, 25_000, 24_000, 10_000)); + // Small tail (1 dirty) after 5s idle since last store & save -> flush! + assert!(should_background_save(1, 30_000, 25_000, 20_000)); + } + } +} + +#[cfg(test)] +mod pso_release_tests { + use super::*; + + /// An adopted pipeline as `orig_fn` sees it: its vtable, the original one before that. + #[repr(C)] + struct Pipeline { + vtable: *const usize, + refs: u32, + /// the pipeline was still known when its last reference went + known_when_freed: Option, + } + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let p = &mut *(this as *mut Pipeline); + p.refs += 1; + p.refs + } + + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let p = &mut *(this as *mut Pipeline); + p.refs -= 1; + if p.refs == 0 { + p.known_when_freed = Some(is_translated_compute(this as usize)); + } + p.refs + } + + /// What XCL keeps of a pipeline goes before the driver frees it, not after: its address can be + /// another pipeline's by then. It stays while there are other references. + #[test] + fn a_pipeline_is_forgotten_before_its_address_is_free() { + let orig: [usize; 3] = [0, add_ref as usize, release as usize]; + let ext: [usize; 4] = [orig.as_ptr() as usize, 0, 0, 0]; + let mut p = Box::new(Pipeline { vtable: &ext[1], refs: 2, known_when_freed: None }); + let this = p.as_mut() as *mut Pipeline as *mut c_void; + register_translated_compute_for_test(this as usize); + unsafe { + assert_eq!(pso_release(this), 1); + assert!(is_translated_compute(this as usize), "another reference is left"); + assert_eq!(pso_release(this), 0); + } + assert_eq!(p.known_when_freed, Some(false)); + assert!(!is_translated_compute(this as usize)); + } +} + +#[cfg(test)] +mod outside_buffer_tests { + use super::*; + + #[test] + fn outside_buffer_table_shares_uav_and_srv_subranges_and_reclaims_on_release() { + let mut t = OutsideBufferTable::default(); + let cap = 1 << 20; // 1 MiB cap + let base = 0x0c00_0000_0000usize; + let uma = 0x0003_1000_0000usize; + + // Disabled cap rejects insertion. + assert!(!t.insert(base, base + 0x4_0000, uma, true, false, 0)); + + // Insert a 256 KiB GPU-writable placed buffer range; sub-range SRV/UAV lookups hit the + // exact same sparse UMA backing at matching byte offsets. + assert!(t.insert(base, base + 0x4_0000, uma, true, false, cap)); + assert_eq!(t.lookup(base, 0x4_0000), Some(uma)); + assert_eq!(t.lookup(base + 0x1_2340, 0x4000), Some(uma + 0x1_2340)); + assert_eq!(t.lookup(base + 0x3_f000, 0x2000), None); // past end + + // Overlapping non-contained insertion is rejected to avoid splitting live tiles. + assert!(!t.insert(base + 0x2_0000, base + 0x6_0000, uma + 0x10_0000, true, false, cap)); + + // Second placed alias retains refcount; releasing first keeps backing alive, releasing second reclaims. + assert_eq!(t.retain_existing(base + 0x1_0000, 0x1_0000, true, false), Some((base, uma + 0x1_0000))); + assert_eq!(t.release_ref(base), None); + assert_eq!(t.release_ref(base), Some(uma)); + assert_eq!(t.total_bytes, 0); + assert_eq!(t.lookup(base, 0x1000), None); + + // UAV-pinned backing created without a placed resource stays resident across release_ref. + assert!(t.insert(base, base + 0x2_0000, uma, false, true, cap)); + assert_eq!(t.release_ref(base), None); + assert_eq!(t.lookup(base + 0x1000, 0x1000), Some(uma + 0x1000)); + } + + /// Regression for #2588: when Agility SDK 1.620+ allocates an open command list's vtable in + /// heap memory (outside any loaded module) and a later list reuses that same heap address with + /// different runtime method slots (e.g., compute list -> direct list `ClearDepthStencilView`), + /// `class_for` must not hand back the stale extended vtable. + #[test] + fn class_for_rebuilds_when_heap_vtable_reused_with_different_methods() { + unsafe extern "system" fn fake_qi(_this: *mut c_void, _iid: *const GUID, out: *mut *mut c_void) -> HRESULT { + if !out.is_null() { + *out = std::ptr::null_mut(); + } + -2147467262 // E_NOINTERFACE + } + unsafe extern "system" fn fake_ref(_this: *mut c_void) -> u32 { 1 } + unsafe extern "system" fn method_a(_this: *mut c_void) {} + unsafe extern "system" fn method_b(_this: *mut c_void) {} + + let base_iface = layout::find(Kind::CommandList.base()).unwrap(); + let n = base_iface.methods.len(); + // Heap-allocated vtable (`module_of(orig) == 0`) with a trailing sentinel `0` so scanning + // stops cleanly at `n`. + let mut heap_vtbl = vec![method_a as usize; n + 1]; + heap_vtbl[0] = fake_qi as usize; + heap_vtbl[1] = fake_ref as usize; + heap_vtbl[2] = fake_ref as usize; + heap_vtbl[n] = 0; + + let orig = heap_vtbl.as_ptr() as usize; + assert_eq!(module_of(orig), 0, "test vtable must live outside any loaded module"); + + struct Cleanup(usize); + impl Drop for Cleanup { + fn drop(&mut self) { + let mut exts = Vec::new(); + CLASSES.write().unwrap().retain(|c| { + if c.orig == self.0 { + exts.push(c.ext); + false + } else { + true + } + }); + if let Some(set) = EXTS.write().unwrap().as_mut() { + for e in exts { + set.remove(&e); + } + } + } + } + let _cleanup = Cleanup(orig); + + let mut obj = orig; + let obj_ptr = &mut obj as *mut usize as *mut c_void; + unsafe { + let ext1 = class_for(obj_ptr, orig, Kind::CommandList); + assert_eq!(class_for(obj_ptr, orig, Kind::CommandList), ext1, "unchanged heap vtable reuses cached class"); + + // Simulate a released compute list's heap vtable address reused by a direct list + // (changing slot 47 `ClearDepthStencilView` and unhooked slot 5 `SetPrivateData`). + heap_vtbl[5] = method_b as usize; + heap_vtbl[47] = method_b as usize; + let ext2 = class_for(obj_ptr, orig, Kind::CommandList); + assert_ne!(ext2, ext1, "reused heap vtable with changed runtime methods must not reuse stale ext"); + assert_eq!(*(ext2 as *const usize).add(5), method_b as usize); + assert_eq!(class_for(obj_ptr, orig, Kind::CommandList), ext2, "matching new methods reuse ext2"); + + // Restoring original slots hits ext1 again cleanly without unbounded growth. + heap_vtbl[5] = method_a as usize; + heap_vtbl[47] = method_a as usize; + assert_eq!(class_for(obj_ptr, orig, Kind::CommandList), ext1); + } + } +} + +#[cfg(test)] +mod release_order_tests { + use super::*; + use std::sync::atomic::AtomicU32; + + /// A driver object whose last Release runs `freed` with its address, as another thread's + /// new object made at that address the moment the driver frees it would. + #[repr(C)] + struct Reused { + vt: *const usize, + refs: u32, + freed: fn(usize), + ext_vt: [usize; 4], + orig_vt: [usize; 3], + } + unsafe extern "system" fn reused_add_ref(this: *mut c_void) -> u32 { + (*(this as *mut Reused)).refs += 1; + (*(this as *mut Reused)).refs + } + unsafe extern "system" fn reused_release(this: *mut c_void) -> u32 { + let o = &mut *(this as *mut Reused); + o.refs -= 1; + if o.refs == 0 { + (o.freed)(this as usize); + } + o.refs + } + fn reused(refs: u32, freed: fn(usize)) -> *mut Reused { + let o = Box::into_raw(Box::new(Reused { vt: std::ptr::null(), refs, freed, ext_vt: [0; 4], orig_vt: [0; 3] })); + unsafe { + (*o).orig_vt[1] = reused_add_ref as usize; + (*o).orig_vt[2] = reused_release as usize; + (*o).ext_vt[0] = (*o).orig_vt.as_ptr() as usize; + (*o).ext_vt[1] = (*o).orig_vt[0]; + (*o).ext_vt[2] = (*o).orig_vt[1]; + (*o).ext_vt[3] = (*o).orig_vt[2]; + (*o).vt = (*o).ext_vt.as_ptr().add(1); + } + o + } + + std::thread_local! { + static EVENTS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + fn event(e: &'static str) { + EVENTS.with(|v| v.borrow_mut().push(e)); + } + + #[test] + fn take_runs_before_the_last_release_and_after_once_it_is_gone() { + EVENTS.with(|v| v.borrow_mut().clear()); + let o = reused(2, |_| event("freed")); + unsafe { + let raw = o as *mut c_void; + assert_eq!(release_taking_first(raw, || event("take"), |()| event("after")), 1); + assert!(EVENTS.with(|v| v.borrow().is_empty()), "nothing runs while references are left"); + assert_eq!(release_taking_first(raw, || { event("take"); 7 }, |t| { assert_eq!(t, 7); event("after") }), 0); + drop(Box::from_raw(o)); + } + assert_eq!(EVENTS.with(|v| v.borrow().clone()), ["take", "freed", "after"]); + } + + #[repr(C)] + struct Racy { + vt: *const usize, + refs: AtomicU32, + ext_vt: [usize; 4], + orig_vt: [usize; 3], + } + static RACY_BARRIER: std::sync::LazyLock = std::sync::LazyLock::new(|| std::sync::Barrier::new(2)); + unsafe extern "system" fn racy_add_ref(this: *mut c_void) -> u32 { + let n = (*(this as *mut Racy)).refs.fetch_add(1, Ordering::AcqRel) + 1; + RACY_BARRIER.wait(); + n + } + unsafe extern "system" fn racy_release(this: *mut c_void) -> u32 { + (*(this as *mut Racy)).refs.fetch_sub(1, Ordering::AcqRel) - 1 + } + + #[test] + fn two_last_releases_at_once_take_the_entries_once() { + static TAKES: AtomicU32 = AtomicU32::new(0); + static AFTERS: AtomicU32 = AtomicU32::new(0); + let o = Box::into_raw(Box::new(Racy { vt: std::ptr::null(), refs: AtomicU32::new(2), ext_vt: [0; 4], orig_vt: [0; 3] })); + unsafe { + (*o).orig_vt[1] = racy_add_ref as usize; + (*o).orig_vt[2] = racy_release as usize; + (*o).ext_vt[0] = (*o).orig_vt.as_ptr() as usize; + (*o).ext_vt[1] = (*o).orig_vt[0]; + (*o).ext_vt[2] = (*o).orig_vt[1]; + (*o).ext_vt[3] = (*o).orig_vt[2]; + (*o).vt = (*o).ext_vt.as_ptr().add(1); + } + let addr = o as usize; + let release = move || unsafe { + release_taking_first(addr as *mut c_void, || TAKES.fetch_add(1, Ordering::AcqRel), |_| { + AFTERS.fetch_add(1, Ordering::AcqRel); + }) + }; + let a = std::thread::spawn(release); + let b = std::thread::spawn(release); + let mut left = [a.join().unwrap(), b.join().unwrap()]; + left.sort_unstable(); + unsafe { drop(Box::from_raw(o)) }; + assert_eq!(left[0], 0, "one of the two releases is the last"); + assert_eq!((TAKES.load(Ordering::Acquire), AFTERS.load(Ordering::Acquire)), (1, 1), "the entries are taken once, by the last release"); + } + + #[test] + fn mem_heap_release_keeps_a_new_heap_at_the_freed_address() { + let o = reused(1, |addr| { + let h = HeapUma { size: 0x1_0000, align: 0x1_0000, prefer_coherent: false, cpu_readback: false, block: None }; + HEAP_UMA.write().unwrap().get_or_insert_with(HashMap::new).insert(addr, h); + }); + let addr = o as usize; + unsafe { + assert_eq!(mem_heap_release(o as *mut c_void), 0); + drop(Box::from_raw(o)); + } + let kept = HEAP_UMA.write().unwrap().as_mut().and_then(|m| m.remove(&addr)).is_some(); + assert!(kept, "mem_heap_release dropped the heap made at the freed address after the driver freed the old one"); + } } +#[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() { + // Zero delta is a no-op. + 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()); + + // Raw buffer (4-byte elements): delta 0x200 -> +128 elements. + let p = patch_buffer_uav_delta(Some(&raw), true, 0x200, false, 0).unwrap().unwrap(); + assert_eq!(unsafe { p.Anonymous.Buffer.FirstElement }, 10 + 128); + + // Structured buffer (24-byte stride): 0x300 % 24 == 0 -> +32 elements; 0x100 % 24 != 0 -> Err. + 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()); + + // Typed buffers (R8=1, R16=2, R32=4, RG32=8, RGBA32=16, R11G11B10=4, R10G10B10A2=4). + 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()); + } + } + + // Counter buffer offset alignment (4096 bytes). + 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()); + + // NULL desc or unknown typed format with non-zero delta must fail safely to null PC UAV. + 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)); + } +} diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 958c9e9c28..6fc4de022a 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -9,16 +9,31 @@ static PIECES: AtomicU64 = AtomicU64::new(0); static DISPATCHES: AtomicU64 = AtomicU64::new(0); /// slabs dispatched (`pso::dispatch_slabs`) static SLABS: AtomicU64 = AtomicU64::new(0); +/// `.plib` hits and misses for split compute pipelines (pieces and whole forms) +static PLIB_HITS: AtomicU64 = AtomicU64::new(0); +static PLIB_MISSES: AtomicU64 = AtomicU64::new(0); /// scratch alive now, the most there was, and the most a dispatch would have needed at once (bytes) static LIVE: AtomicU64 = AtomicU64::new(0); static PEAK: AtomicU64 = AtomicU64::new(0); static WANTED: AtomicU64 = AtomicU64::new(0); +/// ExecuteIndirects run as chains, those of them that ran the whole form instead (more slabs than +/// rounds), and the slabs lost when there was no whole form yet +static INDIRECT: AtomicU64 = AtomicU64::new(0); +static INDIRECT_WHOLE: AtomicU64 = AtomicU64::new(0); +static INDIRECT_LOST: AtomicU64 = AtomicU64::new(0); +/// ExecuteIndirects that ran the whole form (not chainable) +static WHOLE_INDIRECT: AtomicU64 = AtomicU64::new(0); +/// fast check so non-split indirect dispatches avoid locking `CHAINS` +static HAS_CHAINS: AtomicBool = AtomicBool::new(false); +/// raw PSO address of the slicer already labeled for DRED +static SLICER_LABELED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); pub(crate) fn log_counts() { let mib = |a: &AtomicU64| a.load(Ordering::Relaxed) >> 20; - crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued in {} slabs; scratch {} MiB (most {}, largest dispatch {} in one slab)", - PROGRAMS.load(Ordering::Relaxed), PIECES.load(Ordering::Relaxed), DISPATCHES.load(Ordering::Relaxed), SLABS.load(Ordering::Relaxed), - mib(&LIVE), mib(&PEAK), mib(&WANTED)); + let n = |a: &AtomicU64| a.load(Ordering::Relaxed); + crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued in {} slabs; plib {} hits / {} misses; scratch {} MiB (most {}, largest dispatch {} in one slab); ExecuteIndirect: {} chained ({} of them whole, {} slabs lost), {} whole", + n(&PROGRAMS), n(&PIECES), n(&DISPATCHES), n(&SLABS), n(&PLIB_HITS), n(&PLIB_MISSES), mib(&LIVE), mib(&PEAK), mib(&WANTED), + n(&INDIRECT), n(&INDIRECT_WHOLE), n(&INDIRECT_LOST), n(&WHOLE_INDIRECT)); } /// The scratch a dispatch uses at once, `XCL_SPLIT_SCRATCH_MB` (256): more groups than fit run in @@ -29,22 +44,59 @@ fn scratch_budget() -> u64 { *B.get_or_init(|| std::env::var("XCL_SPLIT_SCRATCH_MB").ok().and_then(|v| v.trim().parse().ok()).filter(|&m| m > 0).unwrap_or(256u64).min(4096) << 20) } +/// Thread name for the dedicated background whole-form compiler. The `xcl-pso` prefix ensures +/// `driver_compile_identified` routes its driver compiles through `compile_slots` (`BIG_COMPILES` +/// / `MEDIUM_COMPILES` / `GIANT_COMPILES`) and `big_compile_commit_free` commit-headroom gating. +const WHOLE_WORKER_THREAD_NAME: &str = "xcl-pso-whole"; + +/// Deterministic cross-run `.plib` key for a split compute pipeline (piece or whole form). +/// Prefixed with `s` (`sc-...`) so 8-parameter split-root-signature PSOs never collide with +/// 6-parameter standard compute PSOs (`c-...`) in the shared pipeline library. +fn split_plib_key(dxil: &[u8], samplers: &[pso::StaticSampler], flags: i32) -> String { + format!("s{}", pso_lib::compute_key(dxil, samplers, flags)) +} + struct PipelineBuilder { device: ID3D12Device, create: PsoFn, signature: ID3D12RootSignature, + samplers: Vec, flags: D3D12_PIPELINE_STATE_FLAGS, node: u32, record: u64, } impl PipelineBuilder { - unsafe fn pipeline(&self, dxil: &[u8], iid: &GUID) -> Option { + unsafe fn pipeline(&self, dxil: &[u8], iid: &GUID) -> Result { + let lib_key = split_plib_key(dxil, &self.samplers, self.flags.0); let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: self.node, Flags: self.flags, ..Default::default() }; + let lib_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(self.signature.as_raw()), + CS: bytecode(dxil), + NodeMask: self.node, + Flags: self.flags, + ..Default::default() + }; let mut raw = std::ptr::null_mut(); + if pso_lib::try_load_compute(self.device.as_raw(), &lib_key, &lib_desc, iid, &mut raw) && !raw.is_null() { + let hits = PLIB_HITS.fetch_add(1, Ordering::Relaxed) + 1; + if hits <= 4 { + crate::xlog_info!("compute split: .plib hit #{hits} for cs {:016x} ({lib_key})", self.record); + } + return Ok(ID3D12PipelineState::from_raw(raw)); + } + let misses = PLIB_MISSES.fetch_add(1, Ordering::Relaxed) + 1; + if misses <= 4 { + crate::xlog_info!("compute split: .plib miss #{misses} for cs {:016x} ({lib_key})", self.record); + } let (hr, _, _) = compute_container(self.device.as_raw(), self.create, &desc, self.signature.as_raw(), dxil, self.record, iid, &mut raw, true); - (hr >= 0 && !raw.is_null()).then(|| ID3D12PipelineState::from_raw(raw)) + if hr >= 0 && !raw.is_null() { + pso_lib::store_pipeline(self.device.as_raw(), &lib_key, raw); + Ok(ID3D12PipelineState::from_raw(raw)) + } else { + Err(hr) + } } } @@ -52,50 +104,243 @@ struct Chain { builder: Arc, tail: Vec, words: u32, - whole_code: Vec, - whole: OnceLock, - build_whole: Mutex<()>, + whole_code: Arc>, + whole: OnceLock>, + whole_started: AtomicBool, + /// after a whole build that ran out of memory: when it may be tried, once more + retry_at: Mutex>, + /// its command signature for ExecuteIndirect (`pso::chain_command_signature`) + signature: OnceLock, + /// the most slabs one of its ExecuteIndirects had + slabs: std::sync::atomic::AtomicU32, + /// a lost slab was reported once for this program + warned: AtomicBool, +} + +/// How long a split program's whole form waits after a build that ran out of memory, before its last try. +const WHOLE_RETRY: std::time::Duration = std::time::Duration::from_secs(10); + +pub(in crate::hle::d3d12x) enum WholeStatus { + /// Not a split compute pipeline. + NotSplit, + /// Whole pipeline is built and ready to bind without blocking. + Ready(ID3D12PipelineState), + /// Whole pipeline is compiling on a background thread; skip this indirect dispatch to avoid + /// stalling the title thread past its watchdog. + Pending, + /// Background compilation of the whole pipeline failed. + Failed, } impl Chain { unsafe fn whole(&self) -> Result { - if let Some(p) = self.whole.get() { return Ok(p.clone()); } - let _guard = self.build_whole.lock().unwrap(); - if let Some(p) = self.whole.get() { return Ok(p.clone()); } - let p = self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState)).ok_or("whole compute pipeline")?; - let _ = self.whole.set(p.clone()); - Ok(p) + if let Some(p) = self.whole.get() { + return p.clone().ok_or_else(|| "whole compute pipeline".into()); + } + let mut retry_at = self.retry_at.lock().unwrap(); + if let Some(p) = self.whole.get() { + return p.clone().ok_or_else(|| "whole compute pipeline".into()); + } + if retry_at.is_some_and(|t| std::time::Instant::now() < t) { + return Err("whole compute pipeline: out of memory".into()); + } + match self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState)) { + Ok(p) => { + super::super::dred::label_text(p.as_raw() as usize, || format!("cs {:016x} whole", self.builder.record)); + let _ = self.whole.set(Some(p.clone())); + Ok(p) + } + Err(hr) if hr == crate::util::E_OUTOFMEMORY && retry_at.is_none() => { + *retry_at = Some(std::time::Instant::now() + WHOLE_RETRY); + Err("whole compute pipeline: out of memory".into()) + } + Err(_) => { + let _ = self.whole.set(None); + Err("whole compute pipeline".into()) + } + } + } + + /// After a whole build that ran out of memory, before its retry. Never waits: `whole` holds + /// `retry_at` for the whole driver compile (tens of seconds for the biggest programs), and a + /// title thread asking here (an allocator reset dropping a recording, a dispatch) stood that + /// long – a retail title's own GPU watchdog then ended it (`mov [0], 0x4d8bd421`). A build + /// going on is no cooldown: `start_whole_async` sees it by `whole_started` or starts the + /// async one, which waits for it on a worker. + fn whole_in_cooldown(&self) -> bool { + let in_cooldown = |at: &Option| at.is_some_and(|t| std::time::Instant::now() < t); + match self.retry_at.try_lock() { + Ok(g) => in_cooldown(&g), + Err(std::sync::TryLockError::WouldBlock) => false, + Err(std::sync::TryLockError::Poisoned(p)) => in_cooldown(&p.into_inner()), + } + } + + fn start_whole_async(self: &Arc) { + if self.whole.get().is_some() || self.whole_in_cooldown() { + return; + } + if self.whole_started.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { + return; + } + if !enqueue_whole_async(Arc::clone(self)) { + self.whole_started.store(false, Ordering::Release); + } } } +/// Queue a background whole-form build onto the single `xcl-pso-whole` worker so multiple split +/// programs never compile huge whole forms concurrently and every build goes through +/// `driver_compile_identified`'s `BIG_COMPILES` + commit-headroom gate. +fn enqueue_whole_async(chain: Arc) -> bool { + static QUEUE: LazyLock<(Mutex>>, std::sync::Condvar)> = + LazyLock::new(|| (Mutex::new(std::collections::VecDeque::new()), std::sync::Condvar::new())); + static WORKER_STARTED: AtomicBool = AtomicBool::new(false); + if WORKER_STARTED.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_ok() { + if std::thread::Builder::new() + .name(WHOLE_WORKER_THREAD_NAME.into()) + .spawn(|| { + let (lock, cv) = &*QUEUE; + loop { + let chain = { + let mut q = lock.lock().unwrap(); + while q.is_empty() { + q = cv.wait(q).unwrap(); + } + q.pop_front().unwrap() + }; + let record = chain.builder.record; + if let Err(e) = unsafe { chain.whole() } { + if chain.whole.get().is_none() { + // Transient E_OUTOFMEMORY: allow one retry after WHOLE_RETRY. + chain.whole_started.store(false, Ordering::Release); + } + crate::xlog_warn!("D3D12.X: background whole compute PSO for cs {record:016x} failed: {e}"); + } + } + }) + .is_err() + { + WORKER_STARTED.store(false, Ordering::Release); + return false; + } + } + let (lock, cv) = &*QUEUE; + lock.lock().unwrap().push_back(chain); + cv.notify_one(); + true +} + static CHAINS: LazyLock>>> = LazyLock::new(Default::default); +/// Canonical COM object identity (`IUnknown*`) for a D3D12 device pointer so tear-off interfaces +/// share cache slots while synthetic/unreadable test pointers preserve their raw address safely. +unsafe fn canonical_device_key(this: *mut c_void) -> usize { + if this.is_null() || !crate::gpu::shader::readable(this as usize, std::mem::size_of::()) { + return this as usize; + } + let v = *(this as *const usize); + if !crate::gpu::shader::readable(v, std::mem::size_of::()) || *(v as *const usize) == 0 { + return this as usize; + } + if is_ext(v) && orig_fn(this, 0) == 0 { + return this as usize; + } + ID3D12Device::from_raw_borrowed(&this) + .and_then(|d| d.cast::().ok()) + .map_or(this as usize, |u| u.as_raw() as usize) +} + +/// Dispatch-chain root signatures shared per `(canonical_device_key, static_samplers)`. +/// Intentionally retained for the process lifetime (bounded to one `ID3D12RootSignature` per +/// distinct `(device, static_sampler_set)`) so split programs sharing pieces hit `COMPUTE_BLOBS` +/// instead of allocating a fresh root signature object per program. +static SIGNATURES: LazyLock), ID3D12RootSignature>>> = LazyLock::new(Default::default); + +fn sampler_key(samplers: &[pso::StaticSampler]) -> Vec { + samplers.iter().flat_map(|(w, c)| w.iter().copied().chain([*c as u32])).collect() +} + +unsafe fn root_signature_device(rs: &ID3D12RootSignature) -> Option { + let mut owner: Option = None; + rs.GetDevice(&mut owner).ok()?; + owner +} + +unsafe fn rs_belongs_to_device(rs: &ID3D12RootSignature, dev_key: usize) -> bool { + root_signature_device(rs).is_some_and(|owner| canonical_device_key(owner.as_raw()) == dev_key) +} + +/// Shared dispatch-chain root signature for `dev` and `samplers`, isolating distinct D3D12 devices +/// so `COMPUTE_BLOBS` never reuses a root signature across devices or sampler layouts. +unsafe fn signature_for(dev: &ID3D12Device, samplers: &[pso::StaticSampler]) -> Option { + let dev_key = canonical_device_key(dev.as_raw()); + let key = (dev_key, sampler_key(samplers)); + if let Some(rs) = SIGNATURES.lock().unwrap().get(&key).cloned() { + if rs_belongs_to_device(&rs, dev_key) { + return Some(rs); + } + } + let created = match pso::dispatch_chain_root_signature(dev, samplers) { + Ok(rs) => rs, + Err(e) => { + note_translation_error(format!("dispatch-chain root signature: {e}")); + return None; + } + }; + let mut g = SIGNATURES.lock().unwrap(); + if g.get(&key).is_some_and(|rs| !rs_belongs_to_device(rs, dev_key)) { + g.insert(key, created.clone()); + return Some(created); + } + Some(g.entry(key).or_insert(created).clone()) +} + 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, whole: Arc>, 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)?; - let signature = pso::dispatch_chain_root_signature(dev, samplers).ok()?; + let signature = signature_for(dev, samplers)?; 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(); let iid = if i == 0 { *iid } else { pc_iid(Kind::PipelineState) }; - Box::new(move || builder.pipeline(&plan.pieces[i], &iid).map_or(0, |p| p.into_raw() as usize)) as super::super::pso_async::Job + Box::new(move || builder.pipeline(&plan.pieces[i], &iid).ok().map_or(0, |p| p.into_raw() as usize)) as super::super::pso_async::Job }).collect(); // Take ownership of every success, including when a different piece failed. let built: Vec<_> = super::super::pso_async::build_pieces(jobs).into_iter() .map(|p| (p != 0).then(|| ID3D12PipelineState::from_raw(p as *mut c_void))).collect(); - let mut pieces = built.into_iter().collect::>>()?.into_iter(); + let all = built.into_iter().collect::>>()?; + for (i, piece) in all.iter().enumerate() { + super::super::dred::label_text(piece.as_raw() as usize, || format!("cs {record:016x} piece {i} of {}", all.len())); + } + let mut pieces = all.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(()) }); + let chain = Arc::new(Chain { + builder, + tail: pieces.collect(), + words: plan.dwords_per_group, + whole_code: whole, + whole: OnceLock::new(), + whole_started: AtomicBool::new(false), + retry_at: Mutex::new(None), + signature: OnceLock::new(), + slabs: Default::default(), + warned: AtomicBool::new(false), + }); PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); *result = first.into_raw(); - CHAINS.lock().unwrap().insert(*result as usize, chain); + // a chain this one replaces (the same address made again) is dropped after the lock: its + // pipelines' release goes back into this module, which takes `CHAINS` (a self-deadlock that + // held a retail title's thread for good) + let replaced = CHAINS.lock().unwrap().insert(*result as usize, chain); + drop(replaced); + HAS_CHAINS.store(true, Ordering::Release); Some(rs) } @@ -104,9 +349,43 @@ pub(super) fn forget(pso: usize) { drop(gone); // releasing a tail PSO also goes through forget_pso } -pub(in crate::hle::d3d12x) unsafe fn whole(pso: usize) -> Result, String> { - let chain = CHAINS.lock().unwrap().get(&pso).cloned(); - chain.map(|c| c.whole()).transpose() +/// Fast check for whether `pso` is a split compute pipeline. +pub(in crate::hle::d3d12x) fn is_split(pso: usize) -> bool { + HAS_CHAINS.load(Ordering::Acquire) && CHAINS.lock().unwrap().contains_key(&pso) +} + +/// Resolve the whole compute pipeline for an `ExecuteIndirect` without stalling the recording +/// thread: when async PSO builds are enabled and the whole form is not compiled yet, kick off +/// its build once on a background thread and return `Pending`. +pub(in crate::hle::d3d12x) unsafe fn whole_nonblocking(pso: usize) -> WholeStatus { + if !HAS_CHAINS.load(Ordering::Acquire) { + return WholeStatus::NotSplit; + } + let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { + return WholeStatus::NotSplit; + }; + match chain.whole.get() { + Some(Some(p)) => { + WHOLE_INDIRECT.fetch_add(1, Ordering::Relaxed); + return WholeStatus::Ready(p.clone()); + } + Some(None) => return WholeStatus::Failed, + None => {} + } + if !super::super::pso_async::enabled() { + return match chain.whole() { + Ok(p) => { + WHOLE_INDIRECT.fetch_add(1, Ordering::Relaxed); + WholeStatus::Ready(p) + } + Err(_) => WholeStatus::Failed, + }; + } + if chain.whole_in_cooldown() { + return WholeStatus::Failed; + } + chain.start_whole_async(); + WholeStatus::Pending } struct Scratch { @@ -116,7 +395,7 @@ struct Scratch { impl Drop for Scratch { fn drop(&mut self) { - LIVE.fetch_sub(self.bytes, Ordering::Relaxed); + LIVE.fetch_sub(self.bytes, Ordering::AcqRel); } } @@ -124,6 +403,56 @@ struct Recording { scratch: Arc, first: ID3D12PipelineState, chain: Arc, + indirect: Option, +} + +/// The commands of a chained ExecuteIndirect (`pso::record_slicer`), read when the GPU is done +/// with them (the allocator is reset): with more slabs than rounds, the next ExecuteIndirect of +/// the program records more, and the whole form is built in the background for it. +struct Indirect { + commands: ID3D12Resource, + at: u64, + rounds: u32, + /// the whole form ran instead under predication; `checked`: the predicate is XCL's own + whole: bool, + checked: bool, +} + +impl Recording { + fn read_back(&self) { + let Some(i) = self.indirect.as_ref().filter(|i| i.checked) else { return }; + let mut p = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: i.at as usize, End: i.at as usize + 16 }; + if unsafe { i.commands.Map(0, Some(&range), Some(&mut p)) }.is_err() { + return; + } + let [partial, _, slabs, _] = unsafe { std::ptr::read_volatile((p as *const u8).add(i.at as usize) as *const [u32; 4]) }; + unsafe { i.commands.Unmap(0, Some(&D3D12_RANGE::default())) }; + if partial == 0 { + return; + } + self.chain.slabs.fetch_max(slabs, Ordering::Relaxed); + if i.whole { + INDIRECT_WHOLE.fetch_add(1, Ordering::Relaxed); + return; + } + let lost = slabs.saturating_sub(i.rounds); + INDIRECT_LOST.fetch_add(u64::from(lost), Ordering::Relaxed); + if !self.chain.warned.swap(true, Ordering::Relaxed) { + crate::xlog_warn!( + "D3D12.X: ExecuteIndirect of a split program ({:#x}) had {slabs} slabs for {} rounds: {lost} lost; its whole form is built for the next ones", + self.first.as_raw() as usize, + i.rounds + ); + } + self.chain.start_whole_async(); + } +} + +impl Drop for Recording { + fn drop(&mut self) { + self.read_back(); + } } static RECORDINGS: LazyLock>>>> = LazyLock::new(Default::default); @@ -136,6 +465,16 @@ pub(in crate::hle::d3d12x) fn list_reset(list: usize) { SHARED.lock().unwrap().remove(&list); } +#[cfg(test)] +pub(in crate::hle::d3d12x) fn seed_shared_for_test(list: usize, allocator: usize) { + SHARED.lock().unwrap().insert(list, (allocator, std::sync::Weak::new())); +} + +#[cfg(test)] +pub(in crate::hle::d3d12x) fn has_shared_for_test(list: usize) -> bool { + SHARED.lock().unwrap().contains_key(&list) +} + /// `to` records right after `from` on the same allocator: its chains go on in `from`'s scratch. pub(in crate::hle::d3d12x) fn list_follows(from: usize, to: usize) { let mut shared = SHARED.lock().unwrap(); @@ -167,17 +506,109 @@ fn scratch_bytes(needed: u64, group: u64, budget: u64, had: Option, live: u } } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ScratchOomFallback { + /// Reuse the recording's existing scratch buffer (running smaller slabs). + ReuseExisting, + /// Allocate a minimal 1-workgroup scratch buffer instead of falling back to `Chain::whole()`. + TryMinimal(u64), + /// Neither existing reuse nor a smaller allocation is viable. + None, +} + +/// Choose a smaller-slab fallback when growing `scratch_buffer` fails under VRAM pressure. +fn scratch_oom_fallback(had_bytes: Option, attempted: u64, group: u64) -> ScratchOomFallback { + if had_bytes.is_some_and(|h| h >= group) { + ScratchOomFallback::ReuseExisting + } else if attempted > group { + ScratchOomFallback::TryMinimal(group) + } else { + ScratchOomFallback::None + } +} + +/// Guard for bytes atomically reserved from `LIVE` before `scratch_buffer` allocates GPU memory: +/// releases on drop if allocation fails, shrinks on OOM fallback, or transfers ownership to `Scratch`. +struct ScratchReservation<'a> { + live: &'a AtomicU64, + bytes: u64, +} + +impl<'a> ScratchReservation<'a> { + fn shrink(&mut self, new_bytes: u64) { + if new_bytes < self.bytes { + let release = self.bytes - new_bytes; + self.live.fetch_sub(release, Ordering::AcqRel); + self.bytes = new_bytes; + } + } + + fn commit(mut self) -> u64 { + let bytes = self.bytes; + self.bytes = 0; + bytes + } +} + +impl Drop for ScratchReservation<'_> { + fn drop(&mut self) { + if self.bytes != 0 { + self.live.fetch_sub(self.bytes, Ordering::AcqRel); + self.bytes = 0; + } + } +} + +/// Atomically decide whether to reuse `had` or reserve new scratch bytes from `live` BEFORE +/// creating the GPU buffer so concurrent recording threads cannot overshoot `total`. +fn reserve_scratch_bytes<'a>( + live: &'a AtomicU64, + peak: &AtomicU64, + needed: u64, + group: u64, + budget: u64, + had: Option, + total: u64, +) -> Option> { + let mut cur = live.load(Ordering::Acquire); + loop { + let (bytes, make) = scratch_bytes(needed, group, budget, had, cur, total); + if !make { + return None; + } + let next = cur.saturating_add(bytes); + match live.compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => { + peak.fetch_max(next, Ordering::Relaxed); + return Some(ScratchReservation { live, bytes }); + } + Err(observed) => cur = observed, + } + } +} + /// A scratch for a chain of `needed` bytes recorded on `list` with `allocator`, and whether a /// chain before it on the list used it. unsafe fn scratch_for(dev: &ID3D12Device, list: usize, allocator: usize, needed: u64, group: u64) -> Option<(Arc, bool)> { let had = SHARED.lock().unwrap().get(&list).filter(|s| s.0 == allocator).and_then(|s| s.1.upgrade()); - let (bytes, make) = scratch_bytes(needed, group, scratch_budget(), had.as_ref().map(|s| s.bytes), LIVE.load(Ordering::Relaxed), scratch_total()); - if !make { + let had_bytes = had.as_ref().map(|s| s.bytes); + let Some(mut reservation) = reserve_scratch_bytes(&LIVE, &PEAK, needed, group, scratch_budget(), had_bytes, scratch_total()) else { return had.map(|s| (s, true)); - } - let s = Arc::new(Scratch { buffer: scratch_buffer(dev, bytes)?, bytes }); - let live = LIVE.fetch_add(bytes, Ordering::Relaxed) + bytes; - PEAK.fetch_max(live, Ordering::Relaxed); + }; + let bytes = reservation.bytes; + let buffer = match scratch_buffer(dev, bytes) { + Some(b) => b, + None => match scratch_oom_fallback(had_bytes, bytes, group) { + ScratchOomFallback::ReuseExisting => return had.map(|s| (s, true)), + ScratchOomFallback::TryMinimal(min_bytes) => { + reservation.shrink(min_bytes); + scratch_buffer(dev, min_bytes)? + } + ScratchOomFallback::None => return None, + }, + }; + let actual = reservation.commit(); + let s = Arc::new(Scratch { buffer, bytes: actual }); SHARED.lock().unwrap().insert(list, (allocator, Arc::downgrade(&s))); Some((s, false)) } @@ -220,12 +651,28 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, let most = scratch.as_ref().map_or(1, |(s, _)| (s.bytes / group).max(1)); let slabs = pso::dispatch_slabs(grid, most); let Some((scratch, used)) = scratch else { - list.SetPipelineState(&chain.whole()?); - list.Dispatch(x, y, z); - return Ok(()); + match chain.whole.get() { + Some(Some(whole)) => { + list.SetPipelineState(whole); + list.Dispatch(x, y, z); + return Ok(()); + } + Some(None) => return Err("whole compute pipeline".into()), + None => {} + } + if !super::super::pso_async::enabled() { + list.SetPipelineState(&chain.whole()?); + list.Dispatch(x, y, z); + return Ok(()); + } + if chain.whole_in_cooldown() { + return Err("whole compute pipeline: out of memory".into()); + } + chain.start_whole_async(); + return Err("whole compute pipeline still building in background".into()); }; let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); - let held = Arc::new(Recording { scratch, first, chain }); + let held = Arc::new(Recording { scratch, first, chain, indirect: None }); RECORDINGS.lock().unwrap().entry(allocator).or_default().push(held.clone()); DISPATCHES.fetch_add(1, Ordering::Relaxed); SLABS.fetch_add(slabs.len() as u64, Ordering::Relaxed); @@ -233,26 +680,164 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, Ok(()) } +/// The rounds a chained ExecuteIndirect records at most, `XCL_SPLIT_INDIRECT_ROUNDS` (16): each +/// is one ExecuteIndirect and one barrier per piece, also when the title's arguments leave it empty. +fn most_rounds() -> u32 { + static B: OnceLock = OnceLock::new(); + *B.get_or_init(|| { + std::env::var("XCL_SPLIT_INDIRECT_ROUNDS") + .ok() + .and_then(|v| v.trim().parse().ok()) + .filter(|&n| n > 0) + .unwrap_or(16u32) + .min(1024) + }) +} + +/// The rounds for slabs of `most` groups: as many as the arguments there now (`seen`, the GPU's +/// last ones) or an earlier ExecuteIndirect of the program (`before`) had, a quarter more, at +/// least two and at most `cap`. +fn indirect_rounds(seen: &[[u32; 3]], most: u64, before: u32, cap: u32) -> u32 { + let now: u64 = seen.iter().map(|&g| pso::slab_count(g, most)).sum(); + let want = now.max(u64::from(before)); + (want + want.div_ceil(4)).clamp(2, u64::from(cap.max(2))) as u32 +} + +/// An ExecuteIndirect of split program `pso` whose command signature is one Dispatch of `stride` +/// bytes: `commands` of them at GPU address `args` (their count at `count`, when given), run as +/// the chain. `seen`: the arguments the CPU sees there now; `predicated`: the title's predication +/// is set. `bind` binds the ABI after the slicer, and `whole` is the title's ExecuteIndirect, run +/// with the whole form (built already) when the arguments have more slabs than the rounds. +/// Ok(false): nothing recorded (no chain, a bundle, no scratch) – the caller runs the whole form. +#[allow(clippy::too_many_arguments)] +pub(in crate::hle::d3d12x) unsafe fn execute_indirect( + list: &ID3D12GraphicsCommandList, + pso: usize, + allocator: usize, + args: u64, + stride: u32, + commands: u32, + count: Option, + seen: &[[u32; 3]], + predicated: bool, + bind: impl FnOnce() -> Result<(), String>, + whole: impl FnOnce(), +) -> Result { + if !HAS_CHAINS.load(Ordering::Acquire) { + return Ok(false); + } + let chain = CHAINS.lock().unwrap().get(&pso).cloned(); + let Some(chain) = chain else { return Ok(false) }; + let allocator = if super::super::alloc_pool::enabled() { + super::super::alloc_pool::recording_backing(list.as_raw() as usize).unwrap_or(0) + } else { + allocator + }; + if allocator == 0 || list.GetType() == D3D12_COMMAND_LIST_TYPE_BUNDLE { + return Ok(false); + } + let dev = &chain.builder.device; + let group = u64::from(chain.words) * 4; + let Some((scratch, _)) = scratch_for(dev, list.as_raw() as usize, allocator, scratch_budget(), group) else { + return Ok(false); + }; + let most = (scratch.bytes / group).max(1); + let sig = match chain.signature.get() { + Some(s) => s.clone(), + None => { + let s = pso::chain_command_signature(dev, &chain.builder.signature)?; + chain.signature.get_or_init(|| s).clone() + } + }; + let rounds = indirect_rounds(seen, most, chain.slabs.load(Ordering::Relaxed), most_rounds()); + let pieces = chain.tail.len() as u32 + 1; + let buffer = pso::chain_commands_buffer(dev, rounds, pieces).ok_or("no buffer for the commands of a chained ExecuteIndirect")?; + let slicer_pso = pso::record_slicer(list, args, stride, commands, count, rounds, most, pieces, &buffer)?; + if slicer_pso != 0 && SLICER_LABELED.swap(slicer_pso, Ordering::Relaxed) != slicer_pso { + super::super::dred::label_text(slicer_pso, || "xcl dispatch_chain_slicer".into()); + } + if let Err(e) = bind() { + // `record_slicer` already recorded a dispatch writing into `buffer` and `scratch`: + // keep both alive until `allocator` resets so the GPU never page-faults on a freed buffer. + if let Some(first) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { + let indirect = Indirect { + commands: buffer, + at: pso::chain_predicate_offset(rounds, pieces), + rounds, + whole: false, + checked: false, + }; + RECORDINGS + .lock() + .unwrap() + .entry(allocator) + .or_default() + .push(Arc::new(Recording { scratch, first: first.clone(), chain, indirect: Some(indirect) })); + } + return Err(e); + } + // under the title's own predication XCL's cannot be set: the slabs past the rounds are lost + let full = if predicated { None } else { chain.whole.get().and_then(|o| o.clone()) }; + let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); + pso::record_dispatch_chain_indirect(list, &sig, &buffer, rounds, full.is_some(), &scratch.buffer, std::iter::once(&first).chain(&chain.tail)); + let at = pso::chain_predicate_offset(rounds, pieces); + if let Some(full) = &full { + list.SetPredication(&buffer, at, D3D12_PREDICATION_OP_EQUAL_ZERO); + list.SetPipelineState(full); + whole(); + list.SetPredication(None::<&ID3D12Resource>, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); + } + let indirect = Indirect { + commands: buffer, + at, + rounds, + whole: full.is_some(), + checked: !predicated, + }; + RECORDINGS + .lock() + .unwrap() + .entry(allocator) + .or_default() + .push(Arc::new(Recording { scratch, first, chain, indirect: Some(indirect) })); + INDIRECT.fetch_add(1, Ordering::Relaxed); + Ok(true) +} + #[cfg(test)] mod tests { use super::{scratch_bytes, LEAST}; + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Direct3D12::{ + ID3D12Device, ID3D12PipelineState, D3D12_COMPUTE_PIPELINE_STATE_DESC, D3D12_PIPELINE_STATE_FLAG_NONE, + }; const MB: u64 = 1 << 20; - #[test] - fn a_list_recorded_after_another_goes_on_in_its_scratch() { - use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; - use windows::Win32::Graphics::Direct3D12::{D3D12CreateDevice, ID3D12Device}; + fn test_device() -> Option { + use windows::Win32::Graphics::Direct3D12::D3D12CreateDevice; use windows::Win32::Graphics::Dxgi::*; let mut dev: Option = None; if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev) }.is_err() { let warp = unsafe { CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()) }; - if warp.and_then(|w| unsafe { D3D12CreateDevice(&w, D3D_FEATURE_LEVEL_11_0, &mut dev) }).is_err() { - crate::gpu::recomp::runner::skip_test("no GPU"); - return; - } + let _ = warp.and_then(|w| unsafe { D3D12CreateDevice(&w, D3D_FEATURE_LEVEL_11_0, &mut dev) }); } - let dev = dev.unwrap(); + dev + } + + fn warp_device() -> Option { + use windows::Win32::Graphics::Dxgi::*; + let warp = unsafe { CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()) }.ok()?; + crate::gpu::agility::create_device(&warp, D3D_FEATURE_LEVEL_11_0).ok() + } + + #[test] + fn a_list_recorded_after_another_goes_on_in_its_scratch() { + let Some(dev) = test_device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; let (a, b, c, alloc) = (0x7E57_5C01usize, 0x7E57_5C02usize, 0x7E57_5C03usize, 0x7E57_5CA0usize); let (first, used) = unsafe { super::scratch_for(&dev, a, alloc, MB, 4096) }.unwrap(); assert!(!used); @@ -284,4 +869,419 @@ mod tests { assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, None, 400 * MB, 384 * MB), (9 * MB, true)); assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, Some(MB), 400 * MB, 384 * MB), (9 * MB, true)); } + + #[test] + fn whole_nonblocking_returns_not_split_for_unknown_pso() { + assert!(matches!(unsafe { super::whole_nonblocking(0) }, super::WholeStatus::NotSplit)); + assert!(matches!(unsafe { super::whole_nonblocking(0x7800_0001) }, super::WholeStatus::NotSplit)); + } + + #[test] + fn scratch_oom_fallback_reuses_existing_or_shrinks_to_one_group() { + use super::{scratch_oom_fallback, ScratchOomFallback}; + let group = 256 << 10; + // Existing list scratch fits >= 1 group: reuse it with smaller slabs instead of Chain::whole. + assert_eq!(scratch_oom_fallback(Some(2 * MB), 64 * MB, group), ScratchOomFallback::ReuseExisting); + assert_eq!(scratch_oom_fallback(Some(group), 64 * MB, group), ScratchOomFallback::ReuseExisting); + // No usable existing scratch, attempted > 1 group: shrink to minimal 1-group scratch. + assert_eq!(scratch_oom_fallback(None, 64 * MB, group), ScratchOomFallback::TryMinimal(group)); + assert_eq!(scratch_oom_fallback(Some(group - 1), 4 * MB, group), ScratchOomFallback::TryMinimal(group)); + // Already attempted minimal 1-group allocation with no usable existing scratch: give up. + assert_eq!(scratch_oom_fallback(None, group, group), ScratchOomFallback::None); + } + + #[test] + fn concurrent_scratch_admission_serializes_budget_reservations() { + use std::sync::{ + atomic::{AtomicU64, Ordering}, + Arc, Barrier, + }; + let group = 256 << 10; + let budget = 64 * MB; + let total = 384 * MB; + + // Case 1: 12 concurrent threads whose lists already have a 4 MiB scratch buffer race to + // grow to 64 MiB. Atomic reservation caps `peak <= total` (at most 6 grow; 6 reuse). + let live = Arc::new(AtomicU64::new(0)); + let peak = Arc::new(AtomicU64::new(0)); + let start = Arc::new(Barrier::new(12)); + let hold = Arc::new(Barrier::new(12)); + let mut threads = Vec::new(); + for _ in 0..12 { + let (live, peak, start, hold) = (Arc::clone(&live), Arc::clone(&peak), Arc::clone(&start), Arc::clone(&hold)); + threads.push(std::thread::spawn(move || { + start.wait(); + let res = super::reserve_scratch_bytes(&live, &peak, budget, group, budget, Some(4 * MB), total); + let granted = res.as_ref().map_or(0, |r| r.bytes); + hold.wait(); + drop(res); + granted + })); + } + let grants: Vec = threads.into_iter().map(|t| t.join().unwrap()).collect(); + assert_eq!(grants.iter().filter(|&&b| b == budget).count(), 6); + assert_eq!(grants.iter().filter(|&&b| b == 0).count(), 6); + assert_eq!(peak.load(Ordering::Relaxed), total); + assert_eq!(live.load(Ordering::Relaxed), 0); + + // Case 2: shrink + rollback on OOM fallback releases reserved bytes accurately. + let mut r = super::reserve_scratch_bytes(&live, &peak, budget, group, budget, None, total).unwrap(); + assert_eq!(r.bytes, budget); + assert_eq!(live.load(Ordering::Relaxed), budget); + r.shrink(group); + assert_eq!(r.bytes, group); + assert_eq!(live.load(Ordering::Relaxed), group); + drop(r); + assert_eq!(live.load(Ordering::Relaxed), 0); + } + + #[test] + fn indirect_rounds_clamps_and_adds_headroom() { + assert_eq!(super::indirect_rounds(&[], 100, 0, 16), 2); + assert_eq!(super::indirect_rounds(&[[100, 4, 1]], 100, 0, 16), 5); + assert_eq!(super::indirect_rounds(&[[100, 1, 1]], 100, 8, 16), 10); + assert_eq!(super::indirect_rounds(&[[100, 40, 1]], 100, 0, 16), 16); + } + + #[test] + fn whole_worker_thread_name_matches_driver_compile_gate() { + assert!( + super::WHOLE_WORKER_THREAD_NAME.starts_with("xcl-pso"), + "whole-form background worker must carry the xcl-pso prefix so driver_compile_identified gates it" + ); + } + + #[test] + fn split_plib_key_is_distinct_from_standard_compute_key() { + let dxil = b"DXBC-fake-split-whole-dxil"; + let samplers = [([1, 2, 3, 4], false)]; + let std_key = super::super::pso_lib::compute_key(dxil, &samplers, 0); + let split_key = super::split_plib_key(dxil, &samplers, 0); + assert!(split_key.starts_with("sc-")); + assert_ne!(split_key, std_key); + assert_eq!(split_key, super::split_plib_key(dxil, &samplers, 0)); + assert_ne!(split_key, super::split_plib_key(dxil, &[], 0)); + assert_ne!(split_key, super::split_plib_key(dxil, &samplers, 1)); + } + + #[test] + fn signature_for_reuses_root_signature_per_device_and_separates_devices_and_samplers() { + let Some(dev1) = test_device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Some(dev2) = warp_device().filter(|d| d.as_raw() != dev1.as_raw()) else { + crate::gpu::recomp::runner::skip_test("second distinct D3D12 device unavailable"); + return; + }; + let sampler: super::pso::StaticSampler = ([0x1111_0001, 0x2222_0002, 0x3333_0003, 0x4444_0004], false); + unsafe { + let rs1_a = super::signature_for(&dev1, &[]).expect("dispatch chain RS 1"); + let rs1_b = super::signature_for(&dev1, &[]).expect("dispatch chain RS 1 cached"); + assert_eq!(rs1_a.as_raw(), rs1_b.as_raw(), "repeated builds on the same device must share one RS"); + + let rs1_samp_a = super::signature_for(&dev1, &[sampler]).expect("dispatch chain RS with sampler"); + let rs1_samp_b = super::signature_for(&dev1, &[sampler]).expect("dispatch chain RS with sampler cached"); + assert_eq!(rs1_samp_a.as_raw(), rs1_samp_b.as_raw()); + assert_ne!(rs1_samp_a.as_raw(), rs1_a.as_raw(), "static samplers must partition the RS cache"); + + let rs2 = super::signature_for(&dev2, &[]).expect("dispatch chain RS for second device"); + assert_ne!(rs2.as_raw(), rs1_a.as_raw(), "distinct D3D12 devices must never share COM root signatures"); + + let cs = super::super::dummy().cs.clone(); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs2.clone())), + CS: super::super::bytecode(&cs), + ..Default::default() + }; + let _pso: ID3D12PipelineState = dev2.CreateComputePipelineState(&desc).expect("dev2 accepts its own dispatch-chain RS"); + } + } + + #[test] + fn signature_retention_and_device_child_lifetime() { + let Some(dev_hw) = test_device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Some(dev_warp) = warp_device() else { + crate::gpu::recomp::runner::skip_test("WARP device unavailable"); + return; + }; + unsafe { + let warp_key = super::canonical_device_key(dev_warp.as_raw()); + let refs_of = |d: &ID3D12Device| -> u32 { + type F = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32; + let vt = *(d.as_raw() as *const *const usize); + let add: F = std::mem::transmute(*vt.add(1)); + let rel: F = std::mem::transmute(*vt.add(2)); + add(d.as_raw()); + rel(d.as_raw()) + }; + let before_refs = refs_of(&dev_warp); + let rs_warp = super::signature_for(&dev_warp, &[]).expect("WARP dispatch chain RS"); + let after_refs = refs_of(&dev_warp); + assert!(super::rs_belongs_to_device(&rs_warp, warp_key)); + let owner = super::root_signature_device(&rs_warp).expect("GetDevice while device live"); + assert_eq!(super::canonical_device_key(owner.as_raw()), warp_key); + drop(owner); + drop(rs_warp); + drop(dev_warp); + + // While `SIGNATURES` retains the child root signature, inspect `GetDevice` and cache entry count. + let retained = super::SIGNATURES.lock().unwrap().get(&(warp_key, Vec::new())).cloned().expect("retained child RS"); + let resurrected_owner = super::root_signature_device(&retained).expect("retained ID3D12RootSignature keeps parent device queryable"); + assert_eq!(super::canonical_device_key(resurrected_owner.as_raw()), warp_key); + + let sig_count_before = super::SIGNATURES.lock().unwrap().len(); + let _ = super::signature_for(&dev_hw, &[]).expect("HW dispatch chain RS"); + let _ = super::signature_for(&dev_hw, &[]).expect("HW dispatch chain RS cached"); + let sig_count_after = super::SIGNATURES.lock().unwrap().len(); + assert!(sig_count_after <= sig_count_before + 1, "repeated calls must not grow SIGNATURES"); + println!("SIGNATURES_LIFETIME before_refs={before_refs} after_refs={after_refs} cached_entries={sig_count_after}"); + } + } + + #[test] + fn split_programs_sharing_large_piece_hit_compute_blobs_and_reuse_root_signature() { + use std::ffi::c_void; + use std::sync::{atomic::Ordering, Arc, Mutex}; + + if crate::gpu::recomp::dxc::location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + let Some(dev) = test_device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + + // Compile unique >= 16 KB DXIL pieces (`>= COMPUTE_BLOB_MIN_DXIL`) with a per-run salt so + // earlier runs' disk caches cannot satisfy Program A cold builds. + let nonce = (std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() as u32) ^ std::process::id(); + let compile_piece = |rounds: u32, extra_xor: u32| { + let hlsl = format!( + "RWByteAddressBuffer dst : register(u0, space0);\n\ + [numthreads(1, 1, 1)] void main(uint3 id : SV_DispatchThreadID) {{\n\ + uint x = id.x ^ 0x{nonce:08x}u ^ 0x{extra_xor:08x}u;\n\ + [unroll] for (uint i = 0; i < {rounds}; ++i) {{\n\ + x = (x * 1664525u + (i ^ 0x9e3779b9u)) ^ (x >> 13);\n\ + }}\n\ + dst.Store(0, x);\n\ + }}\n" + ); + crate::gpu::recomp::dxc::compile(&hlsl, "main", "cs_6_0", &[]).expect("compile cs_6_0 piece") + }; + let mut rounds = 600u32; + let mut shared = compile_piece(rounds, 0); + while shared.len() < super::super::COMPUTE_BLOB_MIN_DXIL { + rounds *= 2; + shared = compile_piece(rounds, 0); + } + let tail_a = compile_piece(12, 1); + let tail_b = compile_piece(12, 2); + let whole = compile_piece(16, 3); + + static SPY_LOCK: Mutex<()> = Mutex::new(()); + static SPY_CALLS: Mutex> = Mutex::new(Vec::new()); + let _serial = SPY_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SPY_CALLS.lock().unwrap().clear(); + + struct FixtureCleanup { + psos: Vec, + blob_keys: Vec<(u64, usize, i32)>, + disk_dxils: Vec>, + } + impl Drop for FixtureCleanup { + fn drop(&mut self) { + for pso in self.psos.drain(..) { + super::forget(pso.as_raw() as usize); + } + for key in self.blob_keys.drain(..) { + super::super::forget_compute_blob(key); + } + for bytes in self.disk_dxils.drain(..) { + if let Some(p) = super::super::driver_cache::path_for(&bytes, 0, true) { + let _ = std::fs::remove_file(p); + } + } + SPY_CALLS.lock().unwrap().clear(); + } + } + let mut cleanup = FixtureCleanup { + psos: Vec::new(), + blob_keys: Vec::new(), + disk_dxils: vec![shared.clone(), tail_a.clone(), tail_b.clone()], + }; + + unsafe extern "system" fn spy_create(this: *mut c_void, desc: *const c_void, _iid: *const super::GUID, out: *mut *mut c_void) -> super::HRESULT { + let d = &*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC); + SPY_CALLS.lock().unwrap().push((d.CS.BytecodeLength, !d.CachedPSO.pCachedBlob.is_null())); + let dev = ID3D12Device::from_raw_borrowed(&this).unwrap(); + match dev.CreateComputePipelineState::(d) { + Ok(pso) => { + *out = pso.into_raw(); + 0 + } + Err(e) => e.code().0, + } + } + + let base_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + let iid = &ID3D12PipelineState::IID as *const windows::core::GUID as *const super::GUID; + let plan_a = Arc::new(super::DispatchChain { pieces: vec![shared.clone(), tail_a.clone()], dwords_per_group: 4 }); + let plan_b = Arc::new(super::DispatchChain { pieces: vec![shared.clone(), tail_b.clone()], dwords_per_group: 4 }); + + let whole = Arc::new(whole); + unsafe { + let mut raw_a: *mut c_void = std::ptr::null_mut(); + let rs_a = super::build(dev.as_raw(), spy_create, &base_desc, iid, &mut raw_a, 1, whole.clone(), &[], plan_a.clone()).expect("build Program A"); + cleanup.psos.push(ID3D12PipelineState::from_raw(raw_a)); + cleanup.blob_keys.push(super::super::compute_blob_key(&shared, rs_a, 0)); + cleanup.blob_keys.push(super::super::compute_blob_key(&tail_a, rs_a, 0)); + let a_calls = std::mem::take(&mut *SPY_CALLS.lock().unwrap()); + assert_eq!(a_calls.len(), 2, "Program A should compile 2 pieces, got {a_calls:?}"); + assert!(a_calls.iter().any(|&(len, cached)| len == shared.len() && !cached), "Program A shared piece should start cold: {a_calls:?}"); + + let sigs_after_a = super::SIGNATURES.lock().unwrap().len(); + let key_shared = super::super::compute_blob_key(&shared, rs_a, 0); + let count_shared_keys = || { + super::super::COMPUTE_BLOBS.lock().unwrap().as_ref().map_or(0, |(m, _)| m.keys().filter(|k| k.0 == key_shared.0).count()) + }; + let stored_blob = count_shared_keys(); + assert!(stored_blob <= 1, "shared piece driver blob stored at most once in COMPUTE_BLOBS (0 on AMD stub-blob drivers)"); + + let plib_hits_before_b = super::PLIB_HITS.load(Ordering::Relaxed); + let mut raw_b: *mut c_void = std::ptr::null_mut(); + let rs_b = super::build(dev.as_raw(), spy_create, &base_desc, iid, &mut raw_b, 2, whole.clone(), &[], plan_b).expect("build Program B"); + cleanup.psos.push(ID3D12PipelineState::from_raw(raw_b)); + cleanup.blob_keys.push(super::super::compute_blob_key(&tail_b, rs_b, 0)); + let b_calls = std::mem::take(&mut *SPY_CALLS.lock().unwrap()); + assert_eq!(rs_b, rs_a, "Program B must reuse Program A's cached dispatch-chain root signature"); + assert_eq!(super::SIGNATURES.lock().unwrap().len(), sigs_after_a, "Program B must not allocate a new SIGNATURES entry"); + if stored_blob == 1 { + assert!( + super::PLIB_HITS.load(Ordering::Relaxed) > plib_hits_before_b + || b_calls.iter().any(|&(len, cached)| len == shared.len() && cached), + "Program B must reuse shared piece from .plib or COMPUTE_BLOBS via CachedPSO: {b_calls:?}" + ); + } + assert_eq!(count_shared_keys(), stored_blob, "Program B must not insert a duplicate COMPUTE_BLOBS entry under another root signature"); + + // Dropping and rebuilding Program A must also hit .plib or COMPUTE_BLOBS with no extra root signature. + let pso_a = cleanup.psos.remove(0); + super::forget(pso_a.as_raw() as usize); + drop(pso_a); + let plib_hits_before_a2 = super::PLIB_HITS.load(Ordering::Relaxed); + let mut raw_a2: *mut c_void = std::ptr::null_mut(); + let rs_a2 = super::build(dev.as_raw(), spy_create, &base_desc, iid, &mut raw_a2, 3, whole.clone(), &[], plan_a).expect("rebuild Program A"); + cleanup.psos.push(ID3D12PipelineState::from_raw(raw_a2)); + let a2_calls = std::mem::take(&mut *SPY_CALLS.lock().unwrap()); + assert_eq!(rs_a2, rs_a); + assert_eq!(super::SIGNATURES.lock().unwrap().len(), sigs_after_a); + if stored_blob == 1 { + assert!( + super::PLIB_HITS.load(Ordering::Relaxed) > plib_hits_before_a2 + || a2_calls.iter().any(|&(len, cached)| len == shared.len() && cached), + "rebuild must hit .plib or COMPUTE_BLOBS: {a2_calls:?}" + ); + } + assert_eq!(count_shared_keys(), stored_blob); + println!("DISPATCH_CHAIN_RS_CACHE shared_dxil={} sigs={}", shared.len(), sigs_after_a); + } + } + + #[test] + fn a_failed_whole_form_is_not_built_again() { + use std::ffi::c_void; + use std::sync::{ + atomic::{AtomicBool, AtomicU64, Ordering}, + Arc, Mutex, OnceLock, + }; + static CALLS: AtomicU64 = AtomicU64::new(0); + unsafe extern "system" fn refused(_: *mut c_void, _: *const c_void, _: *const super::GUID, _: *mut *mut c_void) -> super::HRESULT { + CALLS.fetch_add(1, Ordering::Relaxed); + crate::util::E_FAIL + } + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let signature = super::pso::dispatch_chain_root_signature(&dev, &[]).unwrap(); + let builder = Arc::new(super::PipelineBuilder { + device: dev, + create: refused, + signature, + samplers: Vec::new(), + flags: D3D12_PIPELINE_STATE_FLAG_NONE, + node: 0, + record: 0, + }); + let chain = super::Chain { + builder, + tail: Vec::new(), + words: 4, + whole_code: Arc::new(vec![0; 16]), + whole: OnceLock::new(), + whole_started: AtomicBool::new(false), + retry_at: Mutex::new(None), + signature: OnceLock::new(), + slabs: Default::default(), + warned: AtomicBool::new(false), + }; + assert!(chain.whole().is_err()); + assert!(chain.whole().is_err()); + assert_eq!(CALLS.load(Ordering::Relaxed), 1); + } + } + + #[test] + fn a_whole_form_that_ran_out_of_memory_is_tried_once_more_after_a_pause() { + use std::ffi::c_void; + use std::sync::{ + atomic::{AtomicBool, AtomicU64, Ordering}, + Arc, Mutex, OnceLock, + }; + static CALLS: AtomicU64 = AtomicU64::new(0); + unsafe extern "system" fn out_of_memory(_: *mut c_void, _: *const c_void, _: *const super::GUID, _: *mut *mut c_void) -> super::HRESULT { + CALLS.fetch_add(1, Ordering::Relaxed); + crate::util::E_OUTOFMEMORY + } + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let signature = super::pso::dispatch_chain_root_signature(&dev, &[]).unwrap(); + let builder = Arc::new(super::PipelineBuilder { + device: dev, + create: out_of_memory, + signature, + samplers: Vec::new(), + flags: D3D12_PIPELINE_STATE_FLAG_NONE, + node: 0, + record: 0, + }); + let chain = super::Chain { + builder, + tail: Vec::new(), + words: 4, + whole_code: Arc::new(vec![0; 16]), + whole: OnceLock::new(), + whole_started: AtomicBool::new(false), + retry_at: Mutex::new(None), + signature: OnceLock::new(), + slabs: Default::default(), + warned: AtomicBool::new(false), + }; + assert!(chain.whole().is_err()); + assert!(chain.whole().is_err()); + assert_eq!(CALLS.load(Ordering::Relaxed), 1); + *chain.retry_at.lock().unwrap() = Some(std::time::Instant::now()); + assert!(chain.whole().is_err()); + assert_eq!(CALLS.load(Ordering::Relaxed), 2); + *chain.retry_at.lock().unwrap() = Some(std::time::Instant::now()); + assert!(chain.whole().is_err()); + assert_eq!(CALLS.load(Ordering::Relaxed), 2); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs index 6ca0572281..c1e7efddc3 100644 --- a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs +++ b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs @@ -200,12 +200,31 @@ pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gp for (ty, payload) in subs { match ty { 0 | 19 => {} // RS replaced by ABI RS via ps_samplers; CACHED_PSO is the lookup input - 7 | 12 | 22 => { - if payload.iter().any(|&b| b != 0) { + // These descriptors can carry inert pointers and padding in a title stream. + // Their counts and flags determine whether any state needs to be hashed. + 7 => { + let state = read_state::(payload)?; + if state.NumEntries != 0 || state.NumStrides != 0 || state.RasterizedStream != 0 { + return None; + } + } + 12 => { + let state = read_state::(payload)?; + if state.NumElements != 0 { + return None; + } + } + 22 => { + let state = read_state::(payload)?; + if state.ViewInstanceCount != 0 || state.Flags.0 != 0 { return None; } } 1..=6 | 24 | 25 => { + let state = read_state::(payload)?; + if state.BytecodeLength == 0 && ty != 25 { + continue; + } let code = payload_shader(payload)?; shader_bytes = shader_bytes.checked_add(code.len())?; h.u32(ty); @@ -333,6 +352,49 @@ mod tests { } } + #[test] + fn empty_stream_descriptors_do_not_change_the_key() { + let ms = [1u8, 2, 3, 4]; + let mut base = StreamOut::default(); + base.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, &ms); + let mut with_empty = StreamOut(base.0.clone(), base.1); + with_empty.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT, &D3D12_STREAM_OUTPUT_DESC { + pSODeclaration: 0x2000 as *const _, + pBufferStrides: 0x3000 as *const _, + ..Default::default() + }); + let mut input = [0u8; std::mem::size_of::()]; + input[..8].copy_from_slice(&0x4000u64.to_le_bytes()); + let padding = std::mem::offset_of!(D3D12_INPUT_LAYOUT_DESC, NumElements) + std::mem::size_of::(); + input[padding..].fill(0xaa); + with_empty.raw(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0 as u32, &input, true); + with_empty.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING, &D3D12_VIEW_INSTANCING_DESC { + pViewInstanceLocations: 0x5000 as *const _, + ..Default::default() + }); + let empty_shader = D3D12_SHADER_BYTECODE { pShaderBytecode: 0x6000 as *const _, BytecodeLength: 0 }; + for stage in [ + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, + ] { + with_empty.put(stage, &empty_shader); + } + + unsafe { + let key = two_pass_stream_key(&base.0, &[], 1, 4).expect("base mesh key"); + assert_eq!(two_pass_stream_key(&with_empty.0, &[], 1, 4), Some(key)); + + let mut empty_ms = StreamOut::default(); + empty_ms.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, &empty_shader); + assert_eq!(two_pass_stream_key(&empty_ms.0, &[], 1, 4), None); + } + } + #[test] fn two_pass_keys_cover_mem_windows_invalid_counts_and_duplicates() { let mut s = StreamOut::default(); diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index b7560f861e..89cd5b0fb6 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -19,8 +19,8 @@ use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ffi::c_void; use std::hash::{BuildHasherDefault, Hasher}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; use windows::core::Interface; use windows::Win32::Foundation::{CloseHandle, HANDLE}; @@ -31,9 +31,14 @@ use windows_sys::Win32::System::Memory::{ PAGE_NOACCESS, PAGE_READWRITE, }; +pub mod gpu_view; + 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). A heap goes back only when every tile of it is +/// free (`State::retire_free_pools`), and a title frees its tiles in runs spread over all its +/// heaps: with heaps of 64 MiB a retail title's world load unmapped 1.5 GB of its 4.6 GB of +/// tiles and 3 of 78 heaps went back (0.2 GB); with heaps of 4 MiB 1.25 GB went back. +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; @@ -203,6 +208,13 @@ struct RetiredTiles { marks: Option>, } +struct PendingUnmap { + seq: u64, + entries: Vec<(usize, (u32, u32))>, + /// Fence marks on every known title queue (`None` = signal failed, keep mapped/held). + marks: Option>, +} + struct State { dev: ID3D12Device, queue: ID3D12CommandQueue, @@ -210,17 +222,23 @@ struct State { value: u64, /// reusable auto-reset Win32 event for fence waits (no per-wait CreateEventW/CloseHandle) event: HANDLE, - /// fence signalled on title queues so `queue` waits before copying GPU writes back to CPU + /// dedicated readback queue (NEVER waited on by title queues, so waiting on title queues + /// here cannot form a circular GPU deadlock `title_qA -> title_qB -> sparse_q -> title_qA`) + rb_queue: ID3D12CommandQueue, + /// fence signalled on title queues so `rb_queue` waits before copying GPU writes back to CPU rb_fence: ID3D12Fence, rb_value: u64, + /// fence signalled on `rb_queue` for CPU-side readback completion waits + rb_done_fence: ID3D12Fence, + rb_done_value: u64, /// (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) pools: Vec>, free: Vec<(u32, u32)>, - /// 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, rb_done_value)` + /// and a moment went by (titles' queues and `rb_queue` may still read what was mapped there) + retired: Vec<(ID3D12Heap, u64, u64, std::time::Instant)>, /// tile address → pool tile + uncommitted page hole mask + per-page sent chunk hashes mapped: FxHashMap, /// pool tiles also used by placed buffers (not freed while they are) @@ -232,10 +250,20 @@ struct State { /// decommits and commits again thousands of tiles a second, and each `UpdateTileMappings` /// took ~0.15 ms.) parked: FxHashMap, + /// parked tiles awaiting in-flight title queues before `UpdateTileMappings(NULL)` executes + pending_unmaps: VecDeque, + /// tile VA → `(pool_tile, unmap_seq)` for tiles still mapped in hardware inside `pending_unmaps`; + /// re-committing a VA cancels its pending unmap with no GPU tile-mapping change + pending_unmap_va: FxHashMap, + /// monotonic sequence id preventing ABA cancellation across repeated decommit/recommit cycles + unmap_seq: u64, /// unmapped parked pool tiles awaiting `self.queue` and in-flight title queues before entering `free` quarantined: VecDeque, - /// per-title-queue fences used to mark in-flight GPU work (`note_queue`) - queue_fences: FxHashMap, + /// unpinned unused pool tiles queued from `forget_in` (cannot signal queues under D3D12 release locks) + /// until `flush_pending_quarantine` places them behind GPU fences + pending_quarantine: Vec<(u32, u32)>, + /// per-title-queue fences used to mark in-flight GPU work (non-owning raw queue key → fence + value) + queue_fences: FxHashMap, /// placed buffers → the pool tiles they use buffers: FxHashMap>, /// reused tiles / decommitted partial pages to clear: (address, bytes) @@ -260,6 +288,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 sorted (start, end) runs (None: to be made again) runs: Option>, /// reusable buffer for dirty runs in `before_execute` (avoids per-submit heap alloc) @@ -327,11 +359,82 @@ fn push_run(out: &mut Vec<(usize, usize)>, addr: usize, len: usize) { } } -/// Scan a 4 KiB page at `pg`, appending any changed 64-byte chunk runs directly to `out` -/// (zero per-page heap allocation; skips allocating `slot` completely when a fresh zero page -/// is still all zeros). #[inline] -fn scan_page(page: &[u8], pg: usize, slot: &mut Option>, out: &mut Vec<(usize, usize)>) { +fn has_avx2() -> bool { + #[cfg(target_arch = "x86_64")] + { + static AVX2: OnceLock = OnceLock::new(); + *AVX2.get_or_init(|| std::arch::is_x86_feature_detected!("avx2")) + } + #[cfg(not(target_arch = "x86_64"))] + { + false + } +} + +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +#[inline] +unsafe fn is_chunk_zero_avx2(c: &[u8]) -> bool { + use std::arch::x86_64::{_mm256_loadu_si256, _mm256_or_si256, _mm256_testz_si256, __m256i}; + debug_assert_eq!(c.len(), CHUNK); + let p = c.as_ptr() as *const __m256i; + let v0 = _mm256_loadu_si256(p); + let v1 = _mm256_loadu_si256(p.add(1)); + let any = _mm256_or_si256(v0, v1); + _mm256_testz_si256(any, any) != 0 +} + +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn scan_page_avx2(page: &[u8], pg: usize, slot: &mut Option>, out: &mut Vec<(usize, usize)>) { + use std::arch::x86_64::{_mm256_loadu_si256, _mm256_or_si256, _mm256_testz_si256, __m256i}; + if let Some(sent) = slot.as_deref_mut() { + for (k, c) in page.chunks_exact(CHUNK).enumerate() { + if sent[k] == ZERO_HASH && is_chunk_zero_avx2(c) { + continue; + } + let h = chunk_hash(c); + if h == sent[k] { + continue; + } + sent[k] = h; + push_run(out, pg + k * CHUNK, CHUNK); + } + return; + } + // Fresh all-zero page fast path: scan 128 bytes (2 chunks) per iteration with AVX2. + let ptr = page.as_ptr() as *const __m256i; + let pairs = page.len() / (CHUNK * 2); + let mut first_nz_chunk = None; + for pair in 0..pairs { + let base = ptr.add(pair * 4); + let a = _mm256_or_si256(_mm256_loadu_si256(base), _mm256_loadu_si256(base.add(1))); + let b = _mm256_or_si256(_mm256_loadu_si256(base.add(2)), _mm256_loadu_si256(base.add(3))); + let any = _mm256_or_si256(a, b); + if _mm256_testz_si256(any, any) == 0 { + let k0 = pair * 2; + first_nz_chunk = Some(if _mm256_testz_si256(a, a) == 0 { k0 } else { k0 + 1 }); + break; + } + } + let Some(start_k) = first_nz_chunk else { return }; + for (k, c) in page.chunks_exact(CHUNK).enumerate().skip(start_k) { + if is_chunk_zero_avx2(c) { + continue; + } + let h = chunk_hash(c); + if h == ZERO_HASH { + continue; + } + let sent = slot.get_or_insert_with(|| Box::new(ZERO_HASHES)); + sent[k] = h; + push_run(out, pg + k * CHUNK, CHUNK); + } +} + +#[inline] +fn scan_page_scalar(page: &[u8], pg: usize, slot: &mut Option>, out: &mut Vec<(usize, usize)>) { if let Some(sent) = slot.as_deref_mut() { for (k, c) in page.chunks_exact(CHUNK).enumerate() { let h = chunk_hash(c); @@ -370,6 +473,254 @@ fn scan_page(page: &[u8], pg: usize, slot: &mut Option>, out: } } +/// Scan a 4 KiB page at `pg`, appending any changed 64-byte chunk runs directly to `out` +/// (zero per-page heap allocation; skips allocating `slot` completely when a fresh zero page +/// is still all zeros; uses AVX2 zero-skipping when available). +#[inline] +fn scan_page(page: &[u8], pg: usize, slot: &mut Option>, out: &mut Vec<(usize, usize)>) { + #[cfg(target_arch = "x86_64")] + if has_avx2() && page.len() == PAGE { + unsafe { + scan_page_avx2(page, pg, slot, out); + } + return; + } + scan_page_scalar(page, pg, slot, out); +} + +/// Minimum dirty pages in one `before_execute` before fanning out `scan_page` across `ScanPool`. +const PARALLEL_SCAN_PAGES: usize = 64; +const MAX_SCAN_THREADS: usize = 6; + +fn scan_threads() -> usize { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| { + if let Some(n) = std::env::var("XCL_SPARSE_SCAN_THREADS").ok().and_then(|v| v.trim().parse::().ok()) { + return n.clamp(1, 16); + } + std::thread::available_parallelism().map_or(1, |n| n.get() / 2).clamp(1, MAX_SCAN_THREADS) + }) +} + +struct ScanPoolState { + gen: u64, + active_helpers: usize, + pending_helpers: usize, + func: Option, + ctx: usize, +} + +/// Persistent worker pool for parallel dirty-page chunk scanning in `before_execute` (avoids +/// per-submit thread creation overhead while keeping tile hash state lock-free per page). +struct ScanPool { + run_lock: Mutex<()>, + state: Arc<(Mutex, Condvar, Condvar)>, + helpers: usize, +} + +impl ScanPool { + fn new(max_threads: usize) -> Self { + let helpers = max_threads.saturating_sub(1); + let state = Arc::new(( + Mutex::new(ScanPoolState { gen: 0, active_helpers: 0, pending_helpers: 0, func: None, ctx: 0 }), + Condvar::new(), + Condvar::new(), + )); + let mut spawned = 0usize; + for _ in 0..helpers { + let id = spawned; + let shared = Arc::clone(&state); + if std::thread::Builder::new() + .name(format!("xcl-sparse-scan-{id}")) + .spawn(move || { + let mut seen = 0u64; + loop { + let job = { + let mut g = shared.0.lock().unwrap(); + while g.gen == seen { + g = shared.1.wait(g).unwrap(); + } + seen = g.gen; + if id < g.active_helpers { g.func.map(|f| (f, g.ctx)) } else { None } + }; + if let Some((func, ctx)) = job { + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { func(ctx as *const c_void) })); + let mut g = shared.0.lock().unwrap(); + g.pending_helpers -= 1; + if g.pending_helpers == 0 { + shared.2.notify_one(); + } + } + } + }) + .is_ok() + { + spawned += 1; + } + } + ScanPool { run_lock: Mutex::new(()), state, helpers: spawned } + } + + fn run(&self, total_threads: usize, f: &F) { + let helpers = total_threads.saturating_sub(1).min(self.helpers); + if helpers == 0 { + f(); + return; + } + unsafe fn trampoline(ctx: *const c_void) { + (*(ctx as *const F))(); + } + let _serial = self.run_lock.lock().unwrap(); + { + let mut g = self.state.0.lock().unwrap(); + g.func = Some(trampoline::); + g.ctx = (f as *const F) as usize; + g.active_helpers = helpers; + g.pending_helpers = helpers; + g.gen = g.gen.wrapping_add(1); + self.state.1.notify_all(); + } + let caller_res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); + { + let mut g = self.state.0.lock().unwrap(); + while g.pending_helpers > 0 { + g = self.state.2.wait(g).unwrap(); + } + g.func = None; + g.ctx = 0; + g.active_helpers = 0; + } + if let Err(payload) = caller_res { + std::panic::resume_unwind(payload); + } + } +} + +fn scan_pool() -> &'static ScanPool { + static POOL: OnceLock = OnceLock::new(); + POOL.get_or_init(|| ScanPool::new(scan_threads())) +} + +/// Disjoint page work item for parallel `scan_page` execution. +#[derive(Clone, Copy)] +struct ScanItem { + pg: usize, + slot: *mut Option>, +} + +// SAFETY: `scan_dirty_pages_into` deduplicates sorted `pg` values before constructing `ScanItem`s, +// so every item owns a unique `(tile, idx)` hash slot and reads immutable title memory at `pg`. +unsafe impl Sync for ScanItem {} +unsafe impl Send for ScanItem {} + +/// Scan all write-watched `dirty` pages (sorted ascending, `page` bytes each) overlapping `mapped`, +/// appending coalesced changed 64-byte runs into `out` in ascending address order. Uses the +/// persistent `ScanPool` when at least `PARALLEL_SCAN_PAGES` mapped pages are dirty. +unsafe fn scan_dirty_pages_into( + mapped: &mut FxHashMap, + dirty: &[usize], + page: usize, + max_threads: usize, + out: &mut Vec<(usize, usize)>, +) { + if dirty.is_empty() { + return; + } + // Small dirty sets scan directly with zero intermediate allocation. + if dirty.len() < PARALLEL_SCAN_PAGES || max_threads <= 1 { + let mut i = 0; + while i < dirty.len() { + let a = dirty[i]; + let mut n = page; + i += 1; + while i < dirty.len() && dirty[i] == a + n { + n += page; + i += 1; + } + let mut x = a; + while x < a + n { + let t = x & !(TILE - 1); + let end = (t + TILE).min(a + n); + if let Some(entry) = mapped.get_mut(&t) { + let mut pg = x & !(PAGE - 1); + while pg < end { + let idx = (pg - t) / PAGE; + if entry.holes & (1u16 << idx) == 0 { + let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); + scan_page(bytes, pg, &mut entry.sent[idx], out); + } + pg += PAGE; + } + } + x = end; + } + } + return; + } + + // Collect deduplicated, ascending `(pg, &mut entry.sent[idx])` pairs once under `&mut mapped`. + let mut items: Vec = Vec::with_capacity(dirty.len()); + let mut last_pg = usize::MAX; + let mut i = 0; + while i < dirty.len() { + let a = dirty[i]; + let mut n = page; + i += 1; + while i < dirty.len() && dirty[i] == a + n { + n += page; + i += 1; + } + let mut x = a; + while x < a + n { + let t = x & !(TILE - 1); + let end = (t + TILE).min(a + n); + if let Some(entry) = mapped.get_mut(&t) { + let mut pg = x & !(PAGE - 1); + while pg < end { + if pg != last_pg { + last_pg = pg; + let idx = (pg - t) / PAGE; + if entry.holes & (1u16 << idx) == 0 { + items.push(ScanItem { pg, slot: &mut entry.sent[idx] as *mut _ }); + } + } + pg += PAGE; + } + } + x = end; + } + } + + if items.len() < PARALLEL_SCAN_PAGES { + for item in items { + let bytes = std::slice::from_raw_parts(item.pg as *const u8, PAGE); + scan_page(bytes, item.pg, &mut *item.slot, out); + } + return; + } + + let threads = max_threads.min(items.len() / 16).max(1); + let chunk_len = items.len().div_ceil(threads); + let chunks: Vec<&[ScanItem]> = items.chunks(chunk_len).collect(); + let buckets: Vec>> = (0..chunks.len()).map(|_| Mutex::new(Vec::new())).collect(); + let next = AtomicUsize::new(0); + scan_pool().run(chunks.len(), &|| loop { + let b = next.fetch_add(1, Ordering::Relaxed); + let Some(&slice) = chunks.get(b) else { break }; + let mut local = Vec::new(); + for &item in slice { + let bytes = std::slice::from_raw_parts(item.pg as *const u8, PAGE); + scan_page(bytes, item.pg, &mut *item.slot, &mut local); + } + *buckets[b].lock().unwrap() = local; + }); + for b in buckets { + for (addr, len) in b.into_inner().unwrap() { + push_run(out, addr, len); + } + } +} + /// The byte ranges (offset, length) of `page` whose 64-byte chunks differ from `sent` /// (updated to the page's chunks). pub fn changed_chunks(page: &[u8], sent: &mut [u64; CHUNKS]) -> Vec<(usize, usize)> { @@ -407,6 +758,28 @@ fn plan_ring_chunk(ring_write: u64, want: usize, cap: usize) -> (u64, usize) { // D3D12 objects are free-threaded; staging pointers and event handle are only used under STATE lock unsafe impl Send for State {} +/// Wait for `fence` to reach `target` using a reusable auto-reset `event`, bounded by `timeout`. +/// Resets `event` before arming and loops until `GetCompletedValue() >= target` or the deadline +/// expires, so a late completion from an earlier timed-out wait cannot satisfy a newer wait early. +/// (As in #1419 by gridoe and #2821 for `main`, same signature, so the two merge as one.) +unsafe fn wait_fence_until(fence: &ID3D12Fence, event: HANDLE, target: u64, timeout: std::time::Duration) -> bool { + if target == 0 || fence.GetCompletedValue() >= target { + return true; + } + let _ = windows::Win32::System::Threading::ResetEvent(event); + let _ = fence.SetEventOnCompletion(target, event); + let deadline = std::time::Instant::now() + timeout; + while fence.GetCompletedValue() < target { + let rem = deadline.saturating_duration_since(std::time::Instant::now()); + if rem.is_zero() { + return false; + } + let ms = rem.as_millis().clamp(1, u32::MAX as u128) as u32; + windows::Win32::System::Threading::WaitForSingleObject(event, ms); + } + true +} + static STATE: Mutex> = Mutex::new(None); /// The state's queue again, outside `STATE` (`queue`). `STATE` is held around D3D12 calls (an @@ -416,6 +789,18 @@ static STATE: Mutex> = Mutex::new(None); static QUEUE: Mutex> = Mutex::new(None); /// (bytes of video memory in pool heaps, of those mapped) – `XCL_ACTIVITY` +/// Bytes of the pool heaps given back but not released yet (titles' queues may still read +/// them): memory accounting, #2688. +pub fn retired_bytes() -> usize { + lock_state().as_ref().map_or(0, |s| s.retired.len() * POOL_TILES as usize * TILE) +} + +/// Bytes of the title's pages committed in the sparse windows (their CPU side): memory +/// accounting, #2688. +pub fn committed_bytes() -> usize { + lock_state().as_ref().map_or(0, |s| s.committed_bytes()) +} + pub fn pool_bytes() -> (usize, usize) { let g = lock_state(); let Some(s) = g.as_ref() else { return (0, 0) }; @@ -515,6 +900,9 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { return Vec::new(); } let Some(r) = r else { return Vec::new() }; + if super::real::dred_on() { + super::real::name_resource(r.as_raw(), &format!("xcl sparse window {k}")); + } out.push((k, r.clone().into_raw() as usize, r.GetGPUVirtualAddress())); windows.push((base, r)); } @@ -523,8 +911,10 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { } let made = (|| -> windows::core::Result { let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; + let rb_queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let rb_done_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None)?; let mut slots = Vec::with_capacity(UPLOAD_SLOTS); for _ in 0..UPLOAD_SLOTS { @@ -541,14 +931,18 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { 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 _ = rb_queue.SetName(windows::core::w!("xcl sparse readback queue")); Ok(State { dev: dev.clone(), queue, fence, value: 0, event, + rb_queue, rb_fence, rb_value: 0, + rb_done_fence, + rb_done_value: 0, windows, pools: Vec::new(), free: Vec::new(), @@ -556,7 +950,11 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + pending_unmaps: VecDeque::new(), + pending_unmap_va: FxHashMap::default(), + unmap_seq: 0, quarantined: VecDeque::new(), + pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), to_zero: Vec::new(), @@ -573,6 +971,8 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: std::sync::atomic::AtomicBool::new(false), + mapped_value: 0, runs: None, scratch_runs: Vec::new(), }) @@ -606,6 +1006,7 @@ impl State { } unsafe fn take_tile(&mut self) -> Option<((u32, u32), bool)> { + self.flush_pending_quarantine(); self.drain_quarantined(); if self.free.is_empty() && self.flush_parked() { self.drain_quarantined(); @@ -614,10 +1015,10 @@ impl State { return Some((t, true)); } // a pool retired a moment ago (its last tile came free) is taken back before a new - // 64 MB heap is made: freeing and allocating a tile in turn made a new pool each time, + // 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), so this is no less safe than reusing a tile of a pool in use. - 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)); } @@ -654,13 +1055,14 @@ impl State { h } - /// Pools whose every tile is free again go (64 MB of video memory each – and as much of the + /// Pools whose every tile is free again go (their video memory – and as much of the /// system's commit: a retail game's homes of physical pages left 0.75 GB of pools for /// 0.29 GB of tiles in use). Call after their tiles are unmapped and signalled. fn retire_free_pools(&mut self) { let now = std::time::Instant::now(); let done = unsafe { self.fence.GetCompletedValue() }; - self.retired.retain(|(_, v, at)| !(done >= *v && now.duration_since(*at).as_secs() >= 2)); + let rb_done = unsafe { self.rb_done_fence.GetCompletedValue() }; + self.retired.retain(|(_, v, rb_v, at)| !(done >= *v && rb_done >= *rb_v && now.duration_since(*at).as_secs() >= 2)); if self.free.len() < POOL_TILES as usize { return; } @@ -668,14 +1070,15 @@ impl State { for &(h, _) in &self.free { count[h as usize] += 1; } - let gone: Vec = (0..count.len()).filter(|&h| count[h] == POOL_TILES && self.pools[h].is_some()).collect(); - if gone.is_empty() { + // (a flag a pool: a title's world load frees hundreds of pools' worth of tiles at once) + let gone: Vec = (0..count.len()).map(|h| count[h] == POOL_TILES && self.pools[h].is_some()).collect(); + if !gone.contains(&true) { return; } - self.free.retain(|&(h, _)| !gone.contains(&(h as usize))); - for h in gone { + self.free.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)); + self.retired.push((heap, self.value, self.rb_done_value, now)); } } } @@ -686,6 +1089,7 @@ impl State { if tiles.is_empty() { return; } + self.mapping_queued.store(true, Ordering::Relaxed); let mut by_heap: FxHashMap> = FxHashMap::default(); for &(a, (h, t)) in tiles { by_heap.entry(h).or_default().push((((a - res_base) / TILE) as u32, t)); @@ -716,6 +1120,7 @@ impl State { counts.push(run); i += run as usize; } + let flight_t = std::time::Instant::now(); self.queue.UpdateTileMappings( res, coords.len() as u32, @@ -728,6 +1133,7 @@ impl State { Some(counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE, ); + super::flight::tile_map("sparse", windows::core::Interface::as_raw(&self.queue) as usize, (counts.iter().map(|&c| c as u64).sum::()) as u64, flight_t.elapsed()); } } @@ -735,6 +1141,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()); @@ -754,6 +1161,7 @@ impl State { counts.push(run); i += run as usize; } + let flight_t = std::time::Instant::now(); self.queue.UpdateTileMappings( res, coords.len() as u32, @@ -766,6 +1174,14 @@ impl State { Some(counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE, ); + super::flight::tile_map("sparse", windows::core::Interface::as_raw(&self.queue) as usize, (counts.iter().map(|&c| c as u64).sum::()) as u64, flight_t.elapsed()); + } + + /// Bytes of the title's pages committed in the windows: the pages of the mapped tiles that + /// are not holes. A tile the title decommitted whole is not mapped any more, though its pool + /// tile may still be parked (memory accounting, #2688). + fn committed_bytes(&self) -> usize { + self.mapped.values().map(|e| PAGES_PER_TILE - e.holes.count_ones() as usize).sum::() * PAGE } /// tiles of `[a, a + n)` get video memory (mapped in their window); `initial_holes` supplies @@ -782,7 +1198,7 @@ impl State { while t < end { if !self.mapped.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) { + if let Some(tile) = self.parked.remove(&t).or_else(|| self.pending_unmap_va.remove(&t).map(|(tile, _)| tile)) { self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t))); self.runs = None; self.to_zero.push((t, TILE)); @@ -827,6 +1243,10 @@ 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; + } + super::flight::signaled("sparse", windows::core::Interface::as_raw(&self.queue) as usize, &self.fence, self.value); } #[inline] @@ -834,11 +1254,39 @@ impl State { if target == 0 || self.fence.GetCompletedValue() >= target { return; } - let _ = self.fence.SetEventOnCompletion(target, self.event); - windows::Win32::System::Threading::WaitForSingleObject(self.event, 5000); - if self.fence.GetCompletedValue() < target { + if !wait_fence_until(&self.fence, self.event, target, std::time::Duration::from_secs(5)) { crate::xlog_warn!("sparse: the queue has not reached fence value {target} after 5 s (at {})", self.fence.GetCompletedValue()); + super::real::stop_if_device_removed(); + } + } + + #[inline] + unsafe fn order_rb_after_uploads(&self) { + if self.value > 0 && self.fence.GetCompletedValue() < self.value { + let _ = self.rb_queue.Wait(&self.fence, self.value); + } + } + + #[inline] + unsafe fn signal_rb(&mut self) { + self.rb_done_value += 1; + let _ = self.rb_queue.Signal(&self.rb_done_fence, self.rb_done_value); + super::flight::signaled("sparse readback", windows::core::Interface::as_raw(&self.rb_queue) as usize, &self.rb_done_fence, self.rb_done_value); + } + + /// Whether `rb_done_fence` reached `target` within 5 s: if not, the staging bytes are not the + /// readback yet and must not be copied out. + #[inline] + unsafe fn wait_for_rb(&self, target: u64) -> bool { + if wait_fence_until(&self.rb_done_fence, self.event, target, std::time::Duration::from_secs(5)) { + return true; } + crate::xlog_warn!( + "sparse: the readback queue has not reached fence value {target} after 5 s (at {})", + self.rb_done_fence.GetCompletedValue() + ); + super::real::stop_if_device_removed(); + false } #[inline] @@ -908,6 +1356,9 @@ impl State { ) .ok()?; let r = r?; + if super::real::dred_on() { + super::real::name_resource(r.as_raw(), "xcl sparse staging"); + } let mut p = std::ptr::null_mut(); r.Map(0, None, Some(&mut p)).ok()?; self.staging = Some((r, p as *mut u8)); @@ -935,6 +1386,9 @@ impl State { return false; } let Some(r) = r else { return false }; + if super::real::dred_on() { + super::real::name_resource(r.as_raw(), "xcl sparse zero"); + } let mut p = std::ptr::null_mut(); if r.Map(0, None, Some(&mut p)).is_err() { return false; @@ -962,6 +1416,9 @@ impl State { ) .ok()?; let r = r?; + if super::real::dred_on() { + super::real::name_resource(r.as_raw(), "xcl sparse readback"); + } let mut p = std::ptr::null_mut(); r.Map(0, None, Some(&mut p)).ok()?; self.readback = Some((r, p as *mut u8)); @@ -1022,26 +1479,35 @@ impl State { /// `sent` hashes. Caller has already ordered `self.queue` after any GPU writes if needed. unsafe fn readback_ranges(&mut self, ranges: &[(usize, usize)]) { let Some((rb, p)) = self.readback_buf() else { return }; - let mut pending: Vec<(usize, usize, usize)> = Vec::new(); // (va, rb_off, chunk) + // (va, rb_off, len, pre-wait 64-byte chunk hashes of committed pages) + let mut pending: Vec<(usize, usize, usize, Vec>)> = Vec::new(); let mut used = 0usize; let mut open = false; - let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize)>, used: &mut usize, p: *mut u8| { + let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize, Vec>)>, used: &mut usize, p: *mut u8| { if *open { *open = false; + s.order_rb_after_uploads(); if s.rb_list.Close().is_ok() { if let Ok(l) = s.rb_list.cast::() { super::title_textures::own_work(|| { - s.queue.ExecuteCommandLists(&[Some(l)]); + s.rb_queue.ExecuteCommandLists(&[Some(l)]); }); } } - s.signal(); - s.rb_last_fence = s.value; - s.wait_for(s.value); + s.signal_rb(); + s.rb_last_fence = s.rb_done_value; + let done = s.wait_for_rb(s.rb_done_value); s.reclaim_ring(); + if !done { + // the GPU copy has not run: nothing to copy back yet + pending.clear(); + } } - for &(dst, off, len) in pending.iter() { - // copy only committed (non-hole) bytes + for (dst, off, len, snap) in pending.iter() { + let (dst, off, len) = (*dst, *off, *len); + let snap_base = dst & !(CHUNK - 1); + // Copy only committed (non-hole) 64-byte chunks whose host memory did not change + // during the GPU readback wait, so concurrent CPU writes are never clobbered. let mut at = dst; let mut src_off = off; let end = dst + len; @@ -1049,14 +1515,36 @@ impl State { let pg = at & !(PAGE - 1); let t = pg & !(TILE - 1); let idx = (pg - t) / PAGE; - let step = (pg + PAGE).min(end) - at; - if s.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << idx) == 0) { - std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); + let page_end = (pg + PAGE).min(end); + if let Some(entry) = s.mapped.get_mut(&t).filter(|e| e.holes & (1u16 << idx) == 0) { + while at < page_end { + let chunk_va = at & !(CHUNK - 1); + let chunk_end = (chunk_va + CHUNK).min(page_end); + let step = chunk_end - at; + let snap_i = (chunk_va - snap_base) / CHUNK; + let unchanged = snap.get(snap_i).copied().flatten().is_some_and(|expected| { + chunk_hash(std::slice::from_raw_parts(chunk_va as *const u8, CHUNK)) == expected + }); + if unchanged { + std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); + let new_h = chunk_hash(std::slice::from_raw_parts(chunk_va as *const u8, CHUNK)); + let k = (chunk_va - pg) / CHUNK; + if let Some(sent) = entry.sent[idx].as_deref_mut() { + sent[k] = new_h; + } else if new_h != ZERO_HASH { + let sent = entry.sent[idx].insert(Box::new(ZERO_HASHES)); + sent[k] = new_h; + } + } + at += step; + src_off += step; + } + } else { + let step = page_end - at; + at += step; + src_off += step; } - at += step; - src_off += step; } - s.sync_sent_range(dst, len); } pending.clear(); *used = 0; @@ -1082,13 +1570,28 @@ impl State { let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; let chunk = (n - done).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); if !open { - self.wait_for(self.rb_last_fence); + self.wait_for_rb(self.rb_last_fence); let _ = self.rb_alloc.Reset(); let _ = self.rb_list.Reset(&self.rb_alloc, None); open = true; } + let snap_base = cur & !(CHUNK - 1); + let snap_end = (cur + chunk).saturating_add(CHUNK - 1) & !(CHUNK - 1); + let mut snap = Vec::with_capacity((snap_end - snap_base) / CHUNK); + let mut c = snap_base; + while c < snap_end { + let pg = c & !(PAGE - 1); + let t = pg & !(TILE - 1); + let idx = (pg - t) / PAGE; + if self.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << idx) == 0) { + snap.push(Some(chunk_hash(std::slice::from_raw_parts(c as *const u8, CHUNK)))); + } else { + snap.push(None); + } + c += CHUNK; + } self.rb_list.CopyBufferRegion(&rb, used as u64, &self.windows[wi].1, (cur - b) as u64, chunk as u64); - pending.push((cur, used, chunk)); + pending.push((cur, used, chunk, snap)); used += chunk; done += chunk; } @@ -1135,6 +1638,15 @@ impl State { /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via /// the 64 MiB ring staging buffer (zero CPU stall on the common path). unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) { + self.upload_runs(runs, &|at, p, n| { + std::ptr::copy_nonoverlapping(at as *const u8, p, n); + true + }); + } + + /// Copies `runs` (address in a window, bytes) into video memory; `read(address, to, bytes)` + /// gives their bytes (false: the run's piece is left as it is). + unsafe fn upload_runs(&mut self, runs: &[(usize, usize)], read: &dyn Fn(usize, *mut u8, usize) -> bool) { if runs.is_empty() { return; } @@ -1181,7 +1693,10 @@ impl State { } }; let dst_off = (aligned as usize) % STAGING; - std::ptr::copy_nonoverlapping(cur as *const u8, p.add(dst_off), chunk); + if !read(cur, p.add(dst_off), chunk) { + done += chunk; + continue; + } let staging_res = &self.staging.as_ref().unwrap().0; self.slots[slot_idx].list.CopyBufferRegion(&self.windows[wi].1, (cur - b) as u64, staging_res, dst_off as u64, chunk as u64); self.ring_write = aligned + chunk as u64; @@ -1208,6 +1723,101 @@ pub unsafe fn alloc(size: usize, align: usize) -> Option<(usize, usize)> { Some((addr, rounded)) } +/// `alloc` for the title's own memory: its CPU pages are committed when the CPU first touches +/// them (`commit_title`). +pub unsafe fn alloc_title(size: usize, align: usize) -> Option<(usize, usize)> { + let u = crate::gpu::uma::get()?; + let (addr, rounded) = u.sparse_alloc(size, align)?; + if commit_title(addr, rounded, PAGE_READWRITE).is_null() { + u.sparse_release(addr); + return None; + } + Some((addr, rounded)) +} + +/// The title commits `[a, a + n)` in a sparse window with the protection `protect`: as +/// `committed`, but the CPU's copy of a whole 64 KiB page is made when the CPU first touches it +/// (`kernelx::lazy`). Returns the address, or null as VirtualAlloc does. +/// +/// A title page in a sparse window was committed on the CPU as well as mapped to a tile of +/// video memory. A retail title's render targets, depth buffers and GPU-written buffers there +/// took system memory and commit the CPU never touched, and each write-watch look walked them +/// (2-4 GB of tiles, ~5 ms a look, ~90 looks a second). Such a page's tile is now video memory +/// only (all holes: the look leaves it out and no upload writes it) until the CPU's first +/// access commits the page (zeros, as a new commit holds); from then on its writes are watched +/// and uploaded as before. Pages at the ends that do not fill a 64 KiB page, pages already +/// committed, another protection than read-write, and commits before the device exists are +/// committed now, as before. +pub unsafe fn commit_title(a: usize, n: usize, protect: u32) -> *mut c_void { + let eager = |a: usize, n: usize| -> bool { + if n == 0 { + return true; + } + if VirtualAlloc(a as *const c_void, n, MEM_COMMIT, protect).is_null() { + return false; + } + committed(a, n); + true + }; + let (lo, hi) = ((a + TILE - 1) & !(TILE - 1), a.saturating_add(n) & !(TILE - 1)); + if protect != PAGE_READWRITE || hi <= lo || lock_state().is_none() { + return if eager(a, n) { a as *mut c_void } else { std::ptr::null_mut() }; + } + if !eager(a, lo - a) || !eager(hi, a + n - hi) { + return std::ptr::null_mut(); + } + // the pages committed already (the title commits a range again) stay as they are + let mut lazy: Vec<(usize, usize)> = Vec::new(); + let mut at = lo; + while at < hi { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 { + return std::ptr::null_mut(); + } + let end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi).max(at + PAGE); + if m.State == MEM_COMMIT { + committed(at, end - at); + } else { + // whole 64 KiB pages lazy; a part of one at either end now + let s = ((at + TILE - 1) & !(TILE - 1)).min(end); + let e = (end & !(TILE - 1)).max(s); + if !eager(at, s - at) { + return std::ptr::null_mut(); + } + if e > s { + lazy.push((s, e - s)); + } + if !eager(e, end - e) { + return std::ptr::null_mut(); + } + } + at = end; + } + { + let mut g = lock_state(); + let Some(s) = g.as_mut() else { return std::ptr::null_mut() }; + for &(p, len) in &lazy { + s.ensure_mapped(p, len, |_| 0xFFFF); + } + } + // (marked after their tiles are mapped: a first touch finds them, `drain_lazy_commits`) + for &(p, len) in &lazy { + for page in (p..p + len).step_by(TILE) { + crate::hle::kernelx::lazy::mark(page); + } + LAZY_BYTES.fetch_add(len as u64, Ordering::Relaxed); + } + a as *mut c_void +} + +/// Bytes of the title's commits in the sparse windows that `commit_title` left lazy so far +/// (some of them committed since by a first touch, some decommitted). +pub fn lazy_title_bytes() -> u64 { + LAZY_BYTES.load(Ordering::Relaxed) +} + +static LAZY_BYTES: AtomicU64 = AtomicU64::new(0); + /// Allocate a zeroed, write-watched block strictly inside sparse window `window` (e.g. /// window 0 for 32-bit-addressed descriptor heaps). Returns `(address, rounded_size)`. pub unsafe fn alloc_in(window: usize, size: usize, align: usize) -> Option<(usize, usize)> { @@ -1235,6 +1845,69 @@ pub unsafe fn free(p: usize) -> bool { u.sparse_release(p).is_some() } +/// 64 KiB sparse pages lazily committed by `kernelx::lazy` when the title first CPU-touches a +/// `alloc_vram_only` buffer (queued without locking `STATE` so the VEH can never deadlock). +static LAZY_COMMITS: Mutex> = Mutex::new(Vec::new()); +static HAS_LAZY_COMMITS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Record that `kernelx::lazy` just CPU-committed 64 KiB page `page`. Safe inside the VEH: +/// never acquires `STATE`. +pub(crate) fn note_lazy_commit(page: usize) { + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(page)) { + LAZY_COMMITS.lock().unwrap_or_else(|e| e.into_inner()).push(page); + HAS_LAZY_COMMITS.store(true, Ordering::Release); + } +} + +/// Allocate a VRAM-only sparse block (zero upfront CPU commit, `holes = 0xFFFF` so CPU +/// write-watch never overwrites GPU UAV writes) for GPU-writable buffers placed outside the UMA +/// windows. Each 64 KiB page is marked with `kernelx::lazy` so if the title later CPU-writes or +/// reads it (via `GetGPUVirtualAddress()` or `Map()`, #2582), the page commits on demand and +/// subsequent CPU writes upload cleanly to sparse VRAM. +pub unsafe fn alloc_vram_only(size: usize, align: usize) -> Option<(usize, usize)> { + let u = crate::gpu::uma::get()?; + let (addr, rounded) = u.sparse_alloc(size, align.max(TILE))?; + let ok = { + let mut g = lock_state(); + if let Some(s) = g.as_mut() { + s.ensure_mapped(addr, rounded, |_| 0xFFFF); + let last_tile = (addr + rounded - 1) & !(TILE - 1); + if s.mapped.contains_key(&addr) && s.mapped.contains_key(&last_tile) { + true + } else { + s.decommit_range(addr, rounded); + false + } + } else { + false + } + }; + if !ok { + u.sparse_release(addr); + return None; + } + for page in (addr..addr + rounded).step_by(TILE) { + crate::hle::kernelx::lazy::mark(page); + } + Some((addr, rounded)) +} + +/// Release a VRAM-only sparse block from `alloc_vram_only` (unmarks lazy pages, defers tile +/// unmap behind GPU fences, and decommits any pages that were lazily committed by CPU access). +pub unsafe fn free_vram_only(p: usize) -> bool { + let Some(u) = crate::gpu::uma::get() else { return false }; + if !u.is_sparse(p) { + return false; + } + let Some((start, len)) = u.sparse_reservation(p).filter(|&(start, _)| start == p) else { return false }; + for page in (start..start + len).step_by(TILE) { + crate::hle::kernelx::lazy::unmark(page); + } + decommitted(start, len); + VirtualFree(start as *mut c_void, len, MEM_DECOMMIT); + u.sparse_release(p).is_some() +} + /// After `queue.ExecuteCommandLists`: copy GPU-written sparse ranges (e.g. `Write32/64`, /// `FillMemoryWith32BitValueX`, `CopyMemoryToMemoryX`) back to their CPU view so CPU reads /// and spin-waits see the GPU writes without clobbering `sent` hashes. @@ -1250,7 +1923,7 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz } let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; - s.note_queue(queue); + s.drain_lazy_commits(); let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); if filtered.is_empty() { return; @@ -1266,59 +1939,362 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz _ => merged.push((a, n)), } } - s.rb_value += 1; - let v = s.rb_value; - if queue.Signal(&s.rb_fence, v).is_ok() { - 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); + if let Some((f, v)) = readback_after(&s.rb_queue, queue) { + super::list_x::note_internal_wait(s.rb_queue.as_raw() as usize, "sparse readback behind a title queue", &f, v); } s.readback_ranges(&merged); } -/// 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. -pub unsafe fn readback_now(va: usize, len: usize) { - if len == 0 { - return; - } - let mut g = lock_state(); - let Some(s) = g.as_mut() else { return }; - if s.window_index(va).is_none() { - return; - } - let zeroed = 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); +/// The sparse readback queue `rb_queue` waits until `q` has done what it was given so far, on a +/// fence of `q`'s own: (fence, value), None if `q` could not signal it. +/// +/// One fence for all the title's queues, each signalling the next value, went back down: a queue +/// signals 11 and is done, another one still busy signals 10 after it – and the readback queue's +/// wait for 11 never ended. A retail title's frames stopped behind it (every title queue idle, +/// the readback queue stuck with work pending until the device was removed). A queue runs its +/// work in order, so the values of its own fence only go up. +unsafe fn readback_after(rb_queue: &ID3D12CommandQueue, q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> { + static FENCES: Mutex>> = Mutex::new(None); + let key = q.as_raw() as usize; + let mut g = FENCES.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + if !m.contains_key(&key) { + let mut dev: Option = None; + q.GetDevice(&mut dev).ok()?; + let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + m.insert(key, (f, 0)); } - // 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 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(p as *const u8, PAGE); - scan_page(bytes, p, &mut entry.sent[idx], &mut dirty_runs); + let e = m.get_mut(&key)?; + e.1 += 1; + q.Signal(&e.0, e.1).ok()?; + let _ = rb_queue.Wait(&e.0, e.1); + Some((e.0.clone(), e.1)) +} + +/// Pooled per-`Map` synchronous readback resources so concurrent `ID3D12Resource::Map` readbacks +/// record, submit, and GPU-wait OUTSIDE the global `STATE` lock (avoiding `STATE` convoy stalls). +struct ReadbackJob { + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + buf: ID3D12Resource, + event: HANDLE, + mapped: usize, + cap: usize, + dev_key: usize, +} + +unsafe impl Send for ReadbackJob {} + +impl Drop for ReadbackJob { + fn drop(&mut self) { + if !self.event.is_invalid() { + unsafe { let _ = windows::Win32::Foundation::CloseHandle(self.event); } + } + } +} + +const MAX_RB_JOBS: usize = 16; +const MIN_RB_JOB_BYTES: usize = 256 << 10; +static FREE_RB_JOBS: Mutex> = Mutex::new(Vec::new()); + +/// A job whose readback was still queued on the GPU when `readback_now` gave up waiting: its +/// buffer, allocator and list stay alive until `fence` reaches `value`. Dropped earlier, the copy +/// still runs later and writes into freed memory (under RADV: a GPU page fault, CPG write). +struct InFlightRbJob { + job: ReadbackJob, + fence: ID3D12Fence, + value: u64, +} + +// SAFETY: ID3D12Fence is a free-threaded COM object; `ReadbackJob` is `Send`. +unsafe impl Send for InFlightRbJob {} + +static IN_FLIGHT_RB_JOBS: Mutex> = Mutex::new(Vec::new()); + +/// Keep `job` until its GPU readback (`fence` >= `value`) is done. +fn keep_in_flight_readback_job(job: ReadbackJob, fence: ID3D12Fence, value: u64) { + IN_FLIGHT_RB_JOBS.lock().unwrap().push(InFlightRbJob { job, fence, value }); +} + +/// Jobs kept by `keep_in_flight_readback_job` whose readback has finished go back to the pool. +unsafe fn reclaim_in_flight_readback_jobs() { + let done: Vec = { + let mut v = IN_FLIGHT_RB_JOBS.lock().unwrap(); + if v.is_empty() { + return; + } + let (done, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut *v).into_iter().partition(|j| j.fence.GetCompletedValue() >= j.value); + *v = keep; + done.into_iter().map(|j| j.job).collect() + }; + for job in done { + return_readback_job(job); + } +} + +unsafe fn take_readback_job(dev: &ID3D12Device, need: usize) -> Option { + let dev_key = dev.as_raw() as usize; + let want = need.max(MIN_RB_JOB_BYTES).min(READBACK_STAGING); + reclaim_in_flight_readback_jobs(); + { + let mut free = FREE_RB_JOBS.lock().unwrap(); + if let Some(i) = free.iter().position(|j| j.dev_key == dev_key && j.cap >= want) { + return Some(free.swap_remove(i)); + } + } + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).ok()?; + let _ = list.Close(); + let mut d = buffer_desc(want 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 = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).ok()?; + if p.is_null() { + return None; + } + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).ok()?; + Some(ReadbackJob { alloc, list, buf, event, mapped: p as usize, cap: want, dev_key }) +} + +fn return_readback_job(job: ReadbackJob) { + let mut free = FREE_RB_JOBS.lock().unwrap(); + if free.len() < MAX_RB_JOBS { + free.push(job); + } +} + +/// Apply GPU readback bytes for `[dst, dst + len)` into host memory, comparing each 64-byte +/// chunk's current host bytes against its Phase-1 `snap_hashes` entry so any chunk modified by +/// the CPU during the GPU wait is NOT clobbered (and its `sent` hash remains stale so the next +/// `before_execute` uploads the CPU's write). Updates `snap_hashes` for copied chunks so a +/// multi-batch readback splitting a 64-byte chunk across `job.cap` preserves continuity. +unsafe fn apply_readback_preserving_cpu_writes( + dst: usize, + src: *const u8, + len: usize, + snap_base: usize, + snap_hashes: &mut [u64], + mapped: &mut FxHashMap, +) { + let mut at = dst; + let mut src_off = 0usize; + let end = dst + len; + while at < end { + let pg = at & !(PAGE - 1); + let t = pg & !(TILE - 1); + let page_idx = (pg - t) / PAGE; + let page_end = (pg + PAGE).min(end); + if let Some(entry) = mapped.get_mut(&t).filter(|e| e.holes & (1u16 << page_idx) == 0) { + while at < page_end { + let chunk_va = at & !(CHUNK - 1); + let chunk_end = (chunk_va + CHUNK).min(page_end); + let step = chunk_end - at; + let snap_i = (chunk_va - snap_base) / CHUNK; + if let Some(expected) = snap_hashes.get_mut(snap_i) { + let cur_slice = std::slice::from_raw_parts(chunk_va as *const u8, CHUNK); + if chunk_hash(cur_slice) == *expected { + std::ptr::copy_nonoverlapping(src.add(src_off), at as *mut u8, step); + let new_h = chunk_hash(std::slice::from_raw_parts(chunk_va as *const u8, CHUNK)); + *expected = new_h; + let k = (chunk_va - pg) / CHUNK; + if let Some(sent) = entry.sent[page_idx].as_deref_mut() { + sent[k] = new_h; + } else if new_h != ZERO_HASH { + let sent = entry.sent[page_idx].insert(Box::new(ZERO_HASHES)); + sent[k] = new_h; + } + } } - p += PAGE; + at += step; + src_off += step; } + } else { + let step = page_end - at; + at += step; + src_off += step; } - pg = tile_end; } - if !dirty_runs.is_empty() { - s.upload_dirty(&dirty_runs); +} + +/// 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, orders +/// `s.queue` behind active title queues via `rb_fence` before copying, and copies the range +/// back from VRAM into CPU memory using a per-call pooled `ReadbackJob` whose GPU fence wait +/// runs OUTSIDE the global `STATE` lock without clobbering concurrent CPU writes. +pub unsafe fn readback_now(va: usize, len: usize) { + if len == 0 { + return; } - s.readback_ranges(&[(va, len)]); + let end = va.saturating_add(len); + let snap_base = va & !(CHUNK - 1); + let snap_end = end.saturating_add(CHUNK - 1) & !(CHUNK - 1); + let snap_count = (snap_end - snap_base) / CHUNK; + + // 1. Flush pending clears & dirty CPU chunks under `STATE`, snapshot Phase-1 64-byte chunk + // hashes, collect mapped spans, then release `STATE` before recording/waiting so other + // `Map` threads and `before_execute` never stall. + let (dev, spans, mut snap_hashes): (ID3D12Device, Vec<(usize, ID3D12Resource, u64, usize)>, Vec) = { + let mut g = lock_state(); + let Some(s) = g.as_mut() else { return }; + if s.window_index(va).is_none() { + return; + } + s.drain_lazy_commits(); + let zeroed = 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)` and snapshot + // each 64-byte chunk's Phase-1 hash so Phase 3 never clobbers concurrent CPU writes. + let mut dirty_runs: Vec<(usize, usize)> = Vec::new(); + let mut snap_hashes = vec![ZERO_HASH; snap_count]; + let mut pg = va & !(PAGE - 1); + 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 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(p as *const u8, PAGE); + scan_page(bytes, p, &mut entry.sent[idx], &mut dirty_runs); + if let Some(sent) = entry.sent[idx].as_deref() { + let lo = va.saturating_sub(p) / CHUNK; + let hi = (end.min(p + PAGE) - p).div_ceil(CHUNK).min(CHUNKS); + for k in lo..hi { + let snap_i = (p + k * CHUNK - snap_base) / CHUNK; + if let Some(dst_h) = snap_hashes.get_mut(snap_i) { + *dst_h = sent[k]; + } + } + } + } + p += PAGE; + } + } + pg = tile_end; + } + if !dirty_runs.is_empty() { + s.upload_dirty(&dirty_runs); + } + let mut spans = Vec::new(); + let mut done = 0usize; + while done < len { + let cur = va + done; + let tile = cur & !(TILE - 1); + let Some(wi) = s.window_index(cur) else { break }; + let b = s.windows[wi].0; + let to_tile_end = (tile + TILE) - cur; + if !s.mapped.contains_key(&tile) { + done += (len - done).min(to_tile_end); + continue; + } + let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; + let chunk = (len - done).min(to_tile_end).min(to_win_end); + spans.push((cur, s.windows[wi].1.clone(), (cur - b) as u64, chunk)); + done += chunk; + } + if spans.is_empty() { + return; + } + (s.dev.clone(), spans, snap_hashes) + }; + + let total_need: usize = spans.iter().map(|s| s.3).sum(); + let Some(job) = take_readback_job(&dev, total_need) else { + let mut g = lock_state(); + if let Some(s) = g.as_mut() { + s.wait_title_queues_for_readback(); + s.readback_ranges(&[(va, len)]); + } + return; + }; + + let mut idx = 0usize; + let mut sub_off = 0usize; + let mut pending: Vec<(usize, usize, usize)> = Vec::new(); + let mut waited_title_queues = false; + while idx < spans.len() { + let mut used = 0usize; + pending.clear(); + if job.alloc.Reset().is_err() || job.list.Reset(&job.alloc, None).is_err() { + break; + } + while idx < spans.len() && used < job.cap { + let (dst, ref win_buf, src_base, span_len) = spans[idx]; + let rem = span_len - sub_off; + let take = rem.min(job.cap - used); + job.list.CopyBufferRegion(&job.buf, used as u64, win_buf, src_base + sub_off as u64, take as u64); + pending.push((dst + sub_off, used, take)); + used += take; + sub_off += take; + if sub_off >= span_len { + idx += 1; + sub_off = 0; + } + } + if pending.is_empty() || job.list.Close().is_err() { + break; + } + let Ok(cmd_list) = job.list.cast::() else { break }; + // 2. Order `s.rb_queue` behind pending sparse uploads and active title queues via + // `rb_fence`, then submit & signal atomically under `STATE` and release `STATE` BEFORE + // waiting on `rb_done_fence`. (`s.queue` never waits on title queues, preventing a + // `title_qA -> title_qB -> s.queue -> title_qA` circular GPU deadlock.) + let wait_target = { + let mut g = lock_state(); + let Some(s) = g.as_mut() else { break }; + s.order_rb_after_uploads(); + if !waited_title_queues { + s.wait_title_queues_for_readback(); + waited_title_queues = true; + } + super::title_textures::own_work(|| { + s.rb_queue.ExecuteCommandLists(&[Some(cmd_list)]); + }); + s.signal_rb(); + (s.rb_done_fence.clone(), s.rb_done_value) + }; + if wait_target.1 > 0 && wait_target.0.GetCompletedValue() < wait_target.1 { + if !wait_fence_until(&wait_target.0, job.event, wait_target.1, std::time::Duration::from_secs(5)) { + crate::xlog_warn!( + "sparse: readback_now queue has not reached fence value {} after 5 s (at {})", + wait_target.1, + wait_target.0.GetCompletedValue() + ); + super::real::stop_if_device_removed(); + // the copy is still queued: keep its buffer alive until it has run + keep_in_flight_readback_job(job, wait_target.0.clone(), wait_target.1); + return; + } + } + // 3. Copy only still-committed non-hole 64-byte chunks that were NOT modified by the CPU + // during the GPU wait, and sync `sent` hashes only for copied chunks. + let mut g = lock_state(); + let Some(s) = g.as_mut() else { break }; + let p = job.mapped as *const u8; + for &(dst, off, chunk) in &pending { + apply_readback_preserving_cpu_writes(dst, p.add(off), chunk, snap_base, &mut snap_hashes, &mut s.mapped); + } + s.reclaim_ring(); + } + return_readback_job(job); } /// The title committed `[a, a + n)` in a sparse window. The pages of tiles mapped for it that @@ -1343,6 +2319,8 @@ pub unsafe fn decommitted(a: usize, n: usize) { if n == 0 { return; } + // (pages `commit_title` left lazy go with them) + crate::hle::kernelx::lazy::unmark_range(a, n); let mut g = lock_state(); let Some(s) = g.as_mut() else { let (start, end) = page_span(a, n); @@ -1352,32 +2330,78 @@ pub unsafe fn decommitted(a: usize, n: usize) { s.decommit_range(a, n); } +/// Clear per-page hole bits in `[a, a + n)` for already-mapped tiles; if any VRAM-only tile +/// transitions from all-holes (`0xFFFF`) to watchable (`!= 0xFFFF`), invalidate cached watchable +/// tile runs and bump `MAPPED_GEN`. +fn unmask_committed_holes( + mapped: &mut FxHashMap, + runs: &mut Option>, + 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; + } + if was_all_holes && entry.holes != 0xFFFF { + unmasked = true; + } + } + if tile_end <= pg { + break; + } + pg = tile_end; + } + if unmasked { + *runs = None; + 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) { 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; + unmask_committed_holes(&mut self.mapped, &mut self.runs, a, n); + } + + /// Clear hole masks for 64 KiB tiles lazily CPU-committed by `kernelx::lazy` (#2582). + /// Leaves `to_zero` untouched so existing GPU VRAM contents remain intact while subsequent + /// write-watch dirty 4 KiB pages upload cleanly from the CPU view. + fn drain_lazy_commits(&mut self) { + if !HAS_LAZY_COMMITS.swap(false, Ordering::AcqRel) { + return; + } + let pages = std::mem::take(&mut *LAZY_COMMITS.lock().unwrap_or_else(|e| e.into_inner())); + let mut unmasked = false; + for page in pages { + if let Some(entry) = self.mapped.get_mut(&(page & !(TILE - 1))) { + if entry.holes == 0xFFFF { + unmasked = true; } + entry.holes = 0; } - if tile_end <= pg { - break; - } - pg = tile_end; + } + if unmasked { + self.runs = None; + MAPPED_GEN.fetch_add(1, Ordering::Release); } } /// `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) { + self.drain_lazy_commits(); let mut pools: Vec<(usize, (u32, u32))> = Vec::new(); let mut t = a & !(TILE - 1); let end = a.saturating_add(n); @@ -1407,72 +2431,202 @@ impl State { } } - /// a pool tile no window maps, none is parked on and no buffer uses goes back to the free list + /// Queue a pool tile that no window maps, none is parked on, and no buffer pins for GPU fence + /// quarantine. Never pushes straight to `free` or signals queues here (called from `forget_in` + /// during D3D12 `Release`); `flush_pending_quarantine` attaches completion fences before reuse. fn release_if_unused(&mut self, tile: (u32, u32)) { if !self.pinned.contains_key(&tile) && !self.mapped.values().any(|e| e.pool == tile) && !self.parked.values().any(|&p| p == tile) + && !self.pending_unmap_va.values().any(|&(p, _)| p == tile) && !self.quarantined.iter().any(|b| b.tiles.contains(&tile)) + && !self.pending_quarantine.contains(&tile) + && !self.free.contains(&tile) { - self.free.push(tile); + self.pending_quarantine.push(tile); } } - unsafe fn note_queue(&mut self, q: &ID3D12CommandQueue) -> bool { - let key = q.as_raw() as usize; - if self.queue_fences.contains_key(&key) { - return true; + /// Move any `pending_quarantine` tiles (unpinned when a placed buffer was released) into the + /// GPU fence quarantine behind `self.fence` and every known title queue. + unsafe fn flush_pending_quarantine(&mut self) -> bool { + self.flush_pending_quarantine_with(None) + } + + unsafe fn flush_pending_quarantine_with(&mut self, extra: Option<&ID3D12CommandQueue>) -> bool { + if self.pending_quarantine.is_empty() { + return false; } - // Ignore queues belonging to a different device (e.g. isolated unit tests). - let mut qdev: Option = None; - if q.GetDevice(&mut qdev).is_err() || qdev.as_ref().is_none_or(|d| d.as_raw() != self.dev.as_raw()) { - return true; + let raw_ptrs = collect_known_queue_ptrs(extra); + let borrowed: Vec<&ID3D12CommandQueue> = raw_ptrs.iter().filter_map(|p| ID3D12CommandQueue::from_raw_borrowed(p)).collect(); + self.flush_pending_quarantine_for(&borrowed) + } + + unsafe fn flush_pending_quarantine_for(&mut self, queues: &[&ID3D12CommandQueue]) -> bool { + if self.pending_quarantine.is_empty() { + return false; } - match self.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) { - Ok(fence) => { - self.queue_fences.insert(key, (q.clone(), fence, 0)); - true - } - Err(_) => false, + let tiles: Vec<(u32, u32)> = self + .pending_quarantine + .drain(..) + .filter(|tile| { + !self.pinned.contains_key(tile) + && !self.mapped.values().any(|e| e.pool == *tile) + && !self.parked.values().any(|&p| p == *tile) + && !self.pending_unmap_va.values().any(|&(p, _)| p == *tile) + && !self.quarantined.iter().any(|b| b.tiles.contains(tile)) + }) + .collect(); + if tiles.is_empty() { + return false; } + self.quarantine_tiles_for(tiles, queues); + true } - unsafe fn sync_known_queues(&mut self) -> bool { - let mut ok = true; + /// Order `self.queue` behind every active same-device title queue via `self.rb_fence` + /// so a subsequent sparse readback sees all submitted GPU writes. + unsafe fn wait_title_queues_for_readback(&mut self) { + let self_q = self.queue.as_raw() as usize; + let rb_q = self.rb_queue.as_raw() as usize; + let self_dev = self.dev.as_raw(); + let mut seen: Vec = Vec::new(); for raw in super::present::known_queues() { - if !self.queue_fences.contains_key(&raw) { - let ptr = raw as *mut c_void; - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&ptr) { - ok &= self.note_queue(q); - } + if raw == 0 || raw == self_q || raw == rb_q || seen.contains(&raw) { + continue; + } + let ptr = raw as *mut c_void; + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&ptr) else { + continue; + }; + let mut qdev: Option = None; + if q.GetDevice(&mut qdev).is_err() || qdev.as_ref().is_none_or(|d| d.as_raw() != self_dev) { + continue; + } + seen.push(raw); + if let Some((f, v)) = readback_after(&self.rb_queue, q) { + super::list_x::note_internal_wait(rb_q, "sparse readback behind a title queue", &f, v); } } - ok } - unsafe fn quarantine_tiles(&mut self, tiles: Vec<(u32, u32)>) { + unsafe fn signal_title_queues_for(&mut self, queues: &[&ID3D12CommandQueue]) -> Option> { + // Pass 1 (before signaling): deduplicate live same-device title queues and prune stale + // queue fences unconditionally so an early error cannot prune another live queue. + let self_q = self.queue.as_raw() as usize; + let rb_q = self.rb_queue.as_raw() as usize; + let mut active: Vec<(usize, &ID3D12CommandQueue)> = Vec::with_capacity(queues.len()); + let mut live_keys: Vec = Vec::with_capacity(queues.len()); + for &q in queues { + let key = q.as_raw() as usize; + if key == 0 || key == self_q || key == rb_q || live_keys.contains(&key) { + continue; + } + let mut qdev: Option = None; + if q.GetDevice(&mut qdev).is_err() || qdev.as_ref().is_none_or(|d| d.as_raw() != self.dev.as_raw()) { + continue; + } + live_keys.push(key); + active.push((key, q)); + } + self.queue_fences.retain(|k, _| live_keys.contains(k)); + let mut marks = Vec::with_capacity(active.len()); + for (key, q) in active { + let entry = match self.queue_fences.entry(key) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(e) => match self.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) { + Ok(fence) => e.insert((fence, 0)), + Err(_) => return None, + }, + }; + let next = entry.1 + 1; + if q.Signal(&entry.0, next).is_ok() { + entry.1 = next; + marks.push((entry.0.clone(), next)); + } else { + return None; + } + } + Some(marks) + } + + unsafe fn quarantine_tiles_for(&mut self, tiles: Vec<(u32, u32)>, queues: &[&ID3D12CommandQueue]) { if tiles.is_empty() { return; } - let mut ok = self.sync_known_queues(); - let mut marks = Vec::with_capacity(1 + self.queue_fences.len()); - marks.push((self.fence.clone(), self.value)); - if ok { - for (q, fence, val) in self.queue_fences.values_mut() { - let next = *val + 1; - if q.Signal(&*fence, next).is_ok() { - *val = next; - marks.push((fence.clone(), next)); - } else { - ok = false; - break; + let marks = self.signal_title_queues_for(queues).map(|mut title_marks| { + title_marks.push((self.fence.clone(), self.value)); + title_marks + }); + self.quarantined.push_back(RetiredTiles { tiles, marks }); + } + + /// Unmap `entries` on `self.queue` and quarantine their unpinned pool tiles behind `self.fence`. + /// Caller guarantees every active title queue has already passed the work that could touch them. + unsafe fn unmap_entries_and_quarantine(&mut self, entries: Vec<(usize, (u32, u32))>) { + if entries.is_empty() { + return; + } + let mut by_window: FxHashMap> = FxHashMap::default(); + let mut tiles: Vec<(u32, u32)> = Vec::new(); + for (va, tile) in entries { + if let Some(wi) = self.window_index(va) { + by_window.entry(wi).or_default().push(va); + } + if !self.pinned.contains_key(&tile) + && !self.mapped.values().any(|e| e.pool == tile) + && !self.parked.values().any(|&p| p == tile) + && !self.pending_unmap_va.values().any(|&(p, _)| p == tile) + && !self.quarantined.iter().any(|b| b.tiles.contains(&tile)) + && !tiles.contains(&tile) + { + tiles.push(tile); + } + } + for (wi, ts) in by_window { + let (b, r) = (self.windows[wi].0, self.windows[wi].1.clone()); + self.unmap_tiles(&r, b, &ts); + } + self.signal(); + if !tiles.is_empty() { + let mut marks = vec![(self.fence.clone(), self.value)]; + if self.rb_done_value > 0 { + marks.push((self.rb_done_fence.clone(), self.rb_done_value)); + } + self.quarantined.push_back(RetiredTiles { + tiles, + marks: Some(marks), + }); + } + } + + /// Execute deferred `UpdateTileMappings(NULL)` batches once all title queues have passed their + /// completion marks, skipping any VA that was re-committed in the meantime. + unsafe fn drain_pending_unmaps(&mut self) -> bool { + let mut unmapped = false; + while let Some(front) = self.pending_unmaps.front() { + let ready = front.marks.as_ref().is_some_and(|marks| marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)); + if !ready { + break; + } + let batch = self.pending_unmaps.pop_front().unwrap(); + let mut ready_entries = Vec::with_capacity(batch.entries.len()); + for (va, tile) in batch.entries { + if self.pending_unmap_va.get(&va).is_some_and(|&(_, s)| s == batch.seq) { + self.pending_unmap_va.remove(&va); + ready_entries.push((va, tile)); } } + if !ready_entries.is_empty() { + self.unmap_entries_and_quarantine(ready_entries); + unmapped = true; + } } - self.quarantined.push_back(RetiredTiles { tiles, marks: ok.then_some(marks) }); + unmapped } unsafe fn drain_quarantined(&mut self) -> bool { + self.drain_pending_unmaps(); let mut freed = false; while let Some(front) = self.quarantined.front() { let ready = front.marks.as_ref().is_some_and(|marks| marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)); @@ -1490,50 +2644,92 @@ impl State { freed } - /// The parked tiles unmapped from their windows (one call per window) and their unpinned - /// pool tiles quarantined behind `self.queue` and every known title queue's completion fence. - /// Pools left all free are not retired here: callers do that (`retire_free_pools`) unless - /// they take a tile right away. + /// Queue parked tiles for unmapping once all active title queues finish in-flight work (never + /// issuing `UpdateTileMappings(NULL)` concurrently with executing title queues, and never + /// inserting a cross-queue GPU `Wait` on `self.queue`). When no title queues are busy, unmaps + /// immediately on `self.queue` and quarantines unpinned pool tiles behind `self.fence`. unsafe fn flush_parked(&mut self) -> bool { + self.flush_parked_with(None) + } + + unsafe fn flush_parked_with(&mut self, extra: Option<&ID3D12CommandQueue>) -> bool { + self.drain_pending_unmaps(); if self.parked.is_empty() { return false; } - let mut by_window: FxHashMap> = FxHashMap::default(); - let mut tiles: Vec<(u32, u32)> = Vec::new(); - for (t, tile) in std::mem::take(&mut self.parked) { - if let Some(wi) = self.window_index(t) { - by_window.entry(wi).or_default().push(t); - } - if !self.pinned.contains_key(&tile) { - tiles.push(tile); + let raw_ptrs = collect_known_queue_ptrs(extra); + let borrowed: Vec<&ID3D12CommandQueue> = raw_ptrs.iter().filter_map(|p| ID3D12CommandQueue::from_raw_borrowed(p)).collect(); + self.flush_parked_for(&borrowed) + } + + unsafe fn flush_parked_for(&mut self, queues: &[&ID3D12CommandQueue]) -> bool { + self.drain_pending_unmaps(); + if self.parked.is_empty() { + return false; + } + let entries: Vec<(usize, (u32, u32))> = std::mem::take(&mut self.parked).into_iter().collect(); + let mut title_marks = self.signal_title_queues_for(queues); + if self.rb_done_value > 0 { + if let Some(marks) = title_marks.as_mut() { + marks.push((self.rb_done_fence.clone(), self.rb_done_value)); } } - for (wi, ts) in by_window { - let (b, r) = (self.windows[wi].0, self.windows[wi].1.clone()); - self.unmap_tiles(&r, b, &ts); + if title_marks.as_ref().is_some_and(|marks| marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)) { + self.unmap_entries_and_quarantine(entries); + } else { + self.unmap_seq = self.unmap_seq.wrapping_add(1); + let seq = self.unmap_seq; + for &(va, tile) in &entries { + self.pending_unmap_va.insert(va, (tile, seq)); + } + self.pending_unmaps.push_back(PendingUnmap { seq, entries, marks: title_marks }); } - self.signal(); - self.quarantine_tiles(tiles); true } } +fn collect_known_queue_ptrs(extra: Option<&ID3D12CommandQueue>) -> Vec<*mut c_void> { + let mut raw_ptrs: Vec<*mut c_void> = + super::present::known_queues().into_iter().filter(|&raw| raw != 0).map(|raw| raw as *mut c_void).collect(); + if let Some(q) = extra { + let p = q.as_raw(); + if !p.is_null() && !raw_ptrs.contains(&p) { + raw_ptrs.push(p); + } + } + raw_ptrs +} + +fn watchable_tile_runs(mapped: &FxHashMap) -> Vec<(usize, usize)> { + let mut tiles: Vec = mapped.iter().filter(|(_, e)| e.holes != 0xFFFF).map(|(&t, _)| t).collect(); + tiles.sort_unstable(); + let mut runs: Vec<(usize, usize)> = Vec::new(); + for t in tiles { + match runs.last_mut() { + Some(last) if last.1 == t => last.1 = t + TILE, + _ => runs.push((t, t + TILE)), + } + } + runs +} + +/// Drain any pending VEH lazy commits so `mapped_gen()` / `mapped_ranges()` include newly +/// CPU-committed tiles on the very first submit (zero-lock fast path when none are pending). +pub(super) fn drain_lazy_commits_if_pending() { + if HAS_LAZY_COMMITS.load(Ordering::Acquire) { + if let Some(s) = lock_state().as_mut() { + s.drain_lazy_commits(); + } + } +} + /// The sparse windows' tiles with video memory as sorted (start, end) runs: where a CPU write /// has to reach the GPU. pub fn mapped_ranges() -> Vec<(usize, usize)> { let mut g = lock_state(); let Some(s) = g.as_mut() else { return Vec::new() }; if s.runs.is_none() { - let mut tiles: Vec = s.mapped.keys().copied().collect(); - tiles.sort_unstable(); - let mut runs: Vec<(usize, usize)> = Vec::new(); - for t in tiles { - match runs.last_mut() { - Some(last) if last.1 == t => last.1 = t + TILE, - _ => runs.push((t, t + TILE)), - } - } - s.runs = Some(runs); + s.runs = Some(watchable_tile_runs(&s.mapped)); } s.runs.clone().unwrap_or_default() } @@ -1553,13 +2749,17 @@ pub fn note_watch(t: std::time::Duration, pages: usize) { /// memory, and `queue` GPU-waits for that and for new tile mappings. pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) { let t0 = std::time::Instant::now(); + // Phase 1 of GPU-view sync runs BEFORE `lock_state()` so `kernelx::AWAY` / `mirrors` locks + // are never acquired while holding `sparse::STATE` (ABBA deadlock with `XMemMapPhysicalPages`). + let gpu_view_prep = if gpu_view::on() { gpu_view::prepare_sync() } else { None }; let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; - s.note_queue(queue); + s.drain_lazy_commits(); // the title's work sees what was decommitted unmapped, as it was - let flushed = s.flush_parked(); + let flushed = s.flush_parked_with(Some(queue)); + let quarantined = s.flush_pending_quarantine_with(Some(queue)); let drained = s.drain_quarantined(); - if flushed || drained { + if flushed || quarantined || drained { s.retire_free_pools(); } let t_locked = std::time::Instant::now(); @@ -1570,34 +2770,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: } let mut dirty_runs = std::mem::take(&mut s.scratch_runs); dirty_runs.clear(); - let mut i = 0; - while i < dirty.len() { - let a = dirty[i]; - let mut n = page; - i += 1; - while i < dirty.len() && dirty[i] == a + n { - n += page; - i += 1; - } - // only what has video memory (committed tiles of a sparse window) - let mut x = a; - while x < a + n { - let t = x & !(TILE - 1); - let end = (t + TILE).min(a + n); - if let Some(entry) = s.mapped.get_mut(&t) { - let mut pg = x & !(PAGE - 1); - while pg < end { - let idx = (pg - t) / PAGE; - if entry.holes & (1u16 << idx) == 0 { - let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); - scan_page(bytes, pg, &mut entry.sent[idx], &mut dirty_runs); - } - pg += PAGE; - } - } - x = end; - } - } + scan_dirty_pages_into(&mut s.mapped, dirty, page, scan_threads(), &mut dirty_runs); let t_scanned = std::time::Instant::now(); PHASES[1].fetch_add((t_scanned - t_locked).as_micros() as u64, Ordering::Relaxed); PHASES[3].fetch_add((zero_runs.len() + dirty_runs.len()) as u64, Ordering::Relaxed); @@ -1608,6 +2781,9 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: if !dirty_runs.is_empty() { s.upload_dirty(&dirty_runs); } + if gpu_view::on() { + gpu_view::apply_sync(s, dirty, gpu_view_prep); + } PHASES[2].fetch_add(t_scanned.elapsed().as_micros() as u64, Ordering::Relaxed); { static CALLS: AtomicU64 = AtomicU64::new(0); @@ -1633,28 +2809,102 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: } 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); - s.waited.insert(q, s.value); + 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); + // new tile mappings since this queue last waited: on the CPU (`sparse_cpu_wait`); only + // copies: the GPU wait as before (a CPU wait there would hold every submit for them) + let mappings = s.mapped_value > waited_before; + s.waited.insert(q, value); + // (the wait below is without the state lock: the sparse queue's own work needs no lock to + // finish, and other submits must not stand behind this one meanwhile) + 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 fence.GetCompletedValue() >= 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); + fence.GetCompletedValue() >= value + }); + let waited = t.elapsed(); + super::flight::event("mapping cpu wait", value, waited.as_micros() as u64, reached as u64); + 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(), + fence.GetCompletedValue() + ); + } else if waited >= std::time::Duration::from_millis(50) { + let n = SLOW.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: a submit waited {} ms for {what} ({n} such waits)", waited.as_millis()); + } + } + reached +} + /// 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). pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option<(crate::util::HRESULT, usize)> { - let mut g = lock_state(); - let s = g.as_mut()?; let start = va & !(TILE - 1); let delta = va - start; let bytes = desc.Width as usize; if bytes == 0 { return None; } - s.window_index(start)?; - s.window_index(va.checked_add(bytes)?.checked_sub(1)?)?; + let last = va.checked_add(bytes)?.checked_sub(1)?; + { + let g = lock_state(); + let s = g.as_ref()?; + s.window_index(start)?; + s.window_index(last)?; + } let mut d = *desc; d.Width = (delta + bytes) as u64; d.Alignment = 0; @@ -1664,22 +2914,31 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D if state & (D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32 | D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32) != 0 { d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; } + // Create the reserved resource without holding STATE so concurrent final Release -> forget_buffer + // cannot queue a reused COM pointer in FORGOTTEN and later evict this live buffer (#2457). let hr = super::real::dev_create_reserved_resource(this, &d as *const _ as usize, state as usize, 0, riid, ppv); if hr < 0 || ppv.is_null() || (*ppv).is_null() { return None; } + let mut g = lock_state(); + let s = g.as_mut()?; // its tiles: the window's video memory at the same addresses; probe actual OS commitment // so uncommitted pages (e.g. [start, va) or reserved tails) stay marked as holes s.ensure_mapped(start, delta + bytes, |t| query_tile_holes(t)); let tiles: Vec<(usize, (u32, u32))> = (start..va + bytes).step_by(TILE).filter_map(|t| s.mapped.get(&t).map(|e| (t, e.pool))).collect(); let raw = *ppv; + if super::real::dred_on() { + super::real::name_resource(raw, &format!("xcl sparse_buf va={va:#x} sz={bytes:#x}")); + } let res = ID3D12Resource::from_raw_borrowed(&raw)?.clone(); s.map_tiles(&res, start, &tiles); for &(_, tile) in &tiles { *s.pinned.entry(tile).or_default() += 1; } s.buffers.insert(raw as usize, tiles.iter().map(|x| x.1).collect()); - s.signal(); + // (no signal of its own: the next submit's `before_execute` gives one for all the mappings + // queued since – a retail title placed 165 buffers in 6 ms, each with a mapping and a signal, + // right before its GPU stopped) Some((hr, delta)) } @@ -1811,7 +3070,7 @@ mod tests { /// Freeing the last tile in use of a pool and taking a tile again takes the retired pool - /// back, not a new 64 MB heap each time (#913: 288 pools, 18 GB asked of a 12 GB card). + /// back, not a new heap each time (#913: 288 pools of 64 MB, 18 GB asked of a 12 GB card). #[test] fn a_pool_retired_a_moment_ago_is_taken_back() { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; @@ -1826,8 +3085,10 @@ mod tests { } let dev = dev.expect("D3D12 device"); let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let rb_queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("rb_queue"); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let rb_done_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_done_fence"); let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); 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"); @@ -1838,16 +3099,23 @@ mod tests { fence, value: 0, event, + rb_queue, rb_fence, rb_value: 0, + rb_done_fence, + rb_done_value: 0, windows: Vec::new(), pools: Vec::new(), free: Vec::new(), retired: Vec::new(), parked: FxHashMap::default(), + pending_unmaps: VecDeque::new(), + pending_unmap_va: FxHashMap::default(), + unmap_seq: 0, mapped: FxHashMap::default(), pinned: FxHashMap::default(), quarantined: VecDeque::new(), + pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), to_zero: Vec::new(), @@ -1864,6 +3132,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: std::sync::atomic::AtomicBool::new(false), + mapped_value: 0, runs: None, scratch_runs: Vec::new(), }; @@ -1941,6 +3211,108 @@ mod tests { assert_eq!(out, vec![(0x1_0FC0, 128)]); } + #[test] + fn scan_page_avx2_matches_scalar_bit_for_bit() { + let mut page = vec![0u8; PAGE]; + let mut slot_a: Option> = None; + let mut slot_b: Option> = None; + let (mut out_a, mut out_b) = (Vec::new(), Vec::new()); + + // Step 1: all-zero fresh page (neither allocates) + scan_page(&page, 0x2_0000, &mut slot_a, &mut out_a); + scan_page_scalar(&page, 0x2_0000, &mut slot_b, &mut out_b); + assert_eq!(out_a, out_b); + assert!(slot_a.is_none() && slot_b.is_none()); + + // Step 2: sparse non-zero writes across odd/even 64B chunks (including last byte) + for &off in &[0usize, 63, 64, 191, 512, 2048, PAGE - 1] { + page[off] = (off as u8).wrapping_mul(37).wrapping_add(1); + } + scan_page(&page, 0x2_0000, &mut slot_a, &mut out_a); + scan_page_scalar(&page, 0x2_0000, &mut slot_b, &mut out_b); + assert_eq!(out_a, out_b); + assert_eq!(slot_a.as_deref(), slot_b.as_deref()); + + // Step 3: re-scan unchanged page (no runs) + out_a.clear(); + out_b.clear(); + scan_page(&page, 0x2_0000, &mut slot_a, &mut out_a); + scan_page_scalar(&page, 0x2_0000, &mut slot_b, &mut out_b); + assert_eq!(out_a, out_b); + assert!(out_a.is_empty()); + + // Step 4: zero out some previously non-zero chunks and mutate another + page[64] = 0; + page[512] = 0; + page[1024] = 0x5A; + scan_page(&page, 0x2_0000, &mut slot_a, &mut out_a); + scan_page_scalar(&page, 0x2_0000, &mut slot_b, &mut out_b); + assert_eq!(out_a, out_b); + assert_eq!(slot_a.as_deref(), slot_b.as_deref()); + } + + #[test] + fn parallel_scan_dirty_pages_matches_serial_bit_for_bit() { + // Allocate a 64 KiB-aligned backing buffer of 16 tiles (256 pages = 1 MiB) via VirtualAlloc + // so `t = x & !(TILE - 1)` aligns cleanly with `MappedTile` boundaries. + const NUM_TILES: usize = 16; + const TOTAL_BYTES: usize = NUM_TILES * TILE; + unsafe { + let base = VirtualAlloc(std::ptr::null(), TOTAL_BYTES, MEM_COMMIT | 0x2000, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + assert_eq!(base % TILE, 0); + let mem = std::slice::from_raw_parts_mut(base as *mut u8, TOTAL_BYTES); + // Seed deterministic pattern across every other page + boundary-spanning chunks. + for p in 0..(NUM_TILES * PAGES_PER_TILE) { + if p % 3 == 0 { + mem[p * PAGE] = (p as u8).wrapping_add(1); + mem[p * PAGE + PAGE - 1] = (p as u8).wrapping_mul(13).wrapping_add(7); + } else if p % 3 == 1 { + // Adjacent start chunk to force boundary coalescing across worker slices + mem[p * PAGE] = 0xEE; + } + } + let make_map = || -> FxHashMap { + let mut m = FxHashMap::default(); + for ti in 0..NUM_TILES { + // Mark page 5 as a hole on odd tiles + let holes = if ti % 2 == 1 { 1u16 << 5 } else { 0 }; + m.insert(base + ti * TILE, TileEntry::with_holes((0, ti as u32), holes)); + } + m + }; + let mut dirty: Vec = (0..(NUM_TILES * PAGES_PER_TILE)).map(|p| base + p * PAGE).collect(); + // Inject a duplicate entry to verify deduplication safety. + dirty.insert(40, dirty[40]); + + let mut serial_map = make_map(); + let mut parallel_map = make_map(); + let (mut out_serial, mut out_parallel) = (Vec::new(), Vec::new()); + + scan_dirty_pages_into(&mut serial_map, &dirty, PAGE, 1, &mut out_serial); + scan_dirty_pages_into(&mut parallel_map, &dirty, PAGE, 6, &mut out_parallel); + assert_eq!(out_parallel, out_serial, "parallel scan must match serial scan bit-for-bit"); + assert!(!out_parallel.is_empty()); + + // Second pass with no changes must emit zero runs on both. + out_serial.clear(); + out_parallel.clear(); + scan_dirty_pages_into(&mut serial_map, &dirty, PAGE, 1, &mut out_serial); + scan_dirty_pages_into(&mut parallel_map, &dirty, PAGE, 6, &mut out_parallel); + assert!(out_serial.is_empty() && out_parallel.is_empty()); + + // Mutate one byte on every 4th page and re-verify parity. + for p in (0..(NUM_TILES * PAGES_PER_TILE)).step_by(4) { + mem[p * PAGE + 128] ^= 0xFF; + } + scan_dirty_pages_into(&mut serial_map, &dirty, PAGE, 1, &mut out_serial); + scan_dirty_pages_into(&mut parallel_map, &dirty, PAGE, 6, &mut out_parallel); + assert_eq!(out_parallel, out_serial, "second mutation pass must match serial bit-for-bit"); + + VirtualFree(base as *mut c_void, 0, 0x8000); + } + } + /// Ring-buffer planner keeps every chunk contiguous, 64-byte aligned, <= cap/2, and splits /// cleanly across the end of the ring buffer without wrapping mid-copy. #[test] @@ -2033,8 +3405,10 @@ mod tests { .expect("CreateReservedResource"); let reserved = reserved.expect("reserved buffer"); let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let rb_queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("rb_queue"); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let rb_done_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_done_fence"); let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); 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"); @@ -2046,8 +3420,11 @@ mod tests { fence, value: 0, event, + rb_queue, rb_fence, rb_value: 0, + rb_done_fence, + rb_done_value: 0, windows: vec![(base, reserved)], pools: Vec::new(), free: Vec::new(), @@ -2055,7 +3432,11 @@ mod tests { mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + pending_unmaps: VecDeque::new(), + pending_unmap_va: FxHashMap::default(), + unmap_seq: 0, quarantined: VecDeque::new(), + pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), to_zero: Vec::new(), @@ -2072,6 +3453,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: std::sync::atomic::AtomicBool::new(false), + mapped_value: 0, runs: None, scratch_runs: Vec::new(), }; @@ -2130,8 +3513,10 @@ mod tests { .expect("CreateReservedResource"); let reserved = reserved.expect("reserved buffer"); let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let rb_queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("rb_queue"); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let rb_done_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_done_fence"); let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); 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"); @@ -2143,8 +3528,11 @@ mod tests { fence, value: 0, event, + rb_queue, rb_fence, rb_value: 0, + rb_done_fence, + rb_done_value: 0, windows: vec![(base, reserved)], pools: Vec::new(), free: Vec::new(), @@ -2152,7 +3540,11 @@ mod tests { mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + pending_unmaps: VecDeque::new(), + pending_unmap_va: FxHashMap::default(), + unmap_seq: 0, quarantined: VecDeque::new(), + pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), to_zero: Vec::new(), @@ -2169,6 +3561,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: std::sync::atomic::AtomicBool::new(false), + mapped_value: 0, runs: None, scratch_runs: Vec::new(), }; @@ -2236,6 +3630,39 @@ mod tests { } } + /// A title frees its tiles in runs spread over all its pools: the pools of the freed runs go + /// back. With pools of 64 MiB none of these did (every pool kept the tiles still in use). + /// (From upstream PR #2630.) + #[test] + fn pools_of_freed_runs_go_back() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + // 192 MiB of tiles, taken in order as a title's first commits take them + const TILES: usize = 3072; + let tiles: Vec<(u32, u32)> = (0..TILES).map(|_| s.take_tile().expect("a tile").0).collect(); + let made = s.pools.iter().filter(|p| p.is_some()).count(); + assert_eq!(made * POOL_TILES as usize, TILES, "the tiles fill whole pools"); + // of every 64 MiB the title keeps the first 4 MiB and frees the rest + let (mut kept, mut freed) = (0, 0); + for (i, &t) in tiles.iter().enumerate() { + if i % 1024 < 64 { + kept += 1; + } else { + s.free.push(t); + freed += 1; + } + } + s.retire_free_pools(); + let left = s.pools.iter().filter(|p| p.is_some()).count() * POOL_TILES as usize; + assert_eq!(s.free.len() + s.retired.len() * POOL_TILES as usize, freed, "every freed tile is free or its pool retired"); + assert!(left <= kept * 2, "{left} tiles of video memory stay in pools for {kept} tiles in use ({} MiB for {} MiB)", left * TILE >> 20, kept * TILE >> 20); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + unsafe fn test_state_with_reserved(tiles: usize) -> (usize, State) { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::*; @@ -2243,7 +3670,9 @@ mod tests { let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); let mut dev: Option = None; - if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + if std::env::var("XCL_WARP").ok().as_deref() == Some("1") + || D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() + { let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); } @@ -2255,8 +3684,10 @@ mod tests { .expect("CreateReservedResource"); let reserved = reserved.expect("reserved buffer"); let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let rb_queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("rb_queue"); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let rb_done_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_done_fence"); let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); 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"); @@ -2268,8 +3699,11 @@ mod tests { fence, value: 0, event, + rb_queue, rb_fence, rb_value: 0, + rb_done_fence, + rb_done_value: 0, windows: vec![(base, reserved)], pools: Vec::new(), free: Vec::new(), @@ -2277,7 +3711,11 @@ mod tests { mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + pending_unmaps: VecDeque::new(), + pending_unmap_va: FxHashMap::default(), + unmap_seq: 0, quarantined: VecDeque::new(), + pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), to_zero: Vec::new(), @@ -2294,6 +3732,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: std::sync::atomic::AtomicBool::new(false), + mapped_value: 0, runs: None, scratch_runs: Vec::new(), }; @@ -2345,7 +3785,6 @@ mod tests { unsafe { let (base, mut s) = test_state_with_reserved(2); let title_q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); - assert!(s.note_queue(&title_q)); s.commit_range(base, TILE); let tile = s.mapped[&base].pool; @@ -2357,7 +3796,7 @@ mod tests { s.decommit_range(base, TILE); s.free.clear(); - assert!(s.flush_parked()); + assert!(s.flush_parked_for(&[&title_q])); // Even after `s.queue` finishes `unmap_tiles`, `title_q` is still gated behind `title_gate`. s.wait_for(s.value); @@ -2380,6 +3819,108 @@ mod tests { } } + unsafe fn com_refcount(q: &ID3D12CommandQueue) -> u32 { + let raw = q.as_raw() as *mut *const *const c_void; + let vt = *raw; + let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*vt.add(1)); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*vt.add(2)); + let _ = add_ref(raw as *mut c_void); + release(raw as *mut c_void) + } + + #[test] + fn flush_parked_does_not_retain_title_queue_com_refs() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + unsafe { + let (base, mut s) = test_state_with_reserved(1); + let title_q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + let before = com_refcount(&title_q); + s.commit_range(base, TILE); + s.wait_for(s.value); + s.decommit_range(base, TILE); + assert!(s.flush_parked_for(&[&title_q])); + assert_eq!(com_refcount(&title_q), before, "flush_parked must not retain a strong COM ref on title queues"); + assert_eq!(s.queue_fences.len(), 1); + s.wait_for(s.value); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn flush_parked_prunes_stale_queue_fences_while_inflight_batches_stay_gated() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + unsafe { + let (base, mut s) = test_state_with_reserved(2); + let title_q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + let title_gate: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate fence"); + let _unblock = SignalOnDrop(title_gate.clone(), 1); + title_q.Wait(&title_gate, 1).expect("gate title queue"); + + s.commit_range(base, TILE); + let tile_a = s.mapped[&base].pool; + s.commit_range(base + TILE, TILE); + let tile_b = s.mapped[&(base + TILE)].pool; + s.wait_for(s.value); + + s.decommit_range(base, TILE); + s.free.clear(); + assert!(s.flush_parked_for(&[&title_q])); + assert_eq!(s.queue_fences.len(), 1); + + // Simulate title_q release before the next flush: stale fence entry is pruned, + // while batch A keeps its own fence clone in `marks` and stays gated. + s.decommit_range(base + TILE, TILE); + assert!(s.flush_parked_for(&[])); + assert!(s.queue_fences.is_empty(), "stale queue fence must be pruned"); + s.wait_for(s.value); + s.drain_quarantined(); + assert!(!s.free.contains(&tile_a) && !s.pending_unmaps.is_empty(), "in-flight batch A must stay gated"); + + title_gate.Signal(1).expect("release title queue"); + let start = std::time::Instant::now(); + while (!s.free.contains(&tile_a) || !s.free.contains(&tile_b)) && start.elapsed() < std::time::Duration::from_secs(5) { + s.drain_quarantined(); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + assert!(s.free.contains(&tile_a) && s.free.contains(&tile_b), "both batches must drain after title_q completes"); + drop(_unblock); + s.wait_for(s.value); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn repeated_queue_quarantine_and_release_does_not_leak_queues_or_fences() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + unsafe { + let (base, mut s) = test_state_with_reserved(2); + for i in 0..80usize { + let q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap_or_else(|e| panic!("queue {i}: {e}")); + let before = com_refcount(&q); + s.commit_range(base, TILE); + s.decommit_range(base, TILE); + assert!(s.flush_parked_for(&[&q])); + assert_eq!(com_refcount(&q), before, "queue {i} refcount leaked"); + drop(q); + s.commit_range(base + TILE, TILE); + s.decommit_range(base + TILE, TILE); + assert!(s.flush_parked_for(&[])); + assert!(s.queue_fences.is_empty(), "stale fence leaked at iteration {i}"); + s.wait_for(s.value); + let start = std::time::Instant::now(); + while (!s.quarantined.is_empty() || !s.pending_unmaps.is_empty()) && start.elapsed() < std::time::Duration::from_secs(5) { + s.drain_quarantined(); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(s.quarantined.is_empty() && s.pending_unmaps.is_empty(), "quarantine failed to drain at iteration {i}"); + } + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + /// Sub-tile decommits (two 32 KiB halves, sixteen 4 KiB pages, or decommitting the last /// remaining committed page) must unmap the tile and return unpinned pool tiles to `free` /// once `holes` reaches `0xFFFF`, pruning stale `to_zero` entries for unmapped tiles. @@ -2533,6 +4074,77 @@ mod tests { assert_eq!(early.into_iter().collect::>(), vec![(a, a + TILE), (a + 2 * TILE, a + 4 * TILE)]); } + /// A late completion from an earlier timed-out `SetEventOnCompletion` leaves the reusable + /// auto-reset event signalled (or fires it mid-wait). `wait_fence_until` must ignore both + /// and wait until the fence actually reaches `target`. (The test of #2821, for `main`.) + #[test] + fn wait_fence_until_ignores_stale_event_signal() { + use std::time::{Duration, Instant}; + use windows::Win32::System::Threading::{CreateEventW, SetEvent}; + unsafe { + let Some(dev) = test_device() else { return }; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let event = CreateEventW(None, false, false, None).expect("event"); + // a stale signal already set, then an earlier completion (2) firing mid-wait for 5 + SetEvent(event).expect("stale SetEvent"); + fence.SetEventOnCompletion(2, event).expect("stale completion arm"); + let f2 = fence.clone(); + let t = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(30)); + let _ = f2.Signal(2); + std::thread::sleep(Duration::from_millis(50)); + let _ = f2.Signal(5); + }); + let start = Instant::now(); + let ok = wait_fence_until(&fence, event, 5, Duration::from_secs(2)); + let elapsed = start.elapsed(); + t.join().unwrap(); + let _ = CloseHandle(event); + assert!(ok, "wait_fence_until timed out instead of observing Signal(5)"); + assert!(fence.GetCompletedValue() >= 5, "returned early at {}", fence.GetCompletedValue()); + assert!(elapsed >= Duration::from_millis(50), "returned too early ({elapsed:?}) on a stale event signal"); + } + } + + /// A `readback_now` job that timed out with its copy still queued must not be handed out + /// (or freed) before that copy has run, then goes back to the pool. + #[test] + fn a_timed_out_readback_job_is_kept_until_its_copy_ran() { + unsafe { + let Some(dev) = test_device() else { return }; + let job = take_readback_job(&dev, 1).expect("readback job"); + let buf = job.buf.as_raw() as usize; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + keep_in_flight_readback_job(job, fence.clone(), 1); + let other = take_readback_job(&dev, 1).expect("another job"); + assert_ne!(other.buf.as_raw() as usize, buf, "a job whose copy is queued was handed out again"); + assert!(IN_FLIGHT_RB_JOBS.lock().unwrap().iter().any(|j| j.job.buf.as_raw() as usize == buf), "the queued job was dropped"); + return_readback_job(other); + fence.Signal(1).expect("signal"); + reclaim_in_flight_readback_jobs(); + assert!(!IN_FLIGHT_RB_JOBS.lock().unwrap().iter().any(|j| j.job.buf.as_raw() as usize == buf), "the job stayed in flight after its copy"); + assert!(FREE_RB_JOBS.lock().unwrap().iter().any(|j| j.buf.as_raw() as usize == buf), "the job did not go back to the pool"); + } + } + + /// A D3D12 device for the tests above (hardware, else WARP), or `None` after a skip notice. + unsafe fn test_device() -> Option { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() { + return dev; + } + let warp = CreateDXGIFactory1::().ok().and_then(|f| f.EnumWarpAdapter::().ok()); + if let Some(warp) = warp { + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() { + return dev; + } + } + crate::gpu::recomp::runner::skip_test("no GPU"); + None + } + /// Time for n 64 KiB pages committed one at a time and decommitted one at a time in /// reverse, before the device exists (`cargo test --release -p xcl --lib -- /// --ignored --exact hle::d3d12x::sparse::tests::early_commit_timing --nocapture`, @@ -2559,4 +4171,319 @@ mod tests { println!("early: {n} pages: commit {:.1} ms, decommit {:.1} ms", commit.as_secs_f64() * 1e3, decommit.as_secs_f64() * 1e3); } } + + /// Releasing a placed buffer that was the last pin on an already-unmapped tile must queue the + /// tile in `pending_quarantine` (never directly in `free`) and keep it out of `free` until + /// `flush_pending_quarantine` + active title-queue fences complete (#2457). + #[test] + fn gpu_unpinned_unused_tile_waits_in_quarantine_before_free() { + use windows_sys::Win32::System::Memory::{VirtualFree, MEM_RELEASE}; + unsafe { + let (base, mut s) = test_state_with_reserved(1); + let title_queue: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + let gate: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate fence"); + let _release_gate = SignalOnDrop(gate.clone(), 1); + + s.commit_range(base, TILE); + let tile = s.mapped[&base].pool; + const BUF: usize = 0xDEAD_BEE0; + s.pinned.insert(tile, 1); + s.buffers.insert(BUF, vec![tile]); + + // Decommit and flush while still pinned by BUF: tile is unmapped from window once + // idle title_queue passes its fence, NOT freed. + s.decommit_range(base, TILE); + assert!(s.flush_parked_for(&[&title_queue])); + let start = std::time::Instant::now(); + while !s.pending_unmaps.is_empty() && start.elapsed() < std::time::Duration::from_secs(5) { + s.drain_pending_unmaps(); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(s.pending_unmaps.is_empty()); + assert!(!s.free.contains(&tile)); + assert!(s.quarantined.is_empty()); + + // Stall title_queue behind `gate` to simulate in-flight GPU work reading BUF. + title_queue.Wait(&gate, 1).expect("wait on gate"); + + // Buffer release unpins tile: must enter pending_quarantine, NOT free. + forget_in(&mut s, BUF); + assert!(!s.pinned.contains_key(&tile)); + assert!(!s.free.contains(&tile), "unpinned tile must not bypass quarantine into free"); + assert_eq!(s.pending_quarantine, vec![tile]); + + // Flushing pending_quarantine attaches title_queue fence; tile stays quarantined until gate signals. + assert!(s.flush_pending_quarantine_for(&[&title_queue])); + assert!(s.pending_quarantine.is_empty()); + assert!(!s.drain_quarantined(), "tile must remain quarantined while title queue is blocked"); + assert!(!s.free.contains(&tile)); + + gate.Signal(1).expect("signal gate"); + let start = std::time::Instant::now(); + while !s.drain_quarantined() && start.elapsed() < std::time::Duration::from_secs(5) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(s.free.contains(&tile), "tile should enter free once title queue fence completes"); + + s.wait_for(s.value); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + /// `flush_parked` must defer `UpdateTileMappings(NULL)` until active title queues finish + /// their prior work (preventing concurrent PTE unmapping while shaders run), and re-committing + /// the VA before that fence completes must cancel the deferred unmap cleanly (including ABA). + #[test] + fn gpu_flush_parked_defers_null_unmap_and_recommit_cancels_stale_unmap() { + use windows_sys::Win32::System::Memory::{VirtualFree, MEM_RELEASE}; + unsafe { + let (base, mut s) = test_state_with_reserved(2); + let title_q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + + s.commit_range(base, TILE); + let tile = s.mapped[&base].pool; + s.wait_for(s.value); + let v_before = s.value; + + let gate1: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate1"); + let _unblock1 = SignalOnDrop(gate1.clone(), 1); + title_q.Wait(&gate1, 1).expect("gate title_q 1"); + + // Decommit + flush while title_q is busy: NULL unmap must be deferred, NOT queued on s.queue yet. + s.decommit_range(base, TILE); + assert!(s.flush_parked_for(&[&title_q])); + assert_eq!(s.value, v_before, "UpdateTileMappings(NULL) must not be issued while title queue is in flight"); + assert_eq!(s.pending_unmaps.len(), 1); + assert!(s.pending_unmap_va.contains_key(&base)); + + // Re-commit same VA before gate1 signals: cancels pending unmap, keeps tile, zeros it, no GPU remap. + s.to_zero.clear(); + s.commit_range(base, TILE); + assert_eq!(s.mapped[&base].pool, tile); + assert!(!s.pending_unmap_va.contains_key(&base)); + assert_eq!(s.to_zero, vec![(base, TILE)]); + assert_eq!(s.value, v_before); + + // ABA check: decommit & flush again behind a second gate; when gate1 finishes first, + // batch #1 must NOT unmap batch #2's tile. + let gate2: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate2"); + let _unblock2 = SignalOnDrop(gate2.clone(), 1); + title_q.Wait(&gate2, 1).expect("gate title_q 2"); + s.decommit_range(base, TILE); + assert!(s.flush_parked_for(&[&title_q])); + assert_eq!(s.pending_unmaps.len(), 2); + + gate1.Signal(1).expect("signal gate1"); + let start = std::time::Instant::now(); + while s.pending_unmaps.len() == 2 && start.elapsed() < std::time::Duration::from_secs(5) { + s.drain_pending_unmaps(); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(s.pending_unmaps.len(), 1, "batch #1 drained cleanly"); + assert_eq!(s.value, v_before, "stale batch #1 must not unmap VA owned by batch #2"); + assert!(s.pending_unmap_va.contains_key(&base)); + + // Releasing gate2 executes batch #2's deferred NULL unmap and returns tile to free. + gate2.Signal(1).expect("signal gate2"); + let start = std::time::Instant::now(); + while !s.drain_quarantined() && start.elapsed() < std::time::Duration::from_secs(5) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(s.value > v_before, "batch #2 must emit UpdateTileMappings(NULL) once title_q completes"); + assert!(s.pending_unmaps.is_empty() && s.pending_unmap_va.is_empty()); + assert!(s.free.contains(&tile)); + + drop(_unblock2); + drop(_unblock1); + s.wait_for(s.value); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn lazy_commit_clears_vram_only_holes_without_clobbering_to_zero() { + let mut mapped = BTreeMap::new(); + let tile_a = 0x4_6eb2_0000usize; + let tile_unmapped = 0x4_6eb3_0000usize; + mapped.insert(tile_a, TileEntry { pool: (0, 0), holes: 0xFFFF, sent: std::array::from_fn(|_| None) }); + { + let mut g = LAZY_COMMITS.lock().unwrap_or_else(|e| e.into_inner()); + g.clear(); + g.push(tile_a + 0x5920); + g.push(tile_unmapped); + } + HAS_LAZY_COMMITS.store(true, Ordering::Release); + + // Drain via the exact same logic used by `State::drain_lazy_commits`: + // mapped tile clears all holes (`0xFFFF -> 0`), unmapped tile is ignored cleanly. + assert!(HAS_LAZY_COMMITS.swap(false, Ordering::AcqRel)); + let pages = std::mem::take(&mut *LAZY_COMMITS.lock().unwrap_or_else(|e| e.into_inner())); + for page in pages { + if let Some(entry) = mapped.get_mut(&(page & !(TILE - 1))) { + entry.holes = 0; + } + } + assert_eq!(mapped[&tile_a].holes, 0); + assert!(!mapped.contains_key(&tile_unmapped)); + assert!(!HAS_LAZY_COMMITS.load(Ordering::Acquire)); + + // Direct CPU write onto a reserved-only 64 KiB page marked with `kernelx::lazy::mark` + // (matching `alloc_vram_only` + title clear loop at `+0x501eb50`) commits cleanly. + unsafe { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + let p = VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(p, 0); + crate::hle::kernelx::lazy::mark(p); + let slice = std::slice::from_raw_parts_mut((p + 0x5920) as *mut u32, 0x100); + slice.fill(0xFFFF_FFFF); + assert_eq!(slice[0], 0xFFFF_FFFF); + assert_eq!(slice[0xFF], 0xFFFF_FFFF); + assert!(!crate::hle::kernelx::lazy::unmark(p), "page must already have been committed by VEH"); + assert_ne!(VirtualFree(p as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn readback_now_preserves_concurrent_cpu_writes_and_unaligned_batches() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + unsafe { + // Allocate a real 64 KiB aligned tile with page 0 committed and page 1 left as a hole. + let tile = VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert!(tile != 0 && tile % TILE == 0); + assert!(!VirtualAlloc(tile as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + + let host = std::slice::from_raw_parts_mut(tile as *mut u8, PAGE); + host[0..64].fill(0x11); // chunk 0: untouched during GPU wait -> should take GPU readback + host[64..128].fill(0x22); // chunk 1: modified by CPU during GPU wait -> must NOT be clobbered + host[128..192].fill(0x33); // chunk 2: split across two unaligned batches -> both halves should apply + + let mut mapped: FxHashMap = FxHashMap::default(); + mapped.insert(tile, TileEntry::with_holes((0, 0), 0xFFFF & !1u16)); + let mut dirty = Vec::new(); + scan_page(host, tile, &mut mapped.get_mut(&tile).unwrap().sent[0], &mut dirty); + assert_eq!(dirty, vec![(tile, 192)]); + + // Phase-1 snapshot hashes for chunks 0..3. + let mut snap_hashes = vec![ + chunk_hash(&host[0..64]), + chunk_hash(&host[64..128]), + chunk_hash(&host[128..192]), + ]; + + // Simulate concurrent CPU write to chunk 1 during the GPU wait. + host[64 + 7] = 0xEE; + + // GPU readback buffer containing new GPU values for chunks 0..3. + let mut gpu_rb = vec![0u8; 192]; + gpu_rb[0..64].fill(0xA1); + gpu_rb[64..128].fill(0xB2); + gpu_rb[128..160].fill(0xC3); + gpu_rb[160..192].fill(0xD4); + + // Batch 1 covers [0..160) (splitting chunk 2 in half); Batch 2 covers [160..192). + apply_readback_preserving_cpu_writes(tile, gpu_rb.as_ptr(), 160, tile, &mut snap_hashes, &mut mapped); + apply_readback_preserving_cpu_writes(tile + 160, gpu_rb.as_ptr().add(160), 32, tile, &mut snap_hashes, &mut mapped); + + // Chunk 0 received GPU readback; chunk 1 preserved CPU write; chunk 2 received both batch halves. + assert!(host[0..64].iter().all(|&b| b == 0xA1)); + assert_eq!(host[64 + 7], 0xEE, "concurrent CPU write in chunk 1 must not be clobbered"); + assert_eq!(host[64], 0x22, "rest of modified chunk 1 must stay intact"); + assert!(host[128..160].iter().all(|&b| b == 0xC3)); + assert!(host[160..192].iter().all(|&b| b == 0xD4)); + + // Next `scan_page` must detect ONLY chunk 1 as dirty (chunks 0 and 2 had their `sent` hashes synced). + dirty.clear(); + scan_page(host, tile, &mut mapped.get_mut(&tile).unwrap().sent[0], &mut dirty); + assert_eq!(dirty, vec![(tile + 64, 64)]); + + assert_ne!(VirtualFree(tile as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn commit_range_unmasking_vram_only_tile_invalidates_runs_and_gen() { + let mut mapped: FxHashMap = FxHashMap::default(); + let t0 = 0x2000_0000usize; + mapped.insert(t0, TileEntry::with_holes((0, 0), 0xFFFF)); + + // Prime cached watchable runs while tile is VRAM-only (all holes). + let mut runs = Some(watchable_tile_runs(&mapped)); + assert_eq!(runs, Some(Vec::new())); + + let gen_before = MAPPED_GEN.load(Ordering::Acquire); + assert!(unmask_committed_holes(&mut mapped, &mut runs, t0, PAGE)); + assert_eq!(mapped[&t0].holes, 0xFFFE); + assert!(runs.is_none(), "cached runs must be invalidated when a VRAM-only tile becomes watchable"); + assert!(MAPPED_GEN.load(Ordering::Acquire) > gen_before, "MAPPED_GEN must increment on unmask"); + + // Recomputing watchable runs now includes the unmasked tile. + let recomputed = watchable_tile_runs(&mapped); + assert_eq!(recomputed, vec![(t0, t0 + TILE)]); + + // A subsequent page commit on an already-watchable tile does not spuriously invalidate runs. + runs = Some(recomputed); + assert!(!unmask_committed_holes(&mut mapped, &mut runs, t0 + PAGE, PAGE)); + assert_eq!(mapped[&t0].holes, 0xFFFC); + assert!(runs.is_some()); + } + + #[test] + fn watchable_tile_runs_omits_vram_only_holes_until_unmasked() { + let mut mapped: FxHashMap = FxHashMap::default(); + let t0 = 0x1000_0000usize; + let t1 = t0 + TILE; + let t2 = t1 + TILE; + mapped.insert(t0, TileEntry::with_holes((0, 0), 0)); + mapped.insert(t1, TileEntry::with_holes((0, 1), 0xFFFF)); + mapped.insert(t2, TileEntry::with_holes((0, 2), 0x00FF)); + + assert_eq!(watchable_tile_runs(&mapped), vec![(t0, t0 + TILE), (t2, t2 + TILE)]); + + mapped.get_mut(&t1).unwrap().holes = 0; + assert_eq!(watchable_tile_runs(&mapped), vec![(t0, t2 + TILE)]); + } + + /// Regression test for the circular GPU deadlock: + /// `title_qA -> title_qB -> sparse.queue -> title_qA`. + /// When `rb_queue` waits on a gated title queue `title_qA` (`rb_fence`), `sparse.queue` + /// (uploads + tile mappings) must remain unblocked so `title_qB` waiting on `sparse.queue` + /// can complete and release `title_qA`, unblocking the readback cleanly. + #[test] + fn readback_on_dedicated_queue_never_blocks_sparse_uploads_behind_gated_title_queue() { + unsafe { + let (base, mut s) = test_state_with_reserved(1); + let title_q_a: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title_q_a"); + let title_q_b: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title_q_b"); + let cross_fence: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("cross_fence"); + + // 1. title_q_a waits on title_q_b via cross_fence (not yet signalled by title_q_b). + title_q_a.Wait(&cross_fence, 1).expect("qA waits on qB"); + + // 2. A readback orders `rb_queue` behind title_q_a via `rb_fence` and signals `rb_done_fence`. + s.rb_value += 1; + let rb_v = s.rb_value; + title_q_a.Signal(&s.rb_fence, rb_v).expect("qA signals rb_fence"); + s.rb_queue.Wait(&s.rb_fence, rb_v).expect("rb_queue waits on qA"); + s.signal_rb(); + let rb_target = s.rb_done_value; + + // 3. Now title_q_b submits work that waits on `sparse.queue` (uploads), then signals cross_fence. + // With the old shared-queue design, `sparse.queue` was stuck behind qA, causing a 3-way deadlock! + s.signal(); + let upload_target = s.value; + title_q_b.Wait(&s.fence, upload_target).expect("qB waits on sparse.queue"); + title_q_b.Signal(&cross_fence, 1).expect("qB releases qA"); + + // Both `sparse.queue` AND `rb_queue` must complete well within 5 s (no deadlock!). + s.wait_for(upload_target); + assert!(s.fence.GetCompletedValue() >= upload_target, "sparse.queue must not be blocked by rb_queue"); + s.wait_for_rb(rb_target); + assert!(s.rb_done_fence.GetCompletedValue() >= rb_target, "rb_queue must complete once qB unblocks qA"); + + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE), 0); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs new file mode 100644 index 0000000000..e963bc1d0f --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs @@ -0,0 +1,694 @@ +//! Buffers in a GPU view of the title's memory, readable by shaders (`XCL_GPU_VIEW_BUFFERS=1`). +//! +//! A title reserves 64 KiB pages twice, once for the CPU and once with no CPU access (`kernelx:: +//! mirrors`), and gives the GPU addresses of the second. Those lie outside the memory windows, so +//! a shader reads zeros at them: a retail title's culling reads its object lists, and its mesh +//! shaders their geometry, from there (#697). +//! +//! The tiles a buffer view covers are mapped in free address space of a sparse window (video +//! memory only: nothing is committed for the CPU) and hold what the title's pages hold: their +//! bytes go up when the view is made and again when the title writes them. The view's address is +//! replaced by the window's. Only what is read is mirrored: a write through it is lost, so UAVs +//! keep their address. + +use std::collections::{HashMap, HashSet}; + +use super::*; + +/// The window space a chunk of the title's view takes. Views inside one chunk share it; a view +/// across chunks gets a space of its own (its bytes have to be contiguous). +const EXTENT: usize = 1 << 20; +/// Views longer than this keep their address. +const MOST: usize = 64 << 20; +/// Minimum submit age before budget-pressure LRU eviction can reclaim a still-backed tile, +/// ensuring tiles referenced in the current frame or in-flight submissions are never evicted. +const EVICT_GRACE_SUBMITS: u64 = 16; +/// Rotating title tiles inspected per submit for unmapped/decommitted reclamation. +const SWEEP_PER_SUBMIT: usize = 64; +/// Extra cold tiles reclaimed alongside a budget eviction to amortize tile-mapping updates. +const EVICT_BATCH_EXTRA: usize = 32; + +pub fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_GPU_VIEW_BUFFERS").is_ok_and(|v| v.trim() == "1")) +} + +/// `XCL_GPU_VIEW_MB` (512): the video memory the mirrors may take. +fn budget() -> usize { + static B: std::sync::OnceLock = std::sync::OnceLock::new(); + *B.get_or_init(|| std::env::var("XCL_GPU_VIEW_MB").ok().and_then(|v| v.trim().parse().ok()).filter(|&m| m > 0).unwrap_or(512usize) << 20) +} + +#[derive(Default)] +pub(super) struct Mirrors { + /// (first byte of the title's chunks, chunks) → the window space of them + extents: HashMap<(usize, usize), usize>, + /// window tile → title tile (an address in the GPU view) + title_of: FxHashMap, + /// where the bytes of a title tile are read from (its own address, or the CPU view's) + read: FxHashMap, + /// read tile → window tiles whose bytes are there + by_read: FxHashMap>, + /// window tiles none of whose bytes have gone up yet (or whose pages changed place) + fresh: Vec, + /// window tile → submit epoch when last referenced (`base_for`, `show`, or dirty upload) + last_used: FxHashMap, + /// title tiles whose backing read page has been observed committed at least once + backed: HashSet, + /// monotonically incremented once per `sync()` submission + epoch: u64, + /// the next title tile the slow check looks at + turn: usize, + /// GPU-view mappings seen (`kernelx::gpu_view_map_gen`) + gen: u64, +} + +static MIRRORS: Mutex> = Mutex::new(None); + +impl Mirrors { + /// Title tile `title` is shown at window tile `win`, its bytes read from `read`. + pub(super) fn show(&mut self, win: usize, title: usize, read: usize) { + self.title_of.insert(win, title); + self.read.insert(title, read); + self.by_read.entry(read).or_default().push(win); + self.fresh.push(win); + self.last_used.insert(win, self.epoch); + } + + fn touch(&mut self, win: usize) { + if self.title_of.contains_key(&win) { + self.last_used.insert(win, self.epoch); + } + } + + fn set_read(&mut self, title: usize, read: usize) { + let old = self.read.insert(title, read); + if old == Some(read) { + return; + } + let wins: Vec = self.title_of.iter().filter(|&(_, &t)| t == title).map(|(&w, _)| w).collect(); + if let Some(o) = old { + if let Some(v) = self.by_read.get_mut(&o) { + v.retain(|w| !wins.contains(w)); + if v.is_empty() { + self.by_read.remove(&o); + } + } + } + self.by_read.entry(read).or_default().extend(&wins); + self.fresh.extend(wins); + } + + /// Remove `wins` from all mirror tables and prune orphaned `by_read`, `read`, `backed`, and + /// `fresh` entries. Returns the number of mapped window tiles removed. + fn evict_windows(&mut self, wins: &[usize]) -> usize { + if wins.is_empty() { + return 0; + } + let mut evicted = 0usize; + let mut affected_titles: HashSet = HashSet::new(); + let mut touched_reads: HashSet = HashSet::new(); + for &w in wins { + let Some(title) = self.title_of.remove(&w) else { continue }; + self.last_used.remove(&w); + affected_titles.insert(title); + if let Some(&r) = self.read.get(&title) { + touched_reads.insert(r); + } + evicted += 1; + } + if evicted == 0 { + return 0; + } + for r in touched_reads { + if let Some(v) = self.by_read.get_mut(&r) { + v.retain(|w| self.title_of.contains_key(w)); + if v.is_empty() { + self.by_read.remove(&r); + } + } + } + self.fresh.retain(|w| self.title_of.contains_key(w)); + for &t in self.title_of.values() { + affected_titles.remove(&t); + } + for title in affected_titles { + self.read.remove(&title); + self.backed.remove(&title); + } + evicted + } + + /// Evict every window tile showing `title` if none were touched in the current submit epoch. + fn evict_title_if_idle(&mut self, title: usize) -> Vec { + let wins: Vec = self.title_of.iter().filter(|&(_, &t)| t == title).map(|(&w, _)| w).collect(); + if wins.is_empty() || wins.iter().any(|w| self.last_used.get(w).copied().unwrap_or(0) >= self.epoch) { + return Vec::new(); + } + self.evict_windows(&wins); + wins + } + + /// Select up to `want` least-recently-used window tiles at least `min_age` submits old and + /// outside `protect`, ordered oldest-first. + fn lru_eviction_candidates(&self, want: usize, min_age: u64, protect: &HashSet) -> Vec { + if want == 0 { + return Vec::new(); + } + let mut cold: Vec<(u64, usize)> = self + .title_of + .keys() + .filter(|w| !protect.contains(w)) + .filter_map(|&w| { + let last = self.last_used.get(&w).copied().unwrap_or(0); + (self.epoch.saturating_sub(last) >= min_age).then_some((last, w)) + }) + .collect(); + cold.sort_unstable(); + cold.truncate(want); + cold.into_iter().map(|(_, w)| w).collect() + } + + /// The window tiles and pages a set of written pages (`dirty`, title or CPU addresses) is + /// shown at: (window page, the read address of its bytes). + pub(super) fn shown_at(&self, dirty: &[usize]) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + for &d in dirty { + let tile = d & !(TILE - 1); + for &w in self.by_read.get(&tile).map(Vec::as_slice).unwrap_or(&[]) { + out.push((w + (d - tile), d)); + } + } + out + } + + pub(super) fn tiles(&self) -> usize { + self.title_of.len() + } +} + +/// Decommit evicted mirror window tiles in coalesced contiguous runs so `sparse::State` parks, +/// unmaps, and returns their 64 KiB VRAM tiles (and empty 64 MiB pools) safely. +unsafe fn decommit_window_tiles(s: &mut State, wins: &mut [usize]) { + if wins.is_empty() { + return; + } + wins.sort_unstable(); + let mut i = 0; + while i < wins.len() { + let start = wins[i]; + let mut end = start + TILE; + i += 1; + while i < wins.len() && (wins[i] == end || wins[i] == end - TILE) { + if wins[i] == end { + end += TILE; + } + i += 1; + } + s.decommit_range(start, end - start); + } +} + +/// Whether `title` (a 64 KiB tile in a GPU view) has lost its backing: either the GPU-view +/// reservation was released, the page was explicitly unmapped via `CopyPageMappingsBatchX`, or +/// a previously committed backing tile has been completely decommitted. Returns `(dead, read)`. +unsafe fn check_title_tile(title: usize, was_backed: bool) -> (bool, usize) { + if crate::hle::kernelx::mirrors::source(title).is_none() { + return (true, title); + } + if crate::hle::kernelx::mirrors::mapped_source(title) == Some(None) { + return (true, title); + } + let read = super::super::title_textures::mirror_source(title) & !(TILE - 1); + if was_backed + && query_tile_holes(read) == 0xFFFF + && !crate::hle::kernelx::lazy::is_lazy(read) + && !crate::hle::kernelx::physical_page_at(read) + { + return (true, read); + } + (false, read) +} + +/// Copies `n` bytes from the title's memory at `at`; false when the page went away (nothing read). +unsafe fn read_title(at: usize, out: *mut u8, n: usize) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + let mut got = 0usize; + ReadProcessMemory(windows_sys::Win32::System::Threading::GetCurrentProcess(), at as *const c_void, out as *mut c_void, n, &mut got) != 0 && got == n +} + +impl State { + /// Brings the mirrored tiles in step with the title's memory: whole tiles that are new, and + /// the pages the title wrote (`dirty`). Before the title's lists; `m` is held by the caller. + pub(super) unsafe fn mirror_up(&mut self, m: &mut Mirrors, dirty: &[usize]) -> usize { + let mut pages: Vec<(usize, usize)> = m.shown_at(dirty); + let dirty_count = pages.len(); + for &(win, _) in &pages[..dirty_count] { + m.touch(win & !(TILE - 1)); + } + for win in std::mem::take(&mut m.fresh) { + let Some(&title) = m.title_of.get(&win) else { continue }; + let read = m.read[&title]; + pages.extend((0..PAGES_PER_TILE).map(|i| (win + i * PAGE, read + i * PAGE))); + } + pages.sort_unstable(); + pages.dedup(); + let mut runs: Vec<(usize, usize)> = Vec::new(); + let mut from: FxHashMap = FxHashMap::default(); + let mut bytes = [0u8; PAGE]; + for (win, read) in pages { + let tile = win & !(TILE - 1); + let Some(entry) = self.mapped.get_mut(&tile) else { continue }; + if !read_title(read, bytes.as_mut_ptr(), PAGE) { + continue; + } + if let Some(&title) = m.title_of.get(&tile) { + m.backed.insert(title); + } + let i = (win - tile) / PAGE; + entry.holes &= !(1u16 << i); + scan_page(&bytes, win, &mut entry.sent[i], &mut runs); + from.insert(win, read); + } + let n = runs.iter().map(|r| r.1).sum(); + // (the title tile a run lies in never changes within it: a run is at most a page here, but + // `push_run` joins neighbours, and two neighbouring pages may come from two places) + let split: Vec<(usize, usize)> = runs.iter().flat_map(|&(a, l)| { + let mut out = Vec::new(); + let (mut a, end) = (a, a + l); + while a < end { + let e = ((a & !(PAGE - 1)) + PAGE).min(end); + out.push((a, e - a)); + a = e; + } + out + }).collect(); + self.upload_runs(&split, &|dst, p, len| { + let page = dst & !(PAGE - 1); + from.get(&page).is_some_and(|r| read_title(r + (dst - page), p, len)) + }); + n + } +} + +/// The address a view of `len` bytes at `va` gets when it lies in a GPU view of the title's and +/// in no memory window: where the same bytes can be read by a shader. None: it keeps `va`. +pub fn base_for(va: usize, len: usize) -> Option { + if !on() || len == 0 { + return None; + } + if len > MOST { + if crate::hle::kernelx::mirrors::source(va).is_some() { + refused(1, va, len); + } + return None; + } + let u = crate::gpu::uma::get()?; + if u.contains(va) || !u.has_sparse() { + return None; + } + let last = va.checked_add(len)?.checked_sub(1)?; + crate::hle::kernelx::mirrors::source(va)?; + crate::hle::kernelx::mirrors::source(last)?; + let (t0, t1) = (va & !(TILE - 1), (last & !(TILE - 1)) + TILE); + let first = t0 & !(EXTENT - 1); + let n = (t1 - first).div_ceil(EXTENT); + let known = MIRRORS.lock().unwrap().get_or_insert_with(Mirrors::default).extents.get(&(first, n)).copied(); + let win = match known { + Some(w) => w, + None => { + let (w, _) = u.sparse_alloc(n * EXTENT, EXTENT)?; + *MIRRORS.lock().unwrap().get_or_insert_with(Mirrors::default).extents.entry((first, n)).or_insert(w) + } + }; + // Resolve every tile's CPU source and committed-page hole mask BEFORE locking `sparse::STATE` + // so `STATE` is never held across `kernelx::AWAY` / `mirrors` locks (preventing ABBA deadlock + // with `XMemMapPhysicalPages` / `CopyPageMappingsBatchX` which hold `AWAY` -> `STATE`). + let resolved: Vec<(usize, usize, u16)> = (t0..t1) + .step_by(TILE) + .map(|t| { + let src = super::super::title_textures::mirror_source(t) & !(TILE - 1); + let holes = unsafe { query_tile_holes(src) }; + (t, src, holes) + }) + .collect(); + let resolved_of = |t: usize| -> (usize, u16) { + resolved + .binary_search_by_key(&t, |&(k, _, _)| k) + .map_or((t, 0xFFFF), |i| (resolved[i].1, resolved[i].2)) + }; + // (held: STATE, then MIRRORS, as in `apply_sync`) + let mut g = lock_state(); + let s = g.as_mut()?; + let mut mg = MIRRORS.lock().unwrap(); + let m = mg.get_or_insert_with(Mirrors::default); + let new: Vec = (t0..t1).step_by(TILE).filter(|t| !m.title_of.contains_key(&(win + (t - first)))).collect(); + for t in (t0..t1).step_by(TILE) { + m.touch(win + (t - first)); + } + if !new.is_empty() { + let limit = budget() / TILE; + if m.tiles() + new.len() > limit { + let need = (m.tiles() + new.len()).saturating_sub(limit); + let protect: HashSet = (t0..t1).step_by(TILE).map(|t| win + (t - first)).collect(); + let want = need.saturating_add(EVICT_BATCH_EXTRA); + let mut victims = m.lru_eviction_candidates(want, EVICT_GRACE_SUBMITS, &protect); + if victims.len() >= need { + let n = m.evict_windows(&victims); + // SAFETY: evicted mirror tiles live in sparse window VA with no CPU backing. + unsafe { decommit_window_tiles(s, &mut victims) }; + static EVICTED: AtomicU64 = AtomicU64::new(0); + let prev = EVICTED.fetch_add(n as u64, Ordering::Relaxed); + let total = prev + n as u64; + if prev == 0 || (total >> 10) > (prev >> 10) { + crate::xlog_info!("D3D12.X: GPU view mirrors evicted {n} cold tiles ({} MB total reclaimed, {} tiles live)", (total as usize * TILE) >> 20, m.tiles()); + } + } + } + if m.tiles() + new.len() > limit { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: the buffers of the GPU view take more than XCL_GPU_VIEW_MB: the rest keeps its address")); + drop(mg); + drop(g); + refused(0, t0, t1 - t0); + return None; + } + // whole runs of new tiles at once (a mapping call and a signal for each run) + let mut i = 0; + while i < new.len() { + let mut j = i + 1; + while j < new.len() && new[j] == new[j - 1] + TILE { + j += 1; + } + let (a, b) = (new[i], win + (new[i] - first)); + // SAFETY: the tiles are address space of a window, with no CPU memory behind them + unsafe { s.ensure_mapped(b, (j - i) * TILE, |w| resolved_of(a + (w - b)).1) }; + for &t in &new[i..j] { + let w = win + (t - first); + if s.mapped.contains_key(&w) { + let (src, holes) = resolved_of(t); + m.show(w, t, src); + if holes != 0xFFFF { + m.backed.insert(t); + } + } + } + i = j; + } + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed) + 1; + if k.is_power_of_two() { + crate::xlog_info!("D3D12.X: buffers of the GPU view: {} tiles mirrored ({} MB), latest view {va:#x} ({len} B)", m.tiles(), (m.tiles() * TILE) >> 20); + } + } + if (t0..t1).step_by(TILE).any(|t| !m.title_of.contains_key(&(win + (t - first)))) { + return None; + } + Some(win + (va - first)) +} + +/// local: what views kept their address (they read zeros): `kind` 0 the budget, 1 longer than +/// `MOST`; the distinct title tiles of each, logged as they grow +fn refused(kind: usize, at: usize, len: usize) { + static SEEN: Mutex; 2]>> = Mutex::new(None); + static VIEWS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + let k = VIEWS[kind].fetch_add(1, Ordering::Relaxed) + 1; + let mut g = SEEN.lock().unwrap(); + let set = &mut g.get_or_insert_with(Default::default)[kind]; + for t in (at & !(TILE - 1)..at + len).step_by(TILE).take(4096) { + set.insert(t); + } + if k.is_power_of_two() { + crate::xlog_info!("D3D12.X: GPU view buffers refused ({}): {k} views, {} distinct tiles ({} MB), latest {at:#x} ({len} B)", ["budget", "longer than MOST"][kind], set.len(), (set.len() * TILE) >> 20); + } +} + +/// The pages of the CPU (and pool) side whose writes have to be seen: for the write watch. +pub fn sources() -> Vec<(usize, usize)> { + MIRRORS.lock().unwrap().as_ref().map_or(Vec::new(), |m| m.by_read.keys().map(|&r| (r, r + TILE)).collect()) +} + +/// Pre-checked GPU-view tile liveness & backing-address updates collected outside `sparse::STATE` +/// so `apply_sync` never acquires `kernelx::AWAY` / `mirrors` locks while holding `sparse::STATE`. +pub(super) struct PreparedSync { + checked: Vec<(usize, bool, usize, u16)>, +} + +/// Phase 1 of GPU-view sync (called BEFORE locking `sparse::STATE`): snapshot candidate tiles +/// under `MIRRORS`, drop `MIRRORS`, and query `kernelx` backing mappings with no locks held. +pub(super) unsafe fn prepare_sync() -> Option { + let look: Vec<(usize, bool)> = { + let mut g = MIRRORS.lock().unwrap(); + let m = g.as_mut().filter(|m| m.tiles() != 0)?; + let gen = crate::hle::kernelx::gpu_view_map_gen(); + let titles: Vec = m.read.keys().copied().collect(); + let picked: Vec = if std::mem::replace(&mut m.gen, gen) != gen { + titles + } else { + let n = titles.len().max(1); + (0..SWEEP_PER_SUBMIT.min(titles.len())).map(|i| titles[(m.turn + i) % n]).collect() + }; + m.turn = m.turn.wrapping_add(SWEEP_PER_SUBMIT); + picked.into_iter().map(|t| (t, m.backed.contains(&t))).collect() + }; + let mut checked = Vec::with_capacity(look.len()); + for (t, was_backed) in look { + let (dead, r) = check_title_tile(t, was_backed); + let holes = if !dead && !was_backed { query_tile_holes(r) } else { 0xFFFF }; + checked.push((t, dead, r, holes)); + } + Some(PreparedSync { checked }) +} + +/// Phase 2 of GPU-view sync (`before_execute`; `s` is the locked `sparse::STATE`): apply +/// pre-checked liveness/remap updates and upload dirty mirrored pages with zero `kernelx` locks. +pub(super) unsafe fn apply_sync(s: &mut State, dirty: &[usize], prepared: Option) { + let mut g = MIRRORS.lock().unwrap(); + let Some(m) = g.as_mut().filter(|m| m.tiles() != 0) else { return }; + m.epoch = m.epoch.wrapping_add(1); + let mut dead_wins: Vec = Vec::new(); + if let Some(prep) = prepared { + for (t, dead, r, holes) in prep.checked { + if !m.read.contains_key(&t) { + continue; + } + if dead { + dead_wins.extend(m.evict_title_if_idle(t)); + continue; + } + if holes != 0xFFFF { + m.backed.insert(t); + } + m.set_read(t, r); + } + } + if !dead_wins.is_empty() { + let evicted = dead_wins.len(); + decommit_window_tiles(s, &mut dead_wins); + static UNMAPPED_EVICTED: AtomicU64 = AtomicU64::new(0); + let prev = UNMAPPED_EVICTED.fetch_add(evicted as u64, Ordering::Relaxed); + let total = prev + evicted as u64; + if prev == 0 || (total >> 10) > (prev >> 10) { + crate::xlog_info!("D3D12.X: GPU view mirrors reclaimed {evicted} unmapped tiles ({} MB total, {} tiles live)", (total as usize * TILE) >> 20, m.tiles()); + } + } + let n = s.mirror_up(m, dirty); + static SENT: AtomicU64 = AtomicU64::new(0); + static CALLS: AtomicU64 = AtomicU64::new(0); + let total = SENT.fetch_add(n as u64, Ordering::Relaxed) + n as u64; + let k = CALLS.fetch_add(1, Ordering::Relaxed) + 1; + if k.is_power_of_two() && k >= 64 { + crate::xlog_info!("D3D12.X: buffers of the GPU view: {} tiles, {} MB sent in {k} submits", m.tiles(), total >> 20); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_written_page_is_shown_at_every_window_tile_it_is_read_for() { + let mut m = Mirrors::default(); + m.show(0x10_0000, 0xAA_0000, 0xAA_0000); + m.show(0x20_0000, 0xAA_0000, 0xAA_0000); + m.show(0x30_0000, 0xBB_0000, 0xCC_0000); + assert_eq!(m.tiles(), 3); + let mut a = m.shown_at(&[0xAA_3000]); + a.sort(); + assert_eq!(a, vec![(0x10_3000, 0xAA_3000), (0x20_3000, 0xAA_3000)]); + assert_eq!(m.shown_at(&[0xCC_1000]), vec![(0x30_1000, 0xCC_1000)], "by the read address, not the title's"); + assert!(m.shown_at(&[0xBB_1000]).is_empty()); + m.fresh.clear(); + // the page behind a title tile moved: its window tiles are sent whole again + m.set_read(0xBB_0000, 0xDD_0000); + assert_eq!(m.fresh, vec![0x30_0000]); + assert!(m.shown_at(&[0xCC_1000]).is_empty()); + assert_eq!(m.shown_at(&[0xDD_2000]), vec![(0x30_2000, 0xDD_2000)]); + m.set_read(0xBB_0000, 0xDD_0000); + assert_eq!(m.fresh, vec![0x30_0000], "the same place again is nothing new"); + } + + #[test] + fn evict_windows_cleans_all_indices_and_orphaned_sources() { + let mut m = Mirrors::default(); + m.show(0x10_0000, 0xAA_0000, 0xCC_0000); + m.show(0x20_0000, 0xAA_0000, 0xCC_0000); + m.show(0x30_0000, 0xBB_0000, 0xDD_0000); + m.backed.insert(0xAA_0000); + m.backed.insert(0xBB_0000); + // Evicting one of two window aliases keeps the shared title/read entry alive. + assert_eq!(m.evict_windows(&[0x10_0000]), 1); + assert_eq!(m.tiles(), 2); + assert!(m.read.contains_key(&0xAA_0000)); + assert_eq!(m.shown_at(&[0xCC_1000]), vec![(0x20_1000, 0xCC_1000)]); + assert!(!m.fresh.contains(&0x10_0000)); + // Evicting the last alias removes title, backed, and empty by_read source entries. + assert_eq!(m.evict_windows(&[0x20_0000]), 1); + assert_eq!(m.tiles(), 1); + assert!(!m.read.contains_key(&0xAA_0000)); + assert!(!m.backed.contains(&0xAA_0000)); + assert!(!m.by_read.contains_key(&0xCC_0000)); + assert_eq!(m.shown_at(&[0xDD_2000]), vec![(0x30_2000, 0xDD_2000)]); + } + + #[test] + fn lru_eviction_respects_grace_window_and_protected_tiles() { + let mut m = Mirrors::default(); + m.epoch = 1; + m.show(0x10_0000, 0xA0_0000, 0xA0_0000); + m.epoch = 5; + m.show(0x20_0000, 0xB0_0000, 0xB0_0000); + m.epoch = 20; + m.show(0x30_0000, 0xC0_0000, 0xC0_0000); + m.epoch = 25; + // At epoch 25 with grace 16: 0x10 (age 24) and 0x20 (age 20) are cold; 0x30 (age 5) is hot. + let protect: HashSet = [0x10_0000].into_iter().collect(); + assert_eq!(m.lru_eviction_candidates(4, EVICT_GRACE_SUBMITS, &protect), vec![0x20_0000]); + assert_eq!(m.lru_eviction_candidates(4, EVICT_GRACE_SUBMITS, &HashSet::new()), vec![0x10_0000, 0x20_0000]); + // Touching 0x10 makes it hot in the current epoch, so evict_title_if_idle skips it too. + m.touch(0x10_0000); + assert!(m.evict_title_if_idle(0xA0_0000).is_empty()); + assert_eq!(m.evict_title_if_idle(0xB0_0000), vec![0x20_0000]); + } + + /// The bytes of the title's pages reach the window tiles mapped for them, and again when the + /// title writes a page; a page that went away is left as it is. + #[test] + fn gpu_the_titles_bytes_reach_the_window_tiles_shown_for_them() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.expect("D3D12 device"); + let window = VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + let source = VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert!(window % TILE == 0 && source % TILE == 0); + for i in 0..TILE / 4 { + *((source + 4 * i) as *mut u32) = i as u32 * 7 + 1; + } + let mut reserved: Option = None; + dev.CreateReservedResource(&buffer_desc(TILE as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved).expect("reserved buffer"); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let rb_queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("rb_queue"); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let rb_done_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_done_fence"); + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); + let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("list"); + rb_list.Close().expect("close"); + let mut slots = Vec::new(); + for _ in 0..UPLOAD_SLOTS { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list"); + list.Close().expect("close"); + slots.push(UploadSlot { alloc, list, fence_val: 0 }); + } + let mut s = State { + dev, + queue, + fence, + value: 0, + event, + rb_queue, + rb_fence, + rb_value: 0, + mapping_queued: std::sync::atomic::AtomicBool::new(false), + mapped_value: 0, + rb_done_fence, + rb_done_value: 0, + windows: vec![(window, reserved.expect("reserved buffer"))], + pools: Vec::new(), + free: Vec::new(), + retired: Vec::new(), + mapped: FxHashMap::default(), + pinned: FxHashMap::default(), + parked: FxHashMap::default(), + pending_unmaps: VecDeque::new(), + pending_unmap_va: FxHashMap::default(), + unmap_seq: 0, + quarantined: VecDeque::new(), + pending_quarantine: Vec::new(), + queue_fences: FxHashMap::default(), + buffers: FxHashMap::default(), + to_zero: Vec::new(), + staging: None, + ring_write: 0, + ring_submitted: 0, + ring_free: 0, + inflight: VecDeque::new(), + zero_buf: None, + slots, + next_slot: 0, + readback: None, + rb_alloc, + rb_list, + rb_last_fence: 0, + waited: FxHashMap::default(), + runs: None, + scratch_runs: Vec::new(), + }; + let mut m = Mirrors::default(); + s.ensure_mapped(window, TILE, |_| query_tile_holes(source)); + m.show(window, 0x7FFF_0000, source); + let at = |i: usize| *((window + 4 * i) as *const u32); + let shown = |s: &mut State, m: &mut Mirrors, dirty: &[usize]| { + s.mirror_up(m, dirty); + s.readback_ranges(&[(window, TILE)]); + }; + shown(&mut s, &mut m, &[]); + assert!((0..TILE / 4).all(|i| at(i) == i as u32 * 7 + 1), "the whole tile at first"); + // a page the title wrote (and one it did not) + *((source + 0x3010) as *mut u32) = 0xDEAD_BEEF; + shown(&mut s, &mut m, &[source + 0x3000]); + assert_eq!((at(0x3010 / 4), at(0x3014 / 4)), (0xDEAD_BEEF, (0x3014 / 4) as u32 * 7 + 1)); + // not reported as written: not sent + *((source + 0x4010) as *mut u32) = 0x1234_5678; + shown(&mut s, &mut m, &[]); + assert_eq!(at(0x4010 / 4), (0x4010 / 4) as u32 * 7 + 1); + // the page is gone: what the GPU has stays, and nothing faults + assert_ne!(VirtualFree(source as *mut c_void, 0, MEM_RELEASE), 0); + m.fresh.push(window); + shown(&mut s, &mut m, &[source + 0x5000]); + assert_eq!(at(0x3010 / 4), 0xDEAD_BEEF); + s.wait_for(s.value); + drop(s); + VirtualFree(window as *mut c_void, 0, MEM_RELEASE); + } + } + + #[test] + fn prepare_sync_does_not_require_state_lock() { + // Holding `sparse::STATE` on the current thread must not block `prepare_sync`, proving + // Phase 1 runs without `STATE` and cannot ABBA-deadlock against `kernelx::AWAY -> STATE`. + let _held = STATE.lock().unwrap(); + let prep = unsafe { prepare_sync() }; + let _ = prep; + } +} diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index a41e5643fc..b743b7c216 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -59,6 +59,34 @@ static WRAPPER_OF: Mutex>> = Mutex::new(None); struct Vtable(usize); +/// Command-list vtable slots (PC + older/newer console layouts) that can write to GPU buffers +/// or wait on cross-queue fences: calling any of them marks the active recording segment as +/// having GPU writes/waits so subsequent indirect argument clamps stay inline instead of being +/// hoisted into the segment's prelude command list. +fn is_gpu_write_or_wait_slot(slot: usize) -> bool { + matches!( + slot, + 15..=18 // CopyBufferRegion, CopyTextureRegion, CopyResource, CopyTiles + | 27 // ExecuteBundle + | 30 // ResolveQueryData (console #30 = PC #54) + | 53..=54 // ClearUnorderedAccessView{Uint,Float} (console #53/#54 = PC #49/#50) + | 60..=65 // CopyMemoryToMemoryX / Fill{32,64,128}X (older + newer +2 shifted; #61 filtered below) + | 69..=74 // Write{32,64}BottomX / Wait{32,64}X (older + newer +2 shifted; #70 filtered below) + | 83..=86 // Copy{TextureRegion,Resource}FlagsX (older + newer +2 shifted; #83 filtered below) + | 88..=92 // Write{32,64}TopX / Write32BottomOfShaderX (older + newer +2 shifted) + | 104..=105 // AtomicCopyBufferUINT / UINT64 + ) +} + +fn slot_writes_or_waits_now(slot: usize, shifted: bool) -> bool { + if !is_gpu_write_or_wait_slot(slot) { + return false; + } + // On the newer console layout (+2 shifted), #61 is ExecuteIndirect, #70 is SetDepthBoundsX, + // and #83 is DrawIndexedX – none of these write indirect arguments. + !(shifted && matches!(slot, 61 | 70 | 83)) +} + /// The console list vtable: QueryInterface / AddRef / Release / Close / Reset of their own, /// every other slot a thunk to the currently active PC list's entry (`F_BACKING`). fn vtable() -> usize { @@ -67,7 +95,13 @@ fn vtable() -> usize { let mut v = vec![0usize; LIST_SLOTS]; let trace = std::env::var_os("XCL_LIST_TRACE").is_some(); for (slot, e) in v.iter_mut().enumerate() { - *e = if trace { forward_traced(slot) } else { forward(slot) }; + *e = if trace { + forward_precall(slot, record as usize) + } else if is_gpu_write_or_wait_slot(slot) { + forward_precall(slot, note_write_or_wait as usize) + } else { + forward(slot) + }; } v[0] = qi as usize; v[1] = add_ref as usize; @@ -93,8 +127,8 @@ fn forward(slot: usize) -> usize { p as usize } -/// `forward` after `record(this, slot)` (argument registers, xmm0–3 kept) -fn forward_traced(slot: usize) -> usize { +/// `forward` after calling `precall(this, slot)` (argument registers and xmm0–3 preserved). +fn forward_precall(slot: usize, precall: usize) -> usize { let mut c: Vec = vec![0x51, 0x52, 0x41, 0x50, 0x41, 0x51]; // push rcx, rdx, r8, r9 c.extend_from_slice(&[0x48, 0x83, 0xEC, 0x68]); // sub rsp, 0x68 for (reg, off) in [(0x44u8, 0x20u8), (0x4C, 0x30), (0x54, 0x40), (0x5C, 0x50)] { @@ -102,8 +136,8 @@ fn forward_traced(slot: usize) -> usize { } c.push(0xBA); // mov edx, slot c.extend_from_slice(&(slot as u32).to_le_bytes()); - c.extend_from_slice(&[0x48, 0xB8]); // mov rax, record - c.extend_from_slice(&(record as usize as u64).to_le_bytes()); + c.extend_from_slice(&[0x48, 0xB8]); // mov rax, precall + c.extend_from_slice(&(precall as u64).to_le_bytes()); c.extend_from_slice(&[0xFF, 0xD0]); // call rax for (reg, off) in [(0x44u8, 0x20u8), (0x4C, 0x30), (0x54, 0x40), (0x5C, 0x50)] { c.extend_from_slice(&[0xF3, 0x0F, 0x6F, reg, 0x24, off]); // movdqu xmmN, [rsp+off] @@ -121,11 +155,20 @@ fn forward_traced(slot: usize) -> usize { p as usize } +unsafe extern "system" fn note_write_or_wait(this: *mut c_void, slot: u32) { + let shifted = super::real::QUEUE_SHIFTED.load(std::sync::atomic::Ordering::Relaxed); + if slot_writes_or_waits_now(slot as usize, shifted) { + let pc = *((this as usize + F_BACKING) as *const *mut c_void); + super::bind::note_gpu_write(pc); + } +} + unsafe extern "system" fn record(this: *mut c_void, slot: u32) { let at = (this as usize + F_RING_AT) as *mut usize; let k = *at % RING; *((this as usize + F_RING + 2 * k) as *mut u16) = slot as u16; *at += 1; + note_write_or_wait(this, slot); } /// #9 Close: closes the active recording segment (`F_BACKING`); a failure is logged with @@ -134,6 +177,9 @@ unsafe extern "system" fn close(this: *mut c_void) -> HRESULT { let pc = *((this as usize + F_BACKING) as *const *mut c_void); let f: unsafe extern "system" fn(*mut c_void) -> HRESULT = std::mem::transmute(pc_slot(pc, 9)); let hr = f(pc); + if hr >= 0 { + super::title_textures::note_list_closed(this); + } let n = *((this as usize + F_RING_AT) as *const usize); if hr < 0 && n > 0 { let first = n.saturating_sub(RING); @@ -194,6 +240,11 @@ 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); + super::alloc_pool::retire_recording(seg); + } + if stand_in.is_some() { + super::bind::reset(primary, 0, 0); + super::alloc_pool::retire_recording(primary as usize); } } *((this as usize + F_RING_AT) as *mut usize) = 0; @@ -244,19 +295,39 @@ pub fn backing(list: *mut c_void) -> Option<*mut c_void> { unsafe { (*(list as *const usize) == vtable()).then(|| *((list as usize + F_PRIMARY) as *const *mut c_void)) } } -/// Expand a console list object into all of its recorded PC command list segments (in exact -/// recording order). Returns `false` if `list` is not a `title_list` wrapper. -pub fn push_segments(list: *mut c_void, out: &mut Vec<*mut c_void>) -> bool { +/// Expand a console list object into its raw recorded PC command list segments (in exact +/// recording order) WITHOUT building or inserting prelude command lists. Use this for +/// read-only inspection (`deferred_segment`, `record_deferred`) so mid-recording queries never +/// freeze `prelude_list_for` early or mistake a prelude list for `wrapper`'s first segment. +pub fn raw_segments(list: *mut c_void, out: &mut Vec<*mut c_void>) -> bool { let Some(primary) = backing(list) else { return false; }; - let sg = SEGMENTS.lock().unwrap(); - let book = sg.as_ref().and_then(|m| m.get(&(list as usize))); - out.push(book.and_then(|b| b.first).map_or(primary, |f| f as *mut c_void)); - if let Some(book) = book { - for &seg in &book.extra_active { - out.push(seg as *mut c_void); + let (first, extras) = { + let sg = SEGMENTS.lock().unwrap(); + let book = sg.as_ref().and_then(|m| m.get(&(list as usize))); + let first = book.and_then(|b| b.first).map_or(primary, |f| f as *mut c_void); + let extras: Vec<*mut c_void> = book.map_or_else(Vec::new, |b| b.extra_active.iter().map(|&s| s as *mut c_void).collect()); + (first, extras) + }; + out.push(first); + out.extend(extras); + true +} + +/// Expand a console list object into all of its recorded PC command list segments (in exact +/// recording order), inserting any hoisted indirect-argument / VRAM-io prelude list right before +/// the segment that consumes it. Returns `false` if `list` is not a `title_list` wrapper. +pub fn push_segments(list: *mut c_void, out: &mut Vec<*mut c_void>) -> bool { + let mut raw = Vec::new(); + if !raw_segments(list, &mut raw) { + return false; + } + for seg in raw { + if let Some(prelude) = unsafe { super::bind::prelude_list_for(seg) } { + out.push(prelude); } + out.push(seg); } true } @@ -288,6 +359,7 @@ pub(super) fn pop_spare(wrapper: *mut c_void) -> Option<*mut c_void> { /// 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) { + super::alloc_pool::retire_recording(pc as usize); let mut sg = SEGMENTS.lock().unwrap(); sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().spares.push(pc as usize); } @@ -314,19 +386,27 @@ pub(super) unsafe fn activate_segment(wrapper: *mut c_void, old_pc: *mut c_void, m.insert(new_pc as usize, wrapper as usize); } -/// For `KickoffX` on an already-split list: returns `(primary, prior_closed_segments, extra_to_reclaim)` -/// when `active_pc != primary`, switches `F_BACKING` back to `primary`, and moves all extra +/// For `KickoffX`: returns `(primary, prior_closed_segments, extra_to_reclaim)` when `active_pc` +/// was split mid-recording OR has hoisted indirect-argument prelude work that must execute right +/// before `active_pc`. When split, switches `F_BACKING` back to `primary` and moves all extra /// segments (including `active_pc`) into `spares` so recording resumes cleanly on `primary`. /// (`primary` here is the recording's first segment: `first` when one stands in.) pub(super) unsafe fn reclaim_for_kickoff(active_pc: *mut c_void) -> Option<(*mut c_void, Vec<*mut c_void>, Vec)> { let wrapper = wrapper_of(active_pc)?; - let mut sg = SEGMENTS.lock().unwrap(); - let book = sg.as_mut().and_then(|m| m.get_mut(&(wrapper as usize)))?; - let primary = book.first.map_or_else(|| *((wrapper as usize + F_PRIMARY) as *const *mut c_void), |f| f as *mut c_void); + let primary = { + let sg = SEGMENTS.lock().unwrap(); + sg.as_ref() + .and_then(|m| m.get(&(wrapper as usize))) + .and_then(|b| b.first) + .map_or_else(|| *((wrapper as usize + F_PRIMARY) as *const *mut c_void), |f| f as *mut c_void) + }; if primary == active_pc { - return None; + let prelude = super::bind::prelude_list_for(active_pc)?; + return Some((primary, vec![prelude], Vec::new())); } - let (prior, reclaimed) = { + let (raw_prior, reclaimed) = { + let mut sg = SEGMENTS.lock().unwrap(); + let book = sg.as_mut().and_then(|m| m.get_mut(&(wrapper as usize)))?; let extra = std::mem::take(&mut book.extra_active); let mut prior = Vec::with_capacity(extra.len()); prior.push(primary); @@ -338,7 +418,6 @@ pub(super) unsafe fn reclaim_for_kickoff(active_pc: *mut c_void) -> Option<(*mut book.spares.extend(extra.iter().copied()); (prior, extra) }; - drop(sg); *((wrapper as usize + F_BACKING) as *mut usize) = primary as usize; { let mut wg = WRAPPER_OF.lock().unwrap(); @@ -349,6 +428,16 @@ pub(super) unsafe fn reclaim_for_kickoff(active_pc: *mut c_void) -> Option<(*mut m.insert(primary as usize, wrapper as usize); } } + let mut prior = Vec::with_capacity(raw_prior.len() * 2 + 1); + for seg in raw_prior { + if let Some(p) = super::bind::prelude_list_for(seg) { + prior.push(p); + } + prior.push(seg); + } + if let Some(p) = super::bind::prelude_list_for(active_pc) { + prior.push(p); + } Some((primary, prior, reclaimed)) } @@ -641,4 +730,24 @@ mod tests { drop(Box::from_raw(seg1)); } } + + #[test] + fn gpu_write_and_wait_slots_track_older_and_newer_layouts() { + // Common buffer-write / bundle / clear / wait slots block prelude hoisting on both layouts. + for slot in [15, 16, 17, 18, 27, 30, 53, 54, 60, 62, 71, 72, 84, 86, 88, 89, 90, 91, 92, 104, 105] { + assert!(slot_writes_or_waits_now(slot, false), "older slot {slot}"); + assert!(slot_writes_or_waits_now(slot, true), "newer slot {slot}"); + } + // On the newer (+2 shifted) layout, #61 is ExecuteIndirect, #70 is SetDepthBoundsX, and + // #83 is DrawIndexedX – must NOT block hoisting when shifted, while blocking on older. + for slot in [61, 70, 83] { + assert!(slot_writes_or_waits_now(slot, false), "older slot {slot}"); + assert!(!slot_writes_or_waits_now(slot, true), "newer non-write slot {slot}"); + } + // Hot draw / PSO / root-arg slots never block prelude hoisting. + for slot in [12, 13, 25, 34, 36, 38, 40, 42, 44, 46, 59, 127, 129] { + assert!(!slot_writes_or_waits_now(slot, false), "non-write slot {slot}"); + assert!(!slot_writes_or_waits_now(slot, true), "non-write slot {slot}"); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 6d97bc6e4e..53c5790fa0 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -20,7 +20,7 @@ //! (`note_transitions`) and applied, in submission order, when the list is submitted //! (`submitted`) – per subresource once a transition names one. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::ffi::c_void; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; @@ -38,8 +38,15 @@ extern "system" { fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; } -/// (device, address its bytes are read from, layout, states) of an upload -type Upload = (usize, usize, Arc, Vec); +/// Upload parameters for a pending or CPU-dirtied texture. +struct Upload { + device: usize, + src: usize, + tex: Arc, + states: Vec, + dirty_pages: Option>, + page_size: usize, +} struct Entry { device: usize, @@ -75,11 +82,22 @@ static PENDING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize: // raw COM pointers of the title's objects; uploads hold a reference while they run unsafe impl Send for Entry {} +/// Textures at or below this size are indexed in `Table::by_src_small` for bounded range queries +/// on dirty page runs; larger textures sit in `Table::by_src_large` so a single huge texture does +/// not widen small dirty-page range scans. +const SMALL_SRC_MAX: usize = 256 << 10; + struct Table { /// Active PC textures (newest at each range) → its place in the title's memory by_res: BTreeMap, /// Active `(va, PC texture)` → end address (`va + size`); entries with different `(va, end)` are disjoint by_va: BTreeMap<(usize, usize), usize>, + /// Active non-`gpu_written` textures with `size <= SMALL_SRC_MAX`, keyed by `(src, res) -> src + size` + by_src_small: BTreeMap<(usize, usize), usize>, + /// Active non-`gpu_written` textures with `size > SMALL_SRC_MAX`: `res -> (src, src + size)` + by_src_large: BTreeMap, + /// Active textures with `pending == true` + pending_res: BTreeSet, /// Older overlapped textures kept dormant until released or uncovered when a newer one is released shadowed: BTreeMap, /// Shadowed `(va, PC texture)` → end address (may overlap) @@ -94,6 +112,9 @@ impl Table { Table { by_res: BTreeMap::new(), by_va: BTreeMap::new(), + by_src_small: BTreeMap::new(), + by_src_large: BTreeMap::new(), + pending_res: BTreeSet::new(), shadowed: BTreeMap::new(), shadowed_by_va: BTreeMap::new(), max_shadowed_size: 0, @@ -101,6 +122,110 @@ impl Table { } } + fn index_active(&mut self, res: usize, src: usize, size: usize, gpu_written: bool, pending: bool) { + if pending { + self.pending_res.insert(res); + } + if !gpu_written && size > 0 { + let end = src.saturating_add(size); + if size <= SMALL_SRC_MAX { + self.by_src_small.insert((src, res), end); + } else { + self.by_src_large.insert(res, (src, end)); + } + } + } + + fn unindex_active(&mut self, res: usize, src: usize) { + self.pending_res.remove(&res); + self.by_src_small.remove(&(src, res)); + self.by_src_large.remove(&res); + } + + fn mark_pending(&mut self, res: usize) -> bool { + if let Some(e) = self.by_res.get_mut(&res) { + if !e.gpu_written && !e.pending { + e.pending = true; + self.pending_res.insert(res); + return true; + } + } + false + } + + fn mark_gpu_written(&mut self, res: usize) -> bool { + if let Some(e) = self.by_res.get_mut(&res) { + if !e.gpu_written { + e.gpu_written = true; + let src = e.src; + self.by_src_small.remove(&(src, res)); + self.by_src_large.remove(&res); + return true; + } + return false; + } + if let Some(e) = self.shadowed.get_mut(&res) { + if !e.gpu_written { + e.gpu_written = true; + return true; + } + } + false + } + + fn watchable_ranges(&self) -> Vec<(usize, usize)> { + self.by_res + .values() + .filter(|e| !e.gpu_written) + .map(|e| (e.src & !0xFFF, (e.src + e.tex.size() as usize + 0xFFF) & !0xFFF)) + .collect() + } + + /// Collect active textures that are pending or overlap any sorted dirty page in `dirty`, + /// clearing `pending` on returned entries and returning `((res, was_pending) list, pending_cleared)`. + fn dirty_and_pending(&mut self, dirty: &[usize], page: usize) -> (Vec<(usize, bool)>, usize) { + let mut hits: Vec<(usize, bool)> = Vec::with_capacity(self.pending_res.len() + 16); + let mut cleared = 0usize; + for res in std::mem::take(&mut self.pending_res) { + if let Some(e) = self.by_res.get_mut(&res) { + if e.pending { + e.pending = false; + cleared += 1; + } + hits.push((res, true)); + } + } + if !dirty.is_empty() && page > 0 { + // Merge contiguous dirty pages into spans so range lookups run once per span. + let mut i = 0; + while i < dirty.len() { + let lo = dirty[i]; + let mut hi = lo.saturating_add(page); + i += 1; + while i < dirty.len() && dirty[i] <= hi { + hi = hi.max(dirty[i].saturating_add(page)); + i += 1; + } + let q_lo = lo.saturating_sub(SMALL_SRC_MAX); + for (&(_, res), &end) in self.by_src_small.range((q_lo, 0)..(hi, 0)) { + if end > lo { + hits.push((res, false)); + } + } + } + for (&res, &(src, end)) in &self.by_src_large { + let idx = dirty.partition_point(|&p| p.saturating_add(page) <= src); + if dirty.get(idx).is_some_and(|&p| p < end) { + hits.push((res, false)); + } + } + } + // Keep `was_pending == true` when a resource was both pending and dirty-hit. + hits.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1))); + hits.dedup_by_key(|x| x.0); + (hits, cleared) + } + fn has_active_overlap(&self, va: usize, end: usize) -> bool { if let Some((_, &oend)) = self.by_va.range(..(va, 0)).next_back() { if oend > va { @@ -140,19 +265,20 @@ impl Table { /// Permanently retire active and shadowed entries overlapping `[va, end)` (used when a /// GPU-owned render target / depth / UAV overwrites the address range). Returns - /// `(pending_delta, retired_count, placed_res_to_unmap)`. - fn retire_range(&mut self, va: usize, end: usize) -> (isize, usize, Vec) { - let (mut pending_delta, mut retired, mut to_unmap) = (0isize, 0usize, Vec::new()); + /// `(pending_delta, retired_res, placed_res_to_unmap)`. + fn retire_range(&mut self, va: usize, end: usize) -> (isize, Vec, Vec) { + let (mut pending_delta, mut retired, mut to_unmap) = (0isize, Vec::new(), 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) { + self.unindex_active(ores, old.src); if old.pending { pending_delta -= 1; } if old.placed && !old.unmapped { to_unmap.push(ores); } - retired += 1; + retired.push(ores); } } for (sva, sres, _) in self.shadowed_overlaps(va, end) { @@ -161,7 +287,7 @@ impl Table { if old.placed && !old.unmapped { to_unmap.push(sres); } - retired += 1; + retired.push(sres); } } if self.shadowed.is_empty() { @@ -182,6 +308,7 @@ impl Table { let mut to_unmap = Vec::new(); if let Some(old) = self.by_res.remove(&res) { self.by_va.remove(&(old.va, res)); + self.unindex_active(res, old.src); if old.pending { pending_delta -= 1; } @@ -195,6 +322,7 @@ impl Table { } self.by_va.remove(&(ova, ores)); if let Some(mut old) = self.by_res.remove(&ores) { + self.unindex_active(ores, old.src); if old.pending { pending_delta -= 1; } @@ -224,23 +352,28 @@ impl Table { if entry.pending { pending_delta += 1; } + let (src, size, gpu_written, pending) = (entry.src, entry.tex.size() as usize, entry.gpu_written, entry.pending); self.by_va.insert((va, res), end); self.by_res.insert(res, entry); + self.index_active(res, src, size, gpu_written, pending); (pending_delta, to_unmap) } /// 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)`. + 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)); if self.shadowed.is_empty() { self.max_shadowed_size = 0; } - return (true, 0, Vec::new()); + 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()) }; + let Some(old) = self.by_res.remove(&res) else { return (false, 0, Vec::new(), None) }; + let st = (old.states.len() == 1).then(|| old.states[0]); self.by_va.remove(&(old.va, res)); + self.unindex_active(res, old.src); let mut pending_delta = if old.pending { -1 } else { 0 }; let va = old.va; let end = va.saturating_add(old.tex.size() as usize); @@ -267,14 +400,16 @@ impl Table { if e.pending { pending_delta += 1; } + let (src, size, gpu_written, pending) = (e.src, e.tex.size() as usize, e.gpu_written, e.pending); self.by_va.insert((sva, sres), send); self.by_res.insert(sres, e); + self.index_active(sres, src, size, gpu_written, pending); } } if self.shadowed.is_empty() { self.max_shadowed_size = 0; } - (true, pending_delta, to_remap) + (true, pending_delta, to_remap, st) } fn get_mut(&mut self, res: usize) -> Option<&mut Entry> { @@ -309,10 +444,85 @@ static TEXTURES: Mutex = Mutex::new(Table::new()); // 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(()); + +/// `XCL_LOOK_SKIP` (on by default, `0`: off): a submit whose lists were all closed before the last +/// write-watch look began, and not submitted since, takes no look of its own. +/// +/// The look (`GetWriteWatch` over the title's memory XCL keeps in step) was 60 % of a retail +/// title's frame in its world: ~6 ms at each of 80–100 submits a second. What the title wrote +/// for a list it wrote before closing it, and a look that began after the close took those +/// pages already; the next look takes the rest. A list submitted again (a recording the title +/// runs twice, its data written anew in between) always looks, and so does the first submit of +/// each frame. +fn look_skip_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_LOOK_SKIP").map_or(true, |v| v.trim() != "0")) +} + +fn now_us() -> u64 { + static T0: std::sync::OnceLock = std::sync::OnceLock::new(); + T0.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 + 1 +} + +/// When the last finished look began (µs, `now_us`; 0: none yet), and the frame it was in. +static LOOK_BEGAN_US: AtomicU64 = AtomicU64::new(0); +static LOOK_FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + +/// Each title list's last Close (µs) and whether it was submitted since. +static CLOSED: Mutex>> = Mutex::new(None); + +/// The title closed `list` (the object it submits). +pub(super) fn note_list_closed(list: *mut c_void) { + if !look_skip_on() || list.is_null() { + return; + } + CLOSED.lock().unwrap().get_or_insert_with(std::collections::HashMap::new).insert(list as usize, (now_us(), false)); +} + +thread_local! { + /// The next `refresh` on this thread may leave its look out (`look_needed_for` said so). + static SKIP_LOOK: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Before a submit of `lists`: whether its refresh needs a look of its own (then `refresh` looks; +/// else it is told to leave it out). The lists count as submitted from here on. +pub(super) fn decide_look(lists: &[*mut c_void]) { + if !look_skip_on() { + return; + } + let began = LOOK_BEGAN_US.load(Ordering::Acquire); + let same_frame = LOOK_FRAME.load(Ordering::Acquire) == super::present::presents(); + let mut g = CLOSED.lock().unwrap(); + let m = g.get_or_insert_with(std::collections::HashMap::new); + let mut skip = began != 0 && same_frame && !lists.is_empty(); + for &l in lists { + match m.get_mut(&(l as usize)) { + Some((closed, submitted)) => { + if *submitted || *closed >= began { + skip = false; + } + *submitted = true; + } + None => skip = false, + } + } + drop(g); + SKIP_LOOK.with(|c| c.set(skip)); + static SKIPPED: AtomicU64 = AtomicU64::new(0); + static ALL: AtomicU64 = AtomicU64::new(0); + let all = ALL.fetch_add(1, Ordering::Relaxed) + 1; + if skip { + SKIPPED.fetch_add(1, Ordering::Relaxed); + } + if all.is_power_of_two() && all >= 256 { + crate::xlog_info!("title textures: {} of {all} submits took no write-watch look of their own (XCL_LOOK_SKIP)", SKIPPED.load(Ordering::Relaxed)); + } +} static TEXTURES_GEN: AtomicU64 = AtomicU64::new(0); static TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -/// cached `watch_ranges` keyed by `(sparse::mapped_gen, TEXTURES_GEN, graphics_reservations_gen)` -static WATCH_CACHE: Mutex>)>> = Mutex::new(None); +/// cached `watch_ranges` keyed by `(sparse::mapped_gen, TEXTURES_GEN, graphics_reservations_gen, +/// list_x::mirror_sources_gen)` +static WATCH_CACHE: Mutex>)>> = Mutex::new(None); /// the queue uploads go to, per device static QUEUES: Mutex> = Mutex::new(BTreeMap::new()); static UPLOADS: AtomicU64 = AtomicU64::new(0); @@ -322,6 +532,14 @@ pub fn counts() -> (usize, u64) { (TEXTURES.lock().unwrap().by_res.len(), UPLOADS.load(Ordering::Relaxed)) } +/// The title textures kept in step that are committed resources of their own (not on shared +/// `vram::Pages` tiles): how many, and their console size in bytes (memory accounting, #2688; +/// the PC resource can take somewhat more). +pub fn committed_bytes() -> (usize, u64) { + let t = TEXTURES.lock().unwrap(); + t.by_res.values().chain(t.shadowed.values()).filter(|e| !e.placed).fold((0, 0), |(n, b), e| (n + 1, b + e.tex.size())) +} + /// Whether a non-depth render target / UAV texture is small enough to be a CPU-filled glyph or UI /// atlas (`<= 1M` pixels, up to `2048` on either axis, e.g. a retail title's `2048x128` R8 glyph cache). fn is_small_cpu_filled_target(w: u64, h: u32, samples: u32, flags: u32) -> bool { @@ -397,6 +615,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, clone_resources(&unmap_ptrs) }; for r in &to_unmap { + LAST_CONTENT.lock().unwrap().remove(&(r.as_raw() as usize)); super::vram::unmap_superseded(r); } TEXTURES_GEN.fetch_add(1, Ordering::Release); @@ -406,7 +625,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, /// 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`). -fn mirror_source(va: usize) -> usize { +pub(super) fn mirror_source(va: usize) -> usize { let Some(src) = crate::hle::kernelx::mirrors::source(va) else { return va }; if crate::hle::kernelx::physical_page_at(va) { return va; @@ -426,15 +645,33 @@ fn recheck_gpu_view_sources() { if SEEN.swap(gen, Ordering::AcqRel) == gen { return; } - let mut changed = false; + let mut remapped = Vec::new(); // (the shadowed textures too: one comes back when the texture over it goes) let mut g = TEXTURES.lock().unwrap(); let t = &mut *g; - for e in t.by_res.values_mut().chain(t.shadowed.values_mut()) { - changed |= recheck_source(e); + let mut reindex: Vec<(usize, usize, usize, usize, bool, bool)> = Vec::new(); + for (&res, e) in t.by_res.iter_mut() { + let old_src = e.src; + if recheck_source(e) { + remapped.push(res); + reindex.push((res, old_src, e.src, e.tex.size() as usize, e.gpu_written, e.pending)); + } + } + for (res, old_src, new_src, size, gpu_written, pending) in reindex { + t.unindex_active(res, old_src); + t.index_active(res, new_src, size, gpu_written, pending); + } + for (&res, e) in t.shadowed.iter_mut() { + if recheck_source(e) { + remapped.push(res); + } } drop(g); - if changed { + if !remapped.is_empty() { + let mut last = LAST_CONTENT.lock().unwrap(); + for res in remapped { + last.remove(&res); + } TEXTURES_GEN.fetch_add(1, Ordering::Release); } } @@ -473,19 +710,18 @@ pub fn note_gpu_write(res: usize) { } } } - let mut marked = false; - { + let marked = { let mut t = TEXTURES.lock().unwrap(); - if let Some(e) = t.get_mut(res) { - if !e.gpu_written { - e.gpu_written = true; - GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); - marked = true; - } + if t.mark_gpu_written(res) { + GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); + true + } else { + false } - } + }; if marked { STREAM_RECHECK.lock().unwrap().remove(&res); + TEXTURES_GEN.fetch_add(1, Ordering::Release); } } @@ -508,49 +744,66 @@ pub(super) unsafe fn retire_overlapping(va: usize, len: usize) { .into_iter() .filter(|&g| g != va && mirror_source(g) == va) .collect(); - let (retired, to_unmap) = { + let (retired_ptrs, to_unmap) = { let mut t = TEXTURES.lock().unwrap(); - let (mut delta, mut retired, mut unmap_ptrs) = t.retire_range(va, va.saturating_add(len)); + let (mut delta, mut retired_ptrs, mut unmap_ptrs) = t.retire_range(va, va.saturating_add(len)); if src != va { let (d2, r2, u2) = t.retire_range(src, src.saturating_add(len)); delta += d2; - retired += r2; + retired_ptrs.extend(r2); unmap_ptrs.extend(u2); } for g in gpu_aliases { let (d3, r3, u3) = t.retire_range(g, g.saturating_add(len)); delta += d3; - retired += r3; + retired_ptrs.extend(r3); unmap_ptrs.extend(u3); } adjust_pending(delta); TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); - (retired, clone_resources(&unmap_ptrs)) + (retired_ptrs, clone_resources(&unmap_ptrs)) }; + if !retired_ptrs.is_empty() { + { + let mut last = LAST_CONTENT.lock().unwrap(); + for &r in &retired_ptrs { + last.remove(&r); + } + } + { + let mut g = STREAM_RECHECK.lock().unwrap(); + for &r in &retired_ptrs { + g.remove(&r); + } + } + } for r in &to_unmap { super::vram::unmap_superseded(r); } - if retired > 0 { + if !retired_ptrs.is_empty() { TEXTURES_GEN.fetch_add(1, Ordering::Release); } } -/// The PC texture was released for good. -pub fn forget(res: usize) { +/// The PC texture was released for good. Returns its last tracked uniform D3D12 resource state +/// when all subresources shared a single state (used by `vram` to recycle reserved textures safely). +pub fn forget(res: usize) -> Option { LAST_CONTENT.lock().unwrap().remove(&res); 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); - (removed, unsafe { clone_resources(&remap_ptrs) }) + (removed, unsafe { clone_resources(&remap_ptrs) }, state) }; for r in &to_remap { + let key = r.as_raw() as usize; + LAST_CONTENT.lock().unwrap().remove(&key); unsafe { super::vram::remap_if_unmapped(r); // (lazy levels: one the GPU wrote is not uploaded again, so all of it has pages) - if super::vram::level_pages() && TEXTURES.lock().unwrap().by_res.get(&(r.as_raw() as usize)).is_some_and(|e| e.gpu_written) { + if super::vram::level_pages() && TEXTURES.lock().unwrap().by_res.get(&key).is_some_and(|e| e.gpu_written) { super::vram::map_levels(r, None); } } @@ -558,6 +811,7 @@ pub fn forget(res: usize) { if removed { TEXTURES_GEN.fetch_add(1, Ordering::Release); } + state } /// The title-memory address of a texture kept in step with it. @@ -664,6 +918,7 @@ fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc> { super::sparse::mapped_gen(), TEXTURES_GEN.load(Ordering::Acquire), crate::hle::kernelx::graphics_reservations_gen(), + super::list_x::mirror_sources_gen(), ); { let g = WATCH_CACHE.lock().unwrap(); @@ -677,8 +932,11 @@ fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc> { // write-watched regions) only when the set of textures, tiles, or reservations changed. let mut regions = u.watch_regions(); regions.extend(crate::hle::kernelx::graphics_reservations()); - let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().by_res.values().map(|e| (e.src & !0xFFF, (e.src + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect(); + let mut wanted = TEXTURES.lock().unwrap().watchable_ranges(); wanted.extend(super::sparse::mapped_ranges()); + wanted.extend(super::sparse::gpu_view::sources()); + // the sources of buffer mirrors: a draw copies only the pages written (`list_x::copy_written`) + wanted.extend(super::list_x::mirror_sources()); let computed = Arc::new(watch_ranges(®ions, wanted)); *WATCH_CACHE.lock().unwrap() = Some((key, Arc::clone(&computed))); computed @@ -729,6 +987,9 @@ unsafe fn take_written(base: usize, size: usize, buf: &mut [*mut c_void], dirty: } unsafe fn refresh_once(queue: *mut c_void) { + reclaim_completed_on_queue(queue as usize); + // (taken first: a return below must not leave it for the next submit on this thread) + let skip_look = SKIP_LOOK.with(|c| c.replace(false)); let Some(u) = crate::gpu::uma::get() else { return }; let sparse = u.has_sparse(); if !sparse && TEXTURES_LEN.load(Ordering::Relaxed) == 0 { @@ -736,7 +997,10 @@ unsafe fn refresh_once(queue: *mut c_void) { } recheck_gpu_view_sources(); let watch_t0 = std::time::Instant::now(); + let look_began = now_us(); + let look_frame = super::present::presents(); let mut page = 0x1000u32; + super::sparse::drain_lazy_commits_if_pending(); let ranges = cached_watch_ranges(u); let dirty_len = DIRTY_BUF.with(|dcell| { let mut dirty = dcell.borrow_mut(); @@ -746,14 +1010,28 @@ unsafe fn refresh_once(queue: *mut c_void) { if buf.len() < 16384 { buf.resize(16384, std::ptr::null_mut()); } - for &(base, size) in ranges.iter() { - take_written(base, size, &mut buf, &mut dirty, &mut page); + if !skip_look { + super::list_x::mirror_look_begin(); + for &(base, size) in ranges.iter() { + take_written(base, size, &mut buf, &mut dirty, &mut page); + } } }); + // views of physical pages are not write-watched: their writes are caught by guards + // (`XCL_PAGE_ALIAS`), a write through one view counting for all of them + crate::hle::kernelx::guards::take_dirty(&mut dirty, page as usize); dirty.sort_unstable(); + // pages of buffer mirrors' sources, now off the write-watch: their next draw copies them + super::list_x::mirror_pages_written(&dirty); dirty.len() }); super::sparse::note_watch(watch_t0.elapsed(), dirty_len); + if !skip_look { + // what later submits compare their lists' closes with + LOOK_BEGAN_US.store(look_began, Ordering::Release); + LOOK_FRAME.store(look_frame, Ordering::Release); + } + super::prof::add(super::prof::Kind::SubmitWatch, watch_t0.elapsed()); if super::present::trace_frame() { // every 600th look: what the CPU's view of a few textures holds now (does the title's // data reach the address at all, and is the texture still kept in step?) @@ -786,6 +1064,7 @@ unsafe fn refresh_once(queue: *mut c_void) { // the title's own memory: what the CPU wrote goes to its video memory first if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { DIRTY_BUF.with(|dcell| { + let _prof = super::prof::span(super::prof::Kind::SubmitSparse); let dirty = dcell.borrow(); super::sparse::before_execute(q, &dirty, page as usize); super::vram::before_execute(q); @@ -801,37 +1080,65 @@ unsafe fn refresh_once(queue: *mut c_void) { } // textures made since the last submit and those with a written page; a reference each // while they are uploaded + let page_size = (page as usize).max(0x1000); let todo: Vec<(ID3D12Resource, Upload)> = DIRTY_BUF.with(|dcell| { let dirty = dcell.borrow(); let mut t = TEXTURES.lock().unwrap(); - t.by_res - .iter_mut() - .filter(|(_, e)| { - if e.pending { - return true; - } - if e.gpu_written { - return false; - } - 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) - }) - .filter_map(|(&res, e)| { - if e.pending { - e.pending = false; - PENDING.fetch_sub(1, Ordering::Relaxed); - } + let (hits, cleared) = t.dirty_and_pending(&dirty, page_size); + if cleared > 0 { + PENDING.fetch_sub(cleared, Ordering::Relaxed); + } + hits.into_iter() + .filter_map(|(res, was_pending)| { + let e = t.by_res.get(&res)?; + let dirty_pages = if was_pending { + None + } else { + let end = e.src.saturating_add(e.tex.size() as usize); + let lo = dirty.partition_point(|&p| p.saturating_add(page_size) <= e.src); + let hi = lo + dirty[lo..].partition_point(|&p| p < end); + (lo < hi).then(|| dirty[lo..hi].to_vec()) + }; let p = res as *mut c_void; - ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.src, Arc::clone(&e.tex), e.states.clone()))) + ID3D12Resource::from_raw_borrowed(&p).map(|r| { + ( + r.clone(), + Upload { + device: e.device, + src: e.src, + tex: Arc::clone(&e.tex), + states: e.states.clone(), + dirty_pages, + page_size, + }, + ) + }) }) .collect() }); seed_stream_recheck(&todo, &ranges, recheck_frame); - upload_all(todo); + let uploaded = !todo.is_empty(); + let upload_prof = super::prof::span(super::prof::Kind::SubmitTextures); + upload_all(todo, ID3D12CommandQueue::from_raw_borrowed(&queue)); + drop(upload_prof); + // Ensure the submitting queue waits for any `vram::map_levels` tile mappings queued inside + // `upload_all`, even if an upload batch fell back to the upload queue or exited early. + if uploaded { + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { + super::vram::before_execute(q); + } + } +} + +struct PageHashes { + src: usize, + size: usize, + page_size: usize, + hashes: Vec, } -/// texture → `content_hash` of its memory at its last upload -static LAST_CONTENT: Mutex> = Mutex::new(BTreeMap::new()); +/// texture → per-page `content_hash` of its memory at its last upload +static LAST_CONTENT: Mutex> = Mutex::new(BTreeMap::new()); static UNCHANGED: AtomicU64 = AtomicU64::new(0); /// `XCL_TEXTURE_SKIP_UNCHANGED=0` uploads a texture whenever its pages were written, as before. @@ -840,15 +1147,154 @@ fn unchanged_skip() -> bool { *ON.get_or_init(|| std::env::var("XCL_TEXTURE_SKIP_UNCHANGED").map_or(true, |v| v.trim() != "0")) } -/// Whether texture `res` was last uploaded from memory with hash `h`; `h` is remembered as its -/// content from here on (the caller uploads it when this is false). -fn same_as_last_upload(res: usize, h: u64) -> bool { - LAST_CONTENT.lock().unwrap().insert(res, h) == Some(h) +/// Aligned base of the first page covering `[src, src + size)` and the number of `page_size` pages. +fn page_count(src: usize, size: usize, page_size: usize) -> (usize, usize) { + if size == 0 || page_size == 0 { + return (src, 0); + } + let first_page = src - (src % page_size); + let end = src.saturating_add(size); + let count = end.saturating_sub(first_page).div_ceil(page_size); + (first_page, count) } -/// A 64-bit hash of `b` for "the same bytes as before" (four lanes of multiply-rotate over -/// 8-byte words: gigabytes a second; not for anything adversarial). -fn content_hash(b: &[u8]) -> u64 { +/// Page indices of `[src, src + size)` whose bytes changed since `res`'s last upload, or `None` +/// if all checked pages match. When `dirty_pages` is `Some` and `(src, size, page_size)` matches +/// the recorded `PageHashes`, only those dirty pages are read and hashed (outside `LAST_CONTENT`). +fn changed_pages_with<'a, F>( + res: usize, + src: usize, + size: usize, + dirty_pages: Option<&[usize]>, + page_size: usize, + mut read_range: F, +) -> Option> +where + F: FnMut(usize, usize) -> std::borrow::Cow<'a, [u8]>, +{ + let (first_page, count) = page_count(src, size, page_size); + let end = src.saturating_add(size); + + if let Some(pages) = dirty_pages { + let matched = { + let g = LAST_CONTENT.lock().unwrap(); + g.get(&res).is_some_and(|e| e.src == src && e.size == size && e.page_size == page_size && e.hashes.len() == count) + }; + if matched { + if count == 0 { + return None; + } + let mut indices: Vec = pages + .iter() + .filter_map(|&p| { + let pg = p - (p % page_size); + if pg < first_page { + return None; + } + let k = (pg - first_page) / page_size; + (k < count).then_some(k) + }) + .collect(); + indices.sort_unstable(); + indices.dedup(); + + let mut computed = Vec::with_capacity(indices.len()); + for k in indices { + let pg = first_page + k * page_size; + let lo = pg.max(src); + let hi = pg.saturating_add(page_size).min(end); + let bytes = read_range(lo, hi - lo); + computed.push((k, content_hash(&bytes))); + } + + let mut g = LAST_CONTENT.lock().unwrap(); + if let Some(entry) = g.get_mut(&res).filter(|e| e.src == src && e.size == size && e.page_size == page_size && e.hashes.len() == count) { + let mut changed = Vec::new(); + for (k, h) in computed { + if entry.hashes[k] != h { + entry.hashes[k] = h; + changed.push(k); + } + } + return if changed.is_empty() { None } else { Some(changed) }; + } + } + } + + let mut hashes = Vec::with_capacity(count); + if count > 0 { + let bytes = read_range(src, size); + for k in 0..count { + let pg = first_page + k * page_size; + let lo = pg.max(src); + let hi = pg.saturating_add(page_size).min(end); + hashes.push(content_hash(&bytes[lo - src..hi - src])); + } + } + + let mut g = LAST_CONTENT.lock().unwrap(); + if let Some(entry) = g.get_mut(&res).filter(|e| e.src == src && e.size == size && e.page_size == page_size && e.hashes.len() == count) { + let mut changed = Vec::new(); + for (k, h) in hashes.into_iter().enumerate() { + if entry.hashes[k] != h { + entry.hashes[k] = h; + changed.push(k); + } + } + if changed.is_empty() { None } else { Some(changed) } + } else { + g.insert(res, PageHashes { src, size, page_size, hashes }); + Some((0..count).collect()) + } +} + +/// Per-page change check backed by `title_bytes` for `upload_all`. +unsafe fn changed_pages_since_last_upload(res: usize, src: usize, size: usize, dirty_pages: Option<&[usize]>, page_size: usize) -> Option> { + changed_pages_with(res, src, size, dirty_pages, page_size, |at, len| title_bytes(at, len)) +} + +#[inline] +fn has_avx2() -> bool { + #[cfg(target_arch = "x86_64")] + { + static AVX2: std::sync::OnceLock = std::sync::OnceLock::new(); + *AVX2.get_or_init(|| std::arch::is_x86_feature_detected!("avx2")) + } + #[cfg(not(target_arch = "x86_64"))] + { + false + } +} + +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn is_zero_avx2(b: &[u8]) -> bool { + use std::arch::x86_64::{_mm256_loadu_si256, _mm256_or_si256, _mm256_testz_si256, __m256i}; + let mut ptr = b.as_ptr(); + let mut rem = b.len(); + while rem >= 128 { + let p = ptr as *const __m256i; + let a = _mm256_or_si256(_mm256_loadu_si256(p), _mm256_loadu_si256(p.add(1))); + let c = _mm256_or_si256(_mm256_loadu_si256(p.add(2)), _mm256_loadu_si256(p.add(3))); + let any = _mm256_or_si256(a, c); + if _mm256_testz_si256(any, any) == 0 { + return false; + } + ptr = ptr.add(128); + rem -= 128; + } + while rem >= 32 { + let v = _mm256_loadu_si256(ptr as *const __m256i); + if _mm256_testz_si256(v, v) == 0 { + return false; + } + ptr = ptr.add(32); + rem -= 32; + } + std::slice::from_raw_parts(ptr, rem).iter().all(|&x| x == 0) +} + +fn content_hash_scalar(b: &[u8]) -> u64 { const K: u64 = 0x9E37_79B9_7F4A_7C15; let mut h = [K, K.rotate_left(17), K.rotate_left(31), K.rotate_left(47)]; let mut chunks = b.chunks_exact(32); @@ -865,10 +1311,26 @@ fn content_hash(b: &[u8]) -> u64 { h.iter().fold(tail, |a, &l| (a ^ l).wrapping_mul(K).rotate_left(27)) } +fn zero_page_hash_4k() -> u64 { + static H: std::sync::OnceLock = std::sync::OnceLock::new(); + *H.get_or_init(|| content_hash_scalar(&[0u8; 4096])) +} + +/// A 64-bit hash of `b` for "the same bytes as before" (four lanes of multiply-rotate over +/// 8-byte words: gigabytes a second; AVX2 fast-zero shortcut on 4 KiB pages). +fn content_hash(b: &[u8]) -> u64 { + #[cfg(target_arch = "x86_64")] + if b.len() == 4096 && has_avx2() && unsafe { is_zero_avx2(b) } { + return zero_page_hash_4k(); + } + content_hash_scalar(b) +} + /// Frame milestones (relative to last upload or detected content change) at which unwatched /// textures (e.g. physical-page / `MEM_MAPPED` views that `GetWriteWatch` cannot track) are /// re-fingerprinted to catch late streaming writes that land after an initial zeroed upload. -const STREAM_RECHECK_MILESTONES: [u64; 5] = [4, 12, 40, 120, 400]; +/// Milestone `1` catches late writes before one-time decoration/face bakes run. +const STREAM_RECHECK_MILESTONES: [u64; 6] = [1, 4, 12, 40, 120, 400]; /// Per-slice sample size (start, mid, end -> at most 48 KiB hashed per due texture). const STREAM_SAMPLE_SLICE: usize = 16 * 1024; @@ -944,12 +1406,12 @@ unsafe fn seed_stream_recheck(todo: &[(ID3D12Resource, Upload)], watched: &[(usi return; } let mut seeded = Vec::new(); - for (r, (_, src, tex, _)) in todo { - let size = tex.size() as usize; - if size == 0 || range_is_fully_watched(*src, size, watched) { + for (r, u) in todo { + let size = u.tex.size() as usize; + if size == 0 || range_is_fully_watched(u.src, size, watched) { continue; } - let fp = sample_fingerprint(*src, size); + let fp = sample_fingerprint(u.src, size); seeded.push((r.as_raw() as usize, StreamRecheck { base_frame: frame, stage: 0, last_fp: fp })); } if !seeded.is_empty() { @@ -1052,12 +1514,9 @@ unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) { let mut t = TEXTURES.lock().unwrap(); for res in changed { - if let Some(e) = t.by_res.get_mut(&res) { - if !e.gpu_written && !e.pending { - e.pending = true; - PENDING.fetch_add(1, Ordering::Relaxed); - queued += 1; - } + if t.mark_pending(res) { + PENDING.fetch_add(1, Ordering::Relaxed); + queued += 1; } } } @@ -1075,20 +1534,129 @@ unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) /// and keeps each GPU copy list short enough to avoid WDDM 2 s TDR when thousands of small /// textures stream at once. const BATCH_BYTES: usize = 32 << 20; +/// Tighter batch cap under low Windows commit headroom (`vram::commit_low`) so persistent texture +/// upload staging buffers stay small instead of growing to 64–144 MiB. +const BATCH_BYTES_LOW_COMMIT: usize = 8 << 20; const BATCH_ITEMS: usize = 256; /// Whether another upload `(next_dev, next_bytes)` still fits in the current batch of -/// `picked_count` textures totalling `picked_bytes` on `batch_dev`. An empty batch always takes -/// its first upload (even if larger than `BATCH_BYTES`) so progress is guaranteed. -fn batch_fits(picked_count: usize, picked_bytes: usize, batch_dev: usize, next_dev: usize, next_bytes: usize) -> bool { +/// `picked_count` textures totalling `picked_bytes` on `batch_dev` under byte cap `max_bytes`. +/// An empty batch always takes its first upload (even if larger than `max_bytes`) so progress is +/// guaranteed. +fn batch_fits_limit(picked_count: usize, picked_bytes: usize, batch_dev: usize, next_dev: usize, next_bytes: usize, max_bytes: usize) -> bool { picked_count == 0 || (picked_count < BATCH_ITEMS && next_dev == batch_dev - && picked_bytes.saturating_add(next_bytes) <= BATCH_BYTES) + && picked_bytes.saturating_add(next_bytes) <= max_bytes) +} + +#[cfg(test)] +fn batch_fits(picked_count: usize, picked_bytes: usize, batch_dev: usize, next_dev: usize, next_bytes: usize) -> bool { + batch_fits_limit(picked_count, picked_bytes, batch_dev, next_dev, next_bytes, BATCH_BYTES) +} + +struct QueueUploads { + fence: ID3D12Fence, + value: u64, + in_flight: std::collections::VecDeque<(u64, texture::InFlight)>, + bytes: u64, +} + +unsafe impl Send for QueueUploads {} + +static ON_QUEUE: Mutex> = Mutex::new(BTreeMap::new()); + +const IN_FLIGHT_BYTES: u64 = 512 << 20; +const IN_FLIGHT_BYTES_LOW_COMMIT: u64 = 64 << 20; + +fn in_flight_cap_bytes(low_commit: bool) -> u64 { + if low_commit { IN_FLIGHT_BYTES_LOW_COMMIT } else { IN_FLIGHT_BYTES } } -/// The uploads `todo`, in batches of up to `BATCH_BYTES` and `BATCH_ITEMS` (one list and one wait each). -unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { +unsafe fn title_queue_for(dev: &ID3D12Device, title: Option<&ID3D12CommandQueue>) -> Option { + let q = title?; + if q.GetDesc().Type != D3D12_COMMAND_LIST_TYPE_DIRECT { + return None; + } + let mut qd: Option = None; + q.GetDevice(&mut qd).ok()?; + (qd?.as_raw() == dev.as_raw()).then(|| q.clone()) +} + +/// Non-blockingly release completed in-flight upload batches for `queue_key` so staging buffers do +/// not stay pinned during quiet frames with no new texture uploads. +unsafe fn reclaim_completed_on_queue(queue_key: usize) { + if queue_key == 0 { + return; + } + let mut g = ON_QUEUE.lock().unwrap(); + let Some(q) = g.get_mut(&queue_key) else { return }; + if q.in_flight.is_empty() { + return; + } + let done = q.fence.GetCompletedValue(); + while q.in_flight.front().is_some_and(|&(v, _)| v <= done) { + let (_, f) = q.in_flight.pop_front().unwrap(); + q.bytes = q.bytes.saturating_sub(f.bytes); + } +} + +unsafe fn reclaim(dev: &ID3D12Device, q: &mut QueueUploads, cap: u64, wait_ms: u32) { + let done = q.fence.GetCompletedValue(); + while q.in_flight.front().is_some_and(|&(v, _)| v <= done) { + let (_, f) = q.in_flight.pop_front().unwrap(); + q.bytes = q.bytes.saturating_sub(f.bytes); + } + while q.bytes > cap { + let Some(&(v, _)) = q.in_flight.front() else { break }; + if crate::gpu::fence::wait(&q.fence, v, dev, None, wait_ms).is_err() { + break; + } + let (_, f) = q.in_flight.pop_front().unwrap(); + q.bytes = q.bytes.saturating_sub(f.bytes); + } +} + +unsafe fn submit_on_title_queue(dev: &ID3D12Device, queue: &ID3D12CommandQueue, batch: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { + // Wait for any tile mappings queued since `queue` last waited (from another thread or from + // `map_levels_with_texels` above) so copy-engine writes never hit unmapped tiles. + super::vram::before_execute(queue); + let (failed, f) = texture::submit_batch(dev, queue, batch)?; + let Some(f) = f else { return Ok(failed) }; + let mut g = ON_QUEUE.lock().unwrap(); + let key = queue.as_raw() as usize; + if !g.contains_key(&key) { + match dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) { + Ok(fence) => { + g.insert(key, QueueUploads { fence, value: 0, in_flight: std::collections::VecDeque::new(), bytes: 0 }); + } + Err(e) => { + texture::wait(dev, queue)?; + drop(f); + return Err(e.to_string()); + } + } + } + let q = g.get_mut(&key).unwrap(); + q.value += 1; + if let Err(e) = queue.Signal(&q.fence, q.value) { + q.value -= 1; + texture::wait(dev, queue)?; + drop(f); + return Err(e.to_string()); + } + super::flight::signaled("texture uploads", key, &q.fence, q.value); + q.bytes = q.bytes.saturating_add(f.bytes); + let v = q.value; + q.in_flight.push_back((v, f)); + reclaim(dev, q, in_flight_cap_bytes(super::vram::commit_low()), 10_000); + Ok(failed) +} + +/// The uploads `todo`, in batches of up to `BATCH_BYTES` (or `BATCH_BYTES_LOW_COMMIT` when Windows +/// commit is below reserve) and `BATCH_ITEMS`. Direct title queues execute uploads inline with a +/// bounded in-flight staging ring (no CPU fence stall); other queues fall back to the upload queue. +unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>, title: Option<&ID3D12CommandQueue>) { static N: AtomicU64 = AtomicU64::new(0); let warn = |e: &str| { if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -1100,46 +1668,65 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { let mut picked = Vec::new(); let mut bytes = 0usize; let mut device = 0usize; - while let Some((_, (dev, _, tex, _))) = todo.peek() { - if !batch_fits(picked.len(), bytes, device, *dev, tex.size() as usize) { + let skip_unchanged = unchanged_skip(); + let max_batch_bytes = if super::vram::commit_low() { BATCH_BYTES_LOW_COMMIT } else { BATCH_BYTES }; + while let Some((_, u)) = todo.peek() { + if !batch_fits_limit(picked.len(), bytes, device, u.device, u.tex.size() as usize, max_batch_bytes) { break; } - let (r, (dev, va, tex, states)) = todo.next().unwrap(); - // The same bytes as at this texture's last upload: nothing to do. The write watch is - // per page and a title writes next to its textures (and rewrites what it wrote): a - // retail title's video planes and UI targets went up again for every submit, ~25 MB - // a presented frame where ~3 MB had changed, and the submits waited here. - if unchanged_skip() { - let h = content_hash(&title_bytes(va, tex.size() as usize)); - if same_as_last_upload(r.as_raw() as usize, h) { + let (r, u) = todo.next().unwrap(); + let size = u.tex.size() as usize; + let mut already_checked = false; + if skip_unchanged && u.dirty_pages.is_some() { + if changed_pages_since_last_upload(r.as_raw() as usize, u.src, size, u.dirty_pages.as_deref(), u.page_size).is_none() { let n = UNCHANGED.fetch_add(1, Ordering::Relaxed) + 1; if n == 1 || (n.is_power_of_two() && n >= 1024) { crate::xlog_info!("title textures: {n} uploads left out so far – the texture's memory held what it held at its last upload"); } continue; } + already_checked = true; } - device = dev; - bytes += tex.size() as usize; - picked.push((r, va, tex, states)); + device = u.device; + bytes += size; + picked.push((r, u.src, u.tex, u.states, u.page_size, already_checked)); } if picked.is_empty() { continue; } - let subs = subresources_of_all(&picked, bytes); + let prepared = hash_and_detile_all(&picked, bytes, skip_unchanged); let mut batch = Vec::with_capacity(picked.len()); - for ((r, va, _, states), subs) in picked.into_iter().zip(subs) { + for ((r, va, _, states, _, _), subs) in picked.into_iter().zip(prepared) { + let Some(subs) = subs else { + continue; + }; if super::present::trace_frame() { note_content(va, &r, &subs); } - if super::vram::level_pages() { - // (the queue waits for these mappings before the copies: `vram::before_execute` below) - map_levels_with_texels(&r, &subs); + if super::vram::level_pages() && !map_levels_with_texels(&r, &subs) { + // The copies into unmapped tiles will be dropped. Upload the backed levels, + // and let the next refresh that selects this texture retry the same bytes. + LAST_CONTENT.lock().unwrap().remove(&(r.as_raw() as usize)); } batch.push((r, subs, states)); } + if batch.is_empty() { + continue; + } let d = device as *mut c_void; let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { continue }; + if let Some(tq) = title_queue_for(dev, title) { + match own_work(|| submit_on_title_queue(dev, &tq, &batch)) { + Ok(failed) => { + for (_, e) in failed { + warn(&e); + } + UPLOADS.fetch_add(batch.len() as u64, Ordering::Relaxed); + } + Err(e) => warn(&e), + } + continue; + } let queue = match upload_queue(dev, device) { Ok(q) => q, Err(e) => { @@ -1167,14 +1754,15 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { /// placed with lazy levels; any other: nothing to do. A level of zeros has no texels: a streamed /// texture's larger levels before the title has memory behind them (read as zeros, /// `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). -unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) { +/// to tiles that are not mapped, which drops it (tiled resources tier 2). Returns whether all +/// levels with texels have pages. The upload queue waits for their mappings in `before_execute`. +unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) -> bool { if !super::vram::has_lazy_levels(r.as_raw() as usize) { - return; + return true; } // (one slice: its subresources are its levels) let present: Vec = subs.iter().enumerate().filter(|(_, s)| !all_zero(&s.data)).map(|(i, _)| i as u32).collect(); - super::vram::map_levels(r, Some(&present)); + super::vram::map_levels(r, Some(&present)) } /// Whether every byte of `b` is zero (eight at a time: gigabytes a second where it is). @@ -1349,7 +1937,7 @@ fn watch_ranges(regions: &[(usize, usize)], mut wanted: Vec<(usize, usize)>) -> /// `0`. Because Windows may return `read == 0` when a fault occurs later in the span, binary-split /// failed multi-page ranges at 4 KiB boundaries so all still-committed pages are copied in O(log N) /// calls and only unreadable pages stay zeroed. -unsafe fn copy_committed_region(src: usize, dst: *mut u8, len: usize) { +pub(super) unsafe fn copy_committed_region(src: usize, dst: *mut u8, len: usize) { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; const PAGE: usize = 0x1000; @@ -1410,19 +1998,157 @@ unsafe fn read_committed(at: usize, len: usize) -> Vec { out } -/// Batches of at least this many bytes are detiled on several threads (`subresources_of_all`) +/// Batches of at least this many bytes are detiled on several threads (`hash_and_detile_all`) const PARALLEL_BYTES: usize = 1 << 20; -/// `subresources` of every texture of a batch (`bytes` of them), in order: on several threads -/// when the batch is big. They were read and detiled one after another in the title's own -/// submit – most of a retail game's render thread while it streamed textures the CPU writes. -unsafe fn subresources_of_all(picked: &[(ID3D12Resource, usize, Arc, Vec)], bytes: usize) -> Vec> { - let picked: Vec<(usize, &xg::Texture)> = picked.iter().map(|(_, va, tex, _)| (*va, &**tex)).collect(); +struct DetileState { + gen: u64, + active_helpers: usize, + pending_helpers: usize, + func: Option, + ctx: usize, +} + +/// Reusable persistent worker pool for parallel texture hashing and detiling, avoiding per-submit +/// OS thread creation and DLL attach/detach overhead during streaming bursts. +struct DetilePool { + run_lock: Mutex<()>, + state: Arc<(Mutex, std::sync::Condvar, std::sync::Condvar)>, + helpers: usize, +} + +impl DetilePool { + fn new(max_threads: usize) -> Self { + let helpers = max_threads.saturating_sub(1); + let state = Arc::new(( + Mutex::new(DetileState { gen: 0, active_helpers: 0, pending_helpers: 0, func: None, ctx: 0 }), + std::sync::Condvar::new(), + std::sync::Condvar::new(), + )); + let mut spawned = 0usize; + for _ in 0..helpers { + let id = spawned; + let shared = Arc::clone(&state); + if std::thread::Builder::new() + .name(format!("xcl-detile-{id}")) + .spawn(move || { + let mut seen = 0u64; + loop { + let job = { + let mut g = shared.0.lock().unwrap(); + while g.gen == seen { + g = shared.1.wait(g).unwrap(); + } + seen = g.gen; + if id < g.active_helpers { + g.func.map(|f| (f, g.ctx)) + } else { + None + } + }; + if let Some((func, ctx)) = job { + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { func(ctx as *const c_void) })); + let mut g = shared.0.lock().unwrap(); + g.pending_helpers -= 1; + if g.pending_helpers == 0 { + shared.2.notify_one(); + } + } + } + }) + .is_ok() + { + spawned += 1; + } + } + DetilePool { run_lock: Mutex::new(()), state, helpers: spawned } + } + + fn run(&self, total_threads: usize, f: &F) { + let helpers = total_threads.saturating_sub(1).min(self.helpers); + if helpers == 0 { + f(); + return; + } + unsafe fn trampoline(ctx: *const c_void) { + (*(ctx as *const F))(); + } + let _serial = self.run_lock.lock().unwrap(); + { + let mut g = self.state.0.lock().unwrap(); + g.func = Some(trampoline::); + g.ctx = (f as *const F) as usize; + g.active_helpers = helpers; + g.pending_helpers = helpers; + g.gen = g.gen.wrapping_add(1); + self.state.1.notify_all(); + } + let caller_res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); + { + let mut g = self.state.0.lock().unwrap(); + while g.pending_helpers > 0 { + g = self.state.2.wait(g).unwrap(); + } + g.func = None; + g.ctx = 0; + g.active_helpers = 0; + } + if let Err(payload) = caller_res { + std::panic::resume_unwind(payload); + } + } +} + +fn detile_pool() -> &'static DetilePool { + static POOL: std::sync::OnceLock = std::sync::OnceLock::new(); + POOL.get_or_init(|| { + let max_threads = std::thread::available_parallelism().map_or(1, |n| n.get() / 2).clamp(1, 8); + DetilePool::new(max_threads) + }) +} + +/// Read each texture once, optionally skip unchanged content (`LAST_CONTENT`), and detile from the +/// same buffer — using the persistent detile worker pool when the batch reaches `PARALLEL_BYTES`. +unsafe fn hash_and_detile_all( + picked: &[(ID3D12Resource, usize, Arc, Vec, usize, bool)], + bytes: usize, + skip_unchanged: bool, +) -> Vec>> { + let items: Vec<(usize, usize, &xg::Texture, usize, bool)> = + picked.iter().map(|(r, va, tex, _, page_size, checked)| (r.as_raw() as usize, *va, &**tex, *page_size, *checked)).collect(); let threads = if bytes < PARALLEL_BYTES { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get() / 2).clamp(1, 8) }; - subresources_on(&picked, threads) + let threads = threads.min(items.len()); + let work = |res: usize, va: usize, tex: &xg::Texture, page_size: usize, already_checked: bool| -> Option> { + let size = tex.size() as usize; + let mem = title_bytes(va, size); + if skip_unchanged && !already_checked { + if changed_pages_with(res, va, size, None, page_size, |at, len| std::borrow::Cow::Borrowed(&mem[at - va..at - va + len])).is_none() { + let n = UNCHANGED.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || (n.is_power_of_two() && n >= 1024) { + crate::xlog_info!("title textures: {n} uploads left out so far – the texture's memory held what it held at its last upload"); + } + return None; + } + } + Some(subresources_from_bytes(&mem, tex)) + }; + if threads <= 1 { + return items.iter().map(|&(res, va, tex, ps, checked)| work(res, va, tex, ps, checked)).collect(); + } + let next = std::sync::atomic::AtomicUsize::new(0); + let out: Vec>>> = (0..items.len()).map(|_| Mutex::new(None)).collect(); + detile_pool().run(threads, &|| loop { + let k = next.fetch_add(1, Ordering::Relaxed); + let Some(&(res, va, tex, ps, checked)) = items.get(k) else { break }; + if let Some(subs) = work(res, va, tex, ps, checked) { + *out[k].lock().unwrap() = Some(subs); + } + }); + out.into_iter().map(|m| m.into_inner().unwrap()).collect() } /// `subresources` of each (address, texture), in order, on up to `threads` threads. +#[cfg(test)] unsafe fn subresources_on(picked: &[(usize, &xg::Texture)], threads: usize) -> Vec> { let threads = threads.min(picked.len()); if threads <= 1 { @@ -1454,51 +2180,79 @@ unsafe fn subresources_on(picked: &[(usize, &xg::Texture)], threads: usize) -> V out } -/// The title's bytes at `at`: where they are when all of them are readable (a copy first cost -/// as much as the detile of a video frame), else read page run by page run. +/// The title's bytes at `at`: borrowed directly only inside the permanently-committed coherent +/// UMA window; any other address (alias spaces, sparse reservations, or title heaps) can be +/// concurrently decommitted by another thread between a readability check and the read, so read +/// page run by page run via `read_committed` (`ReadProcessMemory`) without faulting. unsafe fn title_bytes(at: usize, len: usize) -> std::borrow::Cow<'static, [u8]> { - if crate::gpu::shader::readable(at, len) { + if 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 { std::borrow::Cow::Owned(read_committed(at, len)) } } -/// Every subresource (D3D12 order) of a texture from the title's memory at `va`. -unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { +/// Every subresource (D3D12 order) of a texture detiled directly from its already-read bytes `mem`. +fn subresources_from_bytes(mem: &[u8], tex: &xg::Texture) -> Vec { let Some(tex) = tex.texels() else { return Vec::new() }; let c = &tex.chain; let bpe = tex.bpe as usize; if tex.depth > 0 { - let mem = title_bytes(va, tex.size() as usize); - return c.levels.iter().enumerate().map(|(i, l)| Subresource { depth: l.depth, rows: l.height, row_bytes: l.width * bpe, data: c.detile_volume(&mem, i) }).collect(); + return c.levels.iter().enumerate().map(|(i, l)| Subresource { depth: l.depth, rows: l.height, row_bytes: l.width * bpe, data: c.detile_volume(mem, i) }).collect(); } let mut out = Vec::with_capacity(tex.array as usize * c.levels.len()); for s in 0..tex.array as usize { - let slice = title_bytes(va + s * c.slice_bytes, c.slice_bytes); + let start = s * c.slice_bytes; + let Some(slice) = mem.get(start..start + c.slice_bytes) else { break }; for (i, l) in c.levels.iter().enumerate() { - out.push(Subresource { depth: 1, rows: l.height, row_bytes: l.width * bpe, data: c.detile_level(&slice, i, s) }); + out.push(Subresource { depth: 1, rows: l.height, row_bytes: l.width * bpe, data: c.detile_level(slice, i, s) }); } } out } +/// Every subresource (D3D12 order) of a texture from the title's memory at `va`. +unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { + let mem = title_bytes(va, tex.size() as usize); + subresources_from_bytes(&mem, tex) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn content_hash_avx2_zero_fast_path_matches_scalar() { + let mut page = vec![0u8; 4096]; + assert_eq!(content_hash(&page), content_hash_scalar(&page)); + for &off in &[0usize, 31, 32, 127, 128, 2047, 4095] { + page[off] = 1; + assert_eq!(content_hash(&page), content_hash_scalar(&page), "mismatch at offset {off}"); + page[off] = 0; + } + assert_eq!(content_hash(&page), content_hash_scalar(&page)); + } + /// A texture is left out only when its memory hashes as at its own last upload, and a /// texture that was forgotten (released, or its address registered again) is uploaded again. #[test] fn a_texture_with_unchanged_memory_is_left_out_until_it_is_forgotten() { + use std::borrow::Cow; + const PAGE: usize = 0x1000; let (a, b) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize); + forget(a); + forget(b); let mut mem = vec![0u8; 3 << 20]; mem[5] = 1; + let src = mem.as_ptr() as usize; + let size = mem.len(); + let (_, count) = page_count(src, size, PAGE); + let all_pages: Vec = (0..count).collect(); let h = content_hash(&mem); - assert!(!same_as_last_upload(a, h), "the first upload is not left out"); - assert!(same_as_last_upload(a, h), "the same bytes again: left out"); - assert!(!same_as_last_upload(b, h), "another texture over the same bytes has its own first upload"); + assert_eq!(changed_pages_with(a, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), Some(all_pages.clone()), "the first upload is not left out"); + assert_eq!(changed_pages_with(a, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), None, "the same bytes again: left out"); + assert_eq!(changed_pages_with(b, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), Some(all_pages.clone()), "another texture over the same bytes has its own first upload"); // one byte anywhere, also in the tail that is not a whole 32-byte step for at in [0usize, 31, 32, (3 << 20) - 1] { let mut m = mem.clone(); @@ -1506,17 +2260,378 @@ mod tests { assert_ne!(content_hash(&m), h, "byte {at} changed"); } mem[(3 << 20) - 1] = 9; - let h2 = content_hash(&mem); - assert!(!same_as_last_upload(a, h2), "changed memory is uploaded"); - assert!(same_as_last_upload(a, h2)); + assert_eq!(changed_pages_with(a, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), Some(vec![count - 1]), "changed memory is uploaded"); + assert_eq!(changed_pages_with(a, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), None); // the length is part of the content: a prefix of zeros is not the whole assert_ne!(content_hash(&[0u8; 64]), content_hash(&[0u8; 96])); forget(a); - assert!(!same_as_last_upload(a, h2), "forgotten: its next upload is a first one"); + assert_eq!(changed_pages_with(a, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), Some(all_pages), "forgotten: its next upload is a first one"); forget(a); forget(b); } + #[test] + fn dirty_page_unchanged_skips_and_reads_only_that_page() { + use std::borrow::Cow; + const PAGE: usize = 0x1000; + let res = 0x7E57_2395_0001usize; + forget(res); + let mem = vec![0x5Au8; 8 * PAGE]; + let src = 0x10_0000usize; + let mut bytes_read = 0usize; + let got = changed_pages_with(res, src, mem.len(), None, PAGE, |at, len| { + bytes_read += len; + Cow::Borrowed(&mem[at - src..at - src + len]) + }); + assert_eq!(got, Some((0..8).collect())); + assert_eq!(bytes_read, mem.len()); + + bytes_read = 0; + let mut calls = Vec::new(); + let dirty = [src + 3 * PAGE]; + let got = changed_pages_with(res, src, mem.len(), Some(&dirty), PAGE, |at, len| { + bytes_read += len; + calls.push((at, len)); + Cow::Borrowed(&mem[at - src..at - src + len]) + }); + assert_eq!(got, None, "unchanged dirty page must skip upload"); + assert_eq!(bytes_read, PAGE, "only the single 4096-byte dirty page must be read"); + assert_eq!(calls, vec![(src + 3 * PAGE, PAGE)]); + forget(res); + } + + #[test] + fn dirty_page_one_modified_byte_updates_only_that_page_hash() { + use std::borrow::Cow; + const PAGE: usize = 0x1000; + let res = 0x7E57_2395_0002usize; + forget(res); + let mut mem = vec![0x11u8; 6 * PAGE]; + let src = 0x20_0000usize; + assert_eq!( + changed_pages_with(res, src, mem.len(), None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), + Some((0..6).collect()) + ); + + mem[2 * PAGE + 123] ^= 0x01; + mem[4 * PAGE + 77] ^= 0x01; + let mut bytes_read = 0usize; + let dirty2 = [src + 2 * PAGE]; + let got = changed_pages_with(res, src, mem.len(), Some(&dirty2), PAGE, |at, len| { + bytes_read += len; + Cow::Borrowed(&mem[at - src..at - src + len]) + }); + assert_eq!(got, Some(vec![2])); + assert_eq!(bytes_read, PAGE); + + assert_eq!( + changed_pages_with(res, src, mem.len(), Some(&dirty2), PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), + None + ); + let dirty4 = [src + 4 * PAGE]; + assert_eq!( + changed_pages_with(res, src, mem.len(), Some(&dirty4), PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), + Some(vec![4]) + ); + forget(res); + } + + #[test] + fn unaligned_src_and_tail_bytes_hash_exact_clamped_spans() { + use std::borrow::Cow; + const PAGE: usize = 0x1000; + let res = 0x7E57_2395_0003usize; + forget(res); + let src = 0x30_0500usize; + let size = 0x2307usize; + assert_eq!(page_count(src, size, PAGE), (0x30_0000, 3)); + assert_eq!(page_count(src, 0, PAGE), (src, 0)); + + let mut mem = vec![0x33u8; size]; + assert_eq!( + changed_pages_with(res, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), + Some(vec![0, 1, 2]) + ); + + let mut calls = Vec::new(); + assert_eq!( + changed_pages_with(res, src, size, Some(&[0x30_0000]), PAGE, |at, len| { + calls.push((at, len)); + Cow::Borrowed(&mem[at - src..at - src + len]) + }), + None + ); + assert_eq!(calls, vec![(src, 0xB00)]); + + mem[size - 1] ^= 0xFF; + calls.clear(); + assert_eq!( + changed_pages_with(res, src, size, Some(&[0x30_2000]), PAGE, |at, len| { + calls.push((at, len)); + Cow::Borrowed(&mem[at - src..at - src + len]) + }), + Some(vec![2]) + ); + assert_eq!(calls, vec![(0x30_2000, 0x807)]); + + mem[0] ^= 0xFF; + calls.clear(); + assert_eq!( + changed_pages_with(res, src, size, Some(&[0x30_0000]), PAGE, |at, len| { + calls.push((at, len)); + Cow::Borrowed(&mem[at - src..at - src + len]) + }), + Some(vec![0]) + ); + assert_eq!(calls, vec![(src, 0xB00)]); + assert_eq!( + changed_pages_with(res, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), + None + ); + forget(res); + } + + #[test] + fn remapped_src_and_forget_force_full_upload_even_with_identical_bytes() { + use std::borrow::Cow; + const PAGE: usize = 0x1000; + let res = 0x7E57_2395_0004usize; + forget(res); + let mem = vec![0u8; 4 * PAGE]; + let src1 = 0x40_0000usize; + let src2 = 0x50_0000usize; + + assert_eq!( + changed_pages_with(res, src1, mem.len(), None, PAGE, |at, len| Cow::Borrowed(&mem[at - src1..at - src1 + len])), + Some(vec![0, 1, 2, 3]) + ); + assert_eq!( + changed_pages_with(res, src1, mem.len(), Some(&[src1]), PAGE, |at, len| Cow::Borrowed(&mem[at - src1..at - src1 + len])), + None + ); + + assert_eq!( + changed_pages_with(res, src2, mem.len(), Some(&[src2]), PAGE, |at, len| Cow::Borrowed(&mem[at - src2..at - src2 + len])), + Some(vec![0, 1, 2, 3]) + ); + assert_eq!( + changed_pages_with(res, src2, mem.len(), Some(&[src2 + PAGE]), PAGE, |at, len| Cow::Borrowed(&mem[at - src2..at - src2 + len])), + None + ); + + forget(res); + assert_eq!( + changed_pages_with(res, src2, mem.len(), Some(&[src2]), PAGE, |at, len| Cow::Borrowed(&mem[at - src2..at - src2 + len])), + Some(vec![0, 1, 2, 3]) + ); + forget(res); + } + + #[test] + fn duplicate_dirty_pages_produce_unique_changed_indices() { + use std::borrow::Cow; + const PAGE: usize = 0x1000; + let res = 0x7E57_2395_0005usize; + forget(res); + let mut mem = vec![0u8; 4 * PAGE]; + let src = 0x60_0000usize; + assert_eq!( + changed_pages_with(res, src, mem.len(), None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), + Some(vec![0, 1, 2, 3]) + ); + + mem[PAGE + 10] = 0xAA; + mem[3 * PAGE + 20] = 0xBB; + let dirty = [src + 3 * PAGE, src + PAGE, src + PAGE + 0x100, src + 3 * PAGE + 0x200, src + PAGE]; + let mut bytes_read = 0usize; + let got = changed_pages_with(res, src, mem.len(), Some(&dirty), PAGE, |at, len| { + bytes_read += len; + Cow::Borrowed(&mem[at - src..at - src + len]) + }); + assert_eq!(got, Some(vec![1, 3])); + assert_eq!(bytes_read, 2 * PAGE); + forget(res); + } + + #[test] + fn in_flight_cap_shrinks_under_low_commit() { + assert_eq!(in_flight_cap_bytes(false), IN_FLIGHT_BYTES); + assert_eq!(in_flight_cap_bytes(true), IN_FLIGHT_BYTES_LOW_COMMIT); + assert!(in_flight_cap_bytes(true) < in_flight_cap_bytes(false)); + } + + unsafe fn read_r8(dev: &ID3D12Device, queue: &ID3D12CommandQueue, texture: &ID3D12Resource) -> Vec { + own_work(|| { + let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0; + dev.GetCopyableFootprints(&texture.GetDesc(), 0, 1, 0, Some(&mut footprint), None, None, Some(&mut total)); + let mut readback = 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: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }, + D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback, + ).unwrap(); + let readback: ID3D12Resource = readback.unwrap(); + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + let barrier = |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(texture), Subresource: 0, StateBefore: before, StateAfter: after }) }, + ..Default::default() + }; + list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + 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(texture), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); + 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(); + crate::gpu::fence::wait(&fence, 1, dev, None, 5_000).unwrap(); + let mut data = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut data)).unwrap(); + let mut out = Vec::with_capacity(64 * 64); + for y in 0..64 { + out.extend_from_slice(std::slice::from_raw_parts((data as *const u8).add(footprint.Offset as usize + y * footprint.Footprint.RowPitch as usize), 64)); + } + readback.Unmap(0, None); + out + }) + } + + #[test] + fn gpu_uploads_on_the_title_queue_run_before_its_later_work_and_are_released() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + + 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; + } + 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 compute: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + assert!(title_queue_for(dev, Some(&queue)).is_some()); + assert!(title_queue_for(dev, Some(&compute)).is_none()); + assert!(title_queue_for(dev, None).is_none()); + let mut texture = 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 texture, + ).unwrap(); + let texture: ID3D12Resource = texture.unwrap(); + let key = queue.as_raw() as usize; + let upload = |value: u8| { + let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![value; 64 * 64] }]; + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + }; + for value in [0x21, 0xC4] { + upload(value); + assert_eq!(read_r8(dev, &queue, &texture), vec![value; 64 * 64], "the title queue's next work sees the upload"); + } + upload(0x5E); + { + let mut g = ON_QUEUE.lock().unwrap(); + let q = g.get_mut(&key).unwrap(); + assert_eq!(q.value, 3); + reclaim(dev, q, 0, 10_000); + assert!(q.in_flight.is_empty() && q.bytes == 0, "over the cap the oldest uploads are waited for and released"); + assert!(q.fence.GetCompletedValue() >= 3); + } + assert_eq!(read_r8(dev, &queue, &texture), vec![0x5E; 64 * 64]); + ON_QUEUE.lock().unwrap().remove(&key); + } + } + + #[test] + fn gpu_a_title_queue_upload_waits_for_the_page_mappings_before_it() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + + 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; + } + 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 Some(mapped) = super::super::vram::note_mapping_for_test(dev) else { + crate::gpu::recomp::runner::skip_test("no texture pages on this device"); + return; + }; + let key = queue.as_raw() as usize; + assert!(super::super::vram::waited_for_test(raw_device as usize, key) < mapped); + let mut texture = 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 texture, + ).unwrap(); + let texture: ID3D12Resource = texture.unwrap(); + let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![0x3C; 64 * 64] }]; + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + assert_eq!( + super::super::vram::waited_for_test(raw_device as usize, key), + mapped, + "the title queue's upload must wait for the page mappings made before it" + ); + assert_eq!(read_r8(dev, &queue, &texture), vec![0x3C; 64 * 64]); + ON_QUEUE.lock().unwrap().remove(&key); + } + } + + #[test] + fn gpu_an_upload_still_running_is_kept_when_its_wait_times_out() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + + 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; + } + 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 gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + let mut texture = 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 texture, + ).unwrap(); + let texture: ID3D12Resource = texture.unwrap(); + let key = queue.as_raw() as usize; + let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![0x77; 64 * 64] }]; + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + { + let mut g = ON_QUEUE.lock().unwrap(); + let q = g.get_mut(&key).unwrap(); + reclaim(dev, q, 0, 50); + assert_eq!(q.in_flight.len(), 1, "a batch the GPU has not run stays in flight when its wait times out"); + assert!(q.bytes > 0); + } + gate.Signal(1).unwrap(); + { + let mut g = ON_QUEUE.lock().unwrap(); + let q = g.get_mut(&key).unwrap(); + reclaim(dev, q, 0, 10_000); + assert!(q.in_flight.is_empty() && q.bytes == 0); + } + assert_eq!(read_r8(dev, &queue, &texture), vec![0x77; 64 * 64]); + ON_QUEUE.lock().unwrap().remove(&key); + } + } + /// Real uploads, dirty-page detection and a source changing after registration: /// bookkeeping alone cannot show that the bytes the GPU sees follow the mirror. #[test] @@ -1565,45 +2680,6 @@ mod tests { assert!(kernelx::in_graphics_reservation(at), "fallback must be write-watched"); reservation } - unsafe fn read_r8(dev: &ID3D12Device, queue: &ID3D12CommandQueue, texture: &ID3D12Resource) -> Vec { - own_work(|| { - let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); - let mut total = 0; - dev.GetCopyableFootprints(&texture.GetDesc(), 0, 1, 0, Some(&mut footprint), None, None, Some(&mut total)); - let mut readback = 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 readback, - ).unwrap(); - let readback: ID3D12Resource = readback.unwrap(); - let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); - let barrier = |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(texture), Subresource: 0, StateBefore: before, StateAfter: after }) }, - ..Default::default() - }; - list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); - 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(texture), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; - list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); - list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); - 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(); - crate::gpu::fence::wait(&fence, 1, dev, None, 5_000).unwrap(); - let mut data = std::ptr::null_mut(); - readback.Map(0, None, Some(&mut data)).unwrap(); - let mut out = Vec::with_capacity(64 * 64); - for y in 0..64 { - out.extend_from_slice(std::slice::from_raw_parts((data as *const u8).add(footprint.Offset as usize + y * footprint.Footprint.RowPitch as usize), 64)); - } - readback.Unmap(0, None); - out - }) - } unsafe { let raw_device = super::super::real::device_raw(); let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); @@ -1941,12 +3017,12 @@ 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); @@ -1957,6 +3033,99 @@ mod tests { assert!(tbl.by_res.contains_key(&10) && tbl.by_res.contains_key(&11)); assert_eq!(tbl.insert(12, entry(0x20_0000, &tex_64k, true, false)), (-1, vec![])); assert!(!tbl.by_res.contains_key(&10) && !tbl.by_res.contains_key(&11) && tbl.by_res.contains_key(&12)); + // Unaligned 88 KiB mip-chain siblings at +0x4000 own page +0x1_0000 plus 1 extra_page; + // an aligned 64 KiB cover at +0x1_0000 supersedes both without allocating a new base page. + let tex_88k = Arc::new(xg::Texture::new(&console_desc(3, 128, 128, 1, 8, 28, 0x105)).unwrap()); + assert_eq!(tex_88k.size(), 0x1_6000); + assert_eq!(tbl.insert(30, entry(0x30_4000, &tex_88k, true, true)), (1, vec![])); + assert_eq!(tbl.insert(31, entry(0x30_4000, &tex_88k, true, true)), (0, vec![])); + let (_, mut unmap_unaligned) = tbl.insert(32, entry(0x31_0000, &tex_64k, true, true)); + unmap_unaligned.sort_unstable(); + assert_eq!(unmap_unaligned, vec![30, 31]); + } + + /// Real GPU: render targets at two addresses of one physical page (mapped at the second after + /// the first, as a retail game aliases its targets) share one page of video memory, as on the + /// console; a target on another physical page gets its own. + #[test] + fn render_targets_on_one_physical_page_share_its_video_memory() { + // (a test that panicked holding these locks does not fail this one too) + 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()); + use crate::hle::kernelx; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + const NAME: &str = "render_targets_on_one_physical_page_share_its_video_memory"; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let Ok(adapter) = factory.EnumAdapters1(0) else { return println!("SKIPPED {NAME}: no adapter") }; + if adapter.GetDesc1().is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) { + return println!("SKIPPED {NAME}: software adapter"); + } + let mut dev: Option = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev else { return println!("SKIPPED {NAME}: no D3D12 device") }; + 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.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0 + { + return println!("SKIPPED {NAME}: tiled tier < 2"); + } + // (`vram::place` keeps no render target on pages below resource heap tier 2) + if opts.ResourceHeapTier.0 < 2 { + return println!("SKIPPED {NAME}: resource heap tier < 2"); + } + if crate::gpu::uma::get().is_none() { + return println!("SKIPPED {NAME}: no UMA"); + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + // a 128x128 R8G8B8A8 render target: one 64 KiB page on the console and on the PC + let mut rt = console_desc(3, 128, 128, 1, 1, 28, 0x109); + rt[0x30..0x34].copy_from_slice(&1u32.to_le_bytes()); + let place = |va: usize| -> ID3D12Resource { + let mut p = std::ptr::null_mut(); + let hr = super::super::device_x::create_placed_resource_x(dev.as_raw(), va as u64, rt.as_ptr(), D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32, std::ptr::null(), riid, &mut p); + assert!(hr >= 0 && !p.is_null(), "CreatePlacedResourceX at {va:#x}: {hr:#x}"); + assert!(super::super::vram::is_placed_texture(p as usize), "expected a vram::Pages target at {va:#x}"); + ID3D12Resource::from_raw(p) + }; + let dev_pages = || super::super::vram::page_bytes_for(dev.as_raw() as usize).0; + let lost = || super::super::vram::tiles_unaccounted_for(dev.as_raw() as usize); + let space = VirtualAlloc(std::ptr::null(), 4 << 20, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(space, 0); + let (a, b, c, d) = (space, space + (1 << 20), space + (2 << 20), space + (3 << 20)); + let (mut n, mut pages) = (3usize, [0usize; 3]); + assert_eq!(kernelx::AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let (before, lost_before) = (dev_pages(), lost()); + assert_eq!(kernelx::MapTitlePhysicalPages(a as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, a); + let first = place(a); + // the same page at a second address: the console's alias of `a` + assert_eq!(kernelx::MapTitlePhysicalPages(b as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, b); + let second = place(b); + let shared = dev_pages() - before; + // another physical page: video memory of its own + assert_eq!(kernelx::MapTitlePhysicalPages(c as *mut c_void, 1, 0, 4, pages.as_mut_ptr().add(1)) as usize, c); + let third = place(c); + let all = dev_pages() - before; + // a target at `d` with no page mapped (keyed by its address), then a page mapped there + // and a second target: its page is keyed by the physical page, which has none yet + let fourth = place(d); + assert_eq!(kernelx::MapTitlePhysicalPages(d as *mut c_void, 1, 0, 4, pages.as_mut_ptr().add(2)) as usize, d); + let fifth = place(d); + let lost_after = lost(); + drop((first, second, third, fourth, fifth)); + let mut none = [0usize; 1]; + kernelx::MapTitlePhysicalPages(b as *mut c_void, 1, 0, 4, none.as_mut_ptr()); + kernelx::MapTitlePhysicalPages(c as *mut c_void, 1, 0, 4, none.as_mut_ptr()); + kernelx::MapTitlePhysicalPages(d as *mut c_void, 1, 0, 4, none.as_mut_ptr()); + kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), 3, pages.as_mut_ptr()); + VirtualFree(space as *mut c_void, 0, MEM_RELEASE); + assert_eq!(shared, 0x1_0000, "two targets on one physical page: one page of video memory"); + assert_eq!(all, 0x2_0000, "a target on another physical page: a page of its own"); + assert_eq!(lost_after, lost_before, "every pool tile taken is a page's"); + } } /// Real GPU (#248): placed title textures share `vram::Pages` so streaming unreleased @@ -2093,6 +3262,7 @@ mod tests { // 1. Streaming 512 unreleased 1 MiB textures (512 MiB placed) across 16 MiB stays bounded // with zero additional page growth after the 16 MiB working set is covered. let dev_key = dev.as_raw() as usize; + super::super::vram::flush_idle_for(dev_key); let dev_pages = || super::super::vram::page_bytes_for(dev_key).0; let stream_desc = console_desc(3, 512, 512, 1, 1, 28, 0x109); // 64KB_S, 1 MiB let (pages0, vram0, kept0) = (dev_pages(), local_vram(), counts().0); @@ -2162,10 +3332,13 @@ mod tests { assert_eq!(read_sub(&old_res, 0), subresources(base, &xg::Texture::new(&old_desc).unwrap())[0].data, "reactivated unmapped texture remapped cleanly"); drop(old_res); - // 3. 4 KiB-aligned adjacent textures inside one 64 KiB page + straddling page boundary, - // plus reclaiming dead extra_pages when overwritten by a larger placement without Release. + // 3. 4 KiB-aligned adjacent small textures pack into 4 KiB sub-allocated slots (no 64 KiB + // bloat per small texture), reuse the exact slot at the same va without crosstalk, and + // >= 64 KiB unaligned textures reclaim dead extra_pages immediately when overwritten. + super::super::vram::flush_idle_for(dev_key); let d16 = console_desc(3, 64, 64, 1, 1, 28, 0x105); // 4KB_S, 16 KiB let d64 = console_desc(3, 128, 128, 1, 1, 28, 0x105); // 4KB_S, 64 KiB + let adj_base_pages = dev_pages(); let adj_specs = [(0x0000usize, d16, 0x11u8), (0x4000, d16, 0x22), (0x8000, d16, 0x33), (0xC000, d64, 0x44), (0x1_C000, d16, 0x55)]; let adj: Vec<_> = adj_specs.iter().map(|&(off, d, _)| place_tex(base + off, &d)).collect(); for &(off, d, seed) in &adj_specs { @@ -2176,36 +3349,37 @@ mod tests { assert_eq!(read_sub(r, 0), subresources(base + off, &xg::Texture::new(&d).unwrap())[0].data, "4 KiB neighbour at +{off:#x} crosstalk"); } let pages_before_reuse = dev_pages(); - // Binding sweeps pages idle for two seconds, so the device-wide count can fall - // here even when this placement shares the extra tile it already has. - let first = adj[1].as_raw() as usize; - let before = super::super::vram::mapped_tiles_for(dev_key, first); + let adj_delta = pages_before_reuse - adj_base_pages; + assert!(adj_delta <= 128 * 1024, "four 16 KiB + one 64 KiB textures should use <= 128 KiB, got {adj_delta} B"); let reused = place_tex(base + 0x4000, &d16); - if super::super::vram::is_placed_texture(first) { - let before = before.expect("the first unaligned placement is mapped"); - assert!(!before.1.is_empty(), "a 16 KiB texture in a 64 KiB page uses an extra tile"); - assert_eq!( - super::super::vram::mapped_tiles_for(dev_key, first).as_ref(), - Some(&before), - "the first placement keeps its tiles when the va is placed again", - ); - assert_eq!( - super::super::vram::mapped_tiles_for(dev_key, reused.as_raw() as usize).as_ref().map(|t| &t.1), - Some(&before.1), - "reusing unaligned va must share extra_pages tile", - ); - } else { - assert_eq!(dev_pages(), pages_before_reuse, "reusing unaligned va must share extra_pages tile"); - } - // Overwrite the first 64 KiB (covering +0x0000, +0x4000 (both adj[1] & reused), +0x8000, +0xC000) - // WITHOUT releasing adj/reused: dead extra_pages (+0x4000, +0x8000) must drop immediately! - let cover = place_tex(base, &d64); + assert_eq!(dev_pages(), pages_before_reuse, "reusing unaligned va must share backing slot"); + drop((reused, adj)); + + // Reclaiming dead extra_pages immediately when a >= 64 KiB unaligned tiled texture is + // overwritten by an overlapping placement without Release: + // `unaligned_a`/`b` at `base + 0x4000` (88 KiB, 2 tiles) own page `base + 0x1_0000` + // plus 1 `extra_pages` tile; `cover` at `base + 0x1_0000` reuses that already-live + // owned page (+0 new pages) while superseding both unaligned siblings and reclaiming + // their `extra_pages` tile immediately (-64 KiB). + super::super::vram::flush_idle_for(dev_key); + let d64_mips = console_desc(3, 128, 128, 1, 8, 28, 0x105); // 88 KiB, 2 tiles (mip 0 + packed mips) + let extra_before = super::super::vram::extra_page_bytes_for(dev_key); + let unaligned_a = place_tex(base + 0x4000, &d64_mips); + let extra_after_a = super::super::vram::extra_page_bytes_for(dev_key); + assert!(extra_after_a > extra_before, "unaligned >= 64 KiB tiled texture must allocate extra_pages ({extra_before} -> {extra_after_a})"); + let unaligned_b = place_tex(base + 0x4000, &d64_mips); + assert_eq!(super::super::vram::extra_page_bytes_for(dev_key), extra_after_a, "reusing unaligned va must share extra_pages tile"); + let pages_with_extra = dev_pages(); + let cover = place_tex(base + 0x1_0000, &d64); let pages_after_cover = dev_pages(); - assert!(pages_after_cover < pages_before_reuse, "superseded unaligned extra_pages must be reclaimed immediately ({pages_before_reuse} -> {pages_after_cover})"); - drop((cover, reused, adj)); + let extra_after_cover = super::super::vram::extra_page_bytes_for(dev_key); + assert_eq!(extra_after_cover, extra_before, "superseded unaligned extra_pages must drop back to baseline ({extra_after_a} -> {extra_after_cover})"); + assert!(pages_after_cover < pages_with_extra, "superseded unaligned extra_pages must be reclaimed immediately ({pages_with_extra} -> {pages_after_cover})"); + drop((cover, unaligned_b, unaligned_a)); // 4. Full mip chain (standard + packed mips, RGBA8 & BC7), tiny all-packed mips, // 6-slice cubemap (exercises extra_pages reuse), and 3D volume texture (Tier 3). + super::super::vram::flush_idle_for(dev_key); let shapes = [ ("2D 512x512 RGBA8 10 mips", console_desc(3, 512, 512, 1, 10, 28, 0x109)), ("2D 1024x1024 BC7 11 mips", console_desc(3, 1024, 1024, 1, 11, 98, 0x109)), @@ -2362,14 +3536,14 @@ mod tests { g.insert(gpu_res_id, StreamRecheck { base_frame: 100, stage: 0, last_fp: fp0 }); } - // Before first milestone (+4 frames -> frame 104), nothing is checked or re-queued. + // Before first milestone (+1 frame -> frame 101), nothing is checked or re-queued. backing[size - 16] = 0xAB; - unsafe { recheck_streamed_unwatched_at(&[], 103) }; + unsafe { recheck_streamed_unwatched_at(&[], 100) }; assert!(!TEXTURES.lock().unwrap().by_res.get(&res_id).unwrap().pending); - // At milestone 0 (frame 104), late write is detected: pending becomes true, schedule resets - // to base_frame=104, stage=0, and the gpu_written entry is pruned without re-queuing. - unsafe { recheck_streamed_unwatched_at(&[], 104) }; + // At milestone 0 (frame 101), late write is detected: pending becomes true, schedule resets + // to base_frame=101, stage=0, and the gpu_written entry is pruned without re-queuing. + unsafe { recheck_streamed_unwatched_at(&[], 101) }; { let mut t = TEXTURES.lock().unwrap(); let e = t.by_res.get_mut(&res_id).unwrap(); @@ -2382,17 +3556,19 @@ mod tests { let g = STREAM_RECHECK.lock().unwrap(); assert!(!g.contains_key(&gpu_res_id), "gpu_written texture must be pruned from STREAM_RECHECK"); let st = g.get(&res_id).copied().expect("schedule reset after change"); - assert_eq!((st.base_frame, st.stage), (104, 0)); + assert_eq!((st.base_frame, st.stage), (101, 0)); assert_ne!(st.last_fp, fp0); } - // Advance through all 5 milestones with no further writes: entry must not re-queue and must - // clean itself up after milestone 4 (+400 frames -> frame 504). - for f in [108, 116, 144, 224, 504] { + // Advance through all 6 milestones with no further writes: entry must not re-queue and must + // clean itself up after milestone 5 (+400 frames -> frame 501). + for f in [102, 105, 113, 141, 221, 501] { unsafe { recheck_streamed_unwatched_at(&[], f) }; assert!(!TEXTURES.lock().unwrap().by_res.get(&res_id).unwrap().pending, "unchanged texture must not re-queue at frame {f}"); } assert!(!STREAM_RECHECK.lock().unwrap().contains_key(&res_id), "entry must retire after final 400-frame milestone"); + assert!(batch_fits_limit(0, 0, 1, 1, BATCH_BYTES, BATCH_BYTES_LOW_COMMIT), "empty batch always makes progress"); + assert!(!batch_fits_limit(1, BATCH_BYTES_LOW_COMMIT, 1, 1, 1, BATCH_BYTES_LOW_COMMIT), "low-commit cap bounds batch size"); forget(res_id); forget(gpu_res_id); @@ -2520,8 +3696,24 @@ mod tests { 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); let full = place_tex(at); + let full_key = full.as_raw() as usize; + super::super::vram::FAIL_LEVEL_BIND_FOR_TEST.with(|failure| failure.set(Some((full_key, 0)))); refresh(queue.as_raw()); - assert_eq!(dev_pages() - p0, (all as usize) << 16, "mip 0's pages come with its texels; the other levels' are shared"); + assert_eq!(dev_pages() - p0, ((all - top_tiles) as usize) << 16, "the failed mapping left mip 0 without pages"); + assert!(read_sub(&full, 0).iter().all(|&b| b == 0), "the failed mip still reads as zeros"); + assert!(read_sub(&full, 1) == want[1].data, "the other mips still upload"); + + // Offer the texture again without changing any of its source bytes. + { + let mut textures = TEXTURES.lock().unwrap(); + let entry = textures.by_res.get_mut(&full_key).unwrap(); + assert!(!entry.pending); + entry.pending = true; + textures.pending_res.insert(full_key); + adjust_pending(1); + } + refresh(queue.as_raw()); + assert_eq!(dev_pages() - p0, (all as usize) << 16, "retry maps mip 0 with the same source bytes; the other levels are shared"); for sub in 0..11u32 { assert!(read_sub(&full, sub) == want[sub as usize].data, "level {sub} once all of it is there"); } @@ -2630,4 +3822,126 @@ mod tests { // Different device always starts a new batch. assert!(!batch_fits(1, 4096, 1, 2, 4096)); } + + #[test] + fn dirty_and_pending_uses_src_index_for_small_large_pending_and_gpu_written() { + let mut desc_small = [0u8; 0x38]; + desc_small[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + desc_small[0x10..0x18].copy_from_slice(&64u64.to_le_bytes()); + desc_small[0x18..0x1C].copy_from_slice(&64u32.to_le_bytes()); + desc_small[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + desc_small[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + desc_small[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); // RGBA8 (16 KiB) + desc_small[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + let tex_small = Arc::new(xg::Texture::new(&desc_small).unwrap()); + assert!((tex_small.size() as usize) <= SMALL_SRC_MAX); + + let mut desc_large = desc_small; + desc_large[0x10..0x18].copy_from_slice(&512u64.to_le_bytes()); + desc_large[0x18..0x1C].copy_from_slice(&512u32.to_le_bytes()); // 1 MiB + let tex_large = Arc::new(xg::Texture::new(&desc_large).unwrap()); + assert!((tex_large.size() as usize) > SMALL_SRC_MAX); + + let mk = |va: usize, src: usize, tex: &Arc, pending: bool, gpu_written: bool| Entry { + device: 1, + va, + src, + in_gpu_view: false, + tex: Arc::clone(tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending, + gpu_written, + placed: false, + unmapped: false, + seq: 0, + }; + + let mut t = Table::new(); + t.insert(0x100, mk(0x1000_0000, 0x2000_0000, &tex_small, false, false)); + t.insert(0x200, mk(0x1010_0000, 0x2010_0000, &tex_small, true, false)); + t.insert(0x300, mk(0x1020_0000, 0x2020_0000, &tex_large, false, false)); + t.insert(0x400, mk(0x1030_0000, 0x2030_0000, &tex_small, false, true)); + + // Only pending entry fires with no dirty pages. + let (hits, cleared) = t.dirty_and_pending(&[], 0x1000); + assert_eq!(hits, vec![(0x200, true)]); + assert_eq!(cleared, 1); + + // Dirty pages hitting small, large, and gpu_written return only small + large. + let dirty = [0x2000_1000, 0x2021_0000, 0x2030_0000]; + let (hits, cleared) = t.dirty_and_pending(&dirty, 0x1000); + assert_eq!(hits, vec![(0x100, false), (0x300, false)]); + assert_eq!(cleared, 0); + + // Marking small as gpu_written removes it from dirty scans. + assert!(t.mark_gpu_written(0x100)); + let (hits, _) = t.dirty_and_pending(&dirty, 0x1000); + assert_eq!(hits, vec![(0x300, false)]); + } + + #[test] + fn detile_pool_reuses_workers_across_multiple_batches() { + let pool = DetilePool::new(4); + for round in 0..4usize { + let next = std::sync::atomic::AtomicUsize::new(0); + let slots: Vec = (0..64).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect(); + pool.run(4, &|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= slots.len() { + break; + } + slots[i].store((i + 1) * (round + 1), Ordering::Relaxed); + }); + for (i, s) in slots.iter().enumerate() { + assert_eq!(s.load(Ordering::Relaxed), (i + 1) * (round + 1)); + } + } + } + + #[test] + fn title_bytes_outside_uma_copies_safely_via_read_committed() { + let mut buf = vec![0x5Au8; 4096]; + buf[0] = 0x11; + buf[4095] = 0xEE; + let got = unsafe { title_bytes(buf.as_ptr() as usize, buf.len()) }; + assert!(matches!(got, std::borrow::Cow::Owned(_)), "non-UMA allocations must copy via read_committed so concurrent decommits cannot fault"); + assert_eq!(got.len(), 4096); + assert_eq!((got[0], got[1], got[4095]), (0x11, 0x5A, 0xEE)); + } + + #[test] + fn watchable_ranges_excludes_gpu_written_textures() { + let mut desc = [0u8; 0x38]; + desc[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + desc[0x10..0x18].copy_from_slice(&64u64.to_le_bytes()); + desc[0x18..0x1C].copy_from_slice(&64u32.to_le_bytes()); + desc[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + desc[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + desc[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); // RGBA8 + desc[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + let tex = Arc::new(xg::Texture::new(&desc).unwrap()); + let span = (tex.size() as usize + 0xFFF) & !0xFFF; + + let mk = |va: usize, src: usize, gpu_written: bool| Entry { + device: 1, + va, + src, + in_gpu_view: false, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written, + placed: false, + unmapped: false, + seq: 0, + }; + + let mut t = Table::new(); + t.insert(0x100, mk(0x1000_0000, 0x2000_0000, false)); + t.insert(0x200, mk(0x1010_0000, 0x2010_0000, true)); + assert_eq!(t.watchable_ranges(), vec![(0x2000_0000, 0x2000_0000 + span)]); + + assert!(t.mark_gpu_written(0x100)); + assert!(t.watchable_ranges().is_empty()); + } } diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index ea49ce6b89..321db34960 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -23,6 +23,7 @@ //! driver does not make reserved: D32S8, MSAA): heaps of the placement's size, shared by //! placements inside them, let go 2 s after their last resource (256 MiB ones: 2.8 GB of D32S8). +use super::place_times::{step, Step}; use std::collections::HashSet; use std::ffi::c_void; use std::sync::Mutex; @@ -123,23 +124,187 @@ static MADE_BYTES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsi pub fn arena_bytes() -> (usize, usize) { (ARENAS.lock().unwrap().bytes(), MADE_BYTES.load(std::sync::atomic::Ordering::Relaxed)) } -static PLACED_TEXTURES: Mutex>> = Mutex::new(None); +static PLACED_TEXTURES: std::sync::RwLock>> = std::sync::RwLock::new(None); /// A texture backed by one of the aliasable D3D12 heaps. pub(super) fn is_placed_texture(resource: usize) -> bool { - PLACED_TEXTURES.lock().unwrap().as_ref().is_some_and(|textures| textures.contains(&resource)) + PLACED_TEXTURES.read().unwrap().as_ref().is_some_and(|textures| textures.contains(&resource)) } -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 let Some(id) = ARENA_OF.lock().unwrap().as_mut().and_then(|m| m.remove(&resource)) { - ARENAS.lock().unwrap().release(id, std::time::Instant::now()); +/// 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)>, + live: usize, + cap: usize, +} + +impl ReservedPool { + fn new(cap: usize) -> Self { + Self { + by_key: std::collections::HashMap::new(), + order: std::collections::VecDeque::new(), + live: 0, + cap, + } + } + + fn take(&mut self, key: &ReservedKey) -> Option<(usize, u32, Option)> { + let bucket = self.by_key.get_mut(key)?; + let item = bucket.pop()?; + if bucket.is_empty() { + self.by_key.remove(key); + } + self.live -= 1; + Some(item) + } + + fn push(&mut self, key: ReservedKey, raw: usize, total: u32, levels: Option) -> Option { + if self.cap == 0 { + return Some(raw); + } + let mut evicted = None; + while self.live >= self.cap { + let Some((old_key, old_raw)) = self.order.pop_front() else { break }; + if let Some(bucket) = self.by_key.get_mut(&old_key) { + if let Some(pos) = bucket.iter().position(|(r, _, _)| *r == old_raw) { + bucket.swap_remove(pos); + if bucket.is_empty() { + self.by_key.remove(&old_key); + } + self.live -= 1; + evicted = Some(old_raw); + break; + } + } + } + self.by_key.entry(key).or_default().push((raw, total, levels)); + self.order.push_back((key, raw)); + self.live += 1; + evicted + } +} + +/// Metadata for a released reserved sampled texture awaiting GPU completion in `late_release`. +pub(super) struct RecycleInfo { + dev_key: usize, + key: ReservedKey, + total: u32, + was_mapped: bool, + levels: Option, +} + +static PARKING: Mutex>> = Mutex::new(None); + +unsafe fn release_raw_com(raw: usize) { + let ptr = raw as *mut c_void; + let f: unsafe extern "system" fn(*mut c_void) -> u32 = if super::real::is_adopted(ptr) { + std::mem::transmute(super::real::orig_fn(ptr, 2)) + } else { + std::mem::transmute(*(*(ptr as *const *const usize)).add(2)) + }; + f(ptr); +} + +pub(super) fn forget_for_recycle(resource: usize, held: bool) -> Option { + let placed = PLACED_TEXTURES.write().unwrap().as_mut().is_some_and(|textures| textures.remove(&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()); + } + info +} + +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 unmapped and parked in the per-device reuse pool (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() || commit_low() { + return false; + } + let evicted = { + 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.reserved_pool.push(info.key, resource, info.total, info.levels) + }; + if let Some(old) = evicted { + release_raw_com(old); + } + true +} + +#[allow(dead_code)] +pub(super) fn forget(resource: usize) { + let _ = forget_for_recycle(resource, false); +} + /// 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 { @@ -166,6 +331,11 @@ unsafe fn arena_heap(dev: &ID3D12Device, va: usize, size: usize, align: usize) - if n < 16 || n.is_power_of_two() { crate::xlog_info!("D3D12.X: video-memory arena #{n} for title addresses {va:#x}..{:#x} ({made} bytes of arenas made so far)", va + size); } + if super::real::dred_on() { + if let Some(ref h) = heap { + super::real::name_heap(h.as_raw(), &format!("xcl vram arena va={va:#x}")); + } + } heap } @@ -229,10 +399,97 @@ struct Target { console_bytes: Option, total: u32, mapped: bool, + /// incremented on every `unmap_superseded` / `remap_if_unmapped` to cancel stale deferred unmaps + mapping_gen: u64, used: Vec, used_extra: Vec<(usize, usize)>, + /// its owned pages in graphics reservations (`Pages::follow`) + follows: Vec, + /// whether uncommitted pages in graphics reservations may be skipped (`FollowSkip`): + /// true for sampled textures (`place_pages`), false for GPU-owned `RT | DS | UAV` targets (`place`) + follow_backing: bool, /// its levels get their pages one by one (`map_levels`); None: all of it has pages levels: Option, + recycle: Option, + /// placed as GPU-owned: its pages are keyed by the physical page under them (`page_key`) + gpu_owned: bool, +} + +/// An owned page of placed textures in a graphics reservation: mapped only while the title +/// has memory there (committed, a physical page, or one mapped but not yet touched). +struct Follow { + /// (texture, its tile at this page) + users: Vec<(usize, u32)>, + /// whether the textures' tiles there are on a page of video memory + mapped: bool, +} + +/// Ranges of title memory a graphics reservation gained or lost memory in since the last +/// submit (`title_memory_changed`): the pages there are mapped or unmapped before the next one. +static BACKING: Mutex> = Mutex::new(Vec::new()); + +/// The title committed, mapped, decommitted or unmapped `[a, a + n)` of a graphics reservation: +/// the texture pages there follow it before the title's next submit (`before_execute`). +pub fn title_memory_changed(a: usize, n: usize) { + if n > 0 { + // a CPU view's change is its GPU views' too + let gpus = crate::hle::kernelx::mirrors::gpu_views_of(a); + let mut b = BACKING.lock().unwrap(); + b.push((a, n)); + for g in gpus { + b.push((g, n)); + } + } +} + +/// Cached `VirtualQuery` region run so checking contiguous uncommitted pages in a reservation +/// issues one syscall per region instead of one per 64 KiB page. +#[derive(Default)] +struct BackedRun { + start: usize, + end: usize, + committed: bool, +} + +/// Whether the title has memory at the 64 KiB page `a`: committed, a physical page mapped there, +/// or one mapped and not touched yet (`lazy`). In a GPU view of the title's CPU memory +/// (`kernelx::mirrors`) that is the memory of the mapped source or CPU view behind it. +fn title_backed_in(a: usize, run: &mut BackedRun) -> bool { + let a = match crate::hle::kernelx::mirrors::mapped_source(a) { + Some(Some(s)) => s, + Some(None) => return false, + None => crate::hle::kernelx::mirrors::source(a).unwrap_or(a), + }; + let committed = if (run.start..run.end).contains(&a) { + run.committed + } else { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + if unsafe { VirtualQuery(a as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0 && m.RegionSize > 0 { + let start = m.BaseAddress as usize; + *run = BackedRun { start, end: start.saturating_add(m.RegionSize), committed: m.State == MEM_COMMIT }; + run.committed + } else { + false + } + }; + committed || crate::hle::kernelx::lazy::is_lazy(a) || crate::hle::kernelx::physical_page_at(a) +} + +/// The ranges of one UpdateTileMappings call over all `total` tiles of a resource: `sel(i)` is +/// the heap offset of tile i when this call sets it (Some), else it is skipped. `flag` for the +/// set runs (NONE: onto a heap; NULL: unmapped). +fn update_ranges(total: u32, flag: D3D12_TILE_RANGE_FLAGS, sel: impl Fn(u32) -> Option) -> Vec<(D3D12_TILE_RANGE_FLAGS, u32, u32)> { + let mut out: Vec<(D3D12_TILE_RANGE_FLAGS, u32, u32)> = Vec::new(); + for i in 0..total { + match (sel(i), out.last_mut()) { + (Some(o), Some(r)) if r.0 == flag && (flag == D3D12_TILE_RANGE_FLAG_NULL || r.1 + r.2 == o) => r.2 += 1, + (Some(o), _) => out.push((flag, if flag == D3D12_TILE_RANGE_FLAG_NULL { 0 } else { o }, 1)), + (None, Some(r)) if r.0 == D3D12_TILE_RANGE_FLAG_SKIP => r.2 += 1, + (None, _) => out.push((D3D12_TILE_RANGE_FLAG_SKIP, 0, 1)), + } + } + out } /// The tiles of a texture whose levels get video memory when an upload first has texels for @@ -302,6 +559,11 @@ pub(super) fn level_pages() -> bool { #[cfg(test)] pub(super) static LEVEL_PAGES_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +#[cfg(test)] +thread_local! { + pub(super) static FAIL_LEVEL_BIND_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + /// Of the textures with lazy levels there are now: how many, the tiles they stand for, and the /// tiles of them that have pages; and the level groups given pages so far. static LEVEL_STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; @@ -348,6 +610,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`. @@ -359,20 +625,47 @@ impl TilePool { TilePool { free_by_heap: Vec::new(), dirty_sort: Vec::new(), + dirty_bits: Vec::new(), free_total: 0, cooling: std::collections::VecDeque::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)]); } 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.free_total += pool_pages as usize; } @@ -395,6 +688,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.free_total -= full; reclaimed.push(h as u32); } @@ -405,31 +699,56 @@ 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.free_by_heap[idx].push(t); self.dirty_sort[idx] = true; + self.mark_dirty(idx, t); self.free_total += 1; } } } + /// Move every cooled tile (`>= COOL`) into its pool heap's free list. + #[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.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.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 @@ -465,26 +784,56 @@ 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> { + self.take_batch_fenced(count, preferred, now, None, pool_pages, make_heap) + } + + #[cfg(test)] + fn take_batch_fenced( + &mut self, + count: usize, + preferred: Option, + now: std::time::Instant, + safe_before: Option, + pool_pages: u32, + make_heap: impl FnMut() -> Option, + ) -> Option> { + let mut ignored = Vec::new(); + self.take_batch_fenced_recycled(count, preferred, now, safe_before, pool_pages, &mut ignored, make_heap) + } + + fn take_batch_fenced_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); @@ -495,10 +844,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; @@ -507,6 +858,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 { @@ -521,6 +898,11 @@ unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { crate::xlog_warn!("D3D12.X: no video memory for more pages of title textures ({e})"); return None; } + if super::real::dred_on() { + if let Some(ref h) = heap { + super::real::name_heap(h.as_raw(), "xcl vram tile_pool"); + } + } heap } @@ -528,13 +910,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 { @@ -546,20 +931,113 @@ 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 { + self.zero_bufs.get_mut(idx as usize).map(|b| b.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?; + if super::real::dred_on() { + super::real::name_resource(buf.as_raw(), &format!("xcl vram zero_alias h={idx}")); + } + self.zero_bufs[idx] = Some(buf.clone()); + Some(buf) + } +} + +/// 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 { @@ -579,14 +1057,100 @@ fn keep_spare_pools() -> usize { }) } +/// Default Windows virtual commit reserve floor (4 GiB) below which optional VRAM pool spares, +/// reserved-texture reuse caching, and large upload staging batches shed commit headroom. +const DEFAULT_COMMIT_RESERVE_MIB: u64 = 4096; + +/// `XCL_COMMIT_RESERVE_MB` (default `4096`, `0` disables): free Windows commit floor in bytes. +fn commit_reserve_bytes() -> u64 { + static FLOOR: std::sync::OnceLock = std::sync::OnceLock::new(); + *FLOOR.get_or_init(|| { + let mib = std::env::var("XCL_COMMIT_RESERVE_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(DEFAULT_COMMIT_RESERVE_MIB); + mib.saturating_mul(1024 * 1024) + }) +} + +fn avail_commit_bytes() -> 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) +} + +fn commit_below_floor(avail_bytes: Option, floor_bytes: u64) -> bool { + floor_bytes > 0 && avail_bytes.is_some_and(|avail| avail < floor_bytes) +} + +/// True when Windows available virtual commit (`ullAvailPageFile`) is below the reserve floor. +pub(super) fn commit_low() -> bool { + commit_below_floor(avail_commit_bytes(), commit_reserve_bytes()) +} + +/// Deferred `UpdateTileMappings(NULL)` operation awaiting completion of all in-flight device queues. +enum PendingUnmapOp { + /// Whole-resource unmap from `unmap_superseded` (skipped if `Target::mapping_gen` advanced). + Whole { res: ID3D12Resource, key: usize, gen: u64, total: u32, tiles: Vec }, + /// Per-tile unmap from `apply_backing` (each `(tile_idx, page_addr)` skipped if `follow[page_addr].mapped` became true again). + Tiles { res: ID3D12Resource, key: usize, total: u32, pairs: Vec<(u32, usize)> }, +} + +/// 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>, +} + +/// 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, - /// signalled after each mapping; title queues wait for it before their next work + /// signalled after mappings before GPU queues execute; title queues wait for it before their next work fence: ID3D12Fence, value: u64, + /// true when `map()` / `unmap()` queued tile mappings not yet followed by `queue.Signal` + dirty_signal: bool, /// 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, pools: PoolHeaps, pool: TilePool, /// title page address → its video memory @@ -600,13 +1164,24 @@ struct Pages { targets: std::collections::HashMap, /// queue → the fence value it last waited for waited: std::collections::HashMap, + /// owned pages of textures in graphics reservations → their textures (`Follow`) + follow: 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, /// reusable scratch buffers for `map()` + scratch_tiles: Vec, scratch_heaps: Vec, 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 @@ -627,12 +1202,22 @@ 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(), + dirty_signal: false, + 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(), @@ -640,14 +1225,40 @@ impl Pages { idle: std::collections::VecDeque::new(), targets: std::collections::HashMap::new(), waited: std::collections::HashMap::new(), + follow: std::collections::HashMap::new(), reservable_cache: std::collections::HashMap::new(), + scratch_tiles: Vec::new(), + reserved_pool: ReservedPool::new(RESERVED_POOL_MAX), scratch_heaps: Vec::new(), 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 = self.fence.GetCompletedValue(); + 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); + } + } + } + /// 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); @@ -656,10 +1267,11 @@ 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, low_commit: bool) -> Vec { self.sweep(now); - self.pool.drain_cooling(now); - let reclaimed_ids = self.pool.reclaim_empty_heaps(keep_spare_pools(), POOL_PAGES); + self.pool.drain_cooling_before(now, self.cool_bound()); + let keep_spare = if low_commit { 0 } else { keep_spare_pools() }; + let reclaimed_ids = self.pool.reclaim_empty_heaps(keep_spare, 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) { @@ -677,19 +1289,25 @@ impl Pages { dropped } - /// Map every tile of `res` (`tiles[i]`: overall tile i) – one call per pool heap. - /// `tiles` for the tiles of `res` from the first one of subresource `sub` on. - unsafe fn map(&mut self, res: &ID3D12Resource, sub: u32, tiles: &[Tile]) { + /// Map every tile of `res` (`tiles[i]`: overall tile i; `None` stays unmapped) – one call + /// per pool heap. `tiles` for the tiles of `res` from the first one of subresource `sub` on. + unsafe fn map(&mut self, res: &ID3D12Resource, sub: u32, tiles: &[Option]) { if tiles.is_empty() { return; } + // a tile left out (None) stays unmapped: a sentinel heap no pool has + self.scratch_tiles.clear(); + self.scratch_tiles.extend(tiles.iter().map(|t| t.unwrap_or((u32::MAX, 0)))); self.scratch_heaps.clear(); - self.scratch_heaps.extend(tiles.iter().map(|t| t.0)); + self.scratch_heaps.extend(self.scratch_tiles.iter().map(|t| t.0).filter(|&h| h != u32::MAX)); + if self.scratch_heaps.is_empty() { + return; + } self.scratch_heaps.sort_unstable(); self.scratch_heaps.dedup(); for i in 0..self.scratch_heaps.len() { let h = self.scratch_heaps[i]; - let ranges = heap_ranges_trimmed(h, tiles); + let ranges = heap_ranges_trimmed(h, &self.scratch_tiles); if ranges.is_empty() { continue; } @@ -705,6 +1323,8 @@ impl Pages { } let coord = D3D12_TILED_RESOURCE_COORDINATE { Subresource: sub, ..Default::default() }; let region = D3D12_TILE_REGION_SIZE { NumTiles: num_tiles, UseBox: false.into(), ..Default::default() }; + let _timer = step(Step::Map); + let flight_t = std::time::Instant::now(); self.queue.UpdateTileMappings( res, 1, @@ -717,9 +1337,9 @@ impl Pages { Some(self.scratch_counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE, ); + super::flight::tile_map("vram", windows::core::Interface::as_raw(&self.queue) as usize, (num_tiles) as u64, flight_t.elapsed()); } - self.value += 1; - let _ = self.queue.Signal(&self.fence, self.value); + self.dirty_signal = true; } /// Unmap every tile of `res` (`D3D12_TILE_RANGE_FLAG_NULL`) so its unshared tiles can return @@ -731,6 +1351,7 @@ impl Pages { let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); let region = D3D12_TILE_REGION_SIZE { NumTiles: total, UseBox: false.into(), ..Default::default() }; let flag = D3D12_TILE_RANGE_FLAG_NULL; + let flight_t = std::time::Instant::now(); self.queue.UpdateTileMappings( res, 1, @@ -743,8 +1364,179 @@ impl Pages { Some(&total), D3D12_TILE_MAPPING_FLAG_NONE, ); - self.value += 1; - let _ = self.queue.Signal(&self.fence, self.value); + super::flight::tile_map("vram", windows::core::Interface::as_raw(&self.queue) as usize, (total) as u64, flight_t.elapsed()); + self.dirty_signal = true; + } + + /// 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; + } + } + } + // Resolve aliased 64 MiB buffers for every touched live heap before borrowing `zero_ring`. + 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()?; + self.queue.ExecuteCommandLists(&[Some(cmd)]); + Ok(()) + }) + .is_ok(); + if ok { + self.value += 1; + let _ = self.queue.Signal(&self.fence, self.value); + super::flight::signaled("vram pages", windows::core::Interface::as_raw(&self.queue) as usize, &self.fence, self.value); + self.dirty_signal = false; + slot.fence_val = self.value; + } + } + + /// Emit one `queue.Signal` covering all batched `map()` / `unmap()` calls since the last flush. + unsafe fn flush_signal(&mut self) { + if self.dirty_signal { + let _timer = step(Step::Signal); + self.value += 1; + let _ = self.queue.Signal(&self.fence, self.value); + super::flight::signaled("vram pages", windows::core::Interface::as_raw(&self.queue) as usize, &self.fence, self.value); + self.dirty_signal = false; + } + } + + /// 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 ranges = update_ranges(total, D3D12_TILE_RANGE_FLAG_NULL, |i| sel(i).then_some(0)); + if ranges.iter().all(|r| r.0 == D3D12_TILE_RANGE_FLAG_SKIP) { + return; + } + let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let region = D3D12_TILE_REGION_SIZE { NumTiles: total, UseBox: false.into(), ..Default::default() }; + let flags: Vec = ranges.iter().map(|r| r.0).collect(); + let offsets: Vec = ranges.iter().map(|r| r.1).collect(); + let counts: Vec = ranges.iter().map(|r| r.2).collect(); + let flight_t = std::time::Instant::now(); + self.queue.UpdateTileMappings( + res, + 1, + Some(&coord), + Some(®ion), + None, + ranges.len() as u32, + Some(flags.as_ptr()), + Some(offsets.as_ptr()), + Some(counts.as_ptr()), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + super::flight::tile_map("vram", windows::core::Interface::as_raw(&self.queue) as usize, (region.NumTiles) as u64, flight_t.elapsed()); + self.dirty_signal = true; + } + + /// 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) { @@ -780,36 +1572,117 @@ 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`). + /// When `follow_key` is `Some`, a page in a graphics reservation the title has no memory at + /// yet is left unmapped (tier 2: reads zero) and mapped when the title puts memory there + /// (`apply_backing`); GPU-owned targets (`RT | DS | UAV`) pass `None` so every tile is backed. + #[allow(clippy::too_many_arguments)] + unsafe fn bind_with_follow( + &mut self, + dev: &ID3D12Device, + res: &ID3D12Resource, + follow_key: Option, + va: usize, + console_bytes: Option, + total: u32, + phys: &[Option], + ) -> Option<(Vec, Vec<(usize, usize)>, Vec)> { + self.bind_range(dev, res, follow_key, va, console_bytes, total, 0, 0..total as usize, phys) + } + + #[cfg(test)] + unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, key: usize, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>, Vec)> { + self.bind_with_follow(dev, res, Some(key), va, console_bytes, total, &[]) } /// `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, + follow_key: Option, + va: usize, + console_bytes: Option, + total: u32, + sub: u32, + range: std::ops::Range, + phys: &[Option], + ) -> Option<(Vec, Vec<(usize, usize)>, Vec)> { + #[cfg(test)] + if FAIL_LEVEL_BIND_FOR_TEST.with(|failure| { + if failure.get() != Some((res.as_raw() as usize, sub)) { + return false; + } + failure.take(); + true + }) { + return None; + } let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); + let timer = step(Step::Sweep); self.sweep(now); + drop(timer); + + enum TilePlan { + FollowSkip(usize), + Own { addr: usize, key: usize, follow: bool }, + Extra(usize, usize), + } + let check_res = follow_key.is_some() + && own > 0 + && crate::hle::kernelx::overlaps_graphics_reservation(first, own.saturating_mul(PAGE)); + let mut res_bounds: Option<(usize, usize)> = None; + let mut backed_run = BackedRun::default(); + + let mut plan = Vec::with_capacity(range.len()); let mut missing = 0usize; 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) + if i < own { + let a = first + i * PAGE; + let key = page_key(a, phys.get(i).copied().flatten()); + let in_res = if check_res { + if res_bounds.is_none_or(|(lo, hi)| a < lo || a >= hi) { + res_bounds = crate::hle::kernelx::graphics_reservation_bounds(a); + } + res_bounds.is_some_and(|(lo, hi)| a >= lo && a < hi) + } else { + false + }; + if in_res { + let shared = self.pages.get(&key).is_some_and(|p| p.users > 0); + let already_mapped = self.follow.get(&a).is_some_and(|f| f.mapped); + if !(already_mapped || shared || title_backed_in(a, &mut backed_run)) { + plan.push(TilePlan::FollowSkip(a)); + continue; + } + } + match self.pages.get(&key).map(|p| p.tile.0) { + Some(h) if preferred.is_none() => preferred = Some(h), + Some(_) => {} + None => missing += 1, + } + plan.push(TilePlan::Own { addr: a, key, follow: in_res }); } else { - self.extra_pages.get(&(va, i)).map(|p| p.tile.0) - }; - match existing { - Some(h) if preferred.is_none() => preferred = Some(h), - Some(_) => {} - None => missing += 1, + match self.extra_pages.get(&(va, i)).map(|p| p.tile.0) { + Some(h) if preferred.is_none() => preferred = Some(h), + Some(_) => {} + None => missing += 1, + } + plan.push(TilePlan::Extra(va, i)); } } + 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_fenced_recycled(missing, preferred, now, safe_before, POOL_PAGES, pending_zero, || { + let _timer = step(Step::Heap); let heap = alloc_pool_heap(dev)?; Some(pools.push_heap(heap)) })?; @@ -818,44 +1691,208 @@ impl Pages { let mut tiles = Vec::with_capacity(range.len()); let mut used = Vec::with_capacity(own.min(range.len())); 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 mut follows = Vec::new(); + for (i, slot) in range.zip(plan) { + match slot { + TilePlan::FollowSkip(a) => { + follows.push(a); + if let Some(key) = follow_key { + self.follow.entry(a).or_insert(Follow { users: Vec::new(), mapped: false }).users.push((key, i as u32)); + } + tiles.push(None); + } + TilePlan::Own { addr: a, key, follow } => { + if follow { + follows.push(a); + if let Some(fkey) = follow_key { + let f = self.follow.entry(a).or_insert(Follow { users: Vec::new(), mapped: false }); + f.users.push((fkey, i as u32)); + f.mapped = true; + } + } + let t = match self.pages.get_mut(&key) { + Some(p) => { + p.users += 1; + p.idle_since = None; + p.tile + } + None => { + let t = fresh_iter.next().unwrap(); + self.pages.insert(key, Page { tile: t, users: 1, idle_since: None }); + t + } + }; + used.push(key); + tiles.push(Some(t)); + } + TilePlan::Extra(va, idx) => { + let k = (va, idx); + let t = match self.extra_pages.get_mut(&k) { + Some(p) => { + p.users += 1; + p.idle_since = None; + p.tile + } + None => { + let t = fresh_iter.next().unwrap(); + self.extra_pages.insert(k, Page { tile: t, users: 1, idle_since: None }); + t + } + }; + used_extra.push(k); + tiles.push(Some(t)); + } + } + } + self.map(res, sub, &tiles); + if self.pending_zero_tiles.len() >= 256 { + self.flush_zero_tiles(dev); + } + Some((used, used_extra, follows)) + } + + /// Texture `key` no longer at its followed pages `addrs`. + fn unfollow(&mut self, key: usize, addrs: &[usize]) { + for a in addrs { + if let Some(f) = self.follow.get_mut(a) { + f.users.retain(|u| u.0 != key); + if f.users.is_empty() { + self.follow.remove(a); + } + } + } + } + + /// The followed pages in `ranges` mapped where the title has memory now and unmapped where + /// it has none (their video memory idle, reused if the title maps there again within + /// `IDLE`): one UpdateTileMappings per texture and heap; caller flushes the batched signal. + unsafe fn apply_backing(&mut self, dev: &ID3D12Device, ranges: &[(usize, usize)]) { + let mut addrs: Vec = Vec::new(); + for &(a, n) in ranges { + let mut p = a & !(PAGE - 1); + let end = a.saturating_add(n); + while p < end { + if self.follow.contains_key(&p) { + addrs.push(p); + } + match p.checked_add(PAGE) { + Some(next) => p = next, + None => break, + } + } + } + if addrs.is_empty() { + return; + } + addrs.sort_unstable(); + addrs.dedup(); + let now = std::time::Instant::now(); + let safe_before = self.cool_bound(); + let mut backed_run = BackedRun::default(); + // texture → (tile, its new page) for immediate maps + let mut map_changes: std::collections::HashMap> = std::collections::HashMap::new(); + // texture → (tile, page_addr) for deferred NULL unmaps (gated behind live device queues) + let mut unmap_changes: std::collections::HashMap> = std::collections::HashMap::new(); + for a in addrs { + let Some(mapped) = self.follow.get(&a).map(|f| f.mapped) else { continue }; + let backed = title_backed_in(a, &mut backed_run); + if backed == mapped { + continue; + } + let users = self.follow[&a].users.clone(); + if backed { + if !users.iter().any(|&(k, _)| self.targets.get(&k).is_some_and(|t| t.mapped)) { + continue; + } + let tile = match self.pages.get_mut(&a) { Some(p) => { - p.users += 1; p.idle_since = None; p.tile } None => { - let t = fresh_iter.next().unwrap(); - self.pages.insert(a, Page { tile: t, users: 1, idle_since: None }); + let pools = &mut self.pools; + let pool = &mut self.pool; + let pending_zero = &mut self.pending_zero_tiles; + let Some(mut fresh) = pool.take_batch_fenced_recycled(1, None, now, safe_before, POOL_PAGES, pending_zero, || { + let _timer = step(Step::Heap); + let heap = alloc_pool_heap(dev)?; + Some(pools.push_heap(heap)) + }) else { + continue; + }; + let t = fresh.pop().unwrap(); + self.pages.insert(a, Page { tile: t, users: 0, idle_since: None }); t } }; - used.push(a); - t - } else { - let k = (va, i); - let t = match self.extra_pages.get_mut(&k) { - Some(p) => { - p.users += 1; - p.idle_since = None; - p.tile + for &(k, i) in &users { + if let Some(t) = self.targets.get_mut(&k).filter(|t| t.mapped) { + t.used.push(a); + self.pages.get_mut(&a).unwrap().users += 1; + map_changes.entry(k).or_default().push((i, tile)); } - None => { - let t = fresh_iter.next().unwrap(); - self.extra_pages.insert(k, Page { tile: t, users: 1, idle_since: None }); - t + } + } else { + for &(k, i) in &users { + if let Some(t) = self.targets.get_mut(&k).filter(|t| t.mapped) { + if let Some(at) = t.used.iter().position(|&u| u == a) { + t.used.swap_remove(at); + self.release_tiles(vec![a], Vec::new(), now, false); + } + unmap_changes.entry(k).or_default().push((i, a)); } - }; - used_extra.push(k); - t - }; - tiles.push(tile); + } + } + if let Some(f) = self.follow.get_mut(&a) { + f.mapped = backed; + } } - self.map(res, sub, &tiles); - Some((used, used_extra)) + for (k, pairs) in unmap_changes { + let Some(total) = self.targets.get(&k).map(|t| t.total) else { continue }; + let raw = k as *mut c_void; + let Some(res) = ID3D12Resource::from_raw_borrowed(&raw) else { continue }; + self.unsealed_unmaps.push(PendingUnmapOp::Tiles { + res: res.clone(), + key: k, + total, + pairs, + }); + } + if map_changes.is_empty() { + return; + } + for (k, tiles) in map_changes { + let Some(total) = self.targets.get(&k).map(|t| t.total) else { continue }; + let raw = k as *mut c_void; + let Some(res) = ID3D12Resource::from_raw_borrowed(&raw) else { continue }; + let at: std::collections::HashMap = tiles.into_iter().collect(); + let mut heaps: Vec = at.values().map(|t| t.0).collect(); + heaps.sort_unstable(); + heaps.dedup(); + for h in heaps { + let ranges = update_ranges(total, D3D12_TILE_RANGE_FLAG_NONE, |i| at.get(&i).copied().filter(|t| t.0 == h).map(|t| t.1)); + let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let region = D3D12_TILE_REGION_SIZE { NumTiles: total, UseBox: false.into(), ..Default::default() }; + let flags: Vec = ranges.iter().map(|r| r.0).collect(); + let offsets: Vec = ranges.iter().map(|r| r.1).collect(); + let counts: Vec = ranges.iter().map(|r| r.2).collect(); + let flight_t = std::time::Instant::now(); + self.queue.UpdateTileMappings( + res, + 1, + Some(&coord), + Some(®ion), + &self.pools[h as usize], + ranges.len() as u32, + Some(flags.as_ptr()), + Some(offsets.as_ptr()), + Some(counts.as_ptr()), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + super::flight::tile_map("vram", windows::core::Interface::as_raw(&self.queue) as usize, (total) as u64, flight_t.elapsed()); + } + } + self.dirty_signal = true; } } @@ -943,6 +1980,30 @@ 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. @@ -960,13 +2021,16 @@ unsafe fn place_on_pages( riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void, ) -> Option { + let timer = step(Step::Va); let va = canonical_va(va); + drop(timer); if desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN || desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D { return None; } 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); @@ -976,44 +2040,118 @@ 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 timer = step(Step::Lock); let mut g = PAGES.lock().unwrap(); + drop(timer); 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"); return None; } - // 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; - } + let mut cached_tiling: Option<(u32, Option)> = None; + let hr = if let Some((pooled_raw, cached_total, cached_levels)) = pooled { + type QiFn = unsafe extern "system" fn(*mut c_void, *const windows_sys::core::GUID, *mut *mut c_void) -> HRESULT; + let ptr = pooled_raw as *mut c_void; + let qi: QiFn = if super::real::is_adopted(ptr) { + std::mem::transmute(super::real::orig_fn(ptr, 0)) + } else { + std::mem::transmute(*(*(ptr as *const *const usize))) + }; + let hr = qi(ptr, riid, ppv); + release_raw_com(pooled_raw); + if hr >= 0 && !(*ppv).is_null() { + super::real::note_reserved(hr, ppv); + static REUSED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let h = REUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if h.is_power_of_two() && h >= 16 { + crate::xlog_info!("D3D12.X: reserved texture pool: {h} reused (skipped CreateReservedResource)"); + } + cached_tiling = Some((cached_total, cached_levels)); + hr + } else { + let timer = step(Step::Reserved); + let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, ppv); + drop(timer); + if hr < 0 || (*ppv).is_null() { + log(&format!("{hr:#x}")); + return None; + } + hr + } + } else { + // 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 timer = step(Step::Reserved); + let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, ppv); + drop(timer); + if hr < 0 || (*ppv).is_null() { + log(&format!("{hr:#x}")); + return None; + } + hr + }; let raw = *ppv; + if super::real::dred_on() { + super::real::name_resource( + raw, + &format!( + "xcl vram tex va={va:#x} {}x{}x{} m={} fmt={} fl={:#x} lazy={}", + desc.Width, desc.Height, desc.DepthOrArraySize, desc.MipLevels, desc.Format.0, desc.Flags.0, lazy + ), + ); + } let res = ID3D12Resource::from_raw_borrowed(&raw)?; let mut total = 0u32; - let levels = if lazy { - 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 { - dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); - None + let levels = match cached_tiling { + Some((cached_total, _)) if !lazy => { + total = cached_total; + None + } + Some((cached_total, Some(mut cached_levels))) => { + total = cached_total; + cached_levels.groups.iter_mut().for_each(|g| g.3 = false); + Some(cached_levels).filter(|_| total > 0 && owned_pages(va, console_bytes, total as usize).is_some()) + } + _ => { + let timer = step(Step::Tiling); + let lv = if lazy { + 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 { + dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + None + }; + drop(timer); + lv + } }; + let follow_backing = !require_aligned; let bound = { + let timer = step(Step::Lock); let mut g = PAGES.lock().unwrap(); + drop(timer); if let Some(Some(pages)) = g.get_mut(&dev_key) { if levels.is_some() { // 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(), follows: Vec::new(), follow_backing, levels, recycle: recycle_key, 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, follows)) = pages.bind_with_follow(dev, res, follow_backing.then_some(raw as usize), va, console_bytes, total, &phys) { + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used, used_extra, follows, follow_backing, levels: None, recycle: recycle_key, gpu_owned: require_aligned }); true } else { false @@ -1027,32 +2165,57 @@ unsafe fn place_on_pages( *ppv = std::ptr::null_mut(); return None; } - PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); + PLACED_TEXTURES.write().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); 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) { 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 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); + let follows = std::mem::take(&mut t.follows); + 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 = pages.release_tiles_unshared(used, used_extra); + pages.unfollow(key, &follows); + pages.unsealed_unmaps.push(PendingUnmapOp::Whole { + res: res.clone(), + key, + gen, + total, + tiles: unshared, + }); + hit = Some(dev_key); + break; } - 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); + 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, true); - return; } } @@ -1064,46 +2227,72 @@ 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.follow_backing, 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, follow_backing, _)) = 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, follows)) = pages.bind_with_follow(&dev, res, follow_backing.then_some(key), 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.follows = follows; t.mapped = true; + t.mapping_gen = t.mapping_gen.wrapping_add(1); } true } /// 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 { + let mapped_level_tiles = t.levels.as_ref().map(|l| l.mapped_tiles()); + if let Some(mapped) = mapped_level_tiles { 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); + LEVEL_STATS[2].fetch_sub(mapped, std::sync::atomic::Ordering::Relaxed); } + let was_mapped = t.mapped && mapped_level_tiles.is_none_or(|m| m > 0); if t.mapped { pages.release_tiles(t.used, t.used_extra, now, false); } - return; + pages.unfollow(resource, &t.follows); + return (held && reserved_pool_enabled()) + .then(|| { + t.recycle.map(|key| { + let levels = t.levels.map(|mut l| { + l.groups.iter_mut().for_each(|g| g.3 = false); + l + }); + RecycleInfo { dev_key, key, total: t.total, was_mapped, levels } + }) + }) + .flatten(); } + None } /// Reclaimed heaps waiting for `unmap_mark` (if any) and every live queue's fence mark on one device. @@ -1115,6 +2304,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 { @@ -1188,6 +2403,112 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla }; } +/// 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 tiles), and drop popped COM resource references outside `PAGES.lock()`. +unsafe fn seal_and_drain_unmaps(dev: &ID3D12Device, dev_key: usize, extra_queue: Option<&ID3D12CommandQueue>) { + let (need_seal_unmaps, need_cool_probe, has_pending_or_probe) = { + let g = PAGES.lock().unwrap(); + let Some(Some(pages)) = g.get(&dev_key) else { return }; + let need_unmaps = !pages.unsealed_unmaps.is_empty(); + 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(); + (need_unmaps, need_probe, has_waiters) + }; + 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 { return }; + if !pages.unsealed_unmaps.is_empty() { + let ops = std::mem::take(&mut pages.unsealed_unmaps); + pages.pending_unmaps.push_back(PendingUnmapBatch { ops, marks: marks.clone() }); + } + 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)| f.GetCompletedValue() >= *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| f.GetCompletedValue()); + 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); + } + PendingUnmapOp::Tiles { res, key, total, pairs } => { + if pages.targets.get(&key).is_some_and(|t| t.mapped) { + let still_unbacked: HashSet = pairs + .into_iter() + .filter(|&(_, addr)| pages.follow.get(&addr).is_none_or(|f| !f.mapped)) + .map(|(tile_idx, _)| tile_idx) + .collect(); + if !still_unbacked.is_empty() { + pages.unmap_selected(&res, total, |i| still_unbacked.contains(&i)); + } + } + drop_outside.push(res); + } + } + } + if !newly_fenced_tiles.is_empty() { + pages.flush_signal(); + 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 @@ -1202,26 +2523,54 @@ 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; + // the page mappings this queue waits for, waited on the CPU after the lock (as the sparse + // windows' are: `sparse::cpu_waited_for_mappings`) + 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(); + let changed = std::mem::take(&mut *BACKING.lock().unwrap()); + if !changed.is_empty() && !pages.follow.is_empty() { + pages.apply_backing(&dev, &changed); + } + pages.flush_zero_tiles(&dev); + pages.flush_signal(); 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) { + let low_commit = commit_low(); + let reclaim_interval = if low_commit { std::time::Duration::from_millis(250) } else { std::time::Duration::from_secs(1) }; + if now.duration_since(pages.last_reclaim) >= reclaim_interval { pages.last_reclaim = now; do_reclaim = true; - newly_reclaimed = pages.sweep_and_reclaim(now); + newly_reclaimed = pages.sweep_and_reclaim(now, low_commit); if !newly_reclaimed.is_empty() { + pages.flush_signal(); 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)); } @@ -1233,6 +2582,37 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { #[cfg(test)] pub(super) static VRAM_TEST_LOCK: Mutex<()> = Mutex::new(()); +/// A tile mapping on `dev`'s page queue, as `map` leaves it (the fence advanced and signalled +/// there): the value a queue must wait for before work that uses the pages. None: no pages on +/// this device (no tiled resources). +#[cfg(test)] +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; + pages.queue.Signal(&pages.fence, pages.value).ok()?; + pages.dirty_signal = false; + Some(pages.value) +} + +/// The page mapping value `queue` was last made to wait for on `dev` (`before_execute`). +#[cfg(test)] +pub(super) fn waited_for_test(dev: usize, queue: usize) -> u64 { + let g = PAGES.lock().unwrap(); + g.get(&dev).and_then(|p| p.as_ref()).and_then(|p| p.waited.get(&queue).copied()).unwrap_or(0) +} + +/// 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))) +} + /// Tile identities of one mapped resource: title pages, then extra pages. /// A device-wide byte count also falls when unrelated idle pages are swept. #[cfg(test)] @@ -1250,9 +2630,41 @@ 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 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 (su, sp) = super::vram_small::bytes_for(device); + let mut g = PAGES.lock().unwrap(); + let Some(Some(p)) = g.get_mut(&device) else { return (su, sp) }; + p.sweep(std::time::Instant::now()); + ((p.pages.len() + p.extra_pages.len()) * PAGE + su, p.pools.len() * POOL_PAGES as usize * PAGE + sp) +} + +#[cfg(test)] +pub(super) fn extra_page_bytes_for(device: usize) -> usize { + let mut g = PAGES.lock().unwrap(); + let Some(Some(p)) = g.get_mut(&device) else { return 0 }; + p.sweep(std::time::Instant::now()); + p.extra_pages.len() * PAGE +} + +/// 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. @@ -1268,10 +2680,19 @@ pub(super) fn tile_mappings_for(device: usize, resource: usize) -> Option<(Vec<( (used.len() + extra.len() == target.total as usize).then_some((used, extra)) } +/// Pool tiles of `device` that are neither free, cooling, nor any page's (taken and lost). +#[cfg(test)] +pub(super) fn tiles_unaccounted_for(device: usize) -> usize { + let g = PAGES.lock().unwrap(); + let Some(Some(p)) = g.get(&device) else { return 0 }; + (p.pools.len() * POOL_PAGES as usize).saturating_sub(p.pool.free_total + p.pool.cooling.len() + p.pages.len() + p.extra_pages.len()) +} + /// (bytes of pages in use by tiled textures, bytes of pool heaps) – `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) }) } @@ -1282,9 +2703,24 @@ 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). +/// the console) backed by shared 4 KiB small-resource heaps (when < 64 KiB and not aliasing an +/// existing 64 KiB GPU page) or shared 64 KiB video-memory pages; None when neither applies (the +/// caller falls back to a committed resource). #[allow(clippy::too_many_arguments)] pub unsafe fn place_pages( this: *mut c_void, @@ -1303,40 +2739,60 @@ pub unsafe fn place_pages( if console_has_packed_3d_mips(desc) { return None; } + 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.write().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); place_on_pages(dev, this, va, desc, state, clear, console_bytes, false, lazy, riid, ppv) } -/// The levels `levels` of `res` (None: all of them) get their pages if they have none yet: a -/// texture placed with lazy levels (any other: nothing to do). Returns the levels that got pages -/// by this call - the queue the texture is used on next has to wait for that (`before_execute`), -/// and what the pages held before is another texture's. -pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> Vec { +/// Give the requested levels of a lazy texture pages (None: all levels). Returns whether every +/// requested level has pages. Other textures have nothing to map. The queue that uses the +/// texture waits for the mappings in `before_execute`. +pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> bool { + if levels.is_some_and(|levels| levels.is_empty()) { + return true; + } let key = res.as_raw() as usize; let mut g = PAGES.lock().unwrap(); for (&dev_key, pages) in g.iter_mut() { let Some(pages) = pages.as_mut() else { continue }; let Some(t) = pages.targets.get(&key) else { continue }; - let Some(lv) = t.levels.as_ref().filter(|_| t.mapped) else { return Vec::new() }; + let Some(lv) = t.levels.as_ref() else { return true }; + if !t.mapped { + return false; + } let mut wanted: Vec = match levels { Some(l) => l.iter().map(|&x| lv.group_of(x)).collect(), None => (0..lv.groups.len()).collect(), }; wanted.sort_unstable(); wanted.dedup(); - let todo: Vec<(usize, u32, u32, u32, std::ops::Range)> = - wanted.into_iter().filter(|&k| !lv.groups[k].3).map(|k| (k, lv.groups[k].0, lv.groups[k].1, lv.groups[k].2, lv.levels_of(k))).collect(); + let todo: Vec<(usize, u32, u32, u32)> = wanted + .into_iter() + .filter_map(|k| { + let (_, first, count, mapped) = lv.groups[k]; + (!mapped).then(|| (k, lv.levels_of(k).start, first, count)) + }) + .collect(); if todo.is_empty() { - return Vec::new(); + return true; } let (va, console_bytes, total) = (t.va, t.console_bytes, t.total); let d = dev_key as *mut c_void; - 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(t) = pages.targets.get_mut(&key) else { return fresh }; + let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { return false }; + let mut complete = true; + for (k, sub, first, n) in todo { + let Some((used, used_extra, _)) = pages.bind_range(dev, res, None, va, console_bytes, total, sub, first as usize..(first + n) as usize, &[]) else { + complete = false; + continue; + }; + let Some(t) = pages.targets.get_mut(&key) else { return false }; t.used.extend(used); t.used_extra.extend(used_extra); if let Some(l) = t.levels.as_mut() { @@ -1348,11 +2804,10 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> let (textures, stand, mapped, _) = level_stats(); crate::xlog_info!("D3D12.X: level pages: {textures} textures standing for {} MB have pages for {} MB ({groups} levels given pages so far)", stand >> 4, mapped >> 4); } - fresh.extend(levels); } - return fresh; + return complete; } - Vec::new() + true } /// Whether `resource` is a texture whose levels get their pages one by one (`map_levels`). @@ -1380,6 +2835,60 @@ fn console_has_packed_3d_mips(desc: &D3D12_RESOURCE_DESC) -> bool { .unwrap_or(false) } +fn volume_texel_bytes(f: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT) -> u64 { + use windows::Win32::Graphics::Dxgi::Common::*; + match f { + DXGI_FORMAT_R32G32B32A32_FLOAT + | DXGI_FORMAT_R32G32B32A32_UINT + | DXGI_FORMAT_R32G32B32A32_SINT + | DXGI_FORMAT_R32G32B32A32_TYPELESS => 16, + DXGI_FORMAT_R16G16B16A16_FLOAT + | DXGI_FORMAT_R16G16B16A16_UNORM + | DXGI_FORMAT_R16G16B16A16_UINT + | DXGI_FORMAT_R16G16B16A16_SNORM + | DXGI_FORMAT_R16G16B16A16_SINT + | DXGI_FORMAT_R16G16B16A16_TYPELESS + | DXGI_FORMAT_R32G32_FLOAT + | DXGI_FORMAT_R32G32_UINT + | DXGI_FORMAT_R32G32_SINT + | DXGI_FORMAT_R32G32_TYPELESS + | DXGI_FORMAT_D32_FLOAT_S8X24_UINT + | DXGI_FORMAT_R32G8X24_TYPELESS => 8, + DXGI_FORMAT_R8G8_UNORM + | DXGI_FORMAT_R8G8_UINT + | DXGI_FORMAT_R8G8_SNORM + | DXGI_FORMAT_R8G8_SINT + | DXGI_FORMAT_R8G8_TYPELESS + | DXGI_FORMAT_R16_FLOAT + | DXGI_FORMAT_R16_UNORM + | DXGI_FORMAT_R16_UINT + | DXGI_FORMAT_R16_SNORM + | DXGI_FORMAT_R16_SINT + | DXGI_FORMAT_R16_TYPELESS + | DXGI_FORMAT_D16_UNORM + | DXGI_FORMAT_B5G6R5_UNORM + | DXGI_FORMAT_B5G5R5A1_UNORM + | DXGI_FORMAT_B4G4R4A4_UNORM => 2, + DXGI_FORMAT_R8_UNORM + | DXGI_FORMAT_R8_UINT + | DXGI_FORMAT_R8_SNORM + | DXGI_FORMAT_R8_SINT + | DXGI_FORMAT_A8_UNORM + | DXGI_FORMAT_R8_TYPELESS => 1, + _ => 4, + } +} + +/// The least a 3D texture of `desc` takes on the console – the texels of its first level, one +/// after the other – for a 3D texture whose size there is not known: the pages it has to itself +/// at its address. None: not a 3D texture. The PC's tiles past those pages are its own +/// (`owned_pages`), not the pages of what the title placed behind it. +fn least_volume_bytes(desc: &D3D12_RESOURCE_DESC) -> Option { + (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) + .then(|| desc.Width * desc.Height as u64 * desc.DepthOrArraySize as u64 * volume_texel_bytes(desc.Format)) + .filter(|&b| b != 0) +} + /// A GPU-owned texture of the title at `va` (`desc`: the PC description, `console_bytes` its /// size on the console): on the title's pages there, else in the arena for that address (None: /// neither – the caller makes a resource of its own). @@ -1390,6 +2899,10 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st if !tier2(dev) { return None; } + // (a 3D render target's size on the console is not modelled: without one, every PC tile of + // it went on the title's pages from `va` on – more of them than the console's texture takes, + // so the last ones were the first pages of the title's next texture) + let console_bytes = console_bytes.or_else(|| least_volume_bytes(desc)); if std::env::var_os("XCL_VRAM_ARENAS").is_none() { if let Some(hr) = place_on_pages(dev, this, va, desc, state, clear, console_bytes, true, false, riid, ppv) { return Some(hr); @@ -1412,7 +2925,7 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st ARENAS.lock().unwrap().release(id, now); return None; } - PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + PLACED_TEXTURES.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); ARENA_OF.lock().unwrap().get_or_insert_with(std::collections::HashMap::new).insert(*ppv as usize, id); Some(hr) } @@ -1759,6 +3272,21 @@ mod tests { } } + /// A followed page's tiles change alone: the rest of the resource is skipped, consecutive + /// heap tiles merge into one range, unmapped ones into a NULL range. + #[test] + fn update_ranges_set_only_the_changed_tiles() { + let (none, null, skip) = (D3D12_TILE_RANGE_FLAG_NONE, D3D12_TILE_RANGE_FLAG_NULL, D3D12_TILE_RANGE_FLAG_SKIP); + let map = |i: u32| match i { + 2 => Some(7), + 3 => Some(8), + 5 => Some(1), + _ => None, + }; + assert_eq!(update_ranges(7, none, map), [(skip, 0, 2), (none, 7, 2), (skip, 0, 1), (none, 1, 1), (skip, 0, 1)]); + assert_eq!(update_ranges(5, null, |i| [0, 1, 4].contains(&i).then_some(0)), [(null, 0, 2), (skip, 0, 2), (null, 0, 1)]); + } + /// Idle pages go back after `IDLE`, and a sweep looks at the queue of idle pages alone: one /// used again stays, one idle again later goes when that is `IDLE` ago, and the sweeps of /// 20 000 placements beside 200 000 pages in use take no time to speak of (a look at every @@ -1843,6 +3371,36 @@ mod tests { } } + /// Title textures placed one behind the other, 512 KiB apart: 3D render targets of 33 texels + /// a side with 8-byte texels, whose size on the console XCL does not model. Each has the pages + /// of its own texels and no page of the next one, however many tiles the PC's texture has + /// (18 here: with all of them on the title's pages, the tenth to the eighteenth were the + /// next texture's first pages, and two such textures wrote over each other). + #[test] + fn a_3d_texture_of_unknown_console_size_keeps_off_the_next_textures_pages() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D, + Width: 33, + Height: 33, + DepthOrArraySize: 33, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_FLOAT, + ..Default::default() + }; + let bytes = least_volume_bytes(&desc); + assert_eq!(bytes, Some(33 * 33 * 33 * 8)); + let (a, b, pc_tiles) = (0x12_31f1_0000usize, 0x12_31f9_0000usize, 18); + let (first_a, n_a) = owned_pages(a, bytes, pc_tiles).unwrap(); + let (first_b, _) = owned_pages(b, bytes, pc_tiles).unwrap(); + assert_eq!((first_a, n_a), (a, 5)); + assert!(first_a + n_a * PAGE <= first_b, "the first texture's pages end before the second's"); + // as it was: every tile on the title's pages + let (_, all) = owned_pages(a, None, pc_tiles).unwrap(); + assert!(a + all * PAGE > b); + // a 2D texture's size is the caller's to know + assert_eq!(least_volume_bytes(&D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, ..desc }), None); + } + /// Reserved only with TILED support, and for MSAA a tiled sample count (#940: the driver /// refused R32G8X24_TYPELESS reserved, at 1 and 4 samples, and the debug layer said so). #[test] @@ -2174,4 +3732,285 @@ mod tests { assert!(new_calls < old_calls); } } + + #[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 lv = Levels::new(&[(0, 3)], Some((3, 1)), 4, 9); + + let mut pool = ReservedPool::new(2); + assert_eq!(pool.push(k_common, 0x1000, 1, None), None); + assert_eq!(pool.push(k_srv, 0x2000, 1, None), 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, lv.clone()), Some(0x1000)); + assert_eq!(pool.take(&k_common), None); + assert_eq!(pool.take(&k_srv), Some((0x2000, 1, None))); + assert_eq!(pool.take(&k_512), Some((0x3000, 4, lv))); + assert_eq!(pool.live, 0); + + // Zero-cap pool immediately returns pushed objects for release. + let mut disabled = ReservedPool::new(0); + assert_eq!(disabled.push(k_common, 0x4000, 1, None), Some(0x4000)); + } + + #[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, raw, 0x2000_0000, Some(total as u64 * PAGE as u64), total).expect("initial bind"); + pages.unmap(borrowed, total); + pages.release_tiles(used1, extra1, std::time::Instant::now(), false); + assert_eq!(pages.reserved_pool.push(key, raw, total, None), None); + + // 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, reused_levels) = pages.reserved_pool.take(&key).expect("recycle hit"); + assert_eq!(reused_raw, raw); + assert_eq!(reused_total, total); + assert_eq!(reused_levels, None); + 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, reused_raw, 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. + pages.value += 1; + let _ = pages.queue.Signal(&pages.fence, pages.value); + let _ = pages.fence.SetEventOnCompletion(pages.value, windows::Win32::Foundation::HANDLE::default()); + drop(ID3D12Resource::from_raw(reused_raw as *mut c_void)); + } + } + + #[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, + }); + // While f2 is still behind, nothing drains. + f1.store(1, Ordering::SeqCst); + assert!(drain_ready_unmap_batches(&mut q, |f| f.load(Ordering::SeqCst)).is_empty()); + assert_eq!(q.len(), 2); + // Once both queues complete, batch 1 drains; batch 2 with failed signal stays held. + 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 tile_pool_cooling_respects_gpu_fence_barrier_across_long_stalls() { + let t0 = 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); + + // Tile 0 cooled at t0 + 1s; Tile 1 cooled at t0 + 2s. + pool.push_cooling(taken[0], t0 + Duration::from_secs(1)); + pool.push_cooling(taken[1], t0 + Duration::from_secs(2)); + + // Simulate an 8-second PSO compile stall where GPU fences only cleared up to t0 + 500ms: + // wall-clock COOL (2s) has long expired, yet neither tile may return to free! + let t_stall = t0 + Duration::from_secs(10); + pool.drain_cooling_before(t_stall, Some(t0 + Duration::from_millis(500))); + assert_eq!(pool.free_total, 0, "cooling tiles must stay held while GPU fence barrier has not passed them"); + + // Once GPU queues pass t0 + 1500ms, only Tile 0 returns; Tile 1 stays held. + pool.drain_cooling_before(t_stall, Some(t0 + Duration::from_millis(1500))); + assert_eq!(pool.free_total, 1); + + // Once GPU queues pass t0 + 2500ms, Tile 1 returns too. + pool.drain_cooling_before(t_stall, Some(t0 + Duration::from_millis(2500))); + assert_eq!(pool.free_total, 2); + } + + #[test] + fn commit_below_floor_enforces_reserve_and_zero_disables() { + const FLOOR: u64 = 4 * 1024 * 1024 * 1024; + assert!(commit_below_floor(Some(FLOOR - 1), FLOOR)); + assert!(!commit_below_floor(Some(FLOOR), FLOOR)); + assert!(!commit_below_floor(Some(FLOOR + 1), FLOOR)); + assert!(!commit_below_floor(None, FLOOR)); + assert!(!commit_below_floor(Some(0), 0)); + } + + #[test] + fn should_use_lazy_levels_skips_gpu_aliased_sampled_textures() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R16_FLOAT, DXGI_SAMPLE_DESC}; + let tex = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1024, + Height: 1024, + DepthOrArraySize: 1, + MipLevels: 10, + Format: DXGI_FORMAT_R16_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + assert!(should_use_lazy_levels(true, false, &tex)); + assert!(!should_use_lazy_levels(true, true, &tex), "sampled view aliasing a live GPU page must map eagerly"); + assert!(!should_use_lazy_levels(false, false, &tex)); + let mut uav = tex; + uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + assert!(!should_use_lazy_levels(true, false, &uav)); + let mut arr = tex; + arr.DepthOrArraySize = 2; + assert!(!should_use_lazy_levels(true, false, &arr)); + } + + #[test] + fn gpu_owned_bind_with_no_follow_maps_uncommitted_graphics_reservation_tiles() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R16_FLOAT, DXGI_SAMPLE_DESC}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + 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"); + }; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + let span = 4 * PAGE; + let va = VirtualAlloc(std::ptr::null(), span, MEM_RESERVE, PAGE_READWRITE) as usize; + assert!(va != 0 && va % PAGE == 0); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R16_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..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()); + assert!(total >= 1 && (total as usize) * PAGE <= span); + + let (used, extra, follows) = pages + .bind_with_follow(&dev, &res, None, va, Some(total as u64 * PAGE as u64), total, &[]) + .expect("GPU-owned bind must map every tile even when title VA is uncommitted"); + assert_eq!(used.len() + extra.len(), total as usize); + assert!(follows.is_empty(), "GPU-owned target must not register FollowSkip entries"); + assert!(pages.follow.is_empty()); + + pages.unmap(&res, total); + pages.flush_signal(); + let _ = pages.fence.SetEventOnCompletion(pages.value, windows::Win32::Foundation::HANDLE::default()); + drop(res); + VirtualFree(va as *mut c_void, 0, MEM_RELEASE); + } + } + + #[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_fenced_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_fenced_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_fenced_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()); + } } 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..e33ec692bd --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/vram_small.rs @@ -0,0 +1,601 @@ +//! 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); + +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 after `COOL`. + cooling: VecDeque<(Block, Instant)>, + /// 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(&mut self, now: Instant) { + 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)); + } + } + } + } + + fn drain_cooling(&mut self, now: Instant) { + while self.cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { + 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(&mut self, key: SlotKey, now: Instant) -> Option<(H, u32)> { + self.sweep_idle(now); + 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(now); + 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(&mut self, heap: H, key: SlotKey, now: Instant) -> (H, u32) { + if let Some(got) = self.try_acquire(key, now) { + 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(key, now) { + 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(&mut self, now: Instant) { + 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)); + } + } + } + } +} + +// 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_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 }; + let batch = vec![ + (a2.clone(), vec![sub(fill_a.clone())], vec![D3D12_RESOURCE_STATE_COMMON]), + (b.clone(), vec![sub(fill_b.clone())], vec![D3D12_RESOURCE_STATE_COMMON]), + ]; + let failed = crate::gpu::texture::upload_batch(&dev, &queue, &batch).unwrap(); + assert!(failed.is_empty(), "upload failed: {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)); + } + } +} diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 2ae4fe1b66..92061b4f18 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -18,7 +18,8 @@ //! * queue: QueryInterface, AddRef, Release, EnqueueRequest, EnqueueStatus(array, index), //! EnqueueSignal(fence, value), Submit, CancelRequestsWithTag(mask, value), Close, //! GetErrorEvent, RetrieveErrorRecord (0x290 bytes), Query (0x1C: the desc, then empty -//! slots u16 @0x18 and requests until the automatic submit u16 @0x1A), then 6 more, +//! slots u16 @0x18 and requests until the automatic submit u16 @0x1A), then the X1 +//! EnqueueSetEvent(handle) method and 5 more, //! * file: QueryInterface, AddRef, Release, Close, GetHandle, 2 unknown, GetId, then 4 more; //! status array: QueryInterface, AddRef, Release, IsComplete(index), GetHResult(index), //! then 5 more. @@ -26,8 +27,9 @@ //! Each queue has a worker thread: submitted requests run in order (file reads through the //! 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. +//! previous one, a signal sets the fence from the CPU, and an event signals a Win32 waiter. +//! Unlisted methods log and answer E_NOTIMPL. BCPack BC2, modes above 7, and the hardware +//! swizzle are refused. #![allow(non_snake_case)] @@ -36,7 +38,7 @@ mod parallel; use std::ffi::c_void; use std::os::windows::fs::FileExt; -use std::os::windows::io::AsRawHandle; +use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; use std::collections::BTreeMap; use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; @@ -45,7 +47,7 @@ use serde::{Deserialize, Serialize}; use windows_sys::core::GUID; use windows_sys::Win32::Foundation::{CloseHandle, DuplicateHandle, DUPLICATE_SAME_ACCESS, HANDLE}; use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; -use windows_sys::Win32::System::Threading::{CreateEventW, GetCurrentProcess, ResetEvent, SetEvent}; +use windows_sys::Win32::System::Threading::{CreateEventW, GetCurrentProcess, ResetEvent, SetEvent, EVENT_MODIFY_STATE}; use crate::util::{HRESULT, S_OK}; @@ -813,7 +815,9 @@ unsafe fn read_own(at: usize, out: *mut u8, len: usize) -> bool { /// Whether `n` bytes at `p` are committed, writable memory. fn writable(p: usize, n: usize) -> bool { let Some(end) = p.checked_add(n) else { return false }; - crate::hle::kernelx::lazy::ensure(p, n); + // (held while the protection is asked: a view of a physical page is not guarded again + // meanwhile; the copy that follows faults into the guard if one is) + let _open = crate::hle::kernelx::lazy::ensure(p, n); if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(p, n)) { return true; } @@ -1033,6 +1037,7 @@ enum Entry { Status(Arc, u32), /// a fence (one reference held) and the value it gets Signal(FenceRef, u64), + SetEvent(OwnedHandle), #[cfg(test)] /// Test-only barrier to hold the worker deterministically while testing submitted-batch cancellation. Gate(Arc), @@ -1196,6 +1201,9 @@ impl QueueInner { Entry::Signal(fence, value) => unsafe { fence.signal(value); }, + Entry::SetEvent(event) => unsafe { + SetEvent(event.as_raw_handle()); + }, #[cfg(test)] Entry::Gate(b) => { b.wait(); @@ -1203,8 +1211,19 @@ impl QueueInner { } } + fn should_auto_submit(entries: &[Entry], capacity: usize) -> bool { + // Heap-backed `DestinationPageArray` batches may still have their physical-page lists + // populated before the title calls `Submit()`: never auto-submit them mid-batch at half + // capacity, only if the queue actually fills. + let has_deferred_pages = entries + .iter() + .any(|e| matches!(e, Entry::Request { dest_pages: Some(_), dest_on_stack: false, .. })); + let limit = if has_deferred_pages { capacity } else { (capacity / 2).max(1) }; + entries.len() >= limit + } + fn enqueue(self: &Arc, e: Entry) { - let n = { + let auto = { let mut p = self.pending.lock().unwrap(); if self.closed.load(Ordering::Acquire) { return; @@ -1215,10 +1234,9 @@ impl QueueInner { } } p.entries.push(e); - p.entries.len() + Self::should_auto_submit(&p.entries, self.capacity) }; - // as on PC: a half-full queue submits by itself - if n >= (self.capacity / 2).max(1) { + if auto { self.submit(); } } @@ -1233,7 +1251,7 @@ impl QueueInner { } fn enqueue_numbered(self: &Arc, entry: impl FnOnce(u64) -> Entry) { - let n = { + let auto = { let mut p = self.pending.lock().unwrap(); if self.closed.load(Ordering::Acquire) { return; @@ -1241,9 +1259,9 @@ impl QueueInner { let seq = p.next_seq; p.next_seq += 1; p.entries.push(entry(seq)); - p.entries.len() + Self::should_auto_submit(&p.entries, self.capacity) }; - if n >= (self.capacity / 2).max(1) { + if auto { self.submit(); } } @@ -1273,6 +1291,7 @@ fn queue_vtbl() -> &'static [usize] { queue_get_error_event as usize, queue_retrieve_error_record as usize, queue_query as usize, + queue_enqueue_set_event as usize, // IDStorageQueueX1 ], 18, ) @@ -1438,6 +1457,19 @@ unsafe extern "system" fn queue_enqueue_signal(p: *mut c_void, fence: *mut c_voi q.enqueue(Entry::Signal(FenceRef(fence as usize), value)); } +unsafe extern "system" fn queue_enqueue_set_event(p: *mut c_void, event: HANDLE) { + let q = queue(p); + if q.closed.load(Ordering::Acquire) || event.is_null() { + return; + } + // Retain a separate handle until the marker reaches the worker or is discarded. + let mut duplicate = std::ptr::null_mut(); + let me = GetCurrentProcess(); + if DuplicateHandle(me, event, me, &mut duplicate, EVENT_MODIFY_STATE, 0, 0) != 0 { + q.enqueue(Entry::SetEvent(OwnedHandle::from_raw_handle(duplicate))); + } +} + unsafe extern "system" fn queue_submit(p: *mut c_void) { let q = queue(p); if !q.closed.load(Ordering::Acquire) { @@ -2862,4 +2894,24 @@ mod tests { status_release(s); } } + + #[test] + fn deferred_page_array_batch_does_not_auto_submit_at_half_capacity() { + let mk = |dest_pages: Option>, dest_on_stack: bool| Entry::Request { + seq: 1, + req: Request::parse(&[0u8; REQUEST_BYTES]), + file: None, + dest_pages, + dest_on_stack, + src_pages: None, + }; + // Regular requests still auto-submit at half capacity (capacity = 4 -> 2). + assert!(QueueInner::should_auto_submit(&[mk(None, false), mk(None, false)], 4)); + // Stack-backed page arrays are already snapshotted at enqueue, so half-capacity stays on. + assert!(QueueInner::should_auto_submit(&[mk(Some(vec![1]), true), mk(None, false)], 4)); + // Heap-backed page arrays wait until Submit() or full capacity. + assert!(!QueueInner::should_auto_submit(&[mk(Some(vec![1]), false), mk(None, false)], 4)); + assert!(!QueueInner::should_auto_submit(&[mk(Some(vec![1]), false), mk(None, false), mk(None, false)], 4)); + assert!(QueueInner::should_auto_submit(&[mk(Some(vec![1]), false), mk(None, false), mk(None, false), mk(None, false)], 4)); + } } diff --git a/crates/xcl/src/hle/dstorage/parallel_tests.rs b/crates/xcl/src/hle/dstorage/parallel_tests.rs index 5d5214e4fb..23632eb1eb 100644 --- a/crates/xcl/src/hle/dstorage/parallel_tests.rs +++ b/crates/xcl/src/hle/dstorage/parallel_tests.rs @@ -2,11 +2,14 @@ use super::super::*; use super::*; use std::io::Write; use std::os::windows::ffi::OsStrExt; +use std::os::windows::io::{FromRawHandle, OwnedHandle}; use std::panic::{self, AssertUnwindSafe}; use std::path::PathBuf; use std::ptr::null_mut; use std::thread; use std::time::{Duration, Instant}; +use windows_sys::Win32::Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT}; +use windows_sys::Win32::System::Threading::WaitForSingleObject; const TIMEOUT: Duration = Duration::from_secs(5); const TEST_BUDGET: usize = 1024 * 1024; @@ -109,11 +112,15 @@ struct TestQueue(*mut c_void); impl TestQueue { fn new(pool: Option>, hook: Option) -> Self { + Self::with_desc(64, &IID_QUEUE, pool, hook) + } + + fn with_desc(capacity: u16, iid: &GUID, pool: Option>, hook: Option) -> Self { let mut desc = [0; 0x18]; - desc[8..10].copy_from_slice(&64u16.to_le_bytes()); + desc[8..10].copy_from_slice(&capacity.to_le_bytes()); let mut raw = null_mut(); assert_eq!( - unsafe { factory_create_queue(null_mut(), desc.as_ptr(), &IID_QUEUE, &mut raw) }, + unsafe { factory_create_queue(null_mut(), desc.as_ptr(), iid, &mut raw) }, S_OK ); let queue = Self(raw); @@ -137,6 +144,14 @@ impl TestQueue { unsafe { queue_enqueue_status(self.0, status.0, slot) }; } + fn enqueue_set_event(&self, event: &OwnedHandle) { + unsafe { + let vtable = *(self.0 as *const *const usize); + let enqueue: unsafe extern "system" fn(*mut c_void, HANDLE) = std::mem::transmute(*vtable.add(12)); + enqueue(self.0, event.as_raw_handle()); + } + } + fn submit(&self) { unsafe { queue_submit(self.0) }; } @@ -262,6 +277,89 @@ fn await_later_preparation(events: &mpsc::Receiver) { } } +fn completion_event() -> OwnedHandle { + let event = unsafe { CreateEventW(null_mut(), 1, 0, null_mut()) }; + assert!(!event.is_null()); + unsafe { OwnedHandle::from_raw_handle(event) } +} + +#[test] +fn completion_event_auto_submits_a_half_full_sequential_queue() { + with_deadline(|| { + let payload = vec![0x7b; 48 * 1024]; + let file = TestFile::compressed(&[&payload]); + let mut output = vec![0x5d; payload.len()]; + let queue = TestQueue::with_desc(6, &IID_QUEUE_X1, None, None); + let status = TestStatus::new(1); + let event = completion_event(); + unsafe { queue.enqueue(&file.request(0, output.as_mut_ptr() as usize, 1)) }; + queue.status(&status, 0); + assert_eq!(unsafe { WaitForSingleObject(event.as_raw_handle(), 0) }, WAIT_TIMEOUT); + queue.enqueue_set_event(&event); + + assert_eq!(unsafe { WaitForSingleObject(event.as_raw_handle(), 2_000) }, WAIT_OBJECT_0); + assert_eq!(status.result(0), S_OK); + assert_eq!(output, payload); + }); +} + +#[test] +fn completion_event_waits_for_parallel_retirement_and_keeps_its_handle() { + with_deadline(|| { + let payload = vec![0x4d; 48 * 1024]; + let file = TestFile::compressed(&[&payload]); + let mut output = vec![0; payload.len()]; + let mut failed = vec![0x72; payload.len()]; + let pool = test_pool(2, TEST_BUDGET); + let (gate, milestones, release) = gated_hook(TestEvent::BeforeDecode(1)); + let last_retired = Arc::new(AtomicU64::new(0)); + let retired = Arc::clone(&last_retired); + let hook = Arc::new(move |event| { + if let TestEvent::Retired(seq) = event { + retired.store(seq, Ordering::Release); + } + gate(event); + }); + let queue = TestQueue::with_desc(64, &IID_QUEUE_X1, Some(pool), Some(hook)); + let status = TestStatus::new(1); + let event = completion_event(); + let observer = event.try_clone().unwrap(); + + let mut short = file.request(0, failed.as_mut_ptr() as usize, 2); + short[0x30..0x34].copy_from_slice(&(file.chunks[0].1 + 1).to_le_bytes()); + unsafe { + queue.enqueue(&file.request(0, output.as_mut_ptr() as usize, 1)); + queue.enqueue(&short); + } + queue.enqueue_set_event(&event); + queue.status(&status, 0); + queue.submit(); + + assert_eq!(receive(&milestones), TestEvent::BeforeDecode(1)); + let early_wait = unsafe { WaitForSingleObject(observer.as_raw_handle(), 0) }; + drop(event); + release.send(()).unwrap(); + assert_eq!(early_wait, WAIT_TIMEOUT); + assert_eq!(unsafe { WaitForSingleObject(observer.as_raw_handle(), 2_000) }, WAIT_OBJECT_0); + assert_eq!(last_retired.load(Ordering::Acquire), 2); + assert_eq!(status.wait(0), E_END_OF_FILE); + assert_eq!(output, payload); + assert!(failed.iter().all(|&byte| byte == 0x72)); + }); +} + +#[test] +fn completion_event_close_discards_the_pending_marker() { + let queue = TestQueue::with_desc(64, &IID_QUEUE_X1, None, None); + let event = completion_event(); + queue.enqueue_set_event(&event); + assert_eq!(queue.inner().pending.lock().unwrap().entries.len(), 1); + unsafe { queue_close(queue.0) }; + + assert!(queue.inner().pending.lock().unwrap().entries.is_empty()); + assert_eq!(unsafe { WaitForSingleObject(event.as_raw_handle(), 0) }, WAIT_TIMEOUT); +} + #[test] fn parallel_out_of_order_completion_retires_fifo() { with_deadline(|| { diff --git a/crates/xcl/src/hle/gameinput.rs b/crates/xcl/src/hle/gameinput.rs index e7983a8929..58aeb5c106 100644 --- a/crates/xcl/src/hle/gameinput.rs +++ b/crates/xcl/src/hle/gameinput.rs @@ -2,20 +2,21 @@ //! //! The title gets the console's GameInput interfaces (the public GameInput.h of the GDK, v0: //! IGameInput, IGameInputDevice, IGameInputReading as COM objects with the methods in that -//! header's order) with one device: a gamepad that is always connected. A reading is the -//! state at the moment it is asked for – the PC's first XInput controller (else a PlayStation -//! controller, `playstation`), and the keyboard -//! while a window of this process has the focus (Enter / Space A, Escape / Backspace B, +//! header's order) with one device: a gamepad that is always connected. Readings sample +//! the PC's first XInput controller (or a PlayStation controller when XInput is absent) and +//! the keyboard while a window of this process has the focus (Enter / Space A, Escape / Backspace B, //! arrows the D-pad, Tab View, P Menu). Windows' own GameInput.dll is not used: its //! interfaces are not the console's and it reads only for a foreground app of its own. //! Device callbacks report the gamepad (at once for a blocking enumeration, from another -//! thread for an asynchronous one); reading callbacks get a reading when the state changes -//! (polled at 250 Hz). Methods not listed log their slot once and fail. +//! thread for an asynchronous one). One poller samples the gamepad about every 4 ms. +//! State changes enter a half-second history and reach the reading callbacks. +//! Methods not listed log their slot once and fail. //! //! `XCL_PRESS_A_AT=s1,s2…`: press A for 200 ms at those seconds after start (tests). #![allow(non_snake_case)] +use std::collections::VecDeque; use std::ffi::c_void; use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, OnceLock}; @@ -28,6 +29,7 @@ use crate::util::{E_NOINTERFACE, E_NOTIMPL, E_POINTER, HRESULT, S_OK}; const GAMEINPUT_E_DEVICE_NOT_FOUND: HRESULT = 0x838A_0002_u32 as i32; const GAMEINPUT_E_READING_NOT_FOUND: HRESULT = 0x838A_0003_u32 as i32; +const GAMEINPUT_E_REFERENCE_READING_TOO_OLD: HRESULT = 0x838A_0004_u32 as i32; // Verified GameInput v0 interface GUIDs (Windows SDK / GDK `GameInput.h`). const IID_IUNKNOWN: GUID = GUID::from_u128(0x00000000_0000_0000_c000_000000000046); @@ -454,8 +456,8 @@ fn input() -> *mut Object { (2, release as usize), (3, get_current_timestamp as usize), (4, get_current_reading as usize), - (5, other_reading as usize), - (6, other_reading as usize), + (5, other_reading:: as usize), + (6, other_reading:: as usize), (7, get_temporal_reading as usize), (8, register_reading_callback as usize), (9, register_device_callback as usize), @@ -513,10 +515,113 @@ fn reading_vtable() -> *const usize { }) as *const usize } -static SEQUENCE: AtomicU64 = AtomicU64::new(0); +/// One owned COM reference, held by the history or a callback dispatch. +struct OwnedReading(*mut Reading); -fn new_reading(state: GamepadState) -> *mut Reading { - Box::into_raw(Box::new(Reading { vtable: reading_vtable(), refs: AtomicU32::new(1), state, sequence: SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1, timestamp: now_us() })) +// SAFETY: a reading is immutable except for its atomic reference count. Its +// vtable has process lifetime, and this owner keeps the allocation alive. +unsafe impl Send for OwnedReading {} + +impl OwnedReading { + fn new(state: GamepadState, sequence: u64, timestamp: u64) -> Self { + Self(Box::into_raw(Box::new(Reading { + vtable: reading_vtable(), + refs: AtomicU32::new(1), + state, + sequence, + timestamp, + }))) + } + + fn reading(&self) -> &Reading { + // SAFETY: this owner holds a reference for at least the lifetime of the borrow. + unsafe { &*self.0 } + } + + fn into_raw(self) -> *mut Reading { + let ptr = self.0; + std::mem::forget(self); + ptr + } +} + +impl Clone for OwnedReading { + fn clone(&self) -> Self { + // SAFETY: self owns a reference. + unsafe { reading_add_ref(self.0) }; + Self(self.0) + } +} + +impl Drop for OwnedReading { + fn drop(&mut self) { + // SAFETY: release the reference owned by self. + unsafe { reading_release(self.0) }; + } +} + +const POLL_INTERVAL_MS: u64 = 4; +const HISTORY_US: u64 = 500_000; +const HISTORY_CAPACITY: usize = (HISTORY_US / (POLL_INTERVAL_MS * 1000)) as usize + 1; + +struct ReadingHistory { + readings: VecDeque, + /// A title can still use the reading preceding the retained window to + /// advance to its immediate successor after a long period of no input. + predecessor: Option, +} + +static HISTORY: Mutex = Mutex::new(ReadingHistory::new()); +static READING_READY: Condvar = Condvar::new(); + +impl ReadingHistory { + const fn new() -> Self { + Self { readings: VecDeque::new(), predecessor: None } + } + + fn prune(&mut self, now: u64) { + while self.readings.len() > 1 + && (self.readings.len() > HISTORY_CAPACITY + || self.readings.front().is_some_and(|r| now.saturating_sub(r.reading().timestamp) > HISTORY_US)) + { + self.predecessor = self.readings.pop_front(); + } + } + + fn sequence(&self) -> u64 { + self.readings.back().map_or(0, |r| r.reading().sequence) + } + + fn record(&mut self, state: GamepadState, now: u64) -> bool { + let changed = self.readings.back().is_none_or(|r| r.reading().state != state); + if changed { + let reading = OwnedReading::new(state, self.sequence() + 1, now); + self.readings.push_back(reading); + } + self.prune(now); + changed + } + + fn next_after(&self, sequence: u64) -> Option { + self.readings.iter().find(|r| r.reading().sequence > sequence).cloned() + } + + fn adjacent(&mut self, reference: *mut Reading, now: u64) -> Result { + self.prune(now); + let Some(index) = self.readings.iter().position(|r| r.0 == reference) else { + if NEXT && self.predecessor.as_ref().is_some_and(|r| r.0 == reference) { + return self + .readings + .front() + .filter(|r| now.saturating_sub(r.reading().timestamp) <= HISTORY_US) + .cloned() + .ok_or(GAMEINPUT_E_REFERENCE_READING_TOO_OLD); + } + return Err(GAMEINPUT_E_REFERENCE_READING_TOO_OLD); + }; + let neighbor = if NEXT { index.checked_add(1) } else { index.checked_sub(1) }; + neighbor.and_then(|i| self.readings.get(i)).cloned().ok_or(GAMEINPUT_E_READING_NOT_FOUND) + } } // ---- shared methods ---- @@ -622,6 +727,23 @@ fn note_query(what: &str, kind: u32) { unsafe extern "system" fn get_current_reading(_this: *mut Object, kind: u32, dev: *mut c_void, out: *mut *mut Reading) -> HRESULT { note_query("GetCurrentReading", kind); + current_reading(kind, dev, out, || { + let started = start_poller(); + let mut history = HISTORY.lock().unwrap_or_else(|e| e.into_inner()); + // If the worker cannot start, current reads still sample the gamepad. + if !started && history.record(poll(), now_us()) { + READING_READY.notify_one(); + } + history.readings.back().cloned() + }) +} + +unsafe fn current_reading( + kind: u32, + dev: *mut c_void, + out: *mut *mut Reading, + latest: impl FnOnce() -> Option, +) -> HRESULT { if out.is_null() { return E_POINTER; } @@ -629,17 +751,50 @@ unsafe extern "system" fn get_current_reading(_this: *mut Object, kind: u32, dev if kind & KINDS == 0 || !ours(dev) { return GAMEINPUT_E_READING_NOT_FOUND; } - *out = new_reading(poll()); + let Some(reading) = latest() else { + return GAMEINPUT_E_READING_NOT_FOUND; + }; + *out = reading.into_raw(); S_OK } -/// the readings before and after one are not kept -unsafe extern "system" fn other_reading(_this: *mut Object, _reference: *mut c_void, kind: u32, _dev: *mut c_void, out: *mut *mut Reading) -> HRESULT { +unsafe extern "system" fn other_reading( + _this: *mut Object, + reference: *mut Reading, + kind: u32, + dev: *mut c_void, + out: *mut *mut Reading, +) -> HRESULT { note_query("GetNext/PreviousReading", kind); - if !out.is_null() { - *out = std::ptr::null_mut(); + adjacent_reading::(&HISTORY, reference, kind, dev, out, now_us()) +} + +unsafe fn adjacent_reading( + history: &Mutex, + reference: *mut Reading, + kind: u32, + dev: *mut c_void, + out: *mut *mut Reading, + now: u64, +) -> HRESULT { + if out.is_null() { + return E_POINTER; + } + *out = std::ptr::null_mut(); + if reference.is_null() { + return E_POINTER; + } + if kind & KINDS == 0 || !ours(dev) { + return GAMEINPUT_E_READING_NOT_FOUND; + } + let mut history = history.lock().unwrap_or_else(|e| e.into_inner()); + match history.adjacent::(reference, now) { + Ok(reading) => { + *out = reading.into_raw(); + S_OK + } + Err(hr) => hr, } - GAMEINPUT_E_READING_NOT_FOUND } unsafe extern "system" fn get_temporal_reading(this: *mut Object, _timestamp: u64, dev: *mut c_void, out: *mut *mut Reading) -> HRESULT { @@ -652,7 +807,7 @@ type ReadingCallback = unsafe extern "system" fn(u64, *mut c_void, *mut Reading, type DeviceCallback = unsafe extern "system" fn(u64, *mut c_void, *mut Object, u64, u32, u32); enum CallbackKind { - Reading { ctx: usize, cb: ReadingCallback }, + Reading { ctx: usize, cb: ReadingCallback, after_sequence: u64 }, Device, } @@ -762,14 +917,22 @@ unsafe extern "system" fn register_reading_callback(_this: *mut Object, dev: *mu *token = t; } if let Some(cb) = cb.filter(|_| kind & KINDS != 0 && ours(dev)) { - let entry = Arc::new(CallbackEntry::new(t, CallbackKind::Reading { ctx: context as usize, cb })); - CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()).push(entry); start_poller(); + let history = HISTORY.lock().unwrap_or_else(|e| e.into_inner()); + let after_sequence = history.sequence(); + track_reading_callback(t, context, cb, after_sequence); + start_reading_dispatcher(after_sequence); } S_OK } -fn dispatch_reading_callbacks(s: GamepadState) { +fn track_reading_callback(token: u64, context: *mut c_void, cb: ReadingCallback, after_sequence: u64) { + let entry = Arc::new(CallbackEntry::new(token, CallbackKind::Reading { ctx: context as usize, cb, after_sequence })); + CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()).push(entry); +} + +fn dispatch_reading_callbacks(reading: &OwnedReading, previous: u64) { + let sequence = reading.reading().sequence; let cbs: Vec> = CALLBACKS .lock() .unwrap_or_else(|e| e.into_inner()) @@ -778,38 +941,75 @@ fn dispatch_reading_callbacks(s: GamepadState) { .cloned() .collect(); for entry in cbs { - let CallbackKind::Reading { ctx, cb } = entry.kind else { continue }; + let CallbackKind::Reading { ctx, cb, after_sequence } = entry.kind else { continue }; + if sequence <= after_sequence { + continue; + } let Some(_guard) = entry.try_enter() else { continue }; - let r = new_reading(s); + let overrun = sequence - previous.max(after_sequence) > 1; // SAFETY: `cb` and `ctx` were registered by the caller; `_guard` keeps - // `UnregisterCallback` blocked until `cb` returns so `ctx` stays valid. - unsafe { - cb(entry.token, ctx as *mut c_void, r, false); - reading_release(r); - } + // `UnregisterCallback` blocked until `cb` returns, and reading is borrowed + // from a live owner throughout the call. + unsafe { cb(entry.token, ctx as *mut c_void, reading.0, overrun) }; } } -/// A thread that calls the reading callbacks when the gamepad's state changes. -fn start_poller() { +/// Deliver callbacks in order on a different thread so guest code cannot +/// stall sampling. If the worker falls behind, resume at the oldest retained +/// reading and report the skipped readings through the v0 overrun flag. +fn start_reading_dispatcher(after_sequence: u64) { static STARTED: OnceLock<()> = OnceLock::new(); STARTED.get_or_init(|| { - let _ = std::thread::Builder::new().name("xcl-gameinput".into()).spawn(|| { + let worker = std::thread::Builder::new().name("xcl-gameinput-callback".into()).spawn(move || { crate::eh::arm_current_thread(); - let mut last = GamepadState::default(); + let mut previous = after_sequence; loop { - std::thread::sleep(Duration::from_millis(4)); - let s = poll(); - if s == last { - continue; + let reading = { + let history = HISTORY.lock().unwrap_or_else(|e| e.into_inner()); + let mut history = READING_READY + .wait_while(history, |history| history.sequence() <= previous) + .unwrap_or_else(|e| e.into_inner()); + history.prune(now_us()); + history.next_after(previous) + }; + if let Some(reading) = reading { + dispatch_reading_callbacks(&reading, previous); + previous = reading.reading().sequence; } - last = s; - dispatch_reading_callbacks(s); } }); + if let Err(e) = worker { + crate::xlog_warn!("GameInput: could not start reading callback worker: {e}"); + } }); } +/// One sampler for current, historical and callback reads. In particular, +/// sampling consumes mouse deltas, so the query and worker must not both poll. +fn start_poller() -> bool { + static STARTED: OnceLock = OnceLock::new(); + *STARTED.get_or_init(|| { + // Seed before starting the worker or returning the first current reading. + let initial = poll(); + HISTORY.lock().unwrap_or_else(|e| e.into_inner()).record(initial, now_us()); + let worker = std::thread::Builder::new().name("xcl-gameinput".into()).spawn(|| { + crate::eh::arm_current_thread(); + loop { + std::thread::sleep(Duration::from_millis(POLL_INTERVAL_MS)); + let state = poll(); + if HISTORY.lock().unwrap_or_else(|e| e.into_inner()).record(state, now_us()) { + READING_READY.notify_one(); + } + } + }); + if let Err(e) = worker { + crate::xlog_warn!("GameInput: could not start reading poller: {e}"); + return false; + } + true + }) +} + /// RegisterDeviceCallback(device, kind, status filter, enumeration kind, context, callback, /// &token): the gamepad, connected – at once for a blocking enumeration, from another /// thread for an asynchronous one, not at all without enumeration (it never comes or goes) @@ -1014,18 +1214,133 @@ mod tests { #[test] fn readings_come_and_go() { unsafe { - let g = input(); + let reading = OwnedReading::new(GamepadState { buttons: A, ..Default::default() }, 1, 1); let mut r = std::ptr::null_mut(); - assert_eq!(get_current_reading(g, KIND_GAMEPAD, std::ptr::null_mut(), &mut r), S_OK); - let mut s = GamepadState { buttons: 99, ..Default::default() }; + assert_eq!(current_reading(KIND_GAMEPAD, std::ptr::null_mut(), &mut r, || Some(reading.clone())), S_OK); + assert_eq!(r, reading.0); + let mut s = GamepadState::default(); assert!(reading_gamepad(r, &mut s)); - assert_ne!(s.buttons, 99); + assert_eq!(s.buttons, A); let mut d = std::ptr::null_mut(); reading_device(r, &mut d); assert_eq!(d, device()); - assert_eq!(reading_release(r), 0); - assert_eq!(get_current_reading(g, 0x10, std::ptr::null_mut(), &mut r), GAMEINPUT_E_READING_NOT_FOUND, "keyboard kind"); + assert_eq!(reading_release(r), 1); + assert_eq!( + current_reading(0x10, std::ptr::null_mut(), &mut r, || panic!("keyboard kind")), + GAMEINPUT_E_READING_NOT_FOUND + ); + assert!(r.is_null()); + } + } + + fn record_test_reading(history: &mut ReadingHistory, buttons: u32, now: u64) -> OwnedReading { + assert!(history.record(GamepadState { buttons, ..Default::default() }, now)); + history.readings.back().unwrap().clone() + } + + #[test] + fn adjacent_readings_preserve_a_tap_after_idle() { + let pressed_at = HISTORY_US + 2; + let now = pressed_at + 3; + let history = Mutex::new(ReadingHistory::new()); + let (neutral, pressed, released) = { + let mut stream = history.lock().unwrap(); + let neutral = record_test_reading(&mut stream, 0, 1); + let pressed = record_test_reading(&mut stream, A, pressed_at); + assert!(!stream.record(pressed.reading().state, pressed_at + 1)); + let released = record_test_reading(&mut stream, 0, pressed_at + 2); + assert_eq!(stream.readings.back().unwrap().0, released.0); + (neutral, pressed, released) + }; + // Use the same out-pointer and filtering path as the IGameInput vtable. + let mut out = std::ptr::null_mut(); + unsafe { + let any_device = std::ptr::null_mut(); + assert_eq!(adjacent_reading::(&history, neutral.0, KIND_GAMEPAD, any_device, &mut out, now), S_OK); + assert_eq!(out, pressed.0); + let mut state = GamepadState::default(); + assert!(reading_gamepad(out, &mut state)); + assert_eq!(state.buttons, A); + assert_eq!(reading_timestamp(out), pressed_at); + assert!(reading_sequence(out, KIND_GAMEPAD) > reading_sequence(neutral.0, KIND_GAMEPAD)); + reading_release(out); + + assert_eq!(adjacent_reading::(&history, pressed.0, KIND_GAMEPAD, any_device, &mut out, now), S_OK); + assert_eq!(out, released.0); + assert!(reading_gamepad(out, &mut state)); + assert_eq!(state.buttons, 0); + reading_release(out); + + let gamepad = device().cast(); + assert_eq!(adjacent_reading::(&history, released.0, KIND_GAMEPAD, gamepad, &mut out, now), S_OK); + assert_eq!(out, pressed.0); + reading_release(out); + + assert_eq!( + adjacent_reading::(&history, released.0, KIND_GAMEPAD, gamepad, &mut out, now), + GAMEINPUT_E_READING_NOT_FOUND + ); + assert!(out.is_null()); + } + } + + #[test] + fn adjacent_readings_check_inputs_and_keep_caller_references_alive() { + use std::ptr::{dangling_mut, null_mut}; + let history = Mutex::new(ReadingHistory::new()); + let (old, latest) = { + let mut stream = history.lock().unwrap(); + let old = record_test_reading(&mut stream, A, 1); + let latest = record_test_reading(&mut stream, 0, HISTORY_US + 1); + (old, latest) + }; + let valid = KIND_GAMEPAD; + let mut out = dangling_mut(); + unsafe { + assert_eq!(adjacent_reading::(&history, old.0, valid, null_mut(), null_mut(), 1), E_POINTER); + assert_eq!(adjacent_reading::(&history, null_mut(), valid, null_mut(), &mut out, 1), E_POINTER); + assert!(out.is_null()); + assert_eq!( + adjacent_reading::(&history, old.0, 0x10, null_mut(), &mut out, 1), + GAMEINPUT_E_READING_NOT_FOUND + ); + assert_eq!( + adjacent_reading::(&history, old.0, valid, dangling_mut::().cast(), &mut out, 1), + GAMEINPUT_E_READING_NOT_FOUND + ); + + // At the retention boundary the old reading is still available. + assert_eq!(adjacent_reading::(&history, latest.0, valid, null_mut(), &mut out, HISTORY_US + 1), S_OK); + assert_eq!(out, old.0); + let caller_ref = out; + drop(old); + assert_eq!( + adjacent_reading::(&history, latest.0, valid, null_mut(), &mut out, HISTORY_US + 2), + GAMEINPUT_E_READING_NOT_FOUND + ); + assert!(out.is_null()); + // The predecessor cannot advance when its successor is also expired, + // even though that successor remains available as the current reading. + assert_eq!( + adjacent_reading::(&history, caller_ref, valid, null_mut(), &mut out, 2 * HISTORY_US + 2), + GAMEINPUT_E_REFERENCE_READING_TOO_OLD + ); + assert!(out.is_null()); + assert_eq!(reading_timestamp(caller_ref), 1); + let mut state = GamepadState::default(); + assert!(reading_gamepad(caller_ref, &mut state)); + assert_eq!(state.buttons, A); + reading_release(caller_ref); + + assert_eq!( + adjacent_reading::(&history, latest.0, valid, null_mut(), &mut out, 3 * HISTORY_US), + GAMEINPUT_E_READING_NOT_FOUND + ); + assert!(out.is_null()); } + let stream = history.lock().unwrap(); + assert_eq!(stream.readings.len(), 1); + assert_eq!(stream.readings.back().unwrap().0, latest.0); } #[test] @@ -1131,7 +1446,7 @@ mod tests { assert_eq!(call_qi(d, &IID_IGAMEINPUT_DEVICE, std::ptr::null_mut()), E_POINTER); // IGameInputReading (refcounted) - let r = new_reading(GamepadState::default()); + let r = OwnedReading::new(GamepadState::default(), 1, now_us()).into_raw(); let rp = r as *mut c_void; out = sentinel; assert_eq!(call_qi(rp, &IID_IUNKNOWN, &mut out), S_OK); @@ -1219,21 +1534,54 @@ mod tests { static READING_CB_TEST_LOCK: Mutex<()> = Mutex::new(()); + // These tests drive dispatch explicitly so no host input changes can + // invoke their callbacks or hold up their synchronization handshake. + fn track_test_reading_callback(context: *mut c_void, cb: ReadingCallback) -> u64 { + let token = TOKENS.fetch_add(1, Ordering::Relaxed) + 1; + track_reading_callback(token, context, cb, 0); + token + } + + fn dispatch_test_reading(buttons: u32) { + let reading = OwnedReading::new(GamepadState { buttons, ..Default::default() }, 1, now_us()); + dispatch_reading_callbacks(&reading, 0); + } + + #[test] + fn callback_history_filters_old_readings_and_reports_overrun() { + let _serial = READING_CB_TEST_LOCK.lock().unwrap(); + unsafe extern "system" fn record_delivery(_token: u64, ctx: *mut c_void, _r: *mut Reading, overrun: bool) { + // SAFETY: the test keeps this counter alive until unregistering. + unsafe { &*ctx.cast::() }.store(if overrun { 2 } else { 1 }, Ordering::Relaxed); + } + let mut history = ReadingHistory::new(); + let initial = record_test_reading(&mut history, 0, 1); + let sequence = history.sequence(); + let delivered = AtomicU32::new(0); + let token = TOKENS.fetch_add(1, Ordering::Relaxed) + 1; + track_reading_callback(token, (&raw const delivered).cast_mut().cast(), record_delivery, sequence); + dispatch_reading_callbacks(&initial, 0); + let delivered_before = delivered.load(Ordering::Relaxed); + + history.record(GamepadState { buttons: A, ..Default::default() }, 2); + let latest = record_test_reading(&mut history, 0, HISTORY_US + 3); + let recovered = history.next_after(sequence).unwrap(); + dispatch_reading_callbacks(&recovered, sequence); + assert!(unsafe { unregister_callback(input(), token, 0) }); + assert_eq!(delivered_before, 0, "pre-registration readings aren't dispatched"); + assert_eq!(recovered.0, latest.0); + assert_eq!(delivered.load(Ordering::Relaxed), 2, "expired unread readings set overrun"); + } + #[test] fn unregister_reading_callback_waits_for_in_flight_and_prevents_uaf() { let _serial = READING_CB_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let gate = Arc::new(CallbackGate::new()); let g = input(); - let mut token = 0u64; - unsafe { - assert_eq!( - register_reading_callback(g, std::ptr::null_mut(), KIND_GAMEPAD, 0.0, Arc::as_ptr(&gate) as *mut c_void, Some(gated_reading_cb), &mut token), - S_OK - ); - } + let token = track_test_reading_callback(Arc::as_ptr(&gate) as *mut c_void, gated_reading_cb); let dispatch_thread = std::thread::spawn(|| { - dispatch_reading_callbacks(GamepadState { buttons: A, ..Default::default() }); + dispatch_test_reading(A); }); gate.wait_entered(); @@ -1259,7 +1607,7 @@ mod tests { // Subsequent dispatches must never invoke the unregistered callback again. let calls_before = gate.calls.load(Ordering::Acquire); - dispatch_reading_callbacks(GamepadState { buttons: B, ..Default::default() }); + dispatch_test_reading(B); assert_eq!(gate.calls.load(Ordering::Acquire), calls_before); } @@ -1268,16 +1616,10 @@ mod tests { let _serial = READING_CB_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let gate = Arc::new(CallbackGate::new()); let g = input(); - let mut token = 0u64; - unsafe { - assert_eq!( - register_reading_callback(g, std::ptr::null_mut(), KIND_GAMEPAD, 0.0, Arc::as_ptr(&gate) as *mut c_void, Some(gated_reading_cb), &mut token), - S_OK - ); - } + let token = track_test_reading_callback(Arc::as_ptr(&gate) as *mut c_void, gated_reading_cb); let dispatch_thread = std::thread::spawn(|| { - dispatch_reading_callbacks(GamepadState { buttons: X, ..Default::default() }); + dispatch_test_reading(X); }); gate.wait_entered(); @@ -1316,21 +1658,13 @@ mod tests { calls: AtomicU32::new(0), unreg_ok: std::sync::atomic::AtomicBool::new(false), }); - let g = input(); - let mut token = 0u64; - unsafe { - assert_eq!( - register_reading_callback(g, std::ptr::null_mut(), KIND_GAMEPAD, 0.0, &*ctx as *const SelfCtx as *mut c_void, Some(self_unreg_cb), &mut token), - S_OK - ); - } - - dispatch_reading_callbacks(GamepadState { buttons: Y, ..Default::default() }); + track_test_reading_callback(&*ctx as *const SelfCtx as *mut c_void, self_unreg_cb); + dispatch_test_reading(Y); assert_eq!(ctx.calls.load(Ordering::Acquire), 1); assert!(ctx.unreg_ok.load(Ordering::Acquire)); // Must not fire again after self-unregister. - dispatch_reading_callbacks(GamepadState { buttons: MENU, ..Default::default() }); + dispatch_test_reading(MENU); assert_eq!(ctx.calls.load(Ordering::Acquire), 1); } diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 4144a1144e..803fa2a354 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -7,7 +7,7 @@ #![allow(non_snake_case)] use std::ffi::c_void; -use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use windows_sys::Win32::Foundation as fnd; use windows_sys::Win32::System::LibraryLoader as ll; @@ -78,6 +78,7 @@ pub fn exports() -> Vec<(&'static str, usize)> { SetThreadpoolAffinityMask, SetThreadAffinityMask, SetThreadGroupAffinity, + SetThreadPriority, QueryProcessorSchedulingStatistics, GetConsoleType, OutputDebugStringA, @@ -109,6 +110,10 @@ pub fn exports() -> Vec<(&'static str, usize)> { pub const MEM_GRAPHICS: u32 = 0x1000_0000; mod placeholders; pub mod lazy; +#[allow(dead_code)] // `replace_with_reservation` and its inverse: not used yet +pub mod sections; +pub mod guards; +pub mod alias; 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; @@ -155,9 +160,49 @@ pub fn graphics_reservations() -> Vec<(usize, usize)> { /// Whether `p` lies in one of the title's graphics reservations. pub fn in_graphics_reservation(p: usize) -> bool { - GRAPHICS_RESERVATIONS.lock().unwrap().range(..=p).next_back().is_some_and(|(&b, &s)| p < b + s) + graphics_reservation_bounds(p).is_some() +} + +/// The `[start, end)` bounds of the graphics reservation containing `p`, if any. +pub fn graphics_reservation_bounds(p: usize) -> Option<(usize, usize)> { + GRAPHICS_RESERVATIONS + .lock() + .unwrap() + .range(..=p) + .next_back() + .and_then(|(&b, &s)| { + let end = b.saturating_add(s); + (p < end).then_some((b, end)) + }) +} + +/// Whether `[start, start + len)` overlaps any graphics reservation. +pub fn overlaps_graphics_reservation(start: usize, len: usize) -> bool { + if len == 0 { + return false; + } + let end = start.saturating_add(len); + let g = GRAPHICS_RESERVATIONS.lock().unwrap(); + if let Some((&b, &s)) = g.range(..=start).next_back() { + if start < b.saturating_add(s) { + return true; + } + } + g.range(start..end).next().is_some() +} + +/// Notify `d3d12x::vram` when a range in a graphics reservation (or a CPU view with GPU views) +/// gains or loses title memory so placed textures there follow it before the next submit. +fn notify_vram_backing(a: usize, n: usize) { + if n > 0 && (overlaps_graphics_reservation(a, n) || !mirrors::gpu_views_of(a).is_empty()) { + crate::hle::d3d12x::vram::title_memory_changed(a, n); + } } +/// Coherent UMA headroom kept for XCL itself (readback heaps; per-draw arguments have their own +/// pool) so title graphics heaps or non-sparse physical-page fallbacks never starve XCL. +const COHERENT_KEEP: usize = 96 << 20; + const MEM_WRITE_WATCH: u32 = 0x20_0000; /// GPU views of the title's CPU memory. A retail game reserves 24 GB of 64 KiB pages twice @@ -213,8 +258,148 @@ pub mod mirrors { pub fn released(base: usize) { let mut s = STATE.lock().unwrap(); s.cpu.retain(|&(b, _)| b != base); - s.gpu.remove(&base); - s.gpu.retain(|_, &mut (_, c)| c != base); + // the GPU views that go with it, and the pages mapped into them + let gone: Vec<(usize, usize)> = s.gpu.iter().filter(|&(&g, &(_, c))| g == base || c == base).map(|(&g, &(n, _))| (g, n)).collect(); + for (g, n) in gone { + s.gpu.remove(&g); + let mut pages = PAGES.lock().unwrap(); + let keys: Vec = pages.range(g..g + n).map(|(&k, _)| k).collect(); + for k in keys { + pages.remove(&k); + } + } + } + + /// Bytes of a page the queue's page-mapping method maps (the console's 64 KiB pages). + pub const PAGE: usize = 0x1_0000; + + /// What a GPU-view page shows after the page-mapping method: the pool page it was given, + /// and the physical page the title had mapped there then (`None`: none). The console maps + /// that physical page, which the title often maps into the CPU view too – XCL keeps its + /// data where it was mapped last (`super::page_now`). + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub struct Shown { + pub pool: usize, + pub page: Option, + } + + /// Pages of GPU views the title pointed somewhere else with the queue's page-mapping + /// method (`CopyPageMappingsBatchX`, `apply_batches`): GPU-view page → what it shows, or + /// `None` for a page left unmapped. A page not listed shows its CPU view (`source`). + static PAGES: Mutex>> = Mutex::new(BTreeMap::new()); + + /// What the page-mapping method put under `va`: `Some(Some(a))` – `va` shows the bytes at + /// `a` (where XCL keeps the physical page now, else the pool page itself), `Some(None)` – + /// nothing (unmapped), `None` – the method never mapped that page. + pub fn mapped_source(va: usize) -> Option> { + let off = va & (PAGE - 1); + let shown = *PAGES.lock().unwrap().get(&(va - off))?; + Some(shown.map(|s| s.page.and_then(super::page_now).unwrap_or(s.pool) + off)) + } + + /// One call of the queue's page-mapping method, `CopyPageMappingsBatchX(count, batches, + /// pool, pool pages, flags)` (queue #29; #31 in the newer layout). `count` batches of 24 + /// bytes – the first destination address (u64), the number of ranges (u32), a pointer to + /// them at +16 – each range three u32: the kind (0: `count` pool pages from `start` on, + /// 1: pool page `start` at each of `count` pages, 2: unmapped, 3: left as they are), + /// `start` and `count`. Pages are 64 KiB; the pool is `pool_pages` of them at `pool`. + /// The layout as VIctory describes it (`crates/victory-gpu/src/queue.rs`, a reference + /// only: no code taken). Only pages of GPU views are recorded (the retail title maps into + /// nothing else). `None` – nothing recorded – when a batch or a range is not readable, a + /// range leaves the pool or has an unknown kind, or the call names over `MOST` pages. + pub unsafe fn apply_batches(count: u32, batches: usize, pool: usize, pool_pages: u32) -> Option { + let changes = decode_batches(count, batches, pool, pool_pages)?; + record(changes) + } + + /// The mappings of one call of the page-mapping method (`apply_batches`), checked whole: + /// (GPU-view page, the pool page it is given or `None`: unmapped), in the call's order. + /// `None` when a batch or a range is not readable, a range leaves the pool or has an unknown + /// kind, or the call names over `MOST` pages. + pub unsafe fn decode_batches(count: u32, batches: usize, pool: usize, pool_pages: u32) -> Option)>> { + const BATCH: usize = 24; + const RANGE: usize = 12; + const MOST: usize = 1 << 20; + let readable = crate::gpu::shader::readable; + let n = count as usize; + if n == 0 { + return Some(Vec::new()); + } + if n > MOST || !readable(batches, n * BATCH) { + return None; + } + // checked whole first, so a bad call records nothing + let mut changes: Vec<(usize, Option)> = Vec::new(); + for b in 0..n { + let p = batches + b * BATCH; + let dest = (p as *const u64).read_unaligned() as usize & !(PAGE - 1); + let ranges_n = ((p + 8) as *const u32).read_unaligned() as usize; + let ranges = ((p + 16) as *const usize).read_unaligned(); + if ranges_n == 0 { + continue; + } + if ranges_n > MOST || !readable(ranges, ranges_n * RANGE) { + return None; + } + let mut at = dest; + for r in 0..ranges_n { + let q = (ranges + r * RANGE) as *const u32; + let (kind, start, len) = (q.read_unaligned(), q.add(1).read_unaligned() as usize, q.add(2).read_unaligned() as usize); + let inside = |k: usize| start.checked_add(k).is_some_and(|e| e <= pool_pages as usize); + if changes.len() + len > MOST || at.checked_add(len * PAGE).is_none() { + return None; + } + match kind { + 0 if inside(len) => changes.extend((0..len).map(|k| (at + k * PAGE, Some(pool + (start + k) * PAGE)))), + 1 if inside(1) => changes.extend((0..len).map(|k| (at + k * PAGE, Some(pool + start * PAGE)))), + 2 => changes.extend((0..len).map(|k| (at + k * PAGE, None))), + 3 => {} + _ => return None, + } + at += len * PAGE; + } + } + Some(changes) + } + + /// `apply_batches`'s record of the decoded mappings. + unsafe fn record(changes: Vec<(usize, Option)>) -> Option { + // the physical page the title has mapped at each pool page: what the console maps + let changes: Vec<(usize, Option)> = { + let away = super::AWAY.lock().unwrap(); + let title = |pool: usize| away.as_ref().and_then(|a| a.title_page(pool)); + changes.into_iter().map(|(va, to)| (va, to.map(|pool| Shown { pool, page: title(pool) }))).collect() + }; + let s = STATE.lock().unwrap(); + let in_view = |va: usize| s.gpu.range(..=va).next_back().is_some_and(|(&g, &(size, _))| va < g + size); + let mut out = Mapped::default(); + let mut pages = PAGES.lock().unwrap(); + for (va, to) in changes { + if !in_view(va) { + out.elsewhere += 1; + continue; + } + match to { + Some(s) => { + out.mapped += 1; + out.physical += s.page.is_some() as u64; + } + None => out.unmapped += 1, + } + pages.insert(va, to); + } + Some(out) + } + + /// What one `apply_batches` call did, in 64 KiB pages. + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] + pub struct Mapped { + pub mapped: u64, + /// of those, pages whose pool page had a physical page the title mapped there + pub physical: u64, + pub unmapped: u64, + /// pages outside any GPU view: not recorded + pub elsewhere: u64, } /// The CPU-view address behind `va` when `va` lies in a GPU view. @@ -244,11 +429,27 @@ const MEM_64K_PAGES: u32 = 0x2040_0000; /// Commit `[a, a + n)` of a sparse window (the title's reservations there) and give it video /// memory (`d3d12x::sparse`). unsafe fn commit_sparse(a: usize, n: usize, p: u32) -> *mut c_void { - let q = mem::VirtualAlloc(a as *const c_void, n, mem::MEM_COMMIT, sanitize_protect(p)); - if !q.is_null() { - crate::hle::d3d12x::sparse::committed(q as usize, n); + crate::hle::d3d12x::sparse::commit_title(a, n, sanitize_protect(p)) +} + +/// A lazy page (`lazy`: the title's memory, committed on the CPU's first touch) reads as the +/// committed read-write memory it is to the title. +unsafe fn lazy_as_committed(mbi: *mut mem::MEMORY_BASIC_INFORMATION) { + let m = &mut *mbi; + if m.State != mem::MEM_RESERVE { + return; + } + let base = m.BaseAddress as usize; + let page = base & !0xFFFF; + if !lazy::is_lazy(page) { + return; + } + let end = lazy::lazy_run_end(page).min(base.saturating_add(m.RegionSize)); + if end > base { + m.State = mem::MEM_COMMIT; + m.Protect = mem::PAGE_READWRITE; + m.RegionSize = end - base; } - q } pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: u32, p: u32) -> *mut c_void { @@ -257,6 +458,21 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: return q; } let uma = crate::gpu::uma::get(); + // physical page aliasing: the title's reservations of 64 KiB pages hold views of its pages, + // so it maps pages there and does not commit memory of its own (a retail title never does) + 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; + } + } // committing inside one of the title's reservations in a sparse window if !addr.is_null() && t & 0x1000 != 0 && uma.is_some_and(|u| u.is_sparse(addr as usize)) { let q = commit_sparse(addr as usize, size, p); @@ -287,7 +503,7 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: crate::gpu::uma::GRAIN }; let rounded = size.max(1).div_ceil(align) * align; - if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc(rounded, align) { + if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc_title(rounded, align) { trace_mem("VirtualAlloc (graphics, sparse VRAM)", 0, rounded, t as u64, p, q); return q as *mut c_void; } @@ -336,8 +552,7 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: let align = if t & 0x2000_0000 != 0 && t & 0x0040_0000 == 0 { 2 << 20 } else { crate::gpu::uma::GRAIN }; // what XCL keeps of the window for itself (readback heaps; its per-draw arguments have // a pool of their own) - const KEEP: usize = 96 << 20; - let fits = u.size().saturating_sub(u.used()) >= size + KEEP; + let fits = u.size().saturating_sub(u.used()) >= size + COHERENT_KEEP; if let Some(q) = fits.then(|| u.alloc(size, align)).flatten() { trace_mem("VirtualAlloc (graphics, coherent window)", 0, size, t as u64, p, q as usize); return q as *mut c_void; @@ -360,6 +575,9 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: } let q = mem::VirtualAlloc(addr, size, sanitize_alloc_type(t), sanitize_protect(p)); trace_mem("VirtualAlloc", addr as usize, size, t as u64, p, q as usize); + if !q.is_null() && t & mem::MEM_COMMIT != 0 { + notify_vram_backing(q as usize, size); + } q } @@ -418,6 +636,14 @@ 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) { + if ok && t & mem::MEM_RELEASE != 0 { + mirrors::released(addr as usize); + } + 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)) { @@ -446,6 +672,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 } }; if n > 0 { + unmap_away_range(a, n); // sparse first: under its lock, so no copy of CPU writes to video memory reads the // pages while they go (the submit thread's copy faulted on them) crate::hle::d3d12x::sparse::decommitted(a, n); @@ -456,22 +683,50 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 if release { u.sparse_release(a); mirrors::released(a); + forget_title_mappings(a, n); } return 1; } if let Some(u) = crate::gpu::uma::get().filter(|u| u.contains(addr as usize)) { + let a = addr as usize; if t & 0x8000 != 0 { - return u.free(addr as usize) as BOOL; + let len = u.allocation_at(a).filter(|&(start, _)| start == a).map(|(_, l)| l); + if let Some(n) = len { + unmap_away_range(a, n); + } + let ok = u.free(a); + if ok { + mirrors::released(a); + if let Some(n) = len { + forget_title_mappings(a, n); + } + } + return ok as BOOL; } if t & 0x4000 != 0 && size > 0 { + unmap_away_range(a, size); std::ptr::write_bytes(addr as *mut u8, 0, size); } return 1; } + let gone = if t & 0x8000 != 0 { + GRAPHICS_RESERVATIONS.lock().unwrap().get(&(addr as usize)).copied().unwrap_or(0) + } else { + size + }; + let notify = gone > 0 && (overlaps_graphics_reservation(addr as usize, gone) || !mirrors::gpu_views_of(addr as usize).is_empty()); + unmap_away_for_plain_free(addr as usize, size, t); let ok = mem::VirtualFree(addr, size, t); - if ok != 0 && t & 0x8000 != 0 && GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)).is_some() { - GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); - mirrors::released(addr as usize); + if ok != 0 && notify { + crate::hle::d3d12x::vram::title_memory_changed(addr as usize, gone); + } + if ok != 0 && t & 0x8000 != 0 { + let released = GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)); + if let Some(len) = released { + GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + mirrors::released(addr as usize); + forget_title_mappings(addr as usize, len); + } } ok } @@ -481,6 +736,7 @@ pub unsafe extern "system" fn VirtualFreeEx(proc_: HANDLE, addr: *mut c_void, si let a = addr as usize; if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(a) || u.contains(a)) || (t & 0x8000 != 0 && in_graphics_reservation(a)) + || alias::in_space(a) { return VirtualFree(addr, size, t); } @@ -493,6 +749,8 @@ pub unsafe extern "system" fn VirtualAllocEx(proc_: HANDLE, addr: *const c_void, } pub unsafe extern "system" fn VirtualProtect(addr: *const c_void, size: usize, p: u32, old: *mut u32) -> BOOL { + // (a lazy page is the title's committed memory: Windows protects committed pages only) + lazy::commit_range(addr as usize, size); mem::VirtualProtect(addr, size, sanitize_protect(p), old) } @@ -569,7 +827,7 @@ pub unsafe extern "system" fn XMemAllocDefault(size: usize, attrs: u64) -> *mut return std::ptr::null_mut(); }; // Graphics memory types live in the sparse VRAM pool (fallback to coherent UMA, then Windows). - if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc(rounded, align) { + if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc_title(rounded, align) { trace_mem("XMemAlloc (graphics, sparse VRAM)", 0, rounded, attrs, 0, q); return q as *mut c_void; } @@ -705,7 +963,11 @@ pub unsafe extern "system" fn VirtualQuery(address: *const c_void, mbi: *mut mem if let Some(n) = query_committed_window(address, mbi, len) { return n; } - mem::VirtualQuery(address, mbi, len) + let n = mem::VirtualQuery(address, mbi, len); + if n != 0 && len >= std::mem::size_of::() { + lazy_as_committed(mbi); + } + n } pub unsafe extern "system" fn VirtualQueryEx(process: HANDLE, address: *const c_void, mbi: *mut mem::MEMORY_BASIC_INFORMATION, len: usize) -> usize { @@ -713,6 +975,11 @@ pub unsafe extern "system" fn VirtualQueryEx(process: HANDLE, address: *const c_ if let Some(n) = query_committed_window(address, mbi, len) { return n; } + let n = mem::VirtualQueryEx(process, address, mbi, len); + if n != 0 && len >= std::mem::size_of::() { + lazy_as_committed(mbi); + } + return n; } mem::VirtualQueryEx(process, address, mbi, len) } @@ -751,6 +1018,9 @@ pub unsafe extern "system" fn XMemVirtualQuery(process: HANDLE, address: *const if mem::VirtualQueryEx(process, address, mbi, std::mem::size_of::()) == 0 { return 0; } + if is_current_process(process) { + lazy_as_committed(mbi); + } const READABLE: u32 = mem::PAGE_READONLY | mem::PAGE_READWRITE | mem::PAGE_WRITECOPY @@ -914,15 +1184,64 @@ struct Away { /// homes in a sparse window whose pages went away in this call, given back at its end in /// runs (`give_back_homes`): one page at a time, a retail game's start took 20 s gone: Vec, + /// address → the page the title mapped there last. On the console a page stays mapped at + /// every address it was mapped at; here its data is in one place (`page`), so an address it + /// moved away from still names it here (the queue's page-mapping method maps the pages of + /// such addresses: `mirrors::apply_batches`). + title: std::collections::HashMap, + /// pages the title freed while others of their allocation live (`page_home` still knows + /// the block): no page is behind such a number any more (numbers are never handed out + /// again), so `page_now` answers none for it + freed: std::collections::HashSet, +} + +impl Away { + /// The page the title mapped at `at` last, if the title has not freed it. + fn title_page(&self, at: usize) -> Option { + self.title.get(&at).copied().filter(|p| !self.freed.contains(p)) + } +} + +/// The title released `[base, base + len)`: the pages it mapped there are mapped there no more. +fn forget_title_mappings(base: usize, len: usize) { + if let Some(a) = AWAY.lock().unwrap().as_mut() { + a.title.retain(|&at, _| at < base || at >= base.saturating_add(len)); + } } static AWAY: std::sync::Mutex> = std::sync::Mutex::new(None); +/// Where page `page`'s data is now: the address it is mapped at away from home, else its home +/// (`None`: no allocated page has that number). +fn page_now(page: usize) -> Option { + let (freed, away) = match AWAY.lock().unwrap().as_ref() { + Some(a) => (a.freed.contains(&page), a.page.get(&page).copied()), + None => (false, None), + }; + if freed { + return None; + } + away.or_else(|| page_home(page)) +} + /// 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)))) } +/// 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); @@ -932,6 +1251,12 @@ pub fn gpu_view_map_gen() -> u64 { GPU_VIEW_MAP_GEN.load(Ordering::Acquire) } +/// The queue's page-mapping method mapped pages at `va`: a GPU view's mappings changed if it +/// lies in one (textures there look again). +pub fn note_gpu_view_mapping(va: usize) { + note_mapping_at(va); +} + /// Pages are mapped or unmapped at `va`: a GPU view's mappings changed if it lies in one. fn note_mapping_at(va: usize) { if mirrors::source(va).is_some() { @@ -961,7 +1286,16 @@ 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 { - !pages.is_empty() && pages.iter().all(|&p| page_home(p).is_some()) + if pages.is_empty() { + return false; + } + if alias::enabled() { + return pages.iter().all(|&p| alias::page_live(p)); + } + // Lock `AWAY` before `PHYS_BLOCKS` (`page_home`) to match `read_physical_pages` / + // `write_physical_pages` and avoid ABBA lock inversions. + let away = AWAY.lock().unwrap(); + pages.iter().all(|&p| !away.as_ref().is_some_and(|a| a.freed.contains(&p)) && page_home(p).is_some()) } /// Whether a home is only reserved until it is used (a sparse window's, or plain memory's – @@ -983,6 +1317,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] { + if away.is_some_and(|a| a.freed.contains(&p)) { + return None; + } let home = page_home(p)?; let addr = match away.and_then(|a| a.page.get(&p).copied()) { Some(at) => at, @@ -997,6 +1334,9 @@ 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; } @@ -1016,6 +1356,9 @@ 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; } @@ -1211,12 +1554,155 @@ unsafe fn release_at(at: usize) { mem::VirtualFree(at as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT); } +/// Unmap every away-mapped physical page overlapping `[start, start + len)` (clearing `title` +/// and `lazy` records so freed/decommitted pages never leave dangling `AWAY` entries). +unsafe fn unmap_away_in(away: &mut Away, start: usize, len: usize) { + if len == 0 || away.at.is_empty() { + return; + } + let lo = start & !(PHYS_PAGE - 1); + let hi = start.saturating_add(len); + let addrs: Vec = away.at.range(lo..hi).map(|(&at, _)| at).collect(); + for at in addrs { + away.title.remove(&at); + unmap_away(away, at, &(0..0)); + note_mapping_at(at); + } +} + +unsafe fn unmap_away_range(start: usize, len: usize) { + if len > 0 { + if let Some(away) = AWAY.lock().unwrap().as_mut() { + unmap_away_in(away, start, len); + } + } +} + +/// Validate a plain `MEM_PRIVATE` `VirtualFree` call and return the byte range it will free/decommit. +unsafe fn plain_free_range(addr: usize, size: usize, t: u32) -> Option<(usize, usize)> { + let mut m: mem::MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if mem::VirtualQuery(addr as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 + || m.State == mem::MEM_FREE + || m.Type != mem::MEM_PRIVATE + || m.RegionSize == 0 + { + return None; + } + let alloc_base = m.AllocationBase as usize; + let query_same = |at: usize| -> Option { + let mut next: mem::MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + (mem::VirtualQuery(at as *const c_void, &mut next, std::mem::size_of_val(&next)) != 0 + && next.State != mem::MEM_FREE + && next.Type == mem::MEM_PRIVATE + && next.AllocationBase as usize == alloc_base + && next.RegionSize > 0) + .then_some(next.RegionSize) + }; + if t == mem::MEM_RELEASE || size == 0 { + if addr != alloc_base { + return None; + } + let mut end = (m.BaseAddress as usize).checked_add(m.RegionSize)?; + while let Some(step) = query_same(end) { + end = end.checked_add(step)?; + } + return Some((alloc_base, end - alloc_base)); + } + let (start, req_end) = (m.BaseAddress as usize, addr.checked_add(size)?); + let mut end = start.checked_add(m.RegionSize)?; + while end < req_end { + end = end.checked_add(query_same(end)?)?; + } + Some((start, req_end - start)) +} + +unsafe fn unmap_away_for_plain_free(addr: usize, size: usize, t: u32) { + if addr == 0 || !((t == mem::MEM_RELEASE && size == 0) || t == mem::MEM_DECOMMIT) { + return; + } + let mut g = AWAY.lock().unwrap(); + let Some(away) = g.as_mut().filter(|a| !a.at.is_empty()) else { return }; + let lo = addr & !(PHYS_PAGE - 1); + let has_cand = if t == mem::MEM_RELEASE || size == 0 { + away.at.range(lo..).next().is_some() + } else { + addr.checked_add(size).is_some_and(|hi| away.at.range(lo..hi).next().is_some()) + }; + if has_cand { + if let Some((start, len)) = plain_free_range(addr, size, t) { + unmap_away_in(away, start, len); + } + } +} + +/// Coalesces contiguous 64 KiB sparse-window commits inside `map_pages` / scatter calls so a +/// multi-gigabyte `XMemMapPhysicalPages` issues one `sparse::committed(start, len)` per run +/// instead of one `UpdateTileMappings` + `Signal` per page. +#[derive(Default)] +struct SparseCommitBatch { + run: Option<(usize, usize)>, +} + +impl SparseCommitBatch { + fn push_with(&mut self, at: usize, mut emit: impl FnMut(usize, usize)) { + if let Some((start, len)) = &mut self.run { + if start.checked_add(*len) == Some(at) { + *len += PHYS_PAGE; + return; + } + } + if let Some((start, len)) = self.run.take() { + emit(start, len); + } + self.run = Some((at, PHYS_PAGE)); + } + + fn flush_if_contains_with(&mut self, addr: usize, mut emit: impl FnMut(usize, usize)) { + if let Some((start, len)) = self.run { + if addr >= start && addr < start.saturating_add(len) { + self.run = None; + emit(start, len); + } + } + } + + fn flush_with(&mut self, mut emit: impl FnMut(usize, usize)) { + if let Some((start, len)) = self.run.take() { + emit(start, len); + } + } + + unsafe fn push(&mut self, at: usize) { + self.push_with(at, |a, n| crate::hle::d3d12x::sparse::committed(a, n)); + } + + unsafe fn flush_if_contains(&mut self, addr: usize) { + self.flush_if_contains_with(addr, |a, n| crate::hle::d3d12x::sparse::committed(a, n)); + } + + unsafe fn flush(&mut self) { + self.flush_with(|a, n| crate::hle::d3d12x::sparse::committed(a, n)); + } +} + /// A page mapped away from home (at `old`) that the title maps at `at`: what `old` holds copied /// to `at`, and `old` given up – its home is not used. By way of its home a move was four /// commits and decommits, each a tile mapping in a sparse window: a retail game moving pages one /// at a time after its first movie spent 20 s in them and its watchdog ended it. False: the page /// was never used at `old` (its home holds it, zeros) and is not mapped anywhere now. +#[cfg(test)] unsafe fn move_away(away: &mut Away, old: usize, at: usize, page: usize, in_uma: bool) -> Result { + move_away_batched(away, old, at, page, in_uma, None) +} + +unsafe fn move_away_batched( + away: &mut Away, + old: usize, + at: usize, + page: usize, + in_uma: bool, + mut sparse_batch: Option<&mut SparseCommitBatch>, +) -> Result { if lazy::unmark(old) { away.at.remove(&old); away.page.remove(&page); @@ -1230,7 +1716,13 @@ unsafe fn move_away(away: &mut Away, old: usize, at: usize, page: usize, in_uma: away.page.remove(&page); std::ptr::copy_nonoverlapping(old as *const u8, at as *mut u8, PHYS_PAGE); if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { - crate::hle::d3d12x::sparse::committed(at, PHYS_PAGE); + match sparse_batch.as_deref_mut() { + Some(batch) => batch.push(at), + None => crate::hle::d3d12x::sparse::committed(at, PHYS_PAGE), + } + } + if let Some(batch) = sparse_batch { + batch.flush_if_contains(old); } release_at(old); away.at.insert(at, page); @@ -1247,7 +1739,8 @@ unsafe fn alloc_physical_home(u: &crate::gpu::uma::Uma, bytes: usize) -> Option< return Some(p); } if !u.has_sparse() { - if let Some(p) = u.alloc(bytes, PHYS_PAGE) { + let fits = u.size().saturating_sub(u.used()) >= bytes.saturating_add(COHERENT_KEEP); + if let Some(p) = fits.then(|| u.alloc(bytes, PHYS_PAGE)).flatten() { return Some(p as usize); } } @@ -1272,6 +1765,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; @@ -1291,20 +1791,36 @@ pub unsafe extern "system" fn AllocateTitlePhysicalPages(_p: HANDLE, _t: u32, nu } pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: *mut usize) -> BOOL { + if alias::enabled() { + if arr.is_null() { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return 0; + } + alias::free(std::slice::from_raw_parts(arr, n)); + return 1; + } let Some(u) = crate::gpu::uma::get() else { return 0 }; if arr.is_null() { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; } // freed pages mapped elsewhere: that address keeps whatever it holds, the mapping goes - if let Some(away) = AWAY.lock().unwrap().as_mut() { + { + let mut g = AWAY.lock().unwrap(); + let away = g.get_or_insert_with(Away::default); for i in 0..n { - if let Some(at) = away.page.remove(&*arr.add(i)) { + let page = *arr.add(i); + if let Some(at) = away.page.remove(&page) { away.at.remove(&at); note_mapping_at(at); } + if page_index(page).is_some() { + away.freed.insert(page); + } } } + // (blocks gone whole: their numbers need no `freed` entries) + let mut gone: Vec<(usize, usize)> = Vec::new(); let mut g = PHYS_BLOCKS.lock().unwrap(); for i in 0..n { let Some(page) = page_index(*arr.add(i)) else { continue }; @@ -1317,6 +1833,7 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: e.1 = e.1.saturating_sub(1); if e.1 == 0 { g.remove(&first); + gone.push((first, count)); if u.is_sparse(home) { crate::hle::d3d12x::sparse::free(home); } else if u.contains(home) { @@ -1326,20 +1843,55 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: } } } + drop(g); + if !gone.is_empty() { + if let Some(away) = AWAY.lock().unwrap().as_mut() { + away.freed.retain(|&p| page_index(p).is_none_or(|i| !gone.iter().any(|&(f, c)| i >= f && i < f + c))); + } + } 1 } pub unsafe extern "system" fn MapTitlePhysicalPages(va: *mut c_void, n: usize, _t: u32, _p: u32, arr: *mut usize) -> *mut c_void { - let mut g = AWAY.lock().unwrap(); - let away = g.get_or_insert_with(Away::default); - let r = map_pages(away, va, n, arr); - give_back_homes(away); + if alias::enabled() { + return map_aliased(va, n, arr); + } + let r = { + let mut g = AWAY.lock().unwrap(); + let away = g.get_or_insert_with(Away::default); + let mut sparse_batch = SparseCommitBatch::default(); + let r = map_pages(away, va, n, arr, &mut sparse_batch); + sparse_batch.flush(); + give_back_homes(away); + r + }; + if !r.is_null() { + notify_vram_backing(r as usize, n.saturating_mul(PHYS_PAGE)); + } r } +/// `MapTitlePhysicalPages` with physical page aliasing (`alias`): the title always names the +/// address (a retail title never maps a page at its home, which is XCL's own view here). +unsafe fn map_aliased(va: *mut c_void, n: usize, arr: *mut usize) -> *mut c_void { + if va.is_null() || n == 0 { + fnd::SetLastError(if va.is_null() { fnd::ERROR_NOT_SUPPORTED } else { fnd::ERROR_INVALID_PARAMETER }); + return std::ptr::null_mut(); + } + note_mapping_at(va as usize); + let pages: Vec = if arr.is_null() { vec![0; n] } else { std::slice::from_raw_parts(arr, n).to_vec() }; + if alias::map(va as usize, &pages) { + notify_vram_backing(va as usize, n.saturating_mul(PHYS_PAGE)); + va + } else { + 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 { +/// caller (`give_back_homes`), and contiguous sparse-window commits are flushed by the caller +/// (`sparse_batch.flush()`). +unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize, sparse_batch: &mut SparseCommitBatch) -> *mut c_void { note_mapping_at(va as usize); if crate::gpu::uma::get().is_none() || n == 0 || (va.is_null() && arr.is_null()) { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); @@ -1364,6 +1916,9 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) } // (pages this call moved away and back are home again, not given back) away.gone.retain(|&h| h < home || h >= home + n * PHYS_PAGE); + for (i, &p) in pages.iter().enumerate() { + away.title.insert(home + i * PHYS_PAGE, p); + } for &p in &pages { if let Some(&at) = away.page.get(&p) { unmap_away(away, at, &(home..home + n * PHYS_PAGE)); @@ -1385,18 +1940,41 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) let (mut at_run, mut home_run) = (StateRun::default(), StateRun::default()); for (i, &p) in pages.iter().enumerate() { let at = base + i * PHYS_PAGE; + // what was mapped at `at` goes; the new page is written down once it is in place + away.title.remove(&at); + sparse_batch.flush_if_contains(at); if unmap_away(away, at, &(0..0)) { (at_run, home_run) = Default::default(); } if p == 0 { continue; } + let Some(home) = page_home(p) else { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return std::ptr::null_mut(); + }; + if at == home { + if !commit_homes(home, 1) { + fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); + return std::ptr::null_mut(); + } + away.gone.retain(|&h| h != home); + if let Some(&old) = away.page.get(&p) { + sparse_batch.flush_if_contains(old); + unmap_away(away, old, &(home..home + PHYS_PAGE)); + } + away.title.insert(home, p); + (at_run, home_run) = Default::default(); + continue; + } if let Some(&old) = away.page.get(&p) { // (a move commits `at` and decommits `old`, which may lie in a run already answered: // both runs go – #556) - match move_away(away, old, at, p, in_uma(at)) { + match move_away_batched(away, old, at, p, in_uma(at), Some(sparse_batch)) { Ok(true) => { + away.gone.retain(|&h| h != at); (at_run, home_run) = Default::default(); + away.title.insert(at, p); continue; } // a lazy page is only unmarked: memory is as it was, the runs stay @@ -1408,20 +1986,22 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) } } let fresh = !in_uma(at) && !committed_page_in(at, &mut at_run); - let home = page_home(p).unwrap(); // a page never used (its home not committed) at the title's own reserved address space: // committed on first use (`lazy`) – GPU-owned targets placed there are never touched let plain = crate::gpu::uma::get().is_none_or(|u| !u.contains(at)); if fresh && plain && !committed_page_in(home, &mut home_run) { + away.gone.retain(|&h| h != at); lazy::mark(at); away.at.insert(at, p); away.page.insert(p, at); + away.title.insert(at, p); continue; } if !in_uma(at) && mem::VirtualAlloc(at as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); return std::ptr::null_mut(); } + away.gone.retain(|&h| h != at); if committed_page(home) { std::ptr::copy_nonoverlapping(home as *const u8, at as *mut u8, PHYS_PAGE); if move_home_away(away, home) { @@ -1431,10 +2011,11 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) std::ptr::write_bytes(at as *mut u8, 0, PHYS_PAGE); // a page never used: zeros } if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { - crate::hle::d3d12x::sparse::committed(at, PHYS_PAGE); + sparse_batch.push(at); } away.at.insert(at, p); away.page.insert(p, at); + away.title.insert(at, p); } va } @@ -1459,19 +2040,38 @@ pub unsafe extern "system" fn XMemMapPhysicalPagesScatter(addresses: *const *mut fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; } + // no page array: page 0 (unmap) for every address + let mut none = 0u64; + let mut page = |i: usize| if pages.is_null() { &mut none as *mut u64 as *mut usize } else { pages.add(i) as *mut usize }; + if alias::enabled() { + return (0..n).all(|i| !map_aliased(*addresses.add(i), 1, page(i)).is_null()) as BOOL; + } if crate::gpu::uma::get().is_none() { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; } - let mut g = AWAY.lock().unwrap(); - let away = g.get_or_insert_with(Away::default); - // no page array: page 0 (unmap) for every address - let ok = (0..n).all(|i| { - let mut none = 0usize; - let page = if pages.is_null() { &mut none as *mut usize } else { pages.add(i) as *mut usize }; - !map_pages(away, *addresses.add(i), 1, page).is_null() - }); - give_back_homes(away); + let mut mapped: Vec = Vec::new(); + let ok = { + let mut g = AWAY.lock().unwrap(); + let away = g.get_or_insert_with(Away::default); + let mut sparse_batch = SparseCommitBatch::default(); + let ok = (0..n).all(|i| { + let addr = *addresses.add(i); + let r = map_pages(away, addr, 1, page(i), &mut sparse_batch); + if !r.is_null() { + mapped.push(r as usize); + true + } else { + false + } + }); + sparse_batch.flush(); + give_back_homes(away); + ok + }; + for a in mapped { + notify_vram_backing(a, PHYS_PAGE); + } ok as BOOL } @@ -1663,6 +2263,35 @@ pub unsafe extern "system" fn SetThreadGroupAffinity(h: HANDLE, a: *const GROUP_ thr::SetThreadGroupAffinity(h, &fit, prev) } +fn priority_boost_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PRIORITY").map_or(true, |v| v.trim() != "0")) +} + +/// Floor guest/title thread priorities at `THREAD_PRIORITY_BELOW_NORMAL` (`-1`) so console +/// background/streaming threads requesting `LOWEST` (`-2`) or `IDLE` (`-15`) are not starved +/// on Windows 11 hybrid E-cores. Values `>= THREAD_PRIORITY_BELOW_NORMAL` (including normal, +/// high, time-critical, and background-mode flags) pass through unchanged. +fn clamp_thread_priority(priority: i32, floor_enabled: bool) -> i32 { + if floor_enabled && priority < thr::THREAD_PRIORITY_BELOW_NORMAL { + thr::THREAD_PRIORITY_BELOW_NORMAL + } else { + priority + } +} + +pub unsafe extern "system" fn SetThreadPriority(h: HANDLE, priority: i32) -> BOOL { + let clamped = clamp_thread_priority(priority, priority_boost_enabled()); + if clamped != priority { + static CLAMPED: AtomicU64 = AtomicU64::new(0); + let n = CLAMPED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!("SetThreadPriority: floored {priority} → {clamped} (THREAD_PRIORITY_BELOW_NORMAL; #{n})"); + } + } + thr::SetThreadPriority(h, clamped) +} + pub unsafe extern "system" fn QueryProcessorSchedulingStatistics(out: *mut [u64; 3]) { if out.is_null() { return; @@ -1705,6 +2334,16 @@ extern "system" { fn NtSetTimerResolution(desired: u32, set: u8, current: *mut u32) -> i32; } +#[link(name = "winmm", kind = "raw-dylib")] +extern "system" { + fn timeBeginPeriod(period: u32) -> u32; + fn timeEndPeriod(period: u32) -> u32; +} + +/// Active timer-resolution requests so `restore_fine_timer()` can cleanly release both on exit. +static TIMER_MM_ACTIVE: AtomicBool = AtomicBool::new(false); +static TIMER_NT_FINEST: AtomicU32 = AtomicU32::new(0); + pub fn host_os_version() -> (u32, u32, u32) { unsafe { let mut v: OsVersionInfoW = std::mem::zeroed(); @@ -1714,38 +2353,97 @@ pub fn host_os_version() -> (u32, u32, u32) { } } -/// The finest timer Windows offers (0.5 ms) for the title: with the default 15.6 ms tick every -/// sleep rounds up (a retail game's audio mixer ran at a third of real time). Windows 11 keeps -/// it while the window is hidden only when told to. +/// The finest timer Windows offers (0.5 ms via `NtSetTimerResolution`, plus `timeBeginPeriod(1)` +/// fallback) for the title: with the default 15.6 ms tick every sleep rounds up (a retail game's +/// audio mixer ran at a third of real time). Windows 11 keeps it while the window is hidden only +/// when told to. Also opt out of Windows 11 Efficiency Mode +/// (`PROCESS_POWER_THROTTLING_EXECUTION_SPEED`) and lift process priority to `ABOVE_NORMAL` so +/// foreground title rendering/streaming threads are not demoted behind background OS work +/// (`XCL_PRIORITY=0` disables priority boost and thread-priority flooring). pub fn fine_timer() { use windows_sys::Win32::System::Threading::{ - GetCurrentProcess, ProcessPowerThrottling, SetProcessInformation, PROCESS_POWER_THROTTLING_CURRENT_VERSION, + GetCurrentProcess, ProcessPowerThrottling, SetPriorityClass, SetProcessInformation, ABOVE_NORMAL_PRIORITY_CLASS, + PROCESS_POWER_THROTTLING_CURRENT_VERSION, PROCESS_POWER_THROTTLING_EXECUTION_SPEED, PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE, }; - let state = PROCESS_POWER_THROTTLING_STATE { + let size = std::mem::size_of::() as u32; + let combined = PROCESS_POWER_THROTTLING_STATE { Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, - ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, + ControlMask: PROCESS_POWER_THROTTLING_EXECUTION_SPEED | PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, StateMask: 0, }; - let size = std::mem::size_of::() as u32; - let kept = unsafe { SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &state as *const _ as *const c_void, size) } != 0; + let mut kept = unsafe { SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &combined as *const _ as *const c_void, size) } != 0; + if !kept { + let timer_only = PROCESS_POWER_THROTTLING_STATE { + Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, + ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, + StateMask: 0, + }; + kept = unsafe { SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &timer_only as *const _ as *const c_void, size) } != 0; + let eco_only = PROCESS_POWER_THROTTLING_STATE { + Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, + ControlMask: PROCESS_POWER_THROTTLING_EXECUTION_SPEED, + StateMask: 0, + }; + unsafe { SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &eco_only as *const _ as *const c_void, size) }; + } + let boosted = if priority_boost_enabled() { + unsafe { SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS) != 0 } + } else { + false + }; + let mm_ok = if TIMER_MM_ACTIVE.load(Ordering::Acquire) { + true + } else if unsafe { timeBeginPeriod(1) } == 0 { + TIMER_MM_ACTIVE.store(true, Ordering::Release); + true + } else { + false + }; // in 100 ns units; "finest" is the smallest period the system supports let (mut coarsest, mut finest, mut was) = (0u32, 0u32, 0u32); if unsafe { NtQueryTimerResolution(&mut coarsest, &mut finest, &mut was) } < 0 || finest == 0 { - crate::xlog_warn!("timer: NtQueryTimerResolution failed – Windows' default resolution"); + crate::xlog_warn!( + "timer: NtQueryTimerResolution failed (winmm 1 ms: {}; above-normal priority: {})", + if mm_ok { "yes" } else { "no" }, + if boosted { "yes" } else { "no" } + ); return; } - let mut now = 0u32; - let status = unsafe { NtSetTimerResolution(finest, 1, &mut now) }; + let mut now = was; + let status = if TIMER_NT_FINEST.load(Ordering::Acquire) == finest { + 0 + } else { + let s = unsafe { NtSetTimerResolution(finest, 1, &mut now) }; + if s >= 0 { + TIMER_NT_FINEST.store(finest, Ordering::Release); + } + s + }; crate::xlog_info!( - "timer: {} (was {:.2} ms, now {:.2} ms; kept while the window is hidden: {})", + "timer: {} (was {:.2} ms, now {:.2} ms; winmm 1 ms: {}; EcoQoS/timer-throttle off: {}; above-normal priority: {})", if status >= 0 { "finest resolution for the title" } else { "raising the resolution failed" }, was as f64 / 10_000.0, now as f64 / 10_000.0, - if kept { "yes" } else { "no" } + if mm_ok { "yes" } else { "no" }, + if kept { "yes" } else { "no" }, + if boosted { "yes" } else { "no" } ); } +/// Release the process's `NtSetTimerResolution` and `timeBeginPeriod(1)` requests on exit. +/// Idempotent so both normal returns and forced exits can call it safely. +pub fn restore_fine_timer() { + let finest = TIMER_NT_FINEST.swap(0, Ordering::AcqRel); + if finest != 0 { + let mut now = 0u32; + unsafe { NtSetTimerResolution(finest, 0, &mut now) }; + } + if TIMER_MM_ACTIVE.swap(false, Ordering::AcqRel) { + unsafe { timeEndPeriod(1) }; + } +} + pub unsafe extern "system" fn GetSystemOSVersion(out: *mut SystemOsVersionInfo) { if out.is_null() { return; @@ -2179,6 +2877,39 @@ mod tests { } let per = t.elapsed() / 20; assert!(per < std::time::Duration::from_millis(5), "Sleep(1) took {per:?}: the 15.6 ms tick"); + // Verify clean, idempotent exit restoration of NtSetTimerResolution + timeBeginPeriod(1). + restore_fine_timer(); + restore_fine_timer(); + assert!(!TIMER_MM_ACTIVE.load(Ordering::Acquire)); + assert_eq!(TIMER_NT_FINEST.load(Ordering::Acquire), 0); + } + + #[test] + fn thread_priority_floor_clamps_lowest_and_idle_to_below_normal() { + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_IDLE, true), thr::THREAD_PRIORITY_BELOW_NORMAL); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_LOWEST, true), thr::THREAD_PRIORITY_BELOW_NORMAL); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_BELOW_NORMAL, true), thr::THREAD_PRIORITY_BELOW_NORMAL); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_NORMAL, true), thr::THREAD_PRIORITY_NORMAL); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_ABOVE_NORMAL, true), thr::THREAD_PRIORITY_ABOVE_NORMAL); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_HIGHEST, true), thr::THREAD_PRIORITY_HIGHEST); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_TIME_CRITICAL, true), thr::THREAD_PRIORITY_TIME_CRITICAL); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_IDLE, false), thr::THREAD_PRIORITY_IDLE); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_LOWEST, false), thr::THREAD_PRIORITY_LOWEST); + + // Live thread check through the exported guest hook: IDLE/LOWEST floor to BELOW_NORMAL. + if priority_boost_enabled() { + std::thread::spawn(|| unsafe { + let me = thr::GetCurrentThread(); + assert_ne!(SetThreadPriority(me, thr::THREAD_PRIORITY_IDLE), 0); + assert_eq!(thr::GetThreadPriority(me), thr::THREAD_PRIORITY_BELOW_NORMAL); + assert_ne!(SetThreadPriority(me, thr::THREAD_PRIORITY_LOWEST), 0); + assert_eq!(thr::GetThreadPriority(me), thr::THREAD_PRIORITY_BELOW_NORMAL); + assert_ne!(SetThreadPriority(me, thr::THREAD_PRIORITY_NORMAL), 0); + assert_eq!(thr::GetThreadPriority(me), thr::THREAD_PRIORITY_NORMAL); + }) + .join() + .unwrap(); + } } #[test] @@ -2784,7 +3515,7 @@ mod tests { let at = mem::VirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; mem::VirtualFree(at as *mut c_void, 0, mem::MEM_RELEASE); let page = 0x7E57_0000usize; - let mut away = Away { at: Default::default(), page: Default::default(), gone: Vec::new() }; + let mut away = Away::default(); away.at.insert(old, page); away.page.insert(page, old); assert!(move_away(&mut away, old, at, page, false).is_err()); @@ -2825,6 +3556,30 @@ mod tests { } } + #[test] + fn sparse_commit_batch_coalesces_contiguous_pages_and_flushes_on_overlap() { + let mut batch = SparseCommitBatch::default(); + let mut emitted = Vec::new(); + let base = 0x1_0000_0000usize; + // 4 contiguous 64 KiB pages coalesce into a single 256 KiB run. + for i in 0..4 { + batch.push_with(base + i * PHYS_PAGE, |a, n| emitted.push((a, n))); + } + assert!(emitted.is_empty()); + // Discontiguous page flushes the first run and starts a second. + batch.push_with(base + 10 * PHYS_PAGE, |a, n| emitted.push((a, n))); + assert_eq!(emitted, vec![(base, 4 * PHYS_PAGE)]); + batch.push_with(base + 11 * PHYS_PAGE, |a, n| emitted.push((a, n))); + // Unrelated address does not flush; overlapping address flushes immediately. + batch.flush_if_contains_with(base + 9 * PHYS_PAGE, |a, n| emitted.push((a, n))); + assert_eq!(emitted.len(), 1); + batch.flush_if_contains_with(base + 10 * PHYS_PAGE, |a, n| emitted.push((a, n))); + assert_eq!(emitted, vec![(base, 4 * PHYS_PAGE), (base + 10 * PHYS_PAGE, 2 * PHYS_PAGE)]); + // Trailing flush on empty batch is a no-op. + batch.flush_with(|a, n| emitted.push((a, n))); + assert_eq!(emitted.len(), 2); + } + /// Timing (`--ignored --nocapture`; `XCL_SCATTER_PAGES=4096,8192`): pages written at their /// home, scattered from there into a reservation in one call, scattered again in reverse, /// and mapped back home. @@ -3039,6 +3794,146 @@ mod tests { mirrors::released(other); } + /// A batch of the queue's page-mapping method: the first destination, the number of ranges + /// (`kind, start, count` each) and a pointer to them. + #[repr(C)] + struct Batch { + dest: u64, + ranges_n: u32, + _pad: u32, + ranges: usize, + } + fn batch(dest: usize, r: &[[u32; 3]]) -> Batch { + Batch { dest: dest as u64, ranges_n: r.len() as u32, _pad: 0, ranges: r.as_ptr() as usize } + } + + /// A GPU-view page given a pool page shows the physical page the title mapped there, where + /// XCL keeps it: at the pool page, then – once the title maps it into another address too + /// (the CPU view of a retail title's streamed textures) – there. + #[test] + fn a_gpu_view_page_shows_the_physical_page_where_it_is_kept() { + use mirrors::{apply_batches, mapped_source, Mapped, PAGE}; + let null = std::ptr::null_mut(); + unsafe { + let mut n = 1usize; + let mut page = [0usize; 1]; + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, page.as_mut_ptr()), 1); + // used at its home first, so the moves below copy it (no lazy page) + let home = MapTitlePhysicalPages(null, 1, 0, 4, page.as_mut_ptr()) as usize; + assert_ne!(home, 0); + *(home as *mut u32) = 0x600D; + // the pool: a reservation of the title's, the page mapped at its page 1 + let pool = mem::VirtualAlloc(std::ptr::null(), 4 * PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_eq!(MapTitlePhysicalPages((pool + PAGE) as *mut c_void, 1, 0, 4, page.as_mut_ptr()) as usize, pool + PAGE); + let (cpu, gpu, size) = (0x7140_0000_0000usize, 0x7146_0000_0000usize, 0x125 * PAGE); + mirrors::reserved(cpu, size, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(gpu, size, 0x2040_2000, 0x801); + // pool pages 0 (nothing mapped there) and 1 at the GPU view's pages 2 and 3 + let r = [[0, 0, 2]]; + assert_eq!(apply_batches(1, [batch(gpu + 2 * PAGE, &r)].as_ptr() as usize, pool, 4), Some(Mapped { mapped: 2, physical: 1, ..Mapped::default() })); + assert_eq!(mapped_source(gpu + 2 * PAGE + 8), Some(Some(pool + 8)), "no physical page: the pool page itself"); + assert_eq!(mapped_source(gpu + 3 * PAGE + 8), Some(Some(pool + PAGE + 8))); + assert_eq!(*(pool as *const u8).add(PAGE).cast::(), 0x600D); + // the title maps the page at another address too: XCL moves its data there, and the + // GPU view shows it there + let other = mem::VirtualAlloc(std::ptr::null(), PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_eq!(MapTitlePhysicalPages(other as *mut c_void, 1, 0, 4, page.as_mut_ptr()) as usize, other); + assert_eq!(*(other as *const u32), 0x600D); + assert_eq!(mapped_source(gpu + 3 * PAGE + 8), Some(Some(other + 8))); + mirrors::released(cpu); + assert_eq!(FreeTitlePhysicalPages(null, 1, page.as_mut_ptr()), 1); + mem::VirtualFree(other as *mut c_void, 0, mem::MEM_RELEASE); + mem::VirtualFree(pool as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + /// A page the title frees while the rest of its allocation lives is no longer looked for: + /// the GPU-view page given its pool page reads the pool page, which keeps its bytes; a later + /// call naming that pool page records no physical page (review of #1055). + #[test] + fn a_freed_page_is_read_at_its_pool_page() { + use mirrors::{apply_batches, mapped_source, Mapped, PAGE}; + let null = std::ptr::null_mut(); + unsafe { + let mut n = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1); + let home = MapTitlePhysicalPages(null, 2, 0, 4, pages.as_mut_ptr()) as usize; + assert_ne!(home, 0); + *((home + PAGE) as *mut u32) = 0xBEEF; + let pool = mem::VirtualAlloc(std::ptr::null(), 4 * PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_eq!(MapTitlePhysicalPages((pool + 2 * PAGE) as *mut c_void, 1, 0, 4, pages.as_mut_ptr().add(1)) as usize, pool + 2 * PAGE); + let (cpu, gpu, size) = (0x7150_0000_0000usize, 0x7156_0000_0000usize, 0x126 * PAGE); + mirrors::reserved(cpu, size, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(gpu, size, 0x2040_2000, 0x801); + let r = [[0u32, 2, 1]]; + assert_eq!(apply_batches(1, [batch(gpu + PAGE, &r)].as_ptr() as usize, pool, 4), Some(Mapped { mapped: 1, physical: 1, ..Mapped::default() })); + assert_eq!(mapped_source(gpu + PAGE), Some(Some(pool + 2 * PAGE))); + // page 1 freed alone: its block lives on (page 0), the pool page keeps the bytes + assert_eq!(FreeTitlePhysicalPages(null, 1, pages.as_mut_ptr().add(1)), 1); + assert!(page_home(pages[1]).is_some(), "the block is still allocated"); + assert_eq!(mapped_source(gpu + PAGE + 4), Some(Some(pool + 2 * PAGE + 4)), "the pool page, not the page's home"); + assert_eq!(*((pool + 2 * PAGE) as *const u32), 0xBEEF); + assert_eq!(apply_batches(1, [batch(gpu + 2 * PAGE, &r)].as_ptr() as usize, pool, 4), Some(Mapped { mapped: 1, ..Mapped::default() }), "no physical page behind it now"); + mirrors::released(cpu); + assert_eq!(FreeTitlePhysicalPages(null, 1, pages.as_mut_ptr()), 1); + assert!(AWAY.lock().unwrap().as_ref().is_some_and(|a| !a.freed.contains(&pages[1])), "the whole block gone: its numbers are forgotten"); + mem::VirtualFree(pool as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + /// The queue's page-mapping method (`CopyPageMappingsBatchX`) points pages of a GPU view + /// at pool pages or at nothing; a bad call records nothing; releasing the view drops them. + #[test] + fn page_mappings_point_gpu_view_pages_at_pool_pages() { + use mirrors::{apply_batches, mapped_source, Mapped, PAGE}; + // (a size no other test uses, so the GPU view pairs with this CPU view) + let (cpu, gpu, size) = (0x7100_0000_0000usize, 0x7106_0000_0000usize, 0x123 * PAGE); + let (pool, pool_pages) = (0x7200_0000_0000usize, 64u32); + mirrors::reserved(cpu, size, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(gpu, size, 0x2040_2000, 0x801); + assert_eq!(mirrors::source(gpu), Some(cpu)); + unsafe { + // two pool pages from 10 on, one page kept, pool page 5 three times, one unmapped; + // then two pages outside any GPU view + let r1 = [[0, 10, 2], [3, 0, 1], [1, 5, 3], [2, 0, 1]]; + let r2 = [[0, 0, 2]]; + let b = [batch(gpu + 4 * PAGE + 0x1234, &r1), batch(0x7300_0000_0000, &r2)]; + assert_eq!(apply_batches(2, b.as_ptr() as usize, pool, pool_pages), Some(Mapped { mapped: 5, unmapped: 1, elsewhere: 2, ..Mapped::default() })); + assert_eq!(mapped_source(gpu + 4 * PAGE + 0x20), Some(Some(pool + 10 * PAGE + 0x20))); + assert_eq!(mapped_source(gpu + 5 * PAGE), Some(Some(pool + 11 * PAGE))); + assert_eq!(mapped_source(gpu + 6 * PAGE), None, "kept"); + for k in 7..10 { + assert_eq!(mapped_source(gpu + k * PAGE + 8), Some(Some(pool + 5 * PAGE + 8))); + } + assert_eq!(mapped_source(gpu + 10 * PAGE), Some(None), "unmapped"); + assert_eq!(mapped_source(gpu + 11 * PAGE), None, "past the ranges"); + assert_eq!(mapped_source(gpu + 3 * PAGE), None, "before the destination"); + assert_eq!(mapped_source(0x7300_0000_0000), None, "outside any GPU view"); + + // a later call maps the unmapped page + let r = [[1, 1, 1]]; + assert_eq!(apply_batches(1, [batch(gpu + 10 * PAGE, &r)].as_ptr() as usize, pool, pool_pages), Some(Mapped { mapped: 1, ..Mapped::default() })); + assert_eq!(mapped_source(gpu + 10 * PAGE), Some(Some(pool + PAGE))); + + // bad calls record nothing: a range leaving the pool (after a good one), an unknown + // kind, ranges that are not readable + let leaves = [[0, 0, 1], [0, 63, 2]]; + assert_eq!(apply_batches(1, [batch(gpu + 20 * PAGE, &leaves)].as_ptr() as usize, pool, pool_pages), None); + assert_eq!(mapped_source(gpu + 20 * PAGE), None); + let unknown = [[7, 0, 1]]; + assert_eq!(apply_batches(1, [batch(gpu + 20 * PAGE, &unknown)].as_ptr() as usize, pool, pool_pages), None); + let unreadable = Batch { dest: (gpu + 20 * PAGE) as u64, ranges_n: 1, _pad: 0, ranges: 0 }; + assert_eq!(apply_batches(1, [unreadable].as_ptr() as usize, pool, pool_pages), None); + assert_eq!(apply_batches(1, 0, pool, pool_pages), None, "batches not readable"); + assert_eq!(apply_batches(0, 0, pool, pool_pages), Some(Mapped::default()), "no batches"); + } + mirrors::released(cpu); + assert_eq!(mirrors::source(gpu), None); + assert_eq!(mapped_source(gpu + 4 * PAGE), None, "released with its GPU view"); + assert_eq!(mapped_source(gpu + 10 * PAGE), None); + } + /// GPU-visible title memory that reaches the plain-memory fallback (64 KiB pages, large /// pages, a graphics protection) is write-watched: a texture placed there sees the CPU's /// writes. The fallback is called directly: through `VirtualAlloc` these sizes land in a @@ -3251,4 +4146,116 @@ mod tests { assert!(u.free(home)); } } + + #[test] + fn map_pages_preserves_self_home_and_reused_home_in_scatter() { + unsafe { + let _ = crate::gpu::uma::get().expect("UMA must initialize"); + let (mut n, mut pages) = (3usize, [0usize; 3]); + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let [p0, p1, p2] = pages; + let h0 = MapTitlePhysicalPages(std::ptr::null_mut(), 3, 0, 4, pages.as_mut_ptr()) as usize; + assert_ne!(h0, 0); + *(h0 as *mut u32) = 0x1111_0001; + *((h0 + PHYS_PAGE) as *mut u32) = 0x2222_0002; + *((h0 + 2 * PHYS_PAGE) as *mut u32) = 0x3333_0003; + + let dst = mem::VirtualAlloc(std::ptr::null(), 2 * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_ne!(dst, 0); + let (dst0, dst1) = (dst, dst + PHYS_PAGE); + // Step 0 moves p0 off h0 (away.gone); step 1 maps p1 from its home onto h0. + let addrs = [dst0 as *mut c_void, h0 as *mut c_void]; + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), 2, [p0 as u64, p1 as u64].as_mut_ptr()), 1); + assert!(committed_page(h0), "reused home (from home) must stay committed"); + assert_eq!((*(dst0 as *const u32), *(h0 as *const u32)), (0x1111_0001, 0x2222_0002)); + // Same scatter with p2 arriving via move_away from dst1 onto h0. + assert_eq!(MapTitlePhysicalPages(std::ptr::null_mut(), 3, 0, 4, pages.as_mut_ptr()) as usize, h0); + assert_eq!(MapTitlePhysicalPages(dst1 as *mut c_void, 1, 0, 4, [p2].as_mut_ptr()) as usize, dst1); + *(dst1 as *mut u32) = 0x4444_0004; + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), 2, [p0 as u64, p2 as u64].as_mut_ptr()), 1); + assert!(committed_page(h0) && !committed_page(dst1), "reused home (via move_away) must stay committed"); + assert_eq!((*(dst0 as *const u32), *(h0 as *const u32)), (0x1111_0001, 0x4444_0004)); + + assert_eq!(MapTitlePhysicalPages(std::ptr::null_mut(), 3, 0, 4, pages.as_mut_ptr()) as usize, h0); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 3, pages.as_mut_ptr()), 1); + assert_eq!(mem::VirtualFree(dst as *mut c_void, 0, mem::MEM_RELEASE), 1); + } + } + + #[test] + fn virtual_free_unmaps_away_pages_in_plain_and_sparse_reservations() { + unsafe { + let u = crate::gpu::uma::get().expect("UMA must initialize"); + let (mut n, mut pages) = (3usize, [0usize; 3]); + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let [p0, p1, p2] = pages; + let r = mem::VirtualAlloc(std::ptr::null(), 2 * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_ne!(r, 0); + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 2, 0, 4, [p0, p1].as_mut_ptr()) as usize, r); + *(r as *mut u32) = 0x5555_0001; + // Invalid VirtualFree calls must fail without touching AWAY. + assert_eq!(VirtualFree(r as *mut c_void, PHYS_PAGE, mem::MEM_RELEASE), 0); + assert_eq!(VirtualFree((r + PHYS_PAGE) as *mut c_void, 0, mem::MEM_RELEASE), 0); + assert_eq!(VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE | mem::MEM_DECOMMIT), 0); + assert_eq!(VirtualFree(r as *mut c_void, 3 * PHYS_PAGE, mem::MEM_DECOMMIT), 0); + assert!(physical_page_at(r) && physical_page_at(r + PHYS_PAGE) && *(r as *const u32) == 0x5555_0001); + // Partial MEM_DECOMMIT unmaps p0 (saving bytes home); MEM_RELEASE clears lazy p1. + assert_eq!(VirtualFree(r as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT), 1); + assert!(!physical_page_at(r) && physical_page_at(r + PHYS_PAGE)); + assert_eq!(VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE), 1); + assert!(!physical_page_at(r + PHYS_PAGE) && !lazy::unmark(r + PHYS_PAGE)); + // Sparse UMA reservation: partial MEM_DECOMMIT + full MEM_RELEASE across committed p0 & lazy p2. + let sp = VirtualAlloc(std::ptr::null(), 2 * PHYS_PAGE, mem::MEM_RESERVE | MEM_GRAPHICS, mem::PAGE_READWRITE) as usize; + assert!(sp != 0 && u.is_sparse(sp)); + assert_eq!(MapTitlePhysicalPages(sp as *mut c_void, 2, 0, 4, [p0, p2].as_mut_ptr()) as usize, sp); + assert_eq!(*(sp as *const u32), 0x5555_0001); + *(sp as *mut u32) = 0x6666_0001; + assert_eq!(VirtualFree(sp as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT), 1); + assert!(!physical_page_at(sp) && physical_page_at(sp + PHYS_PAGE)); + assert_eq!(VirtualFree(sp as *mut c_void, 0, mem::MEM_RELEASE), 1); + assert!(!physical_page_at(sp + PHYS_PAGE) && !lazy::unmark(sp + PHYS_PAGE)); + // Coherent UMA allocation: partial MEM_DECOMMIT + MEM_RELEASE unmap AWAY pages cleanly. + let coh = u.alloc(2 * PHYS_PAGE, PHYS_PAGE).expect("coherent UMA alloc") as usize; + assert!(u.is_committed(coh)); + assert_eq!(MapTitlePhysicalPages(coh as *mut c_void, 2, 0, 4, [p0, p2].as_mut_ptr()) as usize, coh); + assert_eq!(*(coh as *const u32), 0x6666_0001); + *(coh as *mut u32) = 0x7777_0001; + *(coh.wrapping_add(PHYS_PAGE) as *mut u32) = 0x7777_0002; + assert_eq!(VirtualFree(coh as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT), 1); + assert!(!physical_page_at(coh) && physical_page_at(coh + PHYS_PAGE)); + assert_eq!(*(coh as *const u32), 0, "MEM_DECOMMIT zeroes coherent UMA range"); + assert_eq!(VirtualFree(coh as *mut c_void, 0, mem::MEM_RELEASE), 1); + assert!(!physical_page_at(coh + PHYS_PAGE)); + // Saved home bytes for p0 and p2 survive coherent VirtualFree. + let h0 = MapTitlePhysicalPages(std::ptr::null_mut(), 3, 0, 4, pages.as_mut_ptr()) as usize; + assert_eq!((*(h0 as *const u32), *((h0 + 2 * PHYS_PAGE) as *const u32)), (0x7777_0001, 0x7777_0002)); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 3, pages.as_mut_ptr()), 1); + } + } + + #[test] + fn physical_pages_live_and_rw_reject_partially_freed_pages() { + unsafe { + let _ = crate::gpu::uma::get().expect("UMA must initialize"); + let (mut n, mut pages) = (2usize, [0usize; 2]); + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let [p0, p1] = pages; + assert!(physical_pages_live(&[p0, p1])); + + // Free only p0 while p1 keeps the backing PHYS_BLOCKS entry alive. + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, [p0].as_mut_ptr()), 1); + assert!(!physical_pages_live(&[p0]), "individually freed page must not be reported live"); + assert!(!physical_pages_live(&[p0, p1]), "slice containing a freed page must not be reported live"); + assert!(physical_pages_live(&[p1]), "sibling page in the same block must remain live"); + + let mut buf = [0u8; 16]; + assert!(!read_physical_pages(&[p0], 0, &mut buf), "read_physical_pages must reject a freed page"); + assert!(!write_physical_pages(&[p0], 0, &[0xAB; 16]), "write_physical_pages must reject a freed page"); + assert!(write_physical_pages(&[p1], 0, &[0xCD; 16]), "sibling page stays writable"); + assert!(read_physical_pages(&[p1], 0, &mut buf) && buf == [0xCD; 16], "sibling page stays readable"); + + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, [p1].as_mut_ptr()), 1); + assert!(!physical_pages_live(&[p1]), "fully freed block must not be live"); + } + } } diff --git a/crates/xcl/src/hle/kernelx/alias.rs b/crates/xcl/src/hle/kernelx/alias.rs new file mode 100644 index 0000000000..351ab21a05 --- /dev/null +++ b/crates/xcl/src/hle/kernelx/alias.rs @@ -0,0 +1,580 @@ +//! 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::{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); + +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 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); + } + unmap_range(base, len); + with(|s| s.spaces.remove(&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| s.views.range(at..at + len).map(|(&a, _)| a).collect()); + for a in views { + unmap_view(a); + } +} + +/// The view at `at` (if any) unmapped, leaving a placeholder. +unsafe fn unmap_view(at: usize) { + if with(|s| s.views.remove(&at)).is_some() { + guards::forget(at); + lazy::unmark(at); + sections::unmap(at); + } +} + +/// `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); + s.blocks.remove(&first); + } + } + }); + for home in homes { + 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) || pages.iter().any(|&p| p != 0 && with(|s| s.page(p)).is_none()) { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return false; + } + 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 + unmap_view(at); + 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) = with(|s| s.away.get(&page).copied()) { + unmap_away(old); + } + let (section, index, home) = with(|s| s.page(page)).unwrap(); + if with(|s| s.in_space(at)) { + if !section.map(index, 1, at) { + return false; + } + with(|s| s.views.insert(at, (page, section, index))); + guards::watch(page, at); + if !committed(page) { + // 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); + } + 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())) +} + +/// 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); + assert_eq!(dirty(), vec![cpu + 3 * PAGE, gpu + 5 * PAGE], "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); + assert_eq!(dirty(), vec![pool + PAGE, cpu + 2 * PAGE, gpu, gpu + PAGE], "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..c91a13e379 --- /dev/null +++ b/crates/xcl/src/hle/kernelx/guards.rs @@ -0,0 +1,456 @@ +//! 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) { + 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); + } + 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 fn take_dirty(out: &mut Vec, step: usize) { + 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) { + 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 fa750b9a48..adbdd2edf8 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -41,7 +41,16 @@ 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() { + return false; + } + // (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); + // If this lazy page belongs to a VRAM-only sparse backing (`sparse::alloc_vram_only`), + // queue it lock-free of `sparse::STATE` so the next execute/readback clears its hole mask. + crate::hle::d3d12x::sparse::note_lazy_commit(page); + true } unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { @@ -78,13 +87,44 @@ pub(crate) fn mark(page: usize) { LAZY.write().unwrap_or_else(|e| e.into_inner()).insert(page); } +/// Whether `page` (64 KiB aligned) is mapped but not committed yet. +pub fn is_lazy(page: usize) -> bool { + LAZY.read().unwrap_or_else(|e| e.into_inner()).contains(&page) +} + /// `page` is unmapped: true if it was never used (nothing to keep of it). -pub(super) fn unmark(page: usize) -> bool { +pub(crate) fn unmark(page: usize) -> bool { LAZY.write().unwrap_or_else(|e| e.into_inner()).remove(&page) } -/// The lazy pages of `[p, p + len)` committed – memory a kernel call or XCL writes. -pub fn ensure(p: usize, len: usize) { +/// `[p, p + len)` is decommitted or released: its lazy pages are not lazy any more. One it +/// covers in part is committed first (the rest of it stays the title's memory). +pub(crate) fn unmark_range(p: usize, len: usize) { + if len == 0 { + return; + } + let end = p.saturating_add(len); + let (whole, part): (Vec, Vec) = { + let g = LAZY.read().unwrap_or_else(|e| e.into_inner()); + if g.is_empty() { + return; + } + g.range(p & !(PAGE - 1)..end).copied().partition(|&x| x >= p && x.saturating_add(PAGE) <= end) + }; + if !whole.is_empty() { + let mut g = LAZY.write().unwrap_or_else(|e| e.into_inner()); + for x in whole { + g.remove(&x); + } + } + for x in part { + unsafe { commit(x) }; + } +} + +/// The lazy pages of `[p, p + len)` committed now (before a call that needs them committed, +/// as VirtualProtect does; no guard is opened). +pub(crate) fn commit_range(p: usize, len: usize) { if len == 0 { return; } @@ -100,6 +140,40 @@ pub fn ensure(p: usize, len: usize) { } } +/// Where the run of lazy pages from `page` (64 KiB aligned) ends (`page` itself: not lazy). +pub fn lazy_run_end(page: usize) -> usize { + let g = LAZY.read().unwrap_or_else(|e| e.into_inner()); + let mut end = page; + for &x in g.range(page..) { + if x != end { + break; + } + end += PAGE; + } + end +} + +/// The lazy pages of `[p, p + len)` committed – memory a kernel call or XCL writes. Views of +/// physical pages there are read-only until written and a kernel call cannot fault: they are +/// opened, and stay open while the returned value lives (hold it across the write). +pub fn ensure(p: usize, len: usize) -> super::guards::Opened { + let opened = super::guards::open(p, len); + if len == 0 { + return opened; + } + let pages: Vec = { + let g = LAZY.read().unwrap_or_else(|e| e.into_inner()); + if g.is_empty() { + return opened; + } + g.range(p & !(PAGE - 1)..p.saturating_add(len)).copied().collect() + }; + for page in pages { + unsafe { commit(page) }; + } + opened +} + #[cfg(test)] mod tests { use super::*; @@ -117,7 +191,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/hle/xg.rs b/crates/xcl/src/hle/xg.rs index 0eec7dc16e..c7464b049c 100644 --- a/crates/xcl/src/hle/xg.rs +++ b/crates/xcl/src/hle/xg.rs @@ -108,6 +108,15 @@ pub struct Texture { pub empty: bool, /// D3D12_RESOURCE_DIMENSION dimension: u32, + /// tiled resource (D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE or console tiled flag bit 27) + tiled_resource: bool, +} + +/// Whether `mode` is one of the 7 GFX10 depth/stencil Z swizzle modes accepted by +/// `XGValidateDepthStencilSwizzleMode` (`4KB_Z`, `64KB_Z`, `4KB_Z_T`, `VAR_Z`, `4KB_Z_X`, +/// `64KB_Z_X`, `VAR_Z_X`). +pub fn is_depth_stencil_swizzle_mode(mode: u32) -> bool { + matches!(mode, 4 | 8 | 12 | 16 | 20 | 24 | 28) } /// (log2 bytes per element, pixels per element side) of a DXGI format; None for the 96-bit @@ -187,7 +196,7 @@ impl Texture { // is left empty. Render target + depth flags: a render target in a Z mode, unless the // format has a stencil let depth_buffer = ds && mips == 1 && (planar || !rt); - if depth_buffer && mode != 24 { + if depth_buffer && !is_depth_stencil_swizzle_mode(mode) { return Err(E_INVALIDARG); } let depth_format = planar || matches!(format, 39 | 40 | 53 | 55); @@ -232,7 +241,8 @@ impl Texture { Plane { usage, offset: at, kind } }) .collect(); - Ok(Texture { planes, main: main_at, mips, empty, dimension: dim }) + let tiled_resource = layout == 2 || (flags & (1 << 27)) != 0; + Ok(Texture { planes, main: main_at, mips, empty, dimension: dim, tiled_resource }) } /// A 3D texture: one plane of texels, 4KB_S unless the layout names a mode or it is a UAV @@ -265,7 +275,8 @@ impl Texture { let chain = Chain::new_3d(l, width as u32, height, depth, side, mips); let first_tail = chain.levels.iter().position(|m| m.tail.is_some()).unwrap_or(chain.levels.len()); let s = Surface { chain, mode, bpe: 1 << e, side, width: width as u32, height, array: 1, depth, first_tail }; - Ok(Texture { planes: vec![Plane { usage: 1, offset: 0, kind: PlaneKind::Surface(s) }], main: 0, mips, empty: false, dimension: 4 }) + let tiled_resource = layout == 2 || (flags & (1 << 27)) != 0; + Ok(Texture { planes: vec![Plane { usage: 1, offset: 0, kind: PlaneKind::Surface(s) }], main: 0, mips, empty: false, dimension: 4, tiled_resource }) } pub fn size(&self) -> u64 { @@ -359,6 +370,7 @@ impl Surface { match mode { 0 | 1 | 2 | 5 | 6 | 9 | 10 | 17 | 18 | 21 | 22 | 25 | 26 | 27 => {} 24 if e <= 3 && !bc => {} + 4 | 8 | 12 | 16 | 20 | 28 if e <= 3 && !bc => return Err(E_NOTIMPL), 28 | 31 => return Err(E_NOTIMPL), _ => return Err(E_INVALIDARG), } @@ -500,6 +512,8 @@ fn vtbl() -> &'static [usize] { let (stub, _) = crate::stubs::make_stub_info("xg_xs.dll", &format!("XGTextureAddressComputer::#{i}"), E_NOTIMPL as u32 as u64); v.push(stub); } + // Slot 12: IsTiledResource (returns bool/u32 from the resource's tiled-resource flag). + v.push(is_tiled_resource as usize); Box::leak(v.into_boxed_slice()) }) } @@ -589,7 +603,7 @@ unsafe extern "system" fn get_alignment(p: *mut c_void) -> u64 { unsafe extern "system" fn get_mip_offset(p: *mut c_void, plane: u32, mip: u32) -> u64 { match tex(p).plane_surface(plane) { Some((s, at)) if (mip as usize) < s.chain.levels.len() => at + s.mip_offset(mip as usize), - _ => 0, + _ => u64::MAX, } } @@ -599,10 +613,14 @@ unsafe extern "system" fn get_texel_offset(p: *mut c_void, plane: u32, mip: u32, } match tex(p).plane_surface(plane) { Some((s, at)) if (mip as usize) < s.chain.levels.len() && slice < s.slices(mip as usize).0 => at + s.element_offset(mip as usize, x as usize, y as usize, slice as usize), - _ => 0, + _ => u64::MAX, } } +unsafe extern "system" fn is_tiled_resource(p: *mut c_void) -> u32 { + u32::from(tex(p).tiled_resource) +} + unsafe extern "system" fn not_implemented(_p: *mut c_void) -> HRESULT { E_NOTIMPL } @@ -783,4 +801,46 @@ mod tests { assert_eq!((t.size(), t.alignment()), (rgb10a2.size(), rgb10a2.alignment())); } } + + #[test] + fn computer_vtable_has_13_slots_and_invalid_offsets_return_u64_max() { + assert_eq!(vtbl().len(), 13, "XGTextureAddressComputer exposes slots 0..=12"); + let d = desc(64, 64, 1, 2, 28, 0x109); + let mut comp = std::ptr::null_mut(); + assert_eq!(unsafe { XGCreateTextureComputer(d.as_ptr(), &mut comp) }, S_OK); + assert!(!comp.is_null()); + unsafe { + assert_eq!(get_mip_offset(comp, 99, 0), u64::MAX); + assert_eq!(get_mip_offset(comp, 0, 99), u64::MAX); + assert_eq!(get_texel_offset(comp, 99, 0, 0, 0, 0, 0, std::ptr::null_mut()), u64::MAX); + assert_eq!(get_texel_offset(comp, 0, 99, 0, 0, 0, 0, std::ptr::null_mut()), u64::MAX); + assert_eq!(get_texel_offset(comp, 0, 0, 0, 0, 99, 0, std::ptr::null_mut()), u64::MAX); + assert_eq!(is_tiled_resource(comp), 0); + assert_eq!(release(comp), 0); + } + let tiled = desc(64, 64, 1, 1, 28, 2); + let mut comp_tiled = std::ptr::null_mut(); + assert_eq!(unsafe { XGCreateTextureComputer(tiled.as_ptr(), &mut comp_tiled) }, S_OK); + unsafe { + assert_eq!(is_tiled_resource(comp_tiled), 1); + assert_eq!(release(comp_tiled), 0); + } + } + + #[test] + fn depth_stencil_swizzle_modes_distinguish_valid_z_modes_from_invalid() { + for z in [4u32, 8, 12, 16, 20, 24, 28] { + assert!(is_depth_stencil_swizzle_mode(z), "Z mode {z} must be valid"); + } + assert!(!is_depth_stencil_swizzle_mode(25)); + // Valid but unmodelled Z modes return E_NOTIMPL on depth buffers, while non-Z modes return E_INVALIDARG. + for z in [4u32, 8, 12, 16, 20, 28] { + let mut d = desc(256, 256, 1, 1, 40, 0x100 | z); + d[0x30..0x34].copy_from_slice(&2u32.to_le_bytes()); // ALLOW_DEPTH_STENCIL + assert_eq!(Texture::new(&d).err(), Some(E_NOTIMPL), "Z mode {z} should return E_NOTIMPL"); + } + let mut bad = desc(256, 256, 1, 1, 40, 0x100 | 25); + bad[0x30..0x34].copy_from_slice(&2u32.to_le_bytes()); + assert_eq!(Texture::new(&bad).err(), Some(E_INVALIDARG), "non-Z mode 25 must fail with E_INVALIDARG"); + } } diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 444333d891..71686fc8e9 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -8,6 +8,18 @@ use crate::config::Boot; pub static HOST_MODE: AtomicBool = AtomicBool::new(false); +/// System-wide virtual commit `(used_mb, limit_mb)` via `GlobalMemoryStatusEx`. +pub(crate) fn system_commit() -> (u64, u64) { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + if unsafe { GlobalMemoryStatusEx(&mut m) } == 0 { + return (0, 0); + } + let used = m.ullTotalPageFile.saturating_sub(m.ullAvailPageFile); + (used >> 20, m.ullTotalPageFile >> 20) +} + pub fn host_main(boot_path: &Path) -> i32 { let boot: Boot = match std::fs::read_to_string(boot_path).map_err(|e| e.to_string()).and_then(|s| serde_json::from_str(&s).map_err(|e| e.to_string())) { Ok(b) => b, @@ -36,6 +48,11 @@ 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()); + if let Err(e) = crate::hle::d3d12x::present::preparation::before_guest(&boot) { + crate::xlog_error!("Shader preparation: {e}"); + eprintln!("xcl: {e}"); + return 2; + } let _ = std::thread::Builder::new().name("xcl-split-counts".into()).spawn(|| loop { std::thread::sleep(std::time::Duration::from_secs(10)); crate::hle::d3d12x::real::log_dispatch_chain_counts(); @@ -51,14 +68,42 @@ pub fn host_main(boot_path: &Path) -> i32 { [p, e, d, x, f[0], f[1], f[2], f[3], r, b >> 20, fail] }; let mut last = snap(); + let mut prof_last = crate::hle::d3d12x::prof::totals(); loop { std::thread::sleep(std::time::Duration::from_secs(2)); + // a device removed while every title thread waits: nothing else would ask + crate::hle::d3d12x::real::stop_if_device_removed(); + // the GPU's work in flight when no frame came for 6 s (`XCL_GPU_CULPRIT=1`) + static IDLE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let frames = crate::hle::d3d12x::present::counters().1; + let o = std::sync::atomic::Ordering::Relaxed; + if SEEN.swap(frames, o) != frames || frames < 100 { + IDLE.store(0, o); + } else { + let idle = IDLE.fetch_add(1, o); + if idle == 2 { + crate::hle::d3d12x::culprit::on_watchdog_release(); + } + // `XCL_STALL_DUMP=1`: where every thread is, 8 s into a stall (3 stalls at most) + static DUMPS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if idle == 3 && std::env::var("XCL_STALL_DUMP").is_ok_and(|v| v.trim() == "1") && DUMPS.fetch_add(1, o) < 3 { + crate::xlog_info!("no frame for 8 s: thread dump"); + crate::eh::dump_threads(); + } + } let now = snap(); let d: Vec = now.iter().zip(last).map(|(a, b)| a - b).collect(); crate::xlog_info!( "activity (2 s): {} presents, {} submits, {} draws, {} dispatches, {} frame-event waits ({} timed out), {} frame statistics ({} not flipped); DirectStorage {} requests, {} MB, {} failed", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], d[8], d[9], d[10] ); + // where the title's threads waited in XCL meanwhile (`d3d12x::prof`) + let prof_now = crate::hle::d3d12x::prof::totals(); + crate::xlog_info!("{}", crate::hle::d3d12x::prof::line(prof_last, prof_now, d[0], 2.0)); + prof_last = prof_now; + // tile mappings, resources made and the video memory budget (`d3d12x::flight`) + crate::xlog_info!("{}", crate::hle::d3d12x::flight::line()); // where the memory is: the process's commit, video memory, and XCL's parts of it let private = unsafe { use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; @@ -71,6 +116,9 @@ pub fn host_main(boot_path: &Path) -> i32 { let (arenas, arenas_made) = crate::hle::d3d12x::vram::arena_bytes(); let (pools, pools_mapped) = crate::hle::d3d12x::sparse::pool_bytes(); let (pages, page_pools) = crate::hle::d3d12x::vram::page_bytes(); + if let Some(t) = crate::hle::d3d12x::real::committed_report() { + crate::xlog_info!("committed since the last line: {t}"); + } let mb = |b: u64| b >> 20; crate::xlog_info!( "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped)", @@ -84,6 +132,14 @@ pub fn host_main(boot_path: &Path) -> i32 { mb(pools as u64), mb(pools_mapped as u64) ); + // the same against DXGI's budget, by owner, with what XCL does not count (#2688) + crate::xlog_info!("{}", crate::hle::d3d12x::memory_report::snapshot().line()); + crate::xlog_info!("memory: the title's committed resources alive (MB): {}", crate::hle::d3d12x::real::live_committed_line()); + // and every 10 s where the rest is: the address space walked + static WALKS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if WALKS.fetch_add(1, o) % 5 == 0 { + crate::xlog_info!("{}", crate::hle::d3d12x::memory_report::walk_line()); + } last = now; } }); @@ -109,6 +165,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); @@ -146,6 +203,7 @@ pub fn host_main(boot_path: &Path) -> i32 { Err(e) => { crate::xlog_error!("loading the game failed: {e}"); crate::report::write_final(Some(format!("loader: {e}"))); + crate::hle::kernelx::restore_fine_timer(); return 0x7C1_0002; } }; @@ -153,7 +211,9 @@ 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(); + crate::hle::kernelx::restore_fine_timer(); code as i32 } diff --git a/crates/xcl/src/launcher.rs b/crates/xcl/src/launcher.rs index 00a9cb1f87..c328c22750 100644 --- a/crates/xcl/src/launcher.rs +++ b/crates/xcl/src/launcher.rs @@ -6,6 +6,7 @@ use std::path::{Path, PathBuf}; use crate::config::{Boot, Config}; use crate::util::wide; + /// Data root: `%XCL_DATA_ROOT%` or `%LOCALAPPDATA%\XCL`. pub fn data_root() -> PathBuf { if let Ok(p) = std::env::var("XCL_DATA_ROOT") { @@ -286,6 +287,14 @@ fn quote(a: &str) -> String { } pub fn run(target: &Path, args: &[String]) -> i32 { + run_with_ui(target, args, false) +} + +pub fn run_from_menu(target: &Path) -> i32 { + run_with_ui(target, &[], true) +} + +fn run_with_ui(target: &Path, args: &[String], menu: bool) -> i32 { let (root, explicit_exe, title) = match resolve_location(target) { Ok(x) => x, Err(e) => { @@ -388,7 +397,7 @@ pub fn run(target: &Path, args: &[String]) -> i32 { cmdline.push(' '); cmdline.push_str("e(a)); } - let code = match spawn_host(&cmdline, &root, &boot_path) { + let code = match spawn_host(&cmdline, &root, &boot_path, menu) { Ok(c) => c, Err(e) => { eprintln!("xcl: failed to start the game process: {e}"); @@ -448,12 +457,20 @@ pub fn missing_console_cpu_features() -> Vec<&'static str> { }) } -fn spawn_host(cmdline: &str, cwd: &Path, boot_path: &Path) -> Result { +fn spawn_host(cmdline: &str, cwd: &Path, boot_path: &Path, menu: bool) -> Result { use windows_sys::Win32::Foundation::{CloseHandle, GetLastError}; use windows_sys::Win32::System::Threading::{ CreateProcessW, GetExitCodeProcess, WaitForSingleObject, INFINITE, PROCESS_INFORMATION, STARTUPINFOW, }; + use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; + use windows_sys::Win32::System::Threading::{GetCurrentProcessId, OpenProcess, PROCESS_SYNCHRONIZE}; let me = std::env::current_exe().map_err(|e| e.to_string())?; + // An inheritable, synchronize-only handle identifies this exact launcher even after PID reuse. + let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 1, GetCurrentProcessId()) }; + if handle.is_null() { return Err(std::io::Error::last_os_error().to_string()); } + let parent = unsafe { OwnedHandle::from_raw_handle(handle) }; + std::env::set_var("XCL_PREPARATION_PARENT", (parent.as_raw_handle() as usize).to_string()); + if menu { std::env::set_var("XCL_PREPARATION_MENU", "1"); } std::env::set_var("XCL_HOST", boot_path); let app = wide(&me.to_string_lossy()); let mut cmd = wide(cmdline); @@ -474,9 +491,12 @@ fn spawn_host(cmdline: &str, cwd: &Path, boot_path: &Path) -> Result i32 { let _ = std::fs::create_dir_all(xcl::launcher::data_root()); let _ = std::fs::write(&last_file, target.to_string_lossy().as_bytes()); println!("xcl run \"{}\"", target.display()); - let code = xcl::launcher::run(&target, &[]); + let code = xcl::launcher::run_from_menu(&target); if code != 0 { println!("\nXCL ended with code {code}. Press Enter to close."); let _ = std::io::stdin().read_line(&mut String::new()); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 0cd2ed7b3a..a0a0a524e2 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -815,6 +815,8 @@ struct ShadersOptions { only: Option, pipelines: bool, used_only: bool, + /// `--graphics-records`: the path is a job file of `graphics_in_workers` (`graphics_worker`) + graphics_records: bool, direct: bool, sample: usize, seed: u64, @@ -850,6 +852,7 @@ fn parse_args(args: &[String]) -> Result { only: None, pipelines: false, used_only: false, + graphics_records: false, direct: false, sample: 200, seed: 1, @@ -888,6 +891,7 @@ fn parse_args(args: &[String]) -> Result { "--only" => opts.only = Some(p.value("--only")?.to_ascii_lowercase()), "--pipelines" => opts.pipelines = true, "--used-only" => opts.used_only = true, + "--graphics-records" => opts.graphics_records = true, "--direct" => opts.direct = true, "--sample" => opts.sample = p.parse_usize("--sample")?, "--seed" => opts.seed = p.parse_u64("--seed")?, @@ -906,6 +910,14 @@ fn parse_args(args: &[String]) -> Result { Ok(opts) } +fn runtime_windows_flags(windows: u32, heap_windows: bool, heap_flat: bool) -> u32 { + if windows > 1 && heap_windows { + windows | recomp::HEAP_WINDOWS | if heap_flat { recomp::HEAP_FLAT } else { 0 } + } else { + windows + } +} + pub fn run(path: &Path, args: &[String]) -> i32 { let opts = match parse_args(args) { Ok(o) => o, @@ -915,11 +927,11 @@ pub fn run(path: &Path, args: &[String]) -> i32 { } }; // the runtime's memory windows: from the descriptor heap with `XCL_HEAP_WINDOWS=1` - // (`pso::mem_windows`), as `--precompile` - let runtime_windows = || { - let windows = opts.windows; - if windows > 1 && recomp::pso::heap_windows() { windows | recomp::HEAP_WINDOWS } else { windows } - }; + // and flat access with `XCL_HEAP_FLAT=1` (`pso::mem_windows`), as `--precompile` + let runtime_windows = || runtime_windows_flags(opts.windows, recomp::pso::heap_windows(), recomp::pso::heap_flat()); + if opts.graphics_records { + return graphics_worker(path, runtime_windows()); + } let top = opts.top; let json = opts.json; let compile = opts.compile; @@ -981,7 +993,10 @@ pub fn run(path: &Path, args: &[String]) -> i32 { let used = opts.used_only.then(crate::hle::d3d12x::pso_async::earlier_used_keys); // the runtime's key: heap windows with `XCL_HEAP_WINDOWS=1` (`pso::mem_windows`) let windows = runtime_windows(); - return precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, used.as_ref(), t0); + return match precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, used.as_ref(), t0, None) { + Ok(()) => 0, + Err(e) => { eprintln!("xcl shaders: {e}"); 2 } + }; } if opts.direct { return direct_sweep(&input, &opts, t0); @@ -1092,7 +1107,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 { @@ -1204,10 +1219,15 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl /// (the > 8 MB HLSL programs DXC compiles at `-O0`, #1269). struct Pipelines { dev: windows::Win32::Graphics::Direct3D12::ID3D12Device, + library: Option, signatures: Mutex), windows::Win32::Graphics::Direct3D12::ID3D12RootSignature>>, made: AtomicUsize, refused: AtomicUsize, reused: AtomicUsize, + lib_reused: AtomicUsize, + lib_stored: AtomicUsize, + /// pipelines another process of the same preparation was building (`Claim`): left to it + elsewhere: AtomicUsize, split_programs: AtomicUsize, split_pieces: AtomicUsize, /// programs over `max_dxil` with no blob yet, and their DXIL bytes @@ -1216,6 +1236,9 @@ struct Pipelines { /// driver compiles running and the most at once (`XCL_PIPELINE_THREADS`, 4): each of the /// biggest takes ~1.5 GB in the driver – fifteen at once took 24 GB running: (Mutex, std::sync::Condvar), + /// Serializes cold offline compiles `>= OFFLINE_GIANT_DXIL` (900 KiB) to 1-at-a-time so + /// multi-threaded `--pipelines` runs never stack multiple giant driver compiles into OOM. + giant: Mutex<()>, most: usize, /// DXIL bytes a pipeline is still handed to the driver (`XCL_PIPELINE_MAX_KB`, 8 MiB; 0: off) max_dxil: usize, @@ -1223,6 +1246,18 @@ struct Pipelines { cache_dir: Option, } +const OFFLINE_LOG_DXIL: usize = 256 << 10; +const OFFLINE_GIANT_DXIL: usize = 900 << 10; + +fn offline_pso_trace() -> bool { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_PSO_TRACE").is_ok_and(|v| v.trim() == "1")) +} + +fn should_log_offline_compile_start(dxil_bytes: usize, trace: bool) -> bool { + trace || dxil_bytes >= OFFLINE_LOG_DXIL +} + /// `XCL_PIPELINE_MAX_KB`: the KiB of DXIL `--pipelines` still compiles (default 8 MiB; 0: no /// cap). Above it sit the programs whose driver compile takes tens of minutes and gigabytes — /// the > 8 MB HLSL programs DXC compiles at `-O0` (#1269) — and they hang the pass. @@ -1243,6 +1278,22 @@ mod pipeline_cap_tests { assert_eq!(pipeline_cap_kb(Some("off")), 8192); } + #[test] + fn offline_pipeline_library_key_matches_runtime_standard_and_split_keys() { + let dxil = b"DXBC-offline-precompile-test"; + let samplers = [([1u32, 2, 3, 4], false)]; + let std_key = crate::hle::d3d12x::real::compute_library_key(dxil, &samplers, 0, false); + let split_key = crate::hle::d3d12x::real::compute_library_key(dxil, &samplers, 0, true); + assert!(std_key.starts_with("c-")); + assert_eq!(split_key, format!("s{std_key}")); + assert_ne!(std_key, split_key); + assert!(!super::should_log_offline_compile_start(super::OFFLINE_LOG_DXIL - 1, false)); + assert!(super::should_log_offline_compile_start(super::OFFLINE_LOG_DXIL, false)); + assert!(super::should_log_offline_compile_start(128, true)); + assert!(crate::hle::d3d12x::real::rt_gated_compute_held(b"HDR\0CS_ScreenProbes_ActivateRays\0")); + assert!(!crate::hle::d3d12x::real::rt_gated_compute_held(b"HDR\0CS_DepthPyramid\0")); + } + #[test] fn stale_blob_cannot_bypass_the_offline_pipeline_cap() { use super::{Pipelines, recomp, Ordering}; @@ -1273,7 +1324,7 @@ mod pipeline_cap_tests { pipelines.max_dxil = dxil.len() - 1; let start = Instant::now(); - pipelines.make_with_cache_path(&recomp::pso::Compiled { dispatch_chain: None, dxil: dxil.clone(), samplers: vec![] }, Some(path.clone())); + pipelines.make_with_cache_path(&recomp::pso::Compiled { dispatch_chain: None, dxil: dxil.clone().into(), samplers: vec![] }, Some(path.clone())); let elapsed = start.elapsed(); let capped = pipelines.capped.load(Ordering::Relaxed); let made = pipelines.made.load(Ordering::Relaxed); @@ -1352,7 +1403,7 @@ mod pipeline_cap_tests { pieces: vec![piece0.clone(), piece1.clone()], dwords_per_group: 4, })), - dxil: whole.clone(), + dxil: whole.clone().into(), samplers: vec![], }; @@ -1411,27 +1462,47 @@ mod pipeline_cap_tests { unsafe impl Sync for Pipelines {} impl Pipelines { - fn new() -> Result { + fn new() -> Result { Self::for_adapter("auto") } + + fn for_adapter(adapter: &str) -> Result { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; use windows::Win32::Graphics::Dxgi::*; 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("auto"); - let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; - let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?; + let sel = crate::gpu::adapter::Selector::from_env_or(adapter); + let (dev, library) = 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())?, None) + } else { + let (adapter, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + crate::hle::d3d12x::real::driver_cache::note_vendor(desc.VendorId); + let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?; + // Match `real::init`'s adapter string verbatim so offline `--precompile --pipelines` + // opens and populates the exact same `pso-library//gen-*.plib` directory. + let adapter_name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20); + let library = (!cfg!(test)) + .then(|| crate::hle::d3d12x::pso_library::MmapPipelineLibrary::open_or_create(&dev, &adapter_name)) + .flatten(); + (dev, library) + }; let most = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4usize).max(1); let max_dxil = pipeline_cap_kb(std::env::var("XCL_PIPELINE_MAX_KB").ok().as_deref()).saturating_mul(1024); Ok(Pipelines { dev, + library, signatures: Mutex::new(Default::default()), made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), + lib_reused: AtomicUsize::new(0), + lib_stored: AtomicUsize::new(0), + elsewhere: AtomicUsize::new(0), split_programs: AtomicUsize::new(0), split_pieces: AtomicUsize::new(0), capped: AtomicUsize::new(0), capped_bytes: AtomicUsize::new(0), running: (Mutex::new(0), std::sync::Condvar::new()), + giant: Mutex::new(()), most, max_dxil, #[cfg(test)] @@ -1444,11 +1515,21 @@ impl Pipelines { /// 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. + #[cfg(test)] fn make(&self, c: &recomp::pso::Compiled) { - self.make_with_cache_path(c, None); + self.make_with_cache_path_for(c, None, 0); + } + + fn make_record(&self, c: &recomp::pso::Compiled, record: u64) { + self.make_with_cache_path_for(c, None, record); } + #[cfg(test)] fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option) { + self.make_with_cache_path_for(c, path_override, 0); + } + + fn make_with_cache_path_for(&self, c: &recomp::pso::Compiled, path_override: Option, record: u64) { 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); @@ -1456,7 +1537,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(piece, &c.samplers, true, None, record); } } else { let next = AtomicUsize::new(0); @@ -1465,7 +1546,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(piece, &c.samplers, true, None, record); }); } }); @@ -1473,10 +1554,10 @@ impl Pipelines { return; } } - self.make_one(&c.dxil, &c.samplers, false, path_override); + self.make_one(&c.dxil, &c.samplers, false, path_override, record); } - fn make_one(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, path_override: Option) { + fn make_one(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, path_override: Option, record: u64) { 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 = { @@ -1507,6 +1588,32 @@ impl Pipelines { CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const _, BytecodeLength: dxil.len() }, ..Default::default() }; + let lib_key = crate::hle::d3d12x::real::compute_library_key(dxil, samplers, desc.Flags.0, chained); + let has_override = path_override.is_some(); + if !has_override { + if let Some(lib) = self.library.as_ref() { + if unsafe { lib.load_compute(&lib_key, &desc) }.is_some() { + self.lib_reused.fetch_add(1, Ordering::Relaxed); + self.reused.fetch_add(1, Ordering::Relaxed); + let done = self.made.fetch_add(1, Ordering::Relaxed) + 1; + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + if done % 25 == 0 { + eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)); + } + return; + } + } + } + // a pipeline the driver did not come back from in an earlier run is not given to it again + // (`driver_crash`); this one is named there while the driver has it + let crash_key = crate::hle::d3d12x::driver_crash::compute_key(record); + if crate::hle::d3d12x::driver_crash::blocked(&crash_key) { + self.refused.fetch_add(1, Ordering::Relaxed); + eprintln!(" pipeline left out: the driver did not come back from record {record:016x} in an earlier run"); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + return; + } + let _building = crate::hle::d3d12x::driver_crash::building(&crash_key, &[("cs.dxil".to_string(), dxil)]); use crate::hle::d3d12x::real::driver_cache; let path = path_override.or_else(|| { #[cfg(test)] @@ -1515,7 +1622,7 @@ impl Pipelines { } driver_cache::path_for(dxil, desc.Flags.0, chained) }); - let cached = path.as_deref().and_then(driver_cache::load); + let mut cached = path.as_deref().and_then(driver_cache::load); let over_cap = self.max_dxil != 0 && dxil.len() > self.max_dxil; // over the cap and no blob from an earlier run: the driver's compile of this one takes // tens of minutes and gigabytes; the pass finishes without it, and the runtime builds it @@ -1533,6 +1640,26 @@ impl Pipelines { } *n += 1; } + // (another process may have written the blob while this one waited for its turn) + if cached.is_none() { + cached = path.as_deref().and_then(driver_cache::load); + } + // not in the cache: the one process that claims the pipeline builds it. Records with the + // same program are in several workers' slices, and the driver's compile of one took + // twice as long in each of four workers that built it at once. + let claim = match (&cached, path.as_deref()) { + (None, Some(path)) => match Claim::take(path) { + Some(c) => Some(c), + None => { + *self.running.0.lock().unwrap() -= 1; + self.running.1.notify_one(); + self.elsewhere.fetch_add(1, Ordering::Relaxed); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + return; + } + }, + _ => None, + }; let from_cache = cached.as_ref().and_then(|bytes| { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: bytes.as_ptr().cast(), CachedBlobSizeInBytes: bytes.len() }; // a driver that cannot use the blob may compile from the DXIL itself and still @@ -1558,8 +1685,27 @@ impl Pipelines { self.reused.fetch_add(1, Ordering::Relaxed); Ok(pso) } else { + let _giant = (dxil.len() >= OFFLINE_GIANT_DXIL).then(|| self.giant.lock().unwrap()); + let log_start = should_log_offline_compile_start(dxil.len(), offline_pso_trace()); + if log_start { + eprintln!( + " pipeline compile start: record {record:016x} ({} B DXIL{})", + dxil.len(), + if chained { ", split piece" } else { "" } + ); + } + let started = std::time::Instant::now(); desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let pso = unsafe { self.dev.CreateComputePipelineState::(&desc) }; + let took = started.elapsed(); + if log_start || took >= std::time::Duration::from_secs(2) { + eprintln!( + " pipeline compile finish: record {record:016x} ({} B DXIL, {} ms, {})", + dxil.len(), + took.as_millis(), + if pso.is_ok() { "ok" } else { "refused" } + ); + } if let (Some(path), Ok(pso)) = (path.as_deref(), &pso) { if let Ok(blob) = unsafe { pso.GetCachedBlob() } { let bytes = unsafe { blob.GetBufferPointer() }.cast::(); @@ -1571,17 +1717,31 @@ impl Pipelines { } pso }; + drop(claim); *self.running.0.lock().unwrap() -= 1; self.running.1.notify_one(); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); let done = match r { - Ok(_) => self.made.fetch_add(1, Ordering::Relaxed) + 1, + Ok(pso) => { + if !has_override { + if let Some(lib) = self.library.as_ref() { + if unsafe { lib.store(&lib_key, &pso) } { + self.lib_stored.fetch_add(1, Ordering::Relaxed); + } + } + } + self.made.fetch_add(1, Ordering::Relaxed) + 1 + } Err(_) => self.refused.fetch_add(1, Ordering::Relaxed) + 1, }; if done % 25 == 0 { eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)); } } + + fn flush(&self) -> Option { + unsafe { self.library.as_ref()?.flush() } + } } /// A compute program a title used in an earlier run (`--used-only`): its pipeline's key, as the @@ -1590,55 +1750,570 @@ fn used_compute(blob: &[u8], used: &std::collections::HashSet) -> bool { used.contains(&crate::hle::d3d12x::real::shaders_key(&[blob.to_vec()])) } -fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant) -> i32 { - let pipelines = if pipelines { - match Pipelines::new() { - Ok(p) => Some(p), +#[derive(Default)] +pub(crate) struct LaunchPreparation { + pub adapter: String, + pub done: AtomicUsize, + pub total: AtomicUsize, + pub cancel: std::sync::atomic::AtomicBool, + /// The worker processes building compute pipelines (0: none; `done` and `total` then count + /// the records translated here, with them the records the workers have passed). + pub workers: AtomicUsize, + /// The workers build graphics pipelines (`graphics_in_workers`): `done` and `total` count those. + pub graphics: std::sync::atomic::AtomicBool, + /// 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. + pub only: Option>, +} + +/// Unpacked shader containers in the title's shaders directory. Do not follow directory +/// junctions into another tree or back into the shader directory. +fn loose_inputs(dir: &Path, files: &mut Vec) -> std::io::Result<()> { + use std::os::windows::fs::MetadataExt; + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + let metadata = entry.metadata()?; + if metadata.file_attributes() & windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT != 0 { continue; } + let path = entry.path(); + if metadata.is_dir() { + loose_inputs(&path, files)?; + } else if path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("dxbc")) { + files.push(path); + } + } + Ok(()) +} + +pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> Result<(), String> { + let mut inputs = Vec::new(); + let pack = root.join("shaders.rpf"); + if pack.try_exists().map_err(|e| e.to_string())? { + let data = std::fs::read(&pack).map_err(|e| format!("Reading {}: {e}", pack.display()))?; + if !data.starts_with(pack::RPF9_MAGIC) { return Err(format!("Unrecognized shader pack: {}", pack.display())); } + let records = pack::scan(&data, 0x40); + if records.is_empty() { return Err(format!("No readable shader records in {}", pack.display())); } + inputs.push(Input::Pack { data, records }); + } + let loose = root.join("shaders"); + if loose.is_dir() { + let mut files = Vec::new(); + loose_inputs(&loose, &mut files).map_err(|e| format!("Reading {}: {e}", loose.display()))?; + if !files.is_empty() { inputs.push(Input::Files(files)); } + } + 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; } + let workers = prepare_workers(); + for input in &inputs { + if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + // a pack: its stages here, its compute pipelines in worker processes (the driver builds + // about two pipelines at a time for one process, whatever the processors) + if workers > 1 && matches!(input, Input::Pack { .. }) { + let n = input.len(); + precompile(input, usize::MAX, windows, None, None, false, None, std::time::Instant::now(), Some(progress))?; + if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + pipelines_in_workers(&pack, windows, workers, n, progress)?; + continue; + } + precompile(input, usize::MAX, windows, None, None, true, None, std::time::Instant::now(), Some(progress))?; + } + if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + // `XCL_PREPARE_GRAPHICS=0`: the title builds the graphics pipelines it uses as it goes + if std::env::var("XCL_PREPARE_GRAPHICS").is_ok_and(|v| v.trim() == "0") { + crate::xlog_info!("Shader preparation: graphics pipelines left out (XCL_PREPARE_GRAPHICS=0)"); + return Ok(()); + } + graphics_in_workers(&inputs, windows, workers, progress) +} + +/// `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. +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()); + let (used, limit) = crate::host::system_commit(); + workers_for(cores, limit.saturating_sub(used)) +} + +/// 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 record count of a builder's progress line (` 400/26503 (12 s)`). +fn progress_count(line: &str) -> Option { + let (d, rest) = line.trim().split_once('/')?; + let (n, rest) = rest.split_once(' ')?; + n.parse::().ok()?; + if !rest.starts_with('(') { return None; } + d.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`. +struct Claim(PathBuf); + +impl Claim { + const STALE: std::time::Duration = std::time::Duration::from_secs(30 * 60); + + /// None: another process has it. + fn take(blob: &std::path::Path) -> Option { + let mut name = blob.as_os_str().to_owned(); + name.push(".claim"); + let path = PathBuf::from(name); + let make = || std::fs::OpenOptions::new().write(true).create_new(true).open(&path); + match make() { + Ok(_) => Some(Claim(path)), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { + let old = std::fs::metadata(&path).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > Self::STALE); + (old && std::fs::remove_file(&path).is_ok() && make().is_ok()).then(|| Claim(path)) + } + // (the folder cannot be written: nothing is shared through it either) + Err(_) => Some(Claim(PathBuf::new())), + } + } +} + +impl Drop for Claim { + fn drop(&mut self) { + if !self.0.as_os_str().is_empty() { + let _ = std::fs::remove_file(&self.0); + } + } +} + +#[cfg(test)] +mod claim_tests { + use super::Claim; + + /// The first process to ask builds a pipeline, a second one leaves it, and it is free again + /// when the first is done. + #[test] + fn a_pipeline_is_claimed_by_one_builder_at_a_time() { + let dir = std::env::temp_dir().join(format!("xcl-claim-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let blob = dir.join("0123.pso"); + let first = Claim::take(&blob).expect("free"); + assert!(dir.join("0123.pso.claim").exists()); + assert!(Claim::take(&blob).is_none(), "claimed"); + assert!(Claim::take(&dir.join("4567.pso")).is_some(), "another pipeline is free"); + drop(first); + assert!(!dir.join("0123.pso.claim").exists()); + assert!(Claim::take(&blob).is_some(), "free again"); + let _ = std::fs::remove_dir_all(&dir); + } +} + +/// The compute pipelines of `pack` built by `workers` processes of this program, each on its own +/// slice of the records (`XCL_PRECOMPILE_SLICE`): only the ones an earlier run of the title used +/// when that list exists (the title builds another when it first uses it). Their records count +/// into `progress`. A worker that fails is noted and the title starts all the same: it builds +/// what is missing itself. +fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usize, progress: &LaunchPreparation) -> Result<(), String> { + let me = std::env::current_exe().map_err(|e| e.to_string())?; + let used_only = !crate::hle::d3d12x::pso_async::earlier_used_keys().is_empty(); + let t0 = std::time::Instant::now(); + 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()); + if used_only { c.arg("--used-only"); } + c.env("XCL_PRECOMPILE_SLICE", format!("{i}/{workers}")); + c + }); + if cancelled { return Err("Shader preparation cancelled".into()); } + crate::xlog_info!("Shader preparation: compute pipelines done in {:.0} s ({failed} of {workers} workers failed)", t0.elapsed().as_secs_f64()); + Ok(()) +} + +/// A preparation worker: this program, not a host and not a launcher's child, a builder that +/// ends when this process does. +fn worker_command(me: &Path) -> std::process::Command { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let mut c = std::process::Command::new(me); + for gone in ["XCL_HOST", "XCL_PREPARATION_PARENT", "XCL_PREPARATION_MENU", "XCL_RUN_SECONDS"] { c.env_remove(gone); } + c.env("XCL_PRECOMPILE_PARENT", std::process::id().to_string()); + if std::env::var_os("XCL_DXC_THREADS").is_none() { c.env("XCL_DXC_THREADS", "2"); } + if std::env::var_os("XCL_PIPELINE_THREADS").is_none() { c.env("XCL_PIPELINE_THREADS", "1"); } + c.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped()).creation_flags(CREATE_NO_WINDOW); + c +} + +/// `workers` worker processes (`command(i)`), their progress lines (`progress_count`, each of its +/// own part) the count of `records` in all on the screen while they run: whether preparation was +/// cancelled (they are ended then), how many failed, and the summary line each wrote last +/// (`graphics_summary`). +/// +/// A worker that fails has its part done again once the others are through, and counts as failed +/// only when that fails too. A driver gives only so many processes a device at once (an AMD one: +/// nine; the tenth `D3D12CreateDevice` and every one after it returns 0x887A0005), so with ten +/// workers beside the title's own device two ended at once, every start, and the title built +/// their fifth of the pipelines itself while it loaded its world. +fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut command: impl FnMut(usize) -> std::process::Command) -> (bool, usize, Vec) { + use std::io::BufRead; + // the workers' pass has its own count on the screen: the records they have passed + 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.workers.store(workers, Ordering::Relaxed); + let counts: Vec = (0..workers).map(|_| AtomicUsize::new(0)).collect(); + let summaries: Vec> = (0..workers).map(|_| Mutex::new(String::new())).collect(); + let mut parts: Vec = (0..workers).collect(); + let (mut cancelled, mut failed) = (false, Vec::new()); + for again in [false, true] { + failed.clear(); + let mut children = Vec::new(); + for &i in &parts { + match command(i).spawn() { + Ok(child) => children.push((i, child)), Err(e) => { - eprintln!("xcl shaders --pipelines: no GPU device: {e}"); - return 2; + failed.push(i); + crate::xlog_warn!("Shader preparation: worker {i} did not start: {e}"); + } + } + } + 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]); + 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 graphics_summary(part).is_some() { *summary.lock().unwrap() = part.to_string(); } + } + buf.clear(); + } + }); + } + loop { + // (a worker counts the records of its own slice) + let d: usize = counts.iter().map(|c| c.load(Ordering::Relaxed)).sum(); + progress.done.store(d.min(records), Ordering::Relaxed); + if progress.cancel.load(Ordering::Relaxed) { + for (_, child) in children.iter_mut() { let _ = child.kill(); } + return true; + } + if children.iter_mut().all(|(_, child)| !matches!(child.try_wait(), Ok(None))) { return false; } + std::thread::sleep(std::time::Duration::from_millis(100)); + } + }); + let note = if again || cancelled { "" } else { " – its part is done again after the others" }; + for (i, child) in children.iter_mut() { + match child.wait() { + Ok(st) if st.success() => {} + Ok(st) => { failed.push(*i); crate::xlog_warn!("Shader preparation: worker {i} ended with {st}{note}"); } + Err(e) => { failed.push(*i); crate::xlog_warn!("Shader preparation: worker {i}: {e}{note}"); } + } + } + if cancelled || failed.is_empty() { + break; + } + parts = failed.clone(); + } + progress.workers.store(0, Ordering::Relaxed); + progress.total.store(total_before, Ordering::Relaxed); + progress.done.store(done_before, Ordering::Relaxed); + (cancelled, failed.len(), summaries.into_iter().map(|s| s.into_inner().unwrap()).collect()) +} + +#[cfg(test)] +mod worker_tests { + use super::*; + + /// A worker that fails has its part done again once the others are through, and only a part + /// that fails twice counts as failed. + #[test] + fn a_failed_workers_part_is_done_again() { + let exits = |code: i32| { + let mut c = std::process::Command::new("cmd"); + c.args(["/c", "exit", &code.to_string()]).stderr(std::process::Stdio::piped()); + c + }; + let progress = LaunchPreparation::default(); + // worker 1 fails the first time (as one a driver gave no device), worker 2 both times + let mut started = [0usize; 3]; + let (cancelled, failed, summaries) = in_workers(3, 30, &progress, |i| { + started[i] += 1; + exits(if i == 2 || (i == 1 && started[1] == 1) { 3 } else { 0 }) + }); + assert!(!cancelled); + assert_eq!(started, [1, 2, 2], "the parts of the workers that failed are started again, the other is not"); + assert_eq!(failed, 1, "only the part that failed twice"); + assert_eq!(summaries.len(), 3); + } +} + +/// The graphics pipelines earlier runs used (`gfx_records`), built before the title starts by +/// `workers` processes of this program (`graphics_worker`) the way the title builds them, so the +/// title finds their translations and driver blobs on disk and builds each in milliseconds. In +/// worker processes as the compute pipelines: the driver builds about two pipelines at a time for +/// one process, and a driver that ends a worker ends no title. Their shaders come from the title's +/// shader files (`inputs`) by key, as those of `used-shaders.txt`; each worker gets a file of its +/// part (`gfx_records`' format, with the shaders it needs). A failure is noted and the title +/// starts all the same: it builds what is missing itself. +fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: &LaunchPreparation) -> Result<(), String> { + use crate::hle::d3d12x::gfx_records::{self, Entry}; + let t0 = std::time::Instant::now(); + let payloads = gfx_records::read(&gfx_records::path()); + let records: Vec<(Vec, gfx_records::Record)> = payloads.into_iter().filter_map(|p| match gfx_records::decode(&p) { Some(Entry::Pipeline(r)) => Some((p, r)), _ => None }).collect(); + if records.is_empty() { + crate::xlog_info!("Shader preparation: no graphics pipelines of an earlier run to build"); + return Ok(()); + } + let shaders = shaders_by_key(inputs, records.iter().flat_map(|(_, r)| r.shaders).filter(|&k| k != 0).collect(), progress); + if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + let (buildable, missing) = buildable(records.iter().map(|(_, r)| r), &shaders); + if missing != 0 { + crate::xlog_info!("Shader preparation: {missing} of {} graphics pipelines left out (their shaders are not in the title's shader files)", records.len()); + } + if buildable.is_empty() { return Ok(()); } + let workers = workers.clamp(1, buildable.len()); + // each worker's part, with the shaders it needs (removed when they are done) + let mut jobs = Vec::new(); + for i in 0..workers { + let path = std::env::temp_dir().join(format!("xcl-prepare-{}-{i}.bin", std::process::id())); + let _ = std::fs::remove_file(&path); + let mut w = gfx_records::Writer::open(&path, u64::MAX).map_err(|e| format!("{}: {e}", path.display()))?; + let part: Vec = buildable.iter().copied().skip(i).step_by(workers).collect(); + let mut keys = HashSet::new(); + for &k in &part { + w.add(&records[k].0).map_err(|e| format!("{}: {e}", path.display()))?; + keys.extend(records[k].1.shaders.into_iter().filter(|&s| s != 0)); + } + for key in keys { + w.add(&gfx_records::shader_entry(key, &shaders[&key])).map_err(|e| format!("{}: {e}", path.display()))?; + } + jobs.push((path, part.len())); + } + let me = std::env::current_exe().map_err(|e| e.to_string())?; + crate::xlog_info!("Shader preparation: the {} graphics pipelines earlier runs used, in {workers} worker processes", buildable.len()); + 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()); + // (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 + }); + progress.graphics.store(false, Ordering::Relaxed); + for (path, _) in &jobs { let _ = std::fs::remove_file(path); } + if cancelled { return Err("Shader preparation cancelled".into()); } + let sum = summaries.iter().filter_map(|s| graphics_summary(s)).fold([0usize; 4], |a, b| std::array::from_fn(|k| a[k] + b[k])); + crate::xlog_info!( + "Shader preparation: graphics pipelines done in {:.0} s: {} made, {} failed; driver blobs: {} from disk, {} kept ({failed} of {workers} workers failed)", + t0.elapsed().as_secs_f64(), sum[0], sum[1], sum[2], sum[3] + ); + Ok(()) +} + +/// The bytes of the shaders `wanted` (`real::shader_key`) in the title's shader files, looked +/// for on every processor. +fn shaders_by_key(inputs: &[Input], wanted: HashSet, progress: &LaunchPreparation) -> std::collections::HashMap> { + let found = Mutex::new(std::collections::HashMap::new()); + let threads = std::thread::available_parallelism().map_or(4, |n| n.get()); + for input in inputs { + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= input.len() || progress.cancel.load(Ordering::Relaxed) { break; } + let Some(blob) = input.get(i).1 else { continue }; + let key = crate::hle::d3d12x::real::shader_key(&blob); + if wanted.contains(&key) { found.lock().unwrap().insert(key, blob); } + }); } + }); + } + found.into_inner().unwrap() +} + +/// The records (by their index) whose shaders are all in `shaders` and make their set's key, and +/// how many are not. +fn buildable<'a>(records: impl Iterator, shaders: &std::collections::HashMap>) -> (Vec, usize) { + let (mut ok, mut missing) = (Vec::new(), 0); + for (i, r) in records.enumerate() { + let blobs: Option>> = r.shaders.iter().filter(|&&k| k != 0).map(|k| shaders.get(k).cloned()).collect(); + match blobs { + Some(b) if crate::hle::d3d12x::real::shaders_key(&b) == r.key => ok.push(i), + _ => missing += 1, + } + } + (ok, missing) +} + +/// The counts of a graphics worker's last line (`graphics pipelines: 5 made, 1 failed; driver +/// blobs: 2 from disk, 3 kept`): made, failed, blobs from disk, blobs kept. +fn graphics_summary(line: &str) -> Option<[usize; 4]> { + let rest = line.trim().strip_prefix("graphics pipelines: ")?; + let mut n = rest.split(|c: char| !c.is_ascii_digit()).filter(|s| !s.is_empty()).map(|s| s.parse::()); + let out = [n.next()?.ok()?, n.next()?.ok()?, n.next()?.ok()?, n.next()?.ok()?]; + n.next().is_none().then_some(out) +} + +/// `xcl shaders --graphics-records` (a worker of `graphics_in_workers`): the graphics +/// pipelines of a job file built as the title builds them (`real::prepare_graphics`), with the +/// title's memory windows (`windows`) and on its adapter (`XCL_ADAPTER`), `XCL_PIPELINE_THREADS` +/// at a time. A progress line a pipeline, then the summary `graphics_summary` reads. +fn graphics_worker(job: &Path, windows: u32) -> i32 { + use crate::hle::d3d12x::gfx_records::{self, Entry}; + end_with_parent(); + // (no title memory here: its windows are given) + crate::gpu::uma::leave_out(); + recomp::pso::set_title_windows(windows); + recomp::dxc::set_memory_reserve(2); + let mut shaders = std::collections::HashMap::new(); + let mut records = Vec::new(); + for p in gfx_records::read(job) { + match gfx_records::decode(&p) { + Some(Entry::Pipeline(r)) => records.push(r), + Some(Entry::Shader(k, b)) => { shaders.insert(k, b); } + None => {} + } + } + let device = match Pipelines::for_adapter("auto") { + Ok(p) => crate::hle::d3d12x::real::prepare_device(p.dev), + Err(e) => { eprintln!("xcl shaders: no pipeline device: {e}"); return 2; } + }; + let n = records.len(); + let threads = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse::().ok()).unwrap_or(1).clamp(1, 8); + let (next, done, made, failed) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); + let t0 = std::time::Instant::now(); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(r) = records.get(i) else { break }; + let code = r.shaders.map(|k| shaders.get(&k).map(Vec::as_slice)); + let desc = r.desc(code); + // (a pipeline that panics fails; the others are built) + let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { crate::hle::d3d12x::real::prepare_graphics(device, &desc) })).unwrap_or(false); + if ok { made.fetch_add(1, Ordering::Relaxed); } else { failed.fetch_add(1, Ordering::Relaxed); } + let d = done.fetch_add(1, Ordering::Relaxed) + 1; + eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); + }); + } + }); + let (hits, _, stored) = crate::hle::d3d12x::real::driver_cache_stats(); + eprintln!("graphics pipelines: {} made, {} failed; driver blobs: {hits} from disk, {stored} kept", made.into_inner(), failed.into_inner()); + 0 +} + +/// `XCL_PRECOMPILE_PARENT=pid` (set for a title's preparation workers): this process ends when +/// that one does, so no builder is left on the GPU behind a title that was ended. +fn end_with_parent() { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Threading::{OpenProcess, WaitForSingleObject, INFINITE, PROCESS_SYNCHRONIZE}; + let Some(pid) = std::env::var("XCL_PRECOMPILE_PARENT").ok().and_then(|v| v.parse::().ok()) else { return }; + let h = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) }; + if h.is_null() { + // (gone already) + std::process::exit(3); + } + let h = h as usize; + std::thread::spawn(move || unsafe { + WaitForSingleObject(h as _, INFINITE); + CloseHandle(h as _); + std::process::exit(3); + }); +} + +fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> { + if startup.is_none() { end_with_parent(); } + let pipelines = if pipelines { + let mut p = Pipelines::for_adapter(startup.map_or("auto", |p| p.adapter.as_str())) + .map_err(|e| format!("No pipeline device: {e}"))?; + if startup.is_some() && std::env::var_os("XCL_PIPELINE_MAX_KB").is_none() { + p.max_dxil = 0; } + Some(p) } else { None }; let pipelines = pipelines.as_ref(); let n = input.len().min(limit); + // `XCL_PRECOMPILE_SLICE=i/n` (experiment): this process takes only every n-th shader, from the + // i-th, so n processes share the work and each has its own driver compiler + let slice: Option<(usize, usize)> = std::env::var("XCL_PRECOMPILE_SLICE").ok().and_then(|v| { + let (i, n) = v.split_once('/')?; + Some((i.trim().parse().ok()?, n.trim().parse::().ok().filter(|n| *n > 0)?)) + }); + // a progress line every 200 records; every record for a title waiting on this builder + // (`pipelines_in_workers` shows the count) + let every = if std::env::var_os("XCL_PRECOMPILE_PARENT").is_some() { 1 } else { 200 }; let next = AtomicUsize::new(0); let (done, compiled, cached, failed, skipped) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); let errors: Mutex> = Mutex::new(Vec::new()); let unused = AtomicUsize::new(0); + let rt_gated = AtomicUsize::new(0); if let Some(u) = used { println!("--used-only: {} pipelines earlier runs used (used-pipelines.txt); compute programs of other pipelines are passed over", u.len()); } // the compiles run on the DXC pool; these threads translate and keep it fed let threads = recomp::dxc::compile_threads() + 2; // no title runs: only a little commit is kept free besides the compiles - recomp::dxc::set_memory_reserve(2); + if startup.is_none() { recomp::dxc::set_memory_reserve(2); } // VS / PS: the 32-lane form wherever the GPU can run 32-lane waves (`pso::graphics_wave32`); // `--split` sets both - let graphics_split = split.unwrap_or_else(recomp::runner::graphics_wave32); - let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w)); + let startup_device = pipelines.filter(|_| startup.is_some()); + let graphics_split = split.unwrap_or_else(|| startup_device.map_or_else(recomp::runner::graphics_wave32, |p| recomp::pso::graphics_wave32_for_device(&p.dev))); + let split = split.unwrap_or_else(|| startup_device.map_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w), |p| recomp::pso::wave32_only_for_device(&p.dev))); println!( "precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})", recomp::dxc::cache_dir().display(), recomp::dxc::compile_threads(), - windows & !recomp::HEAP_WINDOWS, - if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" }, + windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), + if windows & recomp::HEAP_WINDOWS != 0 { + if windows & recomp::HEAP_FLAT != 0 { " from the descriptor heap (flat)" } else { " from the descriptor heap" } + } else { "" }, if split { ", split wave64 for a GPU with 32-lane waves" } else { "" } ); std::thread::scope(|s| { for _ in 0..threads { s.spawn(|| loop { + if startup.is_some_and(|p| p.cancel.load(Ordering::Relaxed)) { break; } let i = next.fetch_add(1, Ordering::Relaxed); if i >= n { break; } + if slice.is_some_and(|(k, of)| i % of != k) { + continue; + } + let record_done = || { + let d = done.fetch_add(1, Ordering::Relaxed) + 1; + if let Some(p) = startup { p.done.fetch_add(1, Ordering::Relaxed); } + if d % every == 0 { eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); } + }; let (name, blob) = input.get(i); - let Some(blob) = blob else { continue }; - let Some(sh) = xbox::parse(&blob) else { continue }; + let Some(blob) = blob else { + if startup.is_some() { failed.fetch_add(1, Ordering::Relaxed); } + record_done(); + continue; + }; + let Some(sh) = xbox::parse(&blob) else { + if startup.is_some() && !matches!(shader::classify(&blob).0, shader::Kind::Dxil | shader::Kind::Dxbc) { + failed.fetch_add(1, Ordering::Relaxed); + } + record_done(); + continue; + }; if only.is_some_and(|o| !sh.stage.eq_ignore_ascii_case(o)) { - done.fetch_add(1, Ordering::Relaxed); + record_done(); + continue; + } + if startup.and_then(|p| p.only.as_ref()).is_some_and(|used| !used.contains(&crate::hle::d3d12x::real::shader_key(&blob))) { + unused.fetch_add(1, Ordering::Relaxed); + record_done(); continue; } // a compute program as a title's pipeline translates it (`pso::console_to_dxil_in`): @@ -1646,13 +2321,22 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on if sh.fssm.iter().any(|f| matches!(recomp::interface(&blob, &sh, f), Some(recomp::Mode::Compute(_)))) { if used.is_some_and(|u| !used_compute(&blob, u)) { unused.fetch_add(1, Ordering::Relaxed); + record_done(); + continue; + } + if crate::hle::d3d12x::real::rt_gated_compute_held(&blob) { + rt_gated.fetch_add(1, Ordering::Relaxed); done.fetch_add(1, Ordering::Relaxed); continue; } + let record = crate::gpu::shader::fnv64(&blob); match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { if let Some(p) = pipelines { - p.make(&c); + p.make_record(&c, record); + if startup.is_some() && c.dispatch_chain.as_ref().is_some_and(|plan| plan.pieces.len() >= 2) { + p.make_one(&c.dxil, &c.samplers, true, None, record); + } } compiled.fetch_add(1, Ordering::Relaxed) } @@ -1664,10 +2348,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on failed.fetch_add(1, Ordering::Relaxed) } }; - let d = done.fetch_add(1, Ordering::Relaxed) + 1; - if d % 200 == 0 { - eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); - } + record_done(); continue; } for f in &sh.fssm { @@ -1687,11 +2368,22 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // as `pso` translates: with the title's memory windows (`console_translation`, // `translate_mesh`) let split = if matches!(mode, recomp::Mode::Vertex(_) | recomp::Mode::Pixel(_)) { graphics_split } else { split }; - let opt = recomp::Options { mode: mode.clone(), wave64: recomp::fssm_wave64(f, code), split_wave64: split, mem_windows: windows, ..Default::default() }; - let Ok(t) = recomp::translate(code, &opt) else { continue }; - if !t.complete() { - continue; - } + let opt = recomp::Options { mode: mode.clone(), wave64: recomp::fssm_wave64(f, code), split_wave64: split, mem_windows: windows, rodata: f.rodata(p), ..Default::default() }; + let t = match recomp::translate(code, &opt) { + Ok(t) if t.complete() => t, + Ok(_) => { + if startup.is_some() { skipped.fetch_add(1, Ordering::Relaxed); } + continue; + } + Err(e) => { + if startup.is_some() { + failed.fetch_add(1, Ordering::Relaxed); + let mut logs = errors.lock().unwrap(); + if logs.len() < 10 { logs.push(format!("{name}: {e}")); } + } + continue; + } + }; for (profile, src) in &jobs { match recomp::dxc::compile_cached(src.as_deref().unwrap_or(&t.hlsl), "main", profile) { Ok((_, true)) => cached.fetch_add(1, Ordering::Relaxed), @@ -1707,27 +2399,42 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } } } - let d = done.fetch_add(1, Ordering::Relaxed) + 1; - if d % 200 == 0 { - eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); - } + record_done(); }); } }); + let failed = failed.into_inner(); + let skipped_reason = if startup.is_some() { "runtime pairing or unsupported translation" } else { "GS – paired at pipeline creation" }; println!( - "compiled {}, already cached {}, errors {}, skipped (GS – paired at pipeline creation) {}, time {:.1} s", + "compiled {}, already cached {}, errors {}, skipped ({skipped_reason}) {}, time {:.1} s", compiled.into_inner(), cached.into_inner(), - failed.into_inner(), + failed, skipped.into_inner(), t0.elapsed().as_secs_f64() ); if used.is_some() { println!("compute programs passed over (no earlier run used their pipeline): {}", unused.into_inner()); } + let rt_gated = rt_gated.into_inner(); + if rt_gated != 0 { + println!("compute programs held back by XCL_RT_GATE=hold (set XCL_RT_GATE=auto or 0 to precompile): {rt_gated}"); + } if let Some(p) = pipelines { + let saved_plib = p.flush(); 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)); + let lib_reused = p.lib_reused.load(Ordering::Relaxed); + let lib_stored = p.lib_stored.load(Ordering::Relaxed); + if lib_reused != 0 || lib_stored != 0 || saved_plib.is_some() { + println!( + "pipeline library (.plib): {} loaded, {} stored{}", + lib_reused, + lib_stored, + saved_plib.as_ref().map_or_else(String::new, |path| format!(" -> {}", path.display())) + ); + } + println!("pipelines left to another process that was building them {}", p.elsewhere.load(Ordering::Relaxed)); let split_programs = p.split_programs.load(Ordering::Relaxed); if split_programs != 0 { println!("split compute programs: {} ({} pieces)", split_programs, p.split_pieces.load(Ordering::Relaxed)); @@ -1737,10 +2444,21 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on println!("pipelines over the {} MiB DXIL cap, left to the runtime: {} ({} MiB of DXIL; XCL_PIPELINE_MAX_KB)", p.max_dxil >> 20, capped, p.capped_bytes.load(Ordering::Relaxed) >> 20); } } - for e in errors.into_inner().unwrap() { - println!(" {e}"); + let errors = errors.into_inner().unwrap(); + for e in &errors { println!(" {e}"); } + if let Some(progress) = startup { + if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + // (no pipelines here when worker processes build them: `pipelines_in_workers`) + let refused = pipelines.map_or(0, |p| p.refused.load(Ordering::Relaxed)); + let capped = pipelines.map_or(0, |p| p.capped.load(Ordering::Relaxed)); + if failed + refused + capped > 0 { + let cause = errors.first().map(String::as_str).unwrap_or( + if capped > 0 { "Raise XCL_PIPELINE_MAX_KB or set it to 0 to prepare larger pipelines." } + else { "Check the shader pack and driver diagnostics." }); + return Err(format!("Shader preparation stopped: {failed} record failures, {refused} refused pipelines, {capped} over the size cap. {cause}")); + } } - 0 + Ok(()) } /// Compile the kept HLSL samples with DXC on all cores: (ok, failures with the first error line). @@ -2070,6 +2788,65 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim #[cfg(test)] mod tests { + /// The workers of a title's shader preparation: four logical processors are left free, + /// 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); + } + + /// A builder's progress line gives its record count; its other lines give none. + #[test] + fn a_builders_progress_line_gives_its_count() { + assert_eq!(progress_count(" 400/26503 (12 s)"), Some(400)); + assert_eq!(progress_count("26400/26503 (1339 s)"), Some(26400)); + assert_eq!(progress_count("xcl: [SHADER] direct DXIL fallback stage=CS reason=a/b (c)"), None); + assert_eq!(progress_count(" pipelines: 50 made, 0 refused"), None); + assert_eq!(progress_count("3/4"), None); + } + + /// A graphics worker's summary gives its counts; its progress lines and others give none. + #[test] + fn a_graphics_workers_summary_gives_its_counts() { + assert_eq!(graphics_summary("graphics pipelines: 512 made, 3 failed; driver blobs: 40 from disk, 470 kept"), Some([512, 3, 40, 470])); + assert_eq!(graphics_summary(" graphics pipelines: 0 made, 0 failed; driver blobs: 0 from disk, 0 kept\r"), Some([0; 4])); + assert_eq!(graphics_summary(" 12/512 (3 s)"), None); + assert_eq!(graphics_summary("graphics pipelines: 5 made"), None); + assert_eq!(graphics_summary("graphics pipelines: 1 made, 2 failed; driver blobs: 3 from disk, 4 kept, 5 more"), None); + assert_eq!(progress_count("graphics pipelines: 512 made, 3 failed; driver blobs: 40 from disk, 470 kept"), None); + } + + /// A graphics record is built when every shader it names is found and they make its set's + /// key (the key `used-pipelines.txt` has); one with a shader not in the title's files, or + /// other shaders under its keys, is left out. + #[test] + fn a_graphics_record_is_built_only_with_its_own_shaders() { + use crate::hle::d3d12x::gfx_records::{decode, encode, Entry}; + use crate::hle::d3d12x::real::{shader_key, shaders_key}; + let (vs, ps) = (b"vertex".to_vec(), b"pixel".to_vec()); + let record = |key: u64, shaders: [u64; 5]| { + let d = windows::Win32::Graphics::Direct3D12::D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + match decode(&unsafe { encode(key, shaders, &d) }) { + Some(Entry::Pipeline(r)) => r, + _ => unreachable!(), + } + }; + let both = [shader_key(&vs), shader_key(&ps), 0, 0, 0]; + let records = [ + record(shaders_key(&[vs.clone(), ps.clone()]), both), + record(shaders_key(&[vs.clone()]), [shader_key(&vs), 0, 0, 0, 0]), + record(shaders_key(&[vs.clone(), b"other".to_vec()]), [shader_key(&vs), shader_key(b"other"), 0, 0, 0]), + record(shaders_key(&[ps.clone(), vs.clone()]), both), + ]; + let shaders = std::collections::HashMap::from([(shader_key(&vs), vs.clone()), (shader_key(&ps), ps.clone())]); + assert_eq!(buildable(records.iter(), &shaders), (vec![0, 1], 2)); + } + /// `--used-only` keeps a compute program exactly when the runtime noted its pipeline: the /// key of a pipeline of that one shader, as `real::shaders_key` makes it. #[test] @@ -2096,6 +2873,16 @@ mod tests { sample(5, &[compute]) } + #[test] + fn offline_runtime_windows_includes_heap_flat_when_enabled() { + assert_eq!(runtime_windows_flags(1, true, true), 1); + assert_eq!(runtime_windows_flags(4, false, true), 4); + assert_eq!(runtime_windows_flags(4, true, false), 4 | recomp::HEAP_WINDOWS); + let flat = runtime_windows_flags(4, true, true); + assert_eq!(flat, 4 | recomp::HEAP_WINDOWS | recomp::HEAP_FLAT); + assert_eq!(flat & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), 4); + } + #[test] fn record_hash_is_strict_hex() { assert_eq!(parse_record_hash("0x0123aB").unwrap(), 0x123AB); @@ -2338,9 +3125,9 @@ fn direct_sweep(input: &Input, opts: &ShadersOptions, t0: std::time::Instant) -> let t = std::time::Instant::now(); let r = { let (tx, rx) = std::sync::mpsc::channel(); - let (c, m) = (code.to_vec(), mode.clone()); + let (c, m, rodata) = (code.to_vec(), mode.clone(), f.rodata(p)); std::thread::spawn(move || { - let _ = tx.send(coverage::translate_mode(&c, &m, o, validate)); + let _ = tx.send(coverage::translate_mode(&c, &m, o, validate, &rodata)); }); rx.recv_timeout(timeout).unwrap_or_else(|_| Err(format!("timeout: over {} s", timeout.as_secs()))) }; @@ -2382,7 +3169,7 @@ fn direct_sweep(input: &Input, opts: &ShadersOptions, t0: std::time::Instant) -> recomp::Mode::Pixel(_) => "ps_6_6", _ => "cs_6_6", }; - let opt = recomp::Options { mode: mode.clone(), wave64, split_wave64: wave64 && split, mem_windows: windows, ..Default::default() }; + let opt = recomp::Options { mode: mode.clone(), wave64, split_wave64: wave64 && split, mem_windows: windows, rodata: f.rodata(p), ..Default::default() }; let t = recomp::translate(code, &opt).ok().filter(|t| t.complete())?; dump("hlsl", t.hlsl.as_bytes()); let d = recomp::dxc::compile(&t.hlsl, "main", profile, &[]).ok()?; diff --git a/crates/xcl/src/vfs_hooks.rs b/crates/xcl/src/vfs_hooks.rs index 0767cf1e1c..6af3e534d2 100644 --- a/crates/xcl/src/vfs_hooks.rs +++ b/crates/xcl/src/vfs_hooks.rs @@ -531,10 +531,19 @@ 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); + if buf.is_null() { + return orig(h, buf, n, read, ov); + } + // (views of physical pages stay writable until the read is over: a synchronous one when it + // returns, an overlapped one – it writes after this returns – when its OVERLAPPED says done) + let open = crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); + let r = orig(h, buf, n, read, ov); + if ov.is_null() { + drop(open); + } else { + crate::hle::kernelx::guards::open_until_done(open, ov as usize); } - orig(h, buf, n, read, ov) + r } unsafe extern "system" fn hk_delete_file_w(n: *const u16) -> i32 { diff --git a/crates/xcl/tests/d3d12_resource_and_sync.rs b/crates/xcl/tests/d3d12_resource_and_sync.rs index ac4e86ffdf..af8db517a9 100644 --- a/crates/xcl/tests/d3d12_resource_and_sync.rs +++ b/crates/xcl/tests/d3d12_resource_and_sync.rs @@ -12,7 +12,7 @@ use std::sync::{Arc, OnceLock}; use std::time::{Duration, Instant}; use windows::core::{Interface, GUID}; -use windows::Win32::Foundation::{CloseHandle, E_INVALIDARG, S_OK, WAIT_OBJECT_0}; +use windows::Win32::Foundation::{CloseHandle, E_INVALIDARG, S_FALSE, S_OK, WAIT_OBJECT_0}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC}; use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; @@ -409,6 +409,27 @@ fn descriptor_heap_console_start_handles_match_host_and_console_heap() { } } +/// `CreateDescriptorHeap` with a null out pointer is D3D12's validation call: it makes no heap and +/// returns `S_FALSE` (#2401). The console #14 path for CBV_SRV_UAV and SAMPLER heaps used to read +/// `*ppv` on any success code and crash. +#[test] +fn console_descriptor_heap_validation_call_with_null_out_pointer_returns_s_false() { + let Some(dev) = adopted_device() else { return }; + unsafe { + for (ty, count) in [(4u32, 16u32), (D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32, 8u32)] { + for flags in [D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32, D3D12_DESCRIPTOR_HEAP_FLAG_NONE.0 as u32] { + let desc = [ty, count, flags, 0u32]; + let hr = call_console( + dev.as_raw(), + 14, + &[desc.as_ptr() as usize, &ID3D12DescriptorHeap::IID as *const GUID as usize, 0], + ) as i32; + assert_eq!(hr, S_FALSE.0, "console CreateDescriptorHeap(type={ty}, flags={flags:#x}, ppv=NULL): {hr:#x}"); + } + } + } +} + #[test] fn fence_and_command_queue_sync_timing_and_allocator_reset_match_host_and_console() { let Some(dev) = adopted_device() else { return }; diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index 027638eee7..4f238248a9 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -128,6 +128,9 @@ fn test_title_runs_and_game_folder_is_untouched() { copy_dir(&manifest.join("..").join("..").join("tests").join("data").join("testgame"), &game); std::fs::copy(&title, game.join("xcl_testtitle.exe")).unwrap(); std::fs::copy(&dll, game.join("testgame_mw.dll")).unwrap(); + // Already-compiled graphics bytecode still goes through startup discovery. + std::fs::create_dir(game.join("shaders")).unwrap(); + std::fs::copy(manifest.join("../../tests/data/dxil/dxc_vs_uav.dxil"), game.join("shaders/vertex.dxbc")).unwrap(); let before = snapshot(&game); let out = Command::new(&xcl) @@ -157,6 +160,10 @@ fn test_title_runs_and_game_folder_is_untouched() { assert!(stdout.contains("xcl_testtitle: done, failures: 0"), "the test title did not run to the end"); assert!(out.status.success(), "exit code {:?}", out.status.code()); + let log = std::fs::read_to_string(data.join("XCL.TestTitle/logs/xcl.log")).unwrap(); + let window = |tag| log.lines().find_map(|line| line.split_once(tag).map(|(_, hwnd)| hwnd)).unwrap(); + assert_eq!(window("Shader preparation window "), window("present: swap chain window ")); + // (2) the game folder is untouched assert_eq!(snapshot(&game), before, "GAME FOLDER WAS MODIFIED"); diff --git a/crates/xcl/tests/launcher_e2e.rs b/crates/xcl/tests/launcher_e2e.rs index 4100fad051..733d14a866 100644 --- a/crates/xcl/tests/launcher_e2e.rs +++ b/crates/xcl/tests/launcher_e2e.rs @@ -22,6 +22,21 @@ impl Drop for TempDir { } } +#[test] +fn unreadable_shader_pack_stops_launch_before_host_start() { + let game = TempDir::new("xcl-preparation-failed"); + std::fs::write(game.0.join("title.exe"), b"must never be loaded").unwrap(); + std::fs::write(game.0.join("shaders.rpf"), b"9FPR").unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_xcl")) + .args(["run"]).arg(&game.0) + .env("XCL_DATA_ROOT", game.0.join("user")) + .env("XCL_SKIP_CPU_CHECK", "1") + .output().unwrap(); + assert_eq!(output.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&output.stderr).contains("No readable shader records")); + assert!(!String::from_utf8_lossy(&output.stdout).contains("Log:")); +} + #[test] fn launcher_missing_target_argument_exits_code_two() { let output = Command::new(env!("CARGO_BIN_EXE_xcl")) diff --git a/scripts/smoke.ps1 b/scripts/smoke.ps1 index db296218b2..ad15cbc0c0 100644 --- a/scripts/smoke.ps1 +++ b/scripts/smoke.ps1 @@ -2,7 +2,7 @@ # prints an `xcl-smoke` block to paste into the PR's "Regression run" section – once built # from main, once from the PR's head commit (CONTRIBUTING.md, "What a PR needs to be merged"). # -# .\scripts\smoke.ps1 -Game 'D:\Games\SomeTitle' [-Seconds 60] [-Xcl .\target\release\xcl.exe] [-Title