diff --git a/HANDOFF.md b/HANDOFF.md index 984a45360a..d0a01a790d 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -258,7 +258,7 @@ NOTE: ### Console DLLs from the game pack (session 5, without the exe) The user provided 16 DLLs from chunk 1002 (`\*.dll`, ordinary PEs): the console CRT (vcruntime140(_1), msvcp140(_1/_2/_atomic_wait/_codecvt_ids), concrt140, vcomp140, vccorlib140), Bink2Scarlett, XCurl, libHttpClient.GDK, -amd_fidelityfx_loader_xbox / amd_fidelityfx_upscaler_xbox, XboxBvhBuilder. The game exe (`game_scarlett_master.exe`) is still missing. +amd_fidelityfx_loader_xbox / amd_fidelityfx_upscaler_xbox, XboxBvhBuilder. The game exe is still missing. - `xcl inspect`: after fixes **0 missing imports in all 16**. Added: - `XMemVirtualQuery(process, address, info) → BOOL` (signature from the call sites in XboxBvhBuilder, objdump from msys64): info = MEMORY_BASIC_INFORMATION + a field @48, bits 0–1 = memory readable by the CPU (message on error: diff --git a/README.md b/README.md index 33ccbc64a0..2d85657bbb 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ A gamepad is recommended ([Controls](#controls)). The game folder is never modif |---|---|---|---| | **PE loader** | ✅ | relocations, imports by name / ordinal / delay-load, TLS callbacks, exception tables, game DLLs, data-driven import routing (HLE / Windows / stub) | the game's 16 console DLLs load with 0 unresolved imports | | **kernelx** | ✅ | title memory (budget from MicrosoftGame.Config, physical pages), threads on the PC's processors, modules, OS / console info | unit + end-to-end tests | -| **Memory** | ✅ | title graphics memory shared by CPU and GPU without copies, up to 16 GB (4 GiB windows) | GPU tests: loads, stores and atomics across windows | +| **Memory** | ✅ | title graphics memory shared by CPU and GPU without copies, up to 16 GB (4 GiB windows); XMem graphics requests for 2 MiB pages round to 2 MiB boundaries | GPU tests: loads, stores and atomics across windows | | **File system** | ✅ | console paths (`GAME:`, `G:`, `D:` …) → the game folder; writes go to an overlay, the game folder is never modified; the console's drives: `S:\` (persistent local storage) and `T:\` (temp) in the title's data folder; free disk space answered for console paths | end-to-end: the test title's folder stays byte-identical; PLS and free space through the real call path | | **DirectStorage** | ✅ | the console's DirectStorage queues: file and memory sources, 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`) | @@ -377,9 +377,9 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. scratch buffer of at most `XCL_SPLIT_SCRATCH_MB` (default 256); the chains of one recording share it, and `XCL_SPLIT_SCRATCH_TOTAL_MB` (default 384) bounds what all recordings not yet reset hold together (past it a dispatch runs in smaller slabs). -- Huge pipelines (translated DXIL of `XCL_HUGE_PSO_BYTES` or more, default 262144) built on the +- Huge pipelines (translated DXIL of `XCL_HUGE_PSO_BYTES` or more, default 65536) built on the background `xcl-pso*` workers take turns in the driver's compiler: `XCL_HUGE_PSO_CONCURRENCY` - at once (default 1, maximum 64). Pipelines of 4 MiB or more use a separate one-wide lane so + at once (default 2, maximum 64). Pipelines of 4 MiB or more use a separate one-wide lane so they cannot occupy the ordinary huge-pipeline slot; one of them can therefore run next to the ordinary ones, and each gated compile starts only with 3 GB of commit free. Smaller pipelines and those a game thread waits for never wait. `xcl.log` shows each huge one as a numbered @@ -404,8 +404,9 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. those on which the GPU completed at least one operation. For each, it names the translated pipeline bound at the last operation DRED saw complete and those bound after it, by their console shaders' hashes (`cs`, `vs` / `ps`, `ms` / `ps`, `vs` / `gs` / `ps`). -- `XCL_TEXTURE_LEVEL_PAGES=1` gives sampled title textures backing as their mip levels stream in. - Zero-filled mip uploads in a batch share one staging span and still clear any mapped tiles. +- Sampled title textures get backing as their mip levels stream in (`XCL_TEXTURE_LEVEL_PAGES=0`: + all levels at once). Zero-filled mip uploads in a batch share one staging span and still clear + any mapped tiles. - `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib requests with virtual destinations. Defaults: four workers and a shared 32 MiB staging budget (`XCL_DSTORAGE_WORKERS`, `XCL_DSTORAGE_MEMORY_BUDGET_MIB`). Requests retire in queue order. @@ -413,6 +414,20 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. fills into its GPU views) are applied: a GPU-view page shows the physical page mapped into it. `XCL_PAGE_MAPPINGS=0` turns them off (the call is ignored and a GPU-view page shows its CPU view at the same offset, as before). +- `XCL_DEFER_PRIVATE_HOME_TILES` keeps physical-page home storage used only by CPU/storage + transfers from acquiring a second sparse GPU copy. Explicit home mappings expose and upload + the existing bytes before the next submission, even after an earlier write-watch scan. + Already-exposed homes keep their normal behavior. On by default (`=0` turns it off); this + reduces avoidable backing, not the memory needed by live GPU mappings, and is not a VRAM + budget cap. +- Memory on 32 GB PCs: Windows charges every byte of video memory to the system's commit (RAM + + page file), so video memory XCL does not need counts like RAM. These are on by default to keep + it down: a streamed texture's levels get video memory when they are loaded + (`XCL_TEXTURE_LEVEL_PAGES=0` gives every level its memory at once), small sampled textures share + 4 KiB placements (`XCL_SMALL_TEXTURES=0`: a committed resource each), and 64 MB of idle texture + upload buffers are kept (`XCL_UPLOAD_KEEP_MB`). Shader preparation starts no more workers than + the RAM available holds (2 GB each, 4 GB left over) and the commit left (3 GB each); + `XCL_PREPARE_WORKERS=N` sets the number. - Every run writes `report.json` (called stubs, unknown D3D12.X slots and interfaces, XGameRuntime classes asked for, shader statistics, audio formats, crash). `d3d12.presents` counts presentations, not visible content. With `XCL_FRAME_DUMP=N` (`N > 1`), diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index db38e8a443..4e04ecf123 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -11,6 +11,9 @@ carry a note in their header about its origin and the date of changes (GPL-3.0 | [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables | | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | | [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables | +| [Vice-Tay](https://github.com/TaynanGT/Vice-Tay) | GPL-3.0-or-later | `crates/xcl/src/gpu/rt_leave_out.rs` (the programs left out); `crates/xcl/src/hle/d3d12x/ambient.rs`: the cells and their slow mean, and the stand-in for the indirect light made in space – `LIGHT_PLACE_HLSL`, `LIGHT_GATHER_HLSL`, the depth path of `AMBIENT_FILL_R9G9B9E5_HLSL`, `AIR_CAP_HLSL` and the resolve's descriptor slots, after `place`, `gather`, `raise`, `clear_air`, `LIGHT` and `DEPTH` of its `ambient.rs` (commit 99a7f9b) | port of the HLSL into XCL's ambient pass (2026-11-28) | +| [VIctory-Neo](https://github.com/KyleS98/VIctory-Neo) | GPL-3.0-or-later | `crates/xcl/src/hle/d3d12x/mirror.rs`: the light around a mirror's view – the programs' parts by name, `XCL_MIRROR_AMBIENT` and the pass and its programs, after its `crates/victory-gpu/src/mirror.rs` (commits a3af274, 9b61dc9); `crates/xcl/src/hle/d3d12x/depth_uav.rs`: a depth plane brought up to date from its twin before the draws that test against it, after 7da5c9d; `crates/xcl/src/hle/d3d12x/ambient.rs`: the reflections' hold to the light around and their resolve slots (3aca295), the bound on transparent surfaces' light (`CS_SpatialFilterAlpha`, a6e85c6) and the probes' blue garbage test, after its `crates/victory-gpu/src/ambient.rs` at bdc3f38; the stand-in for reflections that found nothing (`MISS_LIGHT_HLSL`, `XCL_AMBIENT_SPECULAR`, the `CS_RayMiss` slots and layers), after its `Role::Miss`, `reflect_light` and `VICTORY_AMBIENT_SPECULAR` at bdc3f38 | port adapted to XCL's passes and state (2026-11-29) | +| Whiplash (Belobug's lineage, VIctory PR #63; a snapshot, `Kalmarv/whiplash` 699f191) | GPL-3.0-or-later | `crates/xcl/src/hle/d3d12x/ambient.rs`: one bounce of the title's own light (`XCL_AMBIENT_ONCE`: the fill's notes at the places the keep reads, and the keep counting each place by them), after `VICTORY_AMBIENT_ONCE` in its `Whiplash-NVIDIA/crates/victory-gpu/src/ambient.rs`; the ideas of `XCL_AMBIENT_SPECULAR_ALPHA`, `XCL_AMBIENT_MEAN_CLEAN` and `XCL_AMBIENT_DITHER`, after its `VICTORY_AMBIENT_SPECULAR_ALPHA`, `VICTORY_AMBIENT_MEAN_CLEAN` and `VICTORY_AMBIENT_DITHER`; `crates/xcl/src/hle/d3d12x/title_textures.rs`: the idea of `XCL_BAKE_AT_SUBMIT`'s whole upload of a bake's sources as title memory has them just before the bake, after `early_budgets` and `bake_exact` in its `Whiplash-AMD/crates/victory-gpu/src/draw.rs`; `crates/xcl/src/title_patch.rs`: the title's upscaler picker (its offset and bytes, `mov eax, kind; ret`: `XCL_UPSCALER`), after `VICTORY_UPSCALER` in its `Whiplash-AMD/crates/victory-loader/src/resolution.rs` (VIctory PR #53) | re-implemented on XCL's passes; what the keep takes out is XCL's; the picker's bytes are the title's, applied only where they match (2026-11-30) | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | diff --git a/crates/xcl/benches/gpu_cpu.rs b/crates/xcl/benches/gpu_cpu.rs index e249d9d434..624d3a1bee 100644 --- a/crates/xcl/benches/gpu_cpu.rs +++ b/crates/xcl/benches/gpu_cpu.rs @@ -87,6 +87,7 @@ fn graphics_options(split_wave64: bool) -> recomp::Options { outputs: Vec::new(), input_ena: 0, attrs: None, + early_depth: false, }), wave64: true, split_wave64, diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 073e51d91f..c4172b526b 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -113,7 +113,8 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i if !ctx.is_null() { let c = &*ctx; let mut seen: Vec = Vec::new(); - for (n, v) in [("rax", c.Rax), ("rbx", c.Rbx), ("rcx", c.Rcx), ("rdx", c.Rdx), ("rsi", c.Rsi), ("rdi", c.Rdi), ("rbp", c.Rbp), ("r8", c.R8), ("r9", c.R9), ("r10", c.R10), ("r11", c.R11), ("r12", c.R12), ("r13", c.R13), ("r14", c.R14), ("r15", c.R15)] { + let fault = if rec.ExceptionCode as u32 == 0xC000_0005 && rec.NumberParameters >= 2 { rec.ExceptionInformation[1] as u64 } else { 0 }; + for (n, v) in [("the fault address", fault), ("rax", c.Rax), ("rbx", c.Rbx), ("rcx", c.Rcx), ("rdx", c.Rdx), ("rsi", c.Rsi), ("rdi", c.Rdi), ("rbp", c.Rbp), ("r8", c.R8), ("r9", c.R9), ("r10", c.R10), ("r11", c.R11), ("r12", c.R12), ("r13", c.R13), ("r14", c.R14), ("r15", c.R15)] { let p = v as usize; if p < 0x1_0000 || seen.contains(&(p & !0xFFFF)) { continue; @@ -123,16 +124,55 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i if !d.is_empty() { crate::xlog_error!("page of {n}={p:#x}: {d}"); } + let g = crate::hle::kernelx::given_up::describe(p); + if !g.is_empty() { + crate::xlog_error!("{n}={p:#x}: {g}"); + } + // which memory it is, and what it holds there + if crate::gpu::shader::readable(p & !7, 64) { + let kind = match crate::gpu::uma::get() { + Some(u) if u.is_sparse(p) => "a sparse window", + Some(u) if u.is_view(p) => "a GPU view", + Some(u) if u.is_committed(p) => "the coherent window", + Some(u) if u.contains(p) => "unified memory", + _ => "outside unified memory", + }; + let words: Vec = (0..8).map(|i| format!("{:016x}", ((p & !7) as *const u64).add(i).read_unaligned())).collect(); + crate::xlog_error!("memory at {n}={p:#x} ({kind}): {}", words.join(" ")); + if kind != "outside unified memory" { + crate::xlog_error!("buffer views compute dispatches were given over {n}={p:#x}: {}", crate::hle::d3d12x::real::dispatch_views_over(p)); + // the neighbourhood, as dwords: what was written over an object shows its + // extent and stride (single words, records, a block) + let from = (p & !15).saturating_sub(192); + if crate::gpu::shader::readable(from, 448) { + for row in 0..7 { + let at = from + 64 * row; + let w: Vec = (0..16).map(|i| format!("{:08x}", ((at + 4 * i) as *const u32).read_unaligned())).collect(); + crate::xlog_error!(" {at:#x}: {}", w.join(" ")); + } + } + } + } } crate::xlog_error!("page events so far: {}", crate::hle::kernelx::pagelog::counts()); } crate::report::write_final(Some(msg)); crate::log::flush(); } - match TITLE_FILTER.load(Ordering::Acquire) { + let verdict = match TITLE_FILTER.load(Ordering::Acquire) { 0 => 0, // EXCEPTION_CONTINUE_SEARCH f => std::mem::transmute:: i32>(f)(info), + }; + // Continuing the search hands the process to Windows Error Reporting, which snapshots it for + // its dump: with a title's tens of GB committed, that doubled the system's commit charge in + // one second (measured: +24 GB). The report is written, so the process ends here with the + // exception's code (`XCL_WER=1`: Windows gets it as before). + if verdict == 0 && std::env::var_os("XCL_WER").is_none() { + let code = if info.is_null() || (*info).ExceptionRecord.is_null() { 0xC000_0005u32 } else { (*(*info).ExceptionRecord).ExceptionCode as u32 }; + crate::log::flush(); + windows_sys::Win32::System::Threading::TerminateProcess(windows_sys::Win32::System::Threading::GetCurrentProcess(), code); } + verdict } static ORIG_NT_TERMINATE: AtomicUsize = AtomicUsize::new(0); @@ -542,6 +582,76 @@ unsafe fn code_bytes_at(rip: usize, most: usize) -> usize { (in_page + 1..=most).rev().find(|&n| crate::gpu::shader::readable(rip, n)).unwrap_or(in_page) } +thread_local! { + /// the address this thread's last `monitorx` armed (rAX) + static MONITORED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// `mwaitx` (ECX bit 1: EBX is a timeout in TSC ticks): waits here, without leaving the handler, +/// until the monitored quadword changes or about a quarter of a millisecond has passed (a late or +/// spurious wake-up is allowed: the title's loop checks and waits again). Returning at +/// once, as before, made a title's wait on a GPU fence two exceptions per turn of its loop – a +/// retail title's world: 61 000 turns a second on the thread that waits for the GPU. +unsafe fn mwaitx_wait(ecx: u32, ebx: u32) { + use std::arch::x86_64::{_mm_pause, _rdtsc}; + const MOST_TICKS: u64 = 800_000; + let at = MONITORED.with(|m| m.get()); + if at == 0 || !at.is_multiple_of(8) || !crate::gpu::shader::readable(at, 8) { + std::hint::spin_loop(); + return; + } + let cell = &*(at as *const std::sync::atomic::AtomicU64); + let seen = cell.load(Ordering::Relaxed); + // (the title's own timeout is 1000 ticks, a pause: it is not kept, the quadword is polled) + let _ = (ecx, ebx); + let end = _rdtsc().saturating_add(MOST_TICKS); + while cell.load(Ordering::Relaxed) == seen && _rdtsc() < end { + _mm_pause(); + } +} + +/// Emulated console-only instructions by kind, logged every 2 s while there are any: each one is +/// an exception (kernel and back), so a title that runs them in a loop pays for it in frame time. +fn count_emulated(what: &crate::insn::ConsoleOnly, rip: usize) { + use crate::insn::ConsoleOnly as C; + const NAMES: [&str; 8] = ["clwb", "clzero", "rdpru", "monitorx", "mwaitx", "rdpid", "extrq", "insertq"]; + static N: [AtomicUsize; 8] = [const { AtomicUsize::new(0) }; 8]; + static LAST_MS: AtomicUsize = AtomicUsize::new(0); + static SITES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + let k = match what { + C::Clwb => 0, + C::Clzero | C::ClzeroLoop { .. } => 1, + C::Rdpru => 2, + C::Monitorx => 3, + C::Mwaitx => 4, + C::Rdpid(_) => 5, + C::Extrq { .. } => 6, + C::Insertq { .. } => 7, + C::Ud2 => return, + }; + N[k].fetch_add(1, Ordering::Relaxed); + if let Ok(mut g) = SITES.try_lock() { + match g.iter().position(|e| e.0 == rip) { + Some(i) => g[i].1 += 1, + None if g.len() < 4096 => g.push((rip, 1)), + None => {} + } + } + let now = (crate::log::uptime() * 1000.0) as usize; + let last = LAST_MS.load(Ordering::Relaxed); + if now >= last + 2000 && LAST_MS.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_ok() { + let counts: Vec = (0..8).map(|i| (NAMES[i], N[i].swap(0, Ordering::Relaxed))).filter(|c| c.1 > 0).map(|(n, c)| format!("{c} {n}")).collect(); + let top = SITES.lock().map_or(String::new(), |mut g| { + g.sort_by_key(|e| std::cmp::Reverse(e.1)); + let t = g.iter().take(6).map(|&(a, c)| format!("{} x{c}", modules::describe_address(a))).collect::>().join(", "); + let sites = g.len(); + g.clear(); + format!("{sites} places, most: {t}") + }); + crate::xlog_info!("emulated console CPU instructions ({} ms): {}; {top}", now - last, counts.join(", ")); + } +} + /// A title's STATUS_ILLEGAL_INSTRUCTION: an instruction the console's Zen 2 has and this CPU /// lacks (`insn`) is emulated and stepped over (EXCEPTION_CONTINUE_EXECUTION); anything else is /// logged with its code bytes and goes on to the title's handlers. @@ -571,6 +681,7 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics } } } + count_emulated(&what, rip); let mut step = len; match what { ConsoleOnly::Ud2 => return 0, diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index 65c1a51b00..d3c5355b1f 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -270,6 +270,64 @@ pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool) -> Option { repeated.then_some(p) } +/// `XCL_DIRECT_COMPACT_MIN=` (unset: `DEFAULT_COMPACT_MIN`; 0: off; it applies only +/// to the programs `XCL_DIRECT_FORMS_ONLY` gives the newer forms): a compute program of at least that +/// many reachable non-terminator instructions takes the compact form whenever it has one whose +/// table fits (`sized_plan`), however little of it repeats. The automatic choice is about size; +/// this one is about speed: on a big program the driver's register allocation of the plain +/// form can spill most of the program's values (a retail title's 6,000-instruction shadow-mask +/// program: 256 VGPRs and 18 KB of scratch a lane on RDNA4), and the compact form's blocks, +/// each lowered on its own, need none. +pub fn compact_min() -> Option { + #[cfg(test)] + if let Some(v) = COMPACT_MIN_FOR_TEST.with(|c| c.get()) { + return v; + } + static V: std::sync::OnceLock> = std::sync::OnceLock::new(); + *V.get_or_init(|| compact_min_of(std::env::var("XCL_DIRECT_COMPACT_MIN").ok().as_deref())) +} + +/// `XCL_DIRECT_COMPACT_MIN` unset: the measured retail run's value (the shadow-mask program, +/// ~6,000 instructions, compact: 95.6 → 4.0 ms offline with the declared LDS). +const DEFAULT_COMPACT_MIN: usize = 4096; + +/// The size of an `XCL_DIRECT_COMPACT_MIN` value: unset, `DEFAULT_COMPACT_MIN`; 0 or not a +/// number, off. +fn compact_min_of(v: Option<&str>) -> Option { + match v { + None => Some(DEFAULT_COMPACT_MIN), + Some(v) => v.trim().parse::().ok().filter(|&n| n > 0), + } +} + +#[cfg(test)] +#[test] +fn the_compact_min_is_on_by_default_and_0_turns_it_off() { + assert_eq!(compact_min_of(None), Some(DEFAULT_COMPACT_MIN)); + assert_eq!(compact_min_of(Some(" 8192 ")), Some(8192)); + assert_eq!(compact_min_of(Some("0")), None); + assert_eq!(compact_min_of(Some("big")), None); +} + +#[cfg(test)] +thread_local! { + /// `compact_min` for the translations of this test thread + pub(crate) static COMPACT_MIN_FOR_TEST: std::cell::Cell>> = const { std::cell::Cell::new(None) }; +} + +/// The compact form of a program of at least `min` reachable instructions whose table fits +/// (`compact_min`). +pub fn sized_plan(cfg: &Cfg, lw: &Lw, min: usize) -> Option { + if insts(cfg) < min { + return None; + } + plan(cfg, lw).filter(|p| p.words() <= MAX_TABLE_WORDS) +} + +fn insts(cfg: &Cfg) -> usize { + cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum() +} + /// Reachable non-terminator instruction count threshold for trying the compact form. const LARGE_INSTS: usize = 10_000; /// Reachable basic-block count threshold for trying the compact form: branch-heavy @@ -280,8 +338,7 @@ const LARGE_BLOCKS: usize = 2_000; /// Whether to consider compaction based on the reachable instruction and block counts. pub fn large(cfg: &Cfg) -> bool { - cfg.rpo.len() >= LARGE_BLOCKS - || cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum::() >= LARGE_INSTS + cfg.rpo.len() >= LARGE_BLOCKS || insts(cfg) >= LARGE_INSTS } pub const END: u32 = u32::MAX; diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index cf56c97c85..4972b5de1d 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -479,3 +479,118 @@ fn gpu_nested_compact_matches_plain_and_flat() { .expect("nested budget GPU run"); assert_eq!((got3.sgpr, got3.vgpr, got3.scc), (plain3.sgpr, plain3.vgpr, plain3.scc), "nested loop budget"); } + +/// `f` with `XCL_DIRECT_COMPACT_MIN` taken as `min` by the translations of this thread. +fn with_compact_min(min: Option, f: impl FnOnce() -> R) -> R { + let before = super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.replace(Some(min))); + let r = f(); + super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.set(before)); + r +} + +/// `XCL_DIRECT_COMPACT_MIN`: a compute program of at least that many instructions takes the +/// compact form, below the automatic choice's size; a smaller one, or a kernel, keeps the plain +/// form. +#[test] +fn a_compute_program_from_the_compact_size_takes_the_compact_form() { + if compact_mode().is_some() { + return; + } + use crate::gpu::recomp::CsInterface; + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + // 100 copies: 900 instructions, below the automatic thresholds + let code = repeated(100); + let compute = |min| with_compact_min(min, || super::kernel::translate_compute(&code, o, &cs)).unwrap().dxil.len(); + let plain = compute(None); + assert!(compute(Some(500)) * 3 < plain, "compact {} B, plain {plain} B", compute(Some(500))); + assert_eq!(compute(Some(5000)), plain, "below the size"); + let kernel = |min| with_compact_min(min, || translate_full(&code, o)).unwrap().dxil; + assert_eq!(kernel(Some(500)), kernel(None), "a kernel keeps its form"); +} + +/// `kernel::with_newer_forms(false)` (a program `XCL_DIRECT_FORMS_ONLY` does not name): the +/// translation is the one every newer form's switch off gives, byte for byte – the compact form of +/// `XCL_DIRECT_COMPACT_MIN`, the declared LDS, one-wave group ids (main's EXEC-select fold stays) – so the +/// driver's shader cache of runs before those forms still holds it; with them it is another one. +#[test] +fn a_program_left_out_of_the_newer_forms_is_translated_as_before_them() { + if compact_mode().is_some() || std::env::var_os("XCL_DXIL_NO_OPT").is_some() { + return; + } + use super::kernel::{with_newer_forms, DECLARED_LDS_FOR_TEST, ONE_WAVE_GROUP_IDS_FOR_TEST}; + use crate::gpu::recomp::CsInterface; + // a one-wave 2-D group that declares one LDS granule, writes LDS and branches on EXEC + let cs = CsInterface { threads: [8, 4, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2, lds_dwords: 128, ..Default::default() }; + let o = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let mut code = encode("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)], None).unwrap(); + code.extend(repeated(100)); + let translate = || super::kernel::translate_compute(&code, o, &cs).unwrap().dxil; + let set = |lds: Option, one_wave: Option, no_fold: bool| { + DECLARED_LDS_FOR_TEST.with(|c| c.set(lds)); + ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.set(one_wave)); + super::module::NO_SELECT_FOLD.with(|c| c.set(no_fold)); + }; + set(Some(false), Some(false), false); + let before = with_compact_min(None, translate); + set(Some(true), Some(true), false); + let newer = with_compact_min(Some(500), translate); + let left_out = with_newer_forms(false, || with_compact_min(Some(500), translate)); + set(None, None, false); + assert_ne!(newer, before, "the newer forms change this program"); + assert!(left_out == before, "left out of the newer forms: {} B, before them: {} B", left_out.len(), before.len()); + assert_eq!(with_newer_forms(true, || with_compact_min(Some(500), || { + set(Some(true), Some(true), false); + let d = translate(); + set(None, None, false); + d + })), newer, "with them: as their switches say"); +} + +/// A compute program in the compact form `XCL_DIRECT_COMPACT_MIN` gives it runs as in the plain +/// one: every thread of a 2-D wave32 group stores its own (group, y, x). +#[test] +fn gpu_compute_compact_form_from_the_size_runs_as_the_plain_form() { + use crate::gpu::recomp::{CsInterface, KERNEL_SGPRS}; + match runner::wave32_supported() { + Ok(true) => {} + Ok(false) => return runner::skip_test("no wave32"), + Err(e) => return runner::skip_test(&e), + } + const V: u64 = 256; + let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + let mut code = Vec::new(); + code.extend(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 1)])); // y · 8 + code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 2)])); // + x + code.extend(i("S_LSHL_B32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 2), ("SSRC1", 134)])); // gid · 64 + code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 2)])); // i + // v3 = x · (y + 1): a loop of y + 1 passes, each lane leaving EXEC after its own + code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128)])); + code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", V + 1)])); + code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 3)])); // loop: v3 += x + code.extend(i("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 129), ("VSRC1", 5)])); // v5 -= 1 + code.extend(i("V_CMP_GT_I32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 5)])); // vcc = 0 > v5 + code.extend(i("S_ANDN2_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)])); // exec &= !vcc + code.extend(i("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFB)])); + code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)])); // exec = all + code.extend(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 2)])); // 4i + code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)])); + code.extend(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 3), ("SADDR", 0x7D)])); + code.extend(i("S_ENDPGM", "ENC_SOPP", &[])); + let cs = CsInterface { threads: [8, 4, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2, ..Default::default() }; + let o = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let groups = 4u32; + let mut want = vec![0xFFFF_FFFFu32; 64 * groups as usize]; + for g in 0..groups { + for y in 0..4 { + for x in 0..8 { + want[(g * 64 + y * 8 + x) as usize] = x * (y + 1); + } + } + } + for min in [None, Some(1)] { + let k = with_compact_min(min, || super::kernel::translate_compute(&code, o, &cs)).unwrap_or_else(|e| panic!("{min:?}: {e}")); + let mem = runner::dispatch(&k.dxil, [groups, 1, 1], &vec![0u32; KERNEL_SGPRS], &vec![0xFFFF_FFFFu32; want.len()]).expect("GPU run"); + assert_eq!(&mem[..want.len()], &want[..], "compact size {min:?}"); + } +} diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 08b7b762ab..0487439dea 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -25,7 +25,7 @@ fn a_single_split_wave_of_a_compute_group_exchanges_without_a_group_barrier() { let code = prog(&[("V_READLANE_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 256), ("SRC1", 160)], None)]); let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; let dis = |threads: u32, code: &[u8]| { - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; super::validate::disassemble(&super::kernel::translate_compute(code, o, &cs).unwrap_or_else(|e| panic!("{threads} threads: {e}")).dxil) }; // (barrier mode 9: the thread group's sync with its memory fence, `ops::barrier::GROUP_SYNC`) @@ -65,7 +65,7 @@ fn a_single_split_wave_of_a_compute_group_exchanges_without_a_group_barrier() { {d}"); // a mesh program's compute pass of one console wave (48 or 64 threads) exchanges the same way for threads in [48, 64] { - let ms = crate::gpu::recomp::MsInterface { outputs: vec![], threads, max_vertices: 64, max_primitives: 64 }; + let ms = crate::gpu::recomp::MsInterface { outputs: vec![], threads, max_vertices: 64, max_primitives: 64, params: None }; let d = super::validate::disassemble(&super::kernel::translate_mesh(&code, o, &ms).unwrap_or_else(|e| panic!("mesh, {threads} threads: {e}")).dxil).unwrap(); assert_eq!(syncs(&d), 1, "mesh, {threads} threads: a group barrier at the exchange: {d}"); @@ -152,7 +152,7 @@ fn split_lds_reads_meet_after_writes() { assert!(looped(&[read, write]) >= looped(&[read]) + 2, "the loop's read and write meet when the bits are set"); // compute groups: the counters' meet (two more atomics), none without a partner half let atomics = |threads: u32, list: &[Inst]| { - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; let d = super::validate::disassemble(&super::kernel::translate_compute(&prog(list), o, &cs).unwrap_or_else(|e| panic!("{threads} threads: {e}")).dxil).unwrap(); d.matches("atomicrmw").count() @@ -188,14 +188,15 @@ fn ps_32bit_rt_export_patches_pkrtz_in_both_backends() { el("SV_Target", 1, 64, 1, 1, 0x1), ], input_ena: 0x2, - attrs: None, - }; + attrs: None, early_depth: false }; let unpatched = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64: false, ..Default::default() }).unwrap(); assert!(unpatched.hlsl.contains("xo.t1[0] = (v6 & 0xFFFFu);"), "unpatched HLSL:\n{}", unpatched.hlsl); let patched = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64: false, ps_rt32_mask: 1 << 1, ..Default::default() }).unwrap(); - assert!(patched.hlsl.contains("xo.t0[0] = f16tof32("), "RT0 must remain compressed:\n{}", patched.hlsl); + // (the PS NaN guard, `XCL_NAN_GUARD`, may wrap the unpacked value in a select) + let rt0 = patched.hlsl.lines().find(|l| l.contains("xo.t0[0] = ")).unwrap_or_default(); + assert!(rt0.contains("f16tof32((v0 & 0xFFFFu))"), "RT0 must remain compressed:\n{}", patched.hlsl); assert!(patched.hlsl.contains("xo.t1[0] = v6;"), "RT1 must export raw 32-bit v6:\n{}", patched.hlsl); assert!(!patched.hlsl.contains("v6 = f16_rtz("), "RT1 pkrtz must be NOPed so v6 keeps its bits:\n{}", patched.hlsl); @@ -230,8 +231,7 @@ fn ps_32bit_rt_export_declines_patch_when_aliased_pkrtz_dst_is_live_after_exp() el("SV_Target", 1, 64, 1, 1, 0x1), ], input_ena: 0x2, - attrs: None, - }; + attrs: None, early_depth: false }; let res = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64: false, ps_rt32_mask: 1 << 1, ..Default::default() }).unwrap(); assert!(res.hlsl.contains("f16_rtz(asfloat(v6))"), "pkrtz must be preserved when v6 is live after EXP:\n{}", res.hlsl); @@ -268,6 +268,7 @@ fn ps_32bit_rt_export_declines_patch_for_clamped_vop3_pkrtz() { outputs: vec![el("SV_Target", 1, 64, 1, 1, 0x1)], input_ena: 0x2, attrs: None, + early_depth: false, }; let hlsl = |clamp: u64| translate(&code(clamp), &Options { mode: Mode::Pixel(psi.clone()), wave64: false, ps_rt32_mask: 1 << 1, ..Default::default() }).unwrap().hlsl; @@ -404,6 +405,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(); @@ -424,6 +426,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 } } @@ -452,7 +579,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)])); } @@ -464,7 +591,7 @@ fn branchy_graphics_stages_validate() { fn wave64_graphics_with_upper_lane_reads_refused_in_32_lane_mode() { use crate::gpu::recomp::{Mode, PsInterface, VsInterface}; let vsi = VsInterface { inputs: vec![], outputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], attr_base: 4, params: 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 }; + 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 upper_body = |exp| { prog(&[ ("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 193)], None), @@ -520,7 +647,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()); @@ -570,6 +697,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; @@ -790,7 +918,7 @@ fn ps_get_lod_with_a_static_sampler() { list.push(("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None)); let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); let code = prog(&refs); - let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None }; + let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None, early_depth: false }; let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; let k = super::kernel::translate_pixel(&code, ko, &psi).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); assert_eq!(k.static_samplers, vec![(linear, false)], "one static sampler, shared by get_lod and sample"); @@ -1129,7 +1257,7 @@ fn count_phis(dis: &str, cap: &str, b: &str) -> Vec { #[test] fn direct_compute_loops_count_each_entry() { use crate::gpu::recomp::CsInterface; - let cs = CsInterface { threads: [8, 4, 2], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [8, 4, 2], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let straight = prog(&[ ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 2)], None), ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 0)], None), @@ -1202,7 +1330,7 @@ fn the_compute_entry_lets_only_the_lanes_below_the_thread_limits_in() { let load = format!("i32 {}, i32 undef, i8 7, i32 4)", IO_THREAD_LIMIT[0] * 4); for (wave64, split, threads) in [(false, false, 32), (true, false, 64), (true, true, 64), (true, true, 32)] { let o = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; // (a split wave64 of 64 threads is two hardware waves: its barrier is the HLSL path's) for barrier in [false, true].into_iter().filter(|&b| !(b && split && threads == 64)) { let what = format!("wave64 {wave64}, split {split}, {threads} threads, barrier {barrier}"); @@ -1278,7 +1406,7 @@ fn gpu_direct_compute_loop_passes_follow_the_dispatch() { Err(e) => return runner::skip_test(&e), } let threads = 64u32; - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; for wave64 in [false, true] { let o = KernelOptions { wave64, split: wave64, mem_windows: 1, sampler_base: 0 }; let run = |code: &[u8], slot: u32| -> u32 { @@ -1407,7 +1535,7 @@ fn compute_movrel_uses_program_max_vgpr_and_masks_m0() { // stored, so DCE keeps the relative move this test looks at ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 0), ("SADDR", 0x7D), ("OFFSET", 0)], None), ]); - let cs = CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let k = super::kernel::translate_compute(&code, ko, &cs).expect("compute movrel translates"); super::validate::validate(&k.dxil).expect("validates"); if let Ok(dis) = super::validate::disassemble(&k.dxil) { @@ -1420,7 +1548,7 @@ fn compute_movrel_uses_program_max_vgpr_and_masks_m0() { fn compute_omits_rodata_without_s_getpc() { use super::kernel::{translate_entry_rodata, Entry}; use crate::gpu::recomp::CsInterface; - let cs = CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let ko = KernelOptions { wave64: false, split: false, mem_windows: 2, sampler_base: 0 }; let rodata = vec![(0x40u32, vec![0x7AB1_E000u32, 0x7AB1_E001, 0xBF81_0000])]; @@ -1520,6 +1648,7 @@ fn raw_loads_in_root_windows_are_branchless() { outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None, + early_depth: false, }; let ps_k = super::kernel::translate_pixel(&ps_code, KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }, &psi) .expect("pixel shader multi-window load translates"); @@ -1689,3 +1818,232 @@ fn raw_buffer_oob_check_guards_32bit_wraparound() { assert!(uge >= 4, "expected wraparound icmp uge checks for load and atomic (got {uge}):\n{dis}"); } } + +/// 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"); +} + +/// `f` with `XCL_DECLARED_LDS` taken as `on` by the translations of this thread. +fn with_declared_lds(on: bool, f: impl FnOnce() -> R) -> R { + let before = super::kernel::DECLARED_LDS_FOR_TEST.with(|c| c.replace(Some(on))); + let r = f(); + super::kernel::DECLARED_LDS_FOR_TEST.with(|c| c.set(before)); + r +} + +/// `XCL_DECLARED_LDS=1`: a compute program's groupshared block is the LDS its header declares +/// (COMPUTE_PGM_RSRC2 LDS_SIZE, 128-dword granules) and the translator's words after it – a +/// native 2-D group's arrival counter, a multi-wave barrier's two words, the split form's +/// exchange slots and counters – or the whole 8,192 dwords when the header gives no size or +/// those words would not fit. Off: always 8,192. +#[test] +fn compute_lds_is_the_declared_block_and_the_translators_words() { + use crate::gpu::recomp::CsInterface; + let write = prog(&[("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)], None)]); + let barrier = prog(&[("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)], None), ("S_BARRIER", "ENC_SOPP", &[], None)]); + let barrier_words = if crate::gpu::recomp::emit::safe_barrier_wanted() { 2 } else { 0 }; + // (threads, granules, split, program, words with the switch) + let cases: [([u32; 3], u32, bool, &[u8], u32); 8] = [ + ([64, 1, 1], 2, false, &write, 256), + ([8, 8, 1], 1, false, &write, 129), + ([8, 8, 1], 1, false, &barrier, 129 + barrier_words), + ([64, 1, 1], 2, false, &barrier, 256 + barrier_words), + ([8, 8, 1], 1, true, &write, 135), + ([128, 1, 1], 2, true, &write, 269), + ([8, 8, 1], 0, true, &write, 8192), + ([8, 8, 1], 64, true, &write, 8192), + ]; + for (threads, granules, split, code, words) in cases { + // the size comes from the stage descriptor (COMPUTE_PGM_RSRC2 at +0x38, LDS_SIZE at bit 15) + let mut descriptor = [0u8; 0x48]; + for (i, v) in [granules << 15 | 2 << 11, threads[0], threads[1], threads[2]].into_iter().enumerate() { + descriptor[0x38 + 4 * i..0x3C + 4 * i].copy_from_slice(&v.to_le_bytes()); + } + let cs = CsInterface::from_descriptor(&descriptor, 0).unwrap(); + assert_eq!(cs.lds_dwords, granules * 128); + let o = KernelOptions { wave64: split, split, mem_windows: 1, sampler_base: 0 }; + for on in [false, true] { + let k = with_declared_lds(on, || super::kernel::translate_compute(code, o, &cs)).unwrap_or_else(|e| panic!("{threads:?}: {e}")); + let dis = super::validate::disassemble(&k.dxil).unwrap(); + let want = if on { words } else { 8192 }; + assert!(dis.contains(&format!("@xcl_lds = external addrspace(3) global [{want} x i32]")), "{threads:?}, {granules} granules, split {split}, switch {on}: {want} words"); + } + } +} + +/// The declared block on the GPU (`XCL_DECLARED_LDS`): a native 2-D wave32 group of two +/// hardware waves (its arrival counter after the program's LDS) whose threads write their +/// index to the LDS, meet at a group barrier (its two words there too) and read another +/// thread's; the same with the switch off. +#[test] +fn gpu_compute_declared_lds_keeps_the_programs_words() { + use crate::gpu::recomp::{runner, CsInterface, KERNEL_SGPRS}; + match runner::wave32_supported() { + Ok(true) => {} + Ok(false) => return runner::skip_test("no wave32"), + Err(e) => return runner::skip_test(&e), + } + const V: u64 = 256; + let code = prog(&[ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 1)], None), // y · 8 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 2), ("VSRC1", 0)], None), // i + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 2)], None), // 4i + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 3), ("DATA0", 2)], None), + ("S_WAITCNT", "ENC_SOPP", &[("SIMM16", 0)], None), + ("S_BARRIER", "ENC_SOPP", &[], None), + ("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 128 + 63), ("VSRC1", 2)], None), // 63 - i + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 130), ("VSRC1", 4)], None), + ("DS_READ_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 5)], None), + ("S_WAITCNT", "ENC_SOPP", &[("SIMM16", 0)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 3)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 6), ("SADDR", 0x7D)], None), + ]); + let cs = CsInterface { threads: [8, 8, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 2, lds_dwords: 128 }; + let o = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + for on in [false, true] { + let k = with_declared_lds(on, || super::kernel::translate_compute(&code, o, &cs)).unwrap_or_else(|e| panic!("switch {on}: {e}")); + let mem = runner::dispatch(&k.dxil, [1, 1, 1], &vec![0u32; KERNEL_SGPRS], &vec![0xFFFF_FFFFu32; 64]).expect("GPU run"); + for i in 0..64 { + assert_eq!(mem[i], 63 - i as u32, "switch {on}: thread {i}"); + } + } +} + +/// `f` with `XCL_ONE_WAVE_GROUP_IDS` taken as `on` by the translations of this thread. +fn with_one_wave_ids(on: bool, f: impl FnOnce() -> R) -> R { + let before = super::kernel::ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.replace(Some(on))); + let r = f(); + super::kernel::ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.set(before)); + r +} + +/// The thread-id program of the one-wave group tests: mem[i] = (gid · 4096) | (y << 8) | x at +/// i = gid · 64 + y · 8 + x. +fn group_ids_program() -> Vec { + const V: u64 = 256; + prog(&[ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 1)], None), // y · 8 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 2)], None), // + x + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 2), ("SSRC1", 134)], None), // gid · 64 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 2)], None), // i + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 136), ("VSRC1", 1)], None), // y << 8 + ("V_OR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 3)], None), // | x + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 2), ("SSRC1", 140)], None), // gid << 12 + ("V_OR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 5), ("VSRC1", 3)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 2)], None), // 4i + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 3), ("SADDR", 0x7D)], None), + ]) +} + +/// `XCL_ONE_WAVE_GROUP_IDS`: a native 2-D group of one hardware wave numbers its threads by +/// lane, with no arrival counter (an LDS atomic) and no group barrier; a group of two waves +/// keeps them. Off: the counter in both. +#[test] +fn a_one_wave_2d_group_numbers_its_threads_without_the_arrival_counter() { + use crate::gpu::recomp::CsInterface; + let o = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + for (threads, one_wave) in [([4u32, 8, 1], true), ([4, 4, 1], true), ([2, 4, 4], true), ([8, 8, 1], false)] { + let cs = CsInterface { threads, user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 3, ..Default::default() }; + for on in [false, true] { + let k = with_one_wave_ids(on, || super::kernel::translate_compute(&group_ids_program(), o, &cs)).unwrap_or_else(|e| panic!("{threads:?}: {e}")); + let dis = super::validate::disassemble(&k.dxil).unwrap(); + let counter = !(on && one_wave); + assert_eq!(dis.contains("atomicrmw add"), counter, "{threads:?}, switch {on}: the arrival counter"); + assert_eq!(dis.contains("@dx.op.barrier"), counter, "{threads:?}, switch {on}: the group barriers"); + } + } +} + +/// The thread ids of one-wave 2-D / 3-D groups on the GPU, with `XCL_ONE_WAVE_GROUP_IDS` off and +/// on: every thread of every group stores its own (group, y, x), a full wave and a partial one. +#[test] +fn gpu_one_wave_2d_groups_number_their_threads_by_lane() { + use crate::gpu::recomp::{runner, CsInterface, KERNEL_SGPRS}; + match runner::wave32_supported() { + Ok(true) => {} + Ok(false) => return runner::skip_test("no wave32"), + Err(e) => return runner::skip_test(&e), + } + let o = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + for threads in [[4u32, 8, 1], [4, 4, 1]] { + let cs = CsInterface { threads, user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2, ..Default::default() }; + let groups = 8u32; + let mut want = vec![0xFFFF_FFFFu32; 64 * groups as usize]; + for g in 0..groups { + for y in 0..threads[1] { + for x in 0..threads[0] { + want[(g * 64 + y * 8 + x) as usize] = g << 12 | y << 8 | x; + } + } + } + for on in [false, true] { + let k = with_one_wave_ids(on, || super::kernel::translate_compute(&group_ids_program(), o, &cs)).unwrap_or_else(|e| panic!("{threads:?}: {e}")); + let mem = runner::dispatch(&k.dxil, [groups, 1, 1], &vec![0u32; KERNEL_SGPRS], &vec![0xFFFF_FFFFu32; want.len()]).expect("GPU run"); + assert_eq!(&mem[..want.len()], &want[..], "{threads:?}, switch {on}"); + } + } +} + +/// `XCL_COHERENT_PER_ACCESS=1` on heap memory windows: in a compute program with an atomic, its +/// plain loads (`s_load`, `global_load` without GLC) take non-coherent windows, its GLC load, the +/// atomic and the store coherent ones; without the switch, or in a program that invalidates a +/// cache, every window access is coherent; a program with neither has none. +#[test] +fn heap_windows_are_coherent_per_access_with_the_switch() { + use crate::gpu::recomp::{CsInterface, HEAP_FLAT, HEAP_WINDOWS}; + let body: &[(&str, &str, &[(&str, u64)], Option)] = &[ + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125)], None), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 2), ("SADDR", 0x7D)], None), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 4), ("ADDR", 2), ("SADDR", 0x7D), ("GLC", 1)], None), + ("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 5), ("ADDR", 2), ("DATA", 6), ("SADDR", 0x7D), ("GLC", 1)], None), + // (the loads' values are stored: the optimizer drops dead raw loads) + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 4), ("VSRC1", 1)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 256 + 4), ("VSRC1", 1)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 1), ("SADDR", 0x7D)], None), + ]; + let atomic = prog(body); + let mut with_inv = body.to_vec(); + with_inv.push(("BUFFER_GL0_INV", "ENC_MUBUF", &[], None)); + let invalidating = prog(&with_inv); + let plain = prog(&body[..2]); + let cs = CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; + let o = KernelOptions { wave64: false, split: false, mem_windows: 4 | HEAP_WINDOWS | HEAP_FLAT, sampler_base: 0 }; + // (heap window handles: RAW_BUFFER | IsUAV, and | IsGloballyCoherent) + let windows = |code: &[u8], on: bool| { + let before = super::kernel::COHERENT_PER_ACCESS_FOR_TEST.with(|c| c.replace(Some(on))); + let k = super::kernel::translate_compute(code, o, &cs); + super::kernel::COHERENT_PER_ACCESS_FOR_TEST.with(|c| c.set(before)); + let dis = super::validate::disassemble(&k.unwrap().dxil).unwrap(); + let heap: Vec<&str> = dis.lines().filter(|l| l.contains("@dx.op.annotateHandle") && l.contains("RWByteAddressBuffer")).collect(); + let coherent = heap.iter().filter(|l| l.contains("i32 20491,")).count(); + // (io at u0 is a plain one: not counted) + (heap.len() - coherent - 1, coherent) + }; + let (plain_on, coherent_on) = windows(&atomic, true); + assert!(plain_on >= 2 && coherent_on >= 3, "switch on: {plain_on} plain, {coherent_on} coherent"); + assert_eq!(windows(&atomic, false).0, 0, "switch off: every window access coherent"); + assert_eq!(windows(&invalidating, true).0, 0, "a cache invalidation keeps every access coherent"); + for on in [false, true] { + assert_eq!(windows(&plain, on).1, 0, "no atomic, no GLC: no coherent window (switch {on})"); + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index d8d9939b27..44a86b4ed1 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -40,6 +40,92 @@ pub struct KernelOptions { /// (the `gpu/dxil` sources are not in build.rs's translator source hash). pub const TRANSLATOR_VERSION: u32 = 12; +thread_local! { + /// The translations on this thread may take the newer forms (`with_newer_forms`). + static NEWER_FORMS: std::cell::Cell = const { std::cell::Cell::new(true) }; +} + +/// `f` with the translations it makes on this thread taking the newer forms (`on`) or none of +/// them: the declared LDS (`XCL_DECLARED_LDS`), one-wave group ids (`XCL_ONE_WAVE_GROUP_IDS`), +/// per-access coherence (`XCL_COHERENT_PER_ACCESS`) and the compact form of +/// `XCL_DIRECT_COMPACT_MIN`. Each still follows its own switch when on; off, a program is +/// translated as before they existed – the same DXIL, which the driver's shader cache of earlier +/// runs still holds (`pso::newer_forms_for`, `XCL_DIRECT_FORMS_ONLY`). +pub fn with_newer_forms(on: bool, f: impl FnOnce() -> R) -> R { + let before = NEWER_FORMS.with(|c| c.replace(on)); + let r = f(); + NEWER_FORMS.with(|c| c.set(before)); + r +} + +/// Whether the translation on this thread may take the newer forms (`with_newer_forms`). +pub fn newer_forms() -> bool { + NEWER_FORMS.with(|c| c.get()) +} + +/// `XCL_DECLARED_LDS` (default on; `=0` off): a compute program's groupshared block is the LDS +/// its header declares (`CsInterface::lds_dwords`) plus the translator's own words after it, +/// instead of the whole 8,192 dwords D3D12 allows (still so when the header gives no size). A +/// one-wave group holding 32 KB let an RDNA WGP (128 KB) run 4 groups: one wave a SIMD. The +/// caches key it apart. (After xcl-dev/xcl#2937, Kalmarv: "XCL_DECLARED_LDS=1 sizes direct +/// compute LDS from the header", there opt-in.) +pub fn declared_lds_enabled() -> bool { + #[cfg(test)] + if let Some(on) = DECLARED_LDS_FOR_TEST.with(|c| c.get()) { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_DECLARED_LDS").map_or(true, |v| v.trim() != "0")) +} + +#[cfg(test)] +thread_local! { + /// `declared_lds_enabled` for the translations of this test thread + pub(crate) static DECLARED_LDS_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// `XCL_COHERENT_PER_ACCESS=1`: in a compute program that needs coherent memory (an atomic or a +/// `GLC` / `DLC` / `SLC` access, `recomp::needs_coherent_mem`) and invalidates no cache, only its +/// stores, atomics and coherent loads take its heap memory windows `globallycoherent`; its plain +/// loads, as the console's, may be cached (L0) - before, one atomic made every load of the +/// program bypass the cache. Heap windows only (`XCL_HEAP_WINDOWS=1`: a handle per access); off +/// by default; the caches key it apart. (After xcl-dev/xcl#2067, "Recompiler: emit +/// per-instruction globallycoherent on compute flat memory".) +pub fn coherent_per_access() -> bool { + #[cfg(test)] + if let Some(on) = COHERENT_PER_ACCESS_FOR_TEST.with(|c| c.get()) { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_COHERENT_PER_ACCESS").is_ok_and(|v| v.trim() == "1")) +} + +#[cfg(test)] +thread_local! { + /// `coherent_per_access` for the translations of this test thread + pub(crate) static COHERENT_PER_ACCESS_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// `XCL_ONE_WAVE_GROUP_IDS` (default on; `=0` off): a native 2-D / 3-D compute group of one +/// hardware wave takes its thread indices from the lanes, without the arrival counter, its +/// atomic and the two group barriers around it (`Lw::setup_lanes_compute`: with one wave the +/// counter's base is always 0). The caches key it apart. (After xcl-dev/xcl#2349, "split native +/// wave32 compute groups beyond [32, 1, 1]", its lanes.rs part.) +pub fn one_wave_group_ids() -> bool { + #[cfg(test)] + if let Some(on) = ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.get()) { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_ONE_WAVE_GROUP_IDS").map_or(true, |v| v.trim() != "0")) +} + +#[cfg(test)] +thread_local! { + /// `one_wave_group_ids` for the translations of this test thread + pub(crate) static ONE_WAVE_GROUP_IDS_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + /// Console compute shaders (and the kernel tests) go through this translator, with the HLSL /// path as the fallback for what it cannot translate yet: the default, and `XCL_DIRECT_DXIL=1`. /// `XCL_DIRECT_DXIL=0` keeps every stage on the HLSL path. @@ -88,12 +174,60 @@ pub struct Kernel { pub dispatch_chain: Option>, } +pub use super::lower_gfx::nan_guard_enabled; pub use super::module::split::DispatchChain; pub fn dispatch_piece_limit() -> usize { std::env::var("XCL_DIRECT_SPLIT_INSTRUCTIONS").ok().and_then(|s| s.parse().ok()).unwrap_or(12_500) } +/// `XCL_RT_GATE=miss`: every `image_bvh*_intersect_ray` misses (the four result dwords all ones, +/// as for a null BVH). Ray-tracing programs then run and write what they write when no ray hits +/// anything, instead of reading half-built/unmapped BVHs or leaving lighting outputs unwritten. +pub fn rt_all_miss() -> bool { + #[cfg(test)] + if let Some(on) = RT_ALL_MISS_FOR_TEST.with(|c| c.get()) { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_RT_GATE").is_ok_and(|v| v.trim().eq_ignore_ascii_case("miss"))) +} + +#[cfg(test)] +thread_local! { + /// `rt_all_miss` for the translations of this test thread + pub(crate) static RT_ALL_MISS_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Loop iterations a lane of a ray-tracing program may run with `XCL_RT_GATE=miss`. +pub const RT_LOOP_BUDGET: u32 = 1 << 9; + +thread_local! { + /// The translation on this thread is of a ray-tracing program (`with_rt_program`). + static RT_PROGRAM: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// `f` with the translations it makes on this thread taken as of a ray-tracing program (`rt`). +pub fn with_rt_program(rt: bool, f: impl FnOnce() -> R) -> R { + let before = RT_PROGRAM.with(|c| c.replace(rt)); + let r = f(); + RT_PROGRAM.with(|c| c.set(before)); + r +} + +/// The loop budget a lane starts with in the program being translated. +pub fn loop_budget() -> u32 { + if RT_PROGRAM.with(|c| c.get()) && rt_all_miss() { + RT_LOOP_BUDGET + } else { + super::lower::LOOP_BUDGET + } +} + +fn has_bvh_inst(insts: &[Decoded]) -> bool { + insts.iter().any(|d| d.inst.name.contains("BVH")) +} + /// `XCL_DIRECT_COMPACT`: `1` forces the compact form, `0` forbids it, unset uses automatic selection. pub fn compact_mode() -> Option { match std::env::var("XCL_DIRECT_COMPACT").as_deref() { @@ -103,6 +237,14 @@ pub fn compact_mode() -> Option { } } +/// `XCL_DIRECT_COMPACT_MIN` (`compact::compact_min`), for the caches' identities. +pub fn compact_min() -> Option { + super::compact::compact_min() +} + +#[cfg(test)] +pub(crate) use super::compact::COMPACT_MIN_FOR_TEST; + /// Non-default `XCL_DIRECT_COMPACT_NEST` cache tag for the translated cache identity. pub fn compact_nest_tag() -> Option { super::compact::nest_mode().cache_tag() @@ -164,24 +306,28 @@ pub(crate) fn translate_geometry_unrefused(code: &[u8], o: KernelOptions, g: &Gs translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None) } -/// Whether `entry` uses the measured, one-path heap-window read form. Graphics, mesh and -/// geometry stages retain the guarded form until they have stage-specific measurements. -fn reads_heap_flat(entry: &Entry, heap: bool, mem_windows: u32) -> bool { - heap && matches!(entry, Entry::Kernel | Entry::Compute(_)) && mem_windows & crate::gpu::recomp::HEAP_FLAT != 0 +/// Whether `entry` uses the one-path heap-window read form: every stage with `HEAP_FLAT`. +/// The guarded form (a branch per access) in a pixel shader let AMD's compiler run the +/// S#-index arithmetic for the live lanes alone and then take helper lanes into the sampler +/// waterfall: their stale index read a sampler past the heap, a page fault and a TDR on world +/// entry (RX 9070 XT, sync-r12). amd-dev ran every stage flat. +fn reads_heap_flat(_entry: &Entry, heap: bool, mem_windows: u32) -> bool { + heap && mem_windows & crate::gpu::recomp::HEAP_FLAT != 0 } #[cfg(test)] #[test] -fn only_compute_programs_read_heap_windows_flat() { +fn every_stage_reads_heap_windows_flat() { use crate::gpu::recomp::{GsInterface, MsInterface, HEAP_FLAT, HEAP_WINDOWS}; let flat = 4 | HEAP_WINDOWS | HEAP_FLAT; assert!(reads_heap_flat(&Entry::Kernel, true, flat)); assert!(reads_heap_flat(&Entry::Compute(CsInterface::default()), true, flat)); - assert!(!reads_heap_flat(&Entry::Mesh(MsInterface::default()), true, flat)); - assert!(!reads_heap_flat(&Entry::Geometry(GsInterface::default()), true, flat)); - assert!(!reads_heap_flat(&Entry::Vertex(VsInterface::default()), true, flat)); - assert!(!reads_heap_flat(&Entry::Pixel(PsInterface::default()), true, flat)); + assert!(reads_heap_flat(&Entry::Mesh(MsInterface::default()), true, flat)); + assert!(reads_heap_flat(&Entry::Geometry(GsInterface::default()), true, flat)); + assert!(reads_heap_flat(&Entry::Vertex(VsInterface::default()), true, flat)); + assert!(reads_heap_flat(&Entry::Pixel(PsInterface::default()), true, flat)); assert!(!reads_heap_flat(&Entry::Compute(CsInterface::default()), true, 4 | HEAP_WINDOWS)); + assert!(!reads_heap_flat(&Entry::Pixel(PsInterface::default()), true, 4 | HEAP_WINDOWS)); assert!(!reads_heap_flat(&Entry::Compute(CsInterface::default()), false, flat)); } @@ -251,13 +397,31 @@ fn translate_entry_with( // a register's definition and its use): a thread with a large stack for big programs let code = code.to_vec(); #[cfg(test)] + let compact_min = super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.get()); + #[cfg(test)] let no_select_fold = super::module::NO_SELECT_FOLD.with(|c| c.get()); + #[cfg(test)] + let declared_lds = DECLARED_LDS_FOR_TEST.with(|c| c.get()); + #[cfg(test)] + let per_access = COHERENT_PER_ACCESS_FOR_TEST.with(|c| c.get()); + #[cfg(test)] + let one_wave = ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.get()); + let newer = newer_forms(); std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) .spawn(move || { + NEWER_FORMS.with(|c| c.set(newer)); + #[cfg(test)] + super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.set(compact_min)); #[cfg(test)] super::module::NO_SELECT_FOLD.with(|c| c.set(no_select_fold)); + #[cfg(test)] + DECLARED_LDS_FOR_TEST.with(|c| c.set(declared_lds)); + #[cfg(test)] + COHERENT_PER_ACCESS_FOR_TEST.with(|c| c.set(per_access)); + #[cfg(test)] + ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.set(one_wave)); translate_on_this_thread(&code, o, entry, compact, nest, rodata, ps_rt32_mask) }) .map_err(|e| format!("translator thread: {e}"))? @@ -304,7 +468,7 @@ fn translate_on_this_thread( crate::gpu::recomp::patch_ps_32bit_exports(&mut cfg.insts, ps_rt32_mask); } 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(_)); if gfx { let upper = crate::gpu::recomp::upper_lanes::analyze_for(&cfg.insts, o.wave64); @@ -323,9 +487,31 @@ fn translate_on_this_thread( return Err("split wave64 LDS access needs the HLSL path".into()); } let leaders: BTreeSet = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); - if gfx && !crate::gpu::recomp::graphics_reductions(&cfg.insts, &leaders, o.wave64).reads.is_empty() { + // (wave32 VS / PS reductions are taken here: `Lw::wave32_reduction`) + let own_reductions = !o.wave64 && matches!(entry, Entry::Vertex(_) | Entry::Pixel(_)); + if gfx && !own_reductions && !crate::gpu::recomp::graphics_reductions(&cfg.insts, &leaders, o.wave64).reads.is_empty() { return Err("graphics whole-wave reduction needs the HLSL path".into()); } + let rt_prog = compute && rt_all_miss() && has_bvh_inst(&cfg.insts); + with_rt_program(rt_prog, || translate_on_this_thread_inner(cfg, geo, o, entry, compact, nest, rodata, leaders, kernel, follow_loads, gfx, compute, split)) +} + +#[allow(clippy::too_many_arguments)] +fn translate_on_this_thread_inner( + mut cfg: Cfg, + geo: Option, + o: KernelOptions, + entry: Entry, + compact: Option, + nest: Option, + rodata: Vec<(u32, Vec)>, + leaders: BTreeSet, + kernel: bool, + follow_loads: bool, + gfx: bool, + compute: bool, + split: bool, +) -> Result { let waterfall_ssamp = super::waterfall::collapse(&mut cfg); // With LDS, a removed rendezvous can also order guest memory and larger slots // would cut into the guest LDS. Keep its existing exchange schedule. @@ -424,7 +610,10 @@ fn translate_on_this_thread( _ if !compute && !kernel => None, Some(false) => None, Some(true) => super::compact::plan(&cfg, &lw), - None => super::compact::automatic_plan(&cfg, &lw, compute && split), + None => match super::compact::compact_min().filter(|_| newer_forms()) { + Some(min) if compute => super::compact::sized_plan(&cfg, &lw, min).or_else(|| super::compact::automatic_plan(&cfg, &lw, split)), + _ => super::compact::automatic_plan(&cfg, &lw, compute && split), + }, }; if let Some(p) = &plan { crate::xlog_info!("[SHADER] direct DXIL compact form: {} blocks of {} kinds", p.order.len(), p.rep.len()); @@ -685,6 +874,7 @@ impl Lw { } let coherent = cs.is_some() && crate::gpu::recomp::needs_coherent_mem(insts); let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows, coherent); + let per_access = heap_mem == Some(true) && coherent_per_access() && newer_forms() && !crate::gpu::recomp::invalidates_caches(insts); let i32 = s.m.i32(); let z = s.m.i32c(0); let mut lw = Lw { @@ -699,6 +889,8 @@ impl Lw { half: z, mems, heap_mem, + per_access, + coherent_inst: true, heap_flat: reads_heap_flat(entry, heap_mem.is_some(), o.mem_windows), res, fmt_table: None, @@ -720,6 +912,7 @@ impl Lw { track_frexp_denorm: crate::gpu::recomp::emit::tracks_frexp_f32_denorm(insts), has_f64_round_op: false, img_writes: crate::gpu::recomp::emit::image_write_srsrcs(insts), + barrier_uav_fence: crate::gpu::recomp::emit::has_uav_write_or_glc(insts), max_vgpr: insts .iter() .flat_map(|d| { @@ -745,6 +938,7 @@ impl Lw { xslot: 1, lds: None, lds_top: 8191, + lds_declared: false, dpp_enable: None, partner: Partner::Present, mesh: None, @@ -753,6 +947,8 @@ impl Lw { gfx_half: None, whole_live: Default::default(), ps_masks: Default::default(), + reductions: Default::default(), + red_seeds: HashMap::new(), mask_batch_end: Default::default(), waterfall_ssamp: Default::default(), pending_masks: Vec::new(), @@ -792,6 +988,10 @@ impl Lw { } } lw.static_samplers = crate::gpu::recomp::constant_samplers(insts, leaders, matches!(entry, Entry::Vertex(_) | Entry::Pixel(_))); + // (as the HLSL path finds them: `recomp::translate`) + if !o.wave64 && matches!(entry, Entry::Vertex(_) | Entry::Pixel(_)) { + lw.reductions = crate::gpu::recomp::graphics_reductions(insts, leaders, false); + } let group_threads: Option = match entry { Entry::Vertex(_) | Entry::Pixel(_) => None, Entry::Kernel => None, @@ -809,7 +1009,7 @@ 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 { + if matches!(entry, Entry::Pixel(_)) && !split && std::env::var("XCL_PS_MASKS").map_or(true, |v| v.trim() != "0") { lw.ps_masks = crate::gpu::recomp::ps_masks::forms(insts, o.wave64); } // (before the storage: the spin exchange has its own slots and counters) @@ -829,7 +1029,17 @@ impl Lw { let safe_bar = lw.barrier_waves.is_some_and(|w| w > 1) && has_s_barrier && crate::gpu::recomp::emit::safe_barrier_wanted(); - lw.setup_storage(uses_lds, if split { slot } else { 1 }, safe_bar); + // `XCL_DECLARED_LDS`: the program's own LDS, then the translator's words; a native 2-D + // / 3-D group's arrival counter (`setup_lanes_compute`) is one of them + let (declared, native_counter) = match entry { + Entry::Compute(cs) if declared_lds_enabled() && newer_forms() => { + let lanes = if o.wave64 { 64 } else { 32 }; + let one_wave = one_wave_group_ids() && newer_forms() && cs.threads.iter().product::() <= lanes; + (cs.lds_dwords, !split && (cs.threads[1] > 1 || cs.threads[2] > 1) && !one_wave) + } + _ => (0, false), + }; + lw.setup_storage(uses_lds, if split { slot } else { 1 }, safe_bar, declared, native_counter); lw } @@ -848,9 +1058,13 @@ impl Lw { let mut dispatch_chain = None; let c = if matches!(stage, Stage::Vertex | Stage::Pixel) { let g = self.gfx.take().ok_or("graphics entry without graphics I/O")?; - let info = if stage == Stage::Pixel { super::graphics::StageInfo::Pixel { early_depth_stencil: false } } else { super::graphics::StageInfo::Vertex }; + let early_depth_stencil = g.ps.as_ref().is_some_and(|p| p.early_depth); + let info = if stage == Stage::Pixel { super::graphics::StageInfo::Pixel { early_depth_stencil } } else { super::graphics::StageInfo::Vertex }; self.s.try_finish_graphics(g.io, info) - } else if limit > 0 && (numthreads == [32, 1, 1] || split_tid.is_some()) && hw == 32 { + } else if limit > 0 + && (((numthreads == [32, 1, 1] || split_tid.is_some()) && hw == 32) + || (numthreads == [64, 1, 1] && hw == 64 && split_tid.is_none())) + { self.s.m.optimize(); // A single split wave64 meets its other half through group-shared counters its entry // zeroes (`Partner::Spin`), and the exchange's running number counts from the @@ -866,7 +1080,7 @@ impl Lw { } } } else { - dispatch_chain = self.s.split_compute(numthreads, split_tid, limit).map(std::sync::Arc::new); + dispatch_chain = self.s.split_compute(numthreads, split_tid, hw, limit).map(std::sync::Arc::new); } self.s.finish_optimized(numthreads, Some(hw)) } else { @@ -920,10 +1134,14 @@ fn dispatch_chain_native_wave64_builds_whole() { } lw.s.m.ret(); lw.s.m.optimize(); - // Exercise the native-wave admission gate with an otherwise partitionable CFG. + // Native Wave64 [64, 1, 1] without LDS/barriers splits into validated WaveSize(64) pieces. assert!(lw.s.m.dispatch_plan(64).is_some()); let program = lw.finish_dispatch(threads, 64, 64, None).unwrap(); - assert!(program.dispatch_chain.is_none()); + let chain = program.dispatch_chain.as_ref().expect("native wave64 [64,1,1] splits into DispatchChain"); + assert!(chain.pieces.len() >= 2); + for piece in &chain.pieces { + super::validate::validate(piece).expect("valid native wave64 split piece"); + } super::validate::validate(&program.dxil).expect("valid native wave64 whole shader"); if !runner::wave64_supported().unwrap_or(false) { @@ -984,7 +1202,7 @@ fn a_split_wave64_compute_program_stays_whole() { fn a_dispatch_chain_leaves_the_lanes_past_a_thread_limit_out() { use crate::gpu::recomp::{runner, IO_THREAD_LIMIT}; let threads = [32, 1, 1]; - let cs = CsInterface { threads, user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads, user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let options = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs.clone())); let (tid, gtid) = lw.setup_lanes_compute(threads, false); @@ -1023,7 +1241,7 @@ fn a_dispatch_chain_leaves_the_lanes_past_a_thread_limit_out() { lw.s.m.set_block(Block(0)); lw.s.m.br(gate); lw.s.m.optimize(); - let chain = lw.s.split_compute(threads, None, 64).expect("a chain of pieces"); + let chain = lw.s.split_compute(threads, None, 32, 64).expect("a chain of pieces"); assert!(chain.pieces.len() >= 2); // the limits are read once, by the first piece let load = format!("i32 {}, i32 undef, i8 7, i32 4)", IO_THREAD_LIMIT[0] * 4); @@ -1322,7 +1540,7 @@ pub fn mesh_init(lw: &mut Lw, ms: &MsInterface, tid: Value, io: super::shader::R let mut vgpr = HashMap::new(); vgpr.insert(5, v5); lw.init.compute = Some(ComputeInit { sgpr, vgpr, zero }); - lw.mesh = Some(super::lower::MeshCtx { rec, vtx, prm, vok, pok, outputs: ms.outputs.clone() }); + lw.mesh = Some(super::lower::MeshCtx { rec, vtx, prm, vok, pok, outputs: ms.outputs.clone(), params: ms.params.clone() }); } /// EXEC at entry: the console wave's threads (static per wave in the split form: no @@ -1492,7 +1710,7 @@ fn gpu_compact_slots_use_the_dispatch_prologues_exec_mask() { ] { code.extend(encode(name, enc, fields, None).unwrap()); } - let cs = CsInterface { threads: [32, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [32, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let options = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; let kernel = translate_entry(&code, options, Entry::Compute(cs), Some(true), None).unwrap(); let initial = [0xa5a5_5a5a; 32]; diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 5746adaa95..02f1977282 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -21,28 +21,43 @@ impl Lw { /// the program's LDS (`lds_words` > 0), multi-wave safe-barrier counters /// (`safe_bar`, 2 words), and, in the split form, the halves' exchange /// words — in the top of the LDS block when there is one (D3D12 allows - /// 32 KB, the whole LDS), as the HLSL kernel lays it out. - pub fn setup_storage(&mut self, lds: bool, slot: u32, safe_bar: bool) { + /// 32 KB, the whole LDS), as the HLSL kernel lays it out. With `declared` + /// dwords (`XCL_DECLARED_LDS`, 0 = not known) the block is the program's + /// LDS followed by those words (and a native 2-D / 3-D group's arrival + /// counter, `native_counter`), when they fit in 8,192. + pub fn setup_storage(&mut self, lds: bool, slot: u32, safe_bar: bool, declared: u32, native_counter: bool) { let i32 = self.s.m.i32(); self.xslot = slot.max(1); if lds { - let g = self.s.groupshared("xcl_lds", i32, 8192); + // the translator's words at the top: [exchange slots, counters (split)], + // [XCL_BAR_ALIVE, XCL_BAR_STATE (safe_bar)], XCL_XW / XCL_WT + let bar_words = if safe_bar { 2 } else { 0 }; + let slots = 4 * self.xslot * self.waves; + let control = if self.split { slots + 2 * self.waves + 1 + bar_words } else { bar_words + u32::from(native_counter) }; + let fits = declared != 0 && declared <= 8192u32.saturating_sub(control); + let words = if fits { declared + control } else { 8192 }; + let g = self.s.groupshared("xcl_lds", i32, words as u64); self.lds = Some(g); if safe_bar { // Words 8189 = XCL_BAR_ALIVE, 8190 = XCL_BAR_STATE (8191 = XCL_XW / XCL_WT), - // matching `recomp::emit::safe_barrier_prelude`. - self.safe_bar = Some((g, 8189)); + // matching `recomp::emit::safe_barrier_prelude`; with the declared LDS of a + // native group right after the program's + self.safe_bar = Some((g, if fits && !self.split { declared } else { words - 3 })); } if self.split { // HLSL: exchange base = 8192 - slots - counters - 1 (- 2 if safe_bar) // (slots = 4 · slot per console wave, 2 counters each); program LDS stops below it. - let bar_words = if safe_bar { 2 } else { 0 }; - let slots = 4 * self.xslot * self.waves; - let base = 8192 - slots - 2 * self.waves - 1 - bar_words; + let base = words - control; self.lds_top = base - 1; self.xs = Some((g, base)); self.xc = Some((g, base + slots)); - self.xw = Some((g, 8191)); + self.xw = Some((g, words - 1)); + } else if fits { + self.lds_top = declared - 1; + self.lds_declared = true; + if native_counter { + self.xw = Some((g, words - 1)); + } } else { self.lds_top = if safe_bar { 8188 } else { 8191 }; } @@ -130,10 +145,10 @@ impl Lw { let t = self.s.m.i1c(true); let rank = self.s.wave_prefix_bit_count(t); self.add(base, rank) - } else if y * z > 1 { + } else if y * z > 1 && !(total <= lanes && super::kernel::one_wave_group_ids() && super::kernel::newer_forms()) { let i32 = self.s.m.i32(); let (g, at) = match (self.lds, lds_top_word) { - (Some(l), true) => (l, 8191), + (Some(l), true) => self.xw.unwrap_or((l, 8191)), _ => (self.s.groupshared("xcl_wt", i32, 1), 0), }; let ai = self.c(at); @@ -154,6 +169,9 @@ impl Lw { let tid = self.add(base, hw); self.s.barrier(barrier::GROUP_SYNC); tid + } else if y * z > 1 { + // one native wave (`XCL_ONE_WAVE_GROUP_IDS`): the counter's base would be 0 + self.s.wave_lane_index() } else { self.s.flattened_thread_id_in_group() }; @@ -642,8 +660,11 @@ impl Lw { /// `recomp::emit::PRELUDE_SAFE_BARRIER`. pub fn safe_barrier_sync(&mut self) { let Some((bar, base)) = self.safe_bar else { return }; - // groupshared memory only, as the HLSL path's `xcl_s_barrier` (`GroupMemoryBarrier`) - let mem_fence = barrier::TGSM_FENCE; + let mem_fence = if self.barrier_uav_fence { + barrier::TGSM_FENCE | barrier::UAV_FENCE_GLOBAL + } else { + barrier::TGSM_FENCE + }; self.s.barrier(mem_fence); let alive_v = self.rd(VAR_BAR_ALIVE); let is_alive = self.nz(alive_v); @@ -950,6 +971,53 @@ impl Lw { } } + /// The quad positions a pixel shader's lane read whose source lane is `src(lane)` takes + /// (`recomp::emit::quad_map`, `ps_quad_reads_wanted`); None where it is not one. + pub fn ps_quad(&self, src: impl Fn(u32) -> Option) -> Option<[u8; 4]> { + use crate::gpu::recomp::emit; + if !self.gfx.as_ref().is_some_and(|g| g.ps.is_some()) || self.split || !emit::ps_quad_reads_wanted() { + return None; + } + emit::quad_map(if self.wave64 { 64 } else { 32 }, src) + } + + /// `v` of quad position `map[lane & 3]` of this lane's quad (`ps_quad`), through + /// `QuadReadLaneAt` with constant lanes alone: quad reads see helper lanes, and no wave read + /// is made (the HLSL `Em::quad_read`). + pub fn read_lane_quad(&mut self, v: Value, map: [u8; 4]) -> Value { + if map == [0, 1, 2, 3] { + return v; + } + if map.iter().all(|&k| k == map[0]) { + let k = self.c(map[0].into()); + return self.s.quad_read_lane_at(v, k); + } + let mut reads: [Option; 4] = [None; 4]; + let mut vals = [v; 4]; + for (i, &k) in map.iter().enumerate() { + let k = k as usize; + if k == i { + continue; + } + if reads[k].is_none() { + let kk = self.c(k as u32); + reads[k] = Some(self.s.quad_read_lane_at(v, kk)); + } + vals[i] = reads[k].unwrap(); + } + let lane = self.lane; + let b1 = self.andc(lane, 1); + let b1 = self.nz(b1); + let lo = if vals[0] == vals[1] { vals[0] } else { self.sel(b1, vals[1], vals[0]) }; + let hi = if vals[2] == vals[3] { vals[2] } else { self.sel(b1, vals[3], vals[2]) }; + if lo == hi { + return lo; + } + let b2 = self.andc(lane, 2); + let b2 = self.nz(b2); + self.sel(b2, hi, lo) + } + /// The guest selects each quad member with two bits of the instruction. /// QuadReadLaneAt accepts a per-lane index and includes active helper lanes. pub fn read_quad_permutation(&mut self, v: Value, perm: u32) -> Value { @@ -1050,6 +1118,68 @@ impl Lw { let lnz = self.nz(lo); self.sel(lnz, fl, hv) } + + /// The end of a whole-wave reduction of a wave32 VS / PS (`recomp::graphics_reductions`, the + /// HLSL `xcl_red_`): `op` over the seed `x` of every live lane of this console wave (a + /// half of a 64-lane hardware wave is one). The console's DPP and permlane steps pass partial + /// results through lanes that are not here: lanes never launched read 0, and a helper lane's + /// wave reads give it 0 too, which every lane then read back from lane 0 (`v_readlane s, v, 0`) + /// – the min of a partly filled wave on a primitive's edge was 0. A helper lane takes the + /// result from a live lane of its quad (every quad has one). + pub fn wave32_reduction(&mut self, x: Value, op: &str) -> Value { + use super::ops::{WaveBit, WaveOp}; + let identity = if matches!(op, "and" | "min") { u32::MAX } else { 0 }; + let reduce = |lw: &mut Lw, v: Value| match op { + "or" => lw.s.wave_active_bit(v, WaveBit::Or), + "and" => lw.s.wave_active_bit(v, WaveBit::And), + "max" => lw.s.wave_active_op(v, WaveOp::Max, true), + _ => lw.s.wave_active_op(v, WaveOp::Min, true), + }; + let r = match self.gfx_half { + Some(h) => { + let id = self.c(identity); + let lo = self.sel(h, id, x); + let hi = self.sel(h, x, id); + let a = reduce(self, lo); + let b = reduce(self, hi); + self.sel(h, b, a) + } + None => reduce(self, x), + }; + if !self.is_pixel() { + return r; + } + let hw = self.s.wave_lane_index(); + let t = self.s.m.i1c(true); + let lv = self.s.wave_ballot(t); + let upper = self.cmpc(Pred::UGe, hw, 32); + let w = self.sel(upper, lv[1], lv[0]); + let sh = self.andc(hw, 28); + let nib = self.bin(BinOp::LShr, w, sh); + let nib = self.andc(nib, 15); + let k = self.firstbitlow(nib); + let q: Vec = (0..4u32).map(|n| { + let kk = self.c(n); + self.s.quad_read_lane_at(r, kk) + }).collect(); + let b1 = self.andc(k, 1); + let b1 = self.nz(b1); + let b2 = self.andc(k, 2); + let b2 = self.nz(b2); + let hi = self.sel(b1, q[3], q[2]); + let lo = self.sel(b1, q[1], q[0]); + self.sel(b2, hi, lo) + } + + /// `v_readfirstlane_b32`'s result `first` of `own` in a pixel shader: a helper lane takes its + /// own value instead so helper-only waterfall loops converge in one pass on AMD RDNA4. + pub fn helper_reads_own(&mut self, own: Value, first: Value) -> Value { + let Some(g) = self.gfx.as_mut().filter(|g| g.ps.is_some()) else { + return first; + }; + let helper = g.io.is_helper_lane(&mut self.s); + self.sel(helper, own, first) + } } #[cfg(test)] @@ -1067,7 +1197,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`, @@ -1317,19 +1447,21 @@ mod ps_ballot_tests { ins(if wave64 { "S_WQM_B64" } else { "S_WQM_B32" }, "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)]), ins("V_CMP_LT_F32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 2)]), // Split basic block so block-local CSE keeps `op`'s live-lane ballot distinct from entry EXEC - // (the skipped s14 is exported: a dead block would be merged away and the two - // identical ballots folded once the optimizer runs again) + // (the skipped write is exported and the select fold is off: the optimizer merges an + // empty or folded block into its join) ins("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 10), ("SSRC1", 128)]), ins("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)]), - ins("S_ADD_U32", "ENC_SOP2", &[("SDST", 14), ("SSRC0", 14), ("SSRC1", 129)]), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 242)]), ins(op, "ENC_SOP2", &[("SDST", dst), ("SSRC0", s0), ("SSRC1", s1)]), ins("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 129), ("SSRC1", 128)]), ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 11)]), - ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 14)]), ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 3), ("VSRC2", 2), ("VSRC3", 5), ("DONE", 1), ("VM", 1)]), ins("S_ENDPGM", "ENC_SOPP", &[]), ].concat(); - let k = kernel::translate_pixel(&c, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, &psi).expect("translate PS"); + crate::gpu::dxil::module::NO_SELECT_FOLD.with(|c| c.set(true)); + let k = kernel::translate_pixel(&c, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, &psi); + crate::gpu::dxil::module::NO_SELECT_FOLD.with(|c| c.set(false)); + let k = k.expect("translate PS"); validate::validate(&k.dxil).expect("validate PS"); let dis = validate::disassemble(&k.dxil).expect("disassemble PS"); assert_eq!(ballots(&dis), want, "wave64 {wave64} {op} dst={dst} s1={s1}:\n{dis}"); diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 07220732d1..7c54233c12 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -78,6 +78,8 @@ pub struct MeshCtx { pub vok: Value, pub pok: Value, pub outputs: Vec, + /// the console's output table (`MsInterface::params`) + pub params: Option>, } /// Initial register values: loaded from `io` in the entry block on first use. @@ -129,7 +131,7 @@ impl Init { fn first(&mut self, s: &mut Shader, var: u32) -> Value { if var == VAR_BUDGET { - return s.m.i32c(LOOP_BUDGET); + return s.m.i32c(super::kernel::loop_budget()); } if var == super::lower_round::VAR_F32_MODE { return s.m.i32c(super::lower_round::MODE_INIT); @@ -252,6 +254,10 @@ pub struct Lw { pub heap_mem: Option, /// Heap windows read without a branch (`recomp::HEAP_FLAT`; compute programs only). pub heap_flat: bool, + /// coherent heap windows for the stores, atomics and coherent loads alone + /// (`kernel::coherent_per_access`); `coherent_inst`: the instruction being lowered is one + pub per_access: bool, + pub coherent_inst: bool, pub res: Option, /// the buffer format table (`FMT_INFO`), created on first use pub fmt_table: Option, @@ -290,6 +296,8 @@ pub struct Lw { pub has_f64_round_op: bool, /// the T# SGPRs of the program's image stores and atomics (`recomp::emit::image_write_srsrcs`) pub img_writes: Vec, + /// program writes/atomics global or image UAVs or uses `GLC=1`: `s_barrier` emits `ALL_SYNC` + pub barrier_uav_fence: bool, /// highest VGPR index referenced by the program (for `v_movrel*` outside `Entry::Kernel`) pub max_vgpr: u64, /// static samplers bound so far: (S#, comparison, handle) at `s, space1` @@ -327,6 +335,9 @@ pub struct Lw { /// the program's LDS (`xcl_lds`, 8192 dwords) and its last usable dword pub lds: Option, pub lds_top: u32, + /// the block is the declared LDS and the words after it (`XCL_DECLARED_LDS`): addresses + /// are kept below them + pub lds_declared: bool, /// DPP write enable of the instruction being lowered pub dpp_enable: Option, /// the split form's partner half: present, missing (a console wave of at most 32 @@ -347,6 +358,10 @@ pub struct Lw { pub(super) pending_masks: Vec<(Dst, Value)>, /// pixel shaders: compares whose mask needs less than the per-quad form (`recomp::ps_masks`) pub ps_masks: std::collections::BTreeMap, + /// wave32 VS / PS: the whole-wave reductions (`recomp::graphics_reductions`), and the + /// temporaries their seeds are kept in (by the seed's pc) + pub reductions: crate::gpu::recomp::Reductions, + pub red_seeds: HashMap, /// set when an exchange was needed where it is not supported pub exchange_error: Option, pub pc: u64, @@ -1061,6 +1076,7 @@ impl Lw { let name = d.inst.name.to_ascii_lowercase(); self.pc = d.pc; self.dpp_enable = None; + self.coherent_inst = !self.per_access || crate::gpu::recomp::coherent_access(d); if name == "s_sendmsg" && self.mesh.is_some() { return self.mesh_sendmsg(d); } @@ -1073,7 +1089,7 @@ impl Lw { if NOOPS.contains(&name.as_str()) { return Ok(()); } - match d.enc.name { + let r = match d.enc.name { "ENC_SOPP" => self.sopp(d, &name), "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" => self.salu(d, &name), "ENC_SMEM" => self.smem(d, &name), @@ -1085,7 +1101,15 @@ impl Lw { "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" => self.flat(d, &name), e if e.starts_with("ENC_VOP") || e.starts_with("VOP") => self.valu(d, &name), _ => err(d, "encoding"), + }; + // the seed of a whole-wave reduction, kept for the `v_readlane` that ends it + if let Some(&v) = self.reductions.seeds.get(&d.pc) { + let x = self.vreg(v); + let t = self.tmp_var(); + self.wr(t, x); + self.red_seeds.insert(d.pc, t); } + r } /// The condition of a conditional branch (i1). @@ -1134,7 +1158,8 @@ impl Lw { if self.safe_bar.is_some() { self.safe_barrier_sync(); } else { - self.s.barrier(super::ops::barrier::GROUP_SYNC); + let mode = if self.barrier_uav_fence { super::ops::barrier::ALL_SYNC } else { super::ops::barrier::GROUP_SYNC }; + self.s.barrier(mode); } // (split form: both halves made their LDS writes before it) self.lds_met(); diff --git a/crates/xcl/src/gpu/dxil/lower_gfx.rs b/crates/xcl/src/gpu/dxil/lower_gfx.rs index 4869231851..b8758cff07 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::{CastOp, Pred, Value}; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded}; -use crate::gpu::recomp::{elements_at, ps_attribute_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, PsInterface, VsInterface}; +use crate::gpu::recomp::{out_param_elements, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, PsInterface, VsInterface}; /// An output element: its signature handle, components and the temporaries holding them. pub struct GfxOut { @@ -119,7 +119,7 @@ impl Lw { _ => SemKind::Arbitrary, }; let s = io.output(GSig::new(&e.name, e.index, kind, gct(e.component_type), n)); - outs.push((s, n, e.component_type == 3)); + outs.push((s, n, matches!(e.component_type, 3 | 6))); } // initial VGPRs: v0 = vertex id, v3 = instance id, the fetch shader's attribute VGPRs let mut vgpr = HashMap::new(); @@ -166,7 +166,8 @@ impl Lw { for (k, e) in ranked(&ps.inputs, false).iter().enumerate() { let attr = ps_slot_attribute(ps, k); let m = attr.and_then(|a| modes.get(&(a as u32))).cloned().unwrap_or_default(); - let float = e.component_type == 3; + // float16 read through a packed attribute interpolates like a float + let float = e.component_type == 3 || (e.component_type == 6 && attr.is_some_and(|a| ps_attribute_f16(ps, a).is_some())); let interp = if !float { Interp::Constant } else { @@ -326,15 +327,22 @@ impl Lw { 32..=63 => { let vs = self.gfx().vs.clone().expect("vs"); let k = (tgt - 32) as usize; - let at = vs_param_register(&vs, k).map(|r| elements_at(&vs.outputs, true, r)).unwrap_or_default(); - for j in at { + let (at, f16) = out_param_elements(&vs.outputs, vs.params.as_deref(), k); + for (j, first) in at { let (vars, n) = { let o = &self.gfx().params[j]; (o.vars.clone(), o.comps) }; for c in 0..n as usize { - if enabled(c) { - let v = comp(self, c); + // packed float16: component c is half c & 1 of dword first + c / 2 + let dw = if f16 { first + c / 2 } else { c }; + if dw < 4 && enabled(dw) { + let mut v = comp(self, dw); + if f16 { + let h = self.lshrc(v, 16 * (c as u32 & 1)); + let x = self.s.f16_to_f32(h); + v = self.bits(x); + } self.set_out(vars[c], v); } } @@ -353,7 +361,7 @@ impl Lw { continue; } let raw = comp(self, c); - let v = match (ct, compr) { + let mut v = match (ct, compr) { (3, true) => { let f = self.s.f16_to_f32(raw); self.bits(f) @@ -361,6 +369,9 @@ impl Lw { (2, true) => self.sx16(raw), _ => raw, }; + if ct == 3 && nan_guard_enabled() { + v = self.nan_guard_bits(v); + } self.set_out(var, v); } } @@ -401,11 +412,20 @@ impl Lw { let s1 = f("SRC1"); (f("VDST"), if s1 >= 256 { s1 - 256 } else { s1 }, f("SRC0") & 0x3F, f("SRC0") >> 6 & 3) }; - let Some(slot) = ps_attribute_slot(&ps, attr as usize, chan as usize) else { return err(d, "attribute outside ISG1") }; + // a float16-packed attribute: the PC input is the component itself (SRC0 bit 8: the + // high half of the dword); a half nothing declares reads 0 + let place = match ps_attribute_f16(&ps, attr as usize).filter(|_| name.ends_with("_f16")) { + Some(regs) => ps_f16_slot(&ps, ®s, chan as usize, d.enc.name != "ENC_VINTRP" && f("SRC0") >> 8 & 1 == 1), + None => match ps_attribute_slot(&ps, attr as usize, chan as usize) { + Some(slot) => Some((slot, chan as usize)), + None => return err(d, "attribute outside ISG1"), + }, + }; let load = |lw: &mut Lw| -> (Value, u32) { + let Some((slot, comp)) = place else { return (lw.fc(0.0), 0) }; let g = lw.gfx.as_mut().expect("gfx"); let (sig, ct) = g.ps_in[slot]; - (g.io.load_input(&mut lw.s, sig, 0, chan as u8), ct) + (g.io.load_input(&mut lw.s, sig, 0, comp as u8), ct) }; let as_f32 = |lw: &mut Lw, x: Value, ct: u32| -> Value { let f32 = lw.s.m.f32(); @@ -452,6 +472,26 @@ impl Lw { } Ok(()) } + + /// `XCL_NAN_GUARD` (default ON unless `"0"`): sanitize PS float color target exports + /// (`NaN -> 0.0`, `±Inf -> ±65504.0`) using bit ops so a single bad pixel never explodes + /// temporal history / bloom cones or crushes auto-exposure on RDNA4. + pub(super) fn nan_guard_bits(&mut self, v: Value) -> Value { + let abs_v = self.andc(v, 0x7FFF_FFFF); + let is_nan = self.cmpc(super::module::Pred::UGt, abs_v, 0x7F80_0000); + let is_inf = self.cmpc(super::module::Pred::Eq, abs_v, 0x7F80_0000); + let sign = self.andc(v, 0x8000_0000); + let max_f16 = self.orc(sign, 0x477F_E000); // ±65504.0f + let no_inf = self.sel(is_inf, max_f16, v); + let zero = self.c(0); + self.sel(is_nan, zero, no_inf) + } +} + +/// Whether PS float color target exports sanitize `NaN` / `±Inf` (`XCL_NAN_GUARD`, on unless `0`). +pub fn nan_guard_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_NAN_GUARD").map_or(true, |v| v.trim() != "0")) } #[cfg(test)] @@ -486,6 +526,7 @@ mod tests { outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, } } @@ -583,6 +624,7 @@ mod tests { outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let ps_f32 = prog(&[ ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 0)], None), diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index 5325805810..388f9d9d6e 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -204,7 +204,26 @@ impl Lw { (mn, mx) }; 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); @@ -977,6 +996,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); @@ -1006,7 +1033,10 @@ impl Lw { let base_lo = self.shlc(d0, 8); let off_lo = self.shlc(nlo, 3); let a = self.add(base_lo, off_lo); - // the window: bits 32.. of the 64-bit address + // the window: bits 32.. of the 64-bit address; also verify the node is non-null + // (`full >= 0x10000`, `hi != 0`) and that both the start and end of a 112 B Box32 + // node (`full + 111`) fall within the same UMA window. + let mut bvh_valid = self.b(true); if self.mems.len() > 1 { let d1lo = self.andc(d1, 0xFF); let b64 = self.pack64(d0, d1lo); @@ -1027,6 +1057,15 @@ impl Lw { let full = self.add(b64, off); let (_, hi) = self.unpack64(full); self.window_hi(hi, false); + let hi_nz = self.nz(hi); + let k111 = self.c64(111); + let full_end = self.add(full, k111); + let (_, hi_end) = self.unpack64(full_end); + let same_hi = self.cmp(Pred::Eq, hi_end, hi); + let k64k = self.c64(0x1_0000); + let non_null = self.cmp(Pred::UGe, full, k64k); + let ok1 = self.land(hi_nz, same_hi); + bvh_valid = self.land(ok1, non_null); } let ty = self.andc(node, 7); let sort = { @@ -1049,7 +1088,8 @@ impl Lw { // The raw memory accessor returns zeros for a missing // window. Those zeros are not a box with four child IDs. let window = lw.rd(VAR_WIN); - let valid = lw.cmpc(Pred::ULt, window, lw.mems.len() as u32); + let w_ok = lw.cmpc(Pred::ULt, window, lw.mems.len() as u32); + let valid = lw.land(w_ok, bvh_valid); let tri = lw.cmpc(Pred::ULt, ty, 4); for (&t, bits) in out.iter().zip([0x7f80_0000, 0x3f80_0000, 0, 0]) { let triangle = lw.c(bits); @@ -1681,7 +1721,15 @@ impl Lw { let c = self.land(run, is); self.guarded(c, &mut |lw| { let tex = lw.s.heap_texture(ui, lkind, true, ct, 4, true); - let v4 = if ct == CompType::F32 { vals.map(|v| lw.f(v)) } else { vals }; + let v4 = if ct == CompType::F32 { + let guard = super::lower_gfx::nan_guard_enabled(); + vals.map(|v| { + let v = if guard { lw.nan_guard_bits(v) } else { v }; + lw.f(v) + }) + } else { + vals + }; lw.s.texture_store(tex, &ic, v4); Ok(()) })?; diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 74a7821d9f..fbb3b94c14 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -159,6 +159,7 @@ impl Lw { &mut self, mut guard: Option, out_tys: &[super::module::Ty], + read: bool, f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec, ) -> Vec { if let Some(c) = guard { @@ -170,7 +171,8 @@ impl Lw { } // Descriptor-heap windows (`#1693`, `XCL_HEAP_WINDOWS=1`): single guarded heap lookup // combined with `guard`, stacking cleanly with vector loads/stores & FormatLoad opt. - if let Some(coherent) = self.heap_mem { + if self.heap_mem.is_some() { + let coherent = self.heap_coherent(read); let windows = self.mems.len() as u32; let w = self.rd(super::lower::VAR_WIN); let inside = self.cmpc(Pred::ULt, w, windows); @@ -399,13 +401,18 @@ 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) { + if let (Some(_), true) = (self.heap_mem, self.heap_flat) { + let coherent = self.heap_coherent(true); let z = self.c(0); if guard.is_some_and(|g| self.s.m.const_u64(g) == Some(0)) { return vec![z; n]; @@ -428,7 +435,14 @@ impl Lw { } let i32 = self.s.m.i32(); let tys = vec![i32; n]; - self.with_mem_many_tys(guard, &tys, f) + self.with_mem_many_tys(guard, &tys, true, f) + } + + /// Whether this access takes its heap window `globallycoherent`: every access of a program + /// that needs coherent memory, or with `per_access` its stores and atomics (`read` false) + /// and the loads of the instructions that ask for it (`coherent_inst`). + fn heap_coherent(&self, read: bool) -> bool { + self.heap_mem == Some(true) && (!read || self.coherent_inst) } pub(crate) fn with_mem_void( @@ -436,18 +450,18 @@ impl Lw { guard: Option, f: &mut dyn FnMut(&mut Lw, RawUav), ) { - let _ = self.with_mem_many_tys(guard, &[], &mut |lw, m| { + let _ = self.with_mem_many_tys(guard, &[], false, &mut |lw, m| { f(lw, m); Vec::new() }); } fn mraw_atomic(&mut self, op: AtomicOp, a: Value, v: Value) -> Value { let ty = self.s.m.type_of(v); - self.with_mem_many_tys(None, &[ty], &mut |lw, m| vec![lw.s.raw_atomic(m, op, a, v)])[0] + self.with_mem_many_tys(None, &[ty], false, &mut |lw, m| vec![lw.s.raw_atomic(m, op, a, v)])[0] } fn mraw_cmpxchg(&mut self, a: Value, c: Value, n: Value) -> Value { let ty = self.s.m.type_of(c); - self.with_mem_many_tys(None, &[ty], &mut |lw, m| vec![lw.s.raw_cmpxchg(m, a, c, n)])[0] + self.with_mem_many_tys(None, &[ty], false, &mut |lw, m| vec![lw.s.raw_cmpxchg(m, a, c, n)])[0] } /// `mem.Load(a & ~3)` pub fn mem_ld(&mut self, a: Value) -> Value { @@ -1241,8 +1255,9 @@ impl Lw { let off = self.add(k, soff); // When imm and soff are both nonzero, their sum can itself carry. // Keep the full address calculation for those loads. + // (Some(coherent): `heap_coherent`, so `per_access` keeps a plain s_load cached) let flat = self.heap_mem.filter(|_| self.heap_flat && self.windowed() - && (imm == 0 || self.s.m.const_u64(soff) == Some(0))); + && (imm == 0 || self.s.m.const_u64(soff) == Some(0))).map(|_| self.heap_coherent(true)); if flat.is_none() { self.buffer_window(d0, d1, &[Ea::U(k), Ea::U(soff)], false); } @@ -2256,10 +2271,10 @@ impl Lw { let a = self.vreg(f("ADDR")); let l = self.swizzle_lane(off16 as u64); let (el, eh) = self.exec_mask(); - let v = if self.is_pixel() && (0x8000..0xc000).contains(&off16) { - self.read_quad_permutation(a, off16 & 0xff) - } else { - self.read_lane_half(a, l) + let v = match self.ps_quad(|lane| Some((lane & 0x20) | crate::gpu::recomp::emit::swizzle_lane(off16 as u64, lane))) { + Some(map) => self.read_lane_quad(a, map), + None if self.is_pixel() && (0x8000..0xc000).contains(&off16) => self.read_quad_permutation(a, off16 & 0xff), + None => self.read_lane_half(a, l), }; let on = self.lanebit_at(el, eh, l); let z = self.c(0); @@ -2589,8 +2604,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); @@ -2699,13 +2719,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)); } } @@ -2808,7 +2838,7 @@ mod stage_guard_tests { } fn cs_iface() -> CsInterface { - CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 } + CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() } } fn gs_iface(gs_start: Option) -> GsInterface { @@ -2826,7 +2856,7 @@ mod stage_guard_tests { } fn ps_iface() -> PsInterface { - PsInterface { inputs: vec![sig("SV_Position", 1, 0)], outputs: vec![sig("SV_Target", 64, 0)], input_ena: 0x302, attrs: None } + PsInterface { inputs: vec![sig("SV_Position", 1, 0)], outputs: vec![sig("SV_Target", 64, 0)], input_ena: 0x302, attrs: None, early_depth: false } } #[test] diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index d98e6a369c..3069fd59c4 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -213,12 +213,16 @@ impl Lw { let fib = self.b(fi); let ok0 = self.lor(fib, on); let ok = self.land(valid, ok0); - let r = if self.is_pixel() && ctrl <= 0xff { - let q = self.read_quad_permutation(v, ctrl as u32); - self.sel(ok, q, v) - } else { - let src_l = self.sel(ok, lc, self.lane); - self.read_lane_half(v, src_l) + let r = match self.ps_quad(|lane| crate::gpu::recomp::emit::dpp16_lane(ctrl, lane)) { + Some(map) => self.read_lane_quad(v, map), + None if self.is_pixel() && ctrl <= 0xff => { + let q = self.read_quad_permutation(v, ctrl as u32); + self.sel(ok, q, v) + } + None => { + let src_l = self.sel(ok, lc, self.lane); + self.read_lane_half(v, src_l) + } }; let (rm, bm) = (fv("ROW_MASK") as u32, fv("BANK_MASK") as u32); let lane = self.lane; @@ -253,14 +257,23 @@ impl Lw { let s = self.bin(BinOp::LShr, k, sh); let s = self.andc(s, 7); let l = self.or(a, s); + let quad = self.ps_quad(|lane| Some((lane & !7) | ((sel as u32 >> (3 * (lane & 7))) & 7))); t = if !fi { let on = self.lanebit_at(el, eh, l); - let src_l = self.sel(on, l, self.lane); - let r = self.read_lane_half(v, src_l); + let r = match quad { + Some(map) => self.read_lane_quad(v, map), + None => { + let src_l = self.sel(on, l, self.lane); + self.read_lane_half(v, src_l) + } + }; let z = self.c(0); self.sel(on, r, z) } else { - self.read_lane_half(v, l) + match quad { + Some(map) => self.read_lane_quad(v, map), + None => self.read_lane_half(v, l), + } }; } if !u.is_empty() { @@ -662,14 +675,23 @@ impl Lw { _ => self.fma_legacy(x, y, cf), }) } - "v_fma_f32" | "v_mad_f32" | "v_fma_legacy_f32" | "v_div_fmas_f32" => { + "v_fma_f32" | "v_mad_f32" | "v_fma_legacy_f32" => { let (x, y, w) = (fs!(0), fs!(1), fs!(2)); fr!(match name { - "v_fma_f32" | "v_div_fmas_f32" => self.fmad(x, y, w), + "v_fma_f32" => self.fmad(x, y, w), "v_mad_f32" => self.mad_nf(x, y, w), _ => self.fma_legacy(x, y, w), }) } + "v_div_fmas_f32" => { + let (x, y, w) = (fs!(0), fs!(1), fs!(2)); + let unscaled = self.fmad(x, y, w); + let vcc = match u.get(3).copied() { + Some(Src::Pair(l, h)) => self.lane_of(l, h), + _ => self.b(false), + }; + fr!(self.div_fmas_f32(x, y, w, vcc, unscaled)) + } "v_fmamk_f32" | "v_madmk_f32" => { let (x, w) = (fs!(0), fs!(2)); let k = self.f(b); @@ -1056,10 +1078,19 @@ impl Lw { let (el, eh) = self.exec_mask(); let l = self.first_lane(el, eh); let t = self.read_lane_uniform(a, l); + let t = self.helper_reads_own(a, t); self.write32(&dst, t); return Ok(()); } "v_readlane_b32" => { + // the end of a whole-wave reduction (`recomp::graphics_reductions`) + if let Some(t) = self.reductions.reads.get(&self.pc).and_then(|red| self.red_seeds.get(&red.seed)).copied() { + let op = self.reductions.reads[&self.pc].op; + let x = self.rd(t); + let r = self.wave32_reduction(x, op); + self.write32(&dst, r); + return Ok(()); + } let l = self.andc(b, wmask); let t = self.read_lane_uniform(a, l); self.write32(&dst, t); @@ -1079,8 +1110,41 @@ impl Lw { let sdst = outs.get(1).map(|o| Self::dst_of(d, o)).unwrap_or(Dst::S(106)); let f = self.b(false); self.write_mask(&sdst, f); - let x = fs!(0); - let r = self.bits(x); + let (s0, dd, nn) = (fs!(0), fs!(1), fs!(2)); + let (u0, du, nu) = (self.bits(s0), self.bits(dd), self.bits(nn)); + let da = self.andc(du, 0x7FFF_FFFF); + let na = self.andc(nu, 0x7FFF_FFFF); + let d_zero = self.cmpc(Pred::Eq, da, 0); + let n_zero = self.cmpc(Pred::Eq, na, 0); + let any_zero = self.lor(d_zero, n_zero); + let d_sh = self.lshrc(du, 23); + let ed = self.andc(d_sh, 0xFF); + let n_sh = self.lshrc(nu, 23); + let en = self.andc(n_sh, 0xFF); + let d_fin = self.cmpc(Pred::ULt, ed, 0xFF); + let n_fin = self.cmpc(Pred::ULt, en, 0xFF); + let both_fin = self.land(d_fin, n_fin); + // Prescale both operands by 2^+64 when d is subnormal/tiny and n*2^64 fits, or + // by 2^-64 when d is huge and n*2^-64 stays normal (factor cancels in n/d so + // rcp(d) never overflows/underflows to Inf/0 -> NaN, with SDST flag kept 0). + let d_tiny = self.cmpc(Pred::ULt, ed, 23); + let n_fits_up = self.cmpc(Pred::ULt, en, 191); + let up_cond = self.land(d_tiny, n_fits_up); + let scale_up = self.land(both_fin, up_cond); + let d_huge = self.cmpc(Pred::UGe, ed, 232); + let n_fits_dn = self.cmpc(Pred::UGe, en, 65); + let dn_cond = self.land(d_huge, n_fits_dn); + let scale_dn = self.land(both_fin, dn_cond); + let p64 = self.c(64); + let m64 = self.c(-64i32 as u32); + let up_f = self.ldexp_f(s0, p64); + let up_bits = self.bits(up_f); + let dn_f = self.ldexp_f(s0, m64); + let dn_bits = self.bits(dn_f); + let qnan = self.c(0x7FC0_0000); + let r = self.sel(scale_up, up_bits, u0); + let r = self.sel(scale_dn, dn_bits, r); + let r = self.sel(any_zero, qnan, r); self.vwrite(d, &dst, r); return Ok(()); } @@ -1180,10 +1244,19 @@ impl Lw { let zz = self.fc(0.0); self.sel(lz, zz, r) } - "v_fma_f32" | "v_div_fmas_f32" => { + "v_fma_f32" => { let n = self.fmad(fa, fb, fc); self.rm_fma(ba, bb, bc, n) } + "v_div_fmas_f32" => { + let n = self.fmad(fa, fb, fc); + let unscaled = self.rm_fma(ba, bb, bc, n); + let vcc = match u.get(3).copied() { + Some(Src::Pair(l, h)) => self.lane_of(l, h), + _ => self.b(false), + }; + self.div_fmas_f32(fa, fb, fc, vcc, unscaled) + } "v_fma_legacy_f32" => { let n = self.fmad(fa, fb, fc); let r = self.rm_fma(ba, bb, bc, n); @@ -1434,7 +1507,7 @@ impl Lw { "le" => self.fcmp(Pred::FOLe, a, b), "gt" => self.fcmp(Pred::FOGt, a, b), "ge" => self.fcmp(Pred::FOGe, a, b), - "lg" => self.fcmp(Pred::FONe, a, b), + "lg" => { let x = self.fcmp(Pred::FOLt, a, b); let y = self.fcmp(Pred::FOGt, a, b); self.lor(x, y) } "o" => self.fcmp(Pred::FOrd, a, b), "u" => self.fcmp(Pred::FUno, a, b), "nlt" => self.fcmp(Pred::FUGe, a, b), @@ -1442,7 +1515,7 @@ impl Lw { "nle" => self.fcmp(Pred::FUGt, a, b), "ngt" => self.fcmp(Pred::FULe, a, b), "nge" => self.fcmp(Pred::FULt, a, b), - "nlg" => self.fcmp(Pred::FUEq, a, b), + "nlg" => { let x = self.fcmp(Pred::FOLt, a, b); let y = self.fcmp(Pred::FOGt, a, b); let lg = self.lor(x, y); self.lnot(lg) } _ => return None, }); } @@ -1655,3 +1728,29 @@ mod valu_carry_tests { assert_eq!(r.sgpr[6], want_subrev_b, "subrev_co_ci borrow-out mask"); } } + +#[cfg(test)] +mod div_f32_tests { + use crate::gpu::dxil::{kernel, validate}; + use crate::gpu::rdna2; + + #[test] + fn direct_dxil_div_scale_fmas_fixup_validate_and_emit_guards() { + let mut code = Vec::new(); + // V_DIV_SCALE_F32 v4, vcc, v1, v2, v1 + code.extend(rdna2::encode("V_DIV_SCALE_F32", "VOP3_SDST_ENC", &[("VDST", 4), ("SDST", 106), ("SRC0", 257), ("SRC1", 258), ("SRC2", 257)], None).unwrap()); + // V_DIV_FMAS_F32 v5, v4, v2, v1 (implicit VCC) + code.extend(rdna2::encode("V_DIV_FMAS_F32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 260), ("SRC1", 258), ("SRC2", 257)], None).unwrap()); + // V_DIV_FIXUP_F32 v6, v5, v2, v1 + code.extend(rdna2::encode("V_DIV_FIXUP_F32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 261), ("SRC1", 258), ("SRC2", 257)], None).unwrap()); + code.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + + let dxil = kernel::translate(&code, kernel::KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }) + .expect("direct translate div sequence"); + validate::validate(&dxil).expect("dxil validate div sequence"); + let dis = validate::disassemble(&dxil).expect("dxil disassemble div sequence"); + assert!(dis.contains("2143289344"), "expected V_DIV_SCALE_F32 0x7FC00000 QNaN guard in DXIL"); + assert!(dis.contains("2139095040"), "expected V_DIV_FIXUP_F32 0x7F800000 Inf guard in DXIL"); + assert!(dis.contains("-64"), "expected V_DIV_FMAS_F32 -64 pre-rounding scale in DXIL"); + } +} diff --git a/crates/xcl/src/gpu/dxil/lower_wide.rs b/crates/xcl/src/gpu/dxil/lower_wide.rs index 15fa07f393..557d7bce00 100644 --- a/crates/xcl/src/gpu/dxil/lower_wide.rs +++ b/crates/xcl/src/gpu/dxil/lower_wide.rs @@ -59,6 +59,18 @@ impl Lw { let x = h(s, i, hi); s.sx16(x) }; + // a source of the 8- and 4-bit dot products with the halves OP_SEL / OP_SEL_HI pick + // (`recomp::emit` `valu_pk`: FSR4's weights are inline constants folded that way) + let dot_op_sel = vop3p && crate::gpu::recomp::emit::dot_op_sel_wanted(); + let pk = |s: &mut Self, i: usize| -> Value { + if !dot_op_sel || (sel >> i & 1 == 0 && sel_hi >> i & 1 == 1) { + return src(i); + } + let lo = h(s, i, false); + let hi = h(s, i, true); + let hi = s.shlc(hi, 16); + s.or(lo, hi) + }; let fr = |s: &mut Self, e: Value| { let e = if clamp { s.un(op::SATURATE, e) } else { e }; // The product of two binary16 operands fits exactly in binary32. @@ -102,10 +114,16 @@ impl Lw { let q = self.mul(a1, b1); Some(self.dot_sum(&[p, q], src(2), false, clamp)) } - "v_dot4_u32_u8" => Some(self.dot_n(src(0), src(1), src(2), 8, false, clamp)), - "v_dot4_i32_i8" => Some(self.dot_n(src(0), src(1), src(2), 8, true, clamp)), + "v_dot4_u32_u8" => { + let (a, b) = (pk(self, 0), pk(self, 1)); + Some(self.dot_n(a, b, src(2), 8, false, clamp)) + } + "v_dot4_i32_i8" => { + let (a, b) = (pk(self, 0), pk(self, 1)); + Some(self.dot_n(a, b, src(2), 8, true, clamp)) + } "v_dot8_u32_u4" if !clamp => { - let (a, b, c) = (src(0), src(1), src(2)); + let (a, b, c) = (pk(self, 0), pk(self, 1), src(2)); let a_lo = self.andc(a, 0x0F0F_0F0F); let b_lo = self.andc(b, 0x0F0F_0F0F); let a_hi = self.lshrc(a, 4); @@ -115,8 +133,14 @@ impl Lw { let t = self.s.dot4_add_u8_packed(c, a_lo, b_lo); Some(self.s.dot4_add_u8_packed(t, a_hi, b_hi)) } - "v_dot8_u32_u4" => Some(self.dot_n(src(0), src(1), src(2), 4, false, clamp)), - "v_dot8_i32_i4" => Some(self.dot_n(src(0), src(1), src(2), 4, true, clamp)), + "v_dot8_u32_u4" => { + let (a, b) = (pk(self, 0), pk(self, 1)); + Some(self.dot_n(a, b, src(2), 4, false, clamp)) + } + "v_dot8_i32_i4" => { + let (a, b) = (pk(self, 0), pk(self, 1)); + Some(self.dot_n(a, b, src(2), 4, true, clamp)) + } _ => None, }; if let Some(e) = dot { diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index 01b328a1c2..9a5febc29d 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -437,6 +437,16 @@ impl Module { let sext = if w >= 64 { v as i64 } else { ((v << (64 - w)) as i64) >> (64 - w) }; self.constant(ConstDef::Int(ty, sext)) } + /// The value of an integer constant (sign-extended to 64 bits), if `v` is one. + pub fn int_const(&self, v: Value) -> Option { + match v { + Value::Const(c) => match self.consts[c as usize] { + ConstDef::Int(_, x) => Some(x), + _ => None, + }, + _ => None, + } + } pub fn i32c(&mut self, v: u32) -> Value { let t = self.i32(); self.const_int(t, v as u64) diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 29a73ce3c8..3dabab7c1e 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -107,7 +107,22 @@ impl Module { Op::Bin(..) | Op::Cast(..) | Op::Cmp(..) | Op::Select(..) | Op::Extract(..) | Op::Gep(..) => Cse::Dom, Op::Load(p, _) if self.is_const_global_ptr(*p) => Cse::Dom, Op::Phi(_) if cfg!(test) && std::env::var_os("XCL_SAMPLE_PHI_CSE").is_some() => Cse::Block, - Op::Call(f, _) if self.funcs[*f as usize].attrs == FnAttrs::ReadNone => Cse::Dom, + Op::Call(f, _) if self.funcs[*f as usize].attrs == FnAttrs::ReadNone => { + let name = &self.funcs[*f as usize].name; + // AMD RDNA4 (`amdxc64.dll`) crashes on null deref if a raw `createHandleFromHeap` + // handle is shared across distinct `annotateHandle` resource kinds or across basic + // blocks, if `annotateHandle` crosses basic blocks, or if `getDimensions` is reused + // at all (29 `CS_RaytracingResolve` pipelines crash on RDNA4 when CSE merges + // `dx.op.getDimensions` calls, even within the same basic block). + if name.starts_with("dx.op.createHandleFromHeap") || name.starts_with("dx.op.getDimensions") { + Cse::No + } else if name.starts_with("dx.op.annotateHandle") { + Cse::Block + } else { + Cse::Dom + } + } + Op::Call(f, _) if self.funcs[*f as usize].name.starts_with("dx.op.getDimensions") => Cse::No, Op::Call(f, _) if self.wave_call(*f) && !self.funcs[*f as usize].name.starts_with("dx.op.waveIsFirstLane") => Cse::Block, _ => Cse::No, } @@ -976,6 +991,56 @@ impl Module { changed } + /// Post-DCE narrowing of `dx.op.rawBufferLoad.*` component masks: if all surviving uses of a + /// load are `ExtractValue` on components `0..=max_c` (never residency status index `4` and + /// never passed whole), narrow its contiguous DXIL mask (`15`/`7`/`3`) to `(1 << (max_c + 1)) - 1`. + fn narrow_raw_buffer_loads(&mut self, order: &[u32]) -> bool { + let mut max_comp = vec![-1i8; self.insts.len()]; + for &b in order { + for &i in &self.blocks[b as usize] { + match &self.insts[i as usize].op { + Op::Extract(Value::Inst(j), idx) if *idx < 4 => { + let slot = &mut max_comp[*j as usize]; + if *slot < 99 { + *slot = (*slot).max(*idx as i8); + } + } + other => other.for_each_operand(|v| { + if let Value::Inst(j) = v { + max_comp[j as usize] = 99; + } + }), + } + } + } + let mut changed = false; + for &b in order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + let mc = max_comp[i]; + if !(0..4).contains(&mc) { + continue; + } + let (mask_ty, cur_mask) = match &self.insts[i].op { + Op::Call(f, args) if args.len() == 6 && self.funcs[*f as usize].name.starts_with("dx.op.rawBufferLoad.") => { + let Some(m) = self.const_u64(args[4]) else { continue }; + (self.value_ty(args[4]), m) + } + _ => continue, + }; + let new_mask = (1u64 << (mc as u32 + 1)) - 1; + if matches!(cur_mask, 3 | 7 | 15) && new_mask < cur_mask { + let c = self.const_int(mask_ty, new_mask); + if let Op::Call(_, args) = &mut self.insts[i].op { + args[4] = c; + changed = true; + } + } + } + } + changed + } + /// Removes immediately redundant `dx.op.barrier` calls within a basic block when no /// memory-visible side effect occurred since an equally-strong or stronger barrier. fn elim_redundant_barriers(&mut self, order: &[u32]) -> bool { @@ -1124,7 +1189,7 @@ impl Module { /// keep their identities; replaced ones simply lose their uses. The passes run again, /// up to `MAX_OPT_ITERS` times, while one of them still changes the function. /// - /// `XCL_DXIL_NO_OPT=phi,cse,select,cfg,dce,merge,alloca,facts,hoist,barrier` (any subset, + /// `XCL_DXIL_NO_OPT=phi,cse,select,cfg,dce,merge,alloca,facts,hoist,barrier,mask` (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(); @@ -1491,6 +1556,10 @@ impl Module { b.retain(|&i| live[i as usize]); } + if !skip("mask") && self.narrow_raw_buffer_loads(&order) { + iter_changed = true; + } + if !skip("merge") && self.simplify_cfg() { iter_changed = true; // merged blocks can leave trivial phis; fold them (back-edge safe) and drop what dies @@ -2757,6 +2826,30 @@ mod tests { } } + #[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"); + } + #[test] fn local_alloca_store_load_forwarding_and_dse() { let mut m = Module::new(); diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index fe11901212..088550388e 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -87,10 +87,9 @@ impl Scratch { } impl Shader { - /// Start with full native wave32 groups. A fresh dispatch can assign a - /// different physical wave to a group; wave-lane index identifies the - /// continuation within a full, single-wave group. - pub(crate) fn split_compute(&self, threads: [u32; 3], split_tid: Option, limit: usize) -> Option { + /// Split a single-wave compute group (`[32, 1, 1]` on wave32, `[64, 1, 1]` on native wave64, + /// or a split-wave64 `[64, 1, 1]` group with `split_tid`) into a `DispatchChain`. + pub(crate) fn split_compute(&self, threads: [u32; 3], split_tid: Option, hw: u32, limit: usize) -> Option { if self.m.globals.iter().any(|g| !g.constant && !(split_tid.is_some() && matches!(g.name.as_str(), "xcl_xw" | "xcl_xs"))) { return None; } @@ -151,11 +150,11 @@ impl Shader { } (stride, slots) = self.m.reuse_piece_slots(&plan, &slots)?; stride.checked_mul(threads[0])?.checked_mul(4)?; - let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, &slots, threads, &prefix)).collect::>>()?; + let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, &slots, threads, hw, &prefix)).collect::>>()?; Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(threads[0])? }) } - fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, slots: &BTreeMap, threads: [u32; 3], prefix: &[u32]) -> Option> { + fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, slots: &BTreeMap, threads: [u32; 3], hw: u32, prefix: &[u32]) -> Option> { let src = &self.m; let mut dst = self.dispatch_piece(); let mut values = HashMap::new(); @@ -278,7 +277,7 @@ impl Shader { } dst.m.optimize(); dst.prune_unused_bindings(); - let blob = dst.finish_optimized(threads, Some(32)).map_err(|e| refused(e.to_string())).ok()?; + let blob = dst.finish_optimized(threads, Some(hw)).map_err(|e| refused(e.to_string())).ok()?; crate::gpu::dxil::validate::validate(&blob).map_err(refused).ok()?; Some(blob) } @@ -845,7 +844,7 @@ mod tests { lw.s.m.optimize(); let plan = lw.s.m.dispatch_plan(32).unwrap(); assert!(plan.edges.iter().any(|edge| edge.live.contains(&old))); - let chain = lw.s.split_compute(geometry, None, 32).expect("admit a UAV ADD"); + let chain = lw.s.split_compute(geometry, None, 32, 32).expect("admit a UAV ADD"); let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); if !runner::wave32_supported().unwrap_or(false) { runner::skip_test("no wave32 GPU"); @@ -964,7 +963,7 @@ mod tests { let plan = lw.s.m.dispatch_plan(40).expect("partition around oversized loop"); assert!(plan.blocks.iter().any(|piece| piece == &[oversized])); } - let chain = lw.s.split_compute(geometry, split.then_some(tid), 40); + let chain = lw.s.split_compute(geometry, split.then_some(tid), 32, 40); let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); crate::gpu::dxil::validate::validate(&whole).expect("valid unsplit fixture"); let chain = if split { @@ -1065,7 +1064,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| { @@ -1115,7 +1114,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); } @@ -1234,7 +1233,7 @@ mod tests { let plan = lw.s.m.dispatch_plan(64).expect("partition branch fixture"); let stage = |b| plan.blocks.iter().position(|blocks| blocks.contains(&b)).unwrap(); assert!(plan.edges.iter().any(|edge| stage(edge.to) > stage(edge.from) + 1), "exercise a forward skip over an intermediate piece"); - let chain = lw.s.split_compute(geometry, split.then_some(tid), 64); + let chain = lw.s.split_compute(geometry, split.then_some(tid), 32, 64); let chain = if split { assert!(chain.is_none(), "a split wave64 that exchanges through counters stays whole"); None diff --git a/crates/xcl/src/gpu/dxil/ops.rs b/crates/xcl/src/gpu/dxil/ops.rs index f7c23eb0df..6a0a4aed75 100644 --- a/crates/xcl/src/gpu/dxil/ops.rs +++ b/crates/xcl/src/gpu/dxil/ops.rs @@ -359,12 +359,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 7c25de5091..7589d20b9c 100644 --- a/crates/xcl/src/gpu/dxil/ops_tests.rs +++ b/crates/xcl/src/gpu/dxil/ops_tests.rs @@ -1078,6 +1078,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 9b07e6f67f..0056c9e99a 100644 --- a/crates/xcl/src/gpu/dxil/prelude.rs +++ b/crates/xcl/src/gpu/dxil/prelude.rs @@ -268,20 +268,97 @@ impl Lw { let y = self.fmin(y, c); self.fmax(x, y) } - /// `div_fixup` + /// `div_fixup` (RDNA2 `V_DIV_FIXUP_F32` exact special-case, sign, and overflow/underflow rules). pub fn div_fixup(&mut self, q: Value, d: Value, n: Value) -> Value { - let a = self.isnan(d); - let b = self.isnan(n); - let z = self.fc(0.0); - let dz = self.fcmp(Pred::FOEq, d, z); - let di = self.isinf(d); - let ni = self.isinf(n); - let x = self.lor(a, b); - let y = self.lor(di, ni); - let y = self.lor(dz, y); - let c = self.lor(x, y); - let r = self.fdiv(n, d); - self.sel(c, r, q) + let (qu, du, nu) = (self.bits(q), self.bits(d), self.bits(n)); + let abs = self.c(0x7FFF_FFFF); + let (qa, da, na) = (self.and(qu, abs), self.and(du, abs), self.and(nu, abs)); + let x = self.xor(du, nu); + let top = self.c(0x8000_0000); + let sign = self.and(x, top); + let inf = self.c(0x7F80_0000); + let zero = self.c(0); + let quiet = self.c(0x0040_0000); + let signed_inf = self.or(sign, inf); + let mut r = self.or(sign, qa); + let q_nan = self.cmp(Pred::UGt, qa, inf); + r = self.sel(q_nan, signed_inf, r); // overflowed quotient: ±Inf + let ff = self.c(0xFF); + let nsh = self.lshrc(nu, 23); + let en = self.and(nsh, ff); + let dsh = self.lshrc(du, 23); + let ed = self.and(dsh, ff); + let k150 = self.c(150); + let en150 = self.add(en, k150); + let under = self.cmp(Pred::ULt, en150, ed); + r = self.sel(under, sign, r); // exponent gap under -150: ±0 + let d_inf = self.cmp(Pred::Eq, da, inf); + let n_zero = self.cmp(Pred::Eq, na, zero); + let to_zero = self.lor(d_inf, n_zero); + r = self.sel(to_zero, sign, r); // x/Inf, 0/x + let d_zero = self.cmp(Pred::Eq, da, zero); + let n_inf = self.cmp(Pred::Eq, na, inf); + let to_inf = self.lor(d_zero, n_inf); + r = self.sel(to_inf, signed_inf, r); // x/0, Inf/x + let zz = self.land(d_zero, n_zero); + let ii = self.land(d_inf, n_inf); + let invalid = self.lor(zz, ii); + let nan = self.c(0xFFC0_0000); + r = self.sel(invalid, nan, r); // 0/0, Inf/Inf + let d_nan = self.cmp(Pred::UGt, da, inf); + let dq = self.or(du, quiet); + r = self.sel(d_nan, dq, r); + let n_nan = self.cmp(Pred::UGt, na, inf); + let nq = self.or(nu, quiet); + r = self.sel(n_nan, nq, r); // NaN operands, numerator wins + self.f(r) + } + + /// `v_div_fmas_f32`: fused multiply-add with exact pre-rounding `2^(±64)` scale when `vcc` is set + /// (`+64` when `exp(s2) > 127`, `-64` otherwise, matching AMD RDNA2 hardware). + pub fn div_fmas_f32(&mut self, s0: Value, s1: Value, s2: Value, vcc: Value, unscaled: Value) -> Value { + let u0 = self.bits(s0); + let u1 = self.bits(s1); + let u2 = self.bits(s2); + let s0_sh = self.lshrc(u0, 23); + let e0 = self.andc(s0_sh, 0xFF); + let s1_sh = self.lshrc(u1, 23); + let e1 = self.andc(s1_sh, 0xFF); + let s2_sh = self.lshrc(u2, 23); + let e2 = self.andc(s2_sh, 0xFF); + let up = self.cmpc(Pred::UGt, e2, 127); + + // Split +64 or -64 across s0 and s1 without intermediate overflow/underflow so the + // single fused multiply-add rounds only once at the final exponent. + let p0 = self.c(0); + let p32 = self.c(32); + let p64 = self.c(64); + let m32 = self.c(-32i32 as u32); + let m64 = self.c(-64i32 as u32); + + let hi0 = self.cmpc(Pred::UGe, e0, 223); + let hi1 = self.cmpc(Pred::UGe, e1, 223); + let up_n0_b = self.sel(hi1, p64, p32); + let up_n0 = self.sel(hi0, p0, up_n0_b); + let up_n1_b = self.sel(hi1, p0, p32); + let up_n1 = self.sel(hi0, p64, up_n1_b); + + let lo0 = self.cmpc(Pred::ULt, e0, 33); + let lo1 = self.cmpc(Pred::ULt, e1, 33); + let dn_n0_b = self.sel(lo1, m64, m32); + let dn_n0 = self.sel(lo0, p0, dn_n0_b); + let dn_n1_b = self.sel(lo1, p0, m32); + let dn_n1 = self.sel(lo0, m64, dn_n1_b); + + let n0 = self.sel(up, up_n0, dn_n0); + let n1 = self.sel(up, up_n1, dn_n1); + let n2 = self.sel(up, p64, m64); + + let sc0 = self.ldexp_f(s0, n0); + let sc1 = self.ldexp_f(s1, n1); + let sc2 = self.ldexp_f(s2, n2); + let scaled = self.fmad(sc0, sc1, sc2); + self.sel(vcc, scaled, unscaled) } /// cube_id / cube_sc / cube_tc / cube_ma pub fn cube(&mut self, name: &str, x: Value, y: Value, z: Value) -> Value { @@ -828,6 +905,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 46bf5c9b1e..ae7526e46b 100644 --- a/crates/xcl/src/gpu/dxil/reload.rs +++ b/crates/xcl/src/gpu/dxil/reload.rs @@ -398,6 +398,49 @@ 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)]); + // A VS or PS keeps no SGPRs at its end: store the result, or the optimizer drops + // every load as dead and the counts say nothing. + let mov20: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 20)]); + let mov21: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 21)]); + let out: I = ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 3), ("SADDR", 125)]); + let once_code = encode(&[LOAD, ADD, mov20, out, END]); + let repeat_code = encode(&[LOAD, ADD, LOAD, sum, mov21, out, END]); + let store_once_code = encode(&[LOAD, ADD, store, sum, mov21, out, END]); + let store_repeat_code = encode(&[LOAD, ADD, store, LOAD, sum, mov21, out, END]); + + let vs = VsInterface::default(); + let vs_once = count_loads(&translate_vertex(&once_code, opts, &vs).expect("VS once").dxil); + 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 9a82e67cae..ab54e405e3 100644 --- a/crates/xcl/src/gpu/dxil/robustness_tests.rs +++ b/crates/xcl/src/gpu/dxil/robustness_tests.rs @@ -68,8 +68,9 @@ 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 cs = CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let o = |wave64, split| KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; let mut out = Vec::new(); for (w, s) in [(false, false), (true, true), (true, false)] { @@ -107,7 +108,7 @@ fn a_group_barrier_of_several_hardware_waves_uses_safe_barrier_directly() { } let code = prog(&[("S_BARRIER", "ENC_SOPP", &[], None)]); let o = |wave64, split| KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; - let cs = |threads| CsInterface { threads, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = |threads| CsInterface { threads, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; // 16 x 16 threads: 8 hardware waves in the split form, 4 native 64-lane ones, 8 of a // 32-lane program; and the two 32-lane halves of one console wave for (wave64, split, threads) in [(true, true, [16, 16, 1]), (true, false, [16, 16, 1]), (false, false, [16, 16, 1]), (true, true, [64, 1, 1])] { @@ -125,7 +126,7 @@ fn a_group_barrier_of_several_hardware_waves_uses_safe_barrier_directly() { // (the kernel form of the tests is no thread group of a title's: its barrier stays) kernel::translate(&code, o(true, true)).expect("kernel"); // a mesh program's compute pass: two console waves a group, as a retail title's - let ms = |threads| crate::gpu::recomp::MsInterface { outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], threads, max_vertices: 64, max_primitives: 64 }; + let ms = |threads| crate::gpu::recomp::MsInterface { outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], threads, max_vertices: 64, max_primitives: 64, params: None }; for split in [true, false] { let k = kernel::translate_mesh(&code, o(true, split), &ms(128)) .unwrap_or_else(|e| panic!("mesh pass failed (split {split}): {e}")); @@ -206,7 +207,7 @@ fn gpu_a_multi_wave_barrier_after_the_f32_mode_is_set_to_zero_still_waits() { ("S_ROUND_MODE", "ENC_SOPP", &[("SIMM16", 1)], None), ]); let threads = 128u32; - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; for (wave64, split) in [(false, false), (true, true)] { let o = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; let k = kernel::translate_compute(&code, o, &cs).unwrap_or_else(|e| panic!("wave64 {wave64}: {e}")); @@ -221,7 +222,7 @@ fn gpu_a_multi_wave_barrier_after_the_f32_mode_is_set_to_zero_still_waits() { fn split_wave64_real_lds_is_left_to_the_hlsl_path() { let write = prog(&[("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)], None)]); let swizzle = prog(&[("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 1), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 4)], None)]); - let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let o = |wave64, split| KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; // the direct translator orders split LDS itself (`XCL_X_LDS_ORDER`, on by default); without @@ -242,7 +243,7 @@ fn split_wave64_real_lds_is_left_to_the_hlsl_path() { fn split_wave64_spin_uses_fail_closed_direct_dxil() { const V: u64 = 256; let code = prog(&[("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V)], None)]); - let cs = CsInterface { threads: [128, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [128, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let options = |split| KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }; kernel::translate_compute(&code, options(true), &cs).expect("counter-paired direct DXIL translation"); kernel::translate_compute(&code, options(false), &cs).expect("native wave64 translation"); diff --git a/crates/xcl/src/gpu/mod.rs b/crates/xcl/src/gpu/mod.rs index 3c5d634f4c..7d31717575 100644 --- a/crates/xcl/src/gpu/mod.rs +++ b/crates/xcl/src/gpu/mod.rs @@ -12,6 +12,7 @@ pub(crate) mod fence; pub mod pack; pub mod rdna2; pub mod recomp; +pub mod rt_leave_out; mod rdna2_scan; mod rdna2_spec; mod rdna2_xbox; diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 9c03999491..753f75c048 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -386,6 +386,7 @@ impl DxcMalloc { if heap.is_null() { Err(format!("HeapCreate for DXC: {}", std::io::Error::last_os_error())) } else { + crate::heap_count::note_heap("DXC", heap as usize); Ok(Self { heap }) } } @@ -884,6 +885,21 @@ fn pool() -> &'static Arc { } /// Compile HLSL to signed DXIL. `profile` e.g. "cs_6_6"; `extra` are dxc arguments. +/// A helper program XCL used to give `D3DCompile` (`x_5_0`): compiled with DXC as `x_6_0`. +/// Under Wine `D3DCompile` is vkd3d-shader's HLSL compiler, which refuses several of them, and +/// each caller then switched its feature off without a word. None: DXC refused it too (the +/// caller tries `D3DCompile`). +pub fn compile_sm6_first(src: &str, entry: &str, target: &str) -> Option> { + let t = target.replacen("_5_0", "_6_0", 1).replacen("_5_1", "_6_0", 1); + match compile(src, entry, &t, &[]) { + Ok(b) => Some(b), + Err(e) => { + crate::xlog_warn!("DXC: a helper program ({entry}, {t}) does not compile: {e}; trying D3DCompile"); + None + } + } +} + pub fn compile(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { let (reply, rx) = std::sync::mpsc::channel(); let job = Job { @@ -1127,10 +1143,17 @@ pub(super) fn toolchain_identity() -> &'static str { }) } -/// Generated sources shorter than this are keyed without comments and indentation. Above this -/// threshold source length also selects DXC optimization flags, so the exact text stays in the key. +/// Sources shorter than this are keyed without their comments and indentation +/// (`hash_code_lines`). Up to 1 MiB DXC gets no -O switch (`compile_with`, `link_opt_args`), so +/// two such sources with the same code lines get the same DXC arguments and the same DXIL; the +/// margin covers a linked program's declarations (`emit::linked_form`, a few KB) on top of its +/// source. Longer sources are keyed on their full text: their length, comments included, picks +/// the -O level. const KEY_CODE_LINES_BELOW: usize = 1024 * 1024 - 64 * 1024; +/// FNV-1a 64 of the inputs that determine the DXIL. DXC still compiles the full `src`; the key +/// leaves out what does not reach the DXIL, so programs that differ only in their +/// `// pc: instruction` comments (data words, other offsets) share one compile. fn cache_key_for_toolchain(src: &str, entry: &str, profile: &str, toolchain: &str) -> u64 { key_for_toolchain(src, entry, profile, toolchain, src.len() < KEY_CODE_LINES_BELOW && code_lines_keyable(src)) } @@ -1176,6 +1199,10 @@ fn fnv_bytes(mut h: u64, bytes: impl Iterator) -> u64 { h } +/// Hash `src` as DXC's preprocessor sees it, less what cannot change the DXIL: `//` and `/* */` +/// comments (outside string literals) become a space, every line is trimmed, and empty lines are +/// left out. Lines stay separate, so preprocessor directives keep their extent. For a source +/// `code_lines_keyable` accepts (`cache_key_for_toolchain`). fn hash_code_lines(mut h: u64, src: &str) -> u64 { let mut line = Vec::with_capacity(256); let (mut block, mut string) = (false, false); @@ -1515,6 +1542,14 @@ fn store_error_file(file: &Path, key: u64, src_len: usize, reason: &str) { } } +/// `XCL_DXC_SOURCE_DUMP=`: every source the DXIL cache is asked for, as +/// `..hlsl` under the key its entry has. +fn dump_source(key: u64, profile: &str, src: &str) { + if let Some(d) = std::env::var_os("XCL_DXC_SOURCE_DUMP") { + let _ = std::fs::write(Path::new(&d).join(format!("{key:016x}.{profile}.hlsl")), src); + } +} + #[cfg(test)] fn compile_cached_in_observed( dir: &Path, @@ -1542,6 +1577,7 @@ fn compile_cached_keyed( where F: FnOnce() -> Result, String>, { + dump_source(key, profile, src); let dir = normalized_cache_dir(dir); let file = dir.join(format!("{key:016x}.dxil")); let err_file = dir.join(format!("{key:016x}.err")); @@ -1719,6 +1755,7 @@ where } Some(bytes) }) { + dump_source(key, profile, src); cache_counters().hits.fetch_add(1, Ordering::Relaxed); return Ok((bytes, true)); } @@ -1849,6 +1886,55 @@ mod cache_tests { assert_ne!(a, cache_key_for_toolchain("source", "main", "cs_6_6", "compiler-a/signer-b")); } + #[test] + fn cache_key_leaves_out_comments_and_indentation() { + let key = |src: &str| cache_key_for_toolchain(src, "main", "cs_6_6", "tc"); + let a = "// generated by XCL\n[numthreads(64, 1, 1)]\nvoid main()\n{\n // 0000: v_nop ; lit 0x1\n uint s0 = io.Load(0u); // the first SGPR\n /* a\n block */ io.Store(0u, s0);\n}\n"; + let b = "// generated by XCL\n[numthreads(64, 1, 1)]\nvoid main()\n{\n // 0000: v_nop ; lit 0x2\n\n uint s0 = io.Load(0u);\n io.Store(0u, s0); \n}"; + assert_eq!(key(a), key(b), "programs that differ only in comments and whitespace around lines share a key"); + // what reaches the DXIL keeps keys apart + assert_ne!(key(a), key(&a.replace("io.Load(0u)", "io.Load(4u)"))); + assert_ne!(key(a), key(&a.replace("uint s0", "uint s0")), "spaces inside a line are kept"); + assert_ne!(key(a), key(&a.replace("[numthreads(64, 1, 1)]\nvoid", "[numthreads(64, 1, 1)] void")), "line breaks are kept"); + assert_ne!(key("#define X 1\nuint y = X;\n"), key("#define X 1 uint y = X;\n")); + assert_ne!(key("[shader(\"compute\")]\n"), key("[shader(\"com//pute\")]\n"), "string literals are code"); + assert_ne!(key(a), cache_key_for_toolchain(a, "main", "cs_6_7", "tc")); + assert_ne!(key(a), cache_key_for_toolchain(a, "other", "cs_6_6", "tc")); + // a backslash-newline continues a comment: such a source keys on its full text + let spliced = "uint a = 1u; // note \\\nuint b = 2u;\n"; + assert_ne!(key(spliced), key("uint a = 1u;\n")); + assert_ne!(key(spliced), key("uint a = 1u; // other \\\nuint b = 2u;\n")); + } + + #[test] + fn cache_key_of_a_long_source_keeps_its_comments() { + // from 1 MiB the length (comments included) picks the -O level (`link_opt_args`) + let code = "uint s0 = io.Load(0u);\n"; + let mut long = String::new(); + while long.len() < KEY_CODE_LINES_BELOW { + long.push_str(code); + } + let commented = format!("// 0000: v_nop\n{long}"); + let key = |src: &str| cache_key_for_toolchain(src, "main", "cs_6_6", "tc"); + assert_ne!(key(&long), key(&commented)); + assert_eq!(key(&long), key(&long.clone())); + assert!(KEY_CODE_LINES_BELOW < 1024 * 1024, "keyed without comments only where DXC gets no -O switch"); + } + + #[test] + fn a_linked_program_stays_within_the_code_line_key_margin() { + // `compile_here` links a compute program: its -O level follows the linked program's + // length, which is the source plus the accessor declarations less the inline accessors + let inline = super::super::emit::mem_accessors(4, None); + let mut src = format!("{inline}[numthreads(64, 1, 1)]\nvoid main()\n{{\n"); + for _ in 0..LINK_MIN_ACCESSES { + src.push_str(" xcl_mStore(0u, xcl_mLoad(0u));\n"); + } + src.push_str("}\n"); + let (program, _) = super::super::emit::linked_form(&src, LINK_MIN_ACCESSES).expect("linked form"); + assert!(program.len() <= src.len() + (1024 * 1024 - KEY_CODE_LINES_BELOW), "{} > {} + margin", program.len(), src.len()); + } + #[test] fn generated_cache_keys_ignore_only_comments_and_outer_indentation() { let key = |src: &str| cache_key_for_toolchain(src, "main", "cs_6_6", "tc"); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index f60f533602..466d7ea813 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}; @@ -75,6 +75,9 @@ pub(super) struct Em { safe_barrier: bool, /// any console group barrier; with LDS, this excludes cross-wave-local remapping has_s_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`) @@ -84,6 +87,23 @@ pub(super) struct Em { pub writes_lds: bool, } +/// True when the program writes or atomically updates global/image memory or performs a +/// globally-coherent (`GLC=1`) memory access. On RDNA4, `s_barrier` in such shaders must emit +/// a global UAV fence (`AllMemoryBarrierWithGroupSync` / `barrier::ALL_SYNC`) so L0/L1 caches +/// become visible across waves/workgroups alongside LDS/TGSM. +pub fn has_uav_write_or_glc(insts: &[Decoded]) -> bool { + insts.iter().any(|d| { + if !matches!(d.enc.name, "ENC_MUBUF" | "ENC_MTBUF" | "ENC_MIMG" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_SMEM") { + return false; + } + if rdna2::field_value(d.enc, &d.words, "GLC") == Some(1) { + return true; + } + let n = d.inst.name; + n.contains("STORE") || n.contains("ATOMIC") + }) +} + /// The T# SGPRs (SRSRC) of a program's image stores and atomics, at most 16, sorted. An /// image_load reads through the UAV (`tw0 + 1`) where the invocation stored to the same image /// before (`xcl_iw{srsrc}` holds `tw0 + 1` of the last such store): the SRV need not see a @@ -311,6 +331,56 @@ fn dpp16_src(ctrl: u64) -> Option { }) } +/// `dpp16_src` for one lane: the source lane, None where there is none. +pub(crate) fn dpp16_lane(ctrl: u64, lane: u32) -> Option { + let n = (ctrl & 15) as u32; + let r = lane & 15; + match ctrl { + 0x000..=0x0FF => Some((lane & !3) | ((ctrl as u32 >> (2 * (lane & 3))) & 3)), + 0x101..=0x10F => (r + n < 16).then_some(lane + n), + 0x111..=0x11F => (r >= n).then(|| lane - n), + 0x121..=0x12F => Some((lane & !15) | (r.wrapping_sub(n) & 15)), + 0x140 => Some((lane & !15) | (15 - r)), + 0x141 => Some((lane & !15) | (lane & 8) | (7 - (lane & 7))), + 0x150..=0x15F => Some((lane & !15) | n), + 0x160..=0x16F => Some(lane ^ n), + _ => None, + } +} + +/// A lane read whose source `src(lane)` lies in the reader's quad for each of the wave's `lanes` +/// lanes, at a quad position that depends only on the reader's: that position for each reader's +/// (`map[lane & 3]`); None when a source leaves the quad or is missing. +pub(crate) fn quad_map(lanes: u32, src: impl Fn(u32) -> Option) -> Option<[u8; 4]> { + let mut map = [None; 4]; + for l in 0..lanes { + let s = src(l)?; + if s >> 2 != l >> 2 { + return None; + } + let k = &mut map[(l & 3) as usize]; + if k.is_some_and(|k| k != s & 3) { + return None; + } + *k = Some(s & 3); + } + Some(map.map(|k| k.unwrap_or(0) as u8)) +} + +/// Pixel shaders: lane reads that stay in the reader's quad (DPP quad_perm, row_xmask below 4, +/// such DPP8 and `ds_swizzle` patterns) read through `QuadReadLaneAt` alone (`quad_map`), not +/// `rla`, whose wave reads and ballot only served lanes of other quads; on AMD a wave read inside +/// a loop leaves helper lanes' registers unreliable, and the console's derivatives read them. +/// `XCL_PS_QUAD_READS=0`: through `rla`, the earlier form (both translators). +pub fn ps_quad_reads_wanted() -> bool { + ps_quad_reads_for(std::env::var("XCL_PS_QUAD_READS").ok().as_deref()) +} + +/// `ps_quad_reads_wanted` for the value `env` of `XCL_PS_QUAD_READS`: on unless it is `0`. +pub(crate) fn ps_quad_reads_for(env: Option<&str>) -> bool { + env.is_none_or(|v| v.trim() != "0") +} + /// The lane `lane` of a 32-lane half reads with `ds_swizzle_b32` (the RDNA ISA's DS_SWIZZLE_B32): /// offset ≥ 0xE000 FFT, ≥ 0xC000 rotate, bit 15 quad permute, otherwise the and/or/xor bit /// mode (xor = offset[14:10], so 0x401F swaps the 16-lane halves). @@ -632,6 +702,7 @@ impl Em { track_frexp_denorm: false, safe_barrier: false, has_s_barrier: false, + barrier_uav_fence: false, img_writes: Vec::new(), coherent_mem: false, writes_lds: false, @@ -654,6 +725,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 { @@ -762,6 +834,43 @@ impl Em { } } + /// The quad positions a pixel shader's lane read whose source lane is `src(lane)` takes + /// (`quad_map`, `ps_quad_reads_wanted`); None where it is not one. + fn ps_quad(&self, src: impl Fn(u32) -> Option) -> Option<[u8; 4]> { + if !matches!(self.opt.mode, Mode::Pixel(_)) || self.x64() || !ps_quad_reads_wanted() { + return None; + } + quad_map(if self.opt.wave64 { 64 } else { 32 }, src) + } + + /// `v` of quad position `map[lane & 3]` of this lane's quad (`ps_quad`), through + /// `QuadReadLaneAt` with constant lanes alone (declared as `{t}_q`). + fn quad_read(&mut self, v: &str, map: [u8; 4], t: &str) -> String { + if map == [0, 1, 2, 3] { + return v.to_string(); + } + if map.iter().all(|&k| k == map[0]) { + return format!("QuadReadLaneAt({v}, {}u)", map[0]); + } + let mut read = [false; 4]; + let mut vals: Vec = Vec::new(); + for (i, &k) in map.iter().enumerate() { + if k as usize == i { + vals.push(v.to_string()); + continue; + } + if !read[k as usize] { + read[k as usize] = true; + self.line(&format!("uint {t}_q{k} = QuadReadLaneAt({v}, {k}u);")); + } + vals.push(format!("{t}_q{k}")); + } + let pick = |a: &str, b: &str, bit: u32| if a == b { a.to_string() } else { format!("select((lane_id & {bit}u) != 0u, {b}, {a})") }; + let lo = pick(&vals[0], &vals[1], 1); + let hi = pick(&vals[2], &vals[3], 1); + pick(&lo, &hi, 2) + } + /// Lane read with the same lane index in every lane (v_readlane, v_readfirstlane). fn rla_uniform_fn(&self) -> &'static str { if self.x64() { @@ -1329,20 +1438,26 @@ impl Em { match name { "s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done" => Flow::End, "s_barrier" => { + let sync_fn = if self.barrier_uav_fence { "AllMemoryBarrierWithGroupSync" } else { "GroupMemoryBarrierWithGroupSync" }; + let mem_fn = if self.barrier_uav_fence { "AllMemoryBarrier" } else { "GroupMemoryBarrier" }; if self.x64() && matches!(self.opt.mode, Mode::Geometry(_)) { // split ES+GS: the GS phase runs in the lower hardware wave alone (one console // wave: nothing to wait for), a group barrier there would wait for the other - self.line("if (xcl_es_phase) GroupMemoryBarrierWithGroupSync();"); + self.line(&format!("if (xcl_es_phase) {sync_fn}();")); } else if matches!(self.opt.mode, Mode::Compute(_) | Mode::Mesh(_)) { if self.safe_barrier { - self.line("xcl_s_barrier();"); + if self.barrier_uav_fence { + self.line("AllMemoryBarrier(); xcl_s_barrier(); AllMemoryBarrier();"); + } else { + self.line("xcl_s_barrier();"); + } } else if self.compute_or_mesh_hw_waves() == Some(1) { - self.line("GroupMemoryBarrier();"); + self.line(&format!("{mem_fn}();")); } else { - self.line("GroupMemoryBarrierWithGroupSync();"); + self.line(&format!("{sync_fn}();")); } } else if matches!(self.opt.mode, Mode::Kernel | Mode::Geometry(_)) { - self.line("GroupMemoryBarrierWithGroupSync();"); + self.line(&format!("{sync_fn}();")); } // split wave64: both halves made their LDS writes before the barrier (a half // without a partner has nothing to wait for) @@ -1918,7 +2033,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") { @@ -2380,18 +2503,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};")); } @@ -2412,6 +2543,14 @@ impl Em { (2, false) => format!("(int){raw}"), (_, _) => raw, }; + // NaN → 0, ±Inf → ±65504, finite values as they are (the direct + // translator's `nan_guard_bits`): a clamp of every value to the f16 range + // cut what a 32-bit float target holds above 65504 + let v = if e.component_type == 3 && crate::gpu::dxil::kernel::nan_guard_enabled() { + format!("select((asuint({v}) & 0x7FFFFFFFu) > 0x7F800000u, 0.0f, select((asuint({v}) & 0x7FFFFFFFu) == 0x7F800000u, asfloat((asuint({v}) & 0x80000000u) | 0x477FE000u), {v}))") + } else { + v + }; st.push(format!("xo.t{tgt}[{c}] = {v};")); } } else { @@ -2442,15 +2581,19 @@ impl Em { // param N is a register: its record slot is that of every element there (the // pass-through reads an element's slot as the whole register, as for the GS) let k = (tgt - 32) as usize; - let at = param_registers(&ms.outputs, true).get(k).map(|&r| elements_at(&ms.outputs, true, r)).unwrap_or_default(); + let (at, f16) = out_param_elements(&ms.outputs, ms.params.as_deref(), k); if at.is_empty() { self.line("/* param without an OSG1 element (dummy) */"); return Ok(()); } - for j in at { + for (j, first) in at { for c in 0..4 { - if enabled(c) { - st.push(format!("if (xcl_vok) res.Store((xcl_vtx + {}u) * 4u, {});", 4 * (j + 1) + c, Self::exp_comp(srcs, compr, c))); + // packed float16 (as in the VS): the record keeps each half as a float + let dw = if f16 { first + c / 2 } else { c }; + if dw < 4 && enabled(dw) { + let v = Self::exp_comp(srcs, compr, dw); + let v = if f16 { format!("asuint(f16tof32({v} >> {}u))", 16 * (c & 1)) } else { v }; + st.push(format!("if (xcl_vok) res.Store((xcl_vtx + {}u) * 4u, {v});", 4 * (j + 1) + c)); } } } @@ -2491,10 +2634,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" => { @@ -3225,8 +3379,13 @@ impl Em { self.line(&format!( "bool {t}_ok = and({t}_l >= 0, or({fi}, lanebit_at({el}, {eh}, (uint){t}_l)));" )); - let rla = self.rla_half_fn(); - self.line(&format!("uint {t} = {rla}({v}, (uint)max({t}_l, 0));")); + if let Some(map) = self.ps_quad(|lane| dpp16_lane(ctrl, lane)) { + let r = self.quad_read(&v, map, &t); + self.line(&format!("uint {t} = {r};")); + } else { + let rla = self.rla_half_fn(); + self.line(&format!("uint {t} = {rla}({v}, (uint)max({t}_l, 0));")); + } let (rm, bm) = (fv("ROW_MASK"), fv("BANK_MASK")); // write enable: row/bank masks, and an invalid source either reads 0 (bound_ctrl) or disables let mut en = format!("((({rm}u >> (lane_id >> 4)) & 1u) != 0u && (({bm}u >> ((lane_id >> 2) & 3u)) & 1u) != 0u)"); @@ -3240,8 +3399,13 @@ impl Em { let sel: u64 = (0..8).map(|i| fv(&format!("LANE_SEL_{i}")) << (3 * i)).sum(); let fi = rdna2::field_value(d.enc, &d.words, "SRC0").unwrap_or(0) == 0xEA; self.line(&format!("uint {t}_l = (lane_id & ~7u) | (({sel}u >> (3u * (lane_id & 7u))) & 7u);")); - let rla = self.rla_half_fn(); - self.line(&format!("uint {t} = {rla}({v}, {t}_l);")); + if let Some(map) = self.ps_quad(|lane| Some((lane & !7) | ((sel as u32 >> (3 * (lane & 7))) & 7))) { + let r = self.quad_read(&v, map, &t); + self.line(&format!("uint {t} = {r};")); + } else { + let rla = self.rla_half_fn(); + self.line(&format!("uint {t} = {rla}({v}, {t}_l);")); + } if !fi { self.line(&format!("{t} = select(lanebit_at({el}, {eh}, {t}_l), {t}, 0u);")); } @@ -3312,6 +3476,17 @@ impl Em { } }; let si = |i: usize, hi: bool| format!("(((int)({} << 16)) >> 16)", h(i, hi)); + // a source of the 8- and 4-bit dot products: OP_SEL / OP_SEL_HI pick its 16-bit halves + // as for the packed 16-bit ops. The console's compiler folds constants that way: FSR4's + // network passes take weights 0x00400000 as an inline 64 with its halves swapped and + // 0x000A000A as an inline 10 in both halves (`dot_op_sel_wanted`) + let dot_op_sel = vop3p && dot_op_sel_wanted(); + let pk = |i: usize| -> String { + if !dot_op_sel || (sel >> i & 1 == 0 && sel_hi >> i & 1 == 1) { + return src(i); + } + format!("({} | ({} << 16))", h(i, false), h(i, true)) + }; let dyn_rm = self.dynamic_f16_rm; let fr = |e: String| { let s = if clamp { format!("saturate({e})") } else { e }; @@ -3360,16 +3535,16 @@ impl Em { h(1, true), src(2) )), - "v_dot4_u32_u8" if clamp => Some(format!("sat_u32((uint64_t)dot4_u8({}, {}, 0u) + (uint64_t){})", src(0), src(1), src(2))), - "v_dot4_i32_i8" if clamp => Some(format!("sat_i32((int64_t)(int)dot4_i8({}, {}, 0u) + (int64_t)(int){})", src(0), src(1), src(2))), - "v_dot8_u32_u4" if clamp => Some(format!("sat_u32((uint64_t)dot8_u4({}, {}, 0u) + (uint64_t){})", src(0), src(1), src(2))), - "v_dot8_i32_i4" if clamp => Some(format!("sat_i32((int64_t)(int)dot8_i4({}, {}, 0u) + (int64_t)(int){})", src(0), src(1), src(2))), + "v_dot4_u32_u8" if clamp => Some(format!("sat_u32((uint64_t)dot4_u8({}, {}, 0u) + (uint64_t){})", pk(0), pk(1), src(2))), + "v_dot4_i32_i8" if clamp => Some(format!("sat_i32((int64_t)(int)dot4_i8({}, {}, 0u) + (int64_t)(int){})", pk(0), pk(1), src(2))), + "v_dot8_u32_u4" if clamp => Some(format!("sat_u32((uint64_t)dot8_u4({}, {}, 0u) + (uint64_t){})", pk(0), pk(1), src(2))), + "v_dot8_i32_i4" if clamp => Some(format!("sat_i32((int64_t)(int)dot8_i4({}, {}, 0u) + (int64_t)(int){})", pk(0), pk(1), src(2))), "v_dot2_i32_i16" => Some(format!("(uint)({} * {} + {} * {} + (int){})", si(0, false), si(1, false), si(0, true), si(1, true), src(2))), "v_dot2_u32_u16" => Some(format!("({} * {} + {} * {} + {})", h(0, false), h(1, false), h(0, true), h(1, true), src(2))), - "v_dot4_u32_u8" => Some(format!("dot4add_u8packed({}, {}, {})", src(0), src(1), src(2))), - "v_dot4_i32_i8" => Some(format!("(uint)dot4add_i8packed({}, {}, (int){})", src(0), src(1), src(2))), - "v_dot8_u32_u4" => Some(format!("dot8_u4({}, {}, {})", src(0), src(1), src(2))), - "v_dot8_i32_i4" => Some(format!("dot8_i4({}, {}, {})", src(0), src(1), src(2))), + "v_dot4_u32_u8" => Some(format!("dot4add_u8packed({}, {}, {})", pk(0), pk(1), src(2))), + "v_dot4_i32_i8" => Some(format!("(uint)dot4add_i8packed({}, {}, (int){})", pk(0), pk(1), src(2))), + "v_dot8_u32_u4" => Some(format!("dot8_u4({}, {}, {})", pk(0), pk(1), src(2))), + "v_dot8_i32_i4" => Some(format!("dot8_i4({}, {}, {})", pk(0), pk(1), src(2))), _ => None, }; if let Some(e) = dot { @@ -4577,12 +4752,17 @@ impl Em { Ok(()) } - /// scratch_*: per-lane private memory (`xcl_scratch`); address = SADDR or VADDR + offset. + /// scratch_*: per-lane private memory (`xcl_scratch`); address = SADDR, VADDR or 0, + offset. fn scratch(&mut self, d: &Decoded, op: &str) -> Result<(), &'static str> { let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0); self.uses_scratch = true; - let saddr = f("SADDR"); - let base = if saddr != 0x7D && saddr != 0x7F { self.sreg(saddr) } else { self.vreg(f("ADDR")) }; + // RDNA2 has no SGPR + VGPR form (no SVE bit): SADDR 0x7F (EXEC_HI) is the ST form, + // the offset alone; NULL (0x7D) is SV, VADDR + offset; an SGPR is SS, SGPR + offset + let base = match f("SADDR") { + 0x7F => "0u".to_string(), + 0x7D => self.vreg(f("ADDR")), + s => self.sreg(s), + }; let raw = f("OFFSET") as u32; let off = (((raw << 20) as i32) >> 20) as u32; let t = self.t(); @@ -4685,8 +4865,13 @@ impl Em { let (el, eh) = (self.sreg(126), self.sreg(127)); let eh = if self.opt.wave64 { eh } else { "0u".into() }; self.line(&format!("uint {t}_l = {src};")); - let rla = self.rla_half_fn(); - self.line(&format!("uint {t} = {rla}({a}, {t}_l);")); + if let Some(map) = self.ps_quad(|lane| Some((lane & 0x20) | swizzle_lane(off16, lane))) { + let r = self.quad_read(&a, map, &t); + self.line(&format!("uint {t} = {r};")); + } else { + let rla = self.rla_half_fn(); + self.line(&format!("uint {t} = {rla}({a}, {t}_l);")); + } self.line(&format!("{t} = select(lanebit_at({el}, {eh}, {t}_l), {t}, 0u);")); let dst = Dst::V(f("VDST")); self.write32(&dst, &t); @@ -5578,7 +5763,9 @@ static uint xcl_cap = 1u << 16; // the mode of the attribute this input is read through (none: never read) let attr = ps_slot_attribute(ps, k); let mut m = attr.and_then(|a| self.ps_modes.get(&(a as u32))).cloned().unwrap_or_default(); - if e.component_type != 3 { + // float16 read through a packed attribute interpolates like a float + let f16 = e.component_type == 6 && attr.is_some_and(|a| ps_attribute_f16(ps, a).is_some()); + if e.component_type != 3 && !f16 { m = "nointerpolation".into(); } let _ = writeln!(h, " {m} {}4 a{k} : {};", hlsl_type(e), e.semantic()); @@ -5614,7 +5801,13 @@ static uint xcl_cap = 1u << 16; if !self.ps_writes_mask && !ps.outputs.iter().any(|e| matches!(e.system_value, 64 | 65 | 67 | 68)) { h.push_str(" float4 xcl_unused : SV_Target7;\n"); } - h.push_str("};\nXclOut main(XclIn xi)\n{\n XclOut xo = (XclOut)0;\n"); + h.push_str("};\n"); + // the console tests depth first: without it the PC runs (and keeps the memory + // writes of) hidden pixels too + if ps.early_depth { + h.push_str("[earlydepthstencil]\n"); + } + h.push_str("XclOut main(XclIn xi)\n{\n XclOut xo = (XclOut)0;\n"); if self.ps_writes_mask { h.push_str(" xo.xcl_mask = 0xFFFFFFFFu;\n"); } @@ -6219,7 +6412,7 @@ fn method_switch(windows: u32, w: &str, ret: &str, name: &str, args: &str, def: /// out-of-UMA pointers can never wrap onto live memory windows. /// `heap`: Some(storage class) – window k is taken from the descriptor heap /// (`Options::heap_windows`) and the same rule is one comparison before the access. -fn mem_accessors(windows: u32, heap: Option<&str>) -> String { +pub(super) fn mem_accessors(windows: u32, heap: Option<&str>) -> String { let mut s = String::new(); if let Some(coherent) = heap { // Redirect ordinary out-of-window loads/stores to null raw UAVs without a divergent @@ -6594,6 +6787,14 @@ pub(crate) fn lds_order_wanted() -> bool { lds_order_for(std::env::var("XCL_X_LDS_ORDER").ok().as_deref()) } +/// Whether the VOP3P 8- and 4-bit dot products take their sources' halves as OP_SEL / +/// OP_SEL_HI pick them (`valu_pk`); `XCL_DOT_OP_SEL=0` takes the sources whole, as before (the +/// translated cache's identity tells the two apart). +pub(crate) fn dot_op_sel_wanted() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| lds_order_for(std::env::var("XCL_DOT_OP_SEL").ok().as_deref())) +} + /// `lds_order_wanted` for the value `env` of `XCL_X_LDS_ORDER`: on unless it is `0`. pub(super) fn lds_order_for(env: Option<&str>) -> bool { env.map_or(true, |v| v.trim() != "0") @@ -6970,6 +7171,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 4245f3b105..102217a1eb 100644 --- a/crates/xcl/src/gpu/recomp/heap_window_tests.rs +++ b/crates/xcl/src/gpu/recomp/heap_window_tests.rs @@ -642,8 +642,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/link_tests.rs b/crates/xcl/src/gpu/recomp/link_tests.rs index b2e99dfab9..c28b6acf4f 100644 --- a/crates/xcl/src/gpu/recomp/link_tests.rs +++ b/crates/xcl/src/gpu/recomp/link_tests.rs @@ -162,7 +162,7 @@ fn bench_memory_window_accessors() { for round in 0..3 { for windows in [1, 4] { nonce = nonce.wrapping_mul(0x9E37_79B1) | 1; - let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 24, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 24, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let t = translate(&program(n, nonce), &on_gpu(Options { mode: Mode::Compute(cs), wave64: true, mem_windows: windows, ..Default::default() })).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); let forms = if windows == 1 { @@ -212,7 +212,7 @@ fn linked_programs_keep_their_declarations() { let list = [buf("BUFFER_LOAD_DWORD", 2, coherent), buf("BUFFER_STORE_DWORD", 3, false)]; let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); let p = prog(&refs); - let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 16, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 16, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let t = translate(&p, &Options { mode: Mode::Compute(cs), wave64, mem_windows: 4, ..Default::default() }).unwrap(); let size = if wave64 { 64 } else { 32 }; assert!(t.hlsl.contains(&format!("[WaveSize({size})]")), "{}", t.hlsl); diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index ec891719a5..2a28c46122 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -3269,7 +3269,7 @@ pub(crate) mod tests { } pub(crate) fn compute_cs() -> crate::gpu::recomp::CsInterface { - crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 } + crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() } } /// A compute program run on the CPU over `groups` groups (wave32): the memory after. @@ -3341,7 +3341,7 @@ pub(crate) mod tests { } mem }; - let cs = |threads: [u32; 3], y: bool| CsInterface { threads, user_sgprs: 2, tgid: [true, y, false], tg_size: false, tid_components: if y { 2 } else { 1 } }; + let cs = |threads: [u32; 3], y: bool| CsInterface { threads, user_sgprs: 2, tgid: [true, y, false], tg_size: false, tid_components: if y { 2 } else { 1 }, ..Default::default() }; let limit = |x: u32, y: u32| vec![(IO_THREAD_LIMIT[0], x), (IO_THREAD_LIMIT[1], y)]; for wave64 in [false, true] { let lanes = if wave64 { 64 } else { 32 }; diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 0194a6a57c..955916718c 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -130,7 +130,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 { @@ -164,6 +164,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, } /// Whether a DXGI_FORMAT value has 32-bit per-channel components (`R32*`, `R32G32*`, @@ -358,6 +361,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 @@ -452,6 +457,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, } } } @@ -467,6 +473,9 @@ pub struct CsInterface { pub tg_size: bool, /// thread id VGPRs: 1 (v0), 2 (v0, v1) or 3 (v0..v2) pub tid_components: u32, + /// the group's LDS from COMPUTE_PGM_RSRC2 (LDS_SIZE, 128-dword granules), in dwords; 0 = not + /// given (`gpu::dxil::kernel::declared_lds_enabled`) + pub lds_dwords: u32, } impl CsInterface { @@ -488,6 +497,7 @@ impl CsInterface { tgid: [(r >> 7) & 1 == 1, (r >> 8) & 1 == 1, (r >> 9) & 1 == 1], tg_size: (r >> 10) & 1 == 1, tid_components: ((r >> 11) & 3) + 1, + lds_dwords: ((r >> 15) & 0x1FF) * 128, } } } @@ -589,6 +599,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 @@ -596,6 +619,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())); @@ -606,20 +634,90 @@ 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). +pub fn ps_shader_control(fssm: &[u8]) -> Option { + let o = 0x130 + fssm_shift(fssm)? + 0x114; + fssm.get(o..o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())) +} + +/// Apply the FSSM pixel-shader export patches (full 32-bit `32_ABGR` slot, index 9 of 10) to a PS +/// program's code bytes. Console pixel shaders ship with compressed FP16 export templates +/// (`v_cvt_pkrtz_f16_f32` + `exp compr`) that the console driver patches per bound RTV format at +/// pipeline creation; applying slot 9 emits the shader's raw 32-bit `SV_TargetN` values +/// unconverted, matching PC DXIL/HLSL semantics (preventing `R32_UINT` / 32-bit MRTs such as +/// packed SSS radiance from being mangled into `0x7BFF` via FP16 conversion). +pub fn patch_ps_exports(f: &super::xbox::Fssm, p: &super::xbox::Program) -> (Vec, usize) { + let mut code = f.data[p.offset..p.offset + p.len].to_vec(); + let Some(shift) = fssm_shift(&f.data) else { return (code, 0) }; + if ps_input_table(&f.data).is_none() { + return (code, 0); + } + let base = 0x130 + shift; + let rd = |o: usize| f.data.get(o..o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); + const PATCH_SLOT_DWORDS: usize = 10; + const PATCH_FULL: usize = 9; + const PATCH_BYTES: usize = 4 + 10 * PATCH_SLOT_DWORDS * 4; + let Some(size) = rd(base + 0x124).map(|n| n as usize) else { return (code, 0) }; + if size == 0 || size > PATCH_SLOT_DWORDS { + return (code, 0); + } + let Some((code_start, code_len)) = f.code else { return (code, 0) }; + let patch_bytes = size * 4; + let mut patches: Vec<(usize, usize)> = Vec::new(); + for mrt in 0..8usize { + let at = base + 0x128 + mrt * PATCH_BYTES; + let Some(off) = rd(at) else { return (code, 0) }; + if off == u32::MAX { + continue; + } + let Some(end_bytes) = (off as usize).checked_add(size).and_then(|w| w.checked_mul(4)) else { return (code, 0) }; + if end_bytes > code_len { + return (code, 0); + } + let full = at + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4; + let Some(slice) = f.data.get(full..full + patch_bytes) else { return (code, 0) }; + let mut cur = 0usize; + while cur < slice.len() { + match super::rdna2::decode(&slice[cur..], cur as u64) { + Ok(d) if cur + d.len <= slice.len() => cur += d.len, + _ => return (code, 0), + } + } + let target_abs = code_start + off as usize * 4; + if target_abs >= p.offset && target_abs + patch_bytes <= p.offset + p.len { + patches.push((target_abs - p.offset, full)); + } + } + let count = patches.len(); + for (dst, src) in patches { + code[dst..dst + patch_bytes].copy_from_slice(&f.data[src..src + patch_bytes]); + } + (code, count) +} + /// The VS output table of an FSSM: per `exp param N`, the OSG1 register it writes. 32 records /// of 6 bytes at +0x1D4 (+ the sub-version shift): kind (6 user, 0 position), register, param /// number, 0, 0, 0; the record count after them (+0xC0). Usually param N = the N-th output /// 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 { @@ -628,14 +726,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 { @@ -656,7 +818,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), } } @@ -664,7 +829,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(), } } @@ -693,7 +858,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() })), @@ -713,6 +880,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, @@ -1329,14 +1497,15 @@ pub(crate) fn graphics_reductions(insts: &[Decoded], leaders: &std::collections: && f(cross, "SRC1") == Some(128) && f(cross, "SRC2") == Some(128); let last_exact = crossed && same(last, rdna2::Variant::Plain) && lr.len() == 2 && lr.contains(&v) && lr.contains(&cw[0]); + // (BOUND_CTRL and FI of the mirror change nothing: a row mirror reads inside its row, and + // every lane is on in the section; `tests::wave32_reductions_ps`, the form of a retail + // clustered-lighting shader, sets BOUND_CTRL) if !dpp8 || !same(mirror, rdna2::Variant::Dpp16) || !reads_only_v(mirror) || ext(mirror, "DPP_CTRL") != Some(0x140) || ext(mirror, "ROW_MASK") != Some(0xf) || ext(mirror, "BANK_MASK") != Some(0xf) - || ext(mirror, "BOUND_CTRL").unwrap_or(0) != 0 - || ext(mirror, "FI").unwrap_or(0) != 0 || !crossed || !last_exact { @@ -1938,6 +2107,24 @@ pub(crate) fn needs_coherent_mem(insts: &[Decoded]) -> bool { }) } +/// Whether a memory access of the console's asks for coherent memory: an atomic, or `GLC` / +/// `DLC` / `SLC` set (`needs_coherent_mem`'s test of one instruction). +pub(crate) fn coherent_access(d: &Decoded) -> bool { + let name = d.inst.name; + name.starts_with("BUFFER_ATOMIC_") + || name.starts_with("GLOBAL_ATOMIC_") + || name.starts_with("FLAT_ATOMIC_") + || name.starts_with("S_ATOMIC_") + || matches!(d.enc.name, "ENC_SMEM" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL") + && ["GLC", "DLC", "SLC"].iter().any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(1)) +} + +/// Whether the program invalidates a cache (after which its plain loads see other groups' +/// writes, which D3D12 has no instruction for on memory that is not `globallycoherent`). +pub(crate) fn invalidates_caches(insts: &[Decoded]) -> bool { + insts.iter().any(|d| matches!(d.inst.name, "S_DCACHE_INV" | "S_GL1_INV" | "BUFFER_GL0_INV" | "BUFFER_GL1_INV")) +} + #[inline] pub fn translate(code: &[u8], opt: &Options) -> Result { let _stall = crate::stall::span(crate::stall::StallKind::ShaderTranslation); @@ -2162,8 +2349,47 @@ 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); } + + #[test] + fn patches_ps_exports_to_full_32bit_variant() { + // 4 dwords of code: s_nop; v_cvt_pkrtz_f16_f32 v4, v6, v6; exp mrt1 v4 compr done vm + let orig: [u32; 4] = [0xBF80_0000, 0x5E08_0D06, 0xF800_1C13, 0x0000_0004]; + let full: [u32; 3] = [0xBF80_0000, 0xF800_1811, 0x0000_0006]; // s_nop; exp mrt1 v6 done vm + let base = 0x138usize; // sub-version 6 + let code_start = 0xF08usize; + let mut data = vec![0u8; code_start + orig.len() * 4]; + data[0x10..0x14].copy_from_slice(&6u32.to_le_bytes()); + // valid empty PS input table + data[base + 0x100..base + 0x104].copy_from_slice(&0u32.to_le_bytes()); + data[base + 0x110..base + 0x114].copy_from_slice(&0u32.to_le_bytes()); + data[base + 0x124..base + 0x128].copy_from_slice(&3u32.to_le_bytes()); // patch size = 3 dwords + for mrt in 0..8usize { + let at = base + 0x128 + mrt * 404; + data[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + } + // MRT1 at dword offset 1 + let mrt1 = base + 0x128 + 404; + data[mrt1..mrt1 + 4].copy_from_slice(&1u32.to_le_bytes()); + let slot9 = mrt1 + 4 + 9 * 40; + for (i, w) in full.iter().enumerate() { + data[slot9 + i * 4..slot9 + i * 4 + 4].copy_from_slice(&w.to_le_bytes()); + } + for (i, w) in orig.iter().enumerate() { + data[code_start + i * 4..code_start + i * 4 + 4].copy_from_slice(&w.to_le_bytes()); + } + let f = super::super::xbox::Fssm { + data, + code: Some((code_start, orig.len() * 4)), + ..Default::default() + }; + let p = super::super::xbox::Program { offset: code_start, len: orig.len() * 4 }; + let (patched, n) = patch_ps_exports(&f, &p); + assert_eq!(n, 1); + let words: Vec = patched.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect(); + assert_eq!(words, vec![orig[0], full[0], full[1], full[2]]); + } } diff --git a/crates/xcl/src/gpu/recomp/ps_masks.rs b/crates/xcl/src/gpu/recomp/ps_masks.rs index 4224cc5aff..c65360cc12 100644 --- a/crates/xcl/src/gpu/recomp/ps_masks.rs +++ b/crates/xcl/src/gpu/recomp/ps_masks.rs @@ -84,7 +84,7 @@ fn per_lane(d: &Decoded, wave64: bool) -> u128 { return 0; } match fv(d, "SRC2") { - Some(v) if d.enc.name.starts_with("ENC_VOP3") => regs(v, if wave64 { 2 } else { 1 }), + Some(v) if d.enc.name.contains("VOP3") => regs(v, if wave64 { 2 } else { 1 }), _ => vcc_mask(wave64), } } @@ -303,7 +303,7 @@ pub fn forms(insts: &[Decoded], wave64: bool) -> BTreeMap { continue; } // both operands scalar / constant: the mask is `cond ? EXEC : 0`, no ballot needed - let uniform = d.enc.name.starts_with("ENC_VOP3") && fv(d, "SRC0").is_some_and(|v| v < 256) && fv(d, "SRC1").is_some_and(|v| v < 256); + 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, wave64).is_ok() { @@ -549,6 +549,48 @@ mod tests { 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, true), 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, true).get(&cmp_pc), Some(&Form::Uniform)); + } + #[test] fn wave32_compare_does_not_kill_neighbor_sgpr_in_liveness_or_taint() { // Wave32 PS: `v_cmp -> s21`, then `v_cmp -> s20`, then `s_bcnt1 s21` (CharlyRien's repro). diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 0abc5314e4..e429c5e4b9 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -160,9 +160,11 @@ fn windows_for_mode(n: u32, heap: bool) -> u32 { } } -/// `HEAP_FLAT` changes only compute translation; other stages keep their existing cache identity. -fn windows_for_stage(windows: u32, stage: Stage) -> u32 { - if stage == Stage::Compute { windows } else { windows & !super::HEAP_FLAT } +/// The windows `stage` translates with: `HEAP_FLAT` reaches every stage (the direct DXIL +/// translator reads the heap windows of all of them without a branch: `reads_heap_flat`), so +/// it stays in every stage's cache keys. +fn windows_for_stage(windows: u32, _stage: Stage) -> u32 { + windows } thread_local! { @@ -195,11 +197,13 @@ pub fn heap_windows() -> bool { *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").is_ok_and(|v| v.trim() == "1")) && !crate::hle::d3d12x::console_heap::window_views_failed() } -/// `XCL_HEAP_FLAT=1` (with heap windows): the direct DXIL translator reads a compute stage's heap -/// windows without a branch per access (`HEAP_FLAT`). Opt-in while it is measured. +/// `XCL_HEAP_FLAT` (default on with heap windows; `=0` to disable): the direct DXIL translator +/// reads every stage's heap windows without a branch per access (`HEAP_FLAT`). With the branch, +/// AMD's compiler took a pixel shader's quad helper lanes into the sampler waterfall with a stale +/// index: a page fault at world entry (RX 9070 XT). pub fn heap_flat() -> bool { static ENV: OnceLock = OnceLock::new(); - *ENV.get_or_init(|| std::env::var("XCL_HEAP_FLAT").is_ok_and(|v| v.trim() == "1")) + *ENV.get_or_init(|| std::env::var("XCL_HEAP_FLAT").map_or(true, |v| v.trim() != "0")) } /// A static sampler of a translated program: (S#, comparison) – see `Translation`. @@ -363,7 +367,9 @@ mod translated { } pub(super) fn identity_from_source(source: &str) -> u64 { - if std::env::var("XCL_TRANSLATED_CACHE").is_ok_and(|v| v == "0") { return 0; } + if std::env::var("XCL_TRANSLATED_CACHE").is_ok_and(|v| v == "0") { + return 0; + } let id = identity_with( source, super::dxc::toolchain_identity(), @@ -375,6 +381,11 @@ mod translated { Some(on) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), if on { "xcl-direct-compact-1" } else { "xcl-direct-compact-0" }), _ => id, }; + // `XCL_DIRECT_COMPACT_MIN`: compute programs from that size take the compact form + let id = match crate::gpu::dxil::kernel::compact_min() { + Some(n) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), &format!("xcl-direct-compact-min-{n}")), + _ => id, + }; // `XCL_DIRECT_COMPACT_NEST`: a non-default nesting policy changes the compact IR let id = match crate::gpu::dxil::kernel::compact_nest_tag() { Some(tag) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), &tag), @@ -383,8 +394,38 @@ 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_DECLARED_LDS` (on): compute programs' groupshared blocks are another output + let id = if Backend::current() != Backend::Hlsl && crate::gpu::dxil::kernel::declared_lds_enabled() { + identity_for(&id.to_string(), "xcl-declared-lds") + } else { id }; + // `XCL_COHERENT_PER_ACCESS=1`: coherent heap windows per access are another output + let id = if Backend::current() != Backend::Hlsl && crate::gpu::dxil::kernel::coherent_per_access() { + identity_for(&id.to_string(), "xcl-coherent-per-access") + } else { id }; + // `XCL_ONE_WAVE_GROUP_IDS` (on): one-wave 2-D / 3-D groups' entries are another output + let id = if Backend::current() != Backend::Hlsl && crate::gpu::dxil::kernel::one_wave_group_ids() { + identity_for(&id.to_string(), "xcl-one-wave-group-ids") + } else { id }; + // `XCL_DIRECT_FORMS_ONLY`: the newer forms for these programs only; `XCL_DXIL_NO_OPT`: + // the passes left out + let id = match super::forms_only_tag().into_iter().chain(super::no_opt_tag()).collect::>() { + tags if Backend::current() != Backend::Hlsl && !tags.is_empty() => identity_for(&id.to_string(), &tags.join(";")), + _ => id, + }; + // `XCL_NAN_GUARD=0`: disabling PS float NaN/Inf sanitization changes pixel DXIL + let id = if Backend::current() != Backend::Hlsl && !crate::gpu::dxil::kernel::nan_guard_enabled() { + identity_for(&id.to_string(), "xcl-nan-guard-0") + } else { id }; // `XCL_X_LDS_ORDER=0`: the split wave64 form without its LDS order, in both translators let id = if crate::gpu::recomp::emit::lds_order_wanted() { id } else { identity_for(&id.to_string(), "xcl-x-lds-order-0") }; + // `XCL_DOT_OP_SEL=0`: the 8- and 4-bit dot products without OP_SEL on their sources + let id = if crate::gpu::recomp::emit::dot_op_sel_wanted() { id } else { identity_for(&id.to_string(), "xcl-dot-op-sel-0") }; + // `XCL_PS_QUAD_READS=0`: pixel shaders' quad-local lane reads through `rla`, in both translators + let id = if crate::gpu::recomp::emit::ps_quad_reads_wanted() { id } else { identity_for(&id.to_string(), "xcl-ps-quad-reads-0") }; // `XCL_PER_LANE=1` (direct compute only): its entries under their own identity 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"))) @@ -690,7 +731,20 @@ mod translated { Some(tag) => identity_for(&id.to_string(), tag), None => id, }; + let id = match crate::gpu::dxil::kernel::compact_min() { + Some(n) => identity_for(&id.to_string(), &format!("xcl-direct-compact-min-{n}")), + None => id, + }; + let id = if crate::gpu::dxil::kernel::declared_lds_enabled() { identity_for(&id.to_string(), "xcl-declared-lds") } else { id }; + let id = if crate::gpu::dxil::kernel::coherent_per_access() { identity_for(&id.to_string(), "xcl-coherent-per-access") } else { id }; + let id = if crate::gpu::dxil::kernel::one_wave_group_ids() { identity_for(&id.to_string(), "xcl-one-wave-group-ids") } else { id }; + let id = match super::forms_only_tag().into_iter().chain(super::no_opt_tag()).collect::>() { + tags if !tags.is_empty() => identity_for(&id.to_string(), &tags.join(";")), + _ => id, + }; let id = identity_for(&id.to_string(), &format!("dispatch-split-{split_limit}")); + // `XCL_DOT_OP_SEL=0` (as in `identity`) + let id = if crate::gpu::recomp::emit::dot_op_sel_wanted() { id } else { identity_for(&id.to_string(), "xcl-dot-op-sel-0") }; if crate::gpu::recomp::lower_dxil::enabled() { identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID"))) } else { @@ -784,11 +838,75 @@ fn enormous(stage: Stage, hlsl_len: usize) -> bool { stage == Stage::Compute && hlsl_len > dxc::UNOPTIMISED_ABOVE } +/// The DXIL a run would make of a console program now, without the in-memory or disk caches +/// (`xcl shaders --measure-pso --direct`): the routing and switches of the environment. +pub(crate) fn console_dxil_uncached(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result { + compile_console_shader(blob, stage, sampler_base, windows, split_wave64, 0).map(|(c, _)| c) +} + // Changes here, in `fspx`, or in `console_translation` that alter the cached result must bump // `TRANSLATION_GLUE_REVISION` in build.rs; cache serialization changes need not bump it. /// The program's DXIL, and whether it is an `enormous` one the direct translator made (its /// disk cache entry then follows that translator's version: `translated::cached`). fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool, rt32_mask: u8) -> Result<(Compiled, bool), String> { + crate::gpu::dxil::kernel::with_newer_forms(newer_forms_for(blob), || compile_console_shader_formed(blob, stage, sampler_base, windows, split_wave64, rt32_mask)) +} + +/// `XCL_DIRECT_FORMS_ONLY=[,…]` (hex `[SHADER]` hashes of console containers, +/// `none`, or `all` for every program; unset: `DEFAULT_FORMS_ONLY`, the run measured with it): +/// only these programs take the direct translator's newer forms +/// (`kernel::with_newer_forms`: declared LDS, one-wave group ids, per-access coherence, the +/// EXEC-select fold, `XCL_DIRECT_COMPACT_MIN`'s compact form, each as its own switch says); every +/// other compute, vertex, pixel, mesh and geometry program is translated as before they existed. +/// Those forms changed the DXIL of every program, so the driver's shader cache of the earlier +/// runs missed for all of them: at a retail title's world start ~65 compute programs of 140 - 260 +/// KB of DXIL were compiled cold, 28 - 54 s and 2.9 - 6.4 GB each in the compact form (11 - 18 s +/// and 0.6 - 0.9 GB in the plain one; RX 9070 XT), thousands of graphics pipelines besides, and +/// its loading stood still. With the list, the program the forms were made for keeps them and +/// the others hit that cache. The caches key the list. +pub(crate) fn newer_forms_for(blob: &[u8]) -> bool { + forms_only().is_none_or(|set| set.contains(&crate::gpu::shader::fnv64(blob))) +} + +fn forms_only() -> Option<&'static std::collections::BTreeSet> { + static V: OnceLock>> = OnceLock::new(); + V.get_or_init(|| forms_only_of(std::env::var("XCL_DIRECT_FORMS_ONLY").ok().as_deref())).as_ref() +} + +/// `XCL_DIRECT_FORMS_ONLY` unset: the retail title's shadow-mask program +/// (CS_GenerateShadowMasks_Checkerboard_NoHair), the one the forms were made for. A retail run +/// with this list (RX 9070 XT, 300 s, no device removal) took it from 98.6 to 18.6 ms a frame +/// and the open world from 3.0 to 4.0 fps; with the forms on every program (`all`) the cold +/// driver compiles stalled the loading and one run lost the device. +const DEFAULT_FORMS_ONLY: u64 = 0xa3c0b8a98beee431; + +/// The records of an `XCL_DIRECT_FORMS_ONLY` value: unset, `DEFAULT_FORMS_ONLY`; `all`, every +/// program (None); `none` or nothing valid, none of them. +fn forms_only_of(v: Option<&str>) -> Option> { + let Some(v) = v else { return Some([DEFAULT_FORMS_ONLY].into()) }; + if v.trim().eq_ignore_ascii_case("all") { + return None; + } + Some(v.split(',').filter_map(|h| u64::from_str_radix(h.trim().trim_start_matches("0x"), 16).ok()).collect()) +} + +/// The translated caches' tag of `XCL_DIRECT_FORMS_ONLY` (None: `all`). +fn forms_only_tag() -> Option { + forms_only().map(|set| format!("xcl-direct-forms-only-{}", set.iter().map(|h| format!("{h:016x}")).collect::>().join(","))) +} + +/// The translated caches' tag of `XCL_DXIL_NO_OPT` (the direct translator's passes left out; +/// None: unset or empty): the DXIL is another one without them. +fn no_opt_tag() -> Option { + no_opt_tag_of(std::env::var("XCL_DXIL_NO_OPT").ok().as_deref()) +} + +fn no_opt_tag_of(v: Option<&str>) -> Option { + let passes: std::collections::BTreeSet<&str> = v?.split(',').map(str::trim).filter(|p| !p.is_empty()).collect(); + (!passes.is_empty()).then(|| format!("xcl-dxil-no-opt-{}", passes.into_iter().collect::>().join(","))) +} + +fn compile_console_shader_formed(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool, rt32_mask: u8) -> Result<(Compiled, bool), String> { // `XCL_DEBUG_CS_SUB` names this compute shader: the HLSL path, whatever its size let cs_subs = cs_subs(blob, stage); // `XCL_DIRECT_DXIL=1`: compute shaders through the direct DXIL translator, the HLSL path @@ -1543,7 +1661,7 @@ pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Resul let windows = windows_for_stage(mem_windows(), Stage::Mesh); let dir = dxc::cache_dir(); console_mesh_with(blob, ps, split_wave64, windows, &dir, shader_cache(), |code, rodata, ms, wave64| { - compile_console_mesh(blob, code, rodata, ms, wave64, windows, split_wave64) + crate::gpu::dxil::kernel::with_newer_forms(newer_forms_for(blob), || compile_console_mesh(blob, code, rodata, ms, wave64, windows, split_wave64)) }) } @@ -1591,12 +1709,13 @@ pub fn graphics_wave32_for_device(device: &ID3D12Device) -> bool { split_wave64_forced() || wave_range(device).is_none_or(|(min, max)| graphics_wave32(min, max)) } -/// The compute pass of a legacy GS pipeline from its program (`geometry_program`). -fn compile_console_geometry(code: &[u8], g: super::GsInterface, split_wave64: bool, windows: u32) -> Result { +/// The compute pass of a legacy GS pipeline from its program (`geometry_program`); `newer`: +/// `newer_forms_for` its VS or GS. +fn compile_console_geometry(code: &[u8], g: super::GsInterface, split_wave64: bool, windows: u32, newer: bool) -> Result { // `XCL_DIRECT_DXIL=1`: the compute pass through the direct DXIL translator (HLSL fallback) if crate::gpu::dxil::kernel::enabled() { let o = crate::gpu::dxil::kernel::KernelOptions { wave64: true, split: split_wave64, mem_windows: windows, sampler_base: 0 }; - match crate::gpu::dxil::kernel::translate_geometry(code, o, &g) { + match crate::gpu::dxil::kernel::with_newer_forms(newer, || crate::gpu::dxil::kernel::translate_geometry(code, o, &g)) { Ok(k) => { crate::gpu::dxil::coverage::record_translated("GS"); return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }); @@ -1661,7 +1780,7 @@ fn console_geometry_cs_with( pub fn console_geometry_cs_in(vs: &[u8], gs: &[u8], split_wave64: bool, windows: u32) -> Result { let windows = windows_for_stage(windows, Stage::Geometry); console_geometry_cs_with(vs, gs, split_wave64, windows, &dxc::cache_dir(), shader_cache(), |code, g| { - compile_console_geometry(code, g, split_wave64, windows) + compile_console_geometry(code, g, split_wave64, windows, newer_forms_for(vs) || newer_forms_for(gs)) }) .map(|(cs, _)| cs) } @@ -1670,7 +1789,7 @@ pub fn console_geometry_cs_in(vs: &[u8], gs: &[u8], split_wave64: bool, windows: pub fn console_geometry(vs: &[u8], gs: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Result { let windows = windows_for_stage(mem_windows(), Stage::Geometry); let (cs, record) = console_geometry_cs_with(vs, gs, split_wave64, windows, &dxc::cache_dir(), shader_cache(), |code, g| { - compile_console_geometry(code, g, split_wave64, windows) + compile_console_geometry(code, g, split_wave64, windows, newer_forms_for(vs) || newer_forms_for(gs)) })?; finish_two_pass_compiled(cs, record, ps) } @@ -2128,10 +2247,74 @@ mod slab_tests { } } +#[cfg(test)] +mod forms_only_tests { + use super::{forms_only_of, no_opt_tag_of}; + + /// `XCL_DIRECT_FORMS_ONLY`: hex records with or without `0x`, spaces allowed; `none` (or no + /// valid record) names none of them; `all` leaves every program its forms; unset names the + /// shadow-mask program only. + #[test] + fn the_forms_only_list_names_records() { + assert_eq!(forms_only_of(None).unwrap().into_iter().collect::>(), vec![super::DEFAULT_FORMS_ONLY]); + assert_eq!(forms_only_of(Some(" ALL ")), None); + let set = forms_only_of(Some(" a3c0b8a98beee431, 0x3cd8c0e62e7072c8,zz")).unwrap(); + assert_eq!(set.into_iter().collect::>(), vec![0x3cd8c0e62e7072c8, 0xa3c0b8a98beee431]); + assert!(forms_only_of(Some("none")).unwrap().is_empty()); + } + + /// `XCL_DXIL_NO_OPT` keys the translated caches by the passes it names, in any order. + #[test] + fn the_passes_left_out_are_a_cache_tag() { + assert_eq!(no_opt_tag_of(None), None); + assert_eq!(no_opt_tag_of(Some(" , ")), None); + assert_eq!(no_opt_tag_of(Some("select")).as_deref(), Some("xcl-dxil-no-opt-select")); + assert_eq!(no_opt_tag_of(Some("select, dce")), no_opt_tag_of(Some("dce,select"))); + } +} + #[cfg(test)] mod shader_cache_tests { use super::*; + /// `XCL_DECLARED_LDS=1` translations are other entries of the direct translator's caches. + #[test] + fn declared_lds_is_another_direct_output() { + let with = |on| { + let before = crate::gpu::dxil::kernel::DECLARED_LDS_FOR_TEST.with(|c| c.replace(Some(on))); + let id = translated::direct_output_identity(None, 1); + crate::gpu::dxil::kernel::DECLARED_LDS_FOR_TEST.with(|c| c.set(before)); + id + }; + assert_ne!(with(false), with(true)); + assert_eq!(with(true), with(true)); + } + + /// `XCL_DIRECT_COMPACT_MIN` translations are other entries of the direct translator's caches. + #[test] + fn a_compact_size_is_another_direct_output() { + let with = |n| { + let before = crate::gpu::dxil::kernel::COMPACT_MIN_FOR_TEST.with(|c| c.replace(Some(n))); + let id = translated::direct_output_identity(None, 1); + crate::gpu::dxil::kernel::COMPACT_MIN_FOR_TEST.with(|c| c.set(before)); + id + }; + assert_ne!(with(None), with(Some(4096))); + assert_ne!(with(Some(4096)), with(Some(8192))); + } + + /// `XCL_ONE_WAVE_GROUP_IDS` translations are other entries of the direct translator's caches. + #[test] + fn one_wave_group_ids_are_another_direct_output() { + let with = |on| { + let before = crate::gpu::dxil::kernel::ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.replace(Some(on))); + let id = translated::direct_output_identity(None, 1); + crate::gpu::dxil::kernel::ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.set(before)); + id + }; + assert_ne!(with(false), with(true)); + } + /// The switch form (no heap windows, or a pipeline retried in it) has 4 root UAVs: a wider /// count there is 4, which every translator takes; the heap form keeps all of them. #[test] @@ -2153,11 +2336,10 @@ mod shader_cache_tests { } #[test] - fn heap_flat_partitions_only_compute_cache_keys() { + fn heap_flat_stays_in_every_stage_cache_key() { let windows = 4 | super::super::HEAP_WINDOWS | super::super::HEAP_FLAT; - assert_eq!(windows_for_stage(windows, Stage::Compute), windows); - for stage in [Stage::Vertex, Stage::Pixel, Stage::Mesh] { - assert_eq!(windows_for_stage(windows, stage), windows & !super::super::HEAP_FLAT); + for stage in [Stage::Compute, Stage::Vertex, Stage::Pixel, Stage::Mesh] { + assert_eq!(windows_for_stage(windows, stage), windows); } } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 753d9590b4..f2409fa910 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -2151,7 +2151,7 @@ fn gpu_wave32_pixel_carry_preserves_adjacent_mask_at_triangle_edges() { ]; let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let ps = super::PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 15)], - outputs: vec![el("SV_Target", 0, 64, 3, 0, 15)], input_ena: 0x300, attrs: None }; + outputs: vec![el("SV_Target", 0, 64, 3, 0, 15)], input_ena: 0x300, attrs: None, early_depth: false }; let t = translate(&code, &Options { wave64: false, mode: Mode::Pixel(ps), ..Default::default() }).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); let ps = super::dxc::compile(&t.hlsl, "main", "ps_6_6", &[]).unwrap(); @@ -2206,6 +2206,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(); @@ -2290,6 +2291,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() { @@ -2339,6 +2341,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() }; @@ -2524,6 +2527,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(); @@ -2594,6 +2598,7 @@ fn draw_psi() -> super::PsInterface { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, } } @@ -3423,7 +3428,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() } } @@ -3464,6 +3469,248 @@ fn gpu_ps_helper_lanes_see_ballots_and_quads_are_lanes_4k() { assert_eq!(quads, px.len(), "quads not at hardware lanes 4k..4k+3"); } +/// A pixel shader that reads its quad's neighbours inside a loop that also has a wave read, as +/// a retail tiled-lighting shader does (quad sums by `v_mov_b32_dpp quad_perm` in its light +/// loop, `v_readfirstlane` of uniform values beside them). Per pixel, of f = pos.x + 64 · pos.y, +/// three passes: the quad's sum by two quad_perm DPPs, the diagonal neighbour by `ds_swizzle` +/// (quad mode), the other row's by DPP8 plus the other column's by DPP16 row_xmask:1, and the +/// count of a `v_readfirstlane` of 1.0. The quads on the two triangles' shared diagonal hold +/// helper lanes, whose f the console's reads see. +fn quad_reads_in_a_loop_ps(wave64: bool) -> Vec { + let (mov, wqm) = if wave64 { ("S_MOV_B64", "S_WQM_B64") } else { ("S_MOV_B32", "S_WQM_B32") }; + type I = (&'static str, &'static str, Vec<(&'static str, u64)>, Option); + let dpp16 = |d: u64, s: u64, ctrl: u64| -> I { ("V_MOV_B32", "VOP1_VOP_DPP16", vec![("VDST", d), ("SRC0", 0xFA), ("VSRC0", s), ("DPP_CTRL", ctrl), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None) }; + let add = |d: u64, a: u64, b: u64| -> I { ("V_ADD_F32", "ENC_VOP2", vec![("VDST", d), ("SRC0", a), ("VSRC1", b)], None) }; + let head: Vec = vec![ + (mov, "ENC_SOP1", vec![("SDST", 20), ("SSRC0", 126)], None), // the live lanes + (wqm, "ENC_SOP1", vec![("SDST", 126), ("SSRC0", 126)], None), + ("V_MUL_F32", "ENC_VOP2", vec![("VDST", 6), ("SRC0", 255), ("VSRC1", 3)], Some(64f32.to_bits())), + add(6, V + 6, 2), // v6 = f + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 11), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 12), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 13), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 14), ("SRC0", 128)], None), + ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 11), ("SSRC0", 242)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 15), ("SRC0", 11)], None), // 1.0 in every lane + ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 8), ("SSRC0", 128)], None), + ]; + let body: Vec = vec![ + ("V_READFIRSTLANE_B32", "ENC_VOP1", vec![("VDST", 9), ("SRC0", V + 15)], None), + add(14, 9, 14), + dpp16(7, 6, 0xB1), // quad_perm [1,0,3,2] + add(7, V + 7, 6), + dpp16(8, 7, 0x4E), // quad_perm [2,3,0,1] + add(8, V + 8, 7), + add(13, V + 13, 8), + // quad_perm [3,2,1,0]: the diagonal + ("DS_SWIZZLE_B32", "ENC_DS", vec![("VDST", 9), ("ADDR", 6), ("OFFSET0", 0x1B), ("OFFSET1", 0x80)], None), + add(12, V + 12, 9), + ("V_MOV_B32", "VOP1_VOP_DPP8", vec![("VDST", 10), ("SRC0", 0xE9), ("VSRC0", 6), ("LANE_SEL_0", 2), ("LANE_SEL_1", 3), ("LANE_SEL_2", 0), ("LANE_SEL_3", 1), ("LANE_SEL_4", 6), ("LANE_SEL_5", 7), ("LANE_SEL_6", 4), ("LANE_SEL_7", 5)], None), + add(11, V + 11, 10), + dpp16(10, 6, 0x161), // row_xmask:1 + add(11, V + 11, 10), + ("S_ADD_U32", "ENC_SOP2", vec![("SDST", 8), ("SSRC0", 8), ("SSRC1", 129)], None), + ("S_CMP_LT_U32", "ENC_SOPC", vec![("SSRC0", 8), ("SSRC1", 131)], None), + ]; + let tail: Vec = vec![ + (mov, "ENC_SOP1", vec![("SDST", 126), ("SSRC0", 20)], None), + ("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 13), ("VSRC1", 12), ("VSRC2", 14), ("VSRC3", 11), ("DONE", 1), ("VM", 1)], None), + ]; + let enc = |l: &[I]| -> Vec { l.iter().flat_map(|(n, e, f, x)| encode(n, e, f, *x).unwrap_or_else(|err| panic!("{n}: {err}"))).collect() }; + let body_code = enc(&body); + let back = (-((body_code.len() as i64 + 4) / 4)) as u16 as u64; + let mut code = enc(&head); + code.extend(&body_code); + code.extend(encode("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", back)], None).unwrap()); + code.extend(enc(&tail)); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + code +} + +/// The whole-wave reductions a wave32 pixel shader of the console makes (a retail clustered- +/// lighting shader takes the range and the bit-or of its pixels' light lists this way): +/// `s_or_saveexec_b32 s, -1`, `v_cndmask` of the value in the live lanes (the entry EXEC, saved +/// before `s_wqm`) and the identity elsewhere, three DPP8 steps, a row mirror, `v_permlanex16`, +/// one more step and `v_readlane s, v, 0`. Every live lane holds 7 for the min, 5 for the max +/// and 0x10 for the bit-or; the export is the three results and 1.0. +fn wave32_reductions_ps() -> Vec { + type I = (&'static str, &'static str, Vec<(&'static str, u64)>, Option); + let sop1 = |n: &'static str, d: u64, s: u64| -> I { (n, "ENC_SOP1", vec![("SDST", d), ("SSRC0", s)], None) }; + let dpp8 = |op: &'static str, sel: [u64; 8]| -> I { + let mut f = vec![("VDST", 0), ("SRC0", 0xE9), ("VSRC0", 0), ("VSRC1", 0)]; + f.extend(["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"].into_iter().zip(sel)); + (op, "VOP2_VOP_DPP8", f, None) + }; + let mut l: Vec = vec![sop1("S_MOV_B32", 88, 126), sop1("S_WQM_B32", 126, 126)]; + for (k, (op, identity, value)) in [("V_MIN_U32", 193, 7), ("V_MAX_U32", 128, 5), ("V_OR_B32", 128, 0x10)].into_iter().enumerate() { + l.extend([ + sop1("S_OR_SAVEEXEC_B32", 3, 193), + ("S_AND_B32", "ENC_SOP2", vec![("SDST", 2), ("SSRC0", 88), ("SSRC1", 3)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 4), ("SRC0", 128 + value)], None), + ("V_CNDMASK_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", identity), ("SRC1", V + 4), ("SRC2", 2)], None), + dpp8(op, [1, 0, 3, 2, 5, 4, 7, 6]), + dpp8(op, [2, 2, 0, 0, 6, 6, 4, 4]), + dpp8(op, [4, 4, 4, 4, 0, 0, 0, 0]), + (op, "VOP2_VOP_DPP16", vec![("VDST", 0), ("SRC0", 0xFA), ("VSRC0", 0), ("VSRC1", 0), ("DPP_CTRL", 0x140), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF), ("BOUND_CTRL", 1)], None), + ("V_PERMLANEX16_B32", "ENC_VOP3", vec![("VDST", 1), ("SRC0", V), ("SRC1", 128), ("SRC2", 128)], None), + (op, "ENC_VOP2", vec![("VDST", 0), ("SRC0", V + 1), ("VSRC1", 0)], None), + ("V_READLANE_B32", "ENC_VOP3", vec![("VDST", 10 + k as u64), ("SRC0", V), ("SRC1", 128)], None), + sop1("S_MOV_B32", 126, 3), + ]); + } + l.extend([ + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 5), ("SRC0", 10)], None), + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 6), ("SRC0", 11)], None), + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 7), ("SRC0", 12)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 8), ("SRC0", 242)], None), + sop1("S_MOV_B32", 126, 88), + ("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 5), ("VSRC1", 6), ("VSRC2", 7), ("VSRC3", 8), ("DONE", 1), ("VM", 1)], None), + ("S_ENDPGM", "ENC_SOPP", vec![], None), + ]); + l.iter().flat_map(|(n, e, f, x)| encode(n, e, f, *x).unwrap_or_else(|err| panic!("{n}: {err}"))).collect() +} + +/// `wave32_reductions_ps` on the GPU, through both translators, on two triangles that share the +/// diagonal (waves there are partly filled and hold helper lanes): every pixel gets the +/// reductions of its wave's live lanes. +#[test] +fn gpu_ps_wave32_reductions_count_live_lanes_only() { + if !gpu_ready() { + return; + } + use crate::gpu::dxil::kernel::{self, KernelOptions}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT; + let vs = super::dxc::compile("float4 main(float2 p : POSITION) : SV_Position { return float4(p, 0.5, 1.0); }\n", "main", "vs_6_6", &[]).unwrap(); + let psi = super::PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false }; + let quad = [-1.0f32, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0]; + let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }]; + let size = 32usize; + let code = wave32_reductions_ps(); + let t = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}\n{}", t.unsupported_why, t.hlsl); + let hlsl = super::dxc::compile(&t.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + let direct = kernel::translate_pixel(&code, KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, &psi).expect("translate PS").dxil; + for (form, ps) in [("HLSL", &hlsl), ("direct DXIL", &direct)] { + let px = runner::draw(&vs, ps, &layout, &quad, 8, &[], &[], size as u32, [9.0; 4]).unwrap(); + let bad: Vec<(usize, usize, [f32; 4])> = (0..size * size).filter(|&i| px[i] != [7.0, 5.0, 16.0, 1.0]).map(|i| (i % size, i / size, px[i])).collect(); + println!("{form}: {} of {} pixels wrong, first {:?}", bad.len(), size * size, &bad[..bad.len().min(4)]); + assert!(bad.is_empty(), "{form}: {} pixels wrong (min 7, max 5, or 16, 1), first (x, y, got) {:?}", bad.len(), &bad[..bad.len().min(6)]); + } +} + +/// Which lane reads stay in the reader's quad (`emit::quad_map`), and `XCL_PS_QUAD_READS`. +#[test] +fn quad_local_lane_reads() { + use super::emit::{dpp16_lane, ps_quad_reads_for, quad_map, swizzle_lane}; + let dpp16 = |ctrl: u64| quad_map(64, |l| dpp16_lane(ctrl, l)); + assert_eq!(dpp16(0xB1), Some([1, 0, 3, 2]), "quad_perm [1,0,3,2]"); + assert_eq!(dpp16(0x1B), Some([3, 2, 1, 0]), "quad_perm [3,2,1,0]"); + assert_eq!(dpp16(0x00), Some([0, 0, 0, 0]), "quad_perm broadcast"); + assert_eq!(dpp16(0xE4), Some([0, 1, 2, 3]), "quad_perm identity"); + assert_eq!(dpp16(0x163), Some([3, 2, 1, 0]), "row_xmask:3"); + for ctrl in [0x101, 0x111, 0x121, 0x140, 0x141, 0x150, 0x164] { + assert_eq!(dpp16(ctrl), None, "DPP_CTRL {ctrl:#x} leaves the quad"); + } + let dpp8 = |sel: [u32; 8]| quad_map(32, |l| Some((l & !7) | sel[(l & 7) as usize])); + assert_eq!(dpp8([2, 3, 0, 1, 6, 7, 4, 5]), Some([2, 3, 0, 1])); + assert_eq!(dpp8([1, 0, 3, 2, 5, 4, 7, 6]), Some([1, 0, 3, 2])); + assert_eq!(dpp8([2, 2, 0, 0, 6, 6, 4, 4]), Some([2, 2, 0, 0])); + assert_eq!(dpp8([4, 4, 4, 4, 0, 0, 0, 0]), None); + assert_eq!(dpp8([1, 0, 3, 2, 4, 5, 6, 7]), None, "a different pattern in the second quad"); + let swizzle = |offset: u64| quad_map(64, |l| Some((l & 0x20) | swizzle_lane(offset, l))); + assert_eq!(swizzle(0x801B), Some([3, 2, 1, 0]), "quad mode"); + assert_eq!(swizzle(0x041F), Some([1, 0, 3, 2]), "bit mode, xor 1"); + assert_eq!(swizzle(0x001C), Some([0, 0, 0, 0]), "bit mode, and 0x1C"); + assert_eq!(swizzle(0x101F), None, "bit mode, xor 4"); + assert_eq!(swizzle(0x0010), None, "bit mode, and 0x10"); + assert!(ps_quad_reads_for(None) && ps_quad_reads_for(Some("1")) && ps_quad_reads_for(Some(""))); + assert!(!ps_quad_reads_for(Some("0")) && !ps_quad_reads_for(Some(" 0 "))); +} + +/// A pixel shader whose lane reads all stay in the quad (DPP16 quad_perm and row_xmask, DPP8, +/// `ds_swizzle` quad mode) reads only through `QuadReadLaneAt`, in both translators: no wave read, +/// no ballot, no `quadOp` (#134). A compute program's keep their wave reads. +#[test] +fn ps_quad_local_lane_reads_take_quad_reads_only() { + use crate::gpu::dxil::{kernel, validate}; + if !super::emit::ps_quad_reads_wanted() { + println!("XCL_PS_QUAD_READS=0: nothing to check"); + return; + } + let dpp16 = |d: u64, ctrl: u64| encode("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", d), ("SRC0", 0xFA), ("VSRC0", 2), ("DPP_CTRL", ctrl), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None).unwrap(); + let reads = |wqm: &str| -> Vec { + let mut c = Vec::new(); + c.extend(encode(wqm, "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None).unwrap()); + c.extend(dpp16(7, 0xB1)); + c.extend(encode("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 8), ("ADDR", 2), ("OFFSET0", 0x1B), ("OFFSET1", 0x80)], None).unwrap()); + c.extend(encode("V_MOV_B32", "VOP1_VOP_DPP8", &[("VDST", 9), ("SRC0", 0xE9), ("VSRC0", 2), ("LANE_SEL_0", 2), ("LANE_SEL_1", 3), ("LANE_SEL_2", 0), ("LANE_SEL_3", 1), ("LANE_SEL_4", 6), ("LANE_SEL_5", 7), ("LANE_SEL_6", 4), ("LANE_SEL_7", 5)], None).unwrap()); + c.extend(dpp16(10, 0x161)); + c + }; + let psi = super::PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false }; + for wave64 in [false, true] { + let mut code = reads(if wave64 { "S_WQM_B64" } else { "S_WQM_B32" }); + code.extend(encode("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 7), ("VSRC1", 8), ("VSRC2", 9), ("VSRC3", 10), ("DONE", 1), ("VM", 1)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let t = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}\n{}", t.unsupported_why, t.hlsl); + let main = &t.hlsl[t.hlsl.rfind(" main(").expect("main")..]; + assert!(!main.contains("rla("), "wave64 {wave64}: a quad-local read through rla\n{main}"); + // four reads, each position of the quad from another one + assert_eq!(main.matches("QuadReadLaneAt(").count(), 16, "wave64 {wave64}\n{main}"); + let k = kernel::translate_pixel(&code, kernel::KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, &psi).expect("translate PS"); + validate::validate(&k.dxil).expect("validate PS"); + let dis = validate::disassemble(&k.dxil).expect("disassemble PS"); + assert!(!dis.contains("dx.op.waveReadLaneAt") && !dis.contains("dx.op.quadOp"), "wave64 {wave64}: a wave read or quadOp\n{dis}"); + // (the module's CSE shares the reads of the one source register) + let n = dis.matches("call i32 @dx.op.quadReadLaneAt.i32(").count(); + assert!((4..=16).contains(&n), "wave64 {wave64}: {n} quad reads\n{dis}"); + } + // the same reads in a compute program: wave reads + let mut code = dpp16(7, 0xB1); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let t = translate(&code, &Options { wave64: false, ..Default::default() }).unwrap(); + assert!(t.hlsl.contains("rla(v2, ") && !t.hlsl[t.hlsl.rfind(" main(").expect("main")..].contains("QuadReadLaneAt("), "{}", t.hlsl); +} + +/// `quad_reads_in_a_loop_ps` on the GPU, through both translators and as a wave32 and a wave64 +/// program: every pixel, those of the quads on the triangles' shared diagonal included, gets +/// its quad's values. +#[test] +fn gpu_ps_quad_reads_in_a_loop_see_helper_lanes() { + if !gpu_ready() { + return; + } + use crate::gpu::dxil::kernel::{self, KernelOptions}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT; + let vs = super::dxc::compile("float4 main(float2 p : POSITION) : SV_Position { return float4(p, 0.5, 1.0); }\n", "main", "vs_6_6", &[]).unwrap(); + let psi = super::PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false }; + let quad = [-1.0f32, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0]; + let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }]; + let size = 32usize; + let fv = |x: usize, y: usize| (x as f32 + 0.5) + 64.0 * (y as f32 + 0.5); + let want = |x: usize, y: usize| -> [f32; 4] { + let (qx, qy) = (x & !1, y & !1); + let sum = fv(qx, qy) + fv(qx + 1, qy) + fv(qx, qy + 1) + fv(qx + 1, qy + 1); + [3.0 * sum, 3.0 * fv(x ^ 1, y ^ 1), 3.0, 3.0 * (fv(x, y ^ 1) + fv(x ^ 1, y))] + }; + for wave64 in [false, true] { + let code = quad_reads_in_a_loop_ps(wave64); + let t = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}\n{}", t.unsupported_why, t.hlsl); + let hlsl = super::dxc::compile(&t.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + let direct = kernel::translate_pixel(&code, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, &psi).expect("translate PS").dxil; + for (form, ps) in [("HLSL", &hlsl), ("direct DXIL", &direct)] { + let px = runner::draw(&vs, ps, &layout, &quad, 8, &[], &[], size as u32, [9.0; 4]).unwrap(); + let bad: Vec<(usize, usize, [f32; 4], [f32; 4])> = + (0..size * size).map(|i| (i % size, i / size)).filter(|&(x, y)| px[y * size + x] != want(x, y)).map(|(x, y)| (x, y, px[y * size + x], want(x, y))).collect(); + let edge = bad.iter().filter(|b| b.0 >> 1 == b.1 >> 1).count(); + println!("{form}, wave64 {wave64}: {} of {} pixels wrong ({edge} in the diagonal's quads)", bad.len(), size * size); + assert!(bad.is_empty(), "{form}, wave64 {wave64}: {} pixels wrong ({edge} in the diagonal's quads), first (x, y, got, want) {:?}", bad.len(), &bad[..bad.len().min(4)]); + } + } +} + /// XCL image descriptor (T#, GFX10 layout): BASE_ADDRESS = SRV heap index, FORMAT, TYPE. fn tsharp(index: u32, format: u32, ty: u32) -> [u32; 8] { [index, format << 20, 0, ty << 28, 0, 0, 0, 0] @@ -3770,7 +4017,7 @@ fn gpu_static_samplers_from_constants_in_code() { ("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", vec![("ADDR", 8), ("DATA", 10), ("SADDR", 0x7D)], None), ]); let refs: Vec<_> = compute.iter().map(|(n, e, fields, literal)| (*n, *e, fields.as_slice(), *literal)).collect(); - let cs = super::CsInterface { threads: [32, 1, 1], user_sgprs: 24, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [32, 1, 1], user_sgprs: 24, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let options = crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; let translated = crate::gpu::dxil::kernel::translate_compute(&prog(&refs), options, &cs).unwrap(); assert_eq!(translated.static_samplers, [(point, false), (linear, false)]); @@ -4198,6 +4445,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] @@ -4415,6 +4725,15 @@ fn gpu_packed_math_dots_movrel() { ("V_DOT2_F32_F16", "ENC_VOP3P", &[("VDST", 4), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 5), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)], None), ("V_DOT4_U32_U8", "ENC_VOP3P", &[("VDST", 6), ("SRC0", V + 7), ("SRC1", V + 8), ("SRC2", V + 9), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)], None), ("V_DOT4_I32_I8", "ENC_VOP3P", &[("VDST", 11), ("SRC0", V + 7), ("SRC1", V + 12), ("SRC2", V + 9), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)], None), + // OP_SEL / OP_SEL_HI pick the sources' halves, constants' too (FSR4's weights): + // an inline 64 with its halves swapped is 0x00400000 + ("V_DOT4_I32_I8", "ENC_VOP3P", &[("VDST", 14), ("SRC0", V + 7), ("SRC1", 192), ("SRC2", V + 9), ("OP_SEL", 2), ("OP_SEL_HI", 1), ("OP_SEL_HI_2", 1)], None), + // an inline 10 in both halves: 0x000A000A + ("V_DOT4_U32_U8", "ENC_VOP3P", &[("VDST", 15), ("SRC0", V + 7), ("SRC1", 138), ("SRC2", V + 9), ("OP_SEL_HI", 1), ("OP_SEL_HI_2", 1)], None), + // v12's halves swapped: 0x0708FF06 + ("V_DOT4_I32_I8", "ENC_VOP3P", &[("VDST", 16), ("SRC0", V + 7), ("SRC1", V + 12), ("SRC2", V + 9), ("OP_SEL", 2), ("OP_SEL_HI", 1), ("OP_SEL_HI_2", 1)], None), + // an inline 2.0 (integer instructions take the f32 bits) swapped: 0x00004000 + ("V_DOT4_U32_U8", "ENC_VOP3P", &[("VDST", 17), ("SRC0", V + 8), ("SRC1", 244), ("SRC2", V + 9), ("OP_SEL", 2), ("OP_SEL_HI", 1), ("OP_SEL_HI_2", 1)], None), ("V_PK_FMAC_F16", "ENC_VOP2", &[("VDST", 13), ("SRC0", V), ("VSRC1", 1)], None), ("S_MOV_B32", "ENC_SOP1", &[("SDST", 124), ("SSRC0", 131)], None), // m0 = 3 ("V_MOVRELS_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 20)], None), // v10 = v23 @@ -4445,6 +4764,10 @@ fn gpu_packed_math_dots_movrel() { assert_eq!(f32::from_bits(v[4]), 12.375, "lane {l} v_dot2_f32_f16"); assert_eq!(v[6], 70 + l as u32, "lane {l} v_dot4_u32_u8"); assert_eq!(v[11] as i32, 4 * 8 + 3 * 7 + 2 * 6 - 1 + l as i32, "lane {l} v_dot4_i32_i8 (bytes from the low end)"); + assert_eq!(v[14], 2 * 64 + l as u32, "lane {l} v_dot4_i32_i8 op_sel:[0,1,0] op_sel_hi:[1,0,1] of an inline 64"); + assert_eq!(v[15], 4 * 10 + 2 * 10 + l as u32, "lane {l} v_dot4_u32_u8 op_sel_hi:[1,0,1] of an inline 10"); + assert_eq!(v[16] as i32, 4 * 6 - 3 + 2 * 8 + 7 + l as i32, "lane {l} v_dot4_i32_i8 op_sel:[0,1,0] op_sel_hi:[1,0,1] of a register"); + assert_eq!(v[17], 7 * 64 + l as u32, "lane {l} v_dot4_u32_u8 op_sel:[0,1,0] op_sel_hi:[1,0,1] of an inline 2.0"); assert_eq!(v[13], h(1.0 + 1.5 * 2.25) | h(2.0 - 2.0 * 0.5) << 16, "lane {l} v_pk_fmac_f16"); assert_eq!(v[10], 103, "lane {l} v_movrels_b32"); assert_eq!(v[40], l as u32, "lane {l} v_movreld_b32"); @@ -4499,7 +4822,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) }; @@ -4623,7 +4946,7 @@ fn gpu_mesh_mode_exports_stay_inside_the_record() { rw_mask: 0xF, stream: 0, }; - let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 128, max_vertices: 64, max_primitives: 32 }; + let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 128, max_vertices: 64, max_primitives: 32, params: None }; let exp = |tgt: u64, en: u64, v: [u64; 4], done: u64| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option) { ("EXP", "ENC_EXP", vec![("TGT", tgt), ("EN", en), ("VSRC0", v[0]), ("VSRC1", v[1]), ("VSRC2", v[2]), ("VSRC3", v[3]), ("DONE", done)], None) }; @@ -4702,6 +5025,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}"); @@ -4743,7 +5067,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 @@ -4800,7 +5124,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 @@ -5056,7 +5380,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 @@ -6452,7 +6776,7 @@ fn gpu_compute_mode_dispatch_abi() { return; } use super::{dxc, CsInterface}; - let cs = CsInterface { threads: [16, 8, 1], user_sgprs: 2, tgid: [true, true, false], tg_size: false, tid_components: 2 }; + let cs = CsInterface { threads: [16, 8, 1], user_sgprs: 2, tgid: [true, true, false], tg_size: false, tid_components: 2, ..Default::default() }; let p = prog(&[ ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 132), ("VSRC1", 1)], None), // y · 16 ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 2), ("VSRC1", 0)], None), // index in group @@ -7329,10 +7653,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))])); @@ -8183,7 +8507,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(); @@ -8589,7 +8913,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] { @@ -8635,7 +8959,7 @@ fn split_wave64_meet_form_by_group_size() { let lane = prog(&[("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V)], None)]); for dims in [[64u32, 1, 1], [8, 8, 1], [4, 4, 4], [40, 1, 1], [256, 1, 1], [8, 8, 4]] { let threads = dims.iter().product::(); - let cs = CsInterface { threads: dims, user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: dims, user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let t = translate(&lane, &Options { mode: Mode::Compute(cs), wave64: true, split_wave64: true, no_remap: true, ..Default::default() }).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); assert!(t.hlsl.contains(&format!("#define XCL_X_THREADS {threads}u")), "{dims:?}"); @@ -8643,14 +8967,14 @@ fn split_wave64_meet_form_by_group_size() { assert!(t.hlsl.contains(&format!("#define XCL_X_SPIN {}\n", want as u8)), "{dims:?}"); } // A half without a partner (32 threads or fewer: `xcl_xn == 0`) leaves before either form. - let t = translate(&lane, &Options { mode: Mode::Compute(CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }), wave64: true, split_wave64: true, ..Default::default() }).unwrap(); + let t = translate(&lane, &Options { mode: Mode::Compute(CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }), wave64: true, split_wave64: true, ..Default::default() }).unwrap(); let meet = &t.hlsl[t.hlsl.find("bool xcl_x_meet()").unwrap()..]; let (leave, spin, barrier) = (meet.find("if (xcl_xn == 0u) return false;").unwrap(), meet.find("#if XCL_X_SPIN").unwrap(), meet.find("GroupMemoryBarrierWithGroupSync();").unwrap()); assert!(leave < spin && spin < barrier); // A multi-wave production entry checks both its initial EXEC exchange and an // instruction exchange before any following instruction can consume the timeout value. - let cs = CsInterface { threads: [128, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [128, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let split = translate(&lane, &Options { mode: Mode::Compute(cs.clone()), wave64: true, split_wave64: true, no_remap: true, ..Default::default() }).unwrap(); assert!(split.hlsl.contains("static const uint XCL_X_FAIL = 0x80000000u;")); assert!(split.hlsl.contains("((o | (o + lanes) | need) & XCL_X_FAIL) != 0u")); @@ -8732,7 +9056,7 @@ fn split_wave64_lds_reads_meet_after_writes() { } // a compute group of several console waves (the counters' meet) and one of a single half for threads in [128u32, 32] { - let cs = super::CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let h = hlsl(&[write, read], &Options { mode: Mode::Compute(cs), ..split.clone() }); assert!(h.contains(AFTER_WRITE) && h.contains(WROTE), "{threads} threads"); } @@ -9135,7 +9459,7 @@ fn gpu_split_wave64_local_and_exchanged_masks_in_diverging_waves() { ]); for dims in [[256u32, 1, 1], [8, 8, 4]] { let threads = dims.iter().product::(); - let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3 }; + let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -9215,7 +9539,7 @@ fn gpu_split_wave64_waves_diverge() { ]); for dims in [[256u32, 1, 1], [64, 1, 1], [8, 8, 4], [16, 4, 1]] { let threads = dims.iter().product::(); - let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3 }; + let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -9333,7 +9657,7 @@ fn gpu_split_wave64_lds_write_then_read_across_halves() { let base = 0x1000usize; let groups = 64usize; for threads in [64u32, 128, 256] { - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 5, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 5, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -9390,7 +9714,7 @@ fn gpu_split_wave64_one_wave_groups_end_early() { ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 4), ("SADDR", 0x7D)], None), ]); for threads in [64u32, 48, 40] { - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -9454,7 +9778,7 @@ fn lds_order_program() -> Vec { } fn lds_order_cs(threads: u32) -> super::CsInterface { - super::CsInterface { threads: [threads, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 } + super::CsInterface { threads: [threads, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() } } #[test] @@ -9655,7 +9979,7 @@ fn wave_local_remap_decision_and_console_ids() { ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 0), ("SADDR", 0x7D)], None), ]); let translate_as = |code: &[u8], threads, tgid, no_remap| { - let cs = CsInterface { threads, user_sgprs: 2, tgid, tg_size: false, tid_components: 3 }; + let cs = CsInterface { threads, user_sgprs: 2, tgid, tg_size: false, tid_components: 3, ..Default::default() }; translate(code, &Options { mode: Mode::Compute(cs), wave64: true, split_wave64: true, no_remap, ..Default::default() }).unwrap() }; for (threads, remap, shape, group_id) in [ @@ -9690,7 +10014,7 @@ fn dispatch_thread_limits_seed_compute_exec_for_native_and_remapped_groups() { translate( &p, &Options { - mode: Mode::Compute(CsInterface { threads, user_sgprs: 2, tgid: [true; 3], tg_size: false, tid_components: 3 }), + mode: Mode::Compute(CsInterface { threads, user_sgprs: 2, tgid: [true; 3], tg_size: false, tid_components: 3, ..Default::default() }), wave64: true, split_wave64, ..Default::default() @@ -9765,7 +10089,7 @@ fn bench_split_wave64() { let mut exchanges = 0; let mut spin = false; for wave64 in [false, true] { - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64, ..Default::default() }); let t = translate(&p, &opt).unwrap(); // the loop's exchanges: masks read whole (`x64_masks`: not the v_cndmask @@ -9818,7 +10142,7 @@ fn gpu_compute_tg_size_counts_a_partial_last_wave() { ]); for (threads, wave64) in [(96u32, true), (96, false), (64, true), (40, false), (128, true)] { let lanes = if wave64 { 64 } else { 32 }; - let cs = super::CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: true, tid_components: 1 }; + let cs = super::CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: true, tid_components: 1, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -9888,7 +10212,7 @@ fn dispatch_loop_budget_shrinks_with_the_groups() { /// the HLSL of every other program (and with it the DXIL cache's key) is as it was. #[test] fn only_compute_programs_with_a_loop_read_the_dispatch_loop_budget() { - let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let compute = Options { mode: Mode::Compute(cs), wave64: false, ..Default::default() }; let looping = translate(&endless_loop_program(), &compute).unwrap(); assert!(looping.complete(), "{:?}", looping.unsupported_why); @@ -9919,7 +10243,7 @@ fn compute_loop_counts_compile() { if super::dxc::location().is_err() { return runner::skip_test("no DXC"); } - let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; for wave64 in [false, true] { let compute = Options { mode: Mode::Compute(cs.clone()), wave64, ..Default::default() }; for code in [endless_loop_program(), endless_loop_entered_three_times()] { @@ -9943,7 +10267,7 @@ fn gpu_compute_loop_passes_follow_the_dispatch() { } let threads = 64u32; let run = |p: &[u8], wave64: bool, slot: u32| -> u32 { - let cs = super::CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64, ..Default::default() }); let t = translate(p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -10003,7 +10327,7 @@ fn gpu_compute_folded_dispatch_runs_each_console_group_once() { assert_eq!(got, if k < 100 { k as u32 } else { 0xFFFF_FFFF }, "{what}: unfolded group {k}"); } }; - let cs = super::CsInterface { threads: [1, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [1, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; // the native wave64 forms need a GPU that runs wave64 (the split form runs anywhere) let wave64_ok = runner::wave64_supported() == Ok(true); for wave64 in [false, true] { @@ -10049,7 +10373,7 @@ fn compute_prologues_leave_the_lanes_past_a_thread_limit_out_of_exec() { (false, false, [64, 1, 1], true), ] { let what = format!("wave64 {wave64}, split {split}, {threads:?}, barrier {with_barrier}"); - let cs = super::CsInterface { threads, user_sgprs: 2, tgid: [true, true, false], tg_size: false, tid_components: 2 }; + let cs = super::CsInterface { threads, user_sgprs: 2, tgid: [true, true, false], tg_size: false, tid_components: 2, ..Default::default() }; let mut lines = store.to_vec(); if with_barrier { lines.insert(0, ("S_BARRIER", "ENC_SOPP", &[], None)); @@ -10117,7 +10441,7 @@ fn gpu_compute_thread_limits_leave_the_lanes_past_them_out() { forms.push(("direct wave64", true, |l, cs| translate_compute(&code_of(l), KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }, cs).unwrap().dxil)); forms.push(("per-lane wave64", true, |l, cs| super::lower_dxil::compute_code(&code_of(l), cs, true).unwrap())); } - let cs = |threads: [u32; 3], y: bool| CsInterface { threads, user_sgprs: 2, tgid: [true, y, false], tg_size: false, tid_components: if y { 2 } else { 1 } }; + let cs = |threads: [u32; 3], y: bool| CsInterface { threads, user_sgprs: 2, tgid: [true, y, false], tg_size: false, tid_components: if y { 2 } else { 1 }, ..Default::default() }; let io = |x: u32, y: u32, folded: u32| { let mut io = vec![0u32; 128]; (io[IO_THREAD_LIMIT[0]], io[IO_THREAD_LIMIT[1]], io[IO_GROUP_LIMIT]) = (x, y, folded); @@ -10912,7 +11236,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() { @@ -10964,6 +11288,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); @@ -10987,7 +11312,7 @@ fn ps_ancillary_and_pos_fixed_vgprs() { ("V_BFE_U32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + src), ("SRC1", 136), ("SRC2", 132)], None), ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 1), ("VSRC0", 3), ("DONE", 1), ("VM", 1)], None), ]); - let psi = PsInterface { inputs, outputs: vec![el("SV_Target", 0, 64, 1, 0, 0xF)], input_ena: ena, attrs: None }; + let psi = PsInterface { inputs, outputs: vec![el("SV_Target", 0, 64, 1, 0, 0xF)], input_ena: ena, attrs: None, early_depth: false }; let pt = translate(&code, &Options { mode: Mode::Pixel(psi), wave64: true, ..Default::default() }).unwrap(); assert!(pt.complete(), "{:?}\n{}", pt.unsupported_why, pt.hlsl); if super::dxc::location().is_ok() { @@ -11169,7 +11494,7 @@ fn gpu_ds_permute_b32() { #[test] fn ds_permute_b32_refused_where_upper_lanes_do_not_exist() { let code = prog(&[("DS_PERMUTE_B32", "ENC_DS", &[("VDST", 10), ("ADDR", 1), ("DATA0", 0)], None)]); - let ps = Mode::Pixel(super::PsInterface { inputs: vec![], outputs: vec![], input_ena: 0x7F, attrs: None }); + let ps = Mode::Pixel(super::PsInterface { inputs: vec![], outputs: vec![], input_ena: 0x7F, attrs: None, early_depth: false }); let t = translate(&code, &Options { mode: ps.clone(), wave64: true, split_wave64: true, ..Default::default() }).unwrap(); assert_eq!(t.unsupported.get("ds_permute_b32"), Some(&1), "{:?}", t.unsupported); let t = translate(&code, &Options { mode: ps, wave64: true, split_wave64: false, ..Default::default() }).unwrap(); @@ -11825,7 +12150,7 @@ fn gpu_safe_s_barrier_multi_warp_and_early_endpgm() { ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 5), ("SADDR", 0x7D)], None), ]); - let cs = CsInterface { threads: [128, 1, 1], user_sgprs: 2, tgid: [false, false, false], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [128, 1, 1], user_sgprs: 2, tgid: [false, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let base = 0x100usize; let mut io = vec![0u32; 128]; io[0] = base as u32; @@ -12360,7 +12685,7 @@ fn jumps_to_outer_loop_heads_are_structured() { /// backends follow the same predicate. #[test] fn compute_globallycoherent_only_when_needed() { - let cs = super::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let enc = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); let prog = |insts: &[(&str, &str, &[(&str, u64)])]| { let mut c = Vec::new(); @@ -12440,7 +12765,7 @@ fn gpu_compute_coherent_and_cached_loads() { if !gpu_ready() { return; } - let cs = super::CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let enc = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); // 1. Plain cached compute: each thread reads a uniform dword via SMEM (s[0:1] = 0x100) and @@ -12882,7 +13207,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() } @@ -12920,6 +13245,41 @@ fn gpu_ps_readfirstlane_loop_on_a_primitive_edge_ends() { assert!(bad.is_empty(), "{} pixels wrong (iterations, wave OR, own word, lane count), first {:?}", bad.len(), &bad[..bad.len().min(8)]); } +/// The float color exports of a pixel shader with `XCL_NAN_GUARD` on (the default), through both +/// translators: NaN becomes 0 and ±Inf ±65504, finite values stay as they are – also past +/// 65504, which a 32-bit float target holds (the HLSL path clamped them to it). +#[test] +fn gpu_ps_nan_guard_keeps_finite_exports() { + if !gpu_ready() { + return; + } + if !crate::gpu::dxil::kernel::nan_guard_enabled() { + println!("XCL_NAN_GUARD=0: nothing to check"); + return; + } + use crate::gpu::dxil::kernel::{self, KernelOptions}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT; + let vs = super::dxc::compile("float4 main(float2 p : POSITION) : SV_Position { return float4(p, 0.5, 1.0); }\n", "main", "vs_6_6", &[]).unwrap(); + let words = [0x7FC0_0000u32, 0xFF80_0000, 1.0e6f32.to_bits(), (-70000.0f32).to_bits()]; + let mut code = Vec::new(); + for (k, &w) in words.iter().enumerate() { + code.extend(encode("V_MOV_B32", "ENC_VOP1", &[("VDST", 4 + k as u64), ("SRC0", 255)], Some(w)).unwrap()); + } + code.extend(encode("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let psi = super::PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false }; + let t = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}\n{}", t.unsupported_why, t.hlsl); + let hlsl = super::dxc::compile(&t.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + let direct = kernel::translate_pixel(&code, KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, &psi).expect("translate PS").dxil; + let quad = [-1.0f32, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0]; + let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }]; + for (form, ps) in [("HLSL", &hlsl), ("direct DXIL", &direct)] { + let px = runner::draw(&vs, ps, &layout, &quad, 8, &[], &[], 8, [9.0; 4]).unwrap(); + assert!(px.iter().all(|p| *p == [0.0, -65504.0, 1.0e6, -70000.0]), "{form}: (NaN, -Inf, 1e6, -70000) exported as {:?}", px[0]); + } +} + /// A wave32 pixel program under `s_wqm` with the march loop of a retail volumetric PS after /// another loop: every lane counts steps in a vector register, and the loop goes on as long as /// a lane of the mask taken from EXEC has not reached 6 (`v_cmp_le_f32`, `s_andn2 mask, mask, @@ -12963,7 +13323,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() } @@ -13014,9 +13374,10 @@ fn gpu_v_dot8_u32_u4_edge_cases() { (0xA5A5_5A5A, 0x5A5A_A5A5, 0x7FFF_FFFF), (0x0000_000F, 0x0000_000F, 0xFFFF_FF1F), ]; + // (OP_SEL_HI as a compiler sets it: each source's high half from its high half) let p = prog(&[ - ("V_DOT8_U32_U4", "ENC_VOP3P", &[("VDST", 3), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2)], None), - ("V_DOT8_U32_U4", "ENC_VOP3P", &[("VDST", 4), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2), ("CLAMP", 1)], None), + ("V_DOT8_U32_U4", "ENC_VOP3P", &[("VDST", 3), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)], None), + ("V_DOT8_U32_U4", "ENC_VOP3P", &[("VDST", 4), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1), ("CLAMP", 1)], None), ]); let dot_u4 = |a: u32, b: u32, c: u32, clamp: bool| -> u32 { let mut sum = c as u64; diff --git a/crates/xcl/src/gpu/rt_leave_out.rs b/crates/xcl/src/gpu/rt_leave_out.rs new file mode 100644 index 0000000000..174248a4b9 --- /dev/null +++ b/crates/xcl/src/gpu/rt_leave_out.rs @@ -0,0 +1,181 @@ +//! `XCL_RT_LEAVE_OUT=[,…]` (off by default): compute programs whose shader +//! container holds one of the fragments are left out – the title's pipeline gets the dummy +//! compute program a console shader that cannot be translated gets, so its dispatches are +//! skipped, and the shader preparation and `xcl shaders --precompile` pass them over. +//! +//! What it is for: a title's ray-tracing programs that shade the hits of rays or start rays +//! (on a retail title about 1,000 programs, ~1 MB of DXIL each, the largest of its cold driver +//! compiles) do nothing while the title has built no acceleration structure: every ray misses. +//! The fragments name those programs (a name in the container's debug data; find it with +//! `xcl rpf --find`); XCL's source names no title's programs. +//! +//! So that leaving them out stays harmless, XCL watches the acceleration structures the +//! title's views name (`D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE` in unified +//! memory) and warns once when one of them gets a root node: from then on rays can hit, and +//! the programs left out would have shaded those hits. +//! +//! Ported from Vice-Tay (https://github.com/TaynanGT/Vice-Tay, GPL-3.0-or-later; THIRD_PARTY.md). +//! Changes (2026-11-27): the programs are named by the user's fragments instead of names in +//! the source; one switch; the structure watch and its warning are new; the preparation and +//! the precompile pass the programs over. + +use std::collections::BTreeSet; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +/// Fragments shorter than this are refused: they would match bytes of any container. +const SHORTEST: usize = 6; +/// Acceleration structures remembered for the watch (distinct addresses). +const MOST_STRUCTURES: usize = 4096; + +/// The fragments of a `XCL_RT_LEAVE_OUT` value: comma-separated, trimmed, at least +/// [`SHORTEST`] bytes each (shorter ones are dropped). +pub fn fragments_of(value: &str) -> Vec> { + value.split(',').map(str::trim).filter(|f| f.len() >= SHORTEST).map(|f| f.as_bytes().to_vec()).collect() +} + +/// Whether `container` holds one of `fragments`. +pub fn holds_any(container: &[u8], fragments: &[Vec]) -> bool { + fragments.iter().any(|f| container.windows(f.len()).any(|w| w == f.as_slice())) +} + +fn fragments() -> &'static [Vec] { + static F: OnceLock>> = OnceLock::new(); + F.get_or_init(|| { + let Ok(v) = std::env::var("XCL_RT_LEAVE_OUT") else { return Vec::new() }; + let f = fragments_of(&v); + let dropped = v.split(',').map(str::trim).filter(|s| !s.is_empty() && s.len() < SHORTEST).count(); + if f.is_empty() { + crate::xlog_warn!("XCL_RT_LEAVE_OUT: no fragment of at least {SHORTEST} bytes – nothing is left out"); + } else { + crate::xlog_info!( + "XCL_RT_LEAVE_OUT: compute programs holding one of {} fragment(s) are left out while rays cannot hit{}", + f.len(), + if dropped > 0 { format!(" ({dropped} shorter than {SHORTEST} bytes ignored)") } else { String::new() } + ); + } + f + }) +} + +/// Whether the switch is on (at least one usable fragment). +pub fn enabled() -> bool { + !fragments().is_empty() +} + +static LEFT_OUT: AtomicU64 = AtomicU64::new(0); + +/// Whether the compute program in `container` is left out; counts and logs the first few. +pub fn left_out(container: &[u8]) -> bool { + if !enabled() || !holds_any(container, fragments()) { + return false; + } + let n = LEFT_OUT.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 3 || n.is_power_of_two() { + crate::xlog_info!( + "XCL_RT_LEAVE_OUT: compute program of record {:016x} left out (#{n}): its dispatches are skipped", + crate::gpu::shader::fnv64(container) + ); + } + true +} + +/// How many compute programs were left out so far. +pub fn left_out_count() -> u64 { + LEFT_OUT.load(Ordering::Relaxed) +} + +static STRUCTURES: Mutex> = Mutex::new(BTreeSet::new()); + +/// An acceleration structure in unified memory that a title's view names (only kept while the +/// switch is on). +pub fn note_structure(va: u64) { + if enabled() { + let mut s = STRUCTURES.lock().unwrap(); + if s.len() < MOST_STRUCTURES { + s.insert(va); + } + } +} + +/// The root node id in an acceleration structure's header: `None` while it has none (0 or +/// all ones, as before a build). +pub fn root_of(header: &[u8]) -> Option { + let at = crate::gpu::bvh::ROOT_AT; + let root = u32::from_le_bytes(header.get(at..at + 4)?.try_into().ok()?); + (root != 0 && root != u32::MAX).then_some(root) +} + +/// Looks at the structures views named (called every few hundred frames): warns once when one +/// has a root node, since the programs left out would then have hits to shade. +pub fn check_structures() { + static WARNED: AtomicBool = AtomicBool::new(false); + if !enabled() || WARNED.load(Ordering::Relaxed) { + return; + } + let all: Vec = STRUCTURES.lock().unwrap().iter().copied().collect(); + let header = crate::gpu::bvh::HEADER_BYTES; + for va in all { + let p = va as usize; + if !crate::gpu::shader::readable(p, header) { + continue; + } + // SAFETY: `readable` just checked the range; title memory, only read + let bytes = unsafe { std::slice::from_raw_parts(p as *const u8, header) }; + if let Some(root) = root_of(bytes) { + if !WARNED.swap(true, Ordering::Relaxed) { + crate::xlog_warn!( + "XCL_RT_LEAVE_OUT: the acceleration structure at {va:#x} has a root node ({root:#x}) now – rays can hit, and the {} compute program(s) left out would shade those hits; run without XCL_RT_LEAVE_OUT for this title", + left_out_count() + ); + } + return; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fragments_are_trimmed_and_short_ones_dropped() { + let f = fragments_of(" ResolveA ,abc, ,LongerName,"); + assert_eq!(f, vec![b"ResolveA".to_vec(), b"LongerName".to_vec()]); + assert!(fragments_of("").is_empty()); + assert!(fragments_of("short").is_empty()); + } + + #[test] + fn a_container_is_matched_by_any_fragment_anywhere() { + let mut container = vec![0u8; 64]; + container.extend_from_slice(b"\x00prog_Example_Name_x\x00"); + container.extend_from_slice(&[0xFF; 32]); + assert!(holds_any(&container, &fragments_of("Other_Name,Example_Name"))); + assert!(!holds_any(&container, &fragments_of("Example_Names"))); + assert!(!holds_any(&container, &[])); + // a fragment at the very end still matches + assert!(holds_any(b"xxxxEnd_of_it", &fragments_of("End_of_it"))); + } + + #[test] + fn a_header_without_a_root_has_none() { + let mut h = vec![0u8; crate::gpu::bvh::HEADER_BYTES]; + assert_eq!(root_of(&h), None); + let at = crate::gpu::bvh::ROOT_AT; + h[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(root_of(&h), None); + h[at..at + 4].copy_from_slice(&0x25u32.to_le_bytes()); + assert_eq!(root_of(&h), Some(0x25)); + assert_eq!(root_of(&h[..at]), None, "a header too short to hold the root"); + } + + #[test] + fn a_built_structure_from_the_builder_has_a_root() { + // XCL's own builder writes the console layout the watch reads + let tris = crate::gpu::bvh::tests::random_tris(8, 3); + let b = crate::gpu::bvh::build(&tris, 0); + let root = root_of(&b.data).expect("a built structure has a root id"); + assert_eq!(root, b.root); + } +} diff --git a/crates/xcl/src/gpu/shader.rs b/crates/xcl/src/gpu/shader.rs index 0d510f18d3..4da0ad33eb 100644 --- a/crates/xcl/src/gpu/shader.rs +++ b/crates/xcl/src/gpu/shader.rs @@ -215,6 +215,10 @@ pub fn readable(p: usize, len: usize) -> bool { if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(p, len)) { return true; } + if crate::hle::d3d12x::sparse::known_readable(p, end) { + return true; + } + let rev0 = crate::hle::d3d12x::sparse::source_regions_rev(); if let Some(answer) = pages_readable(p, end) { return answer; } @@ -225,7 +229,14 @@ pub fn readable(p: usize, len: usize) -> bool { if n == 0 || mbi.State != MEM_COMMIT || mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD) != 0 || mbi.Protect == 0 { return false; } - cur = mbi.BaseAddress as usize + mbi.RegionSize; + let lo = mbi.BaseAddress as usize; + let hi = lo.saturating_add(mbi.RegionSize); + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(lo) || u.is_view(lo) || u.contains(lo)) + || crate::hle::kernelx::in_graphics_reservation(lo) + { + crate::hle::d3d12x::sparse::cache_readable_region(lo, hi, rev0); + } + cur = hi; } true } diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 18b4024907..5ef0bf88a7 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -110,6 +110,11 @@ pub(crate) fn configured_runtime_windows() -> usize { const DESC_HEADROOM: usize = 512 << 20; /// cap on the eager committed coherent window in `for_runtime` (per-draw args, readback buffers) const RUNTIME_COMMITTED_CAP: usize = 512 << 20; +/// What the coherent window has beyond the title's need stored from earlier runs +/// (`coherent_hint_for`). The window is committed and held in RAM whole while it is open as a +/// heap: with 512 MB a retail title's 968 MB window had 416 MB in use at most (its 457 MB need, +/// XCL's 96 MB kept for itself included). +const COHERENT_HEADROOM: usize = 192 << 20; #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum WindowKind { @@ -901,7 +906,22 @@ impl Uma { // a block of XCL's pool goes back to the pool let mut g = self.pool.lock().unwrap(); if p >= g.0 && p < g.1 { + // (a block freed twice would be handed to two owners at once, each writing over + // the other's records) + if g.2.contains(&p) { + drop(g); + static TWICE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let k = TWICE.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if k.is_power_of_two() { + crate::xlog_error!("UMA: pool block {p:#x} freed while it is free ({k} so far) - left out"); + } + return true; + } g.2.push(p); + drop(g); + for grain in 0..ARENA_BLOCK / GRAIN { + crate::hle::kernelx::pagelog::note("XCL arena block freed", p + grain * GRAIN, 0, ARENA_BLOCK); + } return true; } } @@ -979,6 +999,9 @@ impl Arena { None => u.alloc(ARENA_BLOCK, GRAIN)? as usize, }; blocks.push(p); + for grain in 0..ARENA_BLOCK / GRAIN { + crate::hle::kernelx::pagelog::note("XCL arena block taken", p + grain * GRAIN, 0, ARENA_BLOCK); + } self.at = p + n; self.end = p + ARENA_BLOCK; Some(p as *mut u8) @@ -1085,7 +1108,7 @@ pub fn coherent_hint_for(windows: usize) -> usize { ); return RUNTIME_COMMITTED_CAP.min(cap); } - (title + RUNTIME_COMMITTED_CAP).min(cap) + (title + COHERENT_HEADROOM).max(RUNTIME_COMMITTED_CAP).min(cap) } /// Bytes the coherent window is made with (legacy 4-window cap). @@ -1151,7 +1174,7 @@ pub fn note_coherent_need(bytes: usize) { } let _ = std::fs::write(&f, bytes.to_string()); let cap = max_coherent_bytes(configured_runtime_windows()); - crate::xlog_info!("UMA: the title's graphics memory for the coherent window: {} MB (up to {} MB from the next run)", bytes >> 20, (bytes + RUNTIME_COMMITTED_CAP).min(cap) >> 20); + crate::xlog_info!("UMA: the title's graphics memory for the coherent window: {} MB (up to {} MB from the next run)", bytes >> 20, (bytes + COHERENT_HEADROOM).max(RUNTIME_COMMITTED_CAP).min(cap) >> 20); } } @@ -1169,7 +1192,7 @@ fn settle_coherent_need() { "UMA: this run put {} MB of the title's graphics memory in the coherent window, {} MB were stored for '{route}' (XCL_COHERENT_HEAPS): the next run makes it {} MB", run >> 20, before >> 20, - (next + RUNTIME_COMMITTED_CAP).min(max_coherent_bytes(configured_runtime_windows())) >> 20 + (next + COHERENT_HEADROOM).max(RUNTIME_COMMITTED_CAP).min(max_coherent_bytes(configured_runtime_windows())) >> 20 ); } } diff --git a/crates/xcl/src/heap_count.rs b/crates/xcl/src/heap_count.rs new file mode 100644 index 0000000000..5959c93080 --- /dev/null +++ b/crates/xcl/src/heap_count.rs @@ -0,0 +1,405 @@ +//! XCL's own heap, counted (`XCL_HEAP_COUNT=1`, with `XCL_ACTIVITY`): how much of the process's +//! commit is memory XCL's own code allocated, by the size of the allocations, and from where: +//! every allocation of 64 KiB or more with its call stack, and one smaller allocation in +//! `SAMPLE` (chosen by its address) standing for `SAMPLE` times its bytes. +//! +//! The process holds the title's memory, the driver's, the shader compiler's and XCL's own in one +//! number (`memory: N MB committed by the process`). The title's is found by its addresses; +//! this tells XCL's apart from the rest. Every allocation of XCL's Rust code goes through +//! `Counting` (the system allocator with counters around it). Off, it costs one relaxed load an +//! allocation. + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}; + +/// The allocator of the crate: the system's, counted while `on()`. +pub struct Counting; + +/// 0: not asked yet, 1: off, 2: on +static STATE: AtomicU8 = AtomicU8::new(0); + +/// upper bounds of the size classes, the last one open +const CLASSES: [usize; 7] = [256, 4 << 10, 64 << 10, 1 << 20, 16 << 20, 256 << 20, usize::MAX]; +const CLASS_NAMES: [&str; 7] = ["<256 B", "<4 KiB", "<64 KiB", "<1 MiB", "<16 MiB", "<256 MiB", "larger"]; +/// live bytes and live allocations of each class +static BYTES: [AtomicUsize; 7] = [const { AtomicUsize::new(0) }; 7]; +static COUNT: [AtomicUsize; 7] = [const { AtomicUsize::new(0) }; 7]; + +/// allocations of this many bytes or more are kept with where they were made (`SITES`) +const LARGE: usize = 64 << 10; +/// one smaller allocation in this many is kept with where it was made (by its address: the +/// free of an allocation not kept costs nothing) +const SAMPLE: usize = 256; +/// frames kept of a kept allocation's call stack (the allocator's own left out) +const FRAMES: usize = 12; +const SLOTS: usize = 1 << 16; + +#[derive(Clone, Copy)] +struct Site { + /// the allocation (0: free slot, 1: a slot freed, passed over in a search) + ptr: usize, + size: usize, + frames: [usize; FRAMES], +} + +/// The large allocations alive, an open-addressed table by address (no allocation of its own: +/// it is used inside the allocator). +struct Sites(std::cell::UnsafeCell<[Site; SLOTS]>); +// SAFETY: only touched under `LOCK` +unsafe impl Sync for Sites {} +static SITES: Sites = Sites(std::cell::UnsafeCell::new([Site { ptr: 0, size: 0, frames: [0; FRAMES] }; SLOTS])); +static LOCK: AtomicBool = AtomicBool::new(false); +/// large allocations the full table had no slot for +static UNTRACKED: AtomicUsize = AtomicUsize::new(0); + +fn class(size: usize) -> usize { + CLASSES.iter().position(|&c| size < c).unwrap_or(CLASSES.len() - 1) +} + +/// Whether an allocation of `size` bytes at `ptr` is kept with its call stack. +fn kept(ptr: usize, size: usize) -> bool { + size >= LARGE || ((ptr >> 4).wrapping_mul(0xD6E8_FEB8_6659_FD93) >> (usize::BITS - SAMPLE.trailing_zeros())) == 0 +} + +/// The bytes a kept allocation stands for. +fn weight(size: usize) -> usize { + if size >= LARGE { size } else { size * SAMPLE } +} + +fn slot_of(ptr: usize) -> usize { + (ptr >> 4).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> (usize::BITS - SLOTS.trailing_zeros()) +} + +fn locked(f: impl FnOnce(&mut [Site; SLOTS]) -> R) -> R { + while LOCK.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() { + std::hint::spin_loop(); + } + // SAFETY: `LOCK` is held + let r = f(unsafe { &mut *SITES.0.get() }); + LOCK.store(false, Ordering::Release); + r +} + +/// Whether allocations are counted (`XCL_HEAP_COUNT=1`). The variable is read without the +/// standard library's `env` (it allocates: this runs inside the allocator). +fn on() -> bool { + match STATE.load(Ordering::Relaxed) { + 2 => true, + 1 => false, + _ => { + let mut buf = [0u16; 4]; + const NAME: [u16; 15] = { + let s = b"XCL_HEAP_COUNT\0"; + let mut w = [0u16; 15]; + let mut i = 0; + while i < 15 { + w[i] = s[i] as u16; + i += 1; + } + w + }; + let n = unsafe { windows_sys::Win32::System::Environment::GetEnvironmentVariableW(NAME.as_ptr(), buf.as_mut_ptr(), buf.len() as u32) }; + let yes = n == 1 && buf[0] == b'1' as u16; + STATE.store(if yes { 2 } else { 1 }, Ordering::Relaxed); + yes + } + } +} + +fn added(ptr: *mut u8, size: usize) { + if ptr.is_null() { + return; + } + let c = class(size); + BYTES[c].fetch_add(size, Ordering::Relaxed); + COUNT[c].fetch_add(1, Ordering::Relaxed); + if kept(ptr as usize, size) { + let mut frames = [0usize; FRAMES]; + // (skips this function and the allocator's method) + unsafe { + windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace(2, FRAMES as u32, frames.as_mut_ptr() as *mut *mut std::ffi::c_void, std::ptr::null_mut()); + } + let kept = locked(|t| { + let first = slot_of(ptr as usize); + for k in 0..64 { + let s = &mut t[(first + k) & (SLOTS - 1)]; + if s.ptr <= 1 { + *s = Site { ptr: ptr as usize, size, frames }; + return true; + } + } + false + }); + if !kept { + UNTRACKED.fetch_add(1, Ordering::Relaxed); + } + } +} + +fn removed(ptr: *mut u8, size: usize) { + let c = class(size); + BYTES[c].fetch_sub(size, Ordering::Relaxed); + COUNT[c].fetch_sub(1, Ordering::Relaxed); + if kept(ptr as usize, size) { + locked(|t| { + let first = slot_of(ptr as usize); + for k in 0..64 { + let s = &mut t[(first + k) & (SLOTS - 1)]; + if s.ptr == ptr as usize { + s.ptr = 1; + return; + } + if s.ptr == 0 { + return; + } + } + }); + } +} + +// SAFETY: every call goes to the system allocator unchanged; the counters only watch +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, l: Layout) -> *mut u8 { + let p = System.alloc(l); + if on() { + added(p, l.size()); + } + p + } + + unsafe fn alloc_zeroed(&self, l: Layout) -> *mut u8 { + let p = System.alloc_zeroed(l); + if on() { + added(p, l.size()); + } + p + } + + unsafe fn dealloc(&self, p: *mut u8, l: Layout) { + if on() { + removed(p, l.size()); + } + System.dealloc(p, l) + } + + unsafe fn realloc(&self, p: *mut u8, l: Layout, new_size: usize) -> *mut u8 { + let q = System.realloc(p, l, new_size); + if on() && !q.is_null() { + removed(p, l.size()); + added(q, new_size); + } + q + } +} + +/// The title's allocations XCL serves from the process heap (`kernelx::XMemAllocDefault`): +/// live bytes and live allocations. They share that heap with XCL's own. +static TITLE: [AtomicUsize; 2] = [const { AtomicUsize::new(0) }; 2]; + +/// Whether the counters run (`XCL_HEAP_COUNT=1`): callers that count for others ask first. +pub fn counting() -> bool { + on() +} + +/// The title got `bytes` from the process heap. +pub fn title_added(bytes: usize) { + TITLE[0].fetch_add(bytes, Ordering::Relaxed); + TITLE[1].fetch_add(1, Ordering::Relaxed); +} + +/// The title gave `bytes` of the process heap back. +pub fn title_removed(bytes: usize) { + TITLE[0].fetch_sub(bytes, Ordering::Relaxed); + TITLE[1].fetch_sub(1, Ordering::Relaxed); +} + +/// What the process heap holds, by a walk of it under its lock: (bytes allocated, bytes +/// committed, milliseconds the walk took). XCL's own allocations, the title's from +/// `XMemAllocDefault` and those of the driver, Direct3D and the C runtime are all in it. +fn process_heap() -> Option<(usize, usize, u128)> { + use windows_sys::Win32::System::Memory::{GetProcessHeap, HeapSummary, HEAP_SUMMARY}; + let t = std::time::Instant::now(); + let mut s: HEAP_SUMMARY = unsafe { std::mem::zeroed() }; + s.cb = std::mem::size_of::() as u32; + (unsafe { HeapSummary(GetProcessHeap(), 0, &mut s) } != 0).then(|| (s.cbAllocated, s.cbCommitted, t.elapsed().as_millis())) +} + +/// Windows heaps XCL made for someone else's allocations (the shader compiler's, one a worker): +/// (whose, handle). They are not in the counters above, and a heap keeps memory it once used. +static OTHER_HEAPS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// A serialized Windows heap `whose` allocations go to (`lines` reports what it holds). +pub fn note_heap(whose: &'static str, heap: usize) { + OTHER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()).push((whose, heap)); +} + +/// (heaps, bytes allocated in them, bytes they have committed) of the noted heaps of `whose`. +fn other_heaps(whose: &str) -> (usize, usize, usize) { + use windows_sys::Win32::System::Memory::{HeapSummary, HEAP_SUMMARY}; + let heaps: Vec = OTHER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|h| h.0 == whose).map(|h| h.1).collect(); + let (mut allocated, mut committed) = (0, 0); + for &h in &heaps { + let mut s: HEAP_SUMMARY = unsafe { std::mem::zeroed() }; + s.cb = std::mem::size_of::() as u32; + if unsafe { HeapSummary(h as _, 0, &mut s) } != 0 { + allocated += s.cbAllocated; + committed += s.cbCommitted; + } + } + (heaps.len(), allocated, committed) +} + +/// (live bytes, live allocations) of XCL's own heap; zeros while not counted. +pub fn live() -> (usize, usize) { + (BYTES.iter().map(|b| b.load(Ordering::Relaxed)).sum(), COUNT.iter().map(|c| c.load(Ordering::Relaxed)).sum()) +} + +/// The kept allocations alive, copied into `alive` (made with room for the whole table: no +/// allocation under the lock), but for `alive`'s own buffer, a large allocation of the report's +/// and not XCL's memory being reported. +fn snapshot_into(alive: &mut Vec) { + let own = alive.as_ptr() as usize; + locked(|t| { + for s in t.iter().filter(|s| s.ptr > 1 && s.ptr != own) { + alive.push(*s); + } + }); +} + +/// The lines of the activity log: the heap by size class, then the places that hold the most +/// in large allocations, as offsets in xcl.exe (symbolized afterwards from its .pdb). None: off. +pub fn lines(top: usize) -> Option> { + if !on() { + return None; + } + let (bytes, count) = live(); + let classes: Vec = (0..CLASSES.len()) + .filter(|&c| COUNT[c].load(Ordering::Relaxed) != 0) + .map(|c| format!("{} {} MB in {}", CLASS_NAMES[c], BYTES[c].load(Ordering::Relaxed) >> 20, COUNT[c].load(Ordering::Relaxed))) + .collect(); + let mut out = vec![format!("XCL's own heap: {} MB in {} allocations; by size: {}", bytes >> 20, count, classes.join(", "))]; + let (heaps, allocated, committed) = other_heaps("DXC"); + if heaps != 0 { + out.push(format!("the shader compiler's heaps: {heaps} heaps, {} MB in use, {} MB committed", allocated >> 20, committed >> 20)); + } + // (the walk holds the heap's lock: every third time, a minute apart) + static WALKS: AtomicUsize = AtomicUsize::new(0); + let title = (TITLE[0].load(Ordering::Relaxed), TITLE[1].load(Ordering::Relaxed)); + match (WALKS.fetch_add(1, Ordering::Relaxed) % 3 == 0).then(process_heap).flatten() { + Some((allocated, committed, ms)) => out.push(format!( + "the process heap: {} MB in use, {} MB committed (walked in {ms} ms); of it XCL's own {} MB, the title's {} MB in {} (XMemAllocDefault), others' (driver, Direct3D, C runtime) {} MB", + allocated >> 20, + committed >> 20, + bytes >> 20, + title.0 >> 20, + title.1, + allocated.saturating_sub(bytes + title.0) >> 20 + )), + None => out.push(format!("the title's allocations from the process heap (XMemAllocDefault): {} MB in {}", title.0 >> 20, title.1)), + } + // (copied out under the lock, added up after it: adding up allocates) + let mut alive: Vec = Vec::with_capacity(SLOTS); + snapshot_into(&mut alive); + // (xcl.exe's own base: in host mode the process's executable is the title's) + let base = { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT}; + let mut m = std::ptr::null_mut(); + let flags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT; + unsafe { GetModuleHandleExW(flags, lines as *const u16, &mut m) }; + m as usize + }; + for (large, what) in [(true, "large"), (false, "small")] { + let mut by_site: std::collections::HashMap<[usize; FRAMES], (usize, usize)> = std::collections::HashMap::new(); + for s in alive.iter().filter(|s| (s.size >= LARGE) == large) { + let e = by_site.entry(s.frames).or_default(); + e.0 += weight(s.size); + e.1 += 1; + } + let mut sites: Vec<_> = by_site.into_iter().collect(); + sites.sort_by_key(|s| std::cmp::Reverse(s.1 .0)); + let total: usize = sites.iter().map(|s| s.1 .0).sum(); + out.push(if large { + format!( + "XCL's own heap, large allocations: {} MB in {} from {} places ({} not kept: table full); xcl.exe at {base:#x}", + total >> 20, + alive.iter().filter(|s| s.size >= LARGE).count(), + sites.len(), + UNTRACKED.load(Ordering::Relaxed) + ) + } else { + format!("XCL's own heap, small allocations: about {} MB, from 1 in {SAMPLE} of them kept ({} from {} places)", total >> 20, sites.iter().map(|s| s.1 .1).sum::(), sites.len()) + }); + for (frames, (bytes, n)) in sites.into_iter().take(top) { + let stack: Vec = frames.iter().take_while(|&&f| f != 0).map(|&f| if f >= base && f - base < (64 << 20) { format!("+{:#x}", f - base) } else { format!("{f:#x}") }).collect(); + if large { + out.push(format!("XCL's own heap, large: {} MB in {} from {}", bytes >> 20, n, stack.join(" "))); + } else { + out.push(format!("XCL's own heap, small: about {} MB ({} kept) from {}", bytes >> 20, n, stack.join(" "))); + } + } + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn about_one_small_allocation_in_sample_is_kept() { + let n = (0..1usize << 20).filter(|&k| kept(0x2_0000_0000 + 16 * k, 48)).count(); + let want = (1usize << 20) / SAMPLE; + assert!(n > want / 2 && n < want * 2, "{n} of {} kept, want about {want}", 1 << 20); + assert!(kept(0x1234_0000, LARGE), "every large one"); + assert_eq!(weight(LARGE), LARGE); + assert_eq!(weight(100), 100 * SAMPLE); + } + + #[test] + fn the_reports_own_buffer_is_not_reported() { + let mut alive: Vec = Vec::with_capacity(SLOTS); + // (as the switch on would keep it: a large allocation of the report itself) + added(alive.as_mut_ptr() as *mut u8, SLOTS * std::mem::size_of::()); + let other = 0x4321_0000usize; + added(other as *mut u8, 2 << 20); + snapshot_into(&mut alive); + assert!(alive.iter().all(|s| s.ptr != alive.as_ptr() as usize), "the report's buffer is left out"); + assert!(alive.iter().any(|s| s.ptr == other), "an allocation of XCL's is kept"); + removed(other as *mut u8, 2 << 20); + removed(alive.as_mut_ptr() as *mut u8, SLOTS * std::mem::size_of::()); + } + + #[test] + fn sizes_fall_in_their_class() { + assert_eq!(class(0), 0); + assert_eq!(class(255), 0); + assert_eq!(class(256), 1); + assert_eq!(class((64 << 10) - 1), 2); + assert_eq!(class(64 << 10), 3); + assert_eq!(class(1 << 30), 6); + assert_eq!(class(usize::MAX), 6); + } + + #[test] + fn a_large_allocation_is_kept_with_its_place_until_it_is_freed() { + // (straight at the table: the switch is the process's, read once) + let p = 0x1234_5670usize as *mut u8; + added(p, 3 << 20); + let found = locked(|t| t.iter().find(|s| s.ptr == p as usize).copied()); + let site = found.expect("kept"); + assert_eq!(site.size, 3 << 20); + assert_ne!(site.frames[0], 0, "its call stack was taken"); + removed(p, 3 << 20); + assert!(locked(|t| t.iter().all(|s| s.ptr != p as usize))); + // a small one is kept only when its address is one of the sampled ones + let mut picked = (0x1000_0000usize..).step_by(16).filter(|&a| kept(a, 100)); + let (q, r) = (picked.next().unwrap(), (0x1000_0000usize..).step_by(16).find(|&a| !kept(a, 100)).unwrap()); + added(q as *mut u8, 100); + added(r as *mut u8, 100); + assert!(locked(|t| t.iter().any(|s| s.ptr == q)), "a sampled small allocation is kept"); + assert!(locked(|t| t.iter().all(|s| s.ptr != r)), "another is only counted"); + removed(q as *mut u8, 100); + removed(r as *mut u8, 100); + assert!(locked(|t| t.iter().all(|s| s.ptr != q))); + } +} diff --git a/crates/xcl/src/hle/bcpack/tests.rs b/crates/xcl/src/hle/bcpack/tests.rs index 70c425a95f..6dc20525ca 100644 --- a/crates/xcl/src/hle/bcpack/tests.rs +++ b/crates/xcl/src/hle/bcpack/tests.rs @@ -102,7 +102,7 @@ fn junk_streams_do_not_panic() { } } -/// The BC7 dictionary indices follow VIctory PR #658: a set with 0 bits holds no +/// The BC7 dictionary indices: a set with 0 bits holds no /// indices, and pixel 0 is the anchor (top bit clear). Entry 0 stores all 32 indices /// directly without the repeated width word, keeping its leading `[2, 1, 0, ...]` values. #[test] diff --git a/crates/xcl/src/hle/bcpack/victory.rs b/crates/xcl/src/hle/bcpack/victory.rs index 91c36d38dc..f0870205de 100644 --- a/crates/xcl/src/hle/bcpack/victory.rs +++ b/crates/xcl/src/hle/bcpack/victory.rs @@ -681,10 +681,21 @@ fn pbits(mode: u16) -> bool { matches!(mode, 0 | 1 | 3 | 6 | 7) } +/// The channel rotation of a BC7 block: only modes 4 and 5 have the 2-bit +/// field; in the other modes those control bits mean something else, and +/// reading them as a rotation swapped channels. +fn rotation(ctrl: u16) -> usize { + if matches!(ctrl & 7, 4 | 5) { + usize::from(ctrl >> 3 & 3) + } else { + 0 + } +} + /// Channel precisions: the p-bit is red's lowest bit; rotation swaps alpha /// with the rotated channel. fn bc7_precision(ctrl: u16) -> [u8; 4] { - let (mode, rot) = (ctrl & 7, usize::from(ctrl >> 3 & 3)); + let (mode, rot) = (ctrl & 7, rotation(ctrl)); let mut p = BC7_BITS[usize::from(mode)]; if rot != 0 { p.swap(3, rot - 1); @@ -789,7 +800,7 @@ fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { let mode = ctrl & 7; let subsets = usize::from((ctrl & 0xff) >> 6); let part = usize::from(ctrl >> 8 & 63); - let rot = usize::from(ctrl >> 3 & 3); + let rot = rotation(ctrl); let mut w = Bits::default(); w.put(1 << mode, u32::from(mode) + 1); match mode { @@ -1266,3 +1277,23 @@ mod tests { } } +#[cfg(test)] +mod rotation_tests { + use super::*; + + #[test] + fn bc7_rotation_is_read_only_in_modes_4_and_5() { + for mode in 0u16..8 { + for rot in 0u16..4 { + let ctrl = (rot << 3) | mode; + let want = if matches!(mode, 4 | 5) { usize::from(rot) } else { 0 }; + assert_eq!(rotation(ctrl), want, "mode {mode} rot {rot}"); + let prec = bc7_precision(ctrl); + if !matches!(mode, 4 | 5) { + assert_eq!(prec, bc7_precision(mode), "non-4/5 mode {mode} must ignore rot bits {rot}"); + } + } + } + } +} + diff --git a/crates/xcl/src/hle/bink.rs b/crates/xcl/src/hle/bink.rs index 84fa573aa5..18b949d611 100644 --- a/crates/xcl/src/hle/bink.rs +++ b/crates/xcl/src/hle/bink.rs @@ -12,10 +12,15 @@ //! - `1` / `on` / `true` / `intro`: skip non-looping movies (intro/logo/cutscenes); looping //! movies (`BINKWILLLOOP`, bit 7 of `OpenFlags`) still forward to the real Bink DLL //! - `all`: skip all Bink movies, including looping ones +//! +//! A skipped movie's frame buffers (the planes the title registers with `BinkRegisterFrameBuffers` +//! and draws through its own YUV shader) are never decoded into, so the title showed whatever its +//! memory held: full-screen noise, or flat green (0, 135, 0) where the planes were zero. +//! They are painted black instead (`XCL_SKIP_BINK_BLACK=0` leaves them as they are). #![allow(non_snake_case)] -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::ffi::c_void; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{Mutex, Once, OnceLock}; @@ -38,6 +43,73 @@ pub struct BinkHeader { /// `BINKWILLLOOP` flag in `BinkHeader::open_flags` (set by `BinkSetWillLoop`). pub const BINK_WILL_LOOP: u32 = 0x0000_0080; +/// One plane of `BINKFRAMEBUFFERS`. Layout read from `Bink2Scarlett.dll`: `BinkGetFrameBuffersInfo` +/// sets `allocate` at +8 of each 16-byte plane and the decoder reads the buffer pointer at +0. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct BinkPlane { + pub buffer: *mut u8, + pub allocate: i32, + pub buffer_pitch: u32, +} + +/// `BINKFRAMEPLANESET`: the Y, cR, cB, A and H planes of one frame. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct BinkFramePlaneSet { + pub planes: [BinkPlane; 5], +} + +/// `BINKFRAMEBUFFERS` (`BinkGetFrameBuffersInfo` writes the sizes and clears 3 plane sets at +0x18; +/// `BinkRegisterFrameBuffers` keeps the title's pointer, so the title's struct is the one used). +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct BinkFrameBuffers { + pub total_frames: i32, + pub ya_width: u32, + pub ya_height: u32, + pub crcb_width: u32, + pub crcb_height: u32, + pub frame_num: u32, + pub frames: [BinkFramePlaneSet; 3], +} + +/// Bytes that make each plane black in RAD's BT.601 limited-range conversion (Y 16, cR / cB 128; +/// all-zero planes convert to (0, 135, 0)), alpha 0 so an alpha movie shows nothing; H is left alone. +const PLANE_BLACK: [Option; 5] = [Some(16), Some(128), Some(128), Some(0), None]; + +/// `XCL_SKIP_BINK_BLACK=0` leaves a skipped movie's frame buffers as the title gave them. +fn black_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SKIP_BINK_BLACK").map_or(true, |v| v.trim() != "0")) +} + +/// Paints every frame of `fb` black; returns the bytes written (0 when the struct looks wrong). +unsafe fn blacken(fb: *mut BinkFrameBuffers) -> usize { + if fb.is_null() { + return 0; + } + let f = &*fb; + if !(1..=3).contains(&f.total_frames) { + return 0; + } + let mut written = 0; + for set in &f.frames[..f.total_frames as usize] { + for (k, plane) in set.planes.iter().enumerate() { + let Some(value) = PLANE_BLACK[k] else { continue }; + let (w, h) = if k == 1 || k == 2 { (f.crcb_width, f.crcb_height) } else { (f.ya_width, f.ya_height) }; + if plane.buffer.is_null() || w == 0 || h == 0 || w > 16384 || h > 16384 || plane.buffer_pitch < w { + continue; + } + for row in 0..h as usize { + std::ptr::write_bytes(plane.buffer.add(row * plane.buffer_pitch as usize), value, w as usize); + } + written += w as usize * h as usize; + } + } + written +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Mode { Off, @@ -90,8 +162,11 @@ static REAL_DO_FRAME_ASYNC: AtomicUsize = AtomicUsize::new(0); static REAL_DO_FRAME_ASYNC_MULTI: AtomicUsize = AtomicUsize::new(0); static REAL_DO_FRAME_ASYNC_WAIT: AtomicUsize = AtomicUsize::new(0); static REAL_GOTO: AtomicUsize = AtomicUsize::new(0); +static REAL_REGISTER_FRAME_BUFFERS: AtomicUsize = AtomicUsize::new(0); static LOGGED_HANDLES: Mutex>> = Mutex::new(None); +/// Movie handle → the `BINKFRAMEBUFFERS` the title registered for it. +static FRAME_BUFFERS: Mutex>> = Mutex::new(None); static SKIPPED_MOVIES: AtomicU64 = AtomicU64::new(0); /// If `XCL_SKIP_BINK` is enabled and `function` is a wrapped Bink 2 export, store `real_addr` @@ -152,6 +227,10 @@ fn wrap_with_mode(m: Mode, function: &str, real_addr: usize) -> usize { REAL_GOTO.store(real_addr, Ordering::Release); BinkGoto_hook as usize } + "BinkRegisterFrameBuffers" => { + REAL_REGISTER_FRAME_BUFFERS.store(real_addr, Ordering::Release); + BinkRegisterFrameBuffers_hook as usize + } _ => return real_addr, }; static BANNER: Once = Once::new(); @@ -206,6 +285,12 @@ pub unsafe fn fast_advance(bink: *mut BinkHeader, m: Mode) -> bool { dur_s, h.open_flags ); + if black_on() { + if let Some(fb) = frame_buffers_of(bink) { + let bytes = blacken(fb); + crate::xlog_info!("Bink: movie #{n}'s frame buffers painted black ({bytes} bytes; XCL_SKIP_BINK_BLACK=0 leaves them)"); + } + } } h.frame_num = h.frames; h.last_frame_num = h.frames; @@ -223,6 +308,31 @@ type DoFrameAsyncFn = unsafe extern "system" fn(*mut BinkHeader, u32, u32) -> i3 type DoFrameAsyncMultiFn = unsafe extern "system" fn(*mut BinkHeader, *const u32, i32) -> i32; type DoFrameAsyncWaitFn = unsafe extern "system" fn(*mut BinkHeader, i32) -> i32; type GotoFn = unsafe extern "system" fn(*mut BinkHeader, u32, u32); +type RegisterFrameBuffersFn = unsafe extern "system" fn(*mut BinkHeader, *mut BinkFrameBuffers); + +fn remember_frame_buffers(bink: *mut BinkHeader, fb: *mut BinkFrameBuffers) { + if !bink.is_null() && !fb.is_null() { + FRAME_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(bink as usize, fb as usize); + } +} + +fn frame_buffers_of(bink: *mut BinkHeader) -> Option<*mut BinkFrameBuffers> { + let g = FRAME_BUFFERS.lock().unwrap(); + g.as_ref()?.get(&(bink as usize)).map(|&fb| fb as *mut BinkFrameBuffers) +} + +unsafe extern "system" fn BinkRegisterFrameBuffers_hook(bink: *mut BinkHeader, fb: *mut BinkFrameBuffers) { + let real = REAL_REGISTER_FRAME_BUFFERS.load(Ordering::Acquire); + if real != 0 { + let f: RegisterFrameBuffersFn = std::mem::transmute(real); + f(bink, fb); + } + remember_frame_buffers(bink, fb); + // Black before the first advance too, in case the title draws the movie before it asks for a frame. + if black_on() && should_skip_handle(bink, mode()) { + blacken(fb); + } +} unsafe extern "system" fn BinkOpen_hook(name: *const u8, flags: u32) -> *mut BinkHeader { let real = REAL_OPEN.load(Ordering::Acquire); @@ -271,6 +381,9 @@ unsafe extern "system" fn BinkClose_hook(bink: *mut BinkHeader) { if let Some(set) = LOGGED_HANDLES.lock().unwrap().as_mut() { set.remove(&(bink as usize)); } + if let Some(map) = FRAME_BUFFERS.lock().unwrap().as_mut() { + map.remove(&(bink as usize)); + } } let real = REAL_CLOSE.load(Ordering::Acquire); if real != 0 { @@ -445,6 +558,74 @@ mod tests { } } + #[test] + fn frame_buffers_abi_matches_the_dll() { + assert_eq!(std::mem::size_of::(), 0x10); + assert_eq!(std::mem::offset_of!(BinkPlane, allocate), 0x08); + assert_eq!(std::mem::size_of::(), 0x50); + assert_eq!(std::mem::offset_of!(BinkFrameBuffers, frame_num), 0x14); + assert_eq!(std::mem::offset_of!(BinkFrameBuffers, frames), 0x18); + assert_eq!(std::mem::size_of::(), 0x18 + 0xf0); + } + + #[test] + fn a_skipped_movie_shows_black_not_the_memory_its_planes_held() { + let (w, h, cw, ch, pitch, cpitch) = (64u32, 8u32, 32u32, 4u32, 80usize, 48usize); + let mut planes: Vec> = (0..6).map(|k| vec![0xA5; if k % 3 == 0 { pitch * h as usize } else { cpitch * ch as usize }]).collect(); + let none = BinkPlane { buffer: std::ptr::null_mut(), allocate: 0, buffer_pitch: 0 }; + let mut fb = BinkFrameBuffers { + total_frames: 2, + ya_width: w, + ya_height: h, + crcb_width: cw, + crcb_height: ch, + frame_num: 0, + frames: [BinkFramePlaneSet { planes: [none; 5] }; 3], + }; + for set in 0..2 { + for k in 0..3 { + let p = &mut planes[set * 3 + k]; + fb.frames[set].planes[k] = BinkPlane { buffer: p.as_mut_ptr(), allocate: 1, buffer_pitch: if k == 0 { pitch as u32 } else { cpitch as u32 } }; + } + } + // (on the heap: a stack address may repeat one another test's thread already logged) + let movie: *mut BinkHeader = Box::into_raw(Box::new(BinkHeader { width: 60, height: 8, frames: 90, frame_rate: 30, frame_rate_div: 1, ..Default::default() })); + let looping: *mut BinkHeader = Box::into_raw(Box::new(BinkHeader { frames: 90, open_flags: BINK_WILL_LOOP, ..Default::default() })); + remember_frame_buffers(looping, &mut fb); + unsafe { + // A movie that plays keeps its planes. + assert!(!fast_advance(looping, Mode::NonLooping)); + } + assert!(planes.iter().all(|p| p.iter().all(|&b| b == 0xA5))); + + remember_frame_buffers(movie, &mut fb); + unsafe { + assert!(fast_advance(movie, Mode::NonLooping)); + } + for (i, p) in planes.iter().enumerate() { + let (width, rows, stride, black) = if i % 3 == 0 { (w as usize, h as usize, pitch, 16) } else { (cw as usize, ch as usize, cpitch, 128) }; + for r in 0..rows { + assert!(p[r * stride..r * stride + width].iter().all(|&b| b == black), "plane {i} row {r}"); + // the pitch's padding is not the plane's + assert!(p[r * stride + width..(r + 1) * stride].iter().all(|&b| b == 0xA5), "plane {i} row {r} padding"); + } + } + + // A struct that does not look like frame buffers is left alone. + for frames in [0, 7] { + fb.total_frames = frames; + unsafe { + assert_eq!(blacken(&mut fb), 0); + } + } + unsafe { + BinkClose_hook(movie); + BinkClose_hook(looping); + drop(Box::from_raw(movie)); + drop(Box::from_raw(looping)); + } + } + #[test] fn wrap_only_intercepts_known_exports_when_enabled() { let dummy = 0x1234_5678usize; diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index bbb56bdc3f..f6685252be 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -40,6 +40,13 @@ struct Backing { retire_when_free: bool, /// The driver Reset this backing while idle, and no recording has used it since. already_reset: bool, + /// Made here (`ResetWork::Create`), so ours to release. + made: bool, + /// List Resets on it in progress outside STATE (`reset_list`): neither Reset nor released then. + list_resets: usize, + /// Recordings since its last driver Reset, and the most one cycle had. + cycle: u32, + peak: u32, } #[derive(Default)] @@ -133,6 +140,7 @@ struct BackingProbe { release_owner: Option, retire_when_free: bool, already_reset: bool, + list_resets: usize, } impl BackingProbe { @@ -146,11 +154,12 @@ impl BackingProbe { release_owner: backing.release_owner.as_ref().map(|owner| owner.as_raw() as usize), retire_when_free: backing.retire_when_free, already_reset: backing.already_reset, + list_resets: backing.list_resets, } } unsafe fn free(&self) -> bool { - self.users.is_empty() && self.submit_pins == 0 && self.marks.iter().all(|(_, fence, value)| super::real::fence_completed(fence) >= *value) + self.users.is_empty() && self.submit_pins == 0 && self.list_resets == 0 && self.marks.iter().all(|(_, fence, value)| super::real::fence_completed(fence) >= *value) } unsafe fn in_flight(&self) -> bool { @@ -164,6 +173,7 @@ impl BackingProbe { && self.release_owner == backing.release_owner.as_ref().map(|owner| owner.as_raw() as usize) && self.retire_when_free == backing.retire_when_free && self.already_reset == backing.already_reset + && self.list_resets == backing.list_resets && self.marks.len() == backing.marks.len() && self.marks.iter().all(|(queue, fence, value)| { backing.marks.get(queue).is_some_and(|(current, current_value)| current.as_raw() == fence.as_raw() && current_value == value) @@ -914,6 +924,7 @@ fn move_list(s: &mut State, list: usize, backing: usize) { let backing = backing_mut(s, backing); backing.users.insert(list); backing.already_reset = false; + backing.cycle = backing.cycle.saturating_add(1); } /// Detach a recording that is no longer in the title list's submission graph. Its object @@ -957,16 +968,33 @@ pub(super) fn forget_list(list: usize) { /// Reset `list` on the title's allocator `alloc`, committing its new recording association /// only after native Reset succeeds. No pool lock is held across the driver call. pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) -> HRESULT) -> HRESULT { - let backing = current(alloc); + // (the backing is pinned across the driver call: a reclaim of the namespace meanwhile neither + // Resets nor releases it under the recording that starts) + let pinned = enabled() && alloc != 0; + let backing = if pinned { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + let b = s.cur.get(&alloc).copied().unwrap_or(alloc); + backing_mut(s, b).list_resets += 1; + b + } else { + current(alloc) + }; let hr = { let _in_reset = super::late_release::InListReset::enter(); reset(backing) }; - if hr < 0 || !enabled() || alloc == 0 { + if !pinned { return hr; } let mut g = STATE.lock().unwrap(); let s = g.get_or_insert_with(State::default); + if let Some(b) = s.backings.get_mut(&backing) { + b.list_resets -= 1; + } + if hr < 0 { + return hr; + } if ty >= 0 { s.types.insert(alloc, ty); } @@ -1170,6 +1198,21 @@ pub fn in_flight(list: usize) -> bool { || s.last_submit.get(&list).is_none_or(|current| !same_submit(current, &last)) } +/// Snapshot of every currently in-flight title-queue `(fence, value)` pair (`completed < value`). +/// Used by `vram_small` so freed sub-allocated blocks are never recycled while GPU work submitted +/// at release time is still running (even across multi-second pipeline-compile stalls that outlast `COOL`). +pub(super) fn pending_gpu_marks() -> Vec<(ID3D12Fence, u64)> { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return Vec::new() }; + s.fences + .values() + .filter_map(|q| { + let v = q.next_value.load(Ordering::Relaxed); + (v > 0 && unsafe { super::real::fence_completed(&q.fence) } < v).then(|| (q.fence.clone(), v)) + }) + .collect() +} + /// Compatibility helper for tests that submit directly instead of using `SubmissionGate`. #[cfg(test)] pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { @@ -1250,6 +1293,13 @@ unsafe fn forget_in(s: &mut State, alloc: usize, free: &HashSet) -> (Vec< (made, removed) } +/// Whether the native allocator `raw` is still held here after its title's final Release +/// (`forget`): lists hold a recording on it or the GPU has not passed its submits. What those +/// recordings use then goes at `console_list::allocator_reset`, when it retires. +pub(super) fn retained(raw: usize) -> bool { + STATE.lock().unwrap().as_ref().is_some_and(|s| s.backings.contains_key(&raw)) +} + pub unsafe fn forget(alloc: usize) { let (made, removed, free) = loop { let (mine, probes) = { @@ -1287,6 +1337,100 @@ pub unsafe fn forget(alloc: usize) { } } +/// Recordings in one cycle from which a PC allocator made here counts as heavy (`XCL_ALLOC_HEAVY`): +/// an idle heavy one is released rather than kept as a spare while more than `heavy_keep` are +/// alive. `XCL_ALLOC_RETIRE=0` keeps them all and lets the title's own allocator record past its +/// first Reset, as before. +/// +/// vkd3d-proton keeps every command buffer an allocator needed in one cycle (up to 256), each +/// with its IB (80 KiB and up) and upload buffer in host-visible VRAM, until the allocator goes. +/// GTA VI records 40–110 lists on one allocator in a world frame (4 while loading), and the +/// swaps here spread those frames over hundreds of PC allocators: each kept ~80 command buffers +/// of its one heavy frame, and video memory grew by ~1000 command buffers a minute. +fn heavy_cycle() -> u32 { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_ALLOC_HEAVY").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(16)) +} + +/// Heavy allocators made here that may stay alive (`XCL_ALLOC_HEAVY_KEEP`, 16): an idle heavy +/// spare is released only above this, so a swap can take one again (its command buffers are +/// there already) rather than make an allocator that grows them anew. +fn heavy_keep() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_ALLOC_HEAVY_KEEP").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(16)) +} + +fn is_bundle(s: &State, alloc: usize) -> bool { + s.types.get(&alloc) == Some(&D3D12_COMMAND_LIST_TYPE_BUNDLE.0) +} + +fn retire_heavy() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_ALLOC_RETIRE").is_ok_and(|v| v.trim() == "0")) +} + +static HEAVY_RELEASED: AtomicU64 = AtomicU64::new(0); + +/// Take out of `alloc`'s namespace the idle (`free`) aside backings made here that had a heavy +/// cycle; the caller releases them outside STATE (`release_heavy`). +fn retire_heavy_in(s: &mut State, alloc: usize, free: &HashSet) -> Vec<(usize, Backing)> { + if !retire_heavy() { + return Vec::new(); + } + #[cfg(test)] + if let Some((limit, keep)) = TEST_HEAVY.with(|t| t.get()) { + return retire_heavy_with(s, alloc, free, limit, keep); + } + retire_heavy_with(s, alloc, free, heavy_cycle(), heavy_keep()) +} + +#[cfg(test)] +thread_local! { + /// (heavy cycle, heavy kept) for the reclaims on this test's thread + static TEST_HEAVY: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +fn retire_heavy_with(s: &mut State, alloc: usize, free: &HashSet, limit: u32, keep: usize) -> Vec<(usize, Backing)> { + // (bundles: vkd3d-proton keeps no command buffers for them, they replay on the CPU) + if is_bundle(s, alloc) { + return Vec::new(); + } + let mut over = s.backings.values().filter(|b| b.made && b.peak.max(b.cycle) >= limit).count().saturating_sub(keep); + if over == 0 { + return Vec::new(); + } + let Some(aside) = s.aside.get_mut(&alloc) else { return Vec::new() }; + let mut out = Vec::new(); + aside.retain(|raw| { + let heavy = over > 0 + && *raw != alloc + && free.contains(raw) + && s.backings.get(raw).is_some_and(|b| b.made && b.release_owner.is_none() && !b.retire_when_free && b.peak.max(b.cycle) >= limit); + if heavy { + over -= 1; + out.push(*raw); + } + !heavy + }); + out.into_iter().filter_map(|raw| s.backings.remove(&raw).map(|b| (raw, b))).collect() +} + +unsafe fn release_heavy(heavy: Vec<(usize, Backing)>) { + for (raw, backing) in heavy { + drop(backing); + super::console_list::allocator_reset(raw as *mut c_void); + drop(ID3D12CommandAllocator::from_raw(raw as *mut c_void)); + let n = HEAVY_RELEASED.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + let (made, alive) = STATE.lock().unwrap().as_ref().map_or((0, 0), |s| (s.made, s.backings.values().filter(|b| b.made).count())); + crate::xlog_info!( + "D3D12.X: {n} PC allocators released after a cycle of >= {} recordings (their command buffers go with them); {made} made so far, {alive} alive", + heavy_cycle() + ); + } + } +} + /// Reset every idle aside backing once. The namespace token and backing probes make a driver /// callback, final Release, or newly recorded list invalidate the whole unlocked batch. unsafe fn reclaim_idle_aside(alloc: *mut c_void) { @@ -1304,6 +1448,12 @@ unsafe fn reclaim_idle_aside(alloc: *mut c_void) { let Some(s) = g.as_mut() else { return }; if !namespace_matches(s, a, &mine, &probes) { continue } if s.resetting.contains_key(&a) { return } + let heavy = retire_heavy_in(s, a, &free); + if !heavy.is_empty() { + drop(g); + release_heavy(heavy); + return; + } let mut work = Vec::new(); for raw in s.aside.get(&a).into_iter().flatten().copied() { let Some(probe) = probes.iter().find(|probe| probe.raw == raw && free.contains(&raw) && !probe.already_reset) else { continue }; @@ -1350,6 +1500,8 @@ fn commit_idle_resets( if let Some(backing) = s.backings.get_mut(&probe.raw) { retired.extend(backing.marks.drain().map(|(_, (fence, _))| fence)); backing.already_reset = true; + backing.peak = backing.peak.max(backing.cycle); + backing.cycle = 0; } } } @@ -1440,7 +1592,10 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { return Some(crate::util::E_FAIL); } let current = s.cur.get(&a).copied().unwrap_or(a); - if !s.backings.contains_key(¤t) || free.contains(¤t) { + // (the title's own allocator records only until its first Reset: the command buffers + // vkd3d-proton keeps of a heavy cycle there could never be given back, the title owns it) + let leave_title = current == a && retire_heavy() && s.backings.contains_key(&a) && s.types.contains_key(&a) && !is_bundle(s, a); + if (!s.backings.contains_key(¤t) || free.contains(¤t)) && !leave_title { if current == a { let retired = s.backings.get_mut(¤t) .map(|backing| backing.marks.drain().map(|(_, (fence, _))| fence).collect::>()) @@ -1458,7 +1613,21 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Reset { owner, swap: false, needed } }; } let Some(&ty) = s.types.get(&a) else { return Some(crate::util::E_FAIL) }; - if let Some(candidate) = s.aside.get(&a).and_then(|values| values.iter().copied().find(|raw| !s.backings.contains_key(raw) || free.contains(raw))) { + // (with `retire_heavy`: never the title's own allocator again, and a heavy spare first – its + // command buffers are there already, a light one would grow them anew) + let skip_own = retire_heavy() && !is_bundle(s, a); + let usable = |raw: &usize| !(skip_own && *raw == a) && (!s.backings.contains_key(raw) || free.contains(raw)); + let peak = |raw: &usize| if skip_own { s.backings.get(raw).map_or(0, |b| b.peak.max(b.cycle)) } else { 0 }; + let chosen = s.aside.get(&a).and_then(|values| { + let mut best: Option = None; + for raw in values.iter().copied().filter(usable) { + if best.is_none_or(|b| peak(&raw) > peak(&b)) { + best = Some(raw); + } + } + best + }); + if let Some(candidate) = chosen { let raw = candidate as *mut c_void; let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&raw).cloned() else { return Some(crate::util::E_FAIL) }; let token = reserve_reset(s, a).unwrap(); @@ -1563,6 +1732,8 @@ fn commit_reset( if let Some(backing) = s.backings.get_mut(&candidate) { retired.extend(backing.marks.drain().map(|(_, (fence, _))| fence)); backing.already_reset = true; + backing.peak = backing.peak.max(backing.cycle); + backing.cycle = 0; } if !swap { cancel_reset(s, alloc, token); @@ -1570,7 +1741,10 @@ fn commit_reset( } s.aside.entry(alloc).or_default().push(current); s.cur.insert(alloc, candidate); - if created { s.made += 1; } + if created { + s.made += 1; + backing_mut(s, candidate).made = true; + } s.swaps += 1; cancel_reset(s, alloc, token); if s.swaps.is_power_of_two() { @@ -1588,6 +1762,38 @@ fn commit_reset( mod tests { use super::*; + /// An idle PC allocator made here that took a heavy cycle leaves the namespace (to be released + /// with the command buffers vkd3d-proton keeps of that cycle); a light one, a busy one and one + /// the pool did not make stay. + #[test] + fn an_idle_allocator_made_here_after_a_heavy_cycle_is_released() { + let (alloc, heavy, light, busy, foreign) = (0x1000usize, 0x2000usize, 0x3000usize, 0x4000usize, 0x5000usize); + let mut s = State::default(); + s.aside.insert(alloc, vec![alloc, heavy, light, busy, foreign]); + for (raw, made, cycle) in [(alloc, false, 90), (heavy, true, 80), (light, true, 4), (busy, true, 80), (foreign, false, 80)] { + let b = backing_mut(&mut s, raw); + b.made = made; + b.cycle = cycle; + } + let limit = 16; + backing_mut(&mut s, light).peak = limit - 1; + let free: HashSet = [alloc, heavy, light, foreign].into_iter().collect(); + // (within the budget of heavy ones kept – heavy and busy – nothing goes) + assert!(retire_heavy_with(&mut s, alloc, &free, limit, 2).is_empty()); + let gone = retire_heavy_with(&mut s, alloc, &free, limit, 0); + assert_eq!(gone.iter().map(|(raw, _)| *raw).collect::>(), vec![heavy]); + assert_eq!(s.aside[&alloc], vec![alloc, light, busy, foreign]); + assert!(!s.backings.contains_key(&heavy) && s.backings.contains_key(&busy)); + // a heavy cycle seen at an earlier Reset counts too + backing_mut(&mut s, light).peak = limit; + let gone = retire_heavy_with(&mut s, alloc, &free, limit, 0); + assert_eq!(gone.iter().map(|(raw, _)| *raw).collect::>(), vec![light]); + // bundles keep no command buffers: nothing to release there + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_BUNDLE.0); + backing_mut(&mut s, busy).peak = limit; + assert!(retire_heavy_with(&mut s, alloc, &[busy].into_iter().collect(), limit, 0).is_empty()); + } + /// When a title list goes, the segments that recorded its put-off dispatches on its own /// allocator hold neither the PC allocator it stands for now nor the ones put aside: `forget` /// then releases those the GPU is done with (they were left behind, with what was held on them). @@ -2077,6 +2283,37 @@ mod tests { } } + /// The title's final Release of an allocator a list still records on (and may submit again), + /// or whose submits the GPU has not passed, leaves it `retained`: `alloc_release` must not let + /// its dispatch chains' scratch go then (it faulted the GPU). A free one is not retained. + #[test] + fn a_final_release_retains_a_busy_allocator_and_not_a_free_one() { + let (busy, list, pinned, free) = (0x7ffe_6a00usize, 0x7ffe_6a10usize, 0x7ffe_6b00usize, 0x7ffe_6c00usize); + { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.backings.insert(busy, Backing { users: HashSet::from([list]), ..Default::default() }); + s.of_list.insert(list, busy); + s.backings.insert(pinned, Backing { submit_pins: 1, ..Default::default() }); + s.backings.insert(free, Backing::default()); + } + unsafe { + forget(busy); + forget(pinned); + forget(free); + } + assert!(retained(busy), "a list still holds a recording on it"); + assert!(retained(pinned), "a submit of it has not reached the GPU"); + assert!(!retained(free), "nothing holds it: it retired, and its recordings went with it"); + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(s.backings[&busy].retire_when_free && s.backings[&pinned].retire_when_free); + // (synthetic raws have no COM reference to sweep) + s.backings.remove(&busy); + s.backings.remove(&pinned); + s.of_list.remove(&list); + } + #[test] fn absent_free_made_backing_is_scheduled_for_release_once() { let (alloc, made) = (0x7ffe_6300usize, 0x7ffe_6400usize); @@ -2709,9 +2946,91 @@ mod tests { } } + /// A PC allocator made here that took a heavy cycle (counted per list Reset on it) is released + /// by the namespace's reclaim once the list has moved on and the GPU passed its submits. + /// (Compute lists: no other test shares their spares, `take_shared_aside`.) + #[test] + fn a_heavy_allocator_made_here_is_released_once_idle() { + unsafe { + if !retire_heavy() { + return; + } + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + TEST_HEAVY.with(|t| t.set(Some((3, 0)))); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let a = alloc.as_raw(); + if !super::super::real::is_adopted(a) { + super::super::real::adopt(a, super::super::real::Kind::CommandAllocator); + } + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &alloc, None).unwrap(); + let l = list.as_raw() as usize; + created_on(l, a as usize, D3D12_COMMAND_LIST_TYPE_COMPUTE.0); + list.Close().unwrap(); + let lists = [Some(list.cast::().unwrap())]; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut value = 0; + let mut submit = || { + queue.ExecuteCommandLists(&lists); + executed(queue.as_raw(), &[l as *mut c_void]); + value += 1; + queue.Signal(&fence, value).unwrap(); + let start = std::time::Instant::now(); + while fence.GetCompletedValue() < value && start.elapsed().as_secs() < 10 { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(fence.GetCompletedValue() >= value, "the queue finishes"); + }; + let record = |times: usize| { + for _ in 0..times { + assert_eq!(reset_list(l, a as usize, D3D12_COMMAND_LIST_TYPE_COMPUTE.0, |pc| { + let pc_raw = pc as *mut c_void; + let pc_alloc = ID3D12CommandAllocator::from_raw_borrowed(&pc_raw).unwrap(); + list.Reset(pc_alloc, None).map_or_else(|e| e.code().0, |_| 0) + }), 0); + list.Close().unwrap(); + } + }; + submit(); + // the title's first Reset: a PC allocator made here takes the place of its own + alloc.Reset().unwrap(); + let heavy = current(a as usize); + assert_ne!(heavy, a as usize); + record(4); + assert_eq!(STATE.lock().unwrap().as_ref().unwrap().backings[&heavy].cycle, 4, "each list Reset counts"); + submit(); + // the list holds its recording there: the next Reset puts it aside + alloc.Reset().unwrap(); + let next = current(a as usize); + assert!(next != heavy && next != a as usize); + assert!(STATE.lock().unwrap().as_ref().unwrap().aside[&(a as usize)].contains(&heavy)); + // the list moves on and the GPU is done: the reclaim releases the heavy one + record(1); + submit(); + let before = HEAVY_RELEASED.load(Ordering::Relaxed); + reclaim_idle_aside(a); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert!(!s.backings.contains_key(&heavy), "released with its command buffers"); + assert!(!s.aside[&(a as usize)].contains(&heavy)); + } + assert!(HEAVY_RELEASED.load(Ordering::Relaxed) > before); + assert!(dev.GetDeviceRemovedReason().is_ok()); + TEST_HEAVY.with(|t| t.set(None)); + drop(lists); + drop(list); + drop(alloc); + assert_eq!(current(a as usize), a as usize, "a released allocator leaves nothing behind"); + } + } + /// A list recorded once and submitted again after the title reset its allocator: the - /// recording is still there (the device is not removed), the title's allocator goes on with - /// another PC allocator, and the first one is used again once the list has moved on. + /// recording is still there (the device is not removed), and the title's allocator goes on + /// with another PC allocator. Once the list has moved on, its own allocator is free again but + /// not recorded on (`retire_heavy`): a third PC allocator takes the place. #[test] fn a_recording_outlives_the_reset_of_the_titles_allocator() { unsafe { @@ -2764,17 +3083,29 @@ mod tests { executed(queue.as_raw(), &[l]); done(3); - // the next reset: the first PC allocator holds nothing now and is used again + // the next reset: the title's own allocator is free now, but it is not recorded on + // again (what vkd3d-proton keeps of a cycle there could not be given back) alloc.Reset().unwrap(); - assert_eq!(current(a as usize), a as usize, "the allocator put aside is free again"); + let third = current(a as usize); + if !retire_heavy() { + // (XCL_ALLOC_RETIRE=0: the title's own allocator is used again, as before) + assert_eq!(third, a as usize, "the allocator put aside is free again"); + drop(lists); + drop(list); + drop(alloc); + return; + } + assert!(third != a as usize && third != second, "a PC allocator made here takes the place"); assert!(dev.GetDeviceRemovedReason().is_ok()); // the title's allocator goes while another PC allocator stands for it: nothing of // it stays (the next allocator at its address is its own) + let third_alloc = ID3D12CommandAllocator::from_raw_borrowed(&(third as *mut c_void)).unwrap().clone(); assert_eq!(reset_list(l as usize, a as usize, D3D12_COMMAND_LIST_TYPE_DIRECT.0, |pc| { - assert_eq!(pc, a as usize); - list.Reset(&alloc, None).map_or_else(|e| e.code().0, |_| 0) + assert_eq!(pc, third); + list.Reset(&third_alloc, None).map_or_else(|e| e.code().0, |_| 0) }), 0); + drop(third_alloc); list.Close().unwrap(); alloc.Reset().unwrap(); assert_ne!(current(a as usize), a as usize); diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs new file mode 100644 index 0000000000..3d9c303f79 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -0,0 +1,3917 @@ +//! 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`, `XCL_AMBIENT_FRAME`, +//! `XCL_AMBIENT_KEEP`, `XCL_AMBIENT_MOST`, `XCL_AMBIENT_SKY`, `XCL_AMBIENT_SPACE`, `XCL_AMBIENT_SPLIT`, +//! `XCL_AMBIENT_REFLECT_HOLD`, `XCL_AMBIENT_ALPHA`, `XCL_AMBIENT_SPECULAR`, `XCL_AMBIENT_ONCE`, +//! `XCL_AMBIENT_MEAN_CLEAN`, `XCL_AMBIENT_DITHER`, `XCL_AMBIENT_SPECULAR_ALPHA`. +//! +//! That a stand-in can be put after the screen probes' resolve, and in which of its images, is +//! Belobug's find (beloooo's VIctory-Belobug-AMD, GPL-3.0-or-later), which puts a constant there, +//! shaded in creases from the scene's depth. +//! +//! The sky alone leaves a night scene black wherever no lamp reaches. So the fill is also raised +//! to an estimate taken from the frame itself: the light the visible surfaces send out, which the +//! title keeps for its own screen traces (`CS_CacheScreenSpaceRadiance`, the frame before), is +//! averaged in 64x36 cells right after that program, and every texel of the resolve's output gets +//! `XCL_AMBIENT_FRAME` (default 0.8; 0: off) of the cells around it, a fifth of it their slow +//! mean. +//! +//! Ported in part from Vice-Tay (https://github.com/TaynanGT/Vice-Tay, GPL-3.0-or-later; +//! THIRD_PARTY.md): the cells, their slow mean, and the estimate made in space (2026-11-28). +//! Ported in part from VIctory-Neo (https://github.com/KyleS98/VIctory-Neo, GPL-3.0-or-later): +//! the slots the reflections' resolves write, and their hold to the light around (its `hold`, +//! itself from Vice-Tay #99 and avatarmanz/VIctory-7900XTX #314), the bound of the +//! transparent surfaces' light (its `Role::Alpha`, `ALPHA`), and the bluer kind of the probes' +//! garbage dropped from what the resolve left (its `raise`) (2026-11-29). +//! +//! With the depth the resolve reads, the estimate is made in space rather than on the screen: +//! each cell is placed where it is seen (`LIGHT_PLACE_HLSL`), the cells' light is +//! gathered at 160x90 points by distance, as a mean and a direction for each colour +//! (`LIGHT_GATHER_HLSL`), and a texel takes the four points around it, those at its own depth +//! first, along a normal rebuilt from the depth, shaded where its surroundings close over it. So +//! a dark car cabin gets the light of the lit street beside it, and a face has a lit and a +//! shaded side. What the title's own resolve left is kept up to `XCL_AMBIENT_MOST` times the +//! estimate (2 unless given) when it is kept at all (`XCL_AMBIENT_KEEP`), the sky's level counts +//! for `XCL_AMBIENT_SKY` of itself (0.35 unless given), and the air's +//! scattered light (`XCL_AMBIENT_AIR`, 1.5 unless given, 0: off) is held to that multiple of the +//! light of the room and of the surface seen behind it. +//! +//! The reflections the title resolves (`CS_TemporalResolve2_Opaque`, `CS_TemporalResolve1_Alpha`) +//! are held to `XCL_AMBIENT_REFLECT` times the sky's level or the cells under them, and to +//! `XCL_AMBIENT_REFLECT_HOLD` times the light around besides (1.25 unless given, 0: off): the +//! estimate at the four gathered points about the texel, a fifth of it the slow mean (the cells +//! while no points are gathered), hue kept. Indoors the sky's level is far above the room's, and +//! eyes, glossy floors and glass glowed with it. +//! +//! Transparent surfaces and particles take their light from a volume before the eye that the +//! title's rays fill (`CS_SpatialFilterAlpha` writes it last): with rays that find nothing it holds +//! the sky's light everywhere, and the dust of a room shows as white specks. It is held as the +//! air's is, to `XCL_AMBIENT_ALPHA` times the light around (5 unless given, 0: off). +//! +//! Reflections are traced at half the picture's size: rays the screen-space march resolves take +//! the light seen on screen, the others find nothing and `CS_RayMiss` gives each the sky's light +//! from the sky's cube maps – indoors and at night far above the room's (a cutscene of VIctory-Neo: +//! 10 to 30 against 0.01 to 0.1), the wet look of skin, the sparkles in hair and on car paint. +//! Right after that program (opaque surfaces; transparent ones only with +//! `XCL_AMBIENT_SPECULAR_ALPHA=estimate`; water is left) each texel of its +//! image gets `XCL_AMBIENT_SPECULAR` (1 unless given, 0: off) of the light the gathered points +//! send along the reflected direction instead (`MISS_LIGHT_HLSL`); what the screen-space resolve +//! finds next is still written over it. Ported from VIctory-Neo +//! (https://github.com/KyleS98/VIctory-Neo, GPL-3.0-or-later; its `Role::Miss`, `reflect_light`, +//! `VICTORY_AMBIENT_SPECULAR`, 2026-11-29): the same estimate along the reflected direction, the +//! slots the program writes and reads, which surfaces it acts on. +//! +//! After Whiplash (Belobug's lineage, VIctory PR #63; its `crates/victory-gpu/src/ambient.rs`, +//! GPL-3.0-or-later; THIRD_PARTY.md), re-implemented on XCL's passes (2026-11-30): +//! * `XCL_AMBIENT_ONCE=1` (off unless set, `once`): one bounce of the title's own light, the +//! fill's own light taken out of what comes back to the cells. The fill's notes at the places +//! the keep reads, and the keep counting each place by them, are adapted from its +//! `VICTORY_AMBIENT_ONCE`; what is taken out (no more than the fill added) is XCL's. +//! * `XCL_AMBIENT_SPECULAR_ALPHA` (`title` unless set, `specular_alpha`): the transparent layer's +//! missed reflections are left as the title has them, as its `VICTORY_AMBIENT_SPECULAR_ALPHA`. +//! * `XCL_AMBIENT_MEAN_CLEAN` (on unless `0`, `mean_clean`): the probes' garbage is left out of +//! the cells, as its `VICTORY_AMBIENT_MEAN_CLEAN`, with XCL's test of it. +//! * `XCL_AMBIENT_DITHER` (`frame` unless set, `dither`): the shade's noise moves with the frame +//! (the usual animated interleaved-gradient noise), as its `VICTORY_AMBIENT_DITHER=frame`. + +use std::collections::{HashMap, HashSet}; +use std::ffi::c_void; +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, + frame: f32, + /// what the title's own resolve left counts for at most this many times the estimate + most: f32, + /// the share of the sky's level every texel gets whatever the frame's light + sky: f32, + /// the resolved reflections are held to this many times the light around (0: not held) + reflect_hold: f32, + /// the light of transparent surfaces and particles is held to this many times the light + /// around (0: as the title has it) + alpha: f32, + /// reflection rays that found nothing take this share of the light around along the + /// reflected direction instead of the sky's (0: the sky's, as the title has it) + specular: f32, +} + +impl Default for Config { + fn default() -> Self { + Self { + mode: Mode::Auto, + gain: 0.44, + power: 0.36, + least: 0.075, + ao: 0.55, + reflect: 0.50, + settle_ms: 250.0, + air: 1.5, + frame: 0.8, + most: 2.0, + sky: 0.35, + // VIctory-Neo's 1 of what the surfaces around send out: the estimate is 0.8 of it + // (`frame`) + reflect_hold: 1.25, + // VIctory-Neo's 4, as `reflect_hold` + alpha: 5.0, + // VIctory-Neo's `VICTORY_AMBIENT_SPECULAR=1`: all of the estimate + specular: 1.0, + } + } +} + +/// Fallback ambient level used before the first sky-dome capture completes. +const PRE_SKY_FALLBACK: f32 = 0.28; + +fn parse_mode(raw: Option<&str>) -> Mode { + match raw.map(|s| s.trim().to_ascii_lowercase()).as_deref() { + Some("0" | "off" | "none" | "false") => Mode::Off, + Some("sky" | "1" | "on" | "true") => Mode::Sky, + _ => Mode::Auto, + } +} + +fn env_f32(name: &str, default: f32, lo: f32, hi: f32) -> f32 { + parse_f32(std::env::var(name).ok().as_deref(), default, lo, hi) +} + +fn parse_f32(raw: Option<&str>, default: f32, lo: f32, hi: f32) -> f32 { + raw.and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()).map_or(default, |v| v.clamp(lo, hi)) +} + +fn config() -> &'static Config { + 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), + frame: env_f32("XCL_AMBIENT_FRAME", def.frame, 0.0, 4.0), + most: env_f32("XCL_AMBIENT_MOST", def.most, 1.0, 16.0), + sky: env_f32("XCL_AMBIENT_SKY", def.sky, 0.0, 1.0), + reflect_hold: env_f32("XCL_AMBIENT_REFLECT_HOLD", def.reflect_hold, 0.0, 16.0), + alpha: env_f32("XCL_AMBIENT_ALPHA", def.alpha, 0.0, 16.0), + specular: env_f32("XCL_AMBIENT_SPECULAR", def.specular, 0.0, 4.0), + } + }) +} + +/// Time-based EMA smoothing factor `1 - exp(-dt / tau)` for sky-dome ambient settling. +/// Snaps immediately (`1.0`) on the first captured sample or when `settle_ms <= 0`. +fn settle_alpha(dt_s: f32, settle_ms: f32, first_sample: bool) -> f32 { + if first_sample || settle_ms <= 0.0 { + return 1.0; + } + let dt = dt_s.clamp(0.0, 2.0); + let tau = (settle_ms * 1e-3).max(1e-4); + (1.0 - (-dt / tau).exp()).clamp(0.0, 1.0) +} + +fn monotonic_us() -> u64 { + static EPOCH: OnceLock = OnceLock::new(); + let base = EPOCH.get_or_init(Instant::now); + (base.elapsed().as_micros() as u64).saturating_add(1) +} + +/// Whether sky-following stand-in ambient tracking is enabled (`XCL_AMBIENT != 0/off`). +pub fn enabled() -> bool { + config().mode != Mode::Off +} + +/// Whether stand-in ambient passes should currently execute. +pub fn active() -> bool { + match config().mode { + Mode::Off => false, + Mode::Sky => true, + Mode::Auto => rays_find_nothing(real::bvh_traversal_allowed(), crate::gpu::dxil::kernel::rt_all_miss()), + } +} + +/// Whether the fill keeps what the title's own resolve stored where that is the larger +/// (`XCL_AMBIENT_KEEP=1` / `=0`). Unset: kept, unless programs that feed the resolve are left out +/// (`XCL_RT_LEAVE_OUT`) – then what it stores is made of memory nothing wrote this frame (on a +/// retail title: one colour all over, as bright as the fill's cap lets it be). +/// Whether the resolve's light is made in space, from the depth it reads (`XCL_AMBIENT_SPACE=0`: +/// on the screen, from the cells under each texel). +fn space_light() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_AMBIENT_SPACE").map_or(true, |v| v.trim() != "0")) +} + +/// `XCL_AMBIENT_SPLIT=1`: only the left half of the picture gets the light made in space (the +/// right half the one made on the screen), to compare the two in one frame. +fn split_screen() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_AMBIENT_SPLIT").is_ok_and(|v| v.trim() == "1")) +} + +fn keeps_title_light() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| keeps(std::env::var("XCL_AMBIENT_KEEP").ok().as_deref(), crate::gpu::rt_leave_out::enabled())) +} + +fn keeps(switch: Option<&str>, programs_left_out: bool) -> bool { + match switch.map(str::trim) { + Some("1") => true, + Some("0") => false, + _ => !programs_left_out, + } +} + +/// The title's rays bring no light: traversal is held back, or runs with every ray missing. +fn rays_find_nothing(traversal_allowed: bool, every_ray_misses: bool) -> bool { + !traversal_allowed || every_ray_misses +} + +/// An on/off switch: `1` / `on` / `true` or `0` / `off` / `false`; anything else (or unset): `default`. +fn switch_on(raw: Option<&str>, default: bool) -> bool { + match raw.map(|s| s.trim().to_ascii_lowercase()).as_deref() { + Some("1" | "on" | "true") => true, + Some("0" | "off" | "false") => false, + _ => default, + } +} + +/// `XCL_AMBIENT_ONCE=1`: the estimate is one bounce of the title's own light, not of the +/// stand-in's too. The cells are kept from the light surfaces sent out the frame before, which the +/// fill had raised: its own light comes back to it, and with `XCL_AMBIENT_FRAME` 0.8 and walls that +/// send out 0.6 of what they get it settles at 1 / (1 - 0.8 x 0.6) = 1.9 times one bounce (3.6 +/// times at 0.9, and no bound once the level times what walls send out reaches 1). With it the +/// fill notes, at the 25 places of each cell the keep reads, the luminance of the title's own +/// light it left there and of all it wrote, and the keep takes the fill's part out of what that +/// surface sent back: what the fill added times what the surface sends out of the light it got, +/// at most all of it (a surface sends out no more than it gets, so where a lamp or the sun lights +/// it too the rest is kept). Off unless set: where the stand-in is a room's main light the room +/// gets about half as much. +fn once() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| switch_on(std::env::var("XCL_AMBIENT_ONCE").ok().as_deref(), false)) +} + +/// `XCL_AMBIENT_MEAN_CLEAN`: the probes' garbage (magenta, and the bluer kind: what the fill drops +/// of the resolve's light) is counted as no light in the cells, still one of a cell's 25 places, +/// so neither the cells nor their slow mean take its hue. A few such texels in a dark room made its +/// mean violet. On unless `0`; a magenta or deep blue lamp counts as garbage too. +fn mean_clean() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| switch_on(std::env::var("XCL_AMBIENT_MEAN_CLEAN").ok().as_deref(), true)) +} + +/// `XCL_AMBIENT_DITHER`: `frame` (or on, the default) moves the interleaved-gradient noise that +/// turns the fill's shade samples (and picks its four points) by 5.588238 texels a frame over 64 +/// frames, so the title's temporal filter averages it out; `still` (or off) leaves it where it is +/// on screen, the pattern seen as dotted diagonal lines. +fn dither() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| dither_moves(std::env::var("XCL_AMBIENT_DITHER").ok().as_deref())) +} + +fn dither_moves(raw: Option<&str>) -> bool { + match raw.map(|s| s.trim().to_ascii_lowercase()).as_deref() { + Some("frame") => true, + Some("still") => false, + other => switch_on(other, true), + } +} + +/// The dither's place for the frame `frame` shown: it moves a step a frame and comes back after 64. +fn dither_phase(frame: u64, moves: bool) -> u32 { + if moves { (frame % 64) as u32 } else { 0 } +} + +/// `XCL_AMBIENT_SPECULAR_ALPHA`: `estimate` (or on) gives the transparent layer's missed +/// reflections the estimate as the opaque one's; `title` (or off, the default) leaves them as the +/// title has them. Its depth there is of the opaque surface behind the glass, or the bottom under +/// the foam on water, and the estimate taken along it left dark patches; what the title gives +/// (the sky's light) is bounded after the transparent reflections' resolve, at +/// `XCL_AMBIENT_REFLECT_HOLD` times the light around. +fn specular_alpha() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| transparent_misses_estimated(std::env::var("XCL_AMBIENT_SPECULAR_ALPHA").ok().as_deref())) +} + +fn transparent_misses_estimated(raw: Option<&str>) -> bool { + match raw.map(|s| s.trim().to_ascii_lowercase()).as_deref() { + Some("estimate") => true, + Some("title") => false, + other => switch_on(other, false), + } +} + +/// Whether a `CS_RayMiss` dispatch whose rays are of `layer` is given the estimate: the opaque +/// layer's always, the transparent one's with `transparent_too`, any other never. +fn miss_gets_estimate(layer: u32, transparent_too: bool) -> bool { + let [opaque, transparent] = MISS_LAYERS; + layer == opaque || layer == transparent && transparent_too +} + +/// Role of a console shader identified from FSSM/container metadata. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum PassRole { + SkyDome, + TemporalResolve, + ReflectionHistory, + /// `CS_TemporalResolve2_Opaque` / `CS_TemporalResolve1_Alpha` (R9G9B9E5 packed in R32_UINT) + ReflectionResolve, + InscatteringVolume, + /// keeps the light visible surfaces send out (`CS_CacheScreenSpaceRadiance`) + Radiance, + /// filters the light of transparent surfaces and particles, a 3D volume before the eye + /// (`CS_SpatialFilterAlpha`, the last program that writes it) + AlphaLight, + /// gives the reflection rays that found nothing the sky's light (`CS_RayMiss`, not + /// `CS_RayMiss_Volumetrics` nor the screen probes' `CS_ScreenProbe_RayMiss`) + RayMiss, +} + +/// Where the reflections' resolves write them: root parameter and dword of its table, the first +/// of these that holds a 2D image of their format (R32_UINT holding R9G9B9E5; the opaque +/// surfaces' resolve has it at the first, the transparent ones' at the second). From VIctory-Neo +/// (`REFLECTIONS`, 3aca295). +const REFLECTION_SLOTS: [(usize, usize); 2] = [(1, 128), (1, 136)]; + +/// Where `CS_SpatialFilterAlpha` writes the light of transparent surfaces (a volume of +/// R11G11B10_FLOAT; its direction goes to dword 16), as `REFLECTION_SLOTS`. From VIctory-Neo +/// (`ALPHA`, a6e85c6). +const ALPHA_SLOT: (usize, usize) = (1, 24); + +/// Where `CS_RayMiss` writes the reflected light (R11G11B10_FLOAT, half the picture's size) and +/// where it reads the depth (32-bit, the picture's size), as `REFLECTION_SLOTS`. From VIctory-Neo +/// (`MISS_LIGHT`, `MISS_DEPTH`). +const MISS_LIGHT_SLOT: (usize, usize) = (1, 104); +const MISS_DEPTH_SLOT: (usize, usize) = (0, 1000); +/// Which surfaces a `CS_RayMiss` dispatch's rays are of (its first root constant): the opaque ones +/// and the transparent ones can be given the estimate (the transparent ones with +/// `XCL_AMBIENT_SPECULAR_ALPHA=estimate`, `miss_gets_estimate`); water's (the depth there is of +/// what lies under it) and any other are left as the title has them. From VIctory-Neo +/// (`MISS_OPAQUE`, `MISS_ALPHA`). +const MISS_LAYERS: [u32; 2] = [0, 1]; + +/// `CS_RayMiss_` and the eight hex digits of a variant's hash, then `_`: not `CS_RayMiss_Volumetrics` +/// nor `CS_ScreenProbe_RayMiss` (VIctory-Neo's `is_miss`). +fn is_ray_miss(blob: &[u8]) -> bool { + const NAME: &[u8] = b"CS_RayMiss_"; + blob.windows(NAME.len() + 9).any(|w| w.starts_with(NAME) && w[NAME.len()..NAME.len() + 8].iter().all(u8::is_ascii_hexdigit) && w[NAME.len() + 8] == b'_') +} + +fn contains_ascii_ci(haystack: &[u8], needle: &[u8]) -> bool { + if needle.is_empty() || haystack.len() < needle.len() { + return false; + } + 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_TemporalResolve2_Opaque") + || contains_ascii_ci(blob, b"CS_TemporalResolve1_Alpha") + { + Some(PassRole::ReflectionResolve) + } else if contains_ascii_ci(blob, b"CS_UpdateHistory") { + Some(PassRole::ReflectionHistory) + } else if contains_ascii_ci(blob, b"CS_AccumulateLocalLightInscatteringVolume") { + Some(PassRole::InscatteringVolume) + } else if contains_ascii_ci(blob, b"CS_CacheScreenSpaceRadiance") { + Some(PassRole::Radiance) + } else if contains_ascii_ci(blob, b"CS_SpatialFilterAlpha") { + Some(PassRole::AlphaLight) + } else if is_ray_miss(blob) { + Some(PassRole::RayMiss) + } 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() +} + +/// roles by the console record (`fnv64` of the CS), for pipelines whose pointer was never noted +static RECORD_ROLES: RwLock>> = RwLock::new(None); + +pub(super) fn note_compute_pso(pso: usize, cs: &[u8]) { + if pso == 0 || !enabled() { + return; + } + if let Some(role) = classify_cs(cs) { + RECORD_ROLES.write().unwrap().get_or_insert_with(HashMap::new).insert(crate::gpu::shader::fnv64(cs), role); + PSO_ROLES.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, role); + HAS_CS_PSO.store(true, Ordering::Release); + static LOGGED: AtomicU64 = AtomicU64::new(0); + if LOGGED.fetch_add(1, Ordering::Relaxed) < 64 { + crate::xlog_info!("D3D12.X: ambient: tracked {role:?} compute PSO {pso:#x} (record {:016x})", crate::gpu::shader::fnv64(cs)); + } + } +} + +#[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() +} + +/// (local, `XCL_AMBIENT_DIAG`) a dispatch of one of the stand-in's passes reached `path`: logged +/// before any of the hook's conditions, to see which path the passes take +pub(super) fn diag_path(path: &str, resolved: usize, bound: usize, count_buf: usize, max: u32) { + static DIAG: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*DIAG.get_or_init(|| std::env::var_os("XCL_AMBIENT_DIAG").is_some()) { + return; + } + let by_record = |r: u64| RECORD_ROLES.read().unwrap().as_ref()?.get(&r).copied(); + let role = role_of(resolved).or(role_of(bound)).or_else(|| super::real::pso_record(resolved).and_then(by_record)).or_else(|| super::pso_async::record_of(bound).and_then(by_record)); + let Some(role) = role else { return }; + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed) + 1; + if k <= 32 || k.is_power_of_two() { + crate::xlog_info!("D3D12.X: ambient path #{k}: {role:?} via {path} (resolved {resolved:#x}, bound {bound:#x}, count buffer {count_buf:#x}, max {max})"); + } +} + +/// The pipeline a hook should look the role up by: `resolved` (the PC pipeline the work +/// runs with) when its role was noted, else `bound` (the title's pipeline). With lazy and +/// background builds the two differ, and roles were noted for one or the other: looking up only +/// the resolved one found no role at all, so the stand-in never ran. +pub(super) fn role_pso(resolved: usize, bound: usize) -> usize { + static DIAG: std::sync::OnceLock = std::sync::OnceLock::new(); + if *DIAG.get_or_init(|| std::env::var_os("XCL_AMBIENT_DIAG").is_some()) { + static CALLS: AtomicU64 = AtomicU64::new(0); + let k = CALLS.fetch_add(1, Ordering::Relaxed) + 1; + if k <= 40 || k.is_power_of_two() { + let roles = PSO_ROLES.read().unwrap().as_ref().map_or(0, |m| m.len()); + crate::xlog_info!("D3D12.X: ambient diag #{k}: resolved {resolved:#x} role {:?} record {:x?}, bound {bound:#x} role {:?}, {roles} roles noted, active {}", role_of(resolved), super::real::pso_record(resolved), role_of(bound), active()); + } + } + if role_of(resolved).is_none() && role_of(bound).is_none() { + // neither pointer was noted: the console record of the resolved pipeline names it + let by_record = |r: u64| RECORD_ROLES.read().unwrap().as_ref()?.get(&r).copied().map(|role| (r, role)); + let role = super::real::pso_record(resolved).and_then(by_record).or_else(|| super::pso_async::record_of(bound).and_then(by_record)); + if let Some((record, role)) = role { + PSO_ROLES.write().unwrap().get_or_insert_with(HashMap::new).insert(resolved, role); + static L: AtomicU64 = AtomicU64::new(0); + if L.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_info!("D3D12.X: ambient: {role:?} found by record {record:016x} for pipeline {resolved:#x}"); + } + } + return resolved; + } + if role_of(resolved).is_some() { + return resolved; + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!("D3D12.X: ambient: role found by the bound pipeline {bound:#x}, not the resolved {resolved:#x}"); + } + bound +} + +/// Descriptor-heap view metadata indexed by BOTH console slot UMA address (`slot.at`, globally +/// unique across all shader-visible and CPU-only heaps) and `GLOBAL` heap descriptor index +/// (`slot.index` when hosted in `GLOBAL`) so both `CopyDescriptors*` and inline title `memcpy` +/// 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 matches!(role, PassRole::TemporalResolve | PassRole::ReflectionResolve) && view_fmt != 42 { + return None; + } + if role == PassRole::ReflectionHistory && view_fmt == 42 { + return None; + } + // (the light of visible surfaces is R11G11B10_FLOAT) + if role == PassRole::Radiance && view_fmt != 26 { + return None; + } + score_dispatch_target(rd, view_fmt, groups) +} + +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, + place_pso: ID3D12PipelineState, + gather_pso: ID3D12PipelineState, + reflect_pso: ID3D12PipelineState, + reflect_r9_pso: ID3D12PipelineState, + air_pso: ID3D12PipelineState, + keep_pso: ID3D12PipelineState, + mean_pso: ID3D12PipelineState, + miss_pso: ID3D12PipelineState, + sky_copy: ID3D12Resource, + sky_level: ID3D12Resource, + dummy_depth: ID3D12Resource, + dummy_indirect: ID3D12Resource, + heap: ID3D12DescriptorHeap, + heap_cpu: u64, + heap_gpu: u64, + inc: u32, + next_group: AtomicU32, + sky_ready: AtomicBool, + last_sky_us: AtomicU64, + last_keep_us: AtomicU64, +} + +unsafe impl Send for AmbientDevice {} +unsafe impl Sync for AmbientDevice {} + +static DEVICES: Mutex>>>> = Mutex::new(None); + +/// A helper program: DXC first (`cs_6_0`), then `D3DCompile`. Under Wine `D3DCompile` is +/// vkd3d-shader's HLSL compiler, which refuses some of these programs; a refused one left +/// `get_device` without a device and every pass of the stand-in returned without a word. +fn compile_cs_sm5(src: &str) -> Option> { + match crate::gpu::recomp::dxc::compile(src, "main", "cs_6_0", &[]) { + Ok(dxil) => return Some(dxil), + Err(e) => { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ambient: a helper program does not compile with DXC ({e}); trying D3DCompile"); + } + } + } + let fxc = compile_cs_fxc(src); + if fxc.is_none() { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ambient: a helper program compiles with neither DXC nor D3DCompile: no stand-in lighting"); + } + } + fxc +} + +fn compile_cs_fxc(src: &str) -> Option> { + unsafe { + let mut blob = None; + let r = D3DCompile( + 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); + } +} +"#; + +/// The cells the frame's light is kept in, the points it is gathered at, and the float4s of the +/// level buffer: the sky's level, the cells' slow mean, the cells, where each cell is seen +/// (`LIGHT_PLACE_HLSL`), and three for each point – red, green and blue, a direction and a mean +/// (`LIGHT_GATHER_HLSL`). +const FRAME_CELLS: (u32, u32) = (64, 36); +const GATHER_POINTS: (u32, u32) = (160, 90); +const LEVEL_ELEMENTS: u32 = 2 + 2 * FRAME_CELLS.0 * FRAME_CELLS.1 + 3 * GATHER_POINTS.0 * GATHER_POINTS.1; +/// After those, `XCL_AMBIENT_ONCE`'s notes: a float4 for each of the 25 places of each cell the +/// keep reads – the luminance of the title's own light the fill left there and of all it wrote +/// (zero: nothing noted, nothing taken out). The level buffer holds them whether the switch is on +/// or not (0.9 MB). +const ONCE_AT: u32 = LEVEL_ELEMENTS; +const LEVEL_BUFFER_ELEMENTS: u32 = ONCE_AT + 25 * FRAME_CELLS.0 * FRAME_CELLS.1; +/// A change of the cells' mean by more than this factor is taken at once (a cut, a new room). +const FRAME_JUMP: f32 = 3.0; + +/// The fill's seventh constant: bit 0 a sky was captured, bit 1 the title's own light is kept +/// (`XCL_AMBIENT_KEEP`), bit 2 the light is noted at the keep's places (`XCL_AMBIENT_ONCE`), bits 8 +/// to 13 the frame's place in the dither's round (`XCL_AMBIENT_DITHER`; 0: the still pattern). +fn fill_bits(sky_ready: bool, keeps: bool, once: bool, phase: u32) -> u32 { + sky_ready as u32 | (keeps as u32) << 1 | (once as u32) << 2 | (phase & 63) << 8 +} + +/// The keep's third constant: bit 0 the fill's own light is taken out (`XCL_AMBIENT_ONCE`), bit 1 +/// the probes' garbage is left out (`XCL_AMBIENT_MEAN_CLEAN`). +fn keep_bits(once: bool, clean: bool) -> u32 { + once as u32 | (clean as u32) << 1 +} + +/// The light visible surfaces send out (`out_uav`, read only), averaged into the 64x36 cells of +/// the level buffer, `share` of it. Lamps and glints count, but not for everything. `flags` +/// (`keep_bits`): without the probes' garbage (`XCL_AMBIENT_MEAN_CLEAN`), and without the fill's +/// own light as each place sent it back (`XCL_AMBIENT_ONCE`, the fill's notes from `ONCE_AT` on). +const FRAME_KEEP_HLSL: &str = r#" +Texture2D _unused : register(t0); +RWTexture2D out_uav : register(u0); +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint width; + uint height; + uint flags; + uint _u3; + uint _u4; + float share; + float _p6; + float _p7; +}; +#define ONCE_AT 47810 +[numthreads(8, 8, 1)] +void main(uint3 at : SV_DispatchThreadID) { + if (at.x >= 64 || at.y >= 36 || width == 0 || height == 0) return; + float3 sum = float3(0.0, 0.0, 0.0); + [loop] + for (uint y = 0; y < 5; ++y) { + [loop] + for (uint x = 0; x < 5; ++x) { + float2 at_texel = (float2(at.xy) + (float2(x, y) + 0.5) / 5.0) * float2(width, height) / float2(64.0, 36.0); + uint2 p = min(uint2(at_texel), uint2(width - 1, height - 1)); + float3 c = out_uav[p].rgb; + c = all(isfinite(c)) ? max(c, 0.0) : float3(0.0, 0.0, 0.0); + // (bit 1) The probes' garbage, as the fill drops it from the resolve's light: no + // light, still one of the 25. + if ((flags & 2u) != 0u && ((c.g < 0.5 * min(c.r, c.b) && max(c.r, c.b) > 0.02) || (c.b > 2.5 * c.g && c.b > c.r && c.b > 0.02))) { + c = float3(0.0, 0.0, 0.0); + } + // (bit 0) Less the fill's own light as this place sent it back: what the fill added + // here (its note: the luminance of the title's light it left, of all it wrote) times + // what the place sends out of the light it got, at most all of what it added. + if ((flags & 1u) != 0u) { + float4 noted = sky_level[ONCE_AT + (at.y * 64 + at.x) * 25 + y * 5 + x]; + float added = max(noted.y - noted.x, 0.0); + float sent = dot(c, float3(0.2126, 0.7152, 0.0722)); + c *= saturate(1.0 - added / max(max(noted.y, sent), 1e-6)); + } + sum += c / max(1.0, dot(c, float3(0.2126, 0.7152, 0.0722)) / 20.0); + } + } + sky_level[2 + at.y * 64 + at.x] = float4(sum * (share / 25.0), 1.0); +} +"#; + +/// The slow mean of the cells: `follow` of the way to this frame's mean, all of it when the mean +/// changed by more than `jump` either way. +const FRAME_MEAN_HLSL: &str = r#" +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint _u0; + uint _u1; + uint _u2; + uint _u3; + uint _u4; + float follow; + float jump; + float _p7; +}; +[numthreads(1, 1, 1)] +void main() { + float3 sum = float3(0.0, 0.0, 0.0); + [loop] + for (uint i = 0; i < 2304; ++i) { + float3 c = sky_level[2 + i].rgb; + sum += all(isfinite(c)) ? c : float3(0.0, 0.0, 0.0); + } + float3 now = sum / 2304.0; + float4 was = sky_level[1]; + bool kept = was.a > 0.0 && all(isfinite(was.rgb)); + float a = max(dot(now, float3(0.2126, 0.7152, 0.0722)), 1e-5); + float b = max(dot(was.rgb, float3(0.2126, 0.7152, 0.0722)), 1e-5); + bool jumped = jump > 0.0 && max(a / b, b / a) > jump; + sky_level[1] = float4(kept ? lerp(was.rgb, now, jumped ? 1.0 : saturate(follow)) : now, 1.0); +} +"#; + +/// Screen-space radiance floor + 8-tap IGN-rotated golden-angle horizon crease AO + outlier +/// probe tile suppression (requires typed UAV load on `out_uav`). +const AMBIENT_FILL_HLSL: &str = r#" +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; +}; +// The light the frame before sent out around this texel: 64x36 cells from `sky_level[2]` on, +// their slow mean at `sky_level[1]` (its fourth part 0: nothing kept yet, no light). +float3 frame_light(uint2 tid) { + float4 mean = sky_level[1]; + if (!(mean.a > 0.0)) { + return float3(0.0, 0.0, 0.0); + } + float2 g = (float2(tid) + 0.5) / float2(max(width, 1u), max(height, 1u)) * float2(64.0, 36.0) - 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float3 sum = float3(0.0, 0.0, 0.0); + [unroll] + for (int k = 0; k < 4; ++k) { + int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(63, 35)); + float wx = (k & 1) ? f.x : 1.0 - f.x; + float wy = (k >> 1) ? f.y : 1.0 - f.y; + sum += wx * wy * sky_level[2 + q.y * 64 + q.x].rgb; + } + float3 found = lerp(sum, mean.rgb, 0.2); + return all(isfinite(found)) ? clamp(found, 0.0, 16.0) : float3(0.0, 0.0, 0.0); +} +float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { + float d0 = depth_tex.Load(int3(dc, 0)); + if (!isfinite(d0) || d0 <= 1e-5 || d0 >= 0.99999) { + return 1.0; + } + // (moved by 5.588238 texels for each frame of the dither's round: bits 8 to 13 of sky_ready) + float ign = frac(52.9829189 * frac(dot(float2(tid) + 5.588238 * float((sky_ready >> 8) & 63u), float2(0.06711056, 0.00583715)))); + float base_ang = ign * 6.2831853; + float max_rad = clamp(float(depth_w) * 0.012, 4.0, 16.0); + float inv_d0 = 1.0 / max(d0, 1e-5); + 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 & 1u) != 0u) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); + amb = max(amb, frame_light(tid.xy)); + float ao = 1.0; + if (has_depth != 0 && depth_w > 0 && depth_h > 0) { + int2 dc = int2( + int(min((tid.x * depth_w) / max(width, 1u), depth_w - 1)), + int(min((tid.y * depth_h) / max(height, 1u), depth_h - 1)) + ); + int2 maxc = int2(int(depth_w) - 1, int(depth_h) - 1); + ao = horizon_crease_ao(tid.xy, dc, maxc); + } + float3 amb_ao = amb * ao; + float amb_lum = max(dot(amb, float3(0.2126, 0.7152, 0.0722)), 0.02); + float cap_lum = 4.0 * amb_lum; + float4 cur = out_uav[tid.xy]; + float3 existing = all(isfinite(cur.rgb)) ? max(cur.rgb, 0.0) : float3(0.0, 0.0, 0.0); + if ((sky_ready & 2u) == 0u) { + existing = float3(0.0, 0.0, 0.0); + } + if (existing.g < 0.5 * min(existing.r, existing.b) && max(existing.r, existing.b) > 0.02) { + existing = float3(0.0, 0.0, 0.0); + } + float 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); +} +"#; + +/// What the place, gather and raise programs share (`light_hlsl`): the level buffer's layout and +/// the point seen at a texel, from the depth the resolve reads (the title's depth is near / z +/// with near 0.1 m, its view 0.45 high at 1 m). +const LIGHT_COMMON_HLSL: &str = r#" +Texture2D depth_tex : register(t0); +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; +}; +#define CX 64 +#define CY 36 +#define CELLS 2304 +#define PX 160 +#define PY 90 +#define CELL_AT 2 +#define PLACE_AT 2306 +#define POINT_AT 4610 +#define ONCE_AT 47810 +static const float3 LUMA = float3(0.2126, 0.7152, 0.0722); +// The point seen at a texel of the width x height picture, in metres from the eye (x right, y up, +// z away). +float3 seen(int2 p, float2 size) { + int2 q = clamp(int2((float2(p) + 0.5) * float2(depth_w, depth_h) / size), int2(0, 0), int2(depth_w, depth_h) - 1); + float d = depth_tex.Load(int3(q, 0)); + float z = min(0.1 / max(d, 1e-7), 1000.0); + float2 ndc = (float2(p) + 0.5) / size * 2.0 - 1.0; + return float3(ndc.x * 0.45 * size.x / size.y * z, -ndc.y * 0.45 * z, z); +} +"#; + +/// A light program's source: the switches' values (`XCL_AMBIENT_MOST`, `XCL_AMBIENT_SKY`), what +/// the programs share, and `body`. +fn light_hlsl(body: &str) -> String { + let cfg = config(); + format!("#define MOST {:.6}\n#define SKY_SHARE {:.6}\n{LIGHT_COMMON_HLSL}{body}", cfg.most, cfg.sky) +} + +/// Where each of the 64x36 cells is seen, and its distance squared. +const LIGHT_PLACE_HLSL: &str = r#" +[numthreads(8, 4, 1)] +void main(uint3 at : SV_DispatchThreadID) { + if (at.x >= CX || at.y >= CY) return; + float2 size = float2(width, height); + float3 p = seen(int2((float2(at.xy) + 0.5) * size / float2(CX, CY)), size); + sky_level[PLACE_AT + at.y * CX + at.x] = float4(p, p.z * p.z); +} +"#; + +/// The cells' light as it reaches each of 160x90 points: every cell by its distance, a mean and +/// a direction for each colour. +const LIGHT_GATHER_HLSL: &str = r#" +[numthreads(8, 2, 1)] +void main(uint3 at : SV_DispatchThreadID) { + if (at.x >= PX || at.y >= PY) return; + float2 size = float2(width, height); + float3 p = seen(int2((float2(at.xy) + 0.5) * size / float2(PX, PY)), size); + float r2 = 0.25 + 0.0025 * p.z * p.z; + float whole = 0.0; + float3 toward = float3(0.0, 0.0, 0.0), light = float3(0.0, 0.0, 0.0); + float3 red = float3(0.0, 0.0, 0.0), green = float3(0.0, 0.0, 0.0), blue = float3(0.0, 0.0, 0.0); + [loop] + for (uint i = 0; i < CELLS; ++i) { + float4 c = sky_level[PLACE_AT + i]; + float3 L = sky_level[CELL_AT + i].rgb; + L = all(isfinite(L)) ? max(L, 0.0) : float3(0.0, 0.0, 0.0); + float3 d = c.xyz - p; + float dd = dot(d, d); + float w = c.w / (dd + r2); + float3 dir = d / sqrt(dd + 0.25 * r2); + whole += w; + toward += w * dir; + light += w * L; + red += w * L.r * dir; + green += w * L.g * dir; + blue += w * L.b * dir; + } + whole = max(whole, 1e-6); + light /= whole; + toward /= whole; + uint at0 = POINT_AT + (at.y * PX + at.x) * 3; + sky_level[at0] = float4(red / whole - light.r * toward, light.r); + sky_level[at0 + 1] = float4(green / whole - light.g * toward, light.g); + sky_level[at0 + 2] = float4(blue / whole - light.b * toward, light.b); +} +"#; + +/// The reflected light of a texel of `CS_RayMiss`'s image (R11G11B10_FLOAT, `width` x `height`, +/// half the picture's size), after `light_hlsl`: the light the four gathered points about it send +/// along the reflected direction (the normal rebuilt from the depth of the `depth_w` x `depth_h` +/// picture, as the diffuse fill takes it along the normal), `ao_strength` of it (the share, +/// `XCL_AMBIENT_SPECULAR` over `XCL_AMBIENT_FRAME`: the cells hold the frame's share of the light +/// surfaces send out). Where the picture shows the sky nothing is reflected (left as it was), and +/// before any frame's light is kept the image is left as the title has it. Ported from +/// VIctory-Neo's `reflect_light` (see the module's note). +const MISS_LIGHT_HLSL: &str = r#" +RWTexture2D out_uav : register(u0); +[numthreads(8, 8, 1)] +void main(uint3 at : SV_DispatchThreadID) { + if (at.x >= width || at.y >= height || depth_w == 0u || depth_h == 0u) return; + float4 mean = sky_level[1]; + if (!(mean.a > 0.0) || !all(isfinite(mean.rgb))) return; + float2 size = float2(depth_w, depth_h); + int2 p = int2((float2(at.xy) + 0.5) * size / float2(width, height)); + float3 c = seen(p, size); + if (c.z >= 999.0) return; + float3 l = seen(p + int2(-1, 0), size), r = seen(p + int2(1, 0), size); + float3 u = seen(p + int2(0, -1), size), d = seen(p + int2(0, 1), size); + float3 dx = abs(l.z - c.z) < abs(r.z - c.z) ? c - l : r - c; + float3 dy = abs(u.z - c.z) < abs(d.z - c.z) ? c - u : d - c; + float3 n = normalize(cross(dy, dx) + float3(0.0, 0.0, -1e-9)); + if (dot(n, c) > 0.0) n = -n; + float3 v = normalize(c); + float3 ray = v - 2.0 * dot(v, n) * n; + float2 g = (float2(p) + 0.5) / size * float2(PX, PY) - 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float4 sr = float4(0.0, 0.0, 0.0, 0.0), sg = float4(0.0, 0.0, 0.0, 0.0), sb = float4(0.0, 0.0, 0.0, 0.0); + float sum = 0.0; + [unroll] + for (int k = 0; k < 4; ++k) { + int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(PX, PY) - 1); + float z = seen(int2((float2(q) + 0.5) * size / float2(PX, PY)), size).z; + float2 bw = float2((k & 1) ? f.x : 1.0 - f.x, (k >> 1) ? f.y : 1.0 - f.y); + float w = (bw.x * bw.y + 1e-3) / (0.02 + abs(z - c.z) / c.z); + uint at0 = POINT_AT + (q.y * PX + q.x) * 3; + sr += w * sky_level[at0]; + sg += w * sky_level[at0 + 1]; + sb += w * sky_level[at0 + 2]; + sum += w; + } + float3 all_ = float3(sr.w, sg.w, sb.w) / sum; + // radiance from the first moments: three times the direction's share for an even spread of + // directions, a little less for a smooth image + float3 found = all_ + 2.0 * float3(dot(sr.xyz, ray), dot(sg.xyz, ray), dot(sb.xyz, ray)) / sum; + found = clamp(found, 0.1 * all_, 3.0 * all_); + found = lerp(found, mean.rgb, 0.2) * ao_strength; + out_uav[at.xy] = all(isfinite(found)) ? clamp(found, 0.0, 16.0) : float3(0.0, 0.0, 0.0); +} +"#; + +/// The diffuse light of a texel of the resolve's output (`R9G9B9E5_SHAREDEXP` packed in +/// `R32_UINT`), after `light_hlsl`. With the depth: the four gathered points +/// around the texel, those at its own depth first, along the normal the depth gives, shaded where +/// the surroundings close over it within 0.6 m. Without it: the cells under the texel. The sky's +/// level counts for `SKY_SHARE`, and what the title left for at most `MOST` times the estimate. +/// The shade's noise moves with the frame (`fill_bits`, `XCL_AMBIENT_DITHER`); with +/// `XCL_AMBIENT_ONCE` the light is noted where the keep reads (`ONCE_AT`). +const AMBIENT_FILL_R9G9B9E5_HLSL: &str = r#" +RWTexture2D out_uav : register(u0); +float3 unpack_r9g9b9e5(uint v) { + return float3(float(v & 511u), float((v >> 9) & 511u), float((v >> 18) & 511u)) * exp2(float(v >> 27) - 24.0); +} +uint pack_r9g9b9e5(float3 c) { + c = clamp(c, 0.0, 65408.0); + float top = max(c.r, max(c.g, c.b)); + int e = clamp(int(floor(log2(max(top, 1e-9)))) + 16, 0, 31); + float scale = exp2(float(24 - e)); + if (top * scale >= 511.5) { + e = min(e + 1, 31); + scale = exp2(float(24 - e)); + } + uint3 m = min(uint3(c * scale + 0.5), uint3(511u, 511u, 511u)); + return m.r | (m.g << 9) | (m.b << 18) | (uint(e) << 27); +} +// The light the frame before sent out around this texel on the screen: 64x36 cells, their slow +// mean a fifth of it. +float3 frame_light(uint2 tid, float3 mean) { + float2 g = (float2(tid) + 0.5) / float2(max(width, 1u), max(height, 1u)) * float2(64.0, 36.0) - 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float3 sum = float3(0.0, 0.0, 0.0); + [unroll] + for (int k = 0; k < 4; ++k) { + int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(63, 35)); + float wx = (k & 1) ? f.x : 1.0 - f.x; + float wy = (k >> 1) ? f.y : 1.0 - f.y; + sum += wx * wy * sky_level[CELL_AT + q.y * 64 + q.x].rgb; + } + return lerp(sum, mean, 0.2); +} +// (`XCL_AMBIENT_ONCE`) Whether the keep reads texel `texel` of this width x height picture (place +// (x, y) of cell `at`, as FRAME_KEEP_HLSL finds it), and where that place's note is. +bool keep_reads(int2 texel, out uint noted) { + float2 g = (float2(texel) + 0.5) / float2(width, height) * float2(64.0, 36.0); + uint2 at = min(uint2(g), uint2(63u, 35u)); + uint x = min(uint((g.x - float(at.x)) * 5.0), 4u); + uint y = min(uint((g.y - float(at.y)) * 5.0), 4u); + float2 at_texel = (float2(at.xy) + (float2(x, y) + 0.5) / 5.0) * float2(width, height) / float2(64.0, 36.0); + uint2 p = min(uint2(at_texel), uint2(width - 1, height - 1)); + noted = ONCE_AT + (at.y * 64 + at.x) * 25 + y * 5 + x; + return all(p == uint2(texel)); +} +[numthreads(8, 8, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + if (tid.x >= width || tid.y >= height) return; + int2 p = int2(tid.xy); + float2 size = float2(width, height); + float3 sky = ((sky_ready & 1u) != 0u) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); + sky = all(isfinite(sky)) ? clamp(sky, 0.0, 0.65) : float3(0.0, 0.0, 0.0); + float4 mean = sky_level[1]; + bool kept = mean.a > 0.0 && all(isfinite(mean.rgb)); + float3 found = float3(0.0, 0.0, 0.0); + float open = 1.0; + // (`XCL_AMBIENT_SPLIT=1`: bit 1 of has_depth – only the left half is made in space, to compare) + bool in_space = (has_depth & 1u) != 0u && depth_w > 0u && depth_h > 0u && ((has_depth & 2u) == 0u || tid.x * 2u < width); + if (in_space) { + float3 c = seen(p, size); + float3 l = seen(p + int2(-1, 0), size), r = seen(p + int2(1, 0), size); + float3 u = seen(p + int2(0, -1), size), d = seen(p + int2(0, 1), size); + float3 dx = abs(l.z - c.z) < abs(r.z - c.z) ? c - l : r - c; + float3 dy = abs(u.z - c.z) < abs(d.z - c.z) ? c - u : d - c; + float3 n = normalize(cross(dy, dx) + float3(0.0, 0.0, -1e-9)); + if (dot(n, c) > 0.0) n = -n; + // How open it is: what stands over the surface within 0.6 m shades it. + const float radius = 0.6; + float px = min(radius * size.y / (2.0 * 0.45 * c.z), 128.0); + // (moved by 5.588238 texels for each frame of the dither's round: bits 8 to 13 of sky_ready) + float noise = frac(52.9829189 * frac(dot(float2(p) + 5.588238 * float((sky_ready >> 8) & 63u), float2(0.06711056, 0.00583715)))); + if (ao_strength > 0.0 && px >= 1.5 && c.z < 400.0) { + float over_sum = 0.0; + [loop] + for (int i = 0; i < 12; ++i) { + float a = float(i) * 2.399963 + noise * 6.2831853; + float2 o = float2(cos(a), sin(a)) * (sqrt((float(i) + 0.5) / 12.0) * px); + float3 v = seen(p + int2(round(o)), size) - c; + float vv = dot(v, v); + float over = dot(v, n) - 0.004 * c.z - 0.005; + over_sum += max(over, 0.0) / sqrt(vv + 1e-6) * saturate(1.0 - vv / (radius * radius)); + } + open = saturate(1.0 - ao_strength * 2.0 * over_sum / 12.0); + } + if (kept) { + // Between the four points around, those at its own depth first; which four is + // dithered a little. + float2 g = (float2(p) + 0.5) / size * float2(PX, PY) - 0.5 + (noise - 0.5) * 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float4 sr = float4(0.0, 0.0, 0.0, 0.0), sg = float4(0.0, 0.0, 0.0, 0.0), sb = float4(0.0, 0.0, 0.0, 0.0); + float sum = 0.0; + [unroll] + for (int k = 0; k < 4; ++k) { + int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(PX, PY) - 1); + float z = seen(int2((float2(q) + 0.5) * size / float2(PX, PY)), size).z; + float2 bw = float2((k & 1) ? f.x : 1.0 - f.x, (k >> 1) ? f.y : 1.0 - f.y); + float w = (bw.x * bw.y + 1e-3) / (0.02 + abs(z - c.z) / c.z); + uint at0 = POINT_AT + (q.y * PX + q.x) * 3; + sr += w * sky_level[at0]; + sg += w * sky_level[at0 + 1]; + sb += w * sky_level[at0 + 2]; + sum += w; + } + float3 all_ = float3(sr.w, sg.w, sb.w) / sum; + found = all_ + 1.2 * float3(dot(sr.xyz, n), dot(sg.xyz, n), dot(sb.xyz, n)) / sum; + found = clamp(found, 0.2 * all_, 2.5 * all_); + found = lerp(found, mean.rgb, 0.2); + } + } else if (kept) { + found = frame_light(tid.xy, mean.rgb); + } + found = all(isfinite(found)) ? clamp(found, 0.0, 16.0) : float3(0.0, 0.0, 0.0); + found = max(found, sky * SKY_SHARE) * open; + float3 was = unpack_r9g9b9e5(out_uav[p]); + if (!all(isfinite(was)) || (sky_ready & 2u) == 0u) was = float3(0.0, 0.0, 0.0); + // Magenta (green far below red and blue) is what the probes' memory held, not light. + if (was.g < 0.5 * min(was.r, was.b) && max(was.r, was.b) > 0.02) was = float3(0.0, 0.0, 0.0); + // And the bluer kind of it (blue over 2.5x green and over red), which the line above leaves + // as a faint violet. The sky's light keeps green above 0.4x blue, sunsets keep blue low. + if (was.b > 2.5 * was.g && was.b > was.r && was.b > 0.02) was = float3(0.0, 0.0, 0.0); + // What the program left counts as far as it can be true: the sky's light outdoors, not the + // blocks of other memory. + float top = max(dot(found, LUMA) * MOST, 1e-6); + was *= min(1.0, top / max(dot(was, LUMA), 1e-6)); + float3 now = max(was, found); + out_uav[p] = pack_r9g9b9e5(now); + // (bit 2 of sky_ready, `XCL_AMBIENT_ONCE`) Where the next keep reads, how bright the title's own + // light is and all of it: the keep takes the rest out of what the place sends back. + uint noted = 0u; + if ((sky_ready & 4u) != 0u && keep_reads(p, noted)) sky_level[noted] = float4(dot(was, LUMA), dot(now, LUMA), 0.0, 0.0); +} +"#; + +/// 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; +}; +// The light the frame before sent out around this texel: 64x36 cells from `sky_level[2]` on, +// their slow mean at `sky_level[1]` (its fourth part 0: nothing kept yet, no light). +float3 frame_light(uint2 tid) { + float4 mean = sky_level[1]; + if (!(mean.a > 0.0)) { + return float3(0.0, 0.0, 0.0); + } + float2 g = (float2(tid) + 0.5) / float2(max(width, 1u), max(height, 1u)) * float2(64.0, 36.0) - 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float3 sum = float3(0.0, 0.0, 0.0); + [unroll] + for (int k = 0; k < 4; ++k) { + int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(63, 35)); + float wx = (k & 1) ? f.x : 1.0 - f.x; + float wy = (k >> 1) ? f.y : 1.0 - f.y; + sum += wx * wy * sky_level[2 + q.y * 64 + q.x].rgb; + } + float3 found = lerp(sum, mean.rgb, 0.2); + return all(isfinite(found)) ? clamp(found, 0.0, 16.0) : float3(0.0, 0.0, 0.0); +} +float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { + float d0 = depth_tex.Load(int3(dc, 0)); + if (!isfinite(d0) || d0 <= 1e-5 || d0 >= 0.99999) { + return 1.0; + } + // (moved by 5.588238 texels for each frame of the dither's round: bits 8 to 13 of sky_ready) + float ign = frac(52.9829189 * frac(dot(float2(tid) + 5.588238 * float((sky_ready >> 8) & 63u), float2(0.06711056, 0.00583715)))); + float base_ang = ign * 6.2831853; + float max_rad = clamp(float(depth_w) * 0.012, 4.0, 16.0); + float inv_d0 = 1.0 / max(d0, 1e-5); + 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 & 1u) != 0u) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); + amb = max(amb, frame_light(tid.xy)); + float ao = 1.0; + if (has_depth != 0 && depth_w > 0 && depth_h > 0) { + int2 dc = int2( + 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#" +ByteAddressBuffer indirect_args : register(t0); +RWTexture2D out_uav : register(u0); +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint width; + uint height; + uint indirect_flag; + uint indirect_off; + uint _u4; + float reflect_scale; + float _p6; + float _p7; +}; +[numthreads(8, 8, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + if (indirect_flag != 0u && any(indirect_args.Load3(indirect_off) == 0u)) return; + if (tid.x >= width || tid.y >= height) return; + float4 cur = out_uav[tid.xy]; + float3 rgb = all(isfinite(cur.rgb)) ? max(cur.rgb, 0.0) : float3(0.0, 0.0, 0.0); + // Magenta (green far below red and blue) is what the probes' memory held, not light. + if (rgb.g < 0.5 * min(rgb.r, rgb.b) && max(rgb.r, rgb.b) > 0.02) rgb = float3(0.0, 0.0, 0.0); + float3 cap = max(sky_level[0].rgb * reflect_scale, float3(0.005, 0.005, 0.005)); + out_uav[tid.xy] = float4(min(rgb, cap), isfinite(cur.a) ? cur.a : 1.0); +} +"#; + +/// Hue-preserving reflection luminance cap for `CS_TemporalResolve2_Opaque` / +/// `CS_TemporalResolve1_Alpha` (`R9G9B9E5` packed in `R32_UINT`), with optional GPU indirect-args +/// zero-group gating so empty indirect dispatches leave the texture untouched: `reflect_scale` +/// times the sky's level or the cells', and `hold` times the light around (0: not held). +const REFLECT_CLAMP_R9_HLSL: &str = r#" +ByteAddressBuffer indirect_args : register(t0); +RWTexture2D out_uav : register(u0); +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint width; + uint height; + uint indirect_flag; + uint indirect_off; + uint _u4; + float reflect_scale; + float hold; + float _p7; +}; +float3 unpack_r9g9b9e5(uint v) { + float e = exp2(float(v >> 27) - 24.0); + return float3(float(v & 0x1FFu), float((v >> 9) & 0x1FFu), float((v >> 18) & 0x1FFu)) * e; +} +uint pack_r9g9b9e5(float3 rgb) { + rgb = clamp(rgb, 0.0, 65408.0); + float m = max(rgb.r, max(rgb.g, rgb.b)); + int e = clamp(int(floor(log2(max(m, 1e-9)))) + 16, 0, 31); + float s = exp2(float(24 - e)); + if (m * s >= 511.5) { + e = min(e + 1, 31); + s = exp2(float(24 - e)); + } + uint3 q = min(uint3(rgb * s + 0.5), uint3(511u, 511u, 511u)); + return q.r | (q.g << 9) | (q.b << 18) | (uint(e) << 27); +} +float3 frame_light(uint2 tid) { + float4 mean = sky_level[1]; + if (mean.a <= 0.0 || !all(isfinite(mean.rgb))) return float3(0.0, 0.0, 0.0); + float2 g = (float2(tid) + 0.5) / float2(max(width, 1u), max(height, 1u)) * float2(64.0, 36.0) - 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float3 sum = float3(0.0, 0.0, 0.0); + [unroll] + for (uint k = 0u; k < 4u; ++k) { + int2 q = clamp(g0 + int2(int(k & 1u), int(k >> 1)), int2(0, 0), int2(63, 35)); + float wx = (k & 1u) != 0u ? f.x : 1.0 - f.x; + float wy = (k >> 1) != 0u ? f.y : 1.0 - f.y; + sum += wx * wy * sky_level[2 + q.y * 64 + q.x].rgb; + } + float3 found = lerp(sum, mean.rgb, 0.2); + return all(isfinite(found)) ? clamp(found, 0.0, 16.0) : float3(0.0, 0.0, 0.0); +} +// The light gathered at the four of the 160x90 points about this texel (each colour's mean in +// the fourth part of its float4, from `sky_level[4610]` on); none while no points are gathered. +float3 points_light(uint2 tid) { + float2 g = (float2(tid) + 0.5) / float2(max(width, 1u), max(height, 1u)) * float2(160.0, 90.0) - 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float3 sum = float3(0.0, 0.0, 0.0); + [unroll] + for (uint k = 0u; k < 4u; ++k) { + int2 q = clamp(g0 + int2(int(k & 1u), int(k >> 1)), int2(0, 0), int2(159, 89)); + float wx = (k & 1u) != 0u ? f.x : 1.0 - f.x; + float wy = (k >> 1) != 0u ? f.y : 1.0 - f.y; + uint at0 = 4610u + uint(q.y * 160 + q.x) * 3u; + sum += wx * wy * float3(sky_level[at0].w, sky_level[at0 + 1u].w, sky_level[at0 + 2u].w); + } + return all(isfinite(sum)) ? max(sum, 0.0) : float3(0.0, 0.0, 0.0); +} +[numthreads(8, 8, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + if (indirect_flag != 0u && any(indirect_args.Load3(indirect_off) == 0u)) return; + if (tid.x >= width || tid.y >= height) return; + float3 cur = unpack_r9g9b9e5(out_uav[tid.xy]); + if (!all(isfinite(cur))) cur = float3(0.0, 0.0, 0.0); + cur = max(cur, 0.0); + // Magenta (green far below red and blue) is what the probes' memory held, not light. + if (cur.g < 0.5 * min(cur.r, cur.b) && max(cur.r, cur.b) > 0.02) cur = float3(0.0, 0.0, 0.0); + float3 amb = max(clamp(sky_level[0].rgb, 0.0, 0.65), frame_light(tid.xy)); + float amb_lum = max(dot(amb, float3(0.2126, 0.7152, 0.0722)), 0.005); + float cap_lum = max(amb_lum * reflect_scale, 0.005); + // And no brighter than `hold` times the light around: the four points about the texel, a + // fifth of it the slow mean (the cells under it while no points are gathered). Indoors the + // sky's level above is far brighter than the room: eyes, glossy floors and glass glowed. + float4 mean = sky_level[1]; + if (hold > 0.0 && mean.a > 0.0 && all(isfinite(mean.rgb))) { + float3 around = points_light(tid.xy); + around = dot(around, float3(0.2126, 0.7152, 0.0722)) > 0.0 ? lerp(around, mean.rgb, 0.2) : frame_light(tid.xy); + cap_lum = min(cap_lum, hold * dot(around, float3(0.2126, 0.7152, 0.0722))); + } + float cur_lum = dot(cur, float3(0.2126, 0.7152, 0.0722)); + if (cur_lum > cap_lum) { + cur *= (cap_lum / max(cur_lum, 1e-6)); + } + out_uav[tid.xy] = pack_r9g9b9e5(cur); +} +"#; + +/// The air's scattered light after `CS_AccumulateLocalLightInscatteringVolume`: no more than +/// `air_scale` times the light around – of the room as the last seconds showed it, and of the +/// surface seen in this direction (towards a window the air outside may be as bright as the sky +/// is); what is brighter is scaled down with its colour kept. Before any +/// light is kept or gathered, the sky's level stands for it. The light of transparent surfaces +/// after `CS_SpatialFilterAlpha` is held the same way (`air_scale`: `XCL_AMBIENT_ALPHA`). +const AIR_CAP_HLSL: &str = r#" +Texture2D _unused : register(t0); +RWTexture3D vol_uav : register(u0); +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; +}; +static const float3 LUMA = float3(0.2126, 0.7152, 0.0722); +[numthreads(8, 8, 2)] +void main(uint3 tid : SV_DispatchThreadID) { + if (tid.x >= width || tid.y >= height || tid.z >= depth) return; + float4 cur = vol_uav[tid]; + float3 rgb = all(isfinite(cur.rgb)) ? max(cur.rgb, 0.0) : float3(0.0, 0.0, 0.0); + float4 mean = sky_level[1]; + float room = (mean.a > 0.0 && all(isfinite(mean.rgb))) ? dot(mean.rgb, LUMA) : max(sky_level[0].w, 0.01); + uint2 q = min(uint2((float2(tid.xy) + 0.5) / float2(width, height) * float2(160.0, 90.0)), uint2(159u, 89u)); + uint at0 = 4610 + (q.y * 160 + q.x) * 3; + float there = dot(float3(sky_level[at0].w, sky_level[at0 + 1].w, sky_level[at0 + 2].w), LUMA); + if (!(there > 0.0) || !isfinite(there)) there = room; + float cap = max(air_scale * lerp(room, there, float(tid.z) / float(max(depth, 1u))), 0.002); + float lum = dot(rgb, LUMA); + if (lum > cap) rgb *= cap / lum; + vol_uav[tid] = float4(rgb, isfinite(cur.a) ? cur.a : 0.0); +} +"#; + +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(&light_hlsl(AMBIENT_FILL_R9G9B9E5_HLSL))?; + let place_bc = compile_cs_sm5(&light_hlsl(LIGHT_PLACE_HLSL))?; + let gather_bc = compile_cs_sm5(&light_hlsl(LIGHT_GATHER_HLSL))?; + let reflect_bc = compile_cs_sm5(REFLECT_CLAMP_HLSL)?; + let reflect_r9_bc = compile_cs_sm5(REFLECT_CLAMP_R9_HLSL)?; + let air_bc = compile_cs_sm5(AIR_CAP_HLSL)?; + let keep_bc = compile_cs_sm5(FRAME_KEEP_HLSL)?; + let mean_bc = compile_cs_sm5(FRAME_MEAN_HLSL)?; + let miss_bc = compile_cs_sm5(&light_hlsl(MISS_LIGHT_HLSL))?; + + // Shared compute RS: [0] 8 root constants (b0), [1] 1 SRV (t0), [2] 2 UAVs (u0..u1) + let srv_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + let uav_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + NumDescriptors: 2, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + let params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 8 }, + }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &srv_range }, + }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &uav_range }, + }, + }, + ]; + let rs_desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + ..Default::default() + }; + let mut rs_blob = None; + D3D12SerializeRootSignature(&rs_desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut rs_blob, None).ok()?; + let rs_blob = rs_blob?; + + let dev_raw = dev.as_raw(); + type CreateRsFn = unsafe extern "system" fn(*mut c_void, u32, *const c_void, usize, *const c_void, *mut *mut c_void) -> i32; + type CreateCsFn = unsafe extern "system" fn(*mut c_void, *const D3D12_COMPUTE_PIPELINE_STATE_DESC, *const c_void, *mut *mut c_void) -> i32; + type CreateHeapFn = unsafe extern "system" fn(*mut c_void, *const D3D12_DESCRIPTOR_HEAP_DESC, *const c_void, *mut *mut c_void) -> i32; + type IncSizeFn = unsafe extern "system" fn(*mut c_void, D3D12_DESCRIPTOR_HEAP_TYPE) -> u32; + type CreateResFn = unsafe extern "system" fn( + *mut c_void, + *const D3D12_HEAP_PROPERTIES, + D3D12_HEAP_FLAGS, + *const D3D12_RESOURCE_DESC, + D3D12_RESOURCE_STATES, + *const D3D12_CLEAR_VALUE, + *const c_void, + *mut *mut c_void, + ) -> i32; + + let create_rs: CreateRsFn = std::mem::transmute(real::orig_fn(dev_raw, 16)); + let create_cs: CreateCsFn = std::mem::transmute(real::orig_fn(dev_raw, 11)); + let create_heap: CreateHeapFn = std::mem::transmute(real::orig_fn(dev_raw, 14)); + let inc_size: IncSizeFn = std::mem::transmute(real::orig_fn(dev_raw, 15)); + let create_res: CreateResFn = std::mem::transmute(real::orig_fn(dev_raw, 27)); + + let mut rs_raw = std::ptr::null_mut(); + if create_rs(dev_raw, 0, rs_blob.GetBufferPointer(), rs_blob.GetBufferSize(), &ID3D12RootSignature::IID as *const _ as *const c_void, &mut rs_raw) < 0 || rs_raw.is_null() { + return None; + } + let rs = ID3D12RootSignature::from_raw(rs_raw); + + let make_cs = |bc: &[u8], name: &str| -> Option { + let mut d = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bc.as_ptr() as *const c_void, BytecodeLength: bc.len() }, + ..Default::default() + }; + let mut raw = std::ptr::null_mut(); + let hr = create_cs(dev_raw, &d, &ID3D12PipelineState::IID as *const _ as *const c_void, &mut raw); + ManuallyDrop::drop(&mut d.pRootSignature); + (hr >= 0 && !raw.is_null()).then(|| { + let pso = ID3D12PipelineState::from_raw(raw); + let _ = pso.SetName(&windows::core::HSTRING::from(name)); + super::dred::label_text(pso.as_raw() as usize, || name.to_string()); + pso + }) + }; + let reduce_pso = make_cs(&reduce_bc, "xcl ambient sky_reduce")?; + let fill_pso = make_cs(&fill_bc, "xcl ambient fill")?; + let fill_write_pso = make_cs(&fill_write_bc, "xcl ambient fill_write")?; + let fill_r9_pso = make_cs(&fill_r9_bc, "xcl ambient fill_r9")?; + let place_pso = make_cs(&place_bc, "xcl ambient light_place")?; + let gather_pso = make_cs(&gather_bc, "xcl ambient light_gather")?; + let reflect_pso = make_cs(&reflect_bc, "xcl ambient reflect_clamp")?; + let reflect_r9_pso = make_cs(&reflect_r9_bc, "xcl ambient reflect_clamp_r9")?; + let air_pso = make_cs(&air_bc, "xcl ambient air_cap")?; + let keep_pso = make_cs(&keep_bc, "xcl ambient frame_keep")?; + let mean_pso = make_cs(&mean_bc, "xcl ambient frame_mean")?; + let miss_pso = make_cs(&miss_bc, "xcl ambient miss_light")?; + + let default_hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let make_res = |rd: &D3D12_RESOURCE_DESC, init: D3D12_RESOURCE_STATES| -> Option { + 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: (LEVEL_BUFFER_ELEMENTS as u64 * 16).next_multiple_of(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 dummy_indirect = make_res( + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )?; + + let heap_desc = D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + 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, + place_pso, + gather_pso, + reflect_pso, + reflect_r9_pso, + air_pso, + keep_pso, + mean_pso, + miss_pso, + sky_copy, + sky_level, + dummy_depth, + dummy_indirect, + heap, + heap_cpu, + heap_gpu, + inc, + next_group: AtomicU32::new(0), + sky_ready: AtomicBool::new(false), + last_sky_us: AtomicU64::new(0), + last_keep_us: AtomicU64::new(0), + }) +} + +unsafe fn get_device(dev: &ID3D12Device) -> Option> { + let key = dev.as_raw() as usize; + let mut g = DEVICES.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + if let Some(entry) = map.get(&key) { + return entry.clone(); + } + let built = build_device(dev).map(std::sync::Arc::new); + map.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 { + static NO_DEV: AtomicU64 = AtomicU64::new(0); + if NO_DEV.fetch_add(1, Ordering::Relaxed) < 2 { + crate::xlog_warn!("D3D12.X: ambient: no stand-in device (its helper pipelines could not be made): pass left as it is"); + } + return; + }; + + let sky_raw = ad.sky_copy.as_raw() as usize; + list_x::transition(list, rt0, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + 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: LEVEL_ELEMENTS, StructureByteStride: 16, ..Default::default() }, + }, + }; + create_srv(dev_raw, ad.sky_copy.as_raw(), &sky_srv, cpu0 as usize); + create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + inc) as usize); + create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + 2 * inc) as usize); + + let heap_raw = ad.heap.as_raw() as usize; + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list, 28)); + let set_cs_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 29)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 25)); + let set_cs_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(real::orig_fn(list, 31)); + let set_cs_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(real::orig_fn(list, 35)); + let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list, 14)); + + let cfg = config(); + let now_us = monotonic_us(); + let prev_us = ad.last_sky_us.swap(now_us, Ordering::AcqRel); + let first_sample = prev_us == 0 || !ad.sky_ready.load(Ordering::Acquire); + let dt_s = if first_sample { 0.0 } else { now_us.saturating_sub(prev_us) as f32 * 1e-6 }; + let alpha = settle_alpha(dt_s, cfg.settle_ms, first_sample); + if !first_sample { + uav_barrier(list, ad.sky_level.as_raw() as usize); + } + let consts = [cfg.gain.to_bits(), cfg.power.to_bits(), cfg.least.to_bits(), alpha.to_bits(), 0, 0, 0, 0]; + set_heaps(list, 1, &heap_raw); + set_cs_rs(list, ad.rs.as_raw()); + super::dred::mark_pipeline(list, ad.reduce_pso.as_raw() as usize, ad.reduce_pso.as_raw() as usize); + set_pso(list, ad.reduce_pso.as_raw()); + set_cs_consts(list, 0, 8, consts.as_ptr(), 0); + set_cs_table(list, 1, gpu0); + set_cs_table(list, 2, gpu0 + inc); + dispatch(list, 1, 1, 1); + uav_barrier(list, ad.sky_level.as_raw() as usize); + ad.sky_ready.store(true, Ordering::Release); + list_x::restore_after_internal_pass(list, false, true); + + static LOGGED: AtomicU64 = AtomicU64::new(0); + if LOGGED.fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_info!("D3D12.X: ambient: captured 128x128 R16G16B16A16_FLOAT sky dome ({rt0:#x})"); + } +} + +/// Maximum bindless descriptor-heap slot index probed from root constants/CBVs +/// (covers >1.24M-slot console shader-visible view heaps). +const MAX_SLOT_INDEX: u32 = 2_000_000; + +/// Decode a CBV / buffer `V#` descriptor (`gpu::desc::cbv_words` / `buffer_words`) into +/// `(va, byte_len)` if it is a readable buffer descriptor (`w3 >> 28 < 8` and dst_sel `0xFAC`). +pub(super) 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`. +pub(super) unsafe fn scan_cbv_indices(va: usize, max_bytes: usize, push_idx: &mut impl FnMut(u32)) { + scan_cbv_indices_with(va, max_bytes, resolve_cbv_va, push_idx); +} + +/// 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); + } + } + let mut uav = uav_hit.map(|(_, r, f, w, h, d)| (r, f, w, h, d)); + // A program's own slots: the view at `dword` of root parameter `param`'s table. Where a + // program has several images of one format and size, a guess by format alone can take the + // wrong one. + let pinned = |param: usize, dword: usize| -> Option<(ViewEntry, D3D12_RESOURCE_DESC)> { + let Some(&Param::Table { at }) = layout.params.get(param) else { return None }; + let t = word(at as usize).filter(|&t| t != 0)?; + let addr = u.base().checked_add(t as usize)?.checked_add(4 * dword)?; + if !u.contains(addr) || !crate::gpu::shader::readable(addr, 16) { + return None; + } + let (w0, w3) = ((addr as *const u32).read_unaligned(), ((addr + 12) as *const u32).read_unaligned()); + if (w3 >> 28) < 8 { + return None; + } + // (only views of the light's and of depth formats are noted here: any other picture + // is named by the heap's own record of its index, read in a format of its resource's) + let noted = vs.by_addr.get(&addr).or_else(|| (w0 != 0).then(|| vs.by_idx.get(&w0)).flatten()).copied(); + let named = || match super::console_heap::named_by_index(w0) { + 0 | super::console_heap::GONE => None, + res => Some(ViewEntry { res, fmt: 0, is_uav: false }), + }; + let mut ve = noted.or_else(named)?; + let ptr = ve.res as *mut c_void; + let rd = ID3D12Resource::from_raw_borrowed(&ptr)?.GetDesc(); + if ve.fmt == 0 { + ve.fmt = match rd.Format.0 { + 39..=41 => 41, + 19..=21 => 21, + 44..=46 => 46, + 53 | 55 | 56 => 56, + f => f, + }; + } + let flat = rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && rd.DepthOrArraySize == 1; + (rd.SampleDesc.Count == 1 && (flat || rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D)).then_some((ve, rd)) + }; + let flat = |rd: &D3D12_RESOURCE_DESC| rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D; + if role == PassRole::ReflectionResolve { + // The resolves' own slots (`REFLECTION_SLOTS`): the first that holds a picture of the + // reflections' format, else the one found by its format. + let held = REFLECTION_SLOTS + .iter() + .find_map(|&(param, dword)| pinned(param, dword).filter(|(ve, rd)| ve.is_uav && ve.fmt == 42 && flat(rd))); + if let Some((ve, rd)) = &held { + uav = Some((ve.res, ve.fmt, rd.Width as u32, rd.Height, 1)); + } + static SLOTS: AtomicU64 = AtomicU64::new(0); + if SLOTS.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!( + "D3D12.X: ambient: the reflections' resolve writes {} ({:?})", + if held.is_some() { "the one in its slot" } else { "the one found by its format" }, + uav.map(|(r, f, w, h, _)| (r, f, w, h)) + ); + } + } + if role == PassRole::AlphaLight { + // Its own slot only: the filter writes the light's direction to another volume (dword + // 16), which a bound of luminance does not fit. + let slot = pinned(ALPHA_SLOT.0, ALPHA_SLOT.1); + let light = slot.filter(|(ve, rd)| { + ve.is_uav && ve.fmt == 26 && rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && rd.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0 + }); + uav = light.as_ref().map(|(ve, rd)| (ve.res, ve.fmt, rd.Width as u32, rd.Height, rd.DepthOrArraySize as u32)); + static SLOTS: AtomicU64 = AtomicU64::new(0); + if SLOTS.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!( + "D3D12.X: ambient: the transparent surfaces' light is {} ({:?})", + if light.is_some() { "the one in its slot" } else { "not in its slot: left as the title has it" }, + slot.as_ref().map(|(ve, rd)| (ve.res, ve.fmt, ve.is_uav, rd.Dimension.0, rd.Width, rd.Height, rd.DepthOrArraySize)) + ); + } + } + if role == PassRole::RayMiss { + // Its own slots only (a guess by format could take another half-size image of the + // light): the reflected light, and the depth of the picture it was traced from + let light = pinned(MISS_LIGHT_SLOT.0, MISS_LIGHT_SLOT.1).filter(|(ve, rd)| ve.is_uav && ve.fmt == 26 && flat(rd) && rd.DepthOrArraySize == 1); + uav = light.as_ref().map(|(ve, rd)| (ve.res, ve.fmt, rd.Width as u32, rd.Height, 1)); + let at_least = |w: u64, h: u32| uav.is_some_and(|(_, _, uw, uh, _)| w >= uw as u64 && h >= uh); + let depth = pinned(MISS_DEPTH_SLOT.0, MISS_DEPTH_SLOT.1).filter(|(ve, rd)| !ve.is_uav && matches!(ve.fmt, 21 | 41 | 46) && flat(rd) && at_least(rd.Width, rd.Height)); + static SLOTS: AtomicU64 = AtomicU64::new(0); + if SLOTS.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!( + "D3D12.X: ambient: the missed reflections' light is {} ({:?}), their depth {} ({:?})", + if light.is_some() { "the one in its slot" } else { "not in its slot: left as the title has it" }, + uav.map(|(r, f, w, h, _)| (r, f, w, h)), + if depth.is_some() { "the one in its slot" } else { "not in its slot" }, + depth.as_ref().map(|(ve, rd)| (ve.res, ve.fmt, rd.Width, rd.Height)) + ); + } + depth_hit = depth.map(|(ve, rd)| (ve.res, ve.fmt, rd.Width as u32, rd.Height)); + if depth_hit.is_none() { + uav = None; + } + } + if role == PassRole::TemporalResolve && !want_3d { + // The resolve's own slots: its + // light at dword 176 of root parameter 1's table, the depth it reads at dword 464 of + // parameter 0's. The program has several R32_UINT outputs of the picture's size and reads + // other pictures of it besides the depth: a guess by format alone can take the wrong one. + let light = pinned(1, 176).filter(|(ve, rd)| ve.is_uav && ve.fmt == 42 && flat(rd)); + if let Some((ve, rd)) = &light { + uav = Some((ve.res, ve.fmt, rd.Width as u32, rd.Height, 1)); + } + // (the depth is the picture's size, or it is another picture: none then, and the fill is + // made on the screen) + let same_size = |w: u64, h: u32| uav.is_some_and(|(_, _, uw, uh, _)| w == uw as u64 && h == uh); + let depth = pinned(0, 464).filter(|(ve, rd)| !ve.is_uav && matches!(ve.fmt, 21 | 41 | 46 | 54 | 56) && flat(rd) && same_size(rd.Width, rd.Height)); + let found = depth_hit.filter(|&(_, f, w, h)| matches!(f, 20 | 21 | 39 | 40 | 41 | 46 | 55 | 56) && same_size(w as u64, h)); + static SLOTS: AtomicU64 = AtomicU64::new(0); + if SLOTS.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!( + "D3D12.X: ambient: the resolve's light is {} ({:?}), its depth {} ({:?}; the first picture it reads: {:?})", + if light.is_some() { "the one in its slot" } else { "found by its format" }, + uav.map(|(r, f, w, h, _)| (r, f, w, h)), + if depth.is_some() { "the one in its slot" } else if found.is_some() { "found by its format" } else { "not found" }, + depth.as_ref().map(|(ve, rd)| (ve.res, ve.fmt, rd.Width, rd.Height)), + depth_hit + ); + } + depth_hit = depth.map(|(ve, rd)| (ve.res, ve.fmt, rd.Width as u32, rd.Height)).or(found); + } + (uav, depth_hit, tables.len(), indices.len(), table_cbvs) +} + +/// Called right after a translated compute dispatch completes: when RT is gated off and a sky +/// 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, + indirect_args: Option<(usize, u32)>, +) { + if !has_compute_psos() || !active() { + return; + } + let Some(role) = role_of(pso_resolved) else { return }; + if !matches!( + role, + PassRole::TemporalResolve + | PassRole::ReflectionHistory + | PassRole::ReflectionResolve + | PassRole::InscatteringVolume + | PassRole::Radiance + | PassRole::AlphaLight + | PassRole::RayMiss + ) { + return; + } + let cfg = config(); + if role == PassRole::InscatteringVolume && cfg.air <= 0.0 + || role == PassRole::Radiance && cfg.frame <= 0.0 + || role == PassRole::AlphaLight && cfg.alpha <= 0.0 + || role == PassRole::RayMiss && (cfg.specular <= 0.0 || cfg.frame <= 0.0) + { + return; + } + static SWITCHES: std::sync::Once = std::sync::Once::new(); + SWITCHES.call_once(|| { + crate::xlog_info!( + "D3D12.X: ambient: one bounce {} (XCL_AMBIENT_ONCE), garbage left out of the cells {} (XCL_AMBIENT_MEAN_CLEAN), dither {} (XCL_AMBIENT_DITHER), the transparent layer's missed reflections {} (XCL_AMBIENT_SPECULAR_ALPHA)", + if once() { "on" } else { "off" }, + if mean_clean() { "on" } else { "off" }, + if dither() { "moving with the frame" } else { "still" }, + if specular_alpha() { "given the estimate" } else { "left as the title has them" } + ) + }); + // (which surfaces the miss program's rays are of: its first root constant) + if role == PassRole::RayMiss { + let layer = layout.and_then(|l| l.params.iter().find_map(|p| match *p { + Param::Constants { at, count } if count > 0 => args.get(at as usize..at as usize + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())), + _ => None, + })); + if !layer.is_some_and(|l| miss_gets_estimate(l, specular_alpha())) { + if layer == Some(MISS_LAYERS[1]) { + static LEFT: AtomicU64 = AtomicU64::new(0); + let n = LEFT.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: ambient: the transparent layer's missed reflections left as the title has them ({n} so far)"); + } + } + return; + } + } + 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 { + static NO_DEV: AtomicU64 = AtomicU64::new(0); + if NO_DEV.fetch_add(1, Ordering::Relaxed) < 2 { + crate::xlog_warn!("D3D12.X: ambient: no stand-in device (its helper pipelines could not be made): pass left as it is"); + } + return; + }; + let sky_ready = ad.sky_ready.load(Ordering::Acquire); + // (keeping the frame's light needs no sky) + if !sky_ready && role != PassRole::Radiance { + 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 = matches!(role, PassRole::InscatteringVolume | PassRole::AlphaLight); + let (uav_opt, depth_opt, n_tables, n_indices, n_cbvs) = find_dispatch_views(role, layout, args, groups, view_heap_base, want_3d); + // (`XCL_AMBIENT_SPACE=0`: no depth, the light is made on the screen) + let depth_opt = depth_opt.filter(|_| space_light()); + 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 | PassRole::Radiance | PassRole::AlphaLight) && !can_typed_load { + static NO_LOAD: AtomicU64 = AtomicU64::new(0); + if NO_LOAD.fetch_add(1, Ordering::Relaxed) < 2 { + crate::xlog_info!("D3D12.X: ambient: {role:?} skipped (typed UAV load unsupported for fmt {uav_fmt})"); + } + 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 | PassRole::RayMiss, Some((r, f, dw, dh))) => (r as *mut c_void, DXGI_FORMAT(f), dw, dh, 1u32), + _ => (ad.dummy_depth.as_raw(), DXGI_FORMAT_R32_FLOAT, 1, 1, 0u32), + }; + let is_reflect_role = matches!(role, PassRole::ReflectionHistory | PassRole::ReflectionResolve); + let gated_indirect = if is_reflect_role { indirect_args } else { None }; + let depth_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: depth_fmt, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + 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: LEVEL_BUFFER_ELEMENTS, StructureByteStride: 16, ..Default::default() }, + }, + }; + if is_reflect_role { + let (buf_raw, first_elem) = match gated_indirect { + Some((b, off)) => (b as *mut c_void, (off / 4) as u64), + None => (ad.dummy_indirect.as_raw(), 0u64), + }; + let raw_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: first_elem, + NumElements: 4, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }, + }, + }; + create_srv(dev_raw, buf_raw, &raw_srv, cpu0 as usize); + } else { + create_srv(dev_raw, depth_raw, &depth_srv, cpu0 as usize); + } + create_uav(dev_raw, uav_res as *mut c_void, std::ptr::null_mut(), &out_uav_desc, (cpu0 + inc) as usize); + create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + 2 * inc) as usize); + + uav_barrier(list, uav_res); + if let Some((arg_buf, _)) = gated_indirect { + list_x::transition(list, arg_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + } + + let heap_raw = ad.heap.as_raw() as usize; + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list, 28)); + 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 indirect_flag = gated_indirect.is_some() as u32; + 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 | (has_depth & split_screen() as u32) << 1, cfg.ao.to_bits(), fill_bits(sky_ready, keeps_title_light(), once(), dither_phase(present::presents(), dither())), PRE_SKY_FALLBACK.to_bits()], + (w.div_ceil(8), h.div_ceil(8), 1), + ), + PassRole::ReflectionHistory => ( + ad.reflect_pso.as_raw(), + [w, h, indirect_flag, 0, 0, cfg.reflect.to_bits(), 0, 0], + (w.div_ceil(8), h.div_ceil(8), 1), + ), + PassRole::ReflectionResolve => ( + ad.reflect_r9_pso.as_raw(), + [w, h, indirect_flag, 0, 0, cfg.reflect.to_bits(), cfg.reflect_hold.to_bits(), 0], + (w.div_ceil(8), h.div_ceil(8), 1), + ), + PassRole::InscatteringVolume => ( + 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::Radiance => ( + ad.keep_pso.as_raw(), + [w, h, keep_bits(once(), mean_clean()), 0, 0, cfg.frame.to_bits(), 0, 0], + (FRAME_CELLS.0.div_ceil(8), FRAME_CELLS.1.div_ceil(8), 1), + ), + PassRole::AlphaLight => ( + ad.air_pso.as_raw(), + [w, h, d, 0, 0, cfg.alpha.to_bits(), 0, 0], + (w.div_ceil(8), h.div_ceil(8), d.div_ceil(2)), + ), + // (the cells hold `frame` of what the surfaces send out: the share is of all of it) + PassRole::RayMiss => ( + ad.miss_pso.as_raw(), + [w, h, depth_w, depth_h, has_depth, (cfg.specular / cfg.frame).to_bits(), sky_ready as u32, PRE_SKY_FALLBACK.to_bits()], + (w.div_ceil(8), h.div_ceil(8), 1), + ), + PassRole::SkyDome => return, + }; + set_heaps(list, 1, &heap_raw); + set_cs_rs(list, ad.rs.as_raw()); + super::dred::mark_pipeline(list, pso as usize, pso as usize); + set_pso(list, pso); + set_cs_consts(list, 0, 8, consts.as_ptr(), 0); + set_cs_table(list, 1, gpu0); + set_cs_table(list, 2, gpu0 + inc); + if role == PassRole::TemporalResolve && uav_fmt == 42 && has_depth != 0 || role == PassRole::RayMiss { + // where the cells are seen, then their light gathered at the points: what the fill reads + // (for the missed reflections: from this frame's depth, the picture's size; the diffuse + // fill makes them again later in the frame) + let level = ad.sky_level.as_raw() as usize; + if role == PassRole::RayMiss { + let picture = [depth_w, depth_h, depth_w, depth_h, has_depth, 0, sky_ready as u32, 0]; + set_cs_consts(list, 0, 8, picture.as_ptr(), 0); + } + let passes = [ + (ad.place_pso.as_raw(), FRAME_CELLS.0.div_ceil(8), FRAME_CELLS.1.div_ceil(4)), + (ad.gather_pso.as_raw(), GATHER_POINTS.0.div_ceil(8), GATHER_POINTS.1.div_ceil(2)), + ]; + for (pass, gx, gy) in passes { + super::dred::mark_pipeline(list, pass as usize, pass as usize); + set_pso(list, pass); + dispatch(list, gx, gy, 1); + uav_barrier(list, level); + } + super::dred::mark_pipeline(list, pso as usize, pso as usize); + set_pso(list, pso); + if role == PassRole::RayMiss { + set_cs_consts(list, 0, 8, consts.as_ptr(), 0); + } + } + dispatch(list, disp.0, disp.1, disp.2); + uav_barrier(list, uav_res); + if role == PassRole::TemporalResolve && once() { + // (the fill wrote its notes for the next keep) + uav_barrier(list, ad.sky_level.as_raw() as usize); + } + if let Some((arg_buf, _)) = gated_indirect { + list_x::transition(list, arg_buf, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + } + if role == PassRole::Radiance { + // the cells' slow mean, by the clock + let level = ad.sky_level.as_raw() as usize; + uav_barrier(list, level); + let now_us = monotonic_us(); + let prev_us = ad.last_keep_us.swap(now_us, Ordering::AcqRel); + let dt_s = if prev_us == 0 { 0.0 } else { now_us.saturating_sub(prev_us) as f32 * 1e-6 }; + let consts = [0, 0, 0, 0, 0, settle_alpha(dt_s, cfg.settle_ms, prev_us == 0).to_bits(), FRAME_JUMP.to_bits(), 0]; + super::dred::mark_pipeline(list, ad.mean_pso.as_raw() as usize, ad.mean_pso.as_raw() as usize); + set_pso(list, ad.mean_pso.as_raw()); + set_cs_consts(list, 0, 8, consts.as_ptr(), 0); + dispatch(list, 1, 1, 1); + uav_barrier(list, level); + list_x::restore_after_internal_pass(list, false, true); + static KEPT: AtomicU64 = AtomicU64::new(0); + let n = KEPT.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: ambient: the frame's light kept from {w}x{h} fmt {uav_fmt} in {}x{} cells ({n} so far)", FRAME_CELLS.0, FRAME_CELLS.1); + } + return; + } + list_x::restore_after_internal_pass(list, false, true); + if role == PassRole::ReflectionResolve && cfg.reflect_hold > 0.0 { + static HELD: AtomicU64 = AtomicU64::new(0); + let n = HELD.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: ambient: reflections held to {}x the light around after their resolve, {w}x{h} ({n} so far)", + cfg.reflect_hold + ); + } + } + if role == PassRole::RayMiss { + static GIVEN: AtomicU64 = AtomicU64::new(0); + let n = GIVEN.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: ambient: reflections that found nothing given {} of the light around along the reflected direction, {w}x{h} ({n} so far)", + cfg.specular + ); + } + } + if role == PassRole::AlphaLight { + static BOUND: AtomicU64 = AtomicU64::new(0); + let n = BOUND.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: ambient: the transparent surfaces' light held to {}x the light around, {w}x{h}x{d} ({n} so far)", + cfg.alpha + ); + } + } + + static LOGGED: AtomicU64 = AtomicU64::new(0); + if LOGGED.fetch_add(1, Ordering::Relaxed) < 6 { + crate::xlog_info!("D3D12.X: ambient: applied {role:?} stand-in on {w}x{h}x{d} fmt {uav_fmt} (depth AO: {has_depth})"); + } +} + +/// For `mirror` (a mirror's view is given the light around): while the stand-in runs on `dev`, +/// its level buffer (used as a UAV, `LEVEL_ELEMENTS` float4s), the share the sky's level counts +/// for (`XCL_AMBIENT_SKY`) and whether a sky was captured. +pub(crate) unsafe fn level_for_mirror(dev: &ID3D12Device) -> Option<(ID3D12Resource, u32, f32, bool)> { + if !active() { + return None; + } + let ad = get_device(dev)?; + Some((ad.sky_level.clone(), LEVEL_ELEMENTS, config().sky, ad.sky_ready.load(Ordering::Acquire))) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The stand-in is for a picture without bounce light: with traversal held back, and as much + /// with traversal running while every ray misses; not with rays that hit. + #[test] + fn the_stand_in_is_on_whenever_the_rays_find_nothing() { + assert!(rays_find_nothing(false, false), "traversal held back"); + assert!(rays_find_nothing(true, true), "every ray misses"); + assert!(rays_find_nothing(false, true)); + assert!(!rays_find_nothing(true, false), "rays that hit bring the title's own light"); + } + + #[test] + fn the_titles_own_light_is_kept_unless_the_programs_that_feed_it_are_left_out() { + assert!(keeps(None, false)); + assert!(!keeps(None, true), "left-out programs: the resolve reads memory nothing wrote"); + assert!(keeps(Some("1"), true) && !keeps(Some(" 0 "), false), "the switch decides"); + assert!(keeps(Some("x"), false) && !keeps(Some(""), true), "any other value: as unset"); + } + + #[test] + fn mode_and_shader_classification_match_expected_passes() { + assert_eq!(parse_mode(None), Mode::Auto); + 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_CacheScreenSpaceRadiance\0"), Some(PassRole::Radiance)); + assert_eq!(classify_cs(b"ILDN\0CS_CullInstances\0"), None); + } + + /// The reflections' slots are whole descriptors (8 dwords) of the table of root parameter 1, + /// the opaque surfaces' first, as the diffuse resolve's light is (dword 176). + #[test] + fn the_reflections_are_looked_for_in_whole_descriptor_slots_opaque_first() { + assert_eq!(REFLECTION_SLOTS, [(1, 128), (1, 136)]); + assert!(REFLECTION_SLOTS.iter().all(|&(param, dword)| param == 1 && dword % 8 == 0 && dword != 176)); + } + + #[test] + fn sky_dome_filter_rejects_r11g11b10_and_wrong_sizes() { + let mut rd = D3D12_RESOURCE_DESC { + 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(&light_hlsl(AMBIENT_FILL_R9G9B9E5_HLSL)).is_some(), "AMBIENT_FILL_R9G9B9E5_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(&light_hlsl(LIGHT_PLACE_HLSL)).is_some(), "LIGHT_PLACE_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(&light_hlsl(LIGHT_GATHER_HLSL)).is_some(), "LIGHT_GATHER_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(REFLECT_CLAMP_HLSL).is_some(), "REFLECT_CLAMP_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(REFLECT_CLAMP_R9_HLSL).is_some(), "REFLECT_CLAMP_R9_HLSL failed D3DCompile"); + assert_eq!(classify_cs(b"ILDN\0CS_TemporalResolve2_Opaque_1234\0"), Some(PassRole::ReflectionResolve)); + assert_eq!(classify_cs(b"ILDN\0CS_TemporalResolve1_Alpha_5678\0"), Some(PassRole::ReflectionResolve)); + assert!(compile_cs_sm5(AIR_CAP_HLSL).is_some(), "AIR_CAP_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(FRAME_KEEP_HLSL).is_some(), "FRAME_KEEP_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(FRAME_MEAN_HLSL).is_some(), "FRAME_MEAN_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(&light_hlsl(MISS_LIGHT_HLSL)).is_some(), "MISS_LIGHT_HLSL failed D3DCompile"); + // the cells the fills read are the cells the keeping writes, and the mean sums all of them + assert_eq!((FRAME_CELLS, GATHER_POINTS, LEVEL_ELEMENTS), ((64, 36), (160, 90), 2 + 2 * 2304 + 3 * 14400)); + } + + #[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()); + // the frame's light is kept from the R11G11B10_FLOAT image only + assert!(score_dispatch_target_for_role(PassRole::Radiance, &hdr_scene, DXGI_FORMAT_R11G11B10_FLOAT.0, [320, 360, 1]).is_some()); + assert!(score_dispatch_target_for_role(PassRole::Radiance, &r9_probe, DXGI_FORMAT_R32_UINT.0, [320, 360, 1]).is_none()); + assert!(score_dispatch_target_for_role(PassRole::Radiance, &hdr_scene, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [320, 360, 1]).is_none()); + } + + #[test] + 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 - 1.5).abs() < 1e-6 && (def.most - 2.0).abs() < 1e-6 && (def.sky - 0.35).abs() < 1e-6); + + // First capture or settle_ms == 0 snaps immediately; subsequent samples follow 1 - exp(-dt/tau). + assert_eq!(settle_alpha(0.016, 250.0, true), 1.0); + 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); + } + + /// The hold is on at VIctory-Neo's strength unless the switch says 0; another value is taken + /// within 0 to 16, a word that is not a number leaves the default. + #[test] + fn the_reflection_hold_is_on_unless_switched_off() { + assert_eq!(Config::default().reflect_hold, 1.25); + assert!((Config::default().reflect_hold * Config::default().frame - 1.0).abs() < 1e-6, "Neo's 1 of what the surfaces send out"); + assert_eq!(parse_f32(None, 1.25, 0.0, 16.0), 1.25); + assert_eq!(parse_f32(Some(" 0 "), 1.25, 0.0, 16.0), 0.0, "0: not held"); + assert_eq!(parse_f32(Some("2.5"), 1.25, 0.0, 16.0), 2.5); + assert_eq!(parse_f32(Some("99"), 1.25, 0.0, 16.0), 16.0); + assert_eq!(parse_f32(Some("-1"), 1.25, 0.0, 16.0), 0.0); + assert_eq!(parse_f32(Some("off"), 1.25, 0.0, 16.0), 1.25); + assert_eq!(parse_f32(Some("nan"), 1.25, 0.0, 16.0), 1.25); + // the points the hold reads are where the gather writes them + let point_at = 2 + 2 * FRAME_CELLS.0 * FRAME_CELLS.1; + assert!(REFLECT_CLAMP_R9_HLSL.contains(&format!("{point_at}u + uint(q.y * {} + q.x) * 3u", GATHER_POINTS.0))); + assert!(REFLECT_CLAMP_R9_HLSL.contains(&format!("float2({}.0, {}.0)", GATHER_POINTS.0, GATHER_POINTS.1))); + } + + /// The light of transparent surfaces is followed after its last filter, not after the + /// variance filter before it, and is not taken for the transparent reflections' resolve; it is + /// bounded at VIctory-Neo's strength unless the switch says 0, and found in a slot of its own. + #[test] + fn the_transparent_surfaces_light_is_bounded_after_its_last_filter() { + assert_eq!(classify_cs(b"..indirect_light_probes:CS_SpatialFilterAlpha_08e7839f_Wrapped.."), Some(PassRole::AlphaLight)); + assert!(is_ambient_compute(b"ILDN\0CS_SpatialFilterAlpha\0")); + assert_eq!(classify_cs(b"..CS_VarianceFilterAlpha_b92710bc_Wrapped.."), None); + assert_eq!(classify_cs(b"..CS_ShadeAlpha_1234abcd.."), None); + assert_eq!(classify_cs(b"ILDN\0CS_TemporalResolve1_Alpha_5678\0"), Some(PassRole::ReflectionResolve)); + let def = Config::default(); + assert!((def.alpha * def.frame - 4.0).abs() < 1e-6, "Neo's 4 of what the surfaces send out"); + assert_eq!(parse_f32(Some("0"), def.alpha, 0.0, 16.0), 0.0, "0: as the title has it"); + assert_eq!(ALPHA_SLOT, (1, 24)); + assert!(ALPHA_SLOT.1 % 8 == 0 && !REFLECTION_SLOTS.contains(&ALPHA_SLOT)); + } + + /// The reflection rays' miss program is followed (opaque and transparent surfaces), not the + /// volumetrics' nor the screen probes'; it gets all of the estimate unless the switch says + /// otherwise, and its slots are whole descriptors of their tables. + #[test] + fn the_missed_reflections_are_followed_and_given_the_estimate_by_default() { + assert_eq!(classify_cs(b"..sr_tracing:CS_RayMiss_de6b91a6_Wrapped.."), Some(PassRole::RayMiss)); + assert_eq!(classify_cs(b"..sr_tracing:CS_RayMiss_Volumetrics_3c5d8c00_Wrapped.."), None); + assert_eq!(classify_cs(b"..CS_ScreenProbe_RayMiss_80a88544_Wrapped.."), None); + assert_eq!(classify_cs(b"..CS_RayMiss_de6b91a_.."), None, "eight hex digits"); + assert_eq!(Config::default().specular, 1.0, "VIctory-Neo's VICTORY_AMBIENT_SPECULAR=1"); + assert_eq!(parse_f32(Some("0"), 1.0, 0.0, 4.0), 0.0, "0: the sky's light, as the title has it"); + assert_eq!(MISS_LAYERS, [0, 1]); + assert!(MISS_LIGHT_SLOT.1 % 8 == 0 && MISS_DEPTH_SLOT.1 % 8 == 0 && MISS_LIGHT_SLOT.0 == 1 && MISS_DEPTH_SLOT.0 == 0); + // the points the program reads are where the gather writes them + assert!(LIGHT_COMMON_HLSL.contains(&format!("#define POINT_AT {}", 2 + 2 * FRAME_CELLS.0 * FRAME_CELLS.1))); + } + + /// The switches after Whiplash take their words; any other word (or none) leaves the default. + #[test] + fn the_switches_after_whiplash_take_their_words() { + assert!(!switch_on(None, false) && switch_on(None, true), "unset: the default"); + assert!(switch_on(Some(" 1 "), false) && switch_on(Some("ON"), false) && switch_on(Some("true"), false)); + assert!(!switch_on(Some("0"), true) && !switch_on(Some("off"), true) && !switch_on(Some("False"), true)); + assert!(!switch_on(Some("yes"), false) && switch_on(Some("2"), true), "another word: the default"); + assert!(dither_moves(None) && dither_moves(Some("frame")) && dither_moves(Some(" Frame ")) && dither_moves(Some("1")) && dither_moves(Some("x"))); + assert!(!dither_moves(Some("still")) && !dither_moves(Some("0")) && !dither_moves(Some("off"))); + assert!(!transparent_misses_estimated(None) && !transparent_misses_estimated(Some("title")) && !transparent_misses_estimated(Some("0"))); + assert!(!transparent_misses_estimated(Some("bound")), "another word: left as the title has them"); + assert!(transparent_misses_estimated(Some("estimate")) && transparent_misses_estimated(Some("1")) && transparent_misses_estimated(Some("on"))); + } + + /// The opaque layer's missed reflections are given the estimate; the transparent layer's only + /// with `XCL_AMBIENT_SPECULAR_ALPHA=estimate`; water's and any other never. + #[test] + fn the_transparent_layers_missed_reflections_are_left_unless_asked_for() { + assert!(miss_gets_estimate(0, false) && miss_gets_estimate(0, true), "opaque"); + assert!(!miss_gets_estimate(1, false), "transparent, by default: as the title has them"); + assert!(miss_gets_estimate(1, true), "transparent, with the switch"); + for layer in [2, 3, 7, u32::MAX] { + assert!(!miss_gets_estimate(layer, true) && !miss_gets_estimate(layer, false), "layer {layer}"); + } + } + + /// The fill's and the keep's constants hold the switches where their programs test them, and + /// the notes follow the level buffer's other parts in both programs. + #[test] + fn the_switches_reach_the_programs_in_their_constants() { + assert_eq!(fill_bits(false, false, false, 0), 0, "nothing on: as before"); + assert_eq!(fill_bits(true, true, false, 0), 3, "the sky and the title's light, as before"); + assert_eq!(fill_bits(true, false, true, 0), 0b101); + assert_eq!(fill_bits(false, false, false, 63), 63 << 8); + assert_eq!(fill_bits(true, true, true, 64 + 5), 7 | 5 << 8, "the round's place, 0 to 63"); + assert_eq!([keep_bits(false, false), keep_bits(true, false), keep_bits(false, true), keep_bits(true, true)], [0, 1, 2, 3]); + assert_eq!(ONCE_AT, 2 + 2 * 2304 + 3 * 14400); + assert_eq!(LEVEL_BUFFER_ELEMENTS, ONCE_AT + 25 * FRAME_CELLS.0 * FRAME_CELLS.1); + let define = format!("#define ONCE_AT {ONCE_AT}\n"); + assert!(FRAME_KEEP_HLSL.contains(&define) && LIGHT_COMMON_HLSL.contains(&define)); + for bit in ["(flags & 1u)", "(flags & 2u)"] { + assert!(FRAME_KEEP_HLSL.contains(bit), "{bit}"); + } + for bit in ["(sky_ready & 1u)", "(sky_ready & 2u)", "(sky_ready & 4u)", "(sky_ready >> 8) & 63u"] { + assert!(AMBIENT_FILL_R9G9B9E5_HLSL.contains(bit), "{bit}"); + } + } + + /// The keep's place (x, y) of cell `at` in a `size` picture, as FRAME_KEEP_HLSL finds it. + fn keep_texel(at: [u32; 2], xy: [u32; 2], size: [u32; 2]) -> [u32; 2] { + let one = |i: usize, cells: f32| (((at[i] as f32 + (xy[i] as f32 + 0.5) / 5.0) * size[i] as f32 / cells) as u32).min(size[i] - 1); + [one(0, 64.0), one(1, 36.0)] + } + + /// Where the fill notes texel `p` of a `size` picture (`keep_reads`): its place's index from + /// `ONCE_AT`, if the keep reads it. + fn noted_at(p: [u32; 2], size: [u32; 2]) -> Option { + let g = [(p[0] as f32 + 0.5) / size[0] as f32 * 64.0, (p[1] as f32 + 0.5) / size[1] as f32 * 36.0]; + let at = [(g[0] as u32).min(63), (g[1] as u32).min(35)]; + let xy = [(((g[0] - at[0] as f32) * 5.0) as u32).min(4), (((g[1] - at[1] as f32) * 5.0) as u32).min(4)]; + (keep_texel(at, xy, size) == p).then_some((at[1] * 64 + at[0]) * 25 + xy[1] * 5 + xy[0]) + } + + /// The fill notes every place the keep reads, each by the one texel the keep reads there, at + /// the sizes the title draws (and every texel of a picture too small for 5 x 5 places a cell); + /// both programs find a place in the same words. + #[test] + fn the_fill_notes_each_place_the_keep_reads() { + for size in [[640, 360], [1280, 720], [1920, 1080], [2560, 1440], [3840, 2160]] { + for i in 0..25 * FRAME_CELLS.0 * FRAME_CELLS.1 { + let (cell, place) = (i / 25, i % 25); + let p = keep_texel([cell % 64, cell / 64], [place % 5, place / 5], size); + assert_eq!(noted_at(p, size), Some(i), "{size:?}: place {place} of cell {cell} at {p:?}"); + } + } + let small: Vec = (0..64).filter_map(|i| noted_at([i % 8, i / 8], [8, 8])).collect(); + assert_eq!(small.len(), 64, "8x8: every texel is a place"); + for line in [ + "float2 at_texel = (float2(at.xy) + (float2(x, y) + 0.5) / 5.0) * float2(width, height) / float2(64.0, 36.0);", + "uint2 p = min(uint2(at_texel), uint2(width - 1, height - 1));", + "ONCE_AT + (at.y * 64 + at.x) * 25 + y * 5 + x", + ] { + assert!(FRAME_KEEP_HLSL.contains(line) && AMBIENT_FILL_R9G9B9E5_HLSL.contains(line), "{line}"); + } + } + + /// The interleaved-gradient noise the fill's shade turns its samples by, at texel `p` and the + /// round's place `phase`, as the programs take it. + fn ign(p: [f32; 2], phase: u32) -> f32 { + let shift = 5.588238 * phase as f32; + (52.9829189f32 * ((p[0] + shift) * 0.06711056 + (p[1] + shift) * 0.00583715).fract()).fract() + } + + /// With the dither moving, the noise at a texel takes another value each frame, all of [0, 1) + /// over the round of 64 frames, and comes back after it; still, it is the old pattern every + /// frame. The three programs that use it take it the same way, from the fill's constants. + #[test] + fn the_dither_moves_with_the_frame_and_comes_back_after_64() { + assert!((0..200).all(|f| dither_phase(f, false) == 0), "still"); + assert_eq!([0, 1, 63, 64, 130].map(|f| dither_phase(f, true)), [0, 1, 63, 0, 2]); + for p in [[0.0f32, 0.0], [3.0, 7.0], [100.0, 50.0], [1919.0, 1079.0]] { + let still = (52.9829189f32 * (p[0] * 0.06711056 + p[1] * 0.00583715).fract()).fract(); + assert_eq!(ign(p, 0), still, "place 0: the still pattern"); + let round: Vec = (0..64).map(|k| ign(p, k)).collect(); + let mean = round.iter().sum::() / 64.0; + assert!((mean - 0.5).abs() < 0.05, "{p:?}: mean over the round {mean}"); + assert!(round.iter().all(|v| (0.0..1.0).contains(v))); + assert!(round.iter().cloned().fold(1.0, f32::min) < 0.05 && round.iter().cloned().fold(0.0, f32::max) > 0.95, "{p:?}: all of [0, 1)"); + assert!(round.windows(2).all(|w| (w[0] - w[1]).abs() > 1e-3), "{p:?}: another value each frame"); + } + let moved = "dot(float2(p) + 5.588238 * float((sky_ready >> 8) & 63u), float2(0.06711056, 0.00583715))"; + assert!(AMBIENT_FILL_R9G9B9E5_HLSL.contains(moved)); + for program in [AMBIENT_FILL_HLSL, AMBIENT_FILL_WRITE_HLSL] { + assert!(program.contains(&moved.replace("float2(p)", "float2(tid)"))); + } + for program in [AMBIENT_FILL_HLSL, AMBIENT_FILL_WRITE_HLSL, AMBIENT_FILL_R9G9B9E5_HLSL] { + assert!(!program.contains("dot(float2(tid), float2(0.06711056") && !program.contains("dot(float2(p), float2(0.06711056"), "no still noise left"); + } + } + + /// The probes' garbage as the keep leaves it out with `XCL_AMBIENT_MEAN_CLEAN`. + fn probes_garbage(c: [f32; 3]) -> bool { + (c[1] < 0.5 * c[0].min(c[2]) && c[0].max(c[2]) > 0.02) || (c[2] > 2.5 * c[1] && c[2] > c[0] && c[2] > 0.02) + } + + /// The clean keep leaves out what the fill drops of the resolve's light, in the same words: + /// magenta and the bluer kind, not the sky's blue, a sunset, grey, or what is too dim to tell. + #[test] + fn the_clean_keep_leaves_out_what_the_fill_drops() { + assert!(probes_garbage([1.0, 0.1, 0.9]), "magenta"); + assert!(probes_garbage([0.05, 0.1, 0.6]), "the bluer kind"); + assert!(!probes_garbage([0.3, 0.45, 0.8]), "the sky's blue"); + assert!(!probes_garbage([1.0, 0.45, 0.15]), "a sunset"); + assert!(!probes_garbage([0.5, 0.5, 0.5]) && !probes_garbage([0.0; 3]), "grey, black"); + assert!(!probes_garbage([0.015, 0.0, 0.015]), "too dim to tell"); + assert!(!probes_garbage([0.2, 0.9, 0.1]) && !probes_garbage([1.0, 0.3, 0.1]), "green, orange"); + for test in ["c.g < 0.5 * min(c.r, c.b) && max(c.r, c.b) > 0.02", "c.b > 2.5 * c.g && c.b > c.r && c.b > 0.02"] { + assert!(FRAME_KEEP_HLSL.contains(test), "{test}"); + assert!(AMBIENT_FILL_R9G9B9E5_HLSL.contains(&test.replace("c.", "was.")), "the fill's: {test}"); + } + } + + /// The keep and the fill frame after frame on a room of surfaces that send out `albedo` of the + /// light they get – `direct` from lamps or the sun, which the resolve's light does not hold, and + /// the fill's – with the resolve leaving `title` on each (bounded by `MOST` 2 times the + /// estimate), every surface lit by `level` of the mean the keep counts (`counted`: of a + /// surface's light `sent`, given the fill's note there – the title's light and all of it – if + /// any): the estimate it settles at. + fn settle(level: f32, albedo: &[f32], direct: &[f32], title: &[f32], counted: impl Fn(f32, Option<(f32, f32)>) -> f32) -> f32 { + let mut noted: Vec> = vec![None; albedo.len()]; + let mut estimate = 0.0; + for _ in 0..1000 { + let sent = |i: usize| albedo[i] * (direct[i] + noted[i].map_or(0.0, |(_, all)| all)); + estimate = level * (0..albedo.len()).map(|i| counted(sent(i), noted[i])).sum::() / albedo.len() as f32; + for (i, note) in noted.iter_mut().enumerate() { + let was = title[i].min(2.0 * estimate); + *note = Some((was, was.max(estimate))); + } + } + estimate + } + + /// Without `XCL_AMBIENT_ONCE` the fill's light comes back to it: 1.9 times one bounce in a room + /// whose walls send out 0.6 of what they get, more by far with pale walls. With it, a little + /// under one bounce where a lamp lights a wall (its wall counted as if white: no more than the + /// fill added is taken out) – where the title's share of the light alone would count the lamp's + /// light out with the fill's, and leave nothing. Where the title's own light is above the + /// estimate (outdoors by day) nothing changes. + #[test] + fn once_is_one_bounce_and_keeps_what_the_lamps_give() { + let fed = |sent: f32, _: Option<(f32, f32)>| sent; + let once = |sent: f32, note: Option<(f32, f32)>| { + note.map_or(sent, |(title, all)| sent * (1.0 - (all - title).max(0.0) / all.max(sent).max(1e-6)).clamp(0.0, 1.0)) + }; + let share = |sent: f32, note: Option<(f32, f32)>| note.map_or(sent, |(title, all)| sent * (title / all.max(1e-6)).clamp(0.0, 1.0)); + // a room the rays leave dark: a lamp lights one of its two walls + let (walls, lamp, dark) = ([0.6, 0.6], [1.0, 0.0], [0.0, 0.0]); + let one_bounce = 0.8 * 0.6 * 0.5; + let fed_back = settle(0.8, &walls, &lamp, &dark, fed); + assert!((fed_back - one_bounce / (1.0 - 0.8 * 0.6)).abs() < 1e-4 && fed_back > 1.9 * one_bounce, "fed back: {fed_back}"); + let one = settle(0.8, &walls, &lamp, &dark, once); + assert!((one - one_bounce / (1.0 + 0.8 * 0.4 / 2.0)).abs() < 1e-4 && one > 0.85 * one_bounce, "once: {one}"); + assert!(settle(0.8, &walls, &lamp, &dark, share) < 1e-6, "the title's share alone: nothing left"); + let pale = [0.9, 0.9]; + assert!(settle(0.8, &pale, &lamp, &dark, fed) > 3.0 * settle(0.8, &pale, &lamp, &dark, once), "pale walls"); + let day = [1.0, 1.0]; + assert_eq!(settle(0.8, &walls, &day, &day, once), settle(0.8, &walls, &day, &day, fed), "by day"); + } + + /// R11G11B10_FLOAT of non-negative values (round to nearest), and back. + fn pack_r11g11b10(c: [f32; 3]) -> u32 { + let one = |v: f32, bits: u32| -> u32 { + if v <= 0.0 { + return 0; + } + let e = v.log2().floor() as i32; + let mut m = ((v / 2f32.powi(e) - 1.0) * (1 << bits) as f32).round() as u32; + let mut e = e + 15; + if m == 1 << bits { + m = 0; + e += 1; + } + assert!((1..31).contains(&e), "{v} out of the test's range"); + (e as u32) << bits | m + }; + one(c[0], 6) | one(c[1], 6) << 11 | one(c[2], 5) << 22 + } + + fn unpack_r11g11b10(v: u32) -> [f32; 3] { + let one = |x: u32, bits: u32| { + let (e, m) = (x >> bits, x & ((1 << bits) - 1)); + if e == 0 { m as f32 / (1 << bits) as f32 * 2f32.powi(-14) } else { (1.0 + m as f32 / (1 << bits) as f32) * 2f32.powi(e as i32 - 15) } + }; + [one(v & 0x7FF, 6), one((v >> 11) & 0x7FF, 6), one(v >> 22, 5)] + } + + /// After the miss program, a reflection that found nothing holds the light the points around + /// send along the reflected direction (here the same from everywhere: 0.1 of what surfaces + /// send out kept by the cells, the share 1 / 0.8 of it) instead of the sky's 20; where the + /// picture shows the sky it is left, and before any frame's light is kept so is all of it. + #[test] + fn missed_reflections_take_the_light_around_on_gpu() { + assert_eq!(pack_r11g11b10([20.0, 20.0, 20.0]), pack_r11g11b10(unpack_r11g11b10(pack_r11g11b10([20.0, 20.0, 20.0])))); + let sky = pack_r11g11b10([20.0, 20.0, 20.0]); + let texels = [sky; 64]; + // the top half 10 m away (depth is 0.1 m over the distance), the bottom half the sky + let mut depth = [0.0f32; 64]; + depth[..32].fill(0.01); + let mut level = vec![[0.0f32; 4]; LEVEL_ELEMENTS as usize]; + level[0] = [0.6, 0.6, 0.6, 0.6]; + level[1] = [0.1, 0.1, 0.1, 1.0]; + let cells = (FRAME_CELLS.0 * FRAME_CELLS.1) as usize; + level[2..2 + cells].fill([0.1, 0.1, 0.1, 1.0]); + level[2 + 2 * cells..].fill([0.0, 0.0, 0.0, 0.1]); + let share = Config::default().specular / Config::default().frame; + let consts = [8, 8, 8, 8, 1, share.to_bits(), 1, 0]; + let run = |level: &[[f32; 4]]| unsafe { run_on_image(|ad| &ad.miss_pso, DXGI_FORMAT_R11G11B10_FLOAT, false, Some(&depth), consts, &texels, level) }; + let Some(out) = run(&level) else { return }; + for (i, &v) in out.iter().enumerate() { + let c = unpack_r11g11b10(v); + if i < 32 { + // (within a step of the 5-bit blue mantissa: the store rounds toward zero) + assert!(c.iter().all(|&x| (x - 0.1 * share).abs() < 0.1 * share / 32.0), "texel {i}: {c:?} for {}", 0.1 * share); + } else { + assert_eq!(v, sky, "texel {i} shows the sky: left as it was"); + } + } + level[1][3] = 0.0; + let Some(out) = run(&level) else { return }; + assert!(out.iter().all(|&v| v == sky), "no frame's light kept: the image as the title has it"); + } + + /// R9G9B9E5 as the programs pack it. + fn pack_r9(c: [f32; 3]) -> u32 { + let c = c.map(|v| v.clamp(0.0, 65408.0)); + let top = c[0].max(c[1]).max(c[2]); + let mut e = (top.max(1e-9).log2().floor() as i32 + 16).clamp(0, 31); + let mut scale = 2f32.powi(24 - e); + if top * scale >= 511.5 { + e = (e + 1).min(31); + scale = 2f32.powi(24 - e); + } + let m = c.map(|v| ((v * scale + 0.5) as u32).min(511)); + m[0] | m[1] << 9 | m[2] << 18 | (e as u32) << 27 + } + + fn unpack_r9(v: u32) -> [f32; 3] { + let s = 2f32.powi((v >> 27) as i32 - 24); + [(v & 511) as f32 * s, ((v >> 9) & 511) as f32 * s, ((v >> 18) & 511) as f32 * s] + } + + fn luma(c: [f32; 3]) -> f32 { + 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2] + } + + /// One dispatch of an ambient program (`pick`) over an 8x8 R32_UINT image holding `texels`, + /// with the level buffer holding `level` and the root constants `consts`; the image after it. + /// `t0` is the indirect arguments' raw buffer (`raw_t0`) or a depth. None (skipped) without a + /// D3D12 device. + unsafe fn run_on_r9_image( + pick: impl Fn(&AmbientDevice) -> &ID3D12PipelineState, + raw_t0: bool, + consts: [u32; 8], + texels: &[u32; 64], + level: &[[f32; 4]], + ) -> Option<[u32; 64]> { + run_on_image(pick, DXGI_FORMAT_R32_UINT, raw_t0, None, consts, texels, level) + } + + /// `run_on_r9_image` with an image of `format` (32 bits a texel) and, given `depth`, an 8x8 + /// R32_FLOAT depth holding it at `t0`. + unsafe fn run_on_image( + pick: impl Fn(&AmbientDevice) -> &ID3D12PipelineState, + format: DXGI_FORMAT, + raw_t0: bool, + depth: Option<&[f32; 64]>, + consts: [u32; 8], + texels: &[u32; 64], + level: &[[f32; 4]], + ) -> Option<[u32; 64]> { + assert_eq!(level.len(), LEVEL_ELEMENTS as usize); + let mut whole = level.to_vec(); + whole.resize(LEVEL_BUFFER_ELEMENTS as usize, [0.0; 4]); + run_with_level(pick, format, raw_t0, depth, consts, texels, &whole).map(|(image, _)| image) + } + + /// `run_on_image` with the whole level buffer (`XCL_AMBIENT_ONCE`'s notes too) given and read + /// back after the dispatch. + unsafe fn run_with_level( + pick: impl Fn(&AmbientDevice) -> &ID3D12PipelineState, + format: DXGI_FORMAT, + raw_t0: bool, + depth: Option<&[f32; 64]>, + consts: [u32; 8], + texels: &[u32; 64], + level: &[[f32; 4]], + ) -> Option<([u32; 64], Vec<[f32; 4]>)> { + assert_eq!(level.len(), LEVEL_BUFFER_ELEMENTS as usize); + let mut dev: Option = None; + if D3D12CreateDevice(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return None; + } + let dev = dev.unwrap(); + let dev_raw = dev.as_raw(); + real::adopt(dev_raw, real::Kind::Device); + let ad = build_device(&dev).expect("build_device must succeed"); + + type CreateResFn = unsafe extern "system" fn( + *mut c_void, + *const D3D12_HEAP_PROPERTIES, + D3D12_HEAP_FLAGS, + *const D3D12_RESOURCE_DESC, + D3D12_RESOURCE_STATES, + *const D3D12_CLEAR_VALUE, + *const c_void, + *mut *mut c_void, + ) -> i32; + let create_res: CreateResFn = std::mem::transmute(real::orig_fn(dev_raw, 27)); + let make = |ty: D3D12_HEAP_TYPE, rd: &D3D12_RESOURCE_DESC, init: D3D12_RESOURCE_STATES| -> ID3D12Resource { + let hp = D3D12_HEAP_PROPERTIES { Type: ty, ..Default::default() }; + let mut raw = std::ptr::null_mut(); + let hr = create_res(dev_raw, &hp, D3D12_HEAP_FLAG_NONE, rd, init, std::ptr::null(), &ID3D12Resource::IID as *const _ as *const c_void, &mut raw); + assert!(hr >= 0 && !raw.is_null(), "CreateCommittedResource: {hr:#x}"); + ID3D12Resource::from_raw(raw) + }; + let buffer = |bytes: u64| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + const PITCH: usize = 256; + let level_bytes = LEVEL_BUFFER_ELEMENTS as usize * 16; + let image_at = level_bytes.next_multiple_of(512); + let depth_at = image_at + 8 * PITCH; + let upload = make(D3D12_HEAP_TYPE_UPLOAD, &buffer((depth_at + 8 * PITCH) as u64), D3D12_RESOURCE_STATE_GENERIC_READ); + let readback = make(D3D12_HEAP_TYPE_READBACK, &buffer((8 * PITCH) as u64), D3D12_RESOURCE_STATE_COPY_DEST); + let level_readback = make(D3D12_HEAP_TYPE_READBACK, &buffer(level_bytes as u64), D3D12_RESOURCE_STATE_COPY_DEST); + let image = make( + D3D12_HEAP_TYPE_DEFAULT, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let depth_image = depth.map(|_| { + make( + D3D12_HEAP_TYPE_DEFAULT, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + ) + }); + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::copy_nonoverlapping(level.as_ptr() as *const u8, p as *mut u8, level_bytes); + for y in 0..8 { + std::ptr::copy_nonoverlapping(texels[y * 8..].as_ptr(), (p as *mut u8).add(image_at + y * PITCH) as *mut u32, 8); + if let Some(depth) = depth { + std::ptr::copy_nonoverlapping(depth[y * 8..].as_ptr(), (p as *mut u8).add(depth_at + y * PITCH) as *mut f32, 8); + } + } + upload.Unmap(0, None); + + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let list_raw = list.as_raw(); + real::adopt(list_raw, real::Kind::CommandList); + list_x::on_create(list_raw, alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + + let copy_buffer: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, *mut c_void, u64, u64) = std::mem::transmute(real::orig_fn(list_raw, 15)); + copy_buffer(list_raw, ad.sky_level.as_raw(), 0, upload.as_raw(), 0, level_bytes as u64); + list_x::transition(list_raw, ad.sky_level.as_raw() as usize, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + let footprint_of = |offset: usize, format: DXGI_FORMAT| D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: offset as u64, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: format, Width: 8, Height: 8, Depth: 1, RowPitch: PITCH as u32 }, + }; + let footprint = |offset: usize| footprint_of(offset, format); + let in_image = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&image), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let in_upload = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&upload), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(image_at) }, + }; + let in_readback = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(0) }, + }; + list_x::pc_copy_texture_region(list_raw, &in_image, 0, 0, 0, &in_upload, std::ptr::null()); + list_x::transition(list_raw, image.as_raw() as usize, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + if let Some(d) = &depth_image { + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(d), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&upload), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint_of(depth_at, DXGI_FORMAT_R32_FLOAT) }, + }; + list_x::pc_copy_texture_region(list_raw, &to, 0, 0, 0, &from, std::ptr::null()); + list_x::transition(list_raw, d.as_raw() as usize, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + } + + let (cpu0, gpu0) = ad.alloc_group(); + let inc = ad.inc as u64; + type CreateSrvFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, usize); + type CreateUavFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + let create_srv: CreateSrvFn = std::mem::transmute(real::orig_fn(dev_raw, 18)); + let create_uav: CreateUavFn = std::mem::transmute(real::orig_fn(dev_raw, 19)); + let (t0, t0_view) = if raw_t0 { + ( + ad.dummy_indirect.as_raw(), + D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { FirstElement: 0, NumElements: 4, StructureByteStride: 0, Flags: D3D12_BUFFER_SRV_FLAG_RAW }, + }, + }, + ) + } else { + ( + depth_image.as_ref().map_or(ad.dummy_depth.as_raw(), |d| d.as_raw()), + D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_FLOAT, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() } }, + }, + ) + }; + let image_uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: format, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 } }, + }; + let level_uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: LEVEL_BUFFER_ELEMENTS, StructureByteStride: 16, ..Default::default() }, + }, + }; + create_srv(dev_raw, t0, &t0_view, cpu0 as usize); + create_uav(dev_raw, image.as_raw(), std::ptr::null_mut(), &image_uav, (cpu0 + inc) as usize); + create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + 2 * inc) as usize); + + let heap_raw = ad.heap.as_raw() as usize; + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list_raw, 28)); + let set_cs_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list_raw, 29)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list_raw, 25)); + let set_cs_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(real::orig_fn(list_raw, 31)); + let set_cs_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(real::orig_fn(list_raw, 35)); + let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list_raw, 14)); + set_heaps(list_raw, 1, &heap_raw); + set_cs_rs(list_raw, ad.rs.as_raw()); + set_pso(list_raw, pick(&ad).as_raw()); + set_cs_consts(list_raw, 0, 8, consts.as_ptr(), 0); + set_cs_table(list_raw, 1, gpu0); + set_cs_table(list_raw, 2, gpu0 + inc); + dispatch(list_raw, 1, 1, 1); + list_x::transition(list_raw, image.as_raw() as usize, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list_x::pc_copy_texture_region(list_raw, &in_readback, 0, 0, 0, &in_image, std::ptr::null()); + list_x::transition(list_raw, ad.sky_level.as_raw() as usize, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + copy_buffer(list_raw, level_readback.as_raw(), 0, ad.sky_level.as_raw(), 0, level_bytes as u64); + list.Close().unwrap(); + + let cl: ID3D12CommandList = list.cast().unwrap(); + q.ExecuteCommandLists(&[Some(cl)]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let ev = windows::Win32::System::Threading::CreateEventW(None, false, false, None).unwrap(); + q.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, ev).unwrap(); + windows::Win32::System::Threading::WaitForSingleObject(ev, 5000); + let _ = windows::Win32::Foundation::CloseHandle(ev); + assert_eq!(fence.GetCompletedValue(), 1, "the ambient program must complete (device removed: {:?})", dev.GetDeviceRemovedReason()); + + let mut out = [0u32; 64]; + let mut r = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut r)).unwrap(); + for y in 0..8 { + std::ptr::copy_nonoverlapping((r as *const u8).add(y * PITCH) as *const u32, out[y * 8..].as_mut_ptr(), 8); + } + readback.Unmap(0, None); + let mut level_out = vec![[0.0f32; 4]; LEVEL_BUFFER_ELEMENTS as usize]; + level_readback.Map(0, None, Some(&mut r)).unwrap(); + std::ptr::copy_nonoverlapping(r as *const u8, level_out.as_mut_ptr() as *mut u8, level_bytes); + level_readback.Unmap(0, None); + Some((out, level_out)) + } + + /// A reflection far brighter than the room is held to `hold` times the light around (the + /// four gathered points about it, a fifth of it the slow mean), its hue kept; a dim one is + /// left as it was. With no points gathered the cells under it stand for them, and with the + /// hold off the sky's cap alone holds it. + #[test] + fn reflections_are_held_to_the_light_around_on_gpu() { + let bright = pack_r9([4.0, 2.0, 1.0]); + let dim = pack_r9([0.05, 0.05, 0.05]); + let mut texels = [dim; 64]; + texels[..32].fill(bright); + let mut level = vec![[0.0f32; 4]; LEVEL_ELEMENTS as usize]; + // the sky's level, the cells' slow mean, the cells, and the points (each colour's mean) + level[0] = [0.6, 0.6, 0.6, 0.6]; + level[1] = [0.05, 0.05, 0.05, 1.0]; + let cells = (FRAME_CELLS.0 * FRAME_CELLS.1) as usize; + level[2..2 + cells].fill([0.05, 0.05, 0.05, 1.0]); + let gathered = |level: &mut [[f32; 4]], light: f32| level[2 + 2 * cells..].fill([0.0, 0.0, 0.0, light]); + gathered(&mut level, 0.1); + let consts = |hold: f32| [8, 8, 0, 0, 0, 0.5f32.to_bits(), hold.to_bits(), 0]; + let run = |hold: f32, level: &[[f32; 4]]| unsafe { run_on_r9_image(|ad| &ad.reflect_r9_pso, true, consts(hold), &texels, level) }; + let check = |out: &[u32; 64], bright_lum: f32| { + let (b, d) = (unpack_r9(out[0]), unpack_r9(out[63])); + assert!((luma(b) - bright_lum).abs() < 0.02 * bright_lum, "bright reflection {b:?}, its light {} for {bright_lum}", luma(b)); + assert!((b[0] / b[1] - 2.0).abs() < 0.05 && (b[1] / b[2] - 2.0).abs() < 0.05, "hue kept: {b:?}"); + assert!((luma(d) - 0.05).abs() < 0.001, "dim reflection left: {d:?}"); + assert!(out[..32].iter().all(|&v| v == out[0]) && out[32..].iter().all(|&v| v == out[63])); + }; + let Some(held) = run(1.25, &level) else { return }; + // 1.25 x (0.1 at the points, a fifth of it the mean of 0.05) + check(&held, 1.25 * 0.09); + let Some(sky_only) = run(0.0, &level) else { return }; + // XCL_AMBIENT_REFLECT 0.5 x the sky's 0.6 + check(&sky_only, 0.5 * 0.6); + gathered(&mut level, 0.0); + let Some(by_cells) = run(1.25, &level) else { return }; + // no points: 1.25 x the cells under it (0.05, a fifth of it the mean of 0.05) + check(&by_cells, 1.25 * 0.05); + } + + /// What the diffuse resolve left is dropped where it is the probes' blue garbage (blue far + /// above green and above red), dim enough that the bound by the estimate keeps it, and kept + /// where it is the sky's blue light (bounded, its hue kept). + #[test] + fn the_resolves_blue_garbage_is_dropped_on_gpu() { + let cfg = config(); + let garbage = [0.05, 0.1, 0.6]; + let sky_blue = [0.3, 0.45, 0.8]; + let mut texels = [pack_r9(sky_blue); 64]; + texels[..32].fill(pack_r9(garbage)); + // the sky's level only: no frame's light kept yet (the mean's fourth part 0), no depth + let mut level = vec![[0.0f32; 4]; LEVEL_ELEMENTS as usize]; + level[0] = [0.2, 0.2, 0.2, 0.2]; + // the title's light kept (sky_ready bit 1), the sky captured (bit 0) + let consts = [8, 8, 1, 1, 0, cfg.ao.to_bits(), 3, PRE_SKY_FALLBACK.to_bits()]; + let Some(out) = (unsafe { run_on_r9_image(|ad| &ad.fill_r9_pso, false, consts, &texels, &level) }) else { return }; + let found = 0.2 * cfg.sky; + // the garbage was under the bound (MOST times the estimate) all the same + assert!(luma(garbage) < found * cfg.most, "the test needs garbage the bound keeps"); + let g = unpack_r9(out[0]); + assert!(g.iter().all(|&c| (c - found).abs() < 0.01 * found + 1e-4), "garbage dropped, the estimate left: {g:?} for {found}"); + let s = unpack_r9(out[63]); + assert!((luma(s) - found * cfg.most).abs() < 0.02 * found * cfg.most, "sky light bounded: {s:?}"); + assert!((s[2] / s[1] - sky_blue[2] / sky_blue[1]).abs() < 0.05, "sky light keeps its hue: {s:?}"); + } + + /// The fill's shade turns its samples by the noise: a crease is shaded, otherwise at another + /// place of the dither's round, the same at the same place. + #[test] + fn the_shade_moves_with_the_dither_on_gpu() { + // a wall 1 m away, its right half 0.5 m away: the far side of the step is shaded + let mut depth = [0.1f32; 64]; + for row in depth.chunks_mut(8) { + row[4..].fill(0.2); + } + let mut level = vec![[0.0f32; 4]; LEVEL_ELEMENTS as usize]; + level[0] = [0.2, 0.2, 0.2, 0.2]; + let consts = |phase: u32| [8, 8, 8, 8, 1, 0.55f32.to_bits(), fill_bits(true, false, false, phase), PRE_SKY_FALLBACK.to_bits()]; + let run = |phase: u32| unsafe { run_on_image(|ad| &ad.fill_r9_pso, DXGI_FORMAT_R32_UINT, false, Some(&depth), consts(phase), &[0; 64], &level) }; + let Some(still) = run(0) else { return }; + // (unshaded: the sky's share, nothing else lights it) + let unshaded = 0.2 * config().sky; + assert!(still.iter().any(|&v| luma(unpack_r9(v)) < 0.95 * unshaded), "the step shades: {:?}", still.map(|v| luma(unpack_r9(v)))); + let Some(again) = run(0) else { return }; + assert_eq!(still, again, "the same place of the round: the same shade"); + let Some(moved) = run(1) else { return }; + assert_ne!(still, moved, "the next place: the samples turned"); + } + + /// With `XCL_AMBIENT_ONCE` the fill notes, at each place the keep reads, the luminance of the + /// title's light it left there (bounded by the estimate) and of all it wrote; without, nothing. + #[test] + fn the_fill_notes_its_light_where_the_keep_reads_on_gpu() { + let cfg = config(); + // the sky's level only (no frame's light kept yet, no depth): the estimate is its share + let mut level = vec![[0.0f32; 4]; LEVEL_BUFFER_ELEMENTS as usize]; + level[0] = [0.2, 0.2, 0.2, 0.2]; + let found = 0.2 * cfg.sky; + // the title left a little on the top half, more than the bound lets through below + let (little, much) = (pack_r9([0.02; 3]), pack_r9([0.5; 3])); + let mut texels = [much; 64]; + texels[..32].fill(little); + let consts = |once: bool| [8, 8, 1, 1, 0, cfg.ao.to_bits(), fill_bits(true, true, once, 0), PRE_SKY_FALLBACK.to_bits()]; + let run = |once: bool| unsafe { run_with_level(|ad| &ad.fill_r9_pso, DXGI_FORMAT_R32_UINT, false, None, consts(once), &texels, &level) }; + let Some((_, noted)) = run(true) else { return }; + for i in 0..64u32 { + let p = [i % 8, i / 8]; + let at = noted_at(p, [8, 8]).expect("every texel of an 8x8 picture is a place the keep reads"); + let n = noted[(ONCE_AT + at) as usize]; + let (title, all) = if i < 32 { (luma(unpack_r9(little)), found) } else { (found * cfg.most, found * cfg.most) }; + assert!((n[0] - title).abs() < 0.01 * title && (n[1] - all).abs() < 0.01 * all, "texel {p:?}: {n:?} for ({title}, {all})"); + } + assert_eq!(noted[ONCE_AT as usize..].iter().filter(|n| n[1] > 0.0).count(), 64, "one note a texel"); + let Some((_, none)) = run(false) else { return }; + assert!(none[ONCE_AT as usize..].iter().all(|n| *n == [0.0; 4]), "off: nothing noted"); + } + + /// The keep with `XCL_AMBIENT_ONCE` takes the fill's light out of what each place sent back: + /// all of it where the place sent no more than the fill gave it, what the fill added where it + /// sent more (a lamp lit it too), nothing where nothing was noted. With + /// `XCL_AMBIENT_MEAN_CLEAN` the probes' garbage is no light; with neither the cells are kept + /// as before. + #[test] + fn the_keep_leaves_out_the_fills_light_and_the_garbage_on_gpu() { + // (it reads the light, R11G11B10_FLOAT, from a UAV) + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + if !unsafe { typed_uav_load_supported(dev.as_ref().unwrap(), DXGI_FORMAT_R11G11B10_FLOAT) } { + crate::gpu::recomp::runner::skip_test("no typed UAV loads of R11G11B10_FLOAT"); + return; + } + // an 8x8 picture: the cells (0..8, 0..4) read its first texel, the cells (0..8, 5..8) the + // first of its second row + let magenta = [1.0, 0.0625, 1.0]; + let mut texels = [pack_r11g11b10([0.25; 3]); 64]; + texels[0] = pack_r11g11b10([0.5; 3]); + texels[8] = pack_r11g11b10(magenta); + let mut level = vec![[0.0f32; 4]; LEVEL_BUFFER_ELEMENTS as usize]; + for (cell, title, all) in [(0u32, 0.0f32, 1.0f32), (1, 0.5, 1.0), (2, 0.0, 0.1)] { + let at = (ONCE_AT + cell * 25) as usize; + level[at..at + 25].fill([title, all, 0.0, 0.0]); + } + let run = |once: bool, clean: bool| unsafe { + run_with_level(|ad| &ad.keep_pso, DXGI_FORMAT_R11G11B10_FLOAT, false, None, [8, 8, keep_bits(once, clean), 0, 0, 1.0f32.to_bits(), 0, 0], &texels, &level) + }; + let cell = |level: &[[f32; 4]], x: u32, y: u32| level[2 + (y * 64 + x) as usize]; + let grey = |c: [f32; 4], v: f32| (0..3).all(|k| (c[k] - v).abs() < 1e-4) && c[3] == 1.0; + let is = |c: [f32; 4], v: [f32; 3]| (0..3).all(|k| (c[k] - v[k]).abs() < 1e-4); + let Some((_, once)) = run(true, false) else { return }; + // none of it the title's; half of it; the fill's 0.1 of the lamp-lit 0.5; no note + for (x, v) in [(0, 0.0), (1, 0.25), (2, 0.4), (3, 0.5)] { + assert!(grey(cell(&once, x, 0), v), "cell {x}: {:?} for {v}", cell(&once, x, 0)); + } + assert!(is(cell(&once, 0, 5), magenta), "garbage kept without the clean keep: {:?}", cell(&once, 0, 5)); + let Some((_, clean)) = run(false, true) else { return }; + assert!((0..4).all(|x| grey(cell(&clean, x, 0), 0.5)), "notes not read without one bounce"); + assert!(grey(cell(&clean, 0, 5), 0.0), "garbage: no light, {:?}", cell(&clean, 0, 5)); + let Some((_, neither)) = run(false, false) else { return }; + assert!((0..4).all(|x| grey(cell(&neither, x, 0), 0.5)) && is(cell(&neither, 0, 5), magenta), "as before"); + } + + #[test] + fn scan_cbv_indices_resolves_each_64k_mirror_page_independently() { + const PAGE: usize = crate::hle::kernelx::mirrors::PAGE; + // Backing page 0 sits right before a readable decoy slice; backing page 1 is separate. + let mut backing0_and_decoy = vec![0u32; 128]; + backing0_and_decoy[0] = 101_001; // sentinel in page 0 (last 256 B of GPU page 0) + backing0_and_decoy[64] = 999_999; // decoy immediately after backing 0 (must NEVER be read) + let mut backing1 = vec![0u32; 64]; + backing1[0] = 202_002; // sentinel in page 1 (first 256 B of GPU page 1) + + let gpu_page0 = 0x5000_0000usize; + let gpu_page1 = gpu_page0 + PAGE; + let cbv_start = gpu_page0 + (PAGE - 256); // 0xff00: spans 256 B on page 0 + 256 B on page 1 + let p0_base = backing0_and_decoy.as_ptr() as usize; + let p1_base = backing1.as_ptr() as usize; + + let mut seen = Vec::new(); + unsafe { + scan_cbv_indices_with( + cbv_start, + 512, + |va| { + if va >= gpu_page0 && va < gpu_page1 { + p0_base + (va - cbv_start) + } else if va >= gpu_page1 && va < gpu_page1 + 256 { + p1_base + (va - gpu_page1) + } else { + 0 + } + }, + &mut |v| seen.push(v), + ); + } + assert!(seen.contains(&101_001), "first 64 KiB page sentinel must be read"); + assert!(seen.contains(&202_002), "second 64 KiB page sentinel must be resolved independently"); + assert!(!seen.contains(&999_999), "readable decoy past backing 0 must never be read across 64 KiB boundary"); + assert_eq!(resolve_cbv_va(0), 0); + assert_eq!(resolve_cbv_va(p1_base), p1_base); + } + + #[test] + fn ambient_sky_reduce_runs_cleanly_on_gpu() { + unsafe { + if std::env::var_os("XCL_D3D12_DEBUG").is_some() { + let mut dbg: Option = None; + if D3D12GetDebugInterface(&mut dbg).is_ok() { + if let Some(d) = dbg { + d.EnableDebugLayer(); + } + } + } + let mut dev: Option = None; + if D3D12CreateDevice(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + return; + } + let dev = dev.unwrap(); + let dev_raw = dev.as_raw(); + real::adopt(dev_raw, real::Kind::Device); + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let list_raw = list.as_raw(); + real::adopt(list_raw, real::Kind::CommandList); + list_x::on_create(list_raw, alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + + // Create a 128x128 RGBA16F render target (sky dome) in RENDER_TARGET state. + let rt_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut rt: Option = None; + dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rt_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, None, &mut rt).unwrap(); + let rt = rt.unwrap(); + + let ad = build_device(&dev).expect("build_device must succeed"); + let sky_raw = ad.sky_copy.as_raw() as usize; + let rt0 = rt.as_raw() as usize; + list_x::transition(list_raw, rt0, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + list_x::transition(list_raw, sky_raw, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST); + list_x::pc_copy_resource(list_raw, sky_raw, rt0); + list_x::transition(list_raw, sky_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list_x::transition(list_raw, rt0, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + + let (cpu0, gpu0) = ad.alloc_group(); + let inc = ad.inc as u64; + type CreateSrvFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, usize); + type CreateUavFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + let create_srv: CreateSrvFn = std::mem::transmute(real::orig_fn(dev_raw, 18)); + let create_uav: CreateUavFn = std::mem::transmute(real::orig_fn(dev_raw, 19)); + let sky_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() }, + }, + }; + let level_uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: 1, StructureByteStride: 16, ..Default::default() }, + }, + }; + create_srv(dev_raw, ad.sky_copy.as_raw(), &sky_srv, cpu0 as usize); + create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + inc) as usize); + create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + 2 * inc) as usize); + + let heap_raw = ad.heap.as_raw() as usize; + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list_raw, 28)); + let set_cs_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list_raw, 29)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list_raw, 25)); + let set_cs_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(real::orig_fn(list_raw, 31)); + let set_cs_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(real::orig_fn(list_raw, 35)); + let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list_raw, 14)); + let consts = [0.22f32.to_bits(), 0.65f32.to_bits(), 0.02f32.to_bits(), 1.0f32.to_bits(), 0, 0, 0, 0]; + set_heaps(list_raw, 1, &heap_raw); + set_cs_rs(list_raw, ad.rs.as_raw()); + set_pso(list_raw, ad.reduce_pso.as_raw()); + set_cs_consts(list_raw, 0, 8, consts.as_ptr(), 0); + set_cs_table(list_raw, 1, gpu0); + set_cs_table(list_raw, 2, gpu0 + inc); + dispatch(list_raw, 1, 1, 1); + uav_barrier(list_raw, ad.sky_level.as_raw() as usize); + list.Close().unwrap(); + + let cl: ID3D12CommandList = list.cast().unwrap(); + q.ExecuteCommandLists(&[Some(cl)]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let ev = windows::Win32::System::Threading::CreateEventW(None, false, false, None).unwrap(); + q.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, ev).unwrap(); + windows::Win32::System::Threading::WaitForSingleObject(ev, 5000); + let _ = windows::Win32::Foundation::CloseHandle(ev); + assert_eq!(fence.GetCompletedValue(), 1, "ambient sky_reduce GPU dispatch must complete cleanly (device removed: {:?})", dev.GetDeviceRemovedReason()); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/barrier_groups.rs b/crates/xcl/src/hle/d3d12x/barrier_groups.rs index 9be8840450..5ecc7e8960 100644 --- a/crates/xcl/src/hle/d3d12x/barrier_groups.rs +++ b/crates/xcl/src/hle/d3d12x/barrier_groups.rs @@ -270,6 +270,16 @@ struct Tracked { plane_stride: u32, } +/// Cached texture geometry/flags for a live `ID3D12Resource`, cleared in `forget(res)` when the +/// resource's last reference is released (`real::res_release`). Avoids `shader::readable` +/// (`K32QueryWorkingSetEx`) and COM `GetDesc()` on every texture barrier. +#[derive(Clone, Copy)] +struct CachedDesc { + tex: Option<(bool, u32, u32, u32, Asked)>, +} + +static DESC_CACHE: Sharded = Sharded::new(); + /// The per-plane state each texture was last moved to by a barrier group (the title's recording order). static LAST: Sharded = Sharded::new(); /// Texture barriers read, and transitions made of them. @@ -298,11 +308,46 @@ pub(super) fn note_legacy_state(res: usize, sub: u32, after: u32) { /// The last reference of `res` goes (`real::res_release`). pub(super) fn forget(res: usize) { + DESC_CACHE.remove(res); if COUNTS[0].load(Ordering::Relaxed) != 0 { LAST.remove(res); } } +/// Cached texture descriptor lookup (None for buffers or unreadable pointers). +unsafe fn cached_desc(res: usize) -> Option<(bool, u32, u32, u32, Asked)> { + if let Some(c) = DESC_CACHE.get(res) { + return c.tex; + } + if !crate::gpu::shader::readable(res, 8) { + return None; + } + let r = res as *mut c_void; + let d = ID3D12Resource::from_raw_borrowed(&r)?.GetDesc(); + let tex = if d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + None + } else { + let depth = d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0; + let array = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { d.DepthOrArraySize as u32 }; + // (two planes: the depth-stencil formats R32G8X24 and R24G8 and their views) + let planes = if matches!(d.Format.0, 19..=22 | 44..=47) { 2 } else { 1 }; + let asked = Asked { flags: d.Flags.0 as u32, subresources: d.MipLevels as u32 * array * planes, format: d.Format.0 }; + Some((depth, d.MipLevels as u32, array, planes, asked)) + }; + if super::real::is_adopted(r) { + DESC_CACHE.insert(res, CachedDesc { tex }); + } + tex +} + +/// Fast cached `Dimension == BUFFER` check for `list_x::resource_barrier_x`. +pub(super) unsafe fn is_buffer_cached(res: usize) -> bool { + if res == 0 { + return true; + } + cached_desc(res).is_none() +} + /// `state` as a texture with the PC resource flags `flags` (D3D12_RESOURCE_FLAGS) can be in it on /// a direct list (`direct`) or a compute one: the reading states the texture or the list cannot /// have are left out of it. None: it cannot be there at all (a render target state of a texture @@ -376,22 +421,11 @@ pub(super) unsafe fn transitions(n: u32, groups: *const c_void, direct: bool) -> let mut out = transitions_of( &textures, &mut |res| { - if !crate::gpu::shader::readable(res, 8) { - return None; - } - let r = res as *mut c_void; - let d = ID3D12Resource::from_raw_borrowed(&r)?.GetDesc(); - if d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { - return None; - } - let depth = d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0; - let array = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { d.DepthOrArraySize as u32 }; - // (two planes: the depth-stencil formats R32G8X24 and R24G8 and their views) - let planes = if matches!(d.Format.0, 19..=22 | 44..=47) { 2 } else { 1 }; - if !asked.iter().any(|a| a.0 == res) { - asked.push((res, Asked { flags: d.Flags.0 as u32, subresources: d.MipLevels as u32 * array * planes, format: d.Format.0 })); + let (depth, mips, array, planes, a) = cached_desc(res)?; + if !asked.iter().any(|x| x.0 == res) { + asked.push((res, a)); } - Some((depth, d.MipLevels as u32, array, planes)) + Some((depth, mips, array, planes)) }, &mut |res| LAST.get(res).map_or([None, None], |t| t.states), &mut |res, plane, state, stride| { diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 62d5549b14..4f91ea091c 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -69,6 +69,9 @@ struct State { batch_buf: Option, batch_used: u64, batch_open: bool, + /// the textures this recording's bake draws pick by index, for its submit + /// (`bake_sources`, `title_textures::bake_at_submit`) + bake_sources: Vec, } /// A recording's blocks of rewritten indirect arguments, and most bytes of them (past it, its @@ -244,6 +247,7 @@ impl TwoPassBuf { } }; note_two_pass(TP_MADE); + super::real::note_va("two-pass buffer", res.GetGPUVirtualAddress(), bytes, false); Ok(Some(TwoPassBuf { res, bytes, dev: dev.as_raw() as usize })) } } @@ -320,6 +324,7 @@ impl Drop for TwoPassBuf { fn drop(&mut self) { TWO_PASS[TP_ALIVE].fetch_sub(self.bytes, Ordering::Relaxed); note_two_pass(TP_GONE); + super::real::note_va("two-pass buffer", unsafe { self.res.GetGPUVirtualAddress() }, self.bytes, true); } } @@ -405,24 +410,43 @@ fn hold_res_until_reset(allocator: usize, mut bufs: Vec) { ALLOC_RES.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().append(&mut bufs); } -fn put_free_bufs(bufs: Vec) { +/// `bufs` the GPU is done with, kept in `FREE_RES` for the recordings that need one next: at once +/// when the submit fences of their recording passed (`exact`), else after `free_hold`. +fn put_free_bufs(bufs: Vec, exact: bool) { if bufs.is_empty() { return; } let free_cap = two_pass_cap().min(FREE_RES_CAP); + let hold = free_hold(exact, console_list::retire_age()); let gone = { let mut free = FREE_RES.lock().unwrap(); free.cap = free_cap; let now = std::time::Instant::now(); let mut gone = free.take_idle(now, FREE_RES_IDLE); for b in bufs { - gone.extend(free.put(now, b.bytes, b.dev, b)); + gone.extend(free.put_held(now, hold, b.bytes, b.dev, b)); } gone }; drop(gone); } +/// How long a two-pass buffer handed back to `FREE_RES` waits before a recording takes it again. +/// None when the submit fences of the recording that used it passed (`exact`, `FENCED_RES`): the +/// GPU is done with it. `retire` (`console_list::retire_age`) when an allocator reset or the time +/// in `UNKNOWN_RES` says so: that bookkeeping misses a submit now and then. +/// +/// (A hold for every buffer, with the idle ones let go `FREE_RES_IDLE` after they were handed back, +/// let them go just as they could be taken: with both at 2 s next to nothing was taken again, and +/// the two-pass buffers alive stood at the cap with half of them kept for reuse.) +fn free_hold(exact: bool, retire: std::time::Duration) -> std::time::Duration { + if exact { + std::time::Duration::ZERO + } else { + retire + } +} + const FENCE_WAIT_LIMIT: std::time::Duration = std::time::Duration::from_millis(10); const FENCE_WAIT_RESCAN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(1); const FENCE_WAIT_YIELD_POLLS: u32 = 64; @@ -607,7 +631,7 @@ fn retire_recording_res(allocator: usize, bufs: Vec, marks: Vec<(usi if !untracked && !marks.is_empty() { let marks: Vec<(ID3D12Fence, u64)> = marks.into_iter().map(|(_, f, v)| (f, v)).collect(); if marks.iter().all(|(f, v)| unsafe { fence_state(f, *v) == FenceState::Completed }) { - put_free_bufs(bufs); + put_free_bufs(bufs, true); return; } let bytes: u64 = bufs.iter().map(|b| b.bytes).sum(); @@ -645,7 +669,7 @@ fn reclaim_fenced() -> u64 { WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); } } - put_free_bufs(reclaimed_bufs); + put_free_bufs(reclaimed_bufs, true); reclaimed } @@ -658,7 +682,8 @@ pub(super) fn release_allocator_res(allocator: usize) { let gone = FREE_RES.lock().unwrap().take_idle(std::time::Instant::now(), FREE_RES_IDLE); drop(gone); } else { - put_free_bufs(bufs); + // (an allocator reset, or time, says the GPU is done with them: `free_hold`) + put_free_bufs(bufs, false); } } @@ -727,11 +752,12 @@ impl Aging { static UNKNOWN_RES: Mutex> = Mutex::new(Aging::new(UNKNOWN_RES_CAP)); /// Buffers the GPU is done with, kept for the recordings that need one next (`FREE_RES`): each -/// with when it was handed back, its bytes and its device, oldest first. What it keeps is what -/// recordings took again in the last `FREE_RES_IDLE`, and at most `cap` bytes, so a steady frame -/// takes back what the one before it handed back and makes none. +/// with when it was handed back, its bytes, its device and how long it is held before it is +/// taken again (`free_hold`), oldest first. What it keeps is what recordings took again in the +/// last `FREE_RES_IDLE` they could, and at most `cap` bytes, so a steady frame takes back what the +/// one before it handed back and makes none. struct FreePool { - free: Vec<(std::time::Instant, u64, usize, T)>, + free: Vec<(std::time::Instant, u64, usize, T, std::time::Duration)>, bytes: u64, cap: u64, } @@ -744,11 +770,16 @@ impl FreePool { /// Keep `item` of `bytes` on the device `dev` from `now`. Past the cap the oldest go (what /// is returned). fn put(&mut self, now: std::time::Instant, bytes: u64, dev: usize, item: T) -> Vec { + self.put_held(now, std::time::Duration::ZERO, bytes, dev, item) + } + + /// `put`, the item taken again only `hold` after `now` (`free_hold`). + fn put_held(&mut self, now: std::time::Instant, hold: std::time::Duration, bytes: u64, dev: usize, item: T) -> Vec { self.bytes += bytes; - self.free.push((now, bytes, dev, item)); + self.free.push((now, bytes, dev, item, hold)); let mut over = Vec::new(); while self.bytes > self.cap && !self.free.is_empty() { - let (_, b, _, t) = self.free.remove(0); + let (_, b, _, t, _) = self.free.remove(0); self.bytes -= b; over.push(t); } @@ -757,15 +788,21 @@ impl FreePool { /// The smallest kept on `dev` of `min..=max` bytes, of those the last handed back (so the /// ones no recording needs grow old and go). + /// One held (`put_held`) is not taken before its hold is over. fn take(&mut self, dev: usize, min: u64, max: u64) -> Option { + self.take_at(std::time::Instant::now(), dev, min, max) + } + + /// `take` at `now`. + fn take_at(&mut self, now: std::time::Instant, dev: usize, min: u64, max: u64) -> Option { let i = self .free .iter() .enumerate() - .filter(|(_, &(_, b, d, _))| d == dev && b >= min && b <= max) - .min_by_key(|&(i, &(_, b, _, _))| (b, std::cmp::Reverse(i)))? + .filter(|(_, &(at, b, d, _, hold))| d == dev && b >= min && b <= max && now.saturating_duration_since(at) >= hold) + .min_by_key(|&(i, &(_, b, ..))| (b, std::cmp::Reverse(i)))? .0; - let (_, b, _, t) = self.free.remove(i); + let (_, b, _, t, _) = self.free.remove(i); self.bytes -= b; Some(t) } @@ -789,7 +826,7 @@ impl FreePool { Some( self.free .drain(..n) - .map(|(_, b, _, t)| { + .map(|(_, b, _, t, _)| { self.bytes -= b; t }) @@ -797,12 +834,14 @@ impl FreePool { ) } - /// What was kept `age` or longer at `now`, no recording having taken it. + /// What could be taken for `age` or longer at `now` (from the end of its hold), no recording + /// having taken it. (Holds differ, so these are not only the oldest ones.) fn take_idle(&mut self, now: std::time::Instant, age: std::time::Duration) -> Vec { - let n = self.free.iter().take_while(|&&(at, ..)| now.saturating_duration_since(at) >= age).count(); - self.free - .drain(..n) - .map(|(_, b, _, t)| { + let (idle, kept): (Vec<_>, Vec<_>) = + std::mem::take(&mut self.free).into_iter().partition(|&(at, _, _, _, hold)| now.saturating_duration_since(at) >= hold.saturating_add(age)); + self.free = kept; + idle.into_iter() + .map(|(_, b, _, t, _)| { self.bytes -= b; t }) @@ -1092,6 +1131,7 @@ fn install_reset( let res_untracked = std::mem::take(&mut s.res_untracked); let had_fb = !s.fb_uses.is_empty(); s.fb_uses.clear(); + s.bake_sources.clear(); (old, std::mem::take(&mut s.uma), res_bufs, res_marks, res_untracked, had_fb, old_resolution) }); if !res_bufs.is_empty() || !res_marks.is_empty() || res_untracked || had_fb { @@ -1304,10 +1344,19 @@ pub(super) fn bound_pso(this: *mut c_void) -> usize { /// Remap any superseded targets named in the first 256 slots of each descriptor table in `layout` /// / `args`. Only called when `placements::any_superseded()` is true. -unsafe fn note_superseded_in_tables(u: &crate::gpu::uma::Uma, layout: Option<&Layout>, args: &[u8]) { - let Some(layout) = layout else { return }; - const TABLE_SLOTS: usize = 256; - let mut table = [0u8; TABLE_SLOTS * 32]; +/// Single-pass scan of bound descriptor tables for both superseded target reactivation +/// (`placements::note_uses`, up to 256 slots) and shadowed sampled-texture reactivation +/// (`title_textures::uncover_drawn`, first 64 slots). Avoids reading every table twice per draw +/// and checks each set with one shared `RwLock::read()`. +unsafe fn scan_bound_tables(u: &crate::gpu::uma::Uma, layout: Option<&Layout>, args: &[u8], check_superseded: bool, check_shadowed: bool) { + let Some(layout) = layout.filter(|_| check_superseded || check_shadowed) else { return }; + const SUP_SLOTS: usize = 256; + const SHAD_SLOTS: usize = 64; + let slots = if check_superseded { SUP_SLOTS } else { SHAD_SLOTS }; + let mut table = [0u8; SUP_SLOTS * 32]; + let byte_len = slots * 32; + let mut sup_res = Vec::new(); + let mut shad_res = Vec::new(); for p in &layout.params { let Param::Table { at } = *p else { continue }; let at = at as usize; @@ -1317,23 +1366,75 @@ unsafe fn note_superseded_in_tables(u: &crate::gpu::uma::Uma, layout: Option<&La continue; } let addr = u.base() + offset; - if u.in_committed_window(addr, table.len()) { - std::ptr::copy_nonoverlapping(addr as *const u8, table.as_mut_ptr(), table.len()); + let slice = &mut table[..byte_len]; + if u.in_committed_window(addr, byte_len) || super::sparse::known_readable(addr, addr.saturating_add(byte_len)) { + std::ptr::copy_nonoverlapping(addr as *const u8, slice.as_mut_ptr(), byte_len); } else { - table.fill(0); - super::title_textures::read_committed_into(addr, &mut table); + super::title_textures::read_committed_into(addr, slice); } - for slot in table.chunks_exact(32) { + for (slot_idx, slot) in slice.chunks_exact(32).enumerate() { let index = u32::from_le_bytes(slot[..4].try_into().unwrap()); if slot[15] >> 4 < 8 || index == 0 { continue; } let res = super::console_heap::named_by_index(index); if res != 0 && res != super::console_heap::GONE { - super::placements::note_use(res); + if check_superseded && !sup_res.contains(&res) { + sup_res.push(res); + } + if check_shadowed && slot_idx < SHAD_SLOTS && !shad_res.contains(&res) { + shad_res.push(res); + } } } } + if check_superseded && !sup_res.is_empty() { + super::placements::note_uses(&sup_res); + } + if check_shadowed && !shad_res.is_empty() { + super::title_textures::uncover_drawn(&shad_res); + } +} + +/// `XCL_TRACE_SLOT=`: the image views at that place of the descriptor tables of graphics +/// draws – each resource once (the first 64), with its description and the view's words. Places +/// that hold no image view (another table's layout) are passed over. +unsafe fn trace_table_slot(u: &crate::gpu::uma::Uma, layout: Option<&Layout>, args: &[u8], pso: usize) { + static WANT: std::sync::OnceLock> = std::sync::OnceLock::new(); + let Some(dword) = *WANT.get_or_init(|| std::env::var("XCL_TRACE_SLOT").ok()?.trim().parse().ok()) else { return }; + let Some(layout) = layout else { return }; + for (param, p) in layout.params.iter().enumerate() { + let Param::Table { at } = *p else { continue }; + let Some(word) = args.get(at as usize..at as usize + 4) else { continue }; + let offset = u32::from_le_bytes(word.try_into().unwrap()) as usize; + if offset == 0 { + continue; + } + let mut slot = [0u8; 32]; + super::title_textures::read_committed_into(u.base() + offset + 4 * dword, &mut slot); + let w: [u32; 8] = std::array::from_fn(|k| u32::from_le_bytes(slot[4 * k..4 * k + 4].try_into().unwrap())); + // (an image view: type 8 and up in the top bits of word 3; its index in word 0) + if w[3] >> 28 < 8 || w[0] == 0 || w[0] > 4 << 20 { + continue; + } + let res = super::console_heap::named_by_index(w[0]); + static SEEN: Mutex>> = Mutex::new(None); + let mut g = SEEN.lock().unwrap(); + let seen = g.get_or_insert_with(Default::default); + if seen.len() >= 64 || !seen.insert((param, res)) { + continue; + } + let desc = (res != 0 && res != super::console_heap::GONE) + .then(|| { + let ptr = res as *mut c_void; + ID3D12Resource::from_raw_borrowed(&ptr).map(|r| r.GetDesc()) + }) + .flatten() + .map(|d| (d.Dimension.0, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels, d.Format.0, d.Flags.0)); + crate::xlog_info!( + "D3D12.X: XCL_TRACE_SLOT: parameter {param} dword {dword} of pipeline {pso:#x}: resource {res:#x} (dimension, width, height, depth, mips, format, flags) {desc:?}, view words {w:08x?}" + ); + } } /// `XCL_DUMP_TARGETS`: the resources the first 16 slots of each descriptor table of `this`'s @@ -1362,6 +1463,81 @@ fn table_resources_of(this: *mut c_void, gfx: bool, slots: usize) -> Vec out } +/// Check the first 64 slots of each bound table. A texture descriptor copied as bytes still +/// samples the resource named by its heap index in word 0. +unsafe fn uncover_bound_tables(layout: Option<&Layout>, args: &[u8], u: &crate::gpu::uma::Uma) { + scan_bound_tables(u, layout, args, false, super::title_textures::has_shadowed()); +} + +/// A draw whose result is drawn once and kept (`pso_async::is_kept`: the title's bake of its +/// characters' skin and decorations) picks its source textures by their index in the view heap +/// (`indexed`), from its constants, and names none in a table: `uncover_bound_tables` does not see +/// them. A source that is shadowed then (a newer placement lies over its memory) is not uploaded, +/// and the bake takes nothing from it – once, for the run: a head stays black. +/// So every word of the draw's root constants and constant buffers (root ones, and those in the +/// first 16 slots of its tables) that names a shadowed texture through the slots of the view heap +/// `view_heap` (`indexed::resources`) makes that texture active again, for the upload ahead of the +/// list's submit. `XCL_BAKE_SOURCES=0` turns it off; `XCL_UNCOVER_INDEXED=1` does it for every +/// graphics draw (`bake` false: not a bake's). +unsafe fn uncover_indexed(indices: &[u32], view_heap: u32, bake: bool) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var("XCL_BAKE_SOURCES").map_or(true, |v| v.trim() != "0")) { + return; + } + let resources = super::indexed::resources(indices, view_heap); + let shadowed = super::title_textures::shadowed_among(&resources); + if bake { + static DRAWS: AtomicU64 = AtomicU64::new(0); + static FOUND: AtomicU64 = AtomicU64::new(0); + let (n, found) = (DRAWS.fetch_add(1, Ordering::Relaxed) + 1, FOUND.fetch_add(shadowed as u64, Ordering::Relaxed) + shadowed as u64); + if shadowed != 0 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: a bake's draw (#{n}) picks {} textures by index ({}), {shadowed} of them shadowed: made active again for its upload ({found} so far)", + resources.len(), + if super::indexed::by_slot() { "through the view heap's slots" } else { "as shared-heap indices, XCL_INDEX_BY_SLOT=0" } + ); + } + } + if shadowed != 0 { + super::title_textures::uncover_drawn(&resources); + } +} + +/// `res`, textures a bake's draw on `list` picks by index, are made ready for it again at the +/// list's submit (`bake_sources`, `title_textures::bake_at_submit`): a placement between the +/// draw and the submit shadows them again. +fn keep_bake_sources(list: *mut c_void, res: Vec) { + if res.is_empty() { + return; + } + with(list, |s| { + for r in res { + if !s.bake_sources.contains(&r) { + s.bake_sources.push(r); + } + } + }); +} + +/// The textures the bake draws recorded on `lists` (the PC lists of a submit, as the draws +/// had them) pick by index, each once, taken: a list submitted again has them made ready once. +pub(super) fn bake_sources(lists: &[*mut c_void]) -> Vec { + let mut out = Vec::new(); + for &l in lists { + let Some(entry) = STATES.get(l as usize) else { continue }; + let mut s = entry.state.lock().unwrap(); + if !entry.live.load(Ordering::Acquire) || s.bake_sources.is_empty() { + continue; + } + for r in std::mem::take(&mut s.bake_sources) { + if !out.contains(&r) { + out.push(r); + } + } + } + out +} + /// `XCL_CAPTURE_FRAME`: a draw or dispatch of the title's on `this` (`gfx`: with the graphics /// root arguments), with the root arguments, heaps and pipeline it has, until the call returns. pub(super) unsafe fn capture_work(this: *mut c_void, kind: impl FnOnce() -> super::capture::WorkKind, gfx: bool) -> super::capture::Guard { @@ -1386,7 +1562,16 @@ pub(super) unsafe fn capture_work(this: *mut c_void, kind: impl FnOnce() -> supe }); (root, s.heaps, s.pso) }); - let views = table_resources_of(this, gfx, super::capture::TABLE_SLOTS); + let mut views = table_resources_of(this, gfx, super::capture::TABLE_SLOTS); + // and the textures it picks by index through the view heap's slots (`indexed`) + let (layout, args) = with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) }); + if let (Some(l), Some(u)) = (layout.as_deref(), crate::gpu::uma::get()) { + for n in super::indexed::named(&super::indexed::indices(l, &args, u), heaps[0]) { + if !views.contains(&n.res) { + views.push(n.res); + } + } + } Some(super::capture::work(this, kind(), pso, gfx, root, heaps, views)) }) } @@ -2357,8 +2542,14 @@ unsafe fn emit_commands(this: *mut c_void, list: &ID3D12GraphicsCommandList, cmd let p = *p as *mut c_void; list.SetPipelineState(ID3D12PipelineState::from_raw_borrowed(&p)); } - Cmd::ComputeView(slot, va) => list.SetComputeRootUnorderedAccessView(*slot, *va), - Cmd::GraphicsView(slot, va) => list.SetGraphicsRootUnorderedAccessView(*slot, *va), + Cmd::ComputeView(slot, va) => { + super::real::note_root_view(list.as_raw() as usize, *slot, *va); + list.SetComputeRootUnorderedAccessView(*slot, *va) + } + Cmd::GraphicsView(slot, va) => { + super::real::note_root_view(list.as_raw() as usize, *slot, *va); + list.SetGraphicsRootUnorderedAccessView(*slot, *va) + } Cmd::Dispatch(n) => list.Dispatch(*n, 1, 1), Cmd::DispatchMesh(n) => pc_dm(this, *n, 1, 1), Cmd::Indirect(sig, buf, at) => pc_ei(this, *sig, 1, *buf, *at, 0, 0), @@ -2561,7 +2752,7 @@ unsafe fn defer_execute_indirect(this: *mut c_void, tp: &Arc (Some(va), slot, h), None => (None, 0, None), }; - let region = batch_region_bytes(indirect_record_need_hint(record_bytes, tp.mesh_groups_per_record, hint)); + let region = batch_region_bytes(cold_record_need(indirect_record_need_hint(record_bytes, tp.mesh_groups_per_record, hint), hint, fb_slot != 0, cold_records_bytes())); let ty = super::list_x::tracked_list_type(this); if defer_check(true, ty, super::capture::on(), max, region, batch_records_bytes()).is_err() { return false; @@ -2624,7 +2815,7 @@ fn indirect_record_need(record_bytes: u64, split: u32) -> u64 { } /// Record bytes sized from async GPU `SCALE_ARGS_HLSL` feedback (`hint_groups`): `None` (cold) -/// keeps the full `indirect_record_need` (no cold-start clamping); `Some(0)` takes +/// keeps the full `indirect_record_need` (no cold-start clamping here: `cold_record_need`); `Some(0)` takes /// `RECORD_MIN.min(max_need)`; `Some(g)` reserves `2 × g` records up to `max_need`. fn indirect_record_need_hint(record_bytes: u64, split: u32, hint_groups: Option) -> u64 { let max_need = indirect_record_need(record_bytes, split); @@ -2635,6 +2826,34 @@ fn indirect_record_need_hint(record_bytes: u64, split: u32, hint_groups: Option< } } +/// `XCL_TWO_PASS_COLD_MB` (4 by default; `0`: as the draw alone; read once): the most record bytes +/// a two-pass ExecuteIndirect asks for while its pipeline's feedback slot has given no readback yet +/// (`cold_record_need`). As the draw alone, each such draw asked for up to 32 MiB (`INDIRECT_RECORDS`) +/// and a recording held that: a retail world's first second has its pipelines cold on every list, +/// and at world entry the two-pass buffers alive went to the cap of 1 GiB and some 1,900 draws +/// were skipped in 6 s. Most of these draws have no groups or a few; 4 MiB holds 628 groups of the +/// title's largest records (6,672 B). +fn cold_records_bytes() -> u64 { + static MB: std::sync::OnceLock = std::sync::OnceLock::new(); + *MB.get_or_init(|| std::env::var("XCL_TWO_PASS_COLD_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(4).min(128)) << 20 +} + +/// The record bytes of a two-pass ExecuteIndirect that needs `need` (`indirect_record_need_hint` +/// with `hint`): at most `cold` (`cold_records_bytes`; 0: no limit) while its pipeline has a +/// feedback slot (`has_slot`) that has given no readback yet. A command with more groups keeps +/// what fits – `SCALE_ARGS_HLSL` drops the groups past the records and puts what it asked for in +/// the slot (counted as clamped) – and the slot's next readback sizes the pipeline's draws from +/// then on (`IndirectFeedbackSlot::apply_window`): one or two frames after its first draw. A +/// pipeline with no slot (feedback off, or all slots taken) never learns of it: its draws ask +/// for what they would alone. +fn cold_record_need(need: u64, hint: Option, has_slot: bool, cold: u64) -> u64 { + if hint.is_none() && has_slot && cold != 0 { + need.min(cold) + } else { + need + } +} + const FEEDBACK_HEADER_U32S: usize = 2; const FEEDBACK_SLOTS: usize = 4096; const FEEDBACK_BYTES: u64 = ((FEEDBACK_HEADER_U32S + FEEDBACK_SLOTS) as u64) * 4; @@ -3062,11 +3281,13 @@ unsafe fn emit_two_pass_stage(list: &ID3D12GraphicsCommandList, stage: &StageBin if compute_pass { list.SetComputeRootSignature(rs); for (k, &v) in stage.views.iter().enumerate() { + super::real::note_root_view(list.as_raw() as usize, k as u32, v); list.SetComputeRootUnorderedAccessView(k as u32, v); } } else { list.SetGraphicsRootSignature(rs); for (k, &v) in stage.views.iter().enumerate() { + super::real::note_root_view(list.as_raw() as usize, k as u32, v); list.SetGraphicsRootUnorderedAccessView(k as u32, v); } } @@ -3105,7 +3326,11 @@ unsafe fn prepare_two_pass_stage( if pso == 0 { return Err(if compute_pass { "two-pass compute pipeline" } else { "two-pass mesh pipeline" }.into()); } - let w = |k: usize| super::real::uma_window_va(k).unwrap_or(first); + if !compute_pass { + // Both passes use the same graphics root tables. + uncover_bound_tables(layout.as_deref(), &args, u); + } + let w = |k: usize| super::real::uma_window_va(k).filter(|&v| v != 0).unwrap_or(first); Ok(StageBind { rs, pso, views: [va(io_at), res_va, w(0), w(1), w(2), w(3)] }) } @@ -3195,7 +3420,8 @@ unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Res return Err(format!("its rewritten arguments are past {} MiB this recording", SCRATCH_CAP >> 20)); } let cap = two_pass_cap(); - let block = acquire_two_pass_buf_with_cap(dev, size, remaining, remaining, "two-pass argument scratch", cap, FENCE_WAIT_LIMIT)? + let (min, preferred, most) = scratch_window(size, remaining); + let block = acquire_two_pass_buf_with_cap(dev, min, preferred, most, "two-pass argument scratch", cap, FENCE_WAIT_LIMIT)? .ok_or_else(|| refuse_two_pass("two-pass argument scratch", size, cap))?; let b = block.res.clone(); with(this, |s| { @@ -3210,6 +3436,14 @@ unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Res Ok((b, 0)) } +/// The bytes of a kept buffer a scratch block of `size` takes (`acquire_two_pass_buf_with_cap`): +/// first one of up to twice its size, as a record buffer takes, then – when no new one can be made – +/// any the recording's `remaining` scratch bytes hold. (Any up to `remaining` first took the record +/// buffers of 16 MiB and less from the recordings that needed them next, for 256 KiB of arguments.) +fn scratch_window(size: u64, remaining: u64) -> (u64, u64, u64) { + (size, size.saturating_mul(2).min(remaining).max(size), remaining) +} + /// The root UAVs of the pass that rewrites a two-pass ExecuteIndirect's arguments /// (`SCALE_ARGS_HLSL`), as (root slot, GPU address): every view its program declares gets one. /// @@ -3257,6 +3491,7 @@ unsafe fn make_scaled_args_buffer( list.SetComputeRootSignature(ID3D12RootSignature::from_raw_borrowed(&rs_raw)); list.SetPipelineState(ID3D12PipelineState::from_raw_borrowed(&pso_raw)); for (slot, va) in rewrite.views { + super::real::note_root_view(list.as_raw() as usize, slot, va); list.SetComputeRootUnorderedAccessView(slot, va); } list.Dispatch(rewrite.groups, 1, 1); @@ -3507,6 +3742,497 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: pc_dm(this, x, y, z); } +/// `XCL_TRACE_ARGS=[,…]` (a diagnostic, with `XCL_TRACE_MS` set): the group counts +/// the GPU has in the arguments of two-pass indirect mesh draws with those mesh shaders. The +/// title's culling writes them on the GPU, so the CPU reads zeros when the draw is recorded: +/// one draw in four has its 12 bytes read back after its submit, and what came back is counted +/// a second later (draws with no groups / with groups), logged at powers of two. +unsafe fn trace_args(this: *mut c_void, pso: usize, commands_at: Option<(usize, usize)>, sig: usize) { + static WANT: std::sync::OnceLock> = std::sync::OnceLock::new(); + let want = WANT.get_or_init(|| std::env::var("XCL_TRACE_ARGS").unwrap_or_default().split(',').filter_map(|h| u64::from_str_radix(h.trim(), 16).ok()).collect()); + if want.is_empty() { + return; + } + let Some(h) = super::real::pso_shaders(pso).map(|s| s.0).filter(|h| want.contains(h)) else { return }; + let (Some((p, n)), Some(msig)) = (commands_at, dispatch_mesh_sig_of(sig)) else { return }; + if n < msig.mesh_offset as usize + 12 { + return; + } + let at = p + msig.mesh_offset as usize; + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) % 4 != 0 { + return; + } + // (address, MS, when) + static PENDING: Mutex> = Mutex::new(std::collections::VecDeque::new()); + // MS → draws with no groups, with groups, with counts that are no counts (the memory was + // used again), the most groups in X, the last counts with groups + static STATS: Mutex>> = Mutex::new(None); + let now = std::time::Instant::now(); + let mut due = Vec::new(); + { + let mut q = PENDING.lock().unwrap(); + while q.front().is_some_and(|f| now.duration_since(f.2).as_millis() >= 250) { + due.push(q.pop_front().unwrap()); + } + if q.len() < 4096 { + q.push_back((at, h, now)); + } + } + for (a, ms, _) in due { + if !crate::gpu::shader::readable(a, 12) { + continue; + } + let g: [u32; 3] = std::array::from_fn(|i| std::ptr::read_unaligned((a + 4 * i) as *const u32)); + let mut st = STATS.lock().unwrap(); + let e = st.get_or_insert_with(HashMap::new).entry(ms).or_insert((0, 0, 0, 0, [0; 3])); + if g == [0, 1, 1] || g == [0, 0, 0] { + e.0 += 1; + } else if (1..=65_535).contains(&g[0]) && g[1] == 1 && g[2] == 1 { + e.1 += 1; + e.3 = e.3.max(g[0]); + e.4 = g; + } else { + e.2 += 1; + } + let total = e.0 + e.1 + e.2; + if total.is_power_of_two() || total % 128 == 0 { + crate::xlog_info!("trace args: MS {ms:016x}: {total} draws read back: {} with no groups, {} with groups (most in X: {}, last {:?}), {} unreadable", e.0, e.1, e.3, e.4, e.2); + } + } + super::list_x::trace_read_back(this as usize, at as u64, 12); +} + +/// `XCL_TRACE_RECORD=1` (with `XCL_TRACE_MS=`) or `XCL_TRACE_RECORD=all`: copies the +/// scaled indirect args (or direct group counts) and first two-pass record of sampled draws into +/// a small readback ring and logs per-MS vertex/primitive counts, positions, and indices. +#[allow(clippy::too_many_arguments)] +unsafe fn trace_record( + list: &ID3D12GraphicsCommandList, + pso: usize, + tp: &super::real::TwoPassPso, + res_buf: &ID3D12Resource, + res_off: u64, + scaled: Option<&ID3D12Resource>, + compute_args_off: u64, + mesh_args_off: u64, + direct_groups: Option<(u32, u32)>, +) { + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + let mode = *MODE.get_or_init(|| match std::env::var("XCL_TRACE_RECORD").as_deref().map(str::trim) { + Ok("1") => 1, + Ok(v) if v.eq_ignore_ascii_case("all") => 2, + _ => 0, + }); + if mode == 0 { + return; + } + let Some((ms_h, ps_h)) = super::real::pso_shaders(pso) else { return }; + if mode == 1 { + let Some(want) = super::real::trace_ms() else { return }; + if ms_h != want { + return; + } + } + const SLOTS: usize = 64; + const SLOT_BYTES: usize = 32768; + const HDR_BYTES: usize = 32; + struct Pending { + slot: usize, + ms_h: u64, + ps_h: u64, + draw_id: u64, + direct: Option<(u32, u32)>, + when: std::time::Instant, + max_v: u32, + max_p: u32, + vert_dw: usize, + copy_bytes: usize, + } + #[derive(Default)] + struct MsStat { + zero_g: u64, + nonzero_g: u64, + valid_rec: u64, + empty_rec: u64, + nan_v: u64, + zero_v: u64, + ndc_v: u64, + close_v: u64, + tot_v: u64, + ok_p: u64, + null_p: u64, + oob_p: u64, + logged_early: u32, + logged_late: u32, + ps_h: u64, + split: u32, + direct_draws: u64, + } + struct Ring { + dev: usize, + buf: ID3D12Resource, + ptr: usize, + free: [bool; SLOTS], + pending: std::collections::VecDeque, + stats: HashMap, + last_dump: std::time::Instant, + t0: std::time::Instant, + } + static RING: Mutex> = Mutex::new(None); + static DRAW_N: AtomicU64 = AtomicU64::new(0); + let draw_id = DRAW_N.fetch_add(1, Ordering::Relaxed); + if mode == 1 && draw_id % 4 != 0 { + return; + } + if mode == 2 && direct_groups.is_none() && draw_id % 16 != 0 { + return; + } + let mut dev_opt: Option = None; + if list.GetDevice(&mut dev_opt).is_err() { + return; + } + let Some(dev) = dev_opt else { return }; + let dev_key = dev.as_raw() as usize; + + let mut guard = RING.lock().unwrap(); + if guard.as_ref().is_none_or(|r| r.dev != dev_key) { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: (SLOTS * SLOT_BYTES) as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut rb: Option = None; + if dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).is_err() { + return; + } + let Some(rb) = rb else { return }; + let mut p: *mut c_void = std::ptr::null_mut(); + if rb.Map(0, None, Some(&mut p)).is_err() || p.is_null() { + return; + } + let now = std::time::Instant::now(); + *guard = Some(Ring { + dev: dev_key, + buf: rb, + ptr: p as usize, + free: [true; SLOTS], + pending: std::collections::VecDeque::new(), + stats: HashMap::new(), + last_dump: now, + t0: now, + }); + } + let ring = guard.as_mut().unwrap(); + let now = std::time::Instant::now(); + // Drain completed slots (>= 400 ms old) + while ring.pending.front().is_some_and(|p| now.duration_since(p.when).as_millis() >= 400) { + let p = ring.pending.pop_front().unwrap(); + let base = (ring.ptr + p.slot * SLOT_BYTES) as *const u32; + let (cg, mg) = match p.direct { + Some((n, m)) => ([n, 1, 1], [m, 1, 1]), + None => ([*base, *base.add(1), *base.add(2)], [*base.add(4), *base.add(5), *base.add(6)]), + }; + let rec_ptr = base.add(HDR_BYTES / 4); + let rec_dwords = p.copy_bytes / 4; + let st = ring.stats.entry(p.ms_h).or_default(); + st.ps_h = p.ps_h; + if p.direct.is_some() { + st.direct_draws += 1; + } + if cg[0] == 0 { + st.zero_g += 1; + } else { + st.nonzero_g += 1; + let nv = if rec_dwords > 0 { *rec_ptr } else { 0 }; + let np = if rec_dwords > 1 { *rec_ptr.add(1) } else { 0 }; + let r2 = if rec_dwords > 2 { *rec_ptr.add(2) } else { 0 }; + let r3 = if rec_dwords > 3 { *rec_ptr.add(3) } else { 0 }; + if nv == 0 || np == 0 { + st.empty_rec += 1; + } else { + st.valid_rec += 1; + } + let nv_c = nv.min(p.max_v) as usize; + let np_c = np.min(p.max_p) as usize; + let mut finite = 0usize; + let mut nan_v = 0usize; + let mut zero_v = 0usize; + let mut w_pos = 0usize; + let mut onscreen = 0usize; + let mut close_w = 0usize; + let mut sample_verts = Vec::new(); + for vi in 0..nv_c { + let vo = crate::gpu::recomp::MESH_HEADER + vi * p.vert_dw; + if vo + 4 > rec_dwords { + break; + } + let pos_u = [*rec_ptr.add(vo), *rec_ptr.add(vo + 1), *rec_ptr.add(vo + 2), *rec_ptr.add(vo + 3)]; + let pos = pos_u.map(f32::from_bits); + if pos_u == [0, 0, 0, 0] { + zero_v += 1; + } + if pos.iter().all(|x| x.is_finite()) { + finite += 1; + if pos[3] > 0.0 { + w_pos += 1; + if pos[3] < 25.0 { + close_w += 1; + } + let (nx, ny, nz) = (pos[0] / pos[3], pos[1] / pos[3], pos[2] / pos[3]); + if nx.abs() <= 1.0 && ny.abs() <= 1.0 && (0.0..=1.0).contains(&nz) { + onscreen += 1; + } + } + } else { + nan_v += 1; + } + if vi < 3 { + sample_verts.push(format!("v{vi}=({:.2},{:.2},{:.3},{:.2})", pos[0], pos[1], pos[2], pos[3])); + } + } + let tri_base = crate::gpu::recomp::MESH_HEADER + p.max_v as usize * p.vert_dw; + let mut null_p = 0usize; + let mut oob_p = 0usize; + let mut ok_p = 0usize; + let mut sample_prims = Vec::new(); + for pi in 0..np_c { + if tri_base + pi >= rec_dwords { + break; + } + let raw = *rec_ptr.add(tri_base + pi); + let (i0, i1, i2, nul) = (raw & 0x1FF, (raw >> 10) & 0x1FF, (raw >> 20) & 0x1FF, raw >> 31); + if nul != 0 { + null_p += 1; + } else if i0 >= nv || i1 >= nv || i2 >= nv { + oob_p += 1; + } else { + ok_p += 1; + } + if pi < 3 { + sample_prims.push(format!("p{pi}=({i0},{i1},{i2},n={nul})")); + } + } + st.tot_v += nv_c as u64; + st.nan_v += nan_v as u64; + st.zero_v += zero_v as u64; + st.ndc_v += onscreen as u64; + st.close_v += close_w as u64; + st.ok_p += ok_p as u64; + st.null_p += null_p as u64; + st.oob_p += oob_p as u64; + + let elapsed_s = now.duration_since(ring.t0).as_secs(); + let detail = if mode == 1 { + st.logged_early < 16 || st.nonzero_g % 64 == 0 + } else if elapsed_s >= 175 { + st.logged_late < 2 || (nan_v > 0 && st.logged_late < 4) + } else { + st.logged_early < 1 || ((nv == 0 || np == 0 || nan_v > 0 || zero_v == nv_c) && st.logged_early < 3) + }; + if detail { + if elapsed_s >= 175 { + st.logged_late += 1; + } else { + st.logged_early += 1; + } + crate::xlog_info!( + "trace record: MS {:016x} PS {:016x} {} cg={cg:?} hdr=[nv={nv},np={np},{r2:#x},{r3:#x}] v(fin={finite},nan={nan_v},z={zero_v},w>0={w_pos},w<25={close_w},ndc={onscreen}/{nv_c}) p(ok={ok_p},null={null_p},oob={oob_p}/{np_c}) | {} | {}", + p.ms_h, + p.ps_h, + if p.direct.is_some() { "DIRECT" } else { "IND" }, + sample_verts.join(" "), + sample_prims.join(" ") + ); + } + } + ring.free[p.slot] = true; + } + + if mode == 2 && now.duration_since(ring.last_dump).as_secs() >= 25 { + ring.last_dump = now; + let mut rows: Vec<(u64, &MsStat)> = ring.stats.iter().map(|(&k, v)| (k, v)).collect(); + rows.sort_by_key(|&(_, s)| std::cmp::Reverse(s.zero_g + s.nonzero_g)); + crate::xlog_info!("trace record table ({} MS hashes):", rows.len()); + for (h, s) in rows { + crate::xlog_info!( + " MS {h:016x} PS {:016x} split={} dir={}: 0g={} nz={} (valid={} empty={}) v(tot={} ndc={} w<25={} nan={} zero={}) p(ok={} null={} oob={})", + s.ps_h, s.split, s.direct_draws, s.zero_g, s.nonzero_g, s.valid_rec, s.empty_rec, s.tot_v, s.ndc_v, s.close_v, s.nan_v, s.zero_v, s.ok_p, s.null_p, s.oob_p + ); + } + } + + ring.stats.entry(ms_h).or_default().split = tp.mesh_groups_per_record; + let Some(slot) = ring.free.iter().position(|&f| f) else { return }; + ring.free[slot] = false; + let slot_off = (slot * SLOT_BYTES) as u64; + let copy_bytes = ((tp.record.record_dwords() * 4).min(SLOT_BYTES - HDR_BYTES)) & !3; + let dst_u32 = (ring.ptr + slot * SLOT_BYTES) as *mut u32; + for i in 0..((HDR_BYTES + copy_bytes.min(64)) / 4) { + *dst_u32.add(i) = 0xDEAD_BEEF; + } + let rb = ring.buf.clone(); + ring.pending.push_back(Pending { + slot, + ms_h, + ps_h, + draw_id, + direct: direct_groups, + when: now, + max_v: tp.record.max_vertices, + max_p: tp.record.max_primitives, + vert_dw: tp.record.vert_dwords(), + copy_bytes, + }); + drop(guard); + + if let Some(scaled) = scaled { + emit_transition(list, scaled, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.CopyBufferRegion(&rb, slot_off, scaled, compute_args_off, 12); + list.CopyBufferRegion(&rb, slot_off + 16, scaled, mesh_args_off, 12); + emit_transition(list, scaled, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + } + + emit_transition(list, res_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.CopyBufferRegion(&rb, slot_off + HDR_BYTES as u64, res_buf, res_off, copy_bytes as u64); + emit_transition(list, res_buf, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); +} + +/// `XCL_TRACE_MS=` (diagnostic): the first draws with a mesh pipeline of that MS (and +/// one in a thousand after them) – the root arguments, the descriptors in the first slots of +/// its tables (slot 89 of the first: the title's skinned mesh shader reads it) and the first +/// words the CPU sees behind each buffer view. A mesh shader that reads its vertex and primitive +/// counts as 0 draws nothing. +unsafe fn trace_ms_draw(this: *mut c_void, pso: usize, max: u32) { + let Some(want) = super::real::trace_ms() else { return }; + if super::real::pso_shaders(pso).map(|s| s.0) != Some(want) { + return; + } + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); + let Some(layout) = layout else { return }; + // `XCL_TRACE_READBACK=1`: what the GPU holds, after the submit that draws with them, in two + // places it writes and the CPU does not (slot 5 of the second table; the dword of the whole + // heap, slot 86 of the first, that the root constant names): read back for a few draws, and + // logged some hundred draws later + if std::env::var("XCL_TRACE_READBACK").is_ok_and(|v| v.trim() == "1") { + static PENDING: Mutex> = Mutex::new(Vec::new()); + let dwords = |at: u64, bytes: u64| -> Vec { + let cpu = super::sparse::cpu_of(at as usize); + if !crate::gpu::shader::readable(cpu, bytes as usize) { + return Vec::new(); + } + (0..(bytes / 4).min(16) as usize).map(|i| std::ptr::read_unaligned((cpu + 4 * i) as *const u32)).collect() + }; + { + let mut g = PENDING.lock().unwrap(); + g.retain(|&(at_n, what, at, bytes, records)| { + if n < at_n + 300 { + return true; + } + crate::xlog_info!("trace MS readback: draw #{at_n} {what} at {at:#x} ({records:#x}): after its submit the GPU had {:08x?}", dwords(at, bytes)); + false + }); + } + if n < 3 || n % 1500 < 3 { + let word = |at: usize| args.get(at..at + 4).map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap())); + let tables: Vec = layout.params.iter().filter_map(|p| if let Param::Table { at } = *p { Some(word(at as usize)) } else { None }).collect(); + let constant = layout.params.iter().find_map(|p| if let Param::Constants { at, .. } = *p { Some(word(at as usize)) } else { None }).unwrap_or(0); + let view = |t: u32, k: u32| super::console_heap::words_at(t.wrapping_add(32 * k)).map(|w| ((((w[1] as u64) & 0xFFFF) << 32) | w[0] as u64, ((w[1] >> 16) & 0x3FFF).max(1) as u64 * w[2] as u64, w[2])); + let mut asks: Vec<(&'static str, u64, u64, u32)> = Vec::new(); + if let Some((base, bytes, records)) = tables.get(1).and_then(|&t| view(t, 5)) { + asks.push(("slot 5", base, bytes.min(64), records)); + } + if let Some((heap, bytes, _)) = tables.first().and_then(|&t| view(t, 86)) { + let off = ((constant << 2) & 0x1FFF_FFFC) as u64; + if off + 16 <= bytes { + asks.push(("heap dword of the root constant", heap + off, 16, constant)); + } + } + // PreSkin trace: read table1[0]+0x54 -> offset & buffer selector (table0[33] vs table0[84]) + if let Some((cb0, cb0_bytes, _)) = tables.get(1).and_then(|&t| view(t, 0)) { + let cb0_cpu = super::sparse::cpu_of(cb0 as usize); + if cb0_bytes >= 0x58 && crate::gpu::shader::readable(cb0_cpu + 0x54, 4) { + let s0 = std::ptr::read_unaligned((cb0_cpu + 0x54) as *const u32); + let off = ((s0 << 4) & 0x0FFF_FFF0) as u64; + let slot_idx = if (s0 & 0x0300_0000) == 0 { 33 } else { 84 }; + let uav_idx = if (s0 & 0x0300_0000) == 0 { 24 } else { 25 }; + if let Some((base, bytes, _)) = tables.first().and_then(|&t| view(t, slot_idx)) { + crate::xlog_info!("trace MS preskin: draw #{n} cb0[0x54]={s0:#010x} (off={off:#x} fmt={:#x} sel={} srv_slot={slot_idx} uav_slot={uav_idx}) srv_base={base:#x} bytes={bytes:#x} tile={}", (s0 >> 28) & 3, (s0 >> 24) & 3, super::sparse::view_tile_diag((base + off) as usize)); + if off + 64 <= bytes { + asks.push(("preskin srv[off]", base + off, 64, s0)); + } + } + if let Some((ubase, ubytes, _)) = tables.first().and_then(|&t| view(t, uav_idx)) { + if off + 64 <= ubytes { + asks.push(("preskin uav[off]", ubase + off, 64, s0)); + } + } + } + } + if let Some((bone_base, bone_bytes, bone_rec)) = tables.first().and_then(|&t| view(t, 1)) { + asks.push(("table0 slot 1 (bones)", bone_base, bone_bytes.min(64), bone_rec)); + } + for (what, at, bytes, records) in asks { + if at != 0 && bytes >= 4 { + crate::xlog_info!("trace MS readback: draw #{n} {what} at {at:#x} ({records:#x}): the CPU has {:08x?}", dwords(at, bytes)); + super::list_x::trace_read_back(this as usize, at, bytes); + PENDING.lock().unwrap().push((n, what, at, bytes, records)); + } + } + } + } + if !(n < 6 || (n % 997 == 0 && n < 40_000)) { + return; + } + let word = |at: usize| args.get(at..at + 4).map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap())); + crate::xlog_info!("trace MS draw #{n} (max {max}): root arguments {:08x?}", (0..args.len() / 4).map(|k| word(4 * k)).collect::>()); + for va in console_list::root_views(&layout, &args) { + crate::xlog_info!("trace MS draw #{n}: root view {va:#x}: the view shows {:x?}; {}", crate::hle::kernelx::mirrors::shows(va as usize), super::sparse::view_tile_diag(va as usize)); + // (the skinned mesh shader reads a table at an offset the view's first word names) + let c = super::sparse::cpu_of(va as usize); + if crate::gpu::shader::readable(c, 16) { + let w0 = std::ptr::read_unaligned(c as *const u32); + let off = ((w0 >> 7) & 0x1ff_fffc) as usize; + crate::xlog_info!("trace MS draw #{n}: root view {va:#x}: first word {w0:#010x}: table at +{off:#x} (stride {}): {}", (w0 >> 3) & 60, super::sparse::view_tile_diag(va as usize + off)); + } + } + let mut tables = 0; + for p in layout.params.iter() { + let Param::Table { at } = *p else { continue }; + let t = word(at as usize); + let slots: &[u32] = if tables == 0 { &[0, 1, 8, 24, 25, 29, 33, 84, 86, 89, 190] } else { &[0, 1, 2, 3, 4, 5, 6, 7] }; + for &k in slots { + let Some(w) = super::console_heap::words_at(t.wrapping_add(32 * k)) else { + crate::xlog_info!("trace MS draw #{n}: table {tables} ({t:#x}) slot {k}: not in a console heap"); + continue; + }; + let base = (((w[1] as u64) & 0xFFFF) << 32) | w[0] as u64; + // (in a GPU view the CPU cannot touch: what the view shows there, read at its CPU address) + use crate::hle::kernelx::mirrors::{shows, Shows}; + let shown = shows(base as usize); + let cpu = match shown { + Shows::Same(c) => c, + Shows::Page { at, .. } => at, + Shows::NoView | Shows::Nothing => base as usize, + }; + let head: Option> = (base != 0 && crate::gpu::shader::readable(cpu, 32)).then(|| (0..8).map(|i| std::ptr::read_unaligned((cpu + 4 * i) as *const u32)).collect()); + crate::xlog_info!("trace MS draw #{n}: table {tables} ({t:#x}) slot {k}: {w:08x?}; as a V#: base {base:#x} stride {} records {}; the view shows {shown:x?}; behind it {head:08x?}", (w[1] >> 16) & 0x3FFF, w[2]); + if !matches!(shown, Shows::NoView) || crate::gpu::uma::get().is_some_and(|u| u.is_sparse(base as usize)) { + let bytes = (((w[1] >> 16) & 0x3FFF).max(1) as u64 * w[2] as u64).max(1); + crate::xlog_info!("trace MS draw #{n}: table {tables} slot {k}: first {}; last {}", super::sparse::view_tile_diag(base as usize), super::sparse::view_tile_diag((base + bytes - 1) as usize)); + } + } + tables += 1; + } +} + /// `XCL_DUMP_TARGETS`: a DispatchMesh (the two passes of a translated mesh pipeline count as the /// one draw they stand for) with `outcome` unsafe fn mesh_work(this: *mut c_void, outcome: usize) { @@ -3639,6 +4365,8 @@ unsafe fn execute_indirect_snapshot( // the PC call under the title's root signature with the pass-through mesh pipeline on // the list, whose shaders read their memory through root views the title's root // signature does not have. + trace_ms_draw(this, pso, max); + trace_args(this, pso, commands_at, sig); let Some(msig) = dispatch_mesh_sig_of(sig) else { ei_work(this, dispatches, super::targets::SKIPPED); count(DRAWS_SKIPPED); @@ -3683,7 +4411,8 @@ unsafe fn execute_indirect_snapshot( Some((va, slot, h)) => (Some(va), slot, h), None => (None, 0, None), }; - let (res_buf, res_va, region, records) = records_for(this, indirect_record_need_hint(record_bytes, tp.mesh_groups_per_record, hint), record_bytes, batch)?; + let need = cold_record_need(indirect_record_need_hint(record_bytes, tp.mesh_groups_per_record, hint), hint, fb_slot != 0, cold_records_bytes()); + let (res_buf, res_va, region, records) = records_for(this, need, record_bytes, batch)?; let cap = record_groups(region, record_bytes, tp.mesh_groups_per_record); if cap == 0 { return Err(format!("a record of {record_bytes} B does not fit the record buffer")); @@ -3704,12 +4433,19 @@ unsafe fn execute_indirect_snapshot( } } let plan = two_pass_plan(max, records, with(this, |s| s.record_open)); + let mut first_rec_off = 0u64; let passes = run_two_pass_plan(this, list, &plan, &res_buf, res_va, region, |k, compute, va| { + if k == 0 && compute { + first_rec_off = va - res_va; + } bind_two_pass_stage(this, list, pso, &tp, va, compute)?; let (s, first) = if compute { (msig.companion_dispatch, at) } else { (sig, at + commands as u64) }; pc(this, s, 1, scaled.as_raw() as usize, first + k as u64 * msig.byte_stride as u64, 0, 0); Ok(()) }); + if passes.is_ok() { + trace_record(list, pso, &tp, &res_buf, first_rec_off, Some(&scaled), at + msig.mesh_offset as u64, at + commands as u64 + msig.mesh_offset as u64, None); + } // (with `batch` the block stays in INDIRECT_ARGUMENT for the next rewrite) if !batch { emit_transition(list, &scaled, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); @@ -3742,6 +4478,9 @@ unsafe fn execute_indirect_snapshot( } flush_two_pass(this, RunEnd::Draw); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); + if compute { + note_dispatch_views(this, raw_pso); + } if !gfx && !compute { // (a pipeline still being built: skipped above, `DrawPipeline::StandIn`) // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in @@ -3772,6 +4511,7 @@ unsafe fn execute_indirect_snapshot( if dispatches && (retained_compute.unwrap_or_else(|| super::real::is_console_compute(raw_pso)) || super::real::is_console_compute(pso)) { super::targets::note_dispatch(); count(DISPATCHES_SKIPPED); + super::left_out::indirect(this, raw_pso, pso, sig, max, args, args_off, count_buf); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { crate::xlog_warn!("D3D12.X: ExecuteIndirect dispatch with a pipeline that has no translated console shader ({raw_pso:#x}) skipped"); @@ -3809,9 +4549,12 @@ unsafe fn execute_indirect_snapshot( if gfx && super::present::trace_frame() { trace_ui_draw(this, raw_pso, pso, true); } + super::ambient::diag_path("ExecuteIndirect", pso, raw_pso, count_buf, max); // (binds a compute root signature and a pipeline: before the dispatch's or draw's own) let checked = super::indirect_guard::check(this, pso, sig, max, args, args_off, count_buf); - // a split compute program's one Dispatch-only command runs its chain (`dispatch_chain`) + // a split compute program's one Dispatch-only command runs its chain (`dispatch_chain`), from + // the counts as the guard let them through: its slicer clamps each to 65 535 but runs a + // partial split's whole count in one dispatch, up to 65 535^3 groups of garbage (#3536) if compute && max == 1 && count_buf == 0 && signature.dispatch_only().is_some() { use super::real::dispatch_chain::Indirect; let chained = execute_indirect_chain(this, list, raw_pso, pso, with(this, |s| s.allocator), checked.as_ref(), args, args_off_title, args_off, @@ -3820,6 +4563,13 @@ unsafe fn execute_indirect_snapshot( Ok(Indirect::Ran) => { ei_work(this, dispatches, super::targets::RAN); count(DISPATCHES); + // a split program's chain is the title's pass too: the stand-in lighting follows it + // as it follows the plain ExecuteIndirect below (main's chain path returned before + // that hook, so split lighting passes never got the stand-in) + if compute && super::ambient::has_compute_psos() && count_buf == 0 && max == 1 { + let (layout, root_args, view_heap) = with(this, |s| (s.layout.clone(), s.args.clone(), s.heaps[0])); + super::ambient::after_compute_dispatch(this, super::ambient::role_pso(pso, raw_pso), [0, 0, 0], layout.as_deref(), &root_args, view_heap, None); + } return; } Ok(Indirect::Whole) => {} @@ -3834,6 +4584,9 @@ unsafe fn execute_indirect_snapshot( } } } + if gfx && super::present::trace_planes_from().is_some() { + trace_plane_draw(this, raw_pso, true); + } match bind_abi_resolved(this, list, raw_pso, pso, gfx) { Ok(b) => { let mut whole = None; @@ -3894,6 +4647,9 @@ unsafe fn execute_indirect_snapshot( if let Some(whole) = &whole { super::real::bind_pipeline_exact(this, raw_pso, whole.as_raw() as usize); } + if compute && super::real::trace_preskin() { + trace_preskin_cs(this, pso, "indirect", [max, 0, 0], 0); + } ei_work(this, dispatches, super::targets::RAN); count(if gfx { DRAWS } else { DISPATCHES }); let t = super::gpu_profile::begin(this, pso, if gfx { super::gpu_profile::Kind::IndirectDraw } else { super::gpu_profile::Kind::IndirectDispatch }, [max, 0, 0]); @@ -3914,6 +4670,14 @@ unsafe fn execute_indirect_snapshot( (None, None) => fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)), } super::gpu_profile::end(this, t); + if compute && super::ambient::has_compute_psos() && count_buf == 0 && max == 1 { + let indirect_args = checked.as_ref().map(|c| { + let (b, off) = c.arguments(); + (b, off as u32) + }); + let (layout, args, view_heap) = with(this, |s| (s.layout.clone(), s.args.clone(), s.heaps[0])); + super::ambient::after_compute_dispatch(this, super::ambient::role_pso(pso, raw_pso), [0, 0, 0], layout.as_deref(), &args, view_heap, indirect_args); + } } Err(e) => { ei_work(this, dispatches, super::targets::SKIPPED); @@ -4142,12 +4906,17 @@ pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: let _c = capture_work(this, || super::capture::WorkKind::Draw { vertices, instances, first_vertex, first_instance }, true); DRAW_ARGS.with(|d| d.set((false, vertices, instances, first_vertex, 0))); if let Some((list, pso)) = graphics_bound(this) { - let t = super::gpu_profile::begin(this, with(this, |s| s.pso), super::gpu_profile::Kind::Draw, [vertices, instances, 0]); + let bound_pso = with(this, |s| s.pso); + let t = super::gpu_profile::begin(this, bound_pso, super::gpu_profile::Kind::Draw, [vertices, instances, 0]); if !draw_rects(this, &list, pso, vertices, instances, first_vertex, first_instance) { super::list_x::sync_title_buffers(this, None, first_vertex, vertices, if first_instance != 0 { instances.max(2) } else { instances }); list.DrawInstanced(vertices, instances, first_vertex, first_instance); } super::gpu_profile::end(this, t); + if super::ambient::has_sky_psos() { + let pso = super::pso_async::resolve(bound_pso); + super::ambient::after_draw(this, super::ambient::role_pso(pso, bound_pso)); + } } } @@ -4173,6 +4942,11 @@ pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, i if let Some(list) = prepare_indexed_draw(this, indices, instances, first_index, base_vertex) { super::list_x::sync_title_buffers(this, Some((first_index, indices, base_vertex)), 0, 0, if first_instance != 0 { instances.max(2) } else { instances }); emit_prepared_indexed_draw(&list, indices, instances, first_index, base_vertex, first_instance); + if super::ambient::has_sky_psos() { + let bound = with(this, |s| s.pso); + let pso = super::pso_async::resolve(bound); + super::ambient::after_draw(this, super::ambient::role_pso(pso, bound)); + } } } @@ -4281,6 +5055,9 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option<(ID3D12GraphicsCommandList if super::present::trace_frame() { trace_ui_draw(this, pso, real, false); } + if super::present::trace_planes_from().is_some() { + trace_plane_draw(this, pso, false); + } match bind_abi_resolved(this, &list, pso, real, true) { Ok(_) => { super::targets::note_draw(this, super::targets::RAN); @@ -4531,6 +5308,50 @@ unsafe fn trace_ui_draw(this: *mut c_void, original: usize, pso: usize, indirect } } +/// `XCL_TRACE_PLANES=`: from that frame on, each pair of shaders that draws into a +/// presented resource is logged once with its root arguments (the first 80 pairs). +unsafe fn trace_plane_draw(this: *mut c_void, pso: usize, indirect: bool) { + let Some(from) = super::present::trace_planes_from() else { return }; + let frame = super::present::counters().1; + if frame < from { + return; + } + static WHY: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; + let why = |k: usize, what: &str| { + let n = WHY[k].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 3 || n.is_power_of_two() { + crate::xlog_info!("plane trace: frame {frame} a draw on list {:#x} (pipeline {pso:#x}) is not traced: {what} (#{n})", this as usize); + } + }; + let Some(rt) = super::present::rt0_resource(this as usize) else { + why(0, "no render target 0 known for its list"); + return; + }; + if !super::present::is_presented(rt) { + return; + } + let (vs, ps) = match super::real::pso_shaders(super::pso_async::resolve(pso)) { + Some(x) => x, + None => { + why(2, "its pipeline has no known shaders"); + (0, pso as u64) + } + }; + static SEEN: Mutex> = Mutex::new(Vec::new()); + { + let mut g = SEEN.lock().unwrap(); + if g.len() >= 80 || g.contains(&(vs, ps, rt)) { + return; + } + g.push((vs, ps, rt)); + } + crate::xlog_info!( + "plane trace: frame {frame} draw into {rt:#x} (pipeline {pso:#x}, vs {vs:016x} ps {ps:016x}{}): {}", + if indirect { ", ExecuteIndirect" } else { "" }, + root_args_summary(this, 16) + ); +} + /// A draw's root arguments for the frame trace: constants, root buffers (their first words, as /// the CPU sees them), the first slots of descriptor tables (the PC resources they name). unsafe fn root_args_summary(this: *mut c_void, buffer_words: usize) -> String { @@ -4558,14 +5379,15 @@ unsafe fn root_args_summary(this: *mut c_void, buffer_words: usize) -> String { let slots: Vec = (0..slots) .map(|k| { let at = u.base() + t + 32 * k; - let w = super::console_heap::words_at((t + 32 * k) as u32); + let observed = super::console_heap::read_slot((t + 32 * k) as u32); + let w = observed.map(|(words, _)| words); // with `XCL_TRACE_SLOTS`: the image the T# describes (format, width, // height, first and last level of the view, levels of the texture, smallest // level of detail), the slot's own index in the shared heap, and the // resource the T#'s index names there – a T# the title copied as memory // carries its source slot's index, and samples whatever that slot holds now let image = w.filter(|_| more.is_some()).and_then(|w| crate::gpu::desc::image(&w)).map_or(String::new(), |t| { - let own = super::console_heap::slot(at as u64).map(|s| s.index); + let own = observed.and_then(|(_, index)| index); let named = super::console_heap::named_by_index(w.map_or(0, |w| w[0])); let nd = (named != 0 && named != super::console_heap::GONE).then(|| ID3D12Resource::from_raw_borrowed(&(named as *mut c_void)).map(|x| x.GetDesc())).flatten(); if nd.is_some() && super::title_textures::address(named).is_some() { @@ -4821,10 +5643,172 @@ fn skip_untranslated_dispatch(pso: usize) { count(DISPATCHES_SKIPPED); } +/// Whether the BVH builder's passes (`DispatchX` with `DISPATCH_THREAD_DIMENSIONS`, the title's +/// `XboxBvhBuilder.dll`) run: off unless `XCL_BVH_BUILDER=1`. While its 52 pipelines compile one +/// by one, partial runs write garbage bounds/pointers into title memory and crash or hang world load. +fn bvh_builder_runs(flags: u32, enabled: bool) -> bool { + flags & DISPATCH_THREAD_DIMENSIONS == 0 || enabled +} + +pub(super) fn bvh_builder_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_BVH_BUILDER").is_ok_and(|v| v.trim() == "1")) +} + +/// `XCL_TRACE_RANGE=-` (hex addresses; a diagnostic): the compute work whose descriptor +/// tables or root views hold a buffer view over `[lo, hi)`. +pub(super) fn trace_range_of() -> Option<(u64, u64)> { + trace_range() +} + +fn trace_range() -> Option<(u64, u64)> { + static V: std::sync::OnceLock> = std::sync::OnceLock::new(); + *V.get_or_init(|| { + let v = std::env::var("XCL_TRACE_RANGE").ok()?; + let (lo, hi) = v.trim().split_once('-')?; + let hex = |t: &str| u64::from_str_radix(t.trim().trim_start_matches("0x"), 16).ok(); + Some((hex(lo)?, hex(hi)?)) + }) +} + +/// `XCL_TRACE_RANGE`: compute work (`what`) recorded with pipeline `pso`: each (pipeline, table, +/// slot) with a buffer view over the range is logged the first time and at powers of 16. +unsafe fn trace_range_work(this: *mut c_void, pso: usize, what: &str) { + let Some((lo, hi)) = trace_range() else { return }; + let (layout, args) = with(this, |s| (s.layout.clone(), s.args.clone())); + let Some(layout) = layout else { return }; + static SEEN: Mutex>> = Mutex::new(None); + let seen = |key: (usize, u32, u32)| { + let mut g = SEEN.lock().unwrap(); + let n = g.get_or_insert_with(HashMap::new).entry(key).or_insert(0); + *n += 1; + (*n == 1 || *n == 16 || *n == 256 || *n == 4096).then_some(*n) + }; + let real = super::pso_async::peek(pso); + let label = || format!("pipeline {pso:#x} (cs {:016x?}, translated {})", super::real::pso_shaders(real).map(|s| s.0), super::real::is_translated_compute(real)); + let word = |at: usize| args.get(at..at + 4).map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap())); + for (i, va) in console_list::root_views(&layout, &args).enumerate() { + if va + 0x1_0000 > lo && va < hi { + if let Some(n) = seen((pso, 1000, i as u32)) { + crate::xlog_info!("trace range: {what} #{n} of {}: root view {i} at {va:#x}", label()); + } + } + } + let mut tables = 0; + for p in layout.params.iter() { + let Param::Table { at } = *p else { continue }; + let t = word(at as usize); + for k in 0..256u32 { + if t == 0 { + break; + } + let Some(w) = super::console_heap::words_at(t.wrapping_add(32 * k)) else { break }; + let base = (((w[1] as u64) & 0xFFFF) << 32) | w[0] as u64; + let stride = ((w[1] >> 16) & 0x3FFF) as u64; + let bytes = if stride == 0 { w[2] as u64 } else { w[2] as u64 * stride }; + if bytes == 0 || bytes > 1 << 30 || base >= hi || base + bytes <= lo { + continue; + } + if let Some(n) = seen((pso, tables, k)) { + crate::xlog_info!("trace range: {what} #{n} of {}: table {tables} slot {k}: {w:08x?} = base {base:#x}, {bytes} bytes (stride {stride})", label()); + } + } + tables += 1; + } +} + +/// `XCL_DIAG_VIEWS=1` turns on per-dispatch descriptor-table view tracking (off by default: +/// locks `HEAPS` and `DISPATCH_VIEWS` on every compute dispatch). +fn diag_views_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_DIAG_VIEWS").is_ok_and(|v| v.trim() == "1")) +} + +/// The buffer descriptors (V#) in the first slots of a dispatch's descriptor tables, as the CPU +/// has them now: those in unified memory are written down (`real::note_dispatch_view`), so a +/// crash report can say which dispatches were given a view over an address. +unsafe fn note_dispatch_views(this: *mut c_void, pso: usize) { + if !diag_views_enabled() { + return; + } + let Some(u) = crate::gpu::uma::get() else { return }; + let (layout, args) = with(this, |s| (s.layout.clone(), s.args.clone())); + let Some(layout) = layout else { return }; + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); + for p in layout.params.iter() { + let Param::Table { at } = *p else { continue }; + let t = word(at as usize); + if t == 0 { + continue; + } + for k in 0..8u32 { + let Some(w) = super::console_heap::words_at(t.wrapping_add(32 * k)) else { break }; + let base = ((w[1] as u64 & 0xFFFF) << 32) | w[0] as u64; + let stride = ((w[1] >> 16) & 0x3FFF) as u64; + let bytes = if stride == 0 { w[2] as u64 } else { w[2] as u64 * stride }; + if bytes == 0 || bytes > 1 << 30 || u.window_of(base as usize).is_none() { + continue; + } + super::real::note_dispatch_view(base, bytes, pso); + } + } +} + +unsafe fn trace_preskin_cs(this: *mut c_void, pso: usize, kind: &str, groups: [u32; 3], flags: u32) { + let Some((cs_hash, _)) = super::real::pso_shaders(pso) else { return }; + if !matches!(cs_hash, 0x0d8cb7f3a2e49531 | 0x1404420b38db8597 | 0x44ca55bfefe67bd5 | 0x85c4edb089897347) { + return; + } + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let k = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if k >= 24 { + return; + } + let (layout, args) = with(this, |s| (s.layout.clone(), s.args.clone())); + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); + let mut tables = Vec::new(); + if let Some(l) = layout.as_ref() { + for (i, p) in l.params.iter().enumerate() { + if let Param::Table { at } = *p { + let t = word(at as usize); + tables.push((i, at, t)); + } + } + } + let t0 = tables.first().map(|x| x.2).unwrap_or(0); + let s24 = if t0 != 0 { super::console_heap::words_at(t0.wrapping_add(24 * 32)) } else { None }; + let s25 = if t0 != 0 { super::console_heap::words_at(t0.wrapping_add(25 * 32)) } else { None }; + let s33 = if t0 != 0 { super::console_heap::words_at(t0.wrapping_add(33 * 32)) } else { None }; + let s84 = if t0 != 0 { super::console_heap::words_at(t0.wrapping_add(84 * 32)) } else { None }; + crate::xlog_info!( + "trace preskin CS #{k} ({kind}) cs={cs_hash:016x} groups={groups:?} flags={flags:#x} tables={tables:x?} s24={s24:08x?} s25={s25:08x?} s33={s33:08x?} s84={s84:08x?}" + ); +} + /// `Dispatch` / `DispatchX(x, y, z, flags)`. pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { + if trace_range().is_some() { + trace_range_work(this, with(this, |s| s.pso), if bvh_builder_runs(flags, bvh_builder_enabled()) { "dispatch" } else { "BVH builder pass (left out)" }); + } + if !bvh_builder_runs(flags, bvh_builder_enabled()) { + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n == 1 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: BVH builder pass left out ({n} so far; XCL_BVH_BUILDER=1 runs them)"); + } + if super::real::trace_ms().is_some() { + static SEEN: Mutex>> = Mutex::new(None); + let pso = with(this, |s| s.pso); + let k = { let mut g = SEEN.lock().unwrap(); let k = g.get_or_insert_with(HashMap::new).entry(pso).or_insert(0); *k += 1; *k }; + if k == 1 || k == 64 || k == 4096 { + crate::xlog_info!("trace names: pass left out #{k} of pipeline {pso:#x} (cs {:016x?}): {x}x{y}x{z} flags {flags:#x}", super::real::pso_shaders(super::pso_async::peek(pso)).map(|s| s.0)); + } + } + return; + } let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::DispatchRecord); let (bound_pso, resolution) = with(this, |s| (s.pso, s.resolution.clone())); + note_dispatch_views(this, bound_pso); let _c = capture_work(this, || captured_dispatch(bound_pso, [x, y, z], flags), false); // (recorded at the submit through this call, with everything below: counted there) if let Some(resolution) = &resolution { @@ -4834,6 +5818,7 @@ pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, f } } super::targets::note_dispatch(); + super::ambient::diag_path("Dispatch", super::pso_async::peek(bound_pso), bound_pso, 0, 1); let Some(pso) = resolve_pipeline(this as usize, bound_pso, resolution) else { super::targets::note_compute(bound_pso, super::targets::Dispatched::Direct([0; 3])); skip_untranslated_dispatch(bound_pso); @@ -4849,6 +5834,7 @@ pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, f // 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) skip_untranslated_dispatch(pso); + super::left_out::direct(pso, launch.map(|(g, _)| g)); return; } let Some((groups, limits)) = launch else { @@ -4870,10 +5856,19 @@ pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, f if flags & DISPATCH_THREAD_DIMENSIONS != 0 { note_thread_dimensions([x, y, z], groups, super::real::pso_threads_exact(pso).unwrap_or_default()); } + if super::real::trace_preskin() { + trace_preskin_cs(this, pso, "direct", groups, flags); + } // (more groups than the PC takes in one dimension are folded or left out there, not skipped) let done = translated_dispatch(this, list, bound_pso, pso, groups[0], groups[1], groups[2], limits); match done { - Ok(()) => count(DISPATCHES), + Ok(()) => { + count(DISPATCHES); + if super::ambient::has_compute_psos() && groups[0] > 0 && groups[1] > 0 && groups[2] > 0 { + let (layout, args, view_heap) = with(this, |s| (s.layout.clone(), s.args.clone(), s.heaps[0])); + super::ambient::after_compute_dispatch(this, super::ambient::role_pso(pso, bound_pso), groups, layout.as_deref(), &args, view_heap, None); + } + } Err(e) => { count(DISPATCHES_SKIPPED); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -4971,6 +5966,7 @@ pub(super) unsafe extern "system" fn allocate_upload_memory(this: *mut c_void, s let align = align.max(16); if size <= crate::gpu::uma::ARENA_BLOCK / 2 { if let Some(p) = with(this, |s| s.arena.take(u, size, align, &mut s.uma)) { + crate::hle::kernelx::pagelog::note("upload memory given to the title (list arena)", p as usize, 0, size); return p; } } @@ -5162,11 +6158,13 @@ unsafe fn set_abi_roots(list: &ID3D12GraphicsCommandList, b: &Bound, gfx: bool) if gfx { list.SetGraphicsRootSignature(&b.rs); for (k, v) in b.views.iter().enumerate() { + super::real::note_root_view(list.as_raw() as usize, k as u32, *v); list.SetGraphicsRootUnorderedAccessView(k as u32, *v); } } else { list.SetComputeRootSignature(&b.rs); for (k, v) in b.views.iter().enumerate() { + super::real::note_root_view(list.as_raw() as usize, k as u32, *v); list.SetComputeRootUnorderedAccessView(k as u32, *v); } } @@ -5294,8 +6292,13 @@ unsafe fn bind_abi_with_root_resolved( let prepared = prepare_abi_state(this, u, gfx, user_sgprs)?; let PreparedAbiState { layout, args, inline, table_at, io_at, res_at, allocator, heaps } = prepared; want_root_views(layout.as_deref(), &args, super::view_want::Path::RootView); - if super::placements::any_superseded() { - note_superseded_in_tables(u, layout.as_deref(), &args); + if gfx { + trace_table_slot(u, layout.as_deref(), &args, original); + } + let check_sup = super::placements::any_superseded(); + let check_shad = super::title_textures::has_shadowed(); + if check_sup || check_shad { + scan_bound_tables(u, layout.as_deref(), &args, check_sup, check_shad); } std::ptr::copy_nonoverlapping(args[inline..].as_ptr(), table_at as *mut u8, args.len() - inline); let io = prepared_abi_io(layout.as_deref(), &args, table_at, gfx, user_sgprs, u.base(), heaps, limits, groups, group_limit); @@ -5317,6 +6320,28 @@ unsafe fn bind_abi_with_root_resolved( views[2 + k] = super::real::uma_window_va(k).filter(|&v| v != 0).unwrap_or(first); } let pc = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("pipeline")?.clone(); + // (bound tables already checked by `scan_bound_tables` above; a bake pipeline's draws + // (`pso_async::is_kept`) also check the ones they pick by index) + if gfx { + let bake = super::pso_async::is_kept(original); + let trace = super::indexed::trace_on(); + let uncover = (bake || super::indexed::uncover_all()) && super::title_textures::has_shadowed(); + // (a bake's sources are seen to again at its list's submit, shadowed now or not) + let keep = bake && super::title_textures::bake_at_submit(); + if let Some(l) = layout.as_deref().filter(|_| trace || uncover || keep) { + let indices = super::indexed::indices(l, &args, u); + // (what the draw finds, before it is seen to) + if trace { + super::indexed::trace_draw(this, pso, &indices, heaps[0], bake); + } + if uncover { + uncover_indexed(&indices, heaps[0], bake); + } + if keep { + keep_bake_sources(this, super::indexed::resources(&indices, heaps[0])); + } + } + } let b = Bound { rs, views, original, pso: pc, io: views[0], allocator }; set_abi_roots(list, &b, gfx); if root == 0 { @@ -5338,6 +6363,19 @@ pub(super) fn counts_snapshot() -> [u64; 5] { std::array::from_fn(|k| COUNTS[k].load(Ordering::Relaxed)) } +/// Tracked console `(graphics_root_signature, compute_root_signature)` on `list` for restoring +/// PC root signatures after an internal graphics/compute sync pass (invalidating cached view heap +/// binding state since the internal pass clobbered descriptor heaps / root signatures). +pub(super) fn tracked_root_sigs(list: *mut c_void) -> (usize, usize) { + if STATES.get(list as usize).is_none() { + return (0, 0); + } + with(list, |s| { + s.heap_bound = false; + (s.rs_gfx, 0) + }) +} + #[cfg(test)] pub(super) fn tracked_pso(list: *mut c_void) -> usize { let Some(entry) = STATES.get(list as usize) else { return 0 }; @@ -6600,6 +7638,25 @@ void main(uint t : SV_GroupIndex) { remove_state_for_test(to); } + /// The textures a recording's bake draws pick (`keep_bake_sources`) are taken once, each + /// once, at the submit of its lists, and a reset drops those of a recording not submitted. + #[test] + fn a_recordings_bake_sources_are_taken_at_its_submit_and_dropped_at_its_reset() { + let (a, b) = (0x7103_0001usize as *mut c_void, 0x7103_0002usize as *mut c_void); + let unknown = 0x7103_0003usize as *mut c_void; + keep_bake_sources(a, vec![0xA1, 0xA2]); + keep_bake_sources(a, vec![0xA2, 0xA3]); + keep_bake_sources(b, vec![0xA3, 0xB1]); + assert_eq!(bake_sources(&[a, b, unknown]), vec![0xA1, 0xA2, 0xA3, 0xB1]); + assert!(STATES.get(unknown as usize).is_none(), "a list with no state gets none"); + assert!(bake_sources(&[a, b]).is_empty(), "a list submitted again has them made ready once"); + keep_bake_sources(a, vec![0xA4]); + install_reset(a, 0, 0, None); + assert!(bake_sources(&[a]).is_empty()); + remove_state_for_test(a); + remove_state_for_test(b); + } + #[test] fn reset_keys_uma_to_the_lists_native_allocator_backing() { let list = 0x7101_7001usize as *mut c_void; @@ -8155,10 +9212,257 @@ void main(uint t : SV_GroupIndex) { assert_eq!(p.bytes, 0); } + /// A kept buffer whose recording's submit fences passed is taken again at once, one an + /// allocator reset handed back only after its hold (`retire_age`); and one goes idle + /// `FREE_RES_IDLE` after it could first be taken. (Measured from when it was handed back, a + /// hold as long as `FREE_RES_IDLE` let it go the moment it could be taken.) + #[test] + fn kept_two_pass_buffers_are_taken_after_their_hold_and_go_idle_after_that() { + use std::time::{Duration, Instant}; + let (t, ms) = (Instant::now(), Duration::from_millis(1)); + let retire = Duration::from_secs(2); + let mib = 1u64 << 20; + let mut p: FreePool<&str> = FreePool::new(1 << 30); + p.put_held(t, free_hold(false, retire), mib, 1, "after an allocator reset"); + p.put_held(t, free_hold(true, retire), mib, 1, "after its fences"); + assert_eq!(p.take_at(t, 1, 0, u64::MAX), Some("after its fences"), "the GPU is done with it: at once"); + assert_eq!(p.take_at(t + retire - ms, 1, 0, u64::MAX), None, "held"); + assert!(p.take_idle(t + retire, FREE_RES_IDLE).is_empty(), "not idle the moment it can be taken"); + assert!(p.take_idle(t + retire + FREE_RES_IDLE - ms, FREE_RES_IDLE).is_empty()); + assert_eq!(p.take_at(t + retire + FREE_RES_IDLE - ms, 1, 0, u64::MAX), Some("after an allocator reset")); + // idle only once it could be taken for `FREE_RES_IDLE`, of every hold + p.put_held(t, retire, mib, 1, "held"); + p.put(t + retire, mib, 1, "not held"); + assert!(p.take_idle(t + retire + FREE_RES_IDLE - ms, FREE_RES_IDLE).is_empty()); + assert_eq!(p.take_idle(t + retire + FREE_RES_IDLE, FREE_RES_IDLE), vec!["held", "not held"]); + assert_eq!((p.bytes, p.free.len()), (0, 0)); + } + + /// A scratch block takes a kept buffer of up to twice its size, else a new one is made; a larger + /// one (a record buffer the next recording needs) only when no new one can be made. + #[test] + fn scratch_blocks_take_kept_buffers_of_their_size() { + use std::time::Instant; + let (t, kib) = (Instant::now(), 1u64 << 10); + assert_eq!(scratch_window(SCRATCH_BLOCK, SCRATCH_CAP), (SCRATCH_BLOCK, 2 * SCRATCH_BLOCK, SCRATCH_CAP)); + assert_eq!(scratch_window(SCRATCH_BLOCK, SCRATCH_BLOCK), (SCRATCH_BLOCK, SCRATCH_BLOCK, SCRATCH_BLOCK), "within what the recording has left"); + let (min, preferred, most) = scratch_window(SCRATCH_BLOCK, SCRATCH_CAP); + let mut p: FreePool<&str> = FreePool::new(1 << 30); + p.put(t, 12 << 20, 1, "12 MiB of records"); + assert_eq!(p.take_at(t, 1, min, preferred), None, "the record buffer stays for records"); + p.put(t, 384 * kib, 1, "384 KiB"); + assert_eq!(p.take_at(t, 1, min, preferred), Some("384 KiB")); + assert_eq!(p.take_at(t, 1, min, most), Some("12 MiB of records"), "when no new one can be made"); + } + + /// A two-pass ExecuteIndirect of a pipeline whose feedback slot has given no readback yet asks + /// for at most `XCL_TWO_PASS_COLD_MB` (4 MiB: 628 groups of 6,672 B records, not the 32 MiB of + /// its draw alone); a command with more keeps 628 and its slot's next readback sizes the + /// pipeline's draws as they would be alone. Without a slot, or with the limit off, as alone. + #[test] + fn cold_indirect_draws_ask_for_the_cold_records_until_their_feedback() { + let mib = 1u64 << 20; + let alone = indirect_record_need_hint(6672, 1, None); + assert_eq!(alone, 32 * mib); + let cold = cold_record_need(alone, None, true, 4 * mib); + assert_eq!(cold, 4 * mib); + assert_eq!(record_groups(record_buffer_bytes(cold), 6672, 1), 628); + assert_eq!(cold_record_need(alone, None, false, 4 * mib), alone, "no slot: nothing would ever say it needs more"); + assert_eq!(cold_record_need(alone, None, true, 0), alone, "XCL_TWO_PASS_COLD_MB=0"); + assert_eq!(cold_record_need(mib, None, true, 4 * mib), mib, "never more than the draw alone"); + // a command of 5,000 groups at its first draw: 628 kept, and the readback after it (the + // slot's cap was 628) gives the draws after it all of them + let mut slot = IndirectFeedbackSlot::new(); + slot.in_flight_cap = record_groups(record_buffer_bytes(cold), 6672, 1); + slot.apply_window(5_000 + 1); + let hint = slot.hint(); + assert_eq!(hint, Some(5_000)); + assert_eq!(cold_record_need(indirect_record_need_hint(6672, 1, hint), hint, true, 4 * mib), alone); + // one with no groups: the least record buffer + let mut empty = IndirectFeedbackSlot::new(); + empty.in_flight_cap = 628; + empty.apply_window(1); + assert_eq!(cold_record_need(indirect_record_need_hint(6672, 1, empty.hint()), empty.hint(), true, 4 * mib), RECORD_MIN); + } + + /// What `replay_two_pass_buffers` saw, by kind (0: argument scratch blocks, 1: record buffers). + #[derive(Debug, Default)] + struct Replay { + /// asked for, taken again from the pool, made, refused at the cap + asked: [u64; 2], + taken: [u64; 2], + made: [u64; 2], + refused: [u64; 2], + /// bytes of two-pass buffers alive at most, and of the ones recordings held at most + peak_alive: u64, + peak_held: u64, + /// the same at the end + end_alive: u64, + end_held: u64, + } + + /// The rules of `FREE_RES` a replay follows. + #[derive(Clone, Copy, Debug, PartialEq)] + enum PoolRules { + /// as merged into amd/next: every buffer handed back held for `retire_age` (amd-dev's + /// `take`), while the idle ones went `FREE_RES_IDLE` after they were handed back whenever + /// more were (main's `put_free_bufs`) – both 2 s; a scratch block took any kept buffer up to + /// its recording's 16 MiB; a cold ExecuteIndirect asked for what its draw would alone + Merged, + /// `free_hold`, `scratch_window`, `cold_record_need` + Now, + } + + /// `acquire_two_pass_buf_with_cap` in a replay: a kept buffer within `preferred`, else a new one + /// within the cap (the oldest kept go to make room), else a kept one up to `most` (no fence + /// waits, no shrinking). + #[allow(clippy::too_many_arguments)] + fn replay_acquire(pool: &mut FreePool, alive: &mut u64, cap: u64, r: &mut Replay, now: std::time::Instant, kind: usize, (min, preferred, most): (u64, u64, u64)) -> Option { + r.asked[kind] += 1; + // (`take_free`: the idle ones go first) + for b in pool.take_idle(now, FREE_RES_IDLE) { + *alive -= b; + } + if let Some(b) = pool.take_at(now, 1, min, preferred) { + r.taken[kind] += 1; + return Some(b); + } + if *alive + min > cap { + for b in pool.take_room(*alive + min - cap).unwrap_or_default() { + *alive -= b; + } + } + if *alive + min <= cap { + *alive += min; + r.made[kind] += 1; + return Some(min); + } + if let Some(b) = pool.take_at(now, 1, min, most) { + r.taken[kind] += 1; + return Some(b); + } + r.refused[kind] += 1; + None + } + + /// The two-pass buffers of 30 s of a retail world (next-r6: RX 9070 XT, `XCL_TWO_PASS_MB=1024`, + /// no batching, 6.7 frames a second): a dozen recordings a frame with two-pass ExecuteIndirects + /// of 6,672 B records, each with an argument scratch block and a record buffer as large as its + /// largest draw so far (`ensure_res_buffer_with_cap`), handed back when its submit fences pass + /// three frames on (`reclaim_fenced`; the run had 77 buffers in flight at world entry). Every + /// recording's first draw is of a pipeline with no feedback yet for the first 8 frames. + fn replay_two_pass_buffers(rules: PoolRules) -> Replay { + use std::time::{Duration, Instant}; + const FRAMES: u32 = 200; + const LISTS: u32 = 12; + const DRAWS: u32 = 6; + const LAG: u32 = 3; + const COLD_FRAMES: u32 = 8; + const RECORD: u64 = 6672; + // the groups a pipeline's feedback holds at most: most none or a few (of 12,032 draws of + // one program 10,246 read back empty, amd-dev's XCL_TRACE_ARGS) + const GROUPS: [u32; 9] = [0, 0, 0, 3, 8, 20, 60, 150, 600]; + let frame = Duration::from_millis(150); + // (`console_list::retire_age`'s default) + let retire = Duration::from_secs(2); + let cap = 1u64 << 30; + let t0 = Instant::now(); + let mut pool: FreePool = FreePool::new(cap.min(FREE_RES_CAP)); + let mut alive = 0u64; + let mut r = Replay::default(); + let mut held: VecDeque<(u32, Vec)> = VecDeque::new(); + let mut seed = 0x2545_f491_4f6c_dd1du64; + for f in 0..FRAMES { + let now = t0 + frame * f; + while held.front().is_some_and(|&(done, _)| done <= f) { + let (_, bufs) = held.pop_front().unwrap(); + let (hold, idle) = match rules { + PoolRules::Merged => (retire, Duration::ZERO), + PoolRules::Now => (free_hold(true, retire), FREE_RES_IDLE), + }; + for b in pool.take_idle(now, idle) { + alive -= b; + } + for b in bufs { + for gone in pool.put_held(now, hold, b, 1, b) { + alive -= gone; + } + } + } + for _ in 0..LISTS { + let mut bufs = Vec::new(); + let scratch = match rules { + PoolRules::Merged => (SCRATCH_BLOCK, SCRATCH_CAP, SCRATCH_CAP), + PoolRules::Now => scratch_window(SCRATCH_BLOCK, SCRATCH_CAP), + }; + if let Some(b) = replay_acquire(&mut pool, &mut alive, cap, &mut r, now, 0, scratch) { + bufs.push(b); + let mut have = 0; + for d in 0..DRAWS { + let hint = (f >= COLD_FRAMES || d > 0).then(|| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + GROUPS[(seed % GROUPS.len() as u64) as usize] + }); + let need = indirect_record_need_hint(RECORD, 1, hint); + let need = record_buffer_bytes(if rules == PoolRules::Now { cold_record_need(need, hint, true, cold_records_bytes()) } else { need }); + if have >= need { + continue; + } + if let Some(b) = replay_acquire(&mut pool, &mut alive, cap, &mut r, now, 1, (need, need.saturating_mul(2), u64::MAX)) { + have = b; + bufs.push(b); + } + } + } + held.push_back((f + LAG, bufs)); + } + let held_now: u64 = held.iter().flat_map(|(_, b)| b.iter()).sum(); + (r.peak_held, r.peak_alive) = (r.peak_held.max(held_now), r.peak_alive.max(alive)); + (r.end_held, r.end_alive) = (held_now, alive); + } + r + } + + /// Replayed (`replay_two_pass_buffers`), the buffers kept for reuse are taken again and the + /// two-pass buffers alive stay near what the recordings hold, with no draw refused at world + /// entry. As merged, next to nothing was taken again: buffers were held as long as they were + /// kept, so they went just as they could be taken (next-r6: 179 of 18,369 taken again, 1 GiB + /// alive with 550 MiB kept), and cold draws of 32 MiB each took the buffers to the cap. + #[test] + fn two_pass_buffers_are_taken_again_and_stay_near_what_recordings_hold() { + let mib = |b: u64| b >> 20; + for rules in [PoolRules::Merged, PoolRules::Now] { + let r = replay_two_pass_buffers(rules); + for (k, kind) in ["argument scratch", "record buffers"].iter().enumerate() { + println!( + "{rules:?} {kind}: {} asked, {} taken again ({:.1} %), {} made, {} refused", + r.asked[k], + r.taken[k], + 100.0 * r.taken[k] as f64 / r.asked[k].max(1) as f64, + r.made[k], + r.refused[k] + ); + } + println!("{rules:?}: alive at most {} MiB (recordings held at most {} MiB); at the end {} MiB alive, {} MiB held", mib(r.peak_alive), mib(r.peak_held), mib(r.end_alive), mib(r.end_held)); + } + let merged = replay_two_pass_buffers(PoolRules::Merged); + assert!(merged.taken[0] * 10 < merged.asked[0] && merged.taken[1] * 10 < merged.asked[1], "as merged, next to nothing is taken again: {merged:?}"); + assert!(merged.refused.iter().sum::() > 0, "as merged, cold draws reach the cap: {merged:?}"); + let now = replay_two_pass_buffers(PoolRules::Now); + assert_eq!(now.refused, [0, 0], "{now:?}"); + for k in 0..2 { + assert!(now.taken[k] * 10 >= now.asked[k] * 9, "nine in ten taken again: {now:?}"); + } + assert!(now.peak_alive <= 2 * now.peak_held, "alive at most twice what the recordings hold: {now:?}"); + assert!(now.end_alive <= 2 * now.end_held, "{now:?}"); + } + /// Record buffers come in half-step sizes from 256 KiB, and a draw has at least as many /// groups as before: none drops groups it drew under power-of-two MiB buckets. Cold - /// ExecuteIndirect starts at full `indirect_record_need` (no cold clamping) before shrinking - /// on feedback. + /// ExecuteIndirect starts at full `indirect_record_need` (no cold clamping; the draws' limit is + /// `cold_record_need`'s) before shrinking on feedback. #[test] fn two_pass_record_buffers_fit_what_their_draws_need() { let kib = 1u64 << 10; @@ -8932,6 +10236,227 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) } } + /// Deferred runs (`batch_commands`) on the GPU with stand-ins for the two passes and XCL's + /// argument rewrite: the "compute pass" writes each group's record (from the start of its + /// region) with its draw's number, the "mesh pass" (a mesh shader) copies the records it reads + /// out by draw. One recording's draws (DispatchMesh and one-command ExecuteIndirect, some + /// with no groups) in two runs whose regions start again at the start of its batch record + /// buffer (`batch_open` before the second), then another recording's run in a batch record + /// buffer of its own, both lists in one submit: every mesh pass reads its own draw's records. + #[test] + fn gpu_deferred_runs_read_their_own_records() { + use crate::gpu::recomp::runner::skip_test; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC}; + #[repr(C, align(8))] + struct Sub { + ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, + v: T, + } + #[repr(C)] + struct Stream { + rs: Sub<*mut c_void>, + ms: Sub, + mask: Sub, + rast: Sub, + depth: Sub, + rtv: Sub, + samples: Sub, + } + let src = r#" +#define RS "UAV(u0), UAV(u1), UAV(u2), UAV(u3), UAV(u4), UAV(u5)" +RWByteAddressBuffer io : register(u0); +RWByteAddressBuffer rec : register(u1); +RWByteAddressBuffer o : register(u2); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void cs(uint3 g : SV_GroupID) { rec.Store(g.x * 4u, io.Load(0)); } +struct V { float4 p : SV_Position; }; +[RootSignature(RS)] +[outputtopology("triangle")] +[numthreads(1, 1, 1)] +void ms(uint3 g : SV_GroupID, out vertices V v[3], out indices uint3 t[1]) { + SetMeshOutputCounts(0, 0); + // (never: io dword 1 is 0; the validator wants the outputs written) + if (io.Load(4) != 0u) { v[0].p = float4(0.0f, 0.0f, 0.0f, 1.0f); t[0] = uint3(0u, 0u, 0u); } + o.Store((io.Load(0) * 16u + g.x) * 4u, rec.Load(g.x * 4u)); +} +"#; + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + skip_test("no GPU"); + return; + } + if !crate::gpu::recomp::runner::mesh_shaders_supported().unwrap_or(false) { + skip_test("no mesh shaders"); + return; + } + let dev = dev.unwrap(); + // (recording, run, draw number, groups, ExecuteIndirect) + let draws: [(usize, usize, u32, u32, bool); 10] = + [(0, 0, 1, 3, false), (0, 0, 2, 0, true), (0, 0, 3, 4, true), (0, 1, 4, 1, false), (0, 1, 5, 2, true), (0, 1, 6, 4, true), (1, 0, 7, 2, true), (1, 0, 8, 4, false), (1, 0, 9, 0, true), (1, 0, 10, 3, true)]; + unsafe { + let cs = crate::gpu::recomp::dxc::compile(src, "cs", "cs_6_6", &[]).unwrap(); + let msb = crate::gpu::recomp::dxc::compile(src, "ms", "ms_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &cs).unwrap(); + let cpso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as _, BytecodeLength: cs.len() }, + ..Default::default() + }) + .unwrap(); + let mut stream = Stream { + rs: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, v: rs.as_raw() }, + ms: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, v: D3D12_SHADER_BYTECODE { pShaderBytecode: msb.as_ptr() as _, BytecodeLength: msb.len() } }, + mask: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, v: u32::MAX }, + rast: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, v: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() } }, + depth: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, v: D3D12_DEPTH_STENCIL_DESC::default() }, + rtv: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, v: D3D12_RT_FORMAT_ARRAY::default() }, + samples: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, v: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 } }, + }; + let dev2: ID3D12Device2 = dev.cast().unwrap(); + let mpso: ID3D12PipelineState = dev2 + .CreatePipelineState(&D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: std::mem::size_of::(), pPipelineStateSubobjectStream: &mut stream as *mut Stream as *mut c_void }) + .unwrap(); + let sig_of = |ty: D3D12_INDIRECT_ARGUMENT_TYPE| -> ID3D12CommandSignature { + let a = [D3D12_INDIRECT_ARGUMENT_DESC { Type: ty, ..Default::default() }]; + let mut s: Option = None; + dev.CreateCommandSignature(&D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 12, NumArgumentDescs: 1, pArgumentDescs: a.as_ptr(), NodeMask: 0 }, None, &mut s).unwrap(); + s.unwrap() + }; + let (dsig, msig) = (sig_of(D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH), sig_of(D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH)); + let (rw_rs, rw_pso) = scale_indirect_pipeline(&dev).unwrap(); + let buffer = |bytes: u64, cpu: bool| -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let heap = if cpu { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() } + } else { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() } + }; + let mut r: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + }; + // one block of 256 B a draw: [the commands at 32-byte steps (the title's), io, rewrite constants] + let (mem, out) = (buffer(3 * 256 * 16, true), buffer(256 * 16 * 4, true)); + // (each recording's batch record buffer, and its argument scratch block) + let records = [buffer(256 * 4, false), buffer(256 * 4, false)]; + let scratch = [buffer(256 * 16, false), buffer(256 * 16, false)]; + let map = |b: &ID3D12Resource| -> *mut u32 { + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).unwrap(); + p as *mut u32 + }; + let (m, o) = (map(&mem), map(&out)); + std::ptr::write_bytes(o, 0, 256 * 16); + let mem_va = mem.GetGPUVirtualAddress(); + let (args_at, io_at, consts_at) = (0u64, 256 * 16, 2 * 256 * 16); + let mut steps: [Vec>; 2] = [vec![Vec::new(), Vec::new()], vec![Vec::new()]]; + let mut slot = [0u64; 2]; + for &(list, run, d, groups, indirect) in &draws { + let k = d as u64; + std::ptr::copy_nonoverlapping([groups, 1, 1].as_ptr(), m.add((args_at / 4 + 8 * k) as usize), 3); + *m.add(((io_at + 256 * k) / 4) as usize) = d; + // its region: from the start of the buffer in each run (`batch_region` after a flush) + let at = steps[list][run].len() as u64; + let region = records[list].GetGPUVirtualAddress() + 256 * at; + let io = mem_va + io_at + 256 * k; + let views = [io, region, out.GetGPUVirtualAddress(), io, io, io]; + let work = if indirect { + // (count 1, stride 12, the DispatchMesh argument at 0, split 1, cap 4; no count + // buffer, no feedback slot) + let c = [1u32, 12, 0, 1, 4, 0, 0, 0, 0, 0]; + std::ptr::copy_nonoverlapping(c.as_ptr(), m.add(((consts_at + 256 * k) / 4) as usize), c.len()); + let dst = slot[list] * 256; + slot[list] += 1; + let rewrite = Rewrite { rs: rw_rs.as_raw() as usize, pso: rw_pso.as_raw() as usize, views: scale_views(mem_va + consts_at + 256 * k, None, mem_va + args_at + 32 * k, scratch[list].GetGPUVirtualAddress() + dst, None), groups: 1 }; + // (a later run of the recording finds its block in INDIRECT_ARGUMENT) + let before = if run == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT }; + DeferredWork::Indirect { rewrite, block: scratch[list].as_raw() as usize, before, companion: dsig.as_raw() as usize, sig: msig.as_raw() as usize, compute_at: dst, mesh_at: dst + 12 } + } else { + DeferredWork::Mesh { groups, mesh_groups: groups } + }; + let stage = |pso: &ID3D12PipelineState| StageBind { rs: rs.as_raw() as usize, pso: pso.as_raw() as usize, views }; + steps[list][run].push(Step::Draw(DrawSnap { compute: stage(&cpso), mesh: stage(&mpso), work })); + } + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut lists = Vec::new(); + for (list, runs) in steps.iter().enumerate() { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let l: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let l6: ID3D12GraphicsCommandList6 = l.cast().unwrap(); + for (run, run_steps) in runs.iter().enumerate() { + // a later run of a recording: the last one's mesh passes may still read its + // buffer (`flush_two_pass` leaves `batch_open`); a buffer just taken: none + let open = run > 0; + for c in batch_commands(run_steps, records[list].as_raw() as usize, open) { + let res = |raw: usize| { + let p = raw as *mut c_void; + ID3D12Resource::from_raw_borrowed(&p).cloned() + }; + match c { + Cmd::Barriers { all, uav, transitions } => { + let uav = uav.and_then(res); + let held: Vec<(ID3D12Resource, D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES)> = transitions.iter().filter_map(|&(r, a, b)| Some((res(r)?, a, b))).collect(); + let t: Vec<_> = held.iter().map(|(r, a, b)| (r, *a, *b)).collect(); + emit_barrier_set(&l, all, uav.as_ref(), &t); + } + Cmd::ComputeRs(r) => { + let p = r as *mut c_void; + l.SetComputeRootSignature(ID3D12RootSignature::from_raw_borrowed(&p)); + } + Cmd::GraphicsRs(r) => { + let p = r as *mut c_void; + l.SetGraphicsRootSignature(ID3D12RootSignature::from_raw_borrowed(&p)); + } + Cmd::Pso(p) => { + let p = p as *mut c_void; + l.SetPipelineState(ID3D12PipelineState::from_raw_borrowed(&p)); + } + Cmd::ComputeView(s, va) => l.SetComputeRootUnorderedAccessView(s, va), + Cmd::GraphicsView(s, va) => l.SetGraphicsRootUnorderedAccessView(s, va), + Cmd::Dispatch(n) => l.Dispatch(n, 1, 1), + Cmd::DispatchMesh(n) => l6.DispatchMesh(n, 1, 1), + Cmd::Indirect(sig, b, at) => { + let (sp, bp) = (sig as *mut c_void, b as *mut c_void); + l.ExecuteIndirect(ID3D12CommandSignature::from_raw_borrowed(&sp).unwrap(), 1, ID3D12Resource::from_raw_borrowed(&bp).unwrap(), at, None::<&ID3D12Resource>, 0); + } + Cmd::Bind(_) | Cmd::StencilRef(_) | Cmd::Topology(_) | Cmd::Scissors(_) | Cmd::TimesBegin(_) | Cmd::TimesEnd => {} + } + } + } + emit_transition(&l, &scratch[list], D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + l.Close().unwrap(); + lists.push((alloc, l)); + } + let submit: Vec> = lists.iter().map(|(_, l)| Some(l.cast().unwrap())).collect(); + queue.ExecuteCommandLists(&submit); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 10_000).unwrap(); + for &(_, _, d, groups, indirect) in &draws { + let got: Vec = (0..4).map(|g| *o.add((d * 16 + g) as usize)).collect(); + let want: Vec = (0..4).map(|g| if g < groups { d } else { 0 }).collect(); + assert_eq!(got, want, "the records the mesh pass of draw {d} read (ExecuteIndirect {indirect})"); + } + mem.Unmap(0, None); + out.Unmap(0, None); + } + } + /// With heap windows the two-pass programs read the memory windows from the shared heap /// (`pso::mem_windows`): both passes' binds set it on a list that has none, as `bind_abi` does. /// (Heap windows are opt-in: run with `XCL_HEAP_WINDOWS=1`, else skipped.) @@ -10133,7 +11658,7 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} let buf = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "pool cap test") }.unwrap(); let expected_cap = two_pass_cap().min(FREE_RES_CAP); - put_free_bufs(vec![buf]); + put_free_bufs(vec![buf], true); let pool_cap = FREE_RES.lock().unwrap().cap; while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} assert_eq!(pool_cap, expected_cap); diff --git a/crates/xcl/src/hle/d3d12x/bvh_spare.rs b/crates/xcl/src/hle/d3d12x/bvh_spare.rs new file mode 100644 index 0000000000..017eb32472 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/bvh_spare.rs @@ -0,0 +1,148 @@ +//! `XCL_BVH_SPARE` (default on; `=0` turns it off): while the title's BVH builder does not run +//! (`XCL_BVH_BUILDER` unset, `bind::bvh_builder_enabled`), binds do not wait for a compute +//! pipeline made from one of the builder's programs – those of the title's `XboxBvhBuilder.dll`, +//! known by the module their byte code lies in or by the builder's name in their debug data +//! (`ILDN`). The bind goes on with the stand-in while the pipeline is built +//! (`pso_async::image_only`), as it did once its wait had run out (`XCL_CS_PSO_WAIT_MS`). +//! +//! The builder's passes are left out while it does not run (`bind::bvh_builder_runs`), so a +//! wait for one of its pipelines held a title thread for nothing. On a cold driver cache a +//! retail title's recording thread waited 20 s (`XCL_CS_PSO_WAIT_MS=20000`) for one builder +//! pipeline after another while the world loaded behind its movies: 11 – 13 times in a row, +//! 220 – 260 s with no frame presented (12 of the 13 programs it waited for in one run were +//! byte for byte the DLL's, the 13th a program of the title's own). + +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::OnceLock; + +use windows::Win32::Graphics::Direct3D12::D3D12_COMPUTE_PIPELINE_STATE_DESC; + +/// The builder's DLL, as `modules` names a mapped image. +const MODULE: &str = "xboxbvhbuilder.dll"; +/// The builder's name, as its programs' debug data hold it (the path of their build). +const NAME: &[u8] = b"XboxBvhBuilder"; + +fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| on_of(std::env::var("XCL_BVH_SPARE").ok().as_deref())) +} + +/// An `XCL_BVH_SPARE` value: on unless `0`. +fn on_of(v: Option<&str>) -> bool { + v.is_none_or(|v| v.trim() != "0") +} + +/// Whether console program `cs` is one of the BVH builder's: its byte code lies in the +/// builder's DLL (`module`: the mapped image it lies in), or its container names the builder. +fn builder_program(cs: &[u8], module: Option<&str>) -> bool { + module == Some(MODULE) || cs.windows(NAME.len()).any(|w| w == NAME) +} + +/// Whether binds go on without the compute pipeline of console program `cs`: with the switch +/// `on`, a program of the builder while the builder does not run (`builder_runs`). +fn spared_with(cs: &[u8], module: Option<&str>, on: bool, builder_runs: bool) -> bool { + on && !builder_runs && builder_program(cs, module) +} + +/// Whether binds go on without the compute pipeline `desc` describes, built by the workers from +/// console program `cs` (the title's byte code copied): one of the BVH builder's while it does +/// not run. The first few are logged. +pub(super) unsafe fn spared(cs: &[u8], desc: *const c_void) -> bool { + if !on() || super::bind::bvh_builder_enabled() { + return false; + } + let at = if crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + (*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC)).CS.pShaderBytecode as usize + } else { + 0 + }; + let module = crate::modules::find_mapped_by_addr(at).map(|m| m.name.clone()); + if !spared_with(cs, module.as_deref(), true, false) { + return false; + } + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: compute pipeline of record {:016x} is one of the BVH builder's, whose passes are left out: binds go on without it while it is built (#{n}; XCL_BVH_SPARE=0 waits for them)", + crate::gpu::shader::fnv64(cs) + ); + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::hle::d3d12x::pso_async; + use std::sync::mpsc; + + /// The bytes of a container whose debug data name the builder, as those of the DLL's 52 + /// programs do (their `ILDN` part holds the path of their build); no complete container. + fn builder_container() -> Vec { + let mut c = b"DXBC".to_vec(); + c.extend_from_slice(&[0; 60]); + c.extend_from_slice(b"ILDN\x40\x00\x00\x00\x00\x00\x30\x00X:\\src\\3rdparty\\Microsoft\\XboxBvhBuilder\\Build\\Release\\Output\\a.pdb\x00"); + c.extend_from_slice(&[0xAB; 32]); + c + } + + #[test] + fn the_switch_is_on_unless_0() { + assert!(on_of(None)); + assert!(on_of(Some("1"))); + assert!(on_of(Some(""))); + assert!(!on_of(Some("0"))); + assert!(!on_of(Some(" 0 "))); + } + + #[test] + fn a_builder_program_is_known_by_its_module_or_its_name() { + let plain = vec![0x5Au8; 256]; + assert!(builder_program(&builder_container(), None)); + assert!(builder_program(&plain, Some(MODULE)), "byte code in the builder's DLL"); + assert!(!builder_program(&plain, None)); + assert!(!builder_program(&plain, Some("game_scarlett_master.exe"))); + assert!(!builder_program(b"XboxBvhBuilde", None), "a part of the name is not it"); + } + + #[test] + fn only_a_builder_program_is_spared_and_only_while_the_builder_does_not_run() { + let bvh = builder_container(); + assert!(spared_with(&bvh, None, true, false)); + assert!(!spared_with(&bvh, None, true, true), "XCL_BVH_BUILDER=1: its pipelines are waited for"); + assert!(!spared_with(&bvh, None, false, false), "XCL_BVH_SPARE=0"); + assert!(!spared_with(&[0u8; 128], None, true, false), "a program of the title's own"); + } + + /// A bind does not wait for a compute pipeline of the builder still being built: it gets the + /// stand-in at once; a pipeline of the title's own is still waited for. + #[test] + fn a_bind_does_not_wait_for_a_builder_pipeline_being_built() { + let (builder, own) = (0x7E57_B5A1usize, 0x7E57_B5A2usize); + let (go, finish) = mpsc::channel::<()>(); + pso_async::submit_lazy(builder, true, Box::new(move || { + let _ = finish.recv_timeout(std::time::Duration::from_secs(30)); + 0 + }), 0); + pso_async::submit_lazy(own, true, Box::new(|| 0), 0); + // (as `real::go_background` does with what `spared` says) + for (pso, cs) in [(builder, builder_container()), (own, vec![0u8; 128])] { + if spared_with(&cs, None, true, false) { + pso_async::image_only(pso); + } + } + assert!(!pso_async::waits_for(builder), "a dispatch with it does not wait either"); + assert!(pso_async::waits_for(own), "the title's own pipeline is waited for"); + // (on a thread: a bind that waits would wait for `go`, below) + let (bound_tx, bound) = mpsc::channel(); + std::thread::spawn(move || { + let _ = bound_tx.send(pso_async::resolve_for_bind(builder)); + }); + let bind = bound.recv_timeout(std::time::Duration::from_secs(5)); + let _ = go.send(()); + assert_eq!(bind.expect("the bind waited for the build"), builder, "still being built: the stand-in"); + let _ = (pso_async::released(builder), pso_async::released(own)); + } +} diff --git a/crates/xcl/src/hle/d3d12x/capture.rs b/crates/xcl/src/hle/d3d12x/capture.rs index 320b2fe1a1..2478381df5 100644 --- a/crates/xcl/src/hle/d3d12x/capture.rs +++ b/crates/xcl/src/hle/d3d12x/capture.rs @@ -220,7 +220,8 @@ pub(super) struct Work { root: Vec, delta: bool, heaps: [u32; 2], - /// resources the first slots of its descriptor tables name + /// resources the first slots of its descriptor tables name, and the textures it picks by index + /// through the view heap's slots (`indexed`) views: Vec, outcome: Option, } @@ -735,6 +736,27 @@ pub(super) fn note_stream(pso: usize) { g.get_or_insert_with(HashMap::new).entry(pso).or_insert_with(|| Arc::new(Pipe { kind: "stream", set: None, stages: Vec::new(), state: Value::Null, split: false })); } +/// Mesh pipeline `pso` was made from a stream with a console MS: its shaders by hash (no bytes +/// kept – a title makes tens of thousands of these and uses few), the depth state the stream +/// names (DepthEnable, DepthWriteMask, DepthFunc) and its render target formats. +pub(super) fn note_mesh_stream(pso: usize, stages: &[(&'static str, &[u8])], depth: Option<[u32; 3]>, formats: &[i32]) { + if !enabled() || pso == 0 { + return; + } + let stages = stages + .iter() + .map(|(s, b)| { + let h = crate::gpu::shader::fnv64(b); + (*s, super::real::shader_key_of_hash(h), h, None) + }) + .collect(); + let state = json!({ + "depth_stencil": depth.map(|d| json!({"depth": d[0] != 0, "write_mask": d[1], "func": d[2]})), + "rt_formats": formats, + }); + keep_pipe(pso, Pipe { kind: "mesh", set: None, stages, state, split: false }); +} + fn graphics_state(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Value { let n = (d.NumRenderTargets as usize).min(8); let b = &d.BlendState; diff --git a/crates/xcl/src/hle/d3d12x/clamp.rs b/crates/xcl/src/hle/d3d12x/clamp.rs index d18cf537ea..5fa9a609f9 100644 --- a/crates/xcl/src/hle/d3d12x/clamp.rs +++ b/crates/xcl/src/hle/d3d12x/clamp.rs @@ -212,8 +212,11 @@ unsafe fn pass(list: &ID3D12GraphicsCommandList, args: usize, off: u64, io_limit list.SetComputeRoot32BitConstant(0, slot as u32, 0); // (as `bind::fold_counts_within` bounds the product) list.SetComputeRoot32BitConstant(0, most.saturating_add(crate::gpu::recomp::FOLD_X), 1); + super::real::note_root_view(list.as_raw() as usize, 1, res.GetGPUVirtualAddress() + off); list.SetComputeRootUnorderedAccessView(1, res.GetGPUVirtualAddress() + off); + super::real::note_root_view(list.as_raw() as usize, 2, c.gpu); list.SetComputeRootUnorderedAccessView(2, c.gpu); + super::real::note_root_view(list.as_raw() as usize, 3, io_limit); list.SetComputeRootUnorderedAccessView(3, io_limit); list.Dispatch(1, 1, 1); // the slot for the dispatch's arguments; the io word for its program (a UAV barrier on all) diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 3c9dd506b8..b1e43a0838 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -1083,6 +1083,65 @@ fn finish_view_slot(h: &Heap, k: u32, page: Option<(u32, u32)>) -> Slot { Slot { generation: h.generation, 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, remaining: h.n - k } } +/// A console slot looked up without reserving a page in the shared shader-visible heap: +/// used for descriptors whose shaders read UMA directly (CBVs, buffer V#s, BVH SRVs) and +/// never index into the shared PC heap. +#[derive(Clone, Copy, Debug)] +pub struct ShadowSlot { + pub at: usize, + pub pc_srv: u64, + pub pc_uav: u64, + pub sampler: bool, + /// Present only if the heap is unpaged or this page already has a place in the shared heap. + pub index: Option, + /// Non-zero only if this page already has a place in the shared heap. + pub shared_srv: u64, +} + +/// Whether `cpu` lies inside any registered console descriptor heap (without reserving a page). +pub fn contains(cpu: u64) -> bool { + let heaps = HEAPS.lock().unwrap(); + heaps.iter().any(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64) +} + +/// Look up the console slot behind `cpu` without reserving a page in the shared heap. +pub fn shadow_slot(cpu: u64) -> Option { + let heaps = HEAPS.lock().unwrap(); + let h = heaps.iter().find(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64)?; + let k = ((cpu - h.shadow as u64) / h.slot_bytes() as u64) as u32; + if h.sampler { + let index = if h.pages.is_empty() { + Some(k) + } else { + h.pages.get((k / SAMPLER_PAGE_SLOTS) as usize).filter(|&&first| first != UNMAPPED).map(|&first| first + (k % SAMPLER_PAGE_SLOTS)) + }; + let shared_srv = index.filter(|_| !h.pages.is_empty()).and_then(|i| { + let g = GLOBAL_SAMPLER.lock().unwrap(); + let g = g.as_ref()?; + Some(g.cpu + i as u64 * g.inc as u64) + }).unwrap_or(0); + return Some(ShadowSlot { at: h.shadow + (k * SAMPLER_SLOT) as usize, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, sampler: true, index, shared_srv }); + } + let uav = ((2 * k + 1) * h.inc) as u64; + let index = if h.pages.is_empty() { + Some(2 * k) + } else { + h.pages.get((k / PAGE_SLOTS) as usize).filter(|&&first| first != UNMAPPED).map(|&first| first + 2 * (k % PAGE_SLOTS)) + }; + let shared_srv = index.filter(|_| !h.pages.is_empty()).and_then(|i| { + let g = GLOBAL.lock().unwrap(); + let g = g.as_ref()?; + Some(g.cpu + i as u64 * g.inc as u64) + }).unwrap_or(0); + Some(ShadowSlot { at: h.shadow + (k * SLOT) as usize, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, sampler: false, index, shared_srv }) +} + +/// Write descriptor words into a console slot looked up via `shadow_slot`. +pub fn write_shadow(s: &ShadowSlot, words: &[u32]) { + let n = words.len().min(if s.sampler { 4 } else { 8 }); + unsafe { std::ptr::copy_nonoverlapping(words.as_ptr(), s.at as *mut u32, n) }; +} + /// The slot behind a console CPU handle (None: not one of XCL's console heaps). A view slot /// of a heap in the shared heap gets its page's place there now if the page has none yet; one /// whose page finds no room there gets index 0, the null SRV / UAV pair. @@ -1361,6 +1420,9 @@ pub fn copy_words(src: &Slot, dst: &Slot) { write(dst, &w[..n]); if !src.sampler { note_resource(dst, resource_at(src.at).unwrap_or(0)); + let src_idx = if src.shared_srv != 0 { src.index } else { 0 }; + let dst_idx = if dst.shared_srv != 0 { dst.index } else { 0 }; + super::ambient::copy_descriptor(src.at, src_idx, dst.at, dst_idx); } } @@ -1443,11 +1505,30 @@ pub fn census() { /// The descriptor at a console GPU address (low 32 bits, as in a descriptor table), if it /// is in one of the console heaps. pub fn words_at(addr32: u32) -> Option<[u32; 8]> { - let u = crate::gpu::uma::get()?; - let s = slot((u.base() + addr32 as usize) as u64)?; - let mut w = [0u32; 8]; - unsafe { std::ptr::copy_nonoverlapping(s.at as *const u32, w.as_mut_ptr(), if s.sampler { 4 } else { 8 }) }; - Some(w) + let (words, _) = read_slot(addr32)?; + Some(words) +} + +/// Read guest memory and the slot's current PC index without allocating a page in the +/// shader-visible heap. A title can fill these slots by ordinary memory copies; inspecting +/// their words does not publish a new PC view. +pub(super) fn read_slot(addr32: u32) -> Option<([u32; 8], Option)> { + let at = crate::gpu::uma::get()?.base().checked_add(addr32 as usize)?; + let heaps = HEAPS.lock().unwrap(); + let (h, k) = heaps.iter().find_map(|h| { + let k = at.checked_sub(h.shadow)? / h.slot_bytes() as usize; + (k < h.n as usize).then_some((h, k as u32)) + })?; + let stride = h.slot_bytes() as usize; + let mut words = [0u32; 8]; + unsafe { std::ptr::copy_nonoverlapping((h.shadow + k as usize * stride) as *const u32, words.as_mut_ptr(), stride / 4) }; + let index = if h.pages.is_empty() { + Some(if h.sampler { k } else { 2 * k }) + } else { + let (page, step) = if h.sampler { (SAMPLER_PAGE_SLOTS, 1) } else { (PAGE_SLOTS, 2) }; + h.pages.get((k / page) as usize).filter(|&&first| first != UNMAPPED).map(|first| first + step * (k % page)) + }; + Some((words, index)) } /// Exact console words currently in view slots identified by heap generation and slot number. @@ -2118,6 +2199,15 @@ mod tests { assert!(register(0xC1, 2 * PAGE_SLOTS, 0x30_0000, 0, 32, false, true, true)); assert!(register(0xC2, 16, 0x40_0000, 0, 32, false, true, true)); let (a, b) = (start(0xC1).unwrap(), start(0xC2).unwrap()); + // The dispatch trace inspects tables the title wrote directly. No PC descriptors + // have been published for this page, even after inspecting it. + assert_eq!(read_slot(rel(a + (PAGE_SLOTS * SLOT) as u64)), Some(([0; 8], None))); + assert!(contains(a + (PAGE_SLOTS * SLOT) as u64)); + let sh = shadow_slot(a + (PAGE_SLOTS * SLOT) as u64).unwrap(); + assert_eq!(sh.index, None); + assert_eq!(sh.shared_srv, 0); + write_shadow(&sh, &[1, 2, 3, 4]); + assert_eq!(PAGES_PLACED.load(Relaxed), 0); let placed = slot(a + 2 * SLOT as u64).unwrap(); assert_eq!(placed.index, base + 4, "page 0 of the first heap takes the room there is"); assert_ne!(placed.shared_srv, 0); diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 7c12cdec05..200991ef7f 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -50,6 +50,25 @@ pub fn enabled() -> bool { *E.get_or_init(|| std::env::var_os("XCL_CONSOLE_LISTS").is_some()) } +/// `XCL_CONSOLE_LISTS_LOG=order` (off): each closed list's records in their order, one token +/// each (`order_token`), after the counts line. +fn order_log() -> bool { + static E: OnceLock = OnceLock::new(); + *E.get_or_init(|| std::env::var("XCL_CONSOLE_LISTS_LOG").is_ok_and(|v| v.trim() == "order")) +} + +/// One barrier of a #26 ResourceBarrier record (`D3D12_RESOURCE_BARRIER` as 4 u64) for the +/// order log: `T:>` a transition, `U` a UAV barrier (`U0`: on all), +/// `A` an aliasing barrier; `` the low 24 bits of the object's address. +fn order_token(c: &[u64]) -> String { + let res = c[1] & 0xFF_FFFF; + match c[0] as u32 { + 0 => format!("T{res:x}:{:x}>{:x}", c[2] >> 32, c[3] as u32), + 2 => format!("U{res:x}"), + _ => "A".into(), + } +} + // --------------------------------------------------------------------------------------- // root signature layouts (where each parameter sits in the root argument table) // --------------------------------------------------------------------------------------- @@ -435,6 +454,7 @@ pub fn allocator_reset(allocator: *mut c_void) { unsafe { free_uma(&b) }; } super::bind::release_allocator_res(allocator as usize); + super::real::dispatch_chain::allocator_reset(allocator as usize); } fn with_list(obj: usize, f: impl FnOnce(&mut ListState) -> R) -> Option { @@ -754,7 +774,60 @@ pub fn pc_pso(pso: *mut c_void) -> *mut c_void { unsafe { (*(pso as *const ConsolePso)).pc as *mut c_void } } +/// How long what a finished recording held (unified-memory blocks, two-pass buffers) waits +/// before it is used again or let go, from when its allocator's reset said the GPU was done with +/// it (`XCL_RETIRE_MS`, 2000 by default; 0: at once). A retail title resets its allocators with +/// work still on the GPU about a hundred times a second in its world, and a block handed to the +/// next recording at once was written while a list still read it whenever that bookkeeping +/// missed a submit: its dispatch arguments over the title's own objects in upload memory (CPU +/// crashes on a vtable of `{groups, 1, 1, 0}`), and stale arguments and addresses for the GPU +/// (page faults at addresses no resource is at, device removals). +pub(super) fn retire_age() -> std::time::Duration { + #[cfg(test)] + { + std::time::Duration::ZERO + } + #[cfg(not(test))] + { + static MS: std::sync::OnceLock = std::sync::OnceLock::new(); + std::time::Duration::from_millis(*MS.get_or_init(|| std::env::var("XCL_RETIRE_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2000))) + } +} + +/// unified-memory blocks waiting out `retire_age`, oldest first +static RETIRED: Mutex> = Mutex::new(std::collections::VecDeque::new()); +/// committed unified memory left under which the oldest retired blocks go back early +const RETIRE_ROOM: usize = 96 << 20; + unsafe fn free_uma(blocks: &[usize]) { + let age = retire_age(); + if age.is_zero() { + return free_uma_now(blocks); + } + let now = std::time::Instant::now(); + let ready: Vec = { + let mut g = RETIRED.lock().unwrap(); + g.extend(blocks.iter().map(|&b| (now, b))); + let mut out = Vec::new(); + while g.front().is_some_and(|&(at, _)| now.saturating_duration_since(at) >= age) { + out.push(g.pop_front().unwrap().1); + } + // (draws with no room for their arguments are skipped: before that, the oldest go back) + if out.is_empty() && !g.is_empty() && crate::gpu::uma::get().is_some_and(|u| u.committed_state().0 < RETIRE_ROOM) { + let n = g.len().min(64); + out.extend(g.drain(..n).map(|e| e.1)); + static EARLY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let k = EARLY.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed) + n as u64; + if (k / 64).is_power_of_two() { + crate::xlog_warn!("D3D12.X: {k} retired unified-memory blocks so far given back before {} ms: committed unified memory is under {} MB free", age.as_millis(), RETIRE_ROOM >> 20); + } + } + out + }; + free_uma_now(&ready); +} + +unsafe fn free_uma_now(blocks: &[usize]) { if let Some(u) = crate::gpu::uma::get() { for &b in blocks { if u.is_sparse(b) { @@ -892,6 +965,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let track_shared_view = super::vram::srv_tracking_enabled(); let mut shared_view_bound = false; let mut recording_uses_shared_view = false; + let mut order: Vec = Vec::new(); let chunks: Vec> = st.chunks.iter().map(|(c, used)| c[..*used].chunks(4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).collect()).collect(); 'chunks: for words in &chunks { let mut at = 0usize; @@ -957,6 +1031,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { for c in b.chunks_exact(4).filter(|c| c[0] as u32 == 0) { super::placements::note_use(c[1] as usize); } + if order_log() { + order.extend(b.chunks_exact(4).map(order_token)); + } list.ResourceBarrier(std::slice::from_raw_parts(b.as_ptr() as *const D3D12_RESOURCE_BARRIER, m)); } out.barriers += n as u32; @@ -990,11 +1067,22 @@ pub unsafe fn close(obj: *mut c_void) -> Result { list.ClearUnorderedAccessViewUint(gh, ch, r, &values, &[]); } out.clears += 1; + if order_log() { + order.push(format!("C{:x}={:x}", q(2) & 0xFF_FFFF, values[0])); + } } else { out.skipped += 1; + if order_log() { + order.push(format!("C{:x}-skipped", q(2) & 0xFF_FFFF)); + } + } + } + _ => { + out.skipped += 1; + if order_log() { + order.push(format!("C{:x}-skipped", q(2) & 0xFF_FFFF)); } } - _ => out.skipped += 1, } at += 12; } else if w0 == COPY_TEXTURE_MARKER { @@ -1029,6 +1117,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) }, }]); out.barriers += 1; + if order_log() { + order.push("B".into()); + } at += 1; } else if w0 == DISPATCH || w0 & !4 == 0x4002_E800 { let (x, y, z) = (get(1), get(2), get(3)); @@ -1043,6 +1134,14 @@ pub unsafe fn close(obj: *mut c_void) -> Result { out.skipped_dispatches += 1; continue; } + // `XCL_SKIP_CS` (diagnostic): left out here as on PC lists + if super::real::skip_named_cs(real) { + out.skipped_dispatches += 1; + if order_log() { + order.push(format!("D{:016x}-left-out", super::real::pso_shaders(real).map_or(0, |s| s.0))); + } + continue; + } let user_sgprs = super::real::pso_user_sgprs_exact(real); // (the list is submitted after this: its root views in a GPU view get their tiles there) super::bind::want_root_views(layout.as_deref(), &table, super::view_want::Path::RootView); @@ -1070,10 +1169,13 @@ pub unsafe fn close(obj: *mut c_void) -> Result { None => list.SetComputeRootSignature(rs.as_ref().ok_or("no XCL ABI root signature")?), } shared_view_bound = ensure_dispatch_heaps(&list, &mut bound_heaps, &mut has_sampler_heap, shared_view_bound); + super::real::note_root_view(list.as_raw() as usize, 0, va(io_at)); list.SetComputeRootUnorderedAccessView(0, va(io_at)); + super::real::note_root_view(list.as_raw() as usize, 1, va(res_at)); list.SetComputeRootUnorderedAccessView(1, va(res_at)); // (every window slot gets a buffer: direct DXIL compute reads all four, as in `bind`) for k in 0..4 { + super::real::note_root_view(list.as_raw() as usize, 2 + k as u32, windows.get(k).copied().filter(|&v| v != 0).unwrap_or(uma_va)); list.SetComputeRootUnorderedAccessView(2 + k as u32, windows.get(k).copied().filter(|&v| v != 0).unwrap_or(uma_va)); } super::real::bind_pipeline_exact(list.as_raw(), (*p).pc, real); @@ -1084,8 +1186,17 @@ pub unsafe fn close(obj: *mut c_void) -> Result { ran?; recording_uses_shared_view |= track_shared_view && shared_view_bound; out.dispatches += 1; + if order_log() { + let cs = super::real::pso_shaders(real).map_or(0, |s| s.0); + order.push(format!("D{cs:016x}[{x}x{y}x{z}]")); + } + } + _ => { + out.skipped_dispatches += 1; + if order_log() { + order.push("D-skipped".into()); + } } - _ => out.skipped_dispatches += 1, } } else if w0 & 0xC000_0000 == PARAM_BASE { let i = ((w0 >> 10) & 0x3F) as usize; @@ -1146,6 +1257,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { out.skipped ); } + if order_log() { + crate::xlog_info!("console list order: {}", order.join(" ")); + } if let Some((w, at)) = out.unknown { crate::xlog_warn!("console list: unknown record {w:#010x} (word {at}) – rest skipped"); } diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index f672e42f0a..f92fc5dafd 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -151,6 +151,7 @@ unsafe fn write_now_in(va: usize, words: &[u32], run: &dyn Fn(usize, usize) -> O for (i, &w) in words.iter().enumerate() { (*((va + 4 * i) as *const AtomicU32)).store(w, Ordering::Release); } + crate::hle::kernelx::pagelog::note("list immediate written by the CPU after its submit", va, 0, bytes); note_placed(asked, va, bytes); } @@ -190,6 +191,7 @@ unsafe fn write_u64_now(va: usize, value: u64) { let (asked, va) = (va, cpu_at(va)); if u64_writable_now(va) { (*(va as *const AtomicU64)).store(value, Ordering::Release); + crate::hle::kernelx::pagelog::note("list 64-bit value written by the CPU after its submit", va, 0, 8); note_placed(asked, va, 8); } } @@ -202,6 +204,7 @@ pub(super) unsafe fn max_u64_now(va: usize, value: u64) { let (asked, va) = (va, cpu_at(va)); if u64_writable_now(va) { (*(va as *const AtomicU64)).fetch_max(value, Ordering::AcqRel); + crate::hle::kernelx::pagelog::note("list 64-bit value raised by the CPU", va, 0, 8); note_placed(asked, va, 8); } } @@ -213,7 +216,7 @@ pub(super) fn writable(va: usize, bytes: usize) -> bool { if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { return true; } - crate::hle::kernelx::lazy::ensure(va, bytes); + let _opened = crate::hle::kernelx::lazy::ensure(va, bytes); use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; let found = unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0; diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs index 959d7faa85..3c6c0721d4 100644 --- a/crates/xcl/src/hle/d3d12x/depth_uav.rs +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -17,7 +17,8 @@ //! the shaders wrote reaches the next depth test or sampling). A transition names the state it //! leaves and the one it enters, so each copy starts and ends in states the title gave. //! -//! On unless `XCL_DEPTH_UAV_TWIN=0`; with the switch off nothing is registered, a UAV of a depth +//! On unless `XCL_DEPTH_UAV_TWIN=0` (a title that names layouts moves its buffers through +//! `barrier_groups`, whose transitions reach `plan_barriers`); with the switch off nothing is registered, a UAV of a depth //! buffer stays a null view and every hook stops at one atomic load. //! //! (After the depth+UAV twins of xcl-dev/xcl#1989 by raylitebull: registering at creation, DSVs, @@ -26,10 +27,14 @@ use std::collections::HashMap; use std::ffi::c_void; -use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; +use std::mem::ManuallyDrop; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicU8, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, OnceLock, Weak}; -use windows::core::Interface; +use windows::core::{Interface, PCSTR}; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; @@ -81,12 +86,26 @@ struct Cell { /// the plane (a copy, or the two known to hold the same): only then is the twin copied back /// (`plan_barriers`) entered: AtomicBool, + /// the number of the stretch the title has had the buffer in UNORDERED_ACCESS since a + /// transition of all of it that put the twin in step (0: none): draws that test against the + /// buffer then are watched (`before_work`) + live: AtomicU64, + /// which of the depth plane and its twin holds what was written last in that stretch (`Side`) + side: AtomicU8, /// the same for the stencil plane's twin: the last transition into UNORDERED_ACCESS copied /// the plane into it, so it holds the plane and what shaders wrote since (`plan_barriers`) stencil_entered: AtomicBool, inner: Mutex, } +impl Drop for Cell { + fn drop(&mut self) { + if *self.live.get_mut() != 0 { + LIVE.fetch_sub(1, Ordering::Relaxed); + } + } +} + #[derive(Default)] struct Inner { /// registered objects of this buffer @@ -96,8 +115,18 @@ struct Inner { made_in: Option, /// [depth, stencil] twins: [Option; 2], + /// cached (DSV heap, shader-visible SRV/UAV heap) per depth resource object for R24G8 fullscreen/CS sync + pass_heaps: HashMap, } +struct PassHeaps { + dsv: ID3D12DescriptorHeap, + srv_uav: ID3D12DescriptorHeap, +} + +unsafe impl Send for PassHeaps {} +unsafe impl Sync for PassHeaps {} + /// A plane's twin: a colour texture of the plane's size with unordered access, resting in /// UNORDERED_ACCESS. struct Twin { @@ -128,7 +157,6 @@ struct Object { } #[derive(Clone)] -#[allow(dead_code)] // (read once DSV binds are followed) struct Dsv { res: usize, /// D3D12_DSV_FLAGS of the view: 1 read-only depth, 2 read-only stencil @@ -161,6 +189,14 @@ static CELL_IDS: AtomicU64 = AtomicU64::new(1); static TO_TWIN: AtomicU64 = AtomicU64::new(0); static TO_PLANE: AtomicU64 = AtomicU64::new(0); static IN_STEP: AtomicU64 = AtomicU64::new(0); +/// Cells with a `live` stretch, and the stretches numbered. +static LIVE: AtomicUsize = AtomicUsize::new(0); +static STRETCHES: AtomicU64 = AtomicU64::new(1); +/// Copies made before draws and dispatches inside such a stretch (`before_work`): [into the +/// twin, into the plane]; copies out of UNORDERED_ACCESS not made because a draw's depth test +/// left the plane the newer side. +static WORK_COPIES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; +static PLANE_KEPT: AtomicU64 = AtomicU64::new(0); /// Whether a twin is alive: the gate of the paths that record. pub(super) fn any() -> bool { @@ -205,7 +241,19 @@ fn register(res: usize, x: &[u8; 0x38], at: Option, pc_state: u32) -> boo let cells = g.get_or_insert_with(HashMap::new); let cell = cells .entry(key) - .or_insert_with(|| Arc::new(Cell { key, id: CELL_IDS.fetch_add(1, Ordering::Relaxed), console_format: u32_at(x, 0x20), twinned: AtomicBool::new(false), entered: AtomicBool::new(false), stencil_entered: AtomicBool::new(false), inner: Mutex::new(Inner::default()) })) + .or_insert_with(|| { + Arc::new(Cell { + key, + id: CELL_IDS.fetch_add(1, Ordering::Relaxed), + console_format: u32_at(x, 0x20), + twinned: AtomicBool::new(false), + entered: AtomicBool::new(false), + stencil_entered: AtomicBool::new(false), + live: AtomicU64::new(0), + side: AtomicU8::new(Side::Both as u8), + inner: Mutex::new(Inner::default()), + }) + }) .clone(); { let mut inner = cell.inner.lock().unwrap(); @@ -280,7 +328,9 @@ pub(super) fn forget(res: usize) { } let Some(o) = OBJECTS.remove(res) else { return }; REGISTERED.fetch_sub(1, Ordering::Relaxed); + let dropped_heaps = o.cell.inner.lock().unwrap().pass_heaps.remove(&res); let gone = CELLS.lock().unwrap().as_mut().map(|cells| leave(cells, &o.cell)); + drop(dropped_heaps); drop(gone); } @@ -335,18 +385,26 @@ pub(super) unsafe fn resolve_uav(dev: *mut c_void, res: *mut c_void, rd: Option< } } let stencil = stencil_view(view); - // (a D24S8's depth plane: no UAV format holds it as a shader reads it) - if if stencil { !matches!(key.format, 19 | 44) } else { !matches!(key.format, 19 | 39 | 53) } { + if if stencil { !matches!(key.format, 19 | 44) } else { !matches!(key.format, 19 | 39 | 44 | 53) } { return Resolve::Null("its depth plane has no twin yet"); } // (its states stay the title's: the twin would never be copied) if !stencil && (o.cell.inner.lock().unwrap().made_in.unwrap_or(o.state) | o.state) & UNORDERED_ACCESS != 0 { + twin_trace(&key, || format!("a UAV of object {:#x} stays a null view: the buffer was made in UNORDERED_ACCESS", res as usize)); return Resolve::Null("the buffer was made in UNORDERED_ACCESS"); } // (the Cell holds the twin) - let Some((twin, _)) = plane_twin(&o, stencil as usize, dev) else { return Resolve::Null("the twin could not be made") }; + let Some((twin, n)) = plane_twin(&o, stencil as usize, dev) else { return Resolve::Null("the twin could not be made") }; + twin_trace(&key, || format!("a UAV of the {} plane of object {:#x} is a view of twin #{n}", if stencil { "stencil" } else { "depth" }, res as usize)); REDIRECTED.fetch_add(1, Ordering::Relaxed); - Resolve::Twin(twin.as_raw(), if stencil { twin_view(view, key.array) } else { depth_twin_view(view, key.array, key.format == 53) }) + let r16 = is_r16_depth(key.format, o.cell.console_format); + Resolve::Twin(twin.as_raw(), if stencil { twin_view(view, key.array) } else { depth_twin_view(view, key.array, r16) }) +} + +/// True when the depth plane's twin is 16-bit (`R16_TYPELESS`): PC D16 (`53`) or console +/// `D16_UNORM_S8_UINT` (`118..=120`) backed by PC `R24G8_TYPELESS` (`44`). +fn is_r16_depth(format: u32, console_format: u32) -> bool { + format == 53 || (format == 44 && matches!(console_format, 118..=120)) } /// The twin of `plane` (0 depth, 1 stencil) of the buffer `o` is in, and its number: the one it @@ -357,7 +415,7 @@ unsafe fn plane_twin(o: &Object, plane: usize, dev: *mut c_void) -> Option<(ID3D if let Some(t) = &inner.twins[plane] { return Some((t.res.clone(), t.n)); } - let t = make_twin(dev, &key, twin_format(key.format, plane))?; + let t = make_twin(dev, &key, twin_format(key.format, o.cell.console_format, plane))?; TWINS.fetch_add(1, Ordering::Relaxed); let n = MADE.fetch_add(1, Ordering::Relaxed) + 1; let through = if plane == 1 { make_through(dev, &key) } else { None }; @@ -386,7 +444,7 @@ unsafe fn plane_twin(o: &Object, plane: usize, dev: *mut c_void) -> Option<(ID3D key.format, o.cell.console_format, key.at, - if key.format == 53 { 16 } else { 32 }, + if is_r16_depth(key.format, o.cell.console_format) { 16 } else { 32 }, state ); } @@ -394,12 +452,12 @@ unsafe fn plane_twin(o: &Object, plane: usize, dev: *mut c_void) -> Option<(ID3D Some((t, n)) } -/// The format of the twin of `plane` of a buffer of the PC format `format`: R8 for the stencil -/// plane, R16 for D16's depth, R32 for D32's and D32S8's (the plane copies as R32_TYPELESS). -fn twin_format(format: u32, plane: usize) -> DXGI_FORMAT { +/// The format of the twin of `plane` of a buffer of the PC format `format` (and `console_format`): +/// R8 for stencil, R16 for D16 and console D16S8 (`118..=120`), R32 for D32, D32S8, and D24S8. +fn twin_format(format: u32, console_format: u32, plane: usize) -> DXGI_FORMAT { match (plane, format) { (1, _) => DXGI_FORMAT_R8_TYPELESS, - (_, 53) => DXGI_FORMAT_R16_TYPELESS, + (0, f) if is_r16_depth(f, console_format) => DXGI_FORMAT_R16_TYPELESS, _ => DXGI_FORMAT_R32_TYPELESS, } } @@ -407,9 +465,11 @@ fn twin_format(format: u32, plane: usize) -> DXGI_FORMAT { /// Where a buffer whose depth plane can have a twin rests while the title has it in /// UNORDERED_ACCESS: COPY_SOURCE, the state the plane is copied into the twin from. pub(super) const PARK: u32 = 0x800; -/// D3D12_RESOURCE_STATE_UNORDERED_ACCESS, COPY_DEST +/// D3D12_RESOURCE_STATE_UNORDERED_ACCESS, DEPTH_WRITE, COPY_DEST const UNORDERED_ACCESS: u32 = 0x8; +const DEPTH_WRITE_STATE: u32 = 0x10; const COPY_DEST: u32 = 0x400; +const SRV_ALL: u32 = 0x40 | 0x80; /// The states in which nothing writes a depth plane: DEPTH_READ, NON_PIXEL_SHADER_RESOURCE, /// PIXEL_SHADER_RESOURCE, INDIRECT_ARGUMENT, COPY_SOURCE, RESOLVE_SOURCE (and their sums). const READ_ONLY: u32 = 0x20 | 0x40 | 0x80 | 0x200 | 0x800 | 0x2000; @@ -426,6 +486,13 @@ pub(super) struct PlaneCopy { /// the depth plane's subresources it copies (the twin's have the same numbers) pub subs: Vec, pub twin: ID3D12Resource, + /// Some(steps) for `R24G8_TYPELESS` fullscreen/CS sync (`steps == true` for console D16S8 `118..=120`), + /// None for direct `CopyTextureRegion` (`D32`, `D16`, `D32S8`). + pub r24g8_steps: Option, + pub width: u32, + pub height: u32, + pub array: u16, + pub mips: u16, } /// A copy between stencil plane subresources of a title's object and the same ones of the @@ -456,14 +523,18 @@ pub(super) struct Plan { /// title's transition takes it on from there; the twin UNORDERED_ACCESS → COPY_SOURCE/SRV and back) pub to_plane: Vec, /// after them: depth planes into twins (the buffer rests in PARK; the twin - /// UNORDERED_ACCESS → COPY_DEST and back) + /// UNORDERED_ACCESS → COPY_DEST and back, or CS UAV write for R24G8) pub to_twin: Vec, + /// buffers whose `live` stretch these barriers began: the list follows them (`Owed::add`) + pub live: Vec, + /// Cells whose stretch these barriers ended + pub settled: Vec, } -/// Whether the depth plane of `o`'s buffer can have a twin: a D32, D16 or D32S8 buffer, and the -/// object was not made in UNORDERED_ACCESS (that object's states stay the title's). +/// Whether the depth plane of `o`'s buffer can have a twin: a D32, D16, D32S8 or D24S8/D16S8 +/// buffer, and the object was not made in UNORDERED_ACCESS (that object's states stay the title's). fn plane_twinnable(o: &Object) -> bool { - matches!(o.cell.key.format, 19 | 39 | 53) && o.state & UNORDERED_ACCESS == 0 + matches!(o.cell.key.format, 19 | 39 | 44 | 53) && o.state & UNORDERED_ACCESS == 0 } /// Whether the title's transitions of `o` into and out of UNORDERED_ACCESS are parked: those of @@ -542,6 +613,7 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, } } let key = o.cell.key; + let r24g8_steps = (key.format == 44).then(|| matches!(o.cell.console_format, 118..=120)); // the stencil plane's subresources the transition names, and its twin when shaders were // given one: what they store there (a title's masks for its lighting) reaches the plane // on the way out of UNORDERED_ACCESS, and what was drawn into the plane reaches the twin @@ -579,10 +651,20 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, if leaving { before = PARK; // (a twin whose last way in was not copied holds something else than the plane: not - // copied back – what the shaders wrote into it is lost, as without a twin) + // copied back – what the shaders wrote into it is lost, as without a twin; nor one + // whose plane draws tested and wrote since the twin was last copied into it there, + // `before_work`: the plane holds the newer depth) + let plane_newer = o.cell.live.load(Ordering::Relaxed) != 0 && Side::of(&o.cell) == Side::Plane; let t = (direct && !subs.is_empty()).then(|| twin_if_made(&o)).flatten(); - if let Some((t, k)) = t.filter(|_| entered.load(Ordering::Relaxed)) { - before = COPY_DEST; + if plane_newer && t.is_some() { + let c = PLANE_KEPT.fetch_add(1, Ordering::Relaxed) + 1; + if c <= 4 || c.is_power_of_two() { + crate::xlog_info!("D3D12.X: depth UAV twin: the title moves depth buffer {res:#x} out of UNORDERED_ACCESS into state {after:#x} after draws tested against its plane: the twin is not copied into it ({c} such transitions so far)"); + } + } + twin_trace(&key, || format!("out of UNORDERED_ACCESS into {after:#x} (subresource {sub:#x}, direct {direct}): {}", if t.is_none() { "no twin copy (no twin, or a compute list)" } else if plane_newer { "the plane is newer, not copied" } else if entered.load(Ordering::Relaxed) { "the twin is copied into the plane" } else { "the twin's way in was not copied: not copied back" })); + if let Some((t, k)) = t.filter(|_| entered.load(Ordering::Relaxed) && !plane_newer) { + before = if r24g8_steps.is_some() { DEPTH_WRITE_STATE } else { COPY_DEST }; let c = TO_PLANE.fetch_add(1, Ordering::Relaxed) + 1; if c <= 4 || c.is_power_of_two() { crate::xlog_info!("D3D12.X: depth UAV twin #{k}: the title moves depth buffer {res:#x} out of UNORDERED_ACCESS into state {after:#x}: the twin is copied into its depth plane first ({c} such copies so far)"); @@ -590,11 +672,24 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, if subs.len() as u32 == n && !in_step.contains(&id) { in_step.push(id); } - plan.to_plane.push(PlaneCopy { depth: res, sub, subs: subs.clone(), twin: t }); + plan.to_plane.push(PlaneCopy { + depth: res, + sub, + subs: subs.clone(), + twin: t, + r24g8_steps, + width: key.width, + height: key.height, + array: key.array.max(1), + mips: key.mips.max(1), + }); } if writes(after) { in_step.retain(|&c| c != id); } + if end_stretch(&o.cell) { + plan.settled.push(id); + } } if entering { after = PARK; @@ -617,11 +712,32 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, in_step.push(id); } entered.store(true, Ordering::Relaxed); - plan.to_twin.push(PlaneCopy { depth: res, sub, subs, twin: t }); + plan.to_twin.push(PlaneCopy { + depth: res, + sub, + subs, + twin: t, + r24g8_steps, + width: key.width, + height: key.height, + array: key.array.max(1), + mips: key.mips.max(1), + }); } else { entered.store(false, Ordering::Relaxed); } } + // all of a buffer whose twin now holds its plane, on a DIRECT list: a stretch whose + // draws that test against the buffer are watched (`before_work`; not an R24G8 one, + // whose copy into the plane is a pass of XCL's that a draw being bound cannot take) + let whole = direct && sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES && key.format != 44 && entered.load(Ordering::Relaxed); + if whole { + let stretch = begin_stretch(&o.cell); + plan.live.push(Acting { id, stretch, cell: Arc::downgrade(&o.cell), res }); + } else if end_stretch(&o.cell) { + plan.settled.push(id); + } + twin_trace(&key, || format!("into UNORDERED_ACCESS from {before:#x} (subresource {sub:#x}, direct {direct}): the twin {}; draws testing against it are {}watched", if entered.load(Ordering::Relaxed) { "holds the plane" } else { "does not hold the plane" }, if whole { "" } else { "not " })); } (b[5], b[6]) = (before, after); if before != after { @@ -688,6 +804,646 @@ fn twin_if_made(o: &Object) -> Option<(ID3D12Resource, u64)> { o.cell.inner.lock().unwrap().twins[0].as_ref().map(|t| (t.res.clone(), t.n)) } +// --------------------------------------------------------------------------------------- +// Draws that test against a buffer the title has in UNORDERED_ACCESS +// +// The twin is copied into the plane where the title moves the buffer out of UNORDERED_ACCESS. +// A draw that tests against the buffer before that – with no transition in between, the title +// leaving it in UNORDERED_ACCESS – tested the plane as it was before the shaders wrote the twin. +// (VIctory-Neo, https://github.com/KyleS98/VIctory-Neo, GPL-3.0-or-later, 7da5c9d "the depth +// image a pixel program wrote is brought up to date before the draws that test against it": +// the title marks a mirror's pixels with a pixel program writing the depth of the mirror's view +// through unordered access, then draws that view against it in the same list; with the copy +// left for later the mirror showed the sky.) Here, in such a stretch, the list that began it +// follows which side was written last and copies it into the other before the work that uses +// that one: the twin into the plane before a draw whose depth target names the buffer, the plane +// into the twin before any other draw or dispatch (it may write the twin: XCL does not see which +// views a translated shader reaches). Both are copies of whole planes between resources in +// states XCL knows (the buffer rests in PARK, the twin in UNORDERED_ACCESS): nothing bound on +// the list changes. An R24G8 buffer's plane is written by a pass of XCL's (`execute_r24g8_copy`) +// that a draw being bound cannot take: its stretches are not followed. On unless +// `XCL_DEPTH_PLANE_NOW=0`. +// --------------------------------------------------------------------------------------- + +/// Whether draws inside a `live` stretch are followed (`XCL_DEPTH_PLANE_NOW`, on unless "0"). +fn plane_now() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| on(std::env::var("XCL_DEPTH_PLANE_NOW").ok().as_deref(), true)) +} + +/// The stretch of `cell` in UNORDERED_ACCESS begins; its number. The two sides hold the same. +fn begin_stretch(cell: &Cell) -> u64 { + let n = STRETCHES.fetch_add(1, Ordering::Relaxed); + cell.side.store(Side::Both as u8, Ordering::Relaxed); + if plane_now() && cell.live.swap(n, Ordering::Relaxed) == 0 { + LIVE.fetch_add(1, Ordering::Relaxed); + } + n +} + +/// The stretch of `cell` ends; false: it had none. +fn end_stretch(cell: &Cell) -> bool { + let had = cell.live.swap(0, Ordering::Relaxed) != 0; + if had { + LIVE.fetch_sub(1, Ordering::Relaxed); + } + had +} + +/// Whether a buffer is in a `live` stretch: the gate of the draw and dispatch hooks. +pub(super) fn any_live() -> bool { + LIVE.load(Ordering::Relaxed) != 0 +} + +/// Which of a depth plane and its twin holds what was written last in a `live` stretch. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[repr(u8)] +enum Side { + /// the same (the twin was copied from the plane, or the other way) + Both = 0, + /// shaders may have written the twin since + Twin = 1, + /// a draw tested against the plane, and may have written it + Plane = 2, +} + +impl Side { + fn of(cell: &Cell) -> Side { + match cell.side.load(Ordering::Relaxed) { + 1 => Side::Twin, + 2 => Side::Plane, + _ => Side::Both, + } + } +} + +/// What a draw or dispatch does with a buffer in a `live` stretch. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Use { + /// tests against its plane (its depth target names the buffer); `write`: the view does not + /// make the depth read only + Depth { write: bool }, + /// anything else: it may write the twin through a UAV + Shader, +} + +/// The copy a use `u` of a buffer whose newer side is `side` needs first (Some(true): the plane +/// into the twin, Some(false): the twin into the plane), and the newer side after it. +fn step(side: Side, u: Use) -> (Option, Side) { + match u { + // (a read-only depth target leaves the two as they were after the copy) + Use::Depth { write } => ((side == Side::Twin).then_some(false), if write || side == Side::Plane { Side::Plane } else { Side::Both }), + Use::Shader => ((side == Side::Plane).then_some(true), Side::Twin), + } +} + +/// A buffer a list follows in its `live` stretch. +#[derive(Clone)] +pub(super) struct Acting { + id: u64, + stretch: u64, + cell: Weak, + /// the object the title's transition named + res: usize, +} + +/// The buffers a list follows in their `live` stretches (`before_work`). It is the list's, and +/// goes with its recording. +#[derive(Default)] +pub(super) struct Owed(Vec); + +impl Owed { + /// The buffers whose stretches `plan`'s barriers began are followed, those they ended not. + pub(super) fn apply(&mut self, plan: &Plan) { + if plan.live.is_empty() && plan.settled.is_empty() { + return; + } + self.0.retain(|a| !plan.settled.contains(&a.id) && !plan.live.iter().any(|l| l.id == a.id)); + self.0.extend(plan.live.iter().cloned()); + } +} + +/// A copy to record before a draw or dispatch (`before_work`): of the plane into the twin +/// (`to_twin`) or of the twin into the plane, all the plane's subresources. +pub(super) struct WorkCopy { + pub copy: PlaneCopy, + pub to_twin: bool, +} + +/// All of the depth plane of `res` (an object of `cell`) and its twin, and the twin's number. +fn whole_copy(cell: &Cell, res: usize) -> Option<(PlaneCopy, u64)> { + let (twin, k) = cell.inner.lock().unwrap().twins[0].as_ref().map(|t| (t.res.clone(), t.n))?; + let key = cell.key; + let n = key.mips.max(1) as u32 * key.array.max(1) as u32; + let copy = PlaneCopy { + depth: res, + sub: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + subs: (0..n).collect(), + twin, + r24g8_steps: None, + width: key.width, + height: key.height, + array: key.array.max(1), + mips: key.mips.max(1), + }; + Some((copy, k)) +} + +/// A draw whose depth target is the DSV at `dsv` (None: none, or a dispatch) is about to be +/// recorded on a DIRECT list that follows the buffers `owed`: the copies to record before it, +/// so that the side each buffer's use reads holds what was written last. A depth target of a +/// buffer in a stretch the list does not follow yet (begun on another list) is followed from +/// here on. +pub(super) fn before_work(owed: &mut Owed, dsv: Option) -> Vec { + let tested = dsv.filter(|_| DSV_ENTRIES.load(Ordering::Relaxed) != 0).and_then(|h| DSVS.get(h)).and_then(|d| Some((d.res, d.flags, d.cell.upgrade()?))); + if let Some((res, _, cell)) = &tested { + let stretch = cell.live.load(Ordering::Relaxed); + if stretch != 0 && !owed.0.iter().any(|a| a.id == cell.id) { + twin_trace(&cell.key, || format!("a list follows the stretch begun elsewhere from a draw that tests against object {res:#x}")); + owed.0.push(Acting { id: cell.id, stretch, cell: Arc::downgrade(cell), res: *res }); + } + } + let mut out = Vec::new(); + owed.0.retain(|a| { + let Some(cell) = a.cell.upgrade() else { return false }; + if cell.live.load(Ordering::Relaxed) != a.stretch { + return false; + } + let (target, u) = match &tested { + Some((res, flags, c)) if Arc::ptr_eq(c, &cell) => (*res, Use::Depth { write: flags & 1 == 0 }), + _ => (a.res, Use::Shader), + }; + let was = Side::of(&cell); + let (copy, side) = step(was, u); + if let Some(to_twin) = copy { + // (no twin: the side stays as it was) + let Some((c, k)) = whole_copy(&cell, target) else { return true }; + let n = WORK_COPIES[(!to_twin) as usize].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + if to_twin { + crate::xlog_info!("D3D12.X: depth UAV twin #{k}: work after draws that tested against depth buffer {target:#x}, which the title has in UNORDERED_ACCESS: its depth plane is copied into the twin first ({n} such copies so far)"); + } else { + crate::xlog_info!("D3D12.X: depth UAV twin #{k}: a draw tests against depth buffer {target:#x}, which the title has in UNORDERED_ACCESS, after shaders may have written its twin: the twin is copied into the depth plane first ({n} such copies so far)"); + } + } + twin_trace(&cell.key, || format!("{u:?} of object {target:#x}: the {} first", if to_twin { "plane is copied into the twin" } else { "twin is copied into the plane" })); + out.push(WorkCopy { copy: c, to_twin }); + } else if was != side && matches!(u, Use::Depth { .. }) { + twin_trace(&cell.key, || format!("{u:?} of object {target:#x}: the sides held the same, no copy")); + } + cell.side.store(side as u8, Ordering::Relaxed); + true + }); + out +} + +/// `XCL_TWIN_TRACE=` (a test aid): what XCL does with the depth buffers of that height +/// that shaders write – the title's transitions into and out of UNORDERED_ACCESS, the copies of +/// their twins, the DSVs bound and the draws that test against them – a line each for the first +/// 600 (a mirror's view is 736 high in a retail title). +fn twin_trace(key: &Key, what: impl FnOnce() -> String) { + let h = trace_height(); + if h == 0 || key.height != h { + return; + } + static SAID: AtomicU32 = AtomicU32::new(0); + if SAID.fetch_add(1, Ordering::Relaxed) >= 600 { + return; + } + crate::xlog_info!( + "D3D12.X: XCL_TWIN_TRACE: frame {}: depth buffer at {:#x} ({}x{}x{}, PC format {}): {}", + super::present::counters().1, + key.at, + key.width, + key.height, + key.array, + key.format, + what() + ); +} + +fn trace_height() -> u32 { + static HEIGHT: OnceLock = OnceLock::new(); + *HEIGHT.get_or_init(|| std::env::var("XCL_TWIN_TRACE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) +} + +/// `XCL_TWIN_TRACE`: list `list` binds the DSV at `dsv`. +pub(super) fn trace_dsv_bind(list: usize, dsv: usize) { + if trace_height() == 0 || DSV_ENTRIES.load(Ordering::Relaxed) == 0 { + return; + } + let Some(d) = DSVS.get(dsv) else { return }; + let Some(cell) = d.cell.upgrade() else { return }; + twin_trace(&cell.key, || { + format!( + "list {list:#x} binds a DSV of object {:#x} (flags {:#x}); {}", + d.res, + d.flags, + if cell.live.load(Ordering::Relaxed) != 0 { format!("in a followed stretch in UNORDERED_ACCESS, the newer side {:?}", Side::of(&cell)) } else { "not in UNORDERED_ACCESS as far as XCL followed it".to_owned() } + ) + }); +} + +struct SyncPipelines { + gfx_rs: ID3D12RootSignature, + gfx_pso: ID3D12PipelineState, + gfx_pso_steps: ID3D12PipelineState, + cs_rs: ID3D12RootSignature, + cs_pso: ID3D12PipelineState, +} + +unsafe impl Send for SyncPipelines {} +unsafe impl Sync for SyncPipelines {} + +static SYNC_PIPELINES: Mutex>>> = Mutex::new(None); + +fn compile_sm5(src: &str, target: &str) -> Option> { + if let Some(b) = crate::gpu::recomp::dxc::compile_sm6_first(src, "main", target) { + return Some(b); + } + unsafe { + let mut blob = None; + let t = format!("{target}\0"); + let r = D3DCompile( + src.as_ptr() as *const c_void, + src.len(), + PCSTR::null(), + None, + None, + PCSTR(b"main\0".as_ptr()), + PCSTR(t.as_ptr()), + 0, + 0, + &mut blob, + None, + ); + match (r, blob) { + (Ok(()), Some(b)) => Some(std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()).to_vec()), + _ => None, + } + } +} + +unsafe fn build_sync_pipelines(dev: &ID3D12Device) -> Option { + let vs = compile_sm5( + "float4 main(uint id : SV_VertexID) : SV_Position {\n\ + float2 p = float2((id == 2) ? 3.0 : -1.0, (id == 1) ? 3.0 : -1.0);\n\ + return float4(p, 0.0, 1.0);\n\ + }\n", + "vs_5_0", + )?; + let ps = compile_sm5( + "Texture2DArray src : register(t0);\n\ + cbuffer C : register(b0) { uint slice; uint mip; };\n\ + float main(float4 pos : SV_Position) : SV_Depth {\n\ + return src.Load(int4(int2(pos.xy), int(slice), int(mip)));\n\ + }\n", + "ps_5_0", + )?; + // Console D16_UNORM_S8_UINT (118..=120): read R16_TYPELESS twin as R16_UINT and multiply by + // asfloat(0x37800080) so 24-bit depth matches tiled-lighting DepthFunc = EQUAL vertex shaders + // bit-for-bit on AMD RDNA4. + let ps_steps = compile_sm5( + "Texture2DArray src : register(t0);\n\ + cbuffer C : register(b0) { uint slice; uint mip; };\n\ + float main(float4 pos : SV_Position) : SV_Depth {\n\ + return float(src.Load(int4(int2(pos.xy), int(slice), int(mip)))) * asfloat(0x37800080);\n\ + }\n", + "ps_5_0", + )?; + let cs = compile_sm5( + "Texture2DArray src : register(t0);\n\ + RWTexture2DArray dst : register(u0);\n\ + cbuffer C : register(b0) { uint w; uint h; uint slices; uint mip; };\n\ + [numthreads(8, 8, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + if (id.x < w && id.y < h && id.z < slices) {\n\ + dst[id] = src.Load(int4(int3(id), int(mip)));\n\ + }\n\ + }\n", + "cs_5_0", + )?; + + let srv_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + let uav_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + let dev_raw = dev.as_raw(); + type CreateRsFn = unsafe extern "system" fn(*mut c_void, u32, *const c_void, usize, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + let create_rs: CreateRsFn = std::mem::transmute(super::real::orig_fn(dev_raw, 16)); + + let gfx_params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 2 } }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + Anonymous: D3D12_ROOT_PARAMETER_0 { DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &srv_range } }, + }, + ]; + let mut blob = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC { NumParameters: gfx_params.len() as u32, pParameters: gfx_params.as_ptr(), ..Default::default() }, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).ok()?; + let blob = blob?; + let mut gfx_rs_raw = std::ptr::null_mut(); + if create_rs(dev_raw, 0, blob.GetBufferPointer(), blob.GetBufferSize(), &ID3D12RootSignature::IID as *const _ as *const _, &mut gfx_rs_raw) < 0 || gfx_rs_raw.is_null() { + return None; + } + let gfx_rs = ID3D12RootSignature::from_raw(gfx_rs_raw); + + let cs_params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 4 } }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &srv_range } }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &uav_range } }, + }, + ]; + let mut cs_blob = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC { NumParameters: cs_params.len() as u32, pParameters: cs_params.as_ptr(), ..Default::default() }, D3D_ROOT_SIGNATURE_VERSION_1, &mut cs_blob, None).ok()?; + let cs_blob = cs_blob?; + let mut cs_rs_raw = std::ptr::null_mut(); + if create_rs(dev_raw, 0, cs_blob.GetBufferPointer(), cs_blob.GetBufferSize(), &ID3D12RootSignature::IID as *const _ as *const _, &mut cs_rs_raw) < 0 || cs_rs_raw.is_null() { + return None; + } + let cs_rs = ID3D12RootSignature::from_raw(cs_rs_raw); + + let mut gfx_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(gfx_rs.clone())), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as *const c_void, BytecodeLength: vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as *const c_void, BytecodeLength: ps.len() }, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: false.into(), ..Default::default() }, + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { DepthEnable: true.into(), DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS, StencilEnable: false.into(), ..Default::default() }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 0, + DSVFormat: DXGI_FORMAT_D24_UNORM_S8_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + type CreateGfxPsoFn = unsafe extern "system" fn(*mut c_void, *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + let create_gfx: CreateGfxPsoFn = std::mem::transmute(super::real::orig_fn(dev_raw, 10)); + let mut gfx_pso_raw = std::ptr::null_mut(); + if create_gfx(dev_raw, &gfx_desc, &ID3D12PipelineState::IID as *const _ as *const _, &mut gfx_pso_raw) < 0 || gfx_pso_raw.is_null() { + ManuallyDrop::drop(&mut gfx_desc.pRootSignature); + return None; + } + let gfx_pso = ID3D12PipelineState::from_raw(gfx_pso_raw); + let _ = gfx_pso.SetName(&windows::core::HSTRING::from("xcl depth_uav r24g8 sync gfx")); + + gfx_desc.PS = D3D12_SHADER_BYTECODE { pShaderBytecode: ps_steps.as_ptr() as *const c_void, BytecodeLength: ps_steps.len() }; + let mut gfx_pso_steps_raw = std::ptr::null_mut(); + let hr_steps = create_gfx(dev_raw, &gfx_desc, &ID3D12PipelineState::IID as *const _ as *const _, &mut gfx_pso_steps_raw); + ManuallyDrop::drop(&mut gfx_desc.pRootSignature); + if hr_steps < 0 || gfx_pso_steps_raw.is_null() { + return None; + } + let gfx_pso_steps = ID3D12PipelineState::from_raw(gfx_pso_steps_raw); + let _ = gfx_pso_steps.SetName(&windows::core::HSTRING::from("xcl depth_uav r24g8 sync gfx steps")); + + let mut cs_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(cs_rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }, + ..Default::default() + }; + type CreateCsPsoFn = unsafe extern "system" fn(*mut c_void, *const D3D12_COMPUTE_PIPELINE_STATE_DESC, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + let create_cs: CreateCsPsoFn = std::mem::transmute(super::real::orig_fn(dev_raw, 11)); + let mut cs_pso_raw = std::ptr::null_mut(); + let hr_cs = create_cs(dev_raw, &cs_desc, &ID3D12PipelineState::IID as *const _ as *const _, &mut cs_pso_raw); + ManuallyDrop::drop(&mut cs_desc.pRootSignature); + if hr_cs < 0 || cs_pso_raw.is_null() { + return None; + } + let cs_pso = ID3D12PipelineState::from_raw(cs_pso_raw); + let _ = cs_pso.SetName(&windows::core::HSTRING::from("xcl depth_uav r24g8 sync cs")); + + Some(SyncPipelines { gfx_rs, gfx_pso, gfx_pso_steps, cs_rs, cs_pso }) +} + +unsafe fn get_sync_pipelines(dev: &ID3D12Device) -> Option<(ID3D12RootSignature, ID3D12PipelineState, ID3D12PipelineState, ID3D12RootSignature, ID3D12PipelineState)> { + let key = dev.as_raw() as usize; + let mut g = SYNC_PIPELINES.lock().unwrap(); + let p = g.get_or_insert_with(HashMap::new).entry(key).or_insert_with(|| build_sync_pipelines(dev)).as_ref()?; + Some((p.gfx_rs.clone(), p.gfx_pso.clone(), p.gfx_pso_steps.clone(), p.cs_rs.clone(), p.cs_pso.clone())) +} + +unsafe fn ensure_pass_heaps(dev: &ID3D12Device, copy: &PlaneCopy, steps: bool) -> Option<(ID3D12DescriptorHeap, ID3D12DescriptorHeap)> { + let o = OBJECTS.get(copy.depth)?; + { + let inner = o.cell.inner.lock().unwrap(); + if let Some(h) = inner.pass_heaps.get(©.depth) { + return Some((h.dsv.clone(), h.srv_uav.clone())); + } + } + let dev_raw = dev.as_raw(); + type CreateHeapFn = unsafe extern "system" fn(*mut c_void, *const D3D12_DESCRIPTOR_HEAP_DESC, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + type IncSizeFn = unsafe extern "system" fn(*mut c_void, D3D12_DESCRIPTOR_HEAP_TYPE) -> u32; + type CreateDsvFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_DEPTH_STENCIL_VIEW_DESC, usize); + type CreateSrvFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, usize); + type CreateUavFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + let create_heap: CreateHeapFn = std::mem::transmute(super::real::orig_fn(dev_raw, 14)); + let inc_size: IncSizeFn = std::mem::transmute(super::real::orig_fn(dev_raw, 15)); + let create_srv: CreateSrvFn = std::mem::transmute(super::real::orig_fn(dev_raw, 18)); + let create_uav: CreateUavFn = std::mem::transmute(super::real::orig_fn(dev_raw, 19)); + let create_dsv: CreateDsvFn = std::mem::transmute(super::real::orig_fn(dev_raw, 21)); + + let mips = copy.mips.max(1) as u32; + let slices = copy.array.max(1) as u32; + let depth_raw = copy.depth as *mut c_void; + + let dsv_desc = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, NumDescriptors: mips * slices, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0 }; + let mut dsv_raw = std::ptr::null_mut(); + if create_heap(dev_raw, &dsv_desc, &ID3D12DescriptorHeap::IID as *const _ as *const _, &mut dsv_raw) < 0 || dsv_raw.is_null() { + return None; + } + let dsv_heap = ID3D12DescriptorHeap::from_raw(dsv_raw); + let dsv_inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + let dsv_base = dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + for m in 0..mips { + for a in 0..slices { + let dsv = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D24_UNORM_S8_UINT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY, + Flags: D3D12_DSV_FLAG_NONE, + Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 { Texture2DArray: D3D12_TEX2D_ARRAY_DSV { MipSlice: m, FirstArraySlice: a, ArraySize: 1 } }, + }; + create_dsv(dev_raw, depth_raw, &dsv, dsv_base + ((m * slices + a) as usize) * dsv_inc); + } + } + + let srv_desc = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 2 + mips, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }; + let mut srv_raw = std::ptr::null_mut(); + if create_heap(dev_raw, &srv_desc, &ID3D12DescriptorHeap::IID as *const _ as *const _, &mut srv_raw) < 0 || srv_raw.is_null() { + return None; + } + let srv_heap = ID3D12DescriptorHeap::from_raw(srv_raw); + let inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let base = srv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + let twin_srv_fmt = if steps { DXGI_FORMAT_R16_UINT } else { DXGI_FORMAT_R32_FLOAT }; + let twin_uav_fmt = if steps { DXGI_FORMAT_R16_UNORM } else { DXGI_FORMAT_R32_FLOAT }; + let twin_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: twin_srv_fmt, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { MostDetailedMip: 0, MipLevels: mips, FirstArraySlice: 0, ArraySize: slices, PlaneSlice: 0, ResourceMinLODClamp: 0.0 }, + }, + }; + create_srv(dev_raw, copy.twin.as_raw(), &twin_srv, base); + let depth_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R24_UNORM_X8_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { MostDetailedMip: 0, MipLevels: mips, FirstArraySlice: 0, ArraySize: slices, PlaneSlice: 0, ResourceMinLODClamp: 0.0 }, + }, + }; + create_srv(dev_raw, depth_raw, &depth_srv, base + inc); + for m in 0..mips { + let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: twin_uav_fmt, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture2DArray: D3D12_TEX2D_ARRAY_UAV { MipSlice: m, FirstArraySlice: 0, ArraySize: slices, PlaneSlice: 0 } }, + }; + create_uav(dev_raw, copy.twin.as_raw(), std::ptr::null_mut(), &uav, base + (2 + m as usize) * inc); + } + + let mut inner = o.cell.inner.lock().unwrap(); + let h = inner.pass_heaps.entry(copy.depth).or_insert(PassHeaps { dsv: dsv_heap, srv_uav: srv_heap }); + Some((h.dsv.clone(), h.srv_uav.clone())) +} + +/// Synchronize an `R24G8_TYPELESS` depth plane with its `R16_TYPELESS` (`steps == true`, console +/// D16S8 `118..=120`) or `R32_TYPELESS` twin on a DIRECT list: fullscreen depth write for +/// `Twin -> Depth` (`to_twin == false`) and compute readback for `Depth -> Twin` (`to_twin == true`). +/// Returns `(clobbered_gfx, clobbered_cs)`. +pub(super) unsafe fn execute_r24g8_copy(list: *mut c_void, copy: &PlaneCopy, steps: bool, to_twin: bool) -> (bool, bool) { + let barriers = |b: &[[u32; 8]]| { + let f: unsafe extern "system" fn(*mut c_void, u32, *const [u32; 8]) = std::mem::transmute(super::real::orig_fn(list, 26)); + f(list, b.len() as u32, b.as_ptr()); + }; + let tr = |res: usize, sub: u32, before: u32, after: u32| [0, 0, res as u32, (res as u64 >> 32) as u32, sub, before, after, 0]; + let all = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + + let Some(dev) = super::real::list_device(list) else { + if !to_twin { + barriers(&[tr(copy.depth, copy.sub, PARK, DEPTH_WRITE_STATE)]); + } + return (false, false); + }; + let Some((gfx_rs, gfx_pso, gfx_pso_steps, cs_rs, cs_pso)) = get_sync_pipelines(&dev) else { + if !to_twin { + barriers(&[tr(copy.depth, copy.sub, PARK, DEPTH_WRITE_STATE)]); + } + return (false, false); + }; + let Some((dsv_heap, srv_heap)) = ensure_pass_heaps(&dev, copy, steps) else { + if !to_twin { + barriers(&[tr(copy.depth, copy.sub, PARK, DEPTH_WRITE_STATE)]); + } + return (false, false); + }; + let dev_raw = dev.as_raw(); + type IncSizeFn = unsafe extern "system" fn(*mut c_void, D3D12_DESCRIPTOR_HEAP_TYPE) -> u32; + let inc_size: IncSizeFn = std::mem::transmute(super::real::orig_fn(dev_raw, 15)); + let twin_raw = copy.twin.as_raw() as usize; + let srv_raw = srv_heap.as_raw() as usize; + let mips_u32 = copy.mips.max(1) as u32; + let slices_u32 = copy.array.max(1) as u32; + + if !to_twin { + barriers(&[tr(twin_raw, all, UNORDERED_ACCESS, SRV_ALL), tr(copy.depth, copy.sub, PARK, DEPTH_WRITE_STATE)]); + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(super::real::orig_fn(list, 28)); + let set_gfx_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(super::real::orig_fn(list, 30)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(super::real::orig_fn(list, 25)); + let set_topo: unsafe extern "system" fn(*mut c_void, u32) = std::mem::transmute(super::real::orig_fn(list, 20)); + let set_gfx_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(super::real::orig_fn(list, 32)); + let set_vp: unsafe extern "system" fn(*mut c_void, u32, *const D3D12_VIEWPORT) = std::mem::transmute(super::real::orig_fn(list, 21)); + let set_sc: unsafe extern "system" fn(*mut c_void, u32, *const RECT) = std::mem::transmute(super::real::orig_fn(list, 22)); + let set_rt: unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize) = std::mem::transmute(super::real::orig_fn(list, 46)); + let set_gfx_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(super::real::orig_fn(list, 36)); + let draw: unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32) = std::mem::transmute(super::real::orig_fn(list, 12)); + + set_heaps(list, 1, &srv_raw); + set_gfx_rs(list, gfx_rs.as_raw()); + set_pso(list, if steps { gfx_pso_steps.as_raw() } else { gfx_pso.as_raw() }); + set_topo(list, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32); + set_gfx_table(list, 1, srv_heap.GetGPUDescriptorHandleForHeapStart().ptr); + let dsv_base = dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + let dsv_inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + for &k in ©.subs { + let m = k % mips_u32; + let a = k / mips_u32; + let mw = (copy.width >> m).max(1); + let mh = (copy.height >> m).max(1); + let vp = D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: mw as f32, Height: mh as f32, MinDepth: 0.0, MaxDepth: 1.0 }; + let sc = RECT { left: 0, top: 0, right: mw as i32, bottom: mh as i32 }; + set_vp(list, 1, &vp); + set_sc(list, 1, &sc); + let dsv = dsv_base + ((m * slices_u32 + a) as usize) * dsv_inc; + set_rt(list, 0, std::ptr::null(), 0, &dsv); + let c = [a, m]; + set_gfx_consts(list, 0, 2, c.as_ptr(), 0); + draw(list, 3, 1, 0, 0); + } + barriers(&[tr(twin_raw, all, SRV_ALL, UNORDERED_ACCESS)]); + (true, false) + } else { + barriers(&[tr(copy.depth, copy.sub, PARK, SRV_ALL)]); + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(super::real::orig_fn(list, 28)); + let set_cs_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(super::real::orig_fn(list, 29)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(super::real::orig_fn(list, 25)); + let set_cs_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(super::real::orig_fn(list, 31)); + let set_cs_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(super::real::orig_fn(list, 35)); + let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(super::real::orig_fn(list, 14)); + + set_heaps(list, 1, &srv_raw); + set_cs_rs(list, cs_rs.as_raw()); + set_pso(list, cs_pso.as_raw()); + let gpu_base = srv_heap.GetGPUDescriptorHandleForHeapStart().ptr; + let inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as u64; + set_cs_table(list, 1, gpu_base + inc); + let mut dispatched = vec![false; mips_u32 as usize]; + for &k in ©.subs { + let m = k % mips_u32; + if dispatched[m as usize] { + continue; + } + dispatched[m as usize] = true; + let mw = (copy.width >> m).max(1); + let mh = (copy.height >> m).max(1); + let c = [mw, mh, slices_u32, m]; + set_cs_consts(list, 0, 4, c.as_ptr(), 0); + set_cs_table(list, 2, gpu_base + (2 + m as u64) * inc); + dispatch(list, mw.div_ceil(8), mh.div_ceil(8), slices_u32); + } + let uav_barrier = [2u32, 0, twin_raw as u32, (twin_raw as u64 >> 32) as u32, 0, 0, 0, 0]; + barriers(&[uav_barrier, tr(copy.depth, copy.sub, SRV_ALL, PARK)]); + (false, true) + } +} + /// A UAV of a depth buffer stays a null view (`Resolve::Null`). pub(super) fn null_view(why: &'static str) { #[cfg(test)] @@ -1266,9 +2022,25 @@ mod tests { #[test] fn a_depth_view_is_a_view_of_a_twin_of_the_planes_size() { assert_eq!( - [twin_format(39, 0), twin_format(19, 0), twin_format(53, 0), twin_format(44, 1), twin_format(19, 1)], - [DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_TYPELESS], - "D32, D32S8, D16 depth; stencil" + [ + twin_format(39, 40, 0), + twin_format(19, 20, 0), + twin_format(53, 55, 0), + twin_format(44, 118, 0), + twin_format(44, 45, 0), + twin_format(44, 45, 1), + twin_format(19, 20, 1), + ], + [ + DXGI_FORMAT_R32_TYPELESS, + DXGI_FORMAT_R32_TYPELESS, + DXGI_FORMAT_R16_TYPELESS, + DXGI_FORMAT_R16_TYPELESS, + DXGI_FORMAT_R32_TYPELESS, + DXGI_FORMAT_R8_TYPELESS, + DXGI_FORMAT_R8_TYPELESS, + ], + "D32, D32S8, D16, console D16S8, D24S8 depth; stencil" ); // an R32 twin: the depth as a float unless the title asked for another R32 class for (asked, got) in [ @@ -1316,12 +2088,13 @@ mod tests { ..Default::default() }; let base = 0x7B30_0000_1000usize; - // console D32, D16, D32S8, D24S8; the PC formats of the buffers; the views of their depth + // console D32, D16, D32S8, D24S8, D16S8; the PC formats of the buffers; the views of their depth for (k, (console, pc, view, on)) in [ (40u32, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_FLOAT, "the twin could not be made"), (55, DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UNORM, "the twin could not be made"), (20, DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, "the twin could not be made"), - (45, DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_R24_UNORM_X8_TYPELESS, "its depth plane has no twin yet"), + (45, DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_R24_UNORM_X8_TYPELESS, "the twin could not be made"), + (118, DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_R16_UNORM, "the twin could not be made"), ] .into_iter() .enumerate() @@ -1497,9 +2270,17 @@ mod tests { assert_eq!(plan(tr(res, 1, DEPTH_WRITE, UA)), (vec![tr(res, 1, DEPTH_WRITE, PARK)], vec![(res, 1, vec![1], tw)])); assert_eq!(plan(tr(res, 2, DEPTH_WRITE, UA)), (vec![tr(res, 2, DEPTH_WRITE, PARK)], vec![]), "a stencil subresource: parked, not copied"); - // a D24S8 (its depth plane has no twin): parked, its depth plane not copied - assert!(register(d24, &desc(3, 64, 64, 45, 1, 6), None, DEPTH_WRITE)); - assert_eq!(plan(tr(d24, ALL, DEPTH_WRITE, UA)), (vec![tr(d24, ALL, DEPTH_WRITE, PARK)], vec![])); + // a D24S8/D16S8 now parks and syncs via fullscreen/CS pass + assert!(register(d24, &desc(3, 64, 64, 118, 1, 6), None, DEPTH_WRITE)); + let t24 = stand_in(); + plant_depth_twin(d24, &t24); + assert_eq!(plan(tr(d24, ALL, DEPTH_WRITE, UA)), (vec![tr(d24, ALL, DEPTH_WRITE, PARK)], vec![(d24, ALL, vec![0], t24.as_raw() as usize)])); + let mut out_d24 = vec![tr(d24, ALL, UA, DEPTH_READ)]; + let p_out = plan_with(&mut out_d24, true, &mut Vec::new(), &mut |_r, o| twin_if_made(o)); + assert_eq!(out_d24, vec![tr(d24, ALL, DEPTH_WRITE, DEPTH_READ)]); + assert_eq!(p_out.to_plane.len(), 1); + assert_eq!(p_out.to_plane[0].r24g8_steps, Some(true)); + // an object made in UNORDERED_ACCESS, one XCL does not keep, a UAV barrier: as they came assert!(register(in_ua, &desc(3, 64, 64, 40, 1, 6), None, UA)); let uav_barrier = [2, 0, res as u32, (res as u64 >> 32) as u32, 0, 0, 0, 0]; @@ -1511,6 +2292,108 @@ mod tests { forget(in_ua); } + #[test] + fn a_draws_depth_test_and_other_work_each_get_the_side_written_last() { + let depth = |write| Use::Depth { write }; + // a draw that tests against the buffer: the twin into the plane when shaders may have + // written it; the plane is the newer side after (unless the view is read only) + assert_eq!(step(Side::Twin, depth(true)), (Some(false), Side::Plane)); + assert_eq!(step(Side::Both, depth(true)), (None, Side::Plane)); + assert_eq!(step(Side::Plane, depth(true)), (None, Side::Plane)); + assert_eq!(step(Side::Twin, depth(false)), (Some(false), Side::Both)); + assert_eq!(step(Side::Both, depth(false)), (None, Side::Both)); + assert_eq!(step(Side::Plane, depth(false)), (None, Side::Plane)); + // any other work: the plane into the twin after such draws; the twin is the newer side after + assert_eq!(step(Side::Plane, Use::Shader), (Some(true), Side::Twin)); + assert_eq!(step(Side::Both, Use::Shader), (None, Side::Twin)); + assert_eq!(step(Side::Twin, Use::Shader), (None, Side::Twin)); + } + + /// (the copies before work: (object, into the twin, subresources)) + fn work(c: &[WorkCopy]) -> Vec<(usize, bool, Vec)> { + c.iter().map(|c| (c.copy.depth, c.to_twin, c.copy.subs.clone())).collect() + } + + #[test] + fn draws_that_test_against_a_buffer_left_in_unordered_access_get_what_shaders_wrote() { + let (res, dsv, ro_dsv) = (0x7E30_0000_1000usize, 0x7E30_0001_0000usize, 0x7E30_0001_0040usize); + // a console D32 of 2 mips with unordered access and a depth twin, two DSVs of it + let mut x = desc(3, 1280, 736, 40, 1, 6); + x[0x1E..0x20].copy_from_slice(&2u16.to_le_bytes()); + assert!(register(res, &x, None, DEPTH_WRITE)); + let t = stand_in(); + plant_depth_twin(res, &t); + note_dsv(dsv, res, 0); + note_dsv(ro_dsv, res, 1); + let id = cell_of(res).unwrap().id; + let mut owed = Owed::default(); + let barrier = |b: [u32; 8], owed: &mut Owed| { + let mut v = vec![b]; + let p = plan_with(&mut v, true, &mut Vec::new(), &mut |_r, o| twin_if_made(o)); + owed.apply(&p); + (copies(&p.to_plane), p.settled) + }; + + // into UNORDERED_ACCESS: followed; a pixel program writes the twin (any other draw) + barrier(tr(res, ALL, DEPTH_WRITE, UA), &mut owed); + assert!(any_live()); + assert!(before_work(&mut owed, None).is_empty(), "the two hold the same"); + // the draws that test against it: the twin into the plane first, once + assert_eq!(work(&before_work(&mut owed, Some(dsv))), [(res, false, vec![0, 1])]); + assert!(before_work(&mut owed, Some(dsv)).is_empty(), "the plane holds it now"); + assert!(before_work(&mut owed, Some(ro_dsv)).is_empty()); + // work after them may read the twin: the plane, which those draws wrote, into the twin + assert_eq!(work(&before_work(&mut owed, None)), [(res, true, vec![0, 1])]); + assert!(before_work(&mut owed, None).is_empty()); + // a read-only depth target after it: the twin into the plane, and the two hold the same + assert_eq!(work(&before_work(&mut owed, Some(ro_dsv))), [(res, false, vec![0, 1])]); + assert!(before_work(&mut owed, Some(ro_dsv)).is_empty()); + assert!(before_work(&mut owed, Some(dsv)).is_empty()); + // out of UNORDERED_ACCESS after a draw tested (and wrote) the plane: the twin is not + // copied over it; the stretch ends + let kept = PLANE_KEPT.load(Ordering::Relaxed); + assert_eq!(barrier(tr(res, ALL, UA, DEPTH_READ), &mut owed), (vec![], vec![id])); + assert!(PLANE_KEPT.load(Ordering::Relaxed) > kept); + assert!(before_work(&mut owed, Some(dsv)).is_empty() && owed.0.is_empty(), "no longer followed"); + + // in and out with shaders only: copied back as before + barrier(tr(res, ALL, DEPTH_READ, UA), &mut owed); + assert!(before_work(&mut owed, None).is_empty()); + assert_eq!(barrier(tr(res, ALL, UA, DEPTH_WRITE), &mut owed), (vec![(res, ALL, vec![0, 1], t.as_raw() as usize)], vec![id])); + + // a stretch begun on another list: this one follows it from a draw that tests against it + let mut other = Owed::default(); + barrier(tr(res, ALL, DEPTH_WRITE, UA), &mut other); + assert!(before_work(&mut owed, None).is_empty(), "not followed here: nothing"); + assert!(before_work(&mut other, None).is_empty()); + assert_eq!(work(&before_work(&mut owed, Some(dsv))), [(res, false, vec![0, 1])]); + assert_eq!(owed.0.len(), 1); + barrier(tr(res, ALL, UA, DEPTH_WRITE), &mut other); + + // not followed: one subresource, or into UNORDERED_ACCESS on a compute list + barrier(tr(res, 1, DEPTH_WRITE, UA), &mut owed); + assert!(cell_of(res).unwrap().live.load(Ordering::Relaxed) == 0); + barrier(tr(res, 1, UA, DEPTH_WRITE), &mut owed); + let mut v = vec![tr(res, ALL, DEPTH_WRITE, UA)]; + let p = plan_with(&mut v, false, &mut Vec::new(), &mut |_r, o| twin_if_made(o)); + assert!(p.live.is_empty() && cell_of(res).unwrap().live.load(Ordering::Relaxed) == 0); + forget(res); + } + + #[test] + fn an_r24g8_buffer_in_unordered_access_is_not_followed() { + let res = 0x7E40_0000_1000usize; + // a console D16S8 (PC R24G8): its plane is written by a pass a draw being bound cannot take + assert!(register(res, &desc(3, 64, 64, 118, 1, 6), None, DEPTH_WRITE)); + let t = stand_in(); + plant_depth_twin(res, &t); + let mut v = vec![tr(res, ALL, DEPTH_WRITE, UA)]; + let p = plan_with(&mut v, true, &mut Vec::new(), &mut |_r, o| twin_if_made(o)); + assert_eq!(p.to_twin.len(), 1, "copied into its twin as before"); + assert!(p.live.is_empty() && cell_of(res).unwrap().live.load(Ordering::Relaxed) == 0); + forget(res); + } + /// The stencil twin of a D24S8 (console D16S8) and of a D32S8: the plane is copied into it on /// a DIRECT list's way into UNORDERED_ACCESS and back on the way out, only after such a way in /// (not after one on a compute list, nor before the twin was made); the buffer is parked. diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 8f2809df65..32c8471b52 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -396,15 +396,16 @@ fn intern_shader_blob(bytes: &[u8]) -> Arc<[u8]> { } let arc: Arc<[u8]> = Arc::from(bytes); let mut g = BASE_SHADERS.lock().unwrap(); - let pool = g.get_or_insert_with(|| ShaderPool { map: HashMap::new(), next_sweep: 8192 }); + let pool = g.get_or_insert_with(|| ShaderPool { map: HashMap::new(), next_sweep: super::real::SHADER_POOL_SWEEP }); if let Some(existing) = pool.map.get(&key).and_then(std::sync::Weak::upgrade) { if &*existing == bytes { return existing; } } + // (a dead entry keeps its shader's bytes: `real::SHADER_POOL_SWEEP`) if pool.map.len() >= pool.next_sweep { pool.map.retain(|_, w| w.strong_count() > 0); - pool.next_sweep = (pool.map.len().saturating_mul(2)).max(8192); + pool.next_sweep = pool.map.len() + super::real::SHADER_POOL_SWEEP; } pool.map.insert(key, Arc::downgrade(&arc)); arc @@ -815,6 +816,13 @@ pub(super) unsafe fn pc_resource_desc_for_device(device: *mut c_void, x: &[u8; 0 strip_unsupported_uav_for_device(device, pc_resource_desc(x)) } +/// Whether an sRGB texture with unordered access is made typeless (`pc_resource_desc`): only +/// with `XCL_SRGB_UAV=1` (a retail title's world was not seen to look right with it yet). +fn srgb_uav() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SRGB_UAV").is_ok_and(|v| v.trim() == "1")) +} + /// the console resource desc (0x38 bytes, D3D12_RESOURCE_DESC) as a PC one: its tile layouts /// and console flag bits mean nothing to a PC driver pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { @@ -854,6 +862,14 @@ pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { if format == 67 && flags & 5 != 0 { d[0x20..0x24].copy_from_slice(&26u32.to_le_bytes()); } + // an sRGB texture the console also lets shaders write (a retail title's G-buffer colour, a + // render target and a UAV): the PC has no unordered access for an sRGB format – typeless, + // so the title's sRGB views and a linear UAV of the same bytes both fit + // (`pc_shader_view_format`, `pc_uav_linear_format`) + let samples_x = u32::from_le_bytes(d[0x24..0x28].try_into().unwrap()); + if matches!(format, 29 | 91) && flags & 4 != 0 && flags & 2 == 0 && samples_x <= 1 && dim != D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32 && srgb_uav() { + d[0x20..0x24].copy_from_slice(&(if format == 29 { 27u32 } else { 90u32 }).to_le_bytes()); + } // a depth buffer the console also lets shaders write (a retail game's: ALLOW_DEPTH_STENCIL | // ALLOW_UNORDERED_ACCESS): the PC refuses the pair – the depth buffer stays if flags & 2 != 0 { @@ -952,6 +968,10 @@ pub fn pc_shader_view_format(resource: u32, view: u32) -> u32 { (87, 88) => 87, // a target made R11G11B10_FLOAT (`pc_resource_desc`) (26, 67) => 26, + // an sRGB texture with unordered access made typeless (`pc_resource_desc`): the view the + // title gave no format is the sRGB one (a UAV: `pc_uav_linear_format` of it) + (27, 0 | 27) => 29, + (90, 0 | 90) => 91, (_, v) => v, } } @@ -1290,6 +1310,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } real::note_title_address(*ppv as usize, va as usize); super::depth_uav::note_created(*ppv, &x, Some(va as usize), state); + super::format_alias::register_title_texture(this as usize, *ppv as usize, va as usize, &pc, flags, state); super::lut3d::created("CreatePlacedResourceX (GPU-owned: on the title's pages / an arena)", *ppv, Some(&x), Some(va as usize), false, state); } return hr; @@ -1308,7 +1329,10 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } }; if hr >= 0 && !buffer && !(*ppv).is_null() { + let pc = std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC); + let aliased_to_gpu = super::format_alias::register_title_texture(this as usize, *ppv as usize, va as usize, &pc, flags, state); static M: AtomicU64 = AtomicU64::new(0); + if !aliased_to_gpu { match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)) { Ok(()) => { real::note_title_address(*ppv as usize, va as usize); @@ -1326,6 +1350,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } Err(_) => {} } + } } if hr >= 0 && !(*ppv).is_null() { real::note_title_address(*ppv as usize, va as usize); @@ -1789,7 +1814,7 @@ mod tests { 103, 107, // YUV (NV12, YUY2) ] { let (out_fmt, out_flags) = make(3, fmt, 1, 0x4); - if matches!((fmt, out_fmt), (85, 28) | (88, 87)) { + if matches!((fmt, out_fmt), (85, 28) | (88, 87) | (29, 27) | (91, 90)) { // promoted to a format a PC driver takes as a UAV of the same values: the flag // stays, and is valid there assert_eq!(out_flags & 0x4, 0x4, "format {fmt} promoted to {out_fmt} keeps ALLOW_UNORDERED_ACCESS"); @@ -1798,6 +1823,16 @@ mod tests { assert_eq!(out_flags & 0x4, 0, "format {fmt} must strip ALLOW_UNORDERED_ACCESS"); } } + // an sRGB render target with unordered access is typeless with both flags; without + // unordered access, multisampled or a depth buffer it stays what it is + if srgb_uav() { + assert_eq!((make(3, 29, 1, 0x5), make(3, 91, 1, 0x5)), ((27, 0x5), (90, 0x5))); + } else { + assert_eq!((make(3, 29, 1, 0x5), make(3, 91, 1, 0x5)), ((29, 0x1), (91, 0x1))); + } + assert_eq!((make(3, 29, 1, 0x1), make(3, 29, 4, 0x5)), ((29, 0x1), (29, 0x1))); + assert_eq!((pc_shader_view_format(27, 0), pc_shader_view_format(27, 29), pc_shader_view_format(27, 28), pc_shader_view_format(90, 0)), (29, 29, 28, 91)); + assert_eq!(pc_uav_linear_format(pc_shader_view_format(27, 0)), 28, "its UAV is the linear one"); // Multisampled textures never support UAV even on UAV-capable formats: assert_eq!(make(3, 28, 4, 0x5), (28, 0x1)); assert_eq!(make(3, 27, 2, 0x4), (27, 0x0)); @@ -2204,4 +2239,18 @@ mod tests { forget_base(pso_key2); assert!(weak_vs.upgrade().is_none(), "shared blob drops once all owning PSOs are released"); } + + /// Base shaders no PSO holds any more do not pile up in `BASE_SHADERS` (each dead entry keeps + /// its bytes): after 3000 short-lived ones, fewer than two sweeps' worth are left. + #[test] + fn base_shaders_that_died_are_swept() { + for i in 0u32..3000 { + let mut bytes = vec![0xB5u8; 64]; + bytes[..4].copy_from_slice(&i.to_le_bytes()); + drop(intern_shader_blob(&bytes)); + } + let g = BASE_SHADERS.lock().unwrap(); + let dead = g.as_ref().map_or(0, |p| p.map.values().filter(|w| w.strong_count() == 0).count()); + assert!(dead < 2 * super::super::real::SHADER_POOL_SWEEP, "{dead} dead entries kept"); + } } diff --git a/crates/xcl/src/hle/d3d12x/dred.rs b/crates/xcl/src/hle/d3d12x/dred.rs index 4eef23183e..98561478bd 100644 --- a/crates/xcl/src/hle/d3d12x/dred.rs +++ b/crates/xcl/src/hle/d3d12x/dred.rs @@ -46,6 +46,14 @@ pub fn label(pso: usize, shaders: &[(&str, Option<&[u8]>)]) { LABELS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, text); } +/// Name an internal pipeline (`SCALE_ARGS_HLSL`, `indirect_guard`, etc.) for DRED breadcrumbs. +pub fn label_text(pso: usize, make: impl FnOnce() -> String) { + if !on() || pso == 0 { + return; + } + LABELS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, make()); +} + pub(super) fn label_of(pso: usize) -> Option { LABELS.lock().unwrap().as_ref()?.get(&pso).cloned() } diff --git a/crates/xcl/src/hle/d3d12x/format_alias.rs b/crates/xcl/src/hle/d3d12x/format_alias.rs new file mode 100644 index 0000000000..f10f472390 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/format_alias.rs @@ -0,0 +1,1707 @@ +//! 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=1` to enable 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, RwLock}; + +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); + TITLE_TEX_IDS + .write() + .unwrap_or_else(|e| e.into_inner()) + .get_or_insert_with(HashSet::new) + .insert(res); + } + self.by_res.insert(res, tex); + mark_gpu_written + } + + /// 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(set) = TITLE_TEX_IDS.write().unwrap_or_else(|e| e.into_inner()).as_mut() { + set.remove(&res); + } + } + if let Some(list) = self.by_va.get_mut(&old.va) { + list.retain(|&r| r != res); + 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); +/// Leaf lock mirror of `Owner::TitlePlaced` resource pointers in `TABLE::by_res` so per-barrier +/// `note_title_transition` rejects untracked resources (buffers, non-aliased RTs) with a shared +/// read lock instead of contending on `TABLE`. +static TITLE_TEX_IDS: RwLock>> = RwLock::new(None); +static TRACKED_TITLE_TEX: AtomicUsize = AtomicUsize::new(0); +static ACTIVE_PAIRS: AtomicUsize = AtomicUsize::new(0); +static ACTIVE_PLACED_UAV_PAIRS: AtomicUsize = AtomicUsize::new(0); + +/// Insert `value` at `key` or keep the existing entry, always returning a cloned handle to the +/// winning map entry plus `Some(loser)` if another thread won the race so the caller can drop the +/// loser outside the table lock. +fn cache_insert_or_clone( + map: &mut HashMap, + key: K, + value: V, +) -> (V, Option) { + match map.entry(key) { + std::collections::hash_map::Entry::Occupied(e) => (e.get().clone(), Some(value)), + std::collections::hash_map::Entry::Vacant(e) => (e.insert(value).clone(), None), + } +} + +/// Release internal resources evicted from `placed_uavs` / `placed_srvs` outside `TABLE`. +/// Adopted resources route through `real::res_release`, which cleans up `title_textures` / +/// `vram` / `format_alias` tracking on the final ref and defers the PC `Release` via +/// `late_release::hold` once no in-flight caller still holds a cloned reference. +unsafe fn defer_drop_resources(evicted: Vec) { + for r in evicted { + if super::real::is_adopted(r.as_raw()) || !super::late_release::enabled() { + drop(r); + } else { + super::late_release::hold(r.into_raw() as usize, false); + } + } +} + +/// D3D12 resource states legal in a `ResourceBarrier` on a `COMPUTE` command list for textures +/// (`COMMON`, `UNORDERED_ACCESS`, `NON_PIXEL_SHADER_RESOURCE`, `COPY_DEST`, `COPY_SOURCE`). +const COMPUTE_VALID_STATES: u32 = 0x8 | 0x40 | 0x400 | 0x800; + +fn state_valid_on_list(ty: D3D12_COMMAND_LIST_TYPE, st: u32) -> bool { + ty == D3D12_COMMAND_LIST_TYPE_DIRECT || (st & !COMPUTE_VALID_STATES == 0) +} + +/// Per-open-list state for `PlacedSrv` resources transitioned into read state on that list +/// (returned to `COMMON` before `Close()`), plus last synced `bind::activity()`. +#[derive(Default)] +struct ListSyncState { + /// `PlacedSrv` resource -> current state on this open list (`SRV_ALL` or `SRV_NON_PIXEL`). + srv_states: HashMap, + last_activity: (u64, u64), + list_type: Option, +} + +static LIST_STATES: Mutex>> = Mutex::new(None); + +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_FORMAT_ALIAS").is_ok_and(|v| v.trim() == "1")) +} + +/// `XCL_FORMAT_ALIAS_DEDUP=0`: disable skipping redundant format-alias copies when the source +/// texture was not written since its last sync. +fn dedup_enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_FORMAT_ALIAS_DEDUP").is_ok_and(|v| v.trim() == "0")) +} + +fn note_skipped_sync() { + static SKIPPED: AtomicU64 = AtomicU64::new(0); + let n = SKIPPED.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || (n.is_power_of_two() && n >= 16) { + crate::xlog_info!("D3D12.X: skipped {n} redundant format-alias texture copies (source unchanged since last sync)"); + } +} + +fn mark_writer_dirty(res: usize) { + if TRACKED_TITLE_TEX.load(Ordering::Relaxed) == 0 && ACTIVE_PLACED_UAV_PAIRS.load(Ordering::Relaxed) == 0 { + return; + } + if let Some(tex) = TABLE.lock().unwrap().as_mut().and_then(|t| t.by_res.get_mut(&res)) { + if tex.is_writer { + tex.dirty = true; + tex.last_sync_activity = None; + } + } +} + +unsafe fn create_internal_texture(dev: *mut c_void, pc_desc: &[u8; 0x38], initial_state: u32) -> Option { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut out: *mut c_void = std::ptr::null_mut(); + let hr = real::dev_create_committed_resource( + dev, + &heap as *const _ as usize, + 0, + pc_desc.as_ptr() as usize, + initial_state as usize, + 0, + &ID3D12Resource::IID as *const _ as *const windows_sys::core::GUID, + &mut out, + ); + if hr < 0 || out.is_null() { + return None; + } + Some(ID3D12Resource::from_raw(out)) +} + +/// Obtain or create the host UAV texture backing `CreateUnorderedAccessViewAtX` at `va`, +/// returning an owned reference so concurrent eviction cannot free it mid-call. +pub(super) unsafe fn placed_uav_resource(dev: *mut c_void, rdesc: *const u8, va: u64, view_fmt: u32) -> Option { + if rdesc.is_null() || va == 0 || !crate::gpu::shader::readable(rdesc as usize, 0x38) { + return None; + } + let raw_x: [u8; 0x38] = (rdesc as *const [u8; 0x38]).read_unaligned(); + let prepared = prepare_placed_uav_desc(&raw_x, view_fmt); + let key = (va, prepared); + + { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + if let Some(res) = t.placed_uavs.get(&key) { + return Some(res.clone()); + } + } + + let pc = super::device_x::pc_resource_desc(&prepared); + let flags = u32::from_le_bytes(prepared[0x30..0x34].try_into().unwrap()); + let is_depth_uav = flags & (FLAG_DEPTH_STENCIL | FLAG_UAV) == (FLAG_DEPTH_STENCIL | FLAG_UAV); + let init_state = if is_depth_uav { + super::device_x::pc_initial_state(flags, STATE_UAV) + } else { + STATE_UAV + }; + let Some(res) = create_internal_texture(dev, &pc, init_state) else { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: placed UAV texture at {va:#x} (view fmt {view_fmt}) could not be created"); + } + return None; + }; + let raw = res.as_raw(); + if is_depth_uav { + super::depth_uav::note_created(raw, &prepared, Some(va as usize), init_state); + } + let pc_desc = res.GetDesc(); + let shape = TexShape::from_pc_desc(&pc_desc); + let (winner, lost_race, mark) = { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + let (winner, loser) = cache_insert_or_clone(&mut t.placed_uavs, key, res); + let mark = if loser.is_none() && !is_depth_uav && enabled() { + t.insert( + raw as usize, + TrackedTex::new(dev as usize, va as usize, shape, Owner::PlacedUav, STATE_UAV, true), + ) + } else { + Vec::new() + }; + (winner, loser, mark) + }; + if let Some(loser) = lost_race { + defer_drop_resources(vec![loser]); + } else { + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed); + if n < 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: placed UAV texture at {va:#x} ({}x{}x{}, {} mips, pc fmt {}, view fmt {view_fmt}) -> {raw:p} ({} created)", + pc_desc.Width, + pc_desc.Height, + pc_desc.DepthOrArraySize, + pc_desc.MipLevels, + pc_desc.Format.0, + n + 1 + ); + } + } + for reader in mark { + super::title_textures::note_gpu_write(0, reader); + } + Some(winner) +} + +/// Obtain or create the host SRV texture backing `CreateShaderResourceViewAtX` at `va`, +/// returning an owned reference so concurrent eviction cannot free it mid-call. +/// If a GPU writer already occupies `va` with a compatible shape, creates a dedicated GPU-synced +/// SRV texture (skipping `title_textures` so CPU zeros never overwrite GPU writes); otherwise +/// delegates to `create_placed_resource_x` and registers it as a reader in case a placed UAV +/// appears at `va` later. +pub(super) unsafe fn placed_srv_resource(dev: *mut c_void, rdesc: *const u8, va: u64, view_fmt: u32) -> Option { + if rdesc.is_null() || va == 0 || !crate::gpu::shader::readable(rdesc as usize, 0x38) { + return None; + } + let raw_x: [u8; 0x38] = (rdesc as *const [u8; 0x38]).read_unaligned(); + let prepared = prepare_placed_srv_desc(&raw_x, view_fmt); + let key = (va, prepared); + let pc = super::device_x::pc_resource_desc(&prepared); + let pc_desc = std::ptr::read_unaligned(pc.as_ptr() as *const D3D12_RESOURCE_DESC); + let shape = TexShape::from_pc_desc(&pc_desc); + + let has_writer = { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + if let Some(res) = t.placed_srvs.get(&key) { + return Some(res.clone()); + } + enabled() && t.has_writer_at(va as usize, &shape) + }; + + let res = if has_writer { + // Dedicated GPU-synced SRV texture in COMMON state (not registered in title_textures). + create_internal_texture(dev, &pc, STATE_COMMON)? + } else { + let mut r = std::ptr::null_mut(); + let hr = super::device_x::create_placed_resource_x( + dev, + va, + prepared.as_ptr(), + 0, + std::ptr::null(), + &ID3D12Resource::IID as *const _ as *const windows_sys::core::GUID, + &mut r, + ); + if hr < 0 || r.is_null() { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: placed SRV texture at {va:#x}: resource creation failed ({hr:#x})"); + } + return None; + } + ID3D12Resource::from_raw(r) + }; + + let raw = res.as_raw(); + let owner = if has_writer { Owner::PlacedSrv } else { Owner::TitlePlaced }; + let (winner, lost_race, mark) = { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + let (winner, loser) = cache_insert_or_clone(&mut t.placed_srvs, key, res); + let mark = if loser.is_none() && enabled() { + t.insert( + raw as usize, + TrackedTex::new(dev as usize, va as usize, shape, owner, STATE_COMMON, false), + ) + } else { + Vec::new() + }; + (winner, loser, mark) + }; + if let Some(loser) = lost_race { + defer_drop_resources(vec![loser]); + } + for reader in mark { + super::title_textures::note_gpu_write(0, reader); + } + Some(winner) +} + +/// Register a title-created placed texture from `device_x::create_placed_resource_x`. +/// Returns `true` if the texture is already aliased to a GPU writer at `va` (so callers should +/// call `title_textures::note_gpu_write` and avoid CPU uploads over GPU-written texels). +pub(super) fn register_title_texture(dev: usize, res: usize, va: usize, pc_desc: &D3D12_RESOURCE_DESC, flags: u32, initial_state: u32) -> bool { + if !enabled() || res == 0 || va == 0 || pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + return false; + } + let shape = TexShape::from_pc_desc(pc_desc); + if format_element_bytes(shape.format).is_none() || shape.samples > 1 { + return false; + } + let is_writer = flags & (FLAG_RENDER_TARGET | FLAG_UAV) != 0; + let (mark, evicted) = { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + let evicted = t.evict_stale_internal_at(va, Some(&shape)); + let mark = t.insert( + res, + TrackedTex::new(dev, va, shape, Owner::TitlePlaced, initial_state, is_writer), + ); + (mark, evicted) + }; + if !evicted.is_empty() { + unsafe { defer_drop_resources(evicted) }; + } + let mut self_gpu_written = false; + for r in mark { + if r == res { + self_gpu_written = true; + } + super::title_textures::note_gpu_write(0, r); + } + self_gpu_written +} + +/// Remove a released title resource from format-alias tracking, evicting any orphaned internal +/// `PlacedUav`/`PlacedSrv` textures at the same VA via deferred GPU release. +pub(super) fn forget(res: usize) { + let evicted = { + let mut g = TABLE.lock().unwrap(); + if let Some(t) = g.as_mut() { + let mut dropped = Vec::new(); + let va = t.remove(res); + let uav_keys: Vec<_> = t.placed_uavs.iter().filter(|(_, v)| v.as_raw() as usize == res).map(|(k, _)| *k).collect(); + for k in uav_keys { + if let Some(r) = t.placed_uavs.remove(&k) { + dropped.push(r); + } + } + let srv_keys: Vec<_> = t.placed_srvs.iter().filter(|(_, v)| v.as_raw() as usize == res).map(|(k, _)| *k).collect(); + for k in srv_keys { + if let Some(r) = t.placed_srvs.remove(&k) { + dropped.push(r); + } + } + if let Some(va) = va { + dropped.extend(t.evict_stale_internal_at(va, None)); + } + dropped + } else { + Vec::new() + } + }; + if !evicted.is_empty() { + unsafe { defer_drop_resources(evicted) }; + } + if let Some(m) = LIST_STATES.lock().unwrap().as_mut() { + for s in m.values_mut() { + s.srv_states.remove(&res); + } + } +} + +/// Track state transitions of title-owned textures (even before an alias peer is created at the +/// same VA) and collect any writers leaving `UNORDERED_ACCESS` / `RENDER_TARGET` whose +/// format-aliased readers need a copy. Ignores split-barrier `BEGIN_ONLY` flags. +pub(super) fn note_title_transition(res: usize, subresource: u32, before: u32, after: u32, flags: u32, writers_to_sync: &mut Vec<(usize, u32)>) { + const BARRIER_BEGIN_ONLY: u32 = 1; + const STATE_COPY_DEST: u32 = 0x400; + if TRACKED_TITLE_TEX.load(Ordering::Relaxed) == 0 || flags == BARRIER_BEGIN_ONLY { + return; + } + { + let ids = TITLE_TEX_IDS.read().unwrap_or_else(|e| e.into_inner()); + if !ids.as_ref().is_some_and(|s| s.contains(&res)) { + return; + } + } + let mut g = TABLE.lock().unwrap(); + let Some(t) = g.as_mut() else { + return; + }; + let Some(tex) = t.by_res.get_mut(&res) else { + return; + }; + if tex.owner != Owner::TitlePlaced { + return; + } + tex.update_state(subresource, after); + let write_bits = STATE_UAV | STATE_RENDER_TARGET | STATE_COPY_DEST; + if tex.is_writer && ((before & write_bits != 0) || (after & write_bits != 0)) { + tex.dirty = true; + tex.last_sync_activity = None; + } + let uniform = tex.uniform_state(); + let is_writer = tex.is_writer; + let leaving_write = (before & (STATE_UAV | STATE_RENDER_TARGET) != 0) && (after & (STATE_UAV | STATE_RENDER_TARGET) == 0); + if is_writer && leaving_write && ACTIVE_PAIRS.load(Ordering::Relaxed) != 0 && t.pairs.iter().any(|p| p.writer == res) { + if let Some(st) = uniform { + writers_to_sync.push((res, st)); + } + } +} + +/// Inspect enhanced `D3D12_BARRIER_GROUP` texture barriers (`#146`) and collect any tracked +/// `TitlePlaced` writers leaving write access so their format-aliased readers receive a copy. +pub(super) unsafe fn filter_enhanced_barriers(n: u32, groups: *const c_void, writers_to_sync: &mut Vec<(usize, u32)>) { + if TRACKED_TITLE_TEX.load(Ordering::Relaxed) == 0 + || ACTIVE_PAIRS.load(Ordering::Relaxed) == 0 + || n == 0 + || groups.is_null() + { + return; + } + let group_count = (n as usize).min(256); + let group_bytes = group_count.saturating_mul(std::mem::size_of::()); + if !crate::gpu::shader::readable(groups as usize, group_bytes) { + return; + } + let write_access = (D3D12_BARRIER_ACCESS_RENDER_TARGET.0 as u32) + | (D3D12_BARRIER_ACCESS_UNORDERED_ACCESS.0 as u32) + | (D3D12_BARRIER_ACCESS_COPY_DEST.0 as u32); + let read_access = (D3D12_BARRIER_ACCESS_SHADER_RESOURCE.0 as u32) + | (D3D12_BARRIER_ACCESS_COPY_SOURCE.0 as u32); + let is_write_layout = |l: D3D12_BARRIER_LAYOUT| { + matches!( + l, + D3D12_BARRIER_LAYOUT_RENDER_TARGET + | D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_COPY_DEST + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COPY_DEST + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_DEST + ) + }; + let is_common_layout = |l: D3D12_BARRIER_LAYOUT| { + matches!( + l, + D3D12_BARRIER_LAYOUT_COMMON + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COMMON + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COMMON + ) + }; + let is_read_layout = |l: D3D12_BARRIER_LAYOUT| { + matches!( + l, + D3D12_BARRIER_LAYOUT_SHADER_RESOURCE + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_SHADER_RESOURCE + | D3D12_BARRIER_LAYOUT_GENERIC_READ + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_GENERIC_READ + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_GENERIC_READ + | D3D12_BARRIER_LAYOUT_COPY_SOURCE + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COPY_SOURCE + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_SOURCE + ) + }; + let dedup = dedup_enabled(); + let slice = std::slice::from_raw_parts(groups as *const D3D12_BARRIER_GROUP, group_count); + for grp in slice { + if grp.Type != D3D12_BARRIER_TYPE_TEXTURE { + continue; + } + let count = (grp.NumBarriers as usize).min(4096); + if count == 0 { + continue; + } + let ptr = grp.Anonymous.pTextureBarriers; + let bytes = count.saturating_mul(std::mem::size_of::()); + if ptr.is_null() || !crate::gpu::shader::readable(ptr as usize, bytes) { + continue; + } + let tbs = std::slice::from_raw_parts(ptr, count); + let mut g = TABLE.lock().unwrap(); + let Some(t) = g.as_mut() else { + continue; + }; + for tb in tbs { + let res: usize = std::mem::transmute_copy(&tb.pResource); + if res == 0 { + continue; + } + let has_pair = t.pairs.iter().any(|p| p.writer == res); + let Some(tex) = t.by_res.get_mut(&res) else { + continue; + }; + if tex.owner != Owner::TitlePlaced || !tex.is_writer || !has_pair { + continue; + } + let discard = (tb.Flags.0 as u32) & (D3D12_TEXTURE_BARRIER_FLAG_DISCARD.0 as u32) != 0 + || tb.LayoutBefore == D3D12_BARRIER_LAYOUT_UNDEFINED; + if discard { + tex.dirty = true; + tex.last_sync_activity = None; + continue; + } + let ab = tb.AccessBefore.0 as u32; + let aa = tb.AccessAfter.0 as u32; + let before_write = (ab & write_access != 0) || is_write_layout(tb.LayoutBefore); + let after_write = (aa & write_access != 0) || is_write_layout(tb.LayoutAfter); + if before_write || after_write { + tex.dirty = true; + tex.last_sync_activity = None; + } + let common_to_read = ab == 0 && is_common_layout(tb.LayoutBefore) && ((aa & read_access != 0) || is_read_layout(tb.LayoutAfter)); + if before_write && !after_write { + if let Some(st) = tex.uniform_state() { + writers_to_sync.push((res, st)); + } + } else if common_to_read { + if !dedup || tex.dirty { + if let Some(st) = tex.uniform_state() { + writers_to_sync.push((res, st)); + } + } else { + note_skipped_sync(); + } + } + } + } +} + +/// Copy all subresources of `src` into `dst` through an intermediate buffer (`CopyTextureRegion`), +/// preserving raw texel bits across incompatible DXGI format families (e.g. `R32_UINT` -> +/// `R9G9B9E5_SHAREDEXP` or `BCn` <-> `R32G32B32A32_UINT`). +/// Callers must ensure `src` is in `COPY_SOURCE` and `dst` is in `COPY_DEST`. +pub(super) unsafe fn copy_all_subresources_through_buffer( + list: *mut c_void, + dev: &ID3D12Device, + dst: &ID3D12Resource, + src: &ID3D12Resource, +) -> bool { + let dst_desc = dst.GetDesc(); + let src_desc = src.GetDesc(); + let dst_shape = TexShape::from_pc_desc(&dst_desc); + let src_shape = TexShape::from_pc_desc(&src_desc); + if !can_copy_through_buffer(&dst_shape, &src_shape) { + return false; + } + let count = dst_shape.subresource_count().min(src_shape.subresource_count()); + for sub in 0..count { + if !copy_one_subresource_through_buffer(list, dev, dst, &dst_desc, sub, src, &src_desc, sub) { + return false; + } + } + true +} + +struct OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION); + +impl Drop for OwnedCopyLoc { + fn drop(&mut self) { + unsafe { ManuallyDrop::drop(&mut self.0.pResource) }; + } +} + +/// Verify two single-subresource footprints have identical element byte widths and compatible +/// block/texel dimensions (preventing accidental aliasing of incompatible formats that merely +/// share a 256-byte-aligned `RowPitch`). +fn subresource_footprints_compatible(dst_fmt: u32, dst_fp: &D3D12_SUBRESOURCE_FOOTPRINT, src_fmt: u32, src_fp: &D3D12_SUBRESOURCE_FOOTPRINT) -> bool { + let (Some((db, dbc)), Some((sb, sbc))) = (format_element_bytes(dst_fmt), format_element_bytes(src_fmt)) else { + return false; + }; + if db != sb || dst_fp.Depth != src_fp.Depth { + return false; + } + let eff = |bc: bool, w: u32, h: u32| -> (u32, u32) { + if bc { (w.div_ceil(4), h.div_ceil(4)) } else { (w, h) } + }; + eff(dbc, dst_fp.Width, dst_fp.Height) == eff(sbc, src_fp.Width, src_fp.Height) +} + +unsafe fn copy_one_subresource_through_buffer( + list: *mut c_void, + dev: &ID3D12Device, + dst: &ID3D12Resource, + dst_desc: &D3D12_RESOURCE_DESC, + dst_sub: u32, + src: &ID3D12Resource, + src_desc: &D3D12_RESOURCE_DESC, + src_sub: u32, +) -> bool { + let mut src_fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut dst_fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut src_rows = 0u32; + let mut dst_rows = 0u32; + let mut src_total = 0u64; + let mut dst_total = 0u64; + dev.GetCopyableFootprints(src_desc, src_sub, 1, 0, Some(&mut src_fp), Some(&mut src_rows), None, Some(&mut src_total)); + dev.GetCopyableFootprints(dst_desc, dst_sub, 1, 0, Some(&mut dst_fp), Some(&mut dst_rows), None, Some(&mut dst_total)); + if src_total == 0 + || src_total == u64::MAX + || dst_total == 0 + || dst_total == u64::MAX + || src_rows != dst_rows + || !subresource_footprints_compatible(dst_desc.Format.0 as u32, &dst_fp.Footprint, src_desc.Format.0 as u32, &src_fp.Footprint) + { + return false; + } + let row_pitch = src_fp.Footprint.RowPitch.max(dst_fp.Footprint.RowPitch); + src_fp.Footprint.RowPitch = row_pitch; + dst_fp.Footprint.RowPitch = row_pitch; + let slices = (src_fp.Footprint.Depth as u64).max(1); + let needed = (row_pitch as u64).saturating_mul(src_rows as u64).saturating_mul(slices).max(src_total).max(dst_total); + let Some(scratch_raw) = list_x::acquire_scratch_for_copy(list, needed) else { + return false; + }; + let scratch_ptr = scratch_raw as *mut c_void; + let Some(scratch) = ID3D12Resource::from_raw_borrowed(&scratch_ptr) else { + return false; + }; + + list_x::transition(list, scratch_raw, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + { + let src_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(src.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: src_sub }, + }); + let buf_dst_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(scratch.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: src_fp }, + }); + list_x::pc_copy_texture_region(list, &buf_dst_loc.0, 0, 0, 0, &src_loc.0, std::ptr::null()); + } + + list_x::transition(list, scratch_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); + { + let buf_src_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(scratch.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: dst_fp }, + }); + let dst_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(dst.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: dst_sub }, + }); + list_x::pc_copy_texture_region(list, &dst_loc.0, 0, 0, 0, &buf_src_loc.0, std::ptr::null()); + } + + list_x::transition(list, scratch_raw, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + true +} + +unsafe fn sync_pair(list: *mut c_void, dev: &ID3D12Device, ty: D3D12_COMMAND_LIST_TYPE, pair: AliasPair, writer_state: u32) -> bool { + let w_ptr = pair.writer as *mut c_void; + let r_ptr = pair.reader as *mut c_void; + let (Some(writer_res), Some(reader_res)) = (ID3D12Resource::from_raw_borrowed(&w_ptr), ID3D12Resource::from_raw_borrowed(&r_ptr)) else { + return false; + }; + let target_srv = if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { STATE_SRV_ALL } else { STATE_SRV_NON_PIXEL }; + + // Determine reader's incoming state on this list. + let (reader_before, reader_after) = match pair.reader_owner { + Owner::PlacedSrv => { + let cur = LIST_STATES + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(list as usize))) + .and_then(|s| s.srv_states.get(&pair.reader).copied()) + .unwrap_or(STATE_COMMON); + (cur, target_srv) + } + Owner::TitlePlaced => { + let Some(st) = TABLE + .lock() + .unwrap() + .as_ref() + .and_then(|t| t.by_res.get(&pair.reader)) + .and_then(TrackedTex::uniform_state) + else { + return false; + }; + // On a compute list, never emit transitions referencing DIRECT-only states + // (`RENDER_TARGET`, `INDEX_BUFFER`, `VERTEX_AND_CONSTANT_BUFFER`, `DEPTH_*`, `PIXEL_SHADER_RESOURCE`). + if !state_valid_on_list(ty, st) { + return false; + } + (st, st) + } + Owner::PlacedUav => return false, + }; + + if writer_state != D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32 { + list_x::transition(list, pair.writer, D3D12_RESOURCE_STATES(writer_state as i32), D3D12_RESOURCE_STATE_COPY_SOURCE); + } + if reader_before != D3D12_RESOURCE_STATE_COPY_DEST.0 as u32 { + list_x::transition(list, pair.reader, D3D12_RESOURCE_STATES(reader_before as i32), D3D12_RESOURCE_STATE_COPY_DEST); + } + + let ok = if pair.buffer_through { + copy_all_subresources_through_buffer(list, dev, reader_res, writer_res) + } else { + list_x::pc_copy_resource(list, pair.reader, pair.writer); + true + }; + + if writer_state != D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32 { + list_x::transition(list, pair.writer, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATES(writer_state as i32)); + } + if reader_after != D3D12_RESOURCE_STATE_COPY_DEST.0 as u32 { + list_x::transition(list, pair.reader, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATES(reader_after as i32)); + } + + if pair.reader_owner == Owner::PlacedSrv { + let mut g = LIST_STATES.lock().unwrap(); + let ls = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); + ls.list_type = Some(ty); + ls.srv_states.insert(pair.reader, reader_after); + } + + if ok { + static SYNCED: AtomicU64 = AtomicU64::new(0); + let n = SYNCED.fetch_add(1, Ordering::Relaxed); + if n < 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: synced format-aliased texture {:#x} -> {:#x} ({}, {} syncs so far)", + pair.writer, + pair.reader, + if pair.buffer_through { "buffer-through" } else { "direct copy" }, + n + 1 + ); + } + } + ok +} + +/// Sync active placed-UAV -> format-aliased SRV pairs after a UAV barrier on `list`. +/// When `specific_targets` is `Some(targets)`, only sync pairs whose `writer` is in `targets`; +/// when `None` (global UAV barrier), deduplicate against `bind::activity()`. +pub(super) unsafe fn on_uav_barrier(list: *mut c_void, specific_targets: Option<&[usize]>) { + if ACTIVE_PLACED_UAV_PAIRS.load(Ordering::Relaxed) == 0 || list.is_null() { + return; + } + let Some(ty) = list_x::tracked_list_type(list) else { + return; + }; + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return; + } + let act = super::bind::activity(); + let dedup = dedup_enabled(); + // Skip duplicate back-to-back global UAV barriers when no draw or dispatch executed in between. + if specific_targets.is_none() { + let mut g = LIST_STATES.lock().unwrap(); + let ls = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); + if ls.last_activity == act && act != (0, 0) { + note_skipped_sync(); + return; + } + ls.last_activity = act; + ls.list_type = Some(ty); + } + let Some(dev) = list_x::device_of_list(list) else { + return; + }; + let dev_raw = dev.as_raw() as usize; + let mut skipped = 0usize; + let pairs: Vec<(AliasPair, Option, Option)> = { + let g = TABLE.lock().unwrap(); + match g.as_ref() { + Some(t) => t + .pairs + .iter() + .copied() + .filter(|p| { + if p.writer_owner != Owner::PlacedUav + || p.device != dev_raw + || !specific_targets.is_none_or(|targets| targets.contains(&p.writer)) + { + return false; + } + if dedup && act != (0, 0) { + if let Some(w) = t.by_res.get(&p.writer) { + if !w.dirty && w.last_sync_activity == Some(act) { + skipped += 1; + return false; + } + } + } + true + }) + .map(|p| (p, t.clone_internal(p.writer), t.clone_internal(p.reader))) + .collect(), + None => return, + } + }; + for _ in 0..skipped { + note_skipped_sync(); + } + let mut writer_ok: HashMap = HashMap::new(); + for (pair, _writer_pin, _reader_pin) in pairs { + let ok = sync_pair(list, &dev, ty, pair, STATE_UAV); + let entry = writer_ok.entry(pair.writer).or_insert(true); + *entry &= ok; + } + if !writer_ok.is_empty() { + let mut g = TABLE.lock().unwrap(); + if let Some(t) = g.as_mut() { + for (writer, all_ok) in writer_ok { + if all_ok { + if let Some(w) = t.by_res.get_mut(&writer) { + w.dirty = false; + w.last_sync_activity = Some(act); + } + } + } + } + } +} + +/// Sync format-aliased readers for title-owned writers that just transitioned out of write state. +pub(super) unsafe fn sync_title_writers(list: *mut c_void, writers: &[(usize, u32)]) { + if writers.is_empty() || ACTIVE_PAIRS.load(Ordering::Relaxed) == 0 || list.is_null() { + return; + } + let Some(ty) = list_x::tracked_list_type(list) else { + return; + }; + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return; + } + let Some(dev) = list_x::device_of_list(list) else { + return; + }; + let dev_raw = dev.as_raw() as usize; + let act = super::bind::activity(); + let mut seen = HashSet::new(); + for &(writer, state) in writers { + if !seen.insert(writer) { + continue; + } + let pairs: Vec<(AliasPair, Option, Option)> = { + let g = TABLE.lock().unwrap(); + match g.as_ref() { + Some(t) => t + .pairs + .iter() + .copied() + .filter(|p| p.writer == writer && p.device == dev_raw) + .map(|p| (p, t.clone_internal(p.writer), t.clone_internal(p.reader))) + .collect(), + None => continue, + } + }; + if pairs.is_empty() { + continue; + } + let mut all_ok = true; + for (pair, _writer_pin, _reader_pin) in pairs { + all_ok &= sync_pair(list, &dev, ty, pair, state); + } + if all_ok { + let mut g = TABLE.lock().unwrap(); + if let Some(w) = g.as_mut().and_then(|t| t.by_res.get_mut(&writer)) { + w.dirty = false; + w.last_sync_activity = Some(act); + } + } + } +} + +/// Return any `PlacedSrv` resources transitioned into read state on `list` back to `COMMON` +/// before `Close()`, keeping cross-queue state invariants clean. +pub(super) unsafe fn before_close(list: *mut c_void) { + if list.is_null() { + return; + } + let pending: Vec<(usize, u32)> = { + let mut g = LIST_STATES.lock().unwrap(); + match g.as_mut().and_then(|m| m.get_mut(&(list as usize))) { + Some(ls) if !ls.srv_states.is_empty() => ls.srv_states.drain().collect(), + _ => return, + } + }; + for (res, state) in pending { + if state != STATE_COMMON { + list_x::transition(list, res, D3D12_RESOURCE_STATES(state as i32), D3D12_RESOURCE_STATE_COMMON); + } + } +} + +/// Clear per-list sync state on `Reset` / `Create` / `Release`. +pub(super) fn list_reset(list: usize) { + if let Some(m) = LIST_STATES.lock().unwrap().as_mut() { + m.remove(&list); + } +} + +/// Intercept `CopyResource(dst, src)` between incompatible DXGI format families of equal texel +/// width (e.g. `R32_UINT` <-> `R9G9B9E5_SHAREDEXP`) and run it through an intermediate buffer. +/// Returns `true` if handled. +pub(super) unsafe fn try_copy_resource(list: *mut c_void, dst: usize, src: usize) -> bool { + if !enabled() || dst == 0 || src == 0 || dst == src { + return false; + } + let (dp, sp) = (dst as *mut c_void, src as *mut c_void); + let (Some(d), Some(s)) = (ID3D12Resource::from_raw_borrowed(&dp), ID3D12Resource::from_raw_borrowed(&sp)) else { + return false; + }; + let (dd, sd) = (d.GetDesc(), s.GetDesc()); + if dd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || sd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + return false; + } + if !needs_buffer_through(dd.Format.0 as u32, sd.Format.0 as u32) { + return false; + } + let Some(dev) = list_x::device_of_list(list) else { + return false; + }; + let ok = copy_all_subresources_through_buffer(list, &dev, d, s); + if ok { + mark_writer_dirty(dst); + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed); + if k < 8 || k.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: format-aliased CopyResource fmt {} -> fmt {} ({}x{}) copied via intermediate buffer ({} so far)", + sd.Format.0, + dd.Format.0, + dd.Width, + dd.Height, + k + 1 + ); + } + } + ok +} + +/// Intercept full-subresource texture-to-texture `CopyTextureRegion` between incompatible DXGI +/// format families of equal texel width and run it through an intermediate buffer. +/// Returns `true` if handled. +pub(super) unsafe fn try_copy_texture_region( + list: *mut c_void, + dst: &D3D12_TEXTURE_COPY_LOCATION, + x: u32, + y: u32, + z: u32, + src: &D3D12_TEXTURE_COPY_LOCATION, + bx: *const D3D12_BOX, +) -> bool { + if !enabled() + || dst.Type != D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX + || src.Type != D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX + || x != 0 + || y != 0 + || z != 0 + || !bx.is_null() + { + return false; + } + let (Some(d), Some(s)) = (dst.pResource.as_ref(), src.pResource.as_ref()) else { + return false; + }; + let (dd, sd) = (d.GetDesc(), s.GetDesc()); + if dd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || sd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + return false; + } + if !needs_buffer_through(dd.Format.0 as u32, sd.Format.0 as u32) { + return false; + } + let Some(dev) = list_x::device_of_list(list) else { + return false; + }; + let ok = copy_one_subresource_through_buffer( + list, + &dev, + d, + &dd, + dst.Anonymous.SubresourceIndex, + s, + &sd, + src.Anonymous.SubresourceIndex, + ); + if ok { + mark_writer_dirty(d.as_raw() as usize); + } + ok +} + +#[cfg(test)] +mod tests { + use super::*; + + fn shape(fmt: u32, w: u64, h: u32, d: u16, mips: u16) -> TexShape { + TexShape { + dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D.0, + width: w, + height: h, + depth_or_array: d, + mip_levels: mips, + format: fmt, + samples: 1, + } + } + + #[test] + fn r32_uint_and_r9g9b9e5_alias_needs_buffer_through() { + assert!(needs_buffer_through(67, 42)); // R9G9B9E5_SHAREDEXP vs R32_UINT + assert!(needs_buffer_through(67, 39)); // R9G9B9E5_SHAREDEXP vs R32_TYPELESS + assert!(!needs_buffer_through(42, 39)); // R32_UINT vs R32_TYPELESS (same family) + assert!(!needs_buffer_through(28, 27)); // R8G8B8A8_UNORM vs R8G8B8A8_TYPELESS + + let s_uav = shape(39, 128, 128, 6, 4); + let s_srv = shape(67, 128, 128, 6, 4); + assert!(can_copy_through_buffer(&s_srv, &s_uav)); + + // 3D volumetric fog froxel texture: R32_UINT UAV -> R9G9B9E5_SHAREDEXP SRV + let fog_uav = TexShape { dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D.0, ..shape(42, 160, 90, 64, 1) }; + let fog_srv = TexShape { dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D.0, ..shape(67, 160, 90, 64, 1) }; + assert!(can_copy_through_buffer(&fog_srv, &fog_uav)); + assert_eq!(fog_srv.subresource_count(), 1); + + // BC7 (16 B per 4x4 block) <-> R32G32B32A32_UINT (16 B per texel, 1/4 width & height) + let bc7 = shape(98, 256, 128, 1, 1); + let u32x4 = shape(3, 64, 32, 1, 1); + assert!(can_copy_through_buffer(&bc7, &u32x4)); + assert!(can_copy_through_buffer(&u32x4, &bc7)); + + // Mismatched dimensions or bpp rejected + assert!(!can_copy_through_buffer(&shape(67, 64, 64, 1, 1), &shape(42, 128, 128, 1, 1))); + assert!(!can_copy_through_buffer(&shape(10, 128, 128, 1, 1), &shape(42, 128, 128, 1, 1))); + } + + #[test] + fn placed_uav_and_srv_descs_are_sanitized() { + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + x[0x20..0x24].copy_from_slice(&67u32.to_le_bytes()); // R9G9B9E5_SHAREDEXP + x[0x30..0x34].copy_from_slice(&0x30_0005u32.to_le_bytes()); // RTV | UAV + console bits + + // Placed UAV with R32_UINT view over R9G9B9E5 desc -> R32_TYPELESS + ALLOW_UNORDERED_ACCESS (no RTV) + let uav = prepare_placed_uav_desc(&x, 42); + let uav_fmt = u32::from_le_bytes(uav[0x20..0x24].try_into().unwrap()); + let uav_flags = u32::from_le_bytes(uav[0x30..0x34].try_into().unwrap()); + assert_eq!(uav_fmt, 39, "R32_UINT UAV over R9G9B9E5 must become R32_TYPELESS, not R11G11B10_FLOAT"); + assert!(uav_flags & FLAG_UAV != 0 && uav_flags & FLAG_RENDER_TARGET == 0); + + // Placed SRV with R9G9B9E5 view -> strips RTV|UAV so pc_resource_desc keeps format 67! + let srv = prepare_placed_srv_desc(&x, 67); + let srv_pc = super::super::device_x::pc_resource_desc(&srv); + let srv_fmt = u32::from_le_bytes(srv_pc[0x20..0x24].try_into().unwrap()); + let srv_flags = u32::from_le_bytes(srv_pc[0x30..0x34].try_into().unwrap()); + assert_eq!(srv_fmt, 67, "placed SRV must stay R9G9B9E5_SHAREDEXP"); + assert_eq!(srv_flags & (FLAG_RENDER_TARGET | FLAG_UAV), 0); + } + + #[test] + fn placed_descs_ignore_the_padding_after_dimension() { + // bytes 0x04..0x08 are the padding between `Dimension` and `Alignment`; the title leaves + // stack bytes there, and a different value must not make a second key for the same view + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + x[0x10..0x18].copy_from_slice(&256u64.to_le_bytes()); + x[0x18..0x1C].copy_from_slice(&256u32.to_le_bytes()); + x[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); // R8G8B8A8_UNORM + let mut garbage = x; + garbage[0x04..0x08].copy_from_slice(&[0xd8, 0x7e, 0x3f, 0x01]); + assert_eq!(prepare_placed_srv_desc(&garbage, 28), prepare_placed_srv_desc(&x, 28)); + assert_eq!(prepare_placed_uav_desc(&garbage, 28), prepare_placed_uav_desc(&x, 28)); + assert_eq!(prepare_placed_srv_desc(&garbage, 28)[0x04..0x08], [0u8; 4]); + } + + #[test] + fn alias_table_links_in_both_creation_orders() { + let mut t = AliasTable::new(); + let va = 0x2_0000_0000usize; + let uav_shape = shape(39, 64, 64, 1, 1); + let srv_shape = shape(67, 64, 64, 1, 1); + + // Order 1: SRV created first, placed UAV created second -> links and marks SRV gpu_written + let m1 = t.insert(0x100, TrackedTex::new(1, va, srv_shape, Owner::TitlePlaced, 0, false)); + assert!(m1.is_empty()); + assert!(t.pairs.is_empty()); + + let m2 = t.insert(0x200, TrackedTex::new(1, va, uav_shape, Owner::PlacedUav, STATE_UAV, true)); + assert_eq!(m2, vec![0x100]); + assert_eq!(t.pairs.len(), 1); + assert!(t.pairs[0].buffer_through); + assert_eq!(t.placed_uav_pairs, 1); + + // Order 2: second SRV created after UAV -> links immediately and marks itself gpu_written + let m3 = t.insert(0x300, TrackedTex::new(1, va, srv_shape, Owner::PlacedSrv, 0, false)); + assert_eq!(m3, vec![0x300]); + assert_eq!(t.pairs.len(), 2); + + // Removing the reader cleans up its pair + t.remove(0x100); + assert_eq!(t.pairs.len(), 1); + assert_eq!(t.pairs[0].reader, 0x300); + + // Removing the writer cleans up remaining pairs + t.remove(0x200); + assert!(t.pairs.is_empty()); + assert_eq!(t.placed_uav_pairs, 0); + + // Compute-list state validation rejects RENDER_TARGET (0x4), INDEX_BUFFER (0x2), VCB (0x1), + // DEPTH_WRITE (0x10), PIXEL_SHADER_RESOURCE (0x80), while allowing COMMON/UAV/NON_PIXEL_SRV/COPY. + assert!(state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, STATE_COMMON)); + assert!(state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, STATE_UAV)); + assert!(state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, STATE_SRV_NON_PIXEL)); + assert!(!state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, STATE_RENDER_TARGET)); + assert!(!state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, 0x1)); + assert!(!state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, 0x2)); + assert!(!state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, STATE_SRV_ALL)); + assert!(state_valid_on_list(D3D12_COMMAND_LIST_TYPE_DIRECT, STATE_RENDER_TARGET)); + + // Subresource footprint compatibility rejects mismatched element byte widths even with equal RowPitch + let fp = |w, h, d| D3D12_SUBRESOURCE_FOOTPRINT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(0), + Width: w, + Height: h, + Depth: d, + RowPitch: 256, + }; + assert!(subresource_footprints_compatible(67, &fp(32, 32, 1), 42, &fp(32, 32, 1))); + assert!(!subresource_footprints_compatible(10, &fp(32, 32, 1), 42, &fp(32, 32, 1)), "8 Bpp vs 4 Bpp must be rejected"); + assert!(subresource_footprints_compatible(98, &fp(64, 64, 1), 3, &fp(16, 16, 1)), "BC7 64x64 == R32G32B32A32 16x16"); + } + + #[test] + fn enhanced_common_to_read_skips_unchanged_writer_and_rearms_on_write() { + let dev = 0x7A00_0001usize; + let va = 0x7A00_0000_0000usize; + let writer = 0x7A00_1001usize; + let reader = 0x7A00_1002usize; + let reader2 = 0x7A00_1003usize; + let uav_shape = shape(42, 64, 64, 1, 1); // R32_UINT + let srv_shape = shape(67, 64, 64, 1, 1); // R9G9B9E5_SHAREDEXP + + { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + t.insert(writer, TrackedTex::new(dev, va, uav_shape, Owner::TitlePlaced, STATE_COMMON, true)); + t.insert(reader, TrackedTex::new(dev, va, srv_shape, Owner::TitlePlaced, STATE_COMMON, false)); + } + + let mk_group = |tb: &D3D12_TEXTURE_BARRIER| D3D12_BARRIER_GROUP { + Type: D3D12_BARRIER_TYPE_TEXTURE, + NumBarriers: 1, + Anonymous: D3D12_BARRIER_GROUP_0 { pTextureBarriers: tb as *const _ }, + }; + let mk_tb = |ab: D3D12_BARRIER_ACCESS, aa: D3D12_BARRIER_ACCESS, lb: D3D12_BARRIER_LAYOUT, la: D3D12_BARRIER_LAYOUT, flags: D3D12_TEXTURE_BARRIER_FLAGS| -> D3D12_TEXTURE_BARRIER { + D3D12_TEXTURE_BARRIER { + SyncBefore: D3D12_BARRIER_SYNC_ALL, + SyncAfter: D3D12_BARRIER_SYNC_ALL, + AccessBefore: ab, + AccessAfter: aa, + LayoutBefore: lb, + LayoutAfter: la, + pResource: unsafe { std::mem::transmute_copy(&writer) }, + Subresources: D3D12_BARRIER_SUBRESOURCE_RANGE::default(), + Flags: flags, + } + }; + + // 1. Fresh writer starts dirty: COMMON -> SRV triggers initial sync. + let tb_c2r = mk_tb( + D3D12_BARRIER_ACCESS_COMMON, + D3D12_BARRIER_ACCESS_SHADER_RESOURCE, + D3D12_BARRIER_LAYOUT_COMMON, + D3D12_BARRIER_LAYOUT_SHADER_RESOURCE, + D3D12_TEXTURE_BARRIER_FLAG_NONE, + ); + let grp = mk_group(&tb_c2r); + let mut out = Vec::new(); + unsafe { filter_enhanced_barriers(1, &grp as *const _ as *const c_void, &mut out) }; + assert_eq!(out, vec![(writer, STATE_COMMON)]); + + // Simulate completed sync clearing dirty flag. + TABLE.lock().unwrap().as_mut().unwrap().by_res.get_mut(&writer).unwrap().dirty = false; + + // 2. Second COMMON -> SRV with no intervening write must be skipped. + out.clear(); + unsafe { filter_enhanced_barriers(1, &grp as *const _ as *const c_void, &mut out) }; + assert!(out.is_empty(), "unchanged writer must skip redundant COMMON -> SRV copy"); + + // 3. Entering UAV layout (`COMMON -> UAV`) re-arms dirty without syncing yet. + let tb_c2u = mk_tb( + D3D12_BARRIER_ACCESS_COMMON, + D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + D3D12_BARRIER_LAYOUT_COMMON, + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + D3D12_TEXTURE_BARRIER_FLAG_NONE, + ); + let grp_u = mk_group(&tb_c2u); + unsafe { filter_enhanced_barriers(1, &grp_u as *const _ as *const c_void, &mut out) }; + assert!(out.is_empty()); + assert!(TABLE.lock().unwrap().as_ref().unwrap().by_res.get(&writer).unwrap().dirty); + + // 4. Subsequent COMMON -> SRV now syncs again. + unsafe { filter_enhanced_barriers(1, &grp as *const _ as *const c_void, &mut out) }; + assert_eq!(out, vec![(writer, STATE_COMMON)]); + + // 5. Linking a new format-aliased reader re-arms dirty on the writer. + TABLE.lock().unwrap().as_mut().unwrap().by_res.get_mut(&writer).unwrap().dirty = false; + TABLE.lock().unwrap().as_mut().unwrap().insert(reader2, TrackedTex::new(dev, va, srv_shape, Owner::TitlePlaced, STATE_COMMON, false)); + assert!(TABLE.lock().unwrap().as_ref().unwrap().by_res.get(&writer).unwrap().dirty); + + // Prevent ManuallyDrop::drop on synthetic pointer in tb_c2r / tb_c2u (already ManuallyDrop) + // and clean up test entries from global TABLE. + forget(reader2); + forget(reader); + forget(writer); + } + + #[test] + fn cache_insert_or_clone_returns_winner_and_keeps_handle_alive_across_eviction() { + use std::sync::Arc; + + let mut cache: HashMap> = HashMap::new(); + let first = Arc::new(111u32); + let second = Arc::new(222u32); + + // Initial insert: map and caller both hold a reference to `first`. + let (h1, loser1) = cache_insert_or_clone(&mut cache, 0x1000, Arc::clone(&first)); + assert!(loser1.is_none()); + assert_eq!(*h1, 111); + assert_eq!(Arc::strong_count(&first), 3); // local `first` + cache + `h1` + + // Concurrent miss race: returns a handle to the winning `first` and hands `second` + // back to the caller so it can be dropped outside the lock without UAF or deadlock. + let (h2, loser2) = cache_insert_or_clone(&mut cache, 0x1000, Arc::clone(&second)); + assert_eq!(*h2, 111, "concurrent race must return the cached winner, not the loser"); + assert!(Arc::ptr_eq(&h2, &first)); + let loser = loser2.expect("duplicate loser must be returned for outside-lock drop"); + assert!(Arc::ptr_eq(&loser, &second)); + assert_eq!(Arc::strong_count(&second), 2); + drop(loser); + assert_eq!(Arc::strong_count(&second), 1); + + // Concurrent eviction while `h1` / `h2` are in use keeps the resource alive until dropped. + drop(first); + let evicted = cache.remove(&0x1000).unwrap(); + drop(evicted); + assert_eq!(*h1, 111); + assert_eq!(*h2, 111); + assert_eq!(Arc::strong_count(&h1), 2); + drop(h1); + assert_eq!(Arc::strong_count(&h2), 1); + drop(h2); + } +} diff --git a/crates/xcl/src/hle/d3d12x/gpu_awake.rs b/crates/xcl/src/hle/d3d12x/gpu_awake.rs index 141385f0d8..6bb0f5253d 100644 --- a/crates/xcl/src/hle/d3d12x/gpu_awake.rs +++ b/crates/xcl/src/hle/d3d12x/gpu_awake.rs @@ -285,6 +285,7 @@ unsafe fn init_state(device: &ID3D12Device) -> Result { .map_err(|e| format!("CreateCommandList(COMPUTE) failed: {e}"))?; list.SetComputeRootSignature(&root_sig); list.SetPipelineState(&pso); + super::real::note_root_view(list.as_raw() as usize, 0, uav_va); list.SetComputeRootUnorderedAccessView(0, uav_va); list.Dispatch(1, 1, 1); list.Close().map_err(|e| format!("CommandList::Close failed: {e}"))?; diff --git a/crates/xcl/src/hle/d3d12x/indexed.rs b/crates/xcl/src/hle/d3d12x/indexed.rs new file mode 100644 index 0000000000..99dcac7cf2 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/indexed.rs @@ -0,0 +1,430 @@ +//! Textures a draw picks by index. A console shader that indexes the view heap itself +//! (`ResourceDescriptorHeap[k]`; root signatures with CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) loads +//! the T# in slot k of the view heap its list set (`bind::set_heaps`: the heap's 32-bit console +//! address) and samples the PC view that T#'s word 0 names in the shared heap +//! (`console_heap::named_by_index`). k itself is not an index of the shared heap: slot k of a +//! heap has SRV `2k` of the heap's own PC heap, or `first + 2 (k mod PAGE_SLOTS)` where the +//! slot's page has its place in the shared heap, so the descriptor at shared index k is another +//! slot's view, of another texture. Where k comes from is the title's (root constants, a constant +//! buffer); every word of those is a candidate (`indices`). +//! +//! `XCL_INDEX_BY_SLOT` (on by default): the indices a bake's draw picks (`bind::uncover_indexed`) +//! name textures through the slots of the bound view heap. `0`: through the shared heap's +//! descriptor at that index, as before – which made other textures active again and left the +//! bake's own shadowed sources as they were. +//! +//! `XCL_UNCOVER_INDEXED=1` (off by default): every graphics draw's shadowed textures picked by +//! index are made active again, as a bake's are (`bind::uncover_indexed`). +//! +//! `XCL_TRACE_INDEXED=1` (a diagnostic): each texture a graphics draw picks by index is looked at +//! once a frame, before the draw's own fixes: how XCL keeps it (`title_textures::kept`), which of +//! the levels its T# names have no video memory pages (`vram::levels_with_pages`: a level that +//! had no texels when it was last uploaded reads as zeros), and whether the T# in the slot is the +//! one XCL wrote for the view (`note_made`) or one the title changed (a MIN_LOD or base level of +//! its own, which a translated shader's sample does not apply: the PC view keeps the levels it +//! was made with). A texture that is shadowed, not uploaded yet, has levels without pages in its +//! view, or has a T# that is not XCL's is logged with the frame and the pipeline, once per state; +//! every 2 s a line counts them. + +use std::collections::{HashMap, HashSet}; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use windows::Win32::Graphics::Direct3D12::*; + +use super::console_list::{Layout, Param}; + +/// indices taken from one draw at most +const INDICES_MOST: usize = 4096; +/// lines of textures logged at most +const LINES_MOST: u64 = 3000; + +fn switch(name: &str, default: bool) -> bool { + std::env::var(name).map_or(default, |v| v.trim() != "0") +} + +/// `XCL_INDEX_BY_SLOT` +pub(super) fn by_slot() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| switch("XCL_INDEX_BY_SLOT", true)) +} + +/// `XCL_UNCOVER_INDEXED` +pub(super) fn uncover_all() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| switch("XCL_UNCOVER_INDEXED", false)) +} + +/// `XCL_TRACE_INDEXED` +pub(super) fn trace_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TRACE_INDEXED").is_ok_and(|v| v.trim() == "1")) +} + +/// The words a draw's arguments hold that may be indices: its root constants (64 a parameter), +/// its root CBVs and the CBVs in the first 16 slots of its tables (2 KiB each). +pub(super) unsafe fn indices(layout: &Layout, args: &[u8], u: &crate::gpu::uma::Uma) -> Vec { + let word = |at: usize| args.get(at..at + 4).map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap())); + let mut out: Vec = Vec::new(); + let mut push = |v: u32| { + if v != 0 && v < 4 << 20 && out.len() < INDICES_MOST { + out.push(v); + } + }; + for p in &layout.params { + match *p { + Param::Constants { at, count } => (0..count.min(64) as usize).for_each(|k| push(word(at as usize + 4 * k))), + Param::Descriptor { at } => { + let va = (word(at as usize) as u64 | (word(at as usize + 4) as u64) << 32) as usize; + super::ambient::scan_cbv_indices(va, 2048, &mut push); + } + Param::Table { at } => { + let offset = word(at as usize) as usize; + if offset == 0 { + continue; + } + let mut table = [0u8; 16 * 32]; + super::title_textures::read_committed_into(u.base() + offset, &mut table); + for slot in table.chunks_exact(32) { + let w: [u32; 4] = std::array::from_fn(|k| u32::from_le_bytes(slot[4 * k..4 * k + 4].try_into().unwrap())); + if let Some((va, len)) = super::ambient::decode_cbv_vsharp(w) { + super::ambient::scan_cbv_indices(va, len, &mut push); + } + } + } + } + } + out.sort_unstable(); + out.dedup(); + out +} + +/// A texture index `k` names: the T# in slot k of the view heap, and the PC resource its word 0 +/// names in the shared heap. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Named { + pub k: u32, + pub words: [u32; 8], + pub res: usize, +} + +/// The textures `indices` name through the slots of the view heap at console address +/// `view_heap`: `words_at` reads the slot at a console address (None: not a slot), `named` the +/// resource of a shared-heap index (0: none). A slot that holds no image T# in XCL's form +/// (`desc::xcl_image_words`), or whose T# names nothing, names no texture. One entry a resource. +pub(super) fn resolve(indices: &[u32], view_heap: u32, words_at: impl Fn(u32) -> Option<[u32; 8]>, named: impl Fn(u32) -> usize) -> Vec { + let mut out: Vec = Vec::new(); + if view_heap == 0 { + return out; + } + for &k in indices { + let Some(at) = k.checked_mul(super::console_heap::SLOT).and_then(|o| view_heap.checked_add(o)) else { continue }; + let Some(words) = words_at(at) else { continue }; + if words[3] >> 28 < 8 || words[1] & 0xFF != 0 { + continue; + } + let res = named(words[0]); + if res == 0 || res == super::console_heap::GONE || out.iter().any(|n| n.res == res) { + continue; + } + out.push(Named { k, words, res }); + } + out +} + +/// The textures `indices` name (`resolve`), in the bound view heap `view_heap`. +pub(super) fn named(indices: &[u32], view_heap: u32) -> Vec { + resolve(indices, view_heap, super::console_heap::words_at, super::console_heap::named_by_index) +} + +/// The resources a bake's draw picks by index: through the view heap's slots (`by_slot`), or as +/// the shared heap's descriptors at those indices (before). +pub(super) fn resources(indices: &[u32], view_heap: u32) -> Vec { + pick(indices, view_heap, by_slot(), super::console_heap::words_at, super::console_heap::named_by_index) +} + +/// `resources` with the slots and names given (`resolve`). +fn pick(indices: &[u32], view_heap: u32, by_slot: bool, words_at: impl Fn(u32) -> Option<[u32; 8]>, named: impl Fn(u32) -> usize) -> Vec { + if by_slot { + return resolve(indices, view_heap, words_at, named).into_iter().map(|n| n.res).collect(); + } + indices.iter().map(|&i| named(i)).filter(|&r| r != 0 && r != super::console_heap::GONE).collect() +} + +// --------------------------------------------------------------------------------------- +// XCL_TRACE_INDEXED +// --------------------------------------------------------------------------------------- + +/// The T# XCL wrote for the SRV at shared-heap index i, and its view's ResourceMinLODClamp. +static MADE: Mutex>> = Mutex::new(None); + +/// XCL wrote `words` for the SRV at shared-heap index `index`, made with `desc` (`XCL_TRACE_INDEXED`). +pub(super) fn note_made(index: u32, words: &[u32; 8], desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) { + if !trace_on() { + return; + } + let clamp = desc.map_or(0.0, view_clamp); + MADE.lock().unwrap().get_or_insert_with(HashMap::new).insert(index, (*words, clamp)); +} + +/// A texture view's ResourceMinLODClamp. +fn view_clamp(v: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> f32 { + // SAFETY: the union member the view dimension names + unsafe { + let a = &v.Anonymous; + match v.ViewDimension { + D3D12_SRV_DIMENSION_TEXTURE1D => a.Texture1D.ResourceMinLODClamp, + D3D12_SRV_DIMENSION_TEXTURE1DARRAY => a.Texture1DArray.ResourceMinLODClamp, + D3D12_SRV_DIMENSION_TEXTURE2D => a.Texture2D.ResourceMinLODClamp, + D3D12_SRV_DIMENSION_TEXTURE2DARRAY => a.Texture2DArray.ResourceMinLODClamp, + D3D12_SRV_DIMENSION_TEXTURE3D => a.Texture3D.ResourceMinLODClamp, + D3D12_SRV_DIMENSION_TEXTURECUBE => a.TextureCube.ResourceMinLODClamp, + D3D12_SRV_DIMENSION_TEXTURECUBEARRAY => a.TextureCubeArray.ResourceMinLODClamp, + _ => 0.0, + } + } +} + +/// What the levels a view names have: those without pages, and of them the ones the PC view +/// samples and the ones the T# in the slot leaves out. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub(super) struct Holes { + /// levels of the T#'s range [base, last] without pages + pub none: Vec, + /// of them, those the PC view can sample (from its first level and its clamp on) + pub sampled: Vec, + /// of `sampled`, those the T# in the slot leaves out (its base level or its MIN_LOD): the + /// title keeps the shader off them, the PC view does not + pub left_out_by_tsharp: Vec, +} + +/// `pages`: whether each level has pages; `now`: (base level, last level, MIN_LOD) of the T# in +/// the slot; `view`: (first level, ResourceMinLODClamp) of the PC view. +pub(super) fn holes(pages: &[bool], now: (u32, u32, f32), view: (u32, f32)) -> Holes { + let (base, last, min_lod) = now; + let from_view = view.0.max(view.1.max(0.0).floor() as u32); + let from_tsharp = base.max(min_lod.max(0.0).floor() as u32); + let none: Vec = (base.min(view.0)..=last).filter(|&l| pages.get(l as usize).is_some_and(|&p| !p)).collect(); + let sampled: Vec = none.iter().copied().filter(|&l| l >= from_view).collect(); + let left_out_by_tsharp = sampled.iter().copied().filter(|&l| l < from_tsharp).collect(); + Holes { none, sampled, left_out_by_tsharp } +} + +#[derive(Default)] +struct Trace { + frame: u64, + /// resources looked at in this frame + seen: HashSet, + /// (view heap, index) → what it named in this frame + slots: HashMap<(u32, u32), Option>, + /// resource → the state last logged + logged: HashMap, + lines: u64, + window: Window, +} + +#[derive(Default)] +struct Window { + since: Option, + first_frame: u64, + draws: u64, + named: u64, + looked: u64, + shadowed: u64, + pending: u64, + holes: u64, + sampled: u64, + left_out: u64, + rewritten: u64, +} + +static TRACE: Mutex> = Mutex::new(None); + +/// `XCL_TRACE_INDEXED`: a graphics draw on `list` with pipeline `pso` (`bake`: a bake's) picks the +/// textures `indices` name in the view heap at `view_heap`. +pub(super) unsafe fn trace_draw(list: *mut std::ffi::c_void, pso: usize, indices: &[u32], view_heap: u32, bake: bool) { + let (p, b) = super::present::counters(); + let frame = p.max(b); + let mut g = TRACE.lock().unwrap(); + let t = g.get_or_insert_with(Trace::default); + if t.frame != frame { + t.frame = frame; + t.seen.clear(); + t.slots.clear(); + } + // (a slot is read once a frame: draws share their materials' indices) + let mut named: Vec = Vec::new(); + for &k in indices { + let n = *t.slots.entry((view_heap, k)).or_insert_with(|| self::named(&[k], view_heap).first().copied()); + if let Some(n) = n.filter(|n| !named.iter().any(|m| m.res == n.res)) { + named.push(n); + } + } + let w = &mut t.window; + if w.since.is_none() { + *w = Window { since: Some(Instant::now()), first_frame: frame, ..Window::default() }; + } + w.draws += 1; + w.named += named.len() as u64; + let made = MADE.lock().unwrap(); + // the draw's render targets (their resources where known), for a logged line + let mut targets: Option> = None; + for n in named { + if !t.seen.insert(n.res) { + continue; + } + let w = &mut t.window; + w.looked += 1; + let Some(img) = crate::gpu::desc::image(&n.words) else { continue }; + let kept = super::title_textures::kept(n.res); + let pages = super::vram::levels_with_pages(n.res); + let mine = made.as_ref().and_then(|m| m.get(&n.words[0])).copied(); + let rewritten = mine.is_some_and(|(m, _)| m[1..] != n.words[1..]); + let view = mine.and_then(|(m, c)| crate::gpu::desc::image(&m).map(|i| (i.base_level, c))).unwrap_or((img.base_level, 0.0)); + let h = pages.as_deref().map(|p| holes(p, (img.base_level, img.last_level, img.min_lod), view)).unwrap_or_default(); + let shadowed = kept.is_some_and(|k| !k.active); + let pending = kept.is_some_and(|k| k.pending); + w.shadowed += shadowed as u64; + w.pending += pending as u64; + w.holes += !h.none.is_empty() as u64; + w.sampled += !h.sampled.is_empty() as u64; + w.left_out += !h.left_out_by_tsharp.is_empty() as u64; + w.rewritten += rewritten as u64; + if !(shadowed || pending || !h.sampled.is_empty() || rewritten) { + t.logged.remove(&n.res); + continue; + } + let state = { + use std::hash::{Hash, Hasher}; + let mut s = std::collections::hash_map::DefaultHasher::new(); + (kept, &h, rewritten, n.words, pages.as_deref()).hash(&mut s); + s.finish() + }; + if t.logged.insert(n.res, state) == Some(state) || t.lines >= LINES_MOST { + continue; + } + t.lines += 1; + let how = kept.map_or("not a title texture".to_string(), |k| { + format!( + "title texture at {:#x}: {}{}{}{}{}{}", + k.va, + if k.active { "active" } else if k.displaced { "shadowed (displaced)" } else { "shadowed" }, + if k.pending { ", not uploaded yet" } else { "" }, + if k.gpu_written { ", GPU-written" } else { "" }, + if k.placed { ", placed on shared pages" } else { "" }, + if k.unmapped { ", tiles unmapped" } else { "" }, + if k.paged { ", read where the title's page mappings put its pages" } else { "" }, + ) + }); + let levels = pages.as_deref().map_or("all levels have pages".to_string(), |p| { + format!( + "levels with pages {}, without {:?}; of the view's: without {:?}, sampled by the PC view {:?}, left out by the T# {:?}", + p.iter().map(|&x| if x { '1' } else { '0' }).collect::(), + (0..p.len() as u32).filter(|&l| !p[l as usize]).collect::>(), + h.none, + h.sampled, + h.left_out_by_tsharp + ) + }); + let tsharp = match mine { + Some((m, c)) if rewritten => { + let mi = crate::gpu::desc::image(&m); + format!( + "T# not as XCL made it: made levels {:?} clamp {c}, now levels {}..{} MIN_LOD {} (words made {:08x?}, now {:08x?})", + mi.map(|i| (i.base_level, i.last_level)), + img.base_level, + img.last_level, + img.min_lod, + m, + n.words + ) + } + Some((_, c)) => format!("T# as XCL made it (view clamp {c})"), + None => format!("T# levels {}..{} MIN_LOD {} (made before the trace)", img.base_level, img.last_level, img.min_lod), + }; + let targets = targets.get_or_insert_with(|| super::list_x::bound_render_targets(list).into_iter().map(|h| super::present::rtv_resource(h).unwrap_or(h)).collect()); + crate::xlog_info!( + "D3D12.X: indexed texture {:#x} ({}x{}, format {}, {} levels) by slot {} in frame {frame}, pipeline {pso:#x}{}, targets {targets:#x?}: {how}; {levels}; {tsharp}", + n.res, + img.width, + img.height, + img.format, + img.max_mip + 1, + n.k, + if bake { " (a bake's)" } else { "" } + ); + } + drop(made); + let w = &mut t.window; + if w.since.is_some_and(|s| s.elapsed() >= Duration::from_secs(2)) { + crate::xlog_info!( + "D3D12.X: indexed textures (frames {}..{frame}): {} draws picked {} textures by index, {} looked at (once a frame each): {} shadowed (show what they held), {} not uploaded yet, {} with levels in their T# without pages, {} of them sampled by the PC view, {} of those left out by the T# (its base level / MIN_LOD); {} T#s not as XCL made them; {} lines so far", + w.first_frame, + w.draws, + w.named, + w.looked, + w.shadowed, + w.pending, + w.holes, + w.sampled, + w.left_out, + w.rewritten, + t.lines + ); + t.window = Window::default(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// An image T# in XCL's form naming shared-heap SRV `index`. + fn tsharp(index: u32) -> [u32; 8] { + crate::gpu::desc::xcl_image_for_view(index, 1, crate::gpu::desc::ImageType::D2, 256, 256, 1, 9) + } + + /// `ResourceDescriptorHeap[k]` reads slot k of the bound view heap: the index names the + /// texture whose T# lies there, not the shared heap's descriptor k (another slot's: slot k + /// of a heap has SRV `2k` or a place on its page in the shared heap). + #[test] + fn an_index_names_the_texture_of_its_slot_in_the_view_heap() { + const HEAP: u32 = 0xb8a0_0000; + // slots 5 and 7 of the heap hold T#s naming shared SRVs 1010 and 1014 (page at 1000) + let slots: HashMap = [(HEAP + 5 * 32, tsharp(1010)), (HEAP + 7 * 32, tsharp(1014)), (HEAP + 9 * 32, [0x1234, 0, 0, 0, 0, 0, 0, 0])].into(); + let names: HashMap = [(1010, 0xA), (1014, 0xB), (5, 0xBAD5), (7, 0xBAD7), (9, 0xBAD9)].into(); + let words_at = |at: u32| slots.get(&at).copied(); + let named = |i: u32| names.get(&i).copied().unwrap_or(0); + // slot 9 holds a buffer V#, slot 11 nothing: no textures + assert_eq!(pick(&[5, 7, 9, 11], HEAP, true, words_at, named), vec![0xA, 0xB]); + // (the shared heap's descriptors at those indices are other slots' textures) + assert_eq!(pick(&[5, 7, 9, 11], HEAP, false, words_at, named), vec![0xBAD5, 0xBAD7, 0xBAD9]); + // the same texture twice is one; no heap bound: none + assert_eq!(resolve(&[5, 5], HEAP, words_at, named).len(), 1); + assert!(resolve(&[5], 0, words_at, named).is_empty()); + // an index whose slot would lie past 4 GiB names nothing + assert!(resolve(&[u32::MAX / 16], HEAP, words_at, named).is_empty()); + } + + /// The levels of a T# without pages: those the PC view samples, and of them those the T# in + /// the slot leaves out where the title changed its base level or MIN_LOD. + #[test] + fn levels_without_pages_are_told_against_the_view_and_the_tsharp() { + // levels 0 and 1 have no pages + let pages = [false, false, true, true, true]; + // T# and view as made: levels 0..4, both sampled + let h = holes(&pages, (0, 4, 0.0), (0, 0.0)); + assert_eq!((h.none.clone(), h.sampled.clone(), h.left_out_by_tsharp.clone()), (vec![0, 1], vec![0, 1], vec![])); + // the title's T# says MIN_LOD 2: the shader would not go below level 2, the PC view does + let h = holes(&pages, (0, 4, 2.0), (0, 0.0)); + assert_eq!((h.sampled.clone(), h.left_out_by_tsharp.clone()), (vec![0, 1], vec![0, 1])); + // its base level 1: only level 0 left out by it + let h = holes(&pages, (1, 4, 0.0), (0, 0.0)); + assert_eq!((h.none.clone(), h.sampled.clone(), h.left_out_by_tsharp.clone()), (vec![0, 1], vec![0, 1], vec![0])); + // a PC view clamped at 2 samples none of them + let h = holes(&pages, (0, 4, 0.0), (0, 2.0)); + assert_eq!((h.none, h.sampled), (vec![0, 1], vec![])); + // all levels with pages: nothing + assert_eq!(holes(&[true; 5], (0, 4, 0.0), (0, 0.0)), Holes::default()); + } +} diff --git a/crates/xcl/src/hle/d3d12x/indirect_guard.rs b/crates/xcl/src/hle/d3d12x/indirect_guard.rs index 7b9f873689..d0c81d8f8b 100644 --- a/crates/xcl/src/hle/d3d12x/indirect_guard.rs +++ b/crates/xcl/src/hle/d3d12x/indirect_guard.rs @@ -259,6 +259,8 @@ unsafe fn make(dev: &ID3D12Device, dxil: &Result, String>) -> Result Result { let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, @@ -369,9 +371,13 @@ pub(super) unsafe fn check(list: *mut c_void, pso: usize, sig: usize, max: u32, let at = title.map_or(va, |t| t as u64); let constants = [max_groups(), slot, id as u32, (id >> 32) as u32, at as u32, (at >> 32) as u32, kind as u32]; l.SetComputeRoot32BitConstants(0, constants.len() as u32, constants.as_ptr() as *const c_void, 0); + super::real::note_root_view(l.as_raw() as usize, 1, va); l.SetComputeRootUnorderedAccessView(1, va); + super::real::note_root_view(l.as_raw() as usize, 2, g.out_va); l.SetComputeRootUnorderedAccessView(2, g.out_va); + super::real::note_root_view(l.as_raw() as usize, 3, g.seen_va); l.SetComputeRootUnorderedAccessView(3, g.seen_va); + super::real::note_root_view(l.as_raw() as usize, 4, shown); l.SetComputeRootUnorderedAccessView(4, shown); l.Dispatch(1, 1, 1); report(&g); diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 1c17726248..e3c2be83bd 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -40,6 +40,37 @@ struct Batch { dead: Vec, /// (fence, value) a queue: all reached = nothing submitted before the batch closed is left marks: Vec<(ID3D12Fence, u64)>, + /// the title's submits when it closed (`note_submit`), for `XCL_LATE_RELEASE_LAG` + submits: u64, +} + +/// The title's submits so far (`note_submit`). +static SUBMITS: AtomicU64 = AtomicU64::new(0); + +/// A title's `ExecuteCommandLists` (not XCL's own submits): counted for `XCL_LATE_RELEASE_LAG`. +pub(super) fn note_submit() { + SUBMITS.fetch_add(1, Ordering::Relaxed); +} + +/// `XCL_LATE_RELEASE_LAG=n` (a diagnostic, 0 = off by default): a closed batch also waits for `n` +/// more submits of the title after it closed, as Whiplash's bury lag (64) does. With the fences +/// alone a batch goes once the queues are past the work submitted before the release; a GPU fault +/// that goes away with a lag points at a resource that later work still reaches (a stale view or +/// descriptor), not at the program that faulted. +fn lag() -> u64 { + static LAG: std::sync::OnceLock = std::sync::OnceLock::new(); + *LAG.get_or_init(|| { + let n = std::env::var("XCL_LATE_RELEASE_LAG").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0); + if n != 0 { + crate::xlog_info!("D3D12.X: XCL_LATE_RELEASE_LAG={n}: last releases wait for {n} more title submits too"); + } + n + }) +} + +/// Whether a batch closed at `closed` submits has waited out `lag` title submits by `now`. +fn lag_passed(closed: u64, now: u64, lag: u64) -> bool { + now.saturating_sub(closed) >= lag } #[derive(Default)] @@ -86,7 +117,8 @@ impl Held { signals.push((q.clone(), fence.clone(), *value)); } // (taken now: what is released after this is not behind the signals) - let seal = Seal { dead: std::mem::take(&mut self.open), signals, was_sealed: self.last_seal }; + let seal = Seal { dead: std::mem::take(&mut self.open), signals, was_sealed: self.last_seal, + submits: SUBMITS.load(Ordering::Relaxed) }; self.last_seal = Some(Instant::now()); self.sealing = true; Some(seal) @@ -97,7 +129,7 @@ impl Held { self.sealing = false; if ok { let marks = seal.signals.into_iter().map(|(_, f, v)| (f, v)).collect(); - self.sealed.push_back(Batch { dead: seal.dead, marks }); + self.sealed.push_back(Batch { dead: seal.dead, marks, submits: seal.submits }); } else { self.last_seal = seal.was_sealed; self.open.splice(0..0, seal.dead); @@ -106,8 +138,15 @@ impl Held { /// Take out the batches every queue is past: what to release now. unsafe fn take_gone(&mut self) -> Vec { + self.take_gone_at(SUBMITS.load(Ordering::Relaxed), lag()) + } + + /// `take_gone` with the title's submits so far (`submits`) and `XCL_LATE_RELEASE_LAG` (`lag`) given. + unsafe fn take_gone_at(&mut self, submits: u64, lag: u64) -> Vec { let mut gone = Vec::new(); - while self.sealed.front().is_some_and(|b| b.marks.iter().all(|(f, v)| super::real::fence_completed(&f) >= *v)) { + while self.sealed.front().is_some_and(|b| { + lag_passed(b.submits, submits, lag) && b.marks.iter().all(|(f, v)| super::real::fence_completed(&f) >= *v) + }) { gone.extend(self.sealed.pop_front().unwrap().dead); } gone @@ -116,11 +155,18 @@ impl Held { /// `begin_seal`, the signals, `end_seal` and `take_gone` in one, for a `Held` nobody else uses. #[cfg(test)] unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec { - if let Some(seal) = self.begin_seal(queues, seal_now) { + self.drain_at(queues, seal_now, SUBMITS.load(Ordering::Relaxed), lag()) + } + + /// `drain` with the title's submits so far (`submits`) and `XCL_LATE_RELEASE_LAG` (`lag`) given. + #[cfg(test)] + unsafe fn drain_at(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool, submits: u64, lag: u64) -> Vec { + if let Some(mut seal) = self.begin_seal(queues, seal_now) { + seal.submits = submits; let ok = seal.signal(); self.end_seal(seal, ok); } - self.take_gone() + self.take_gone_at(submits, lag) } } @@ -135,6 +181,8 @@ struct Seal { dead: Vec, signals: Vec<(ID3D12CommandQueue, ID3D12Fence, u64)>, was_sealed: Option, + /// the title's submits when it closed (`Batch::submits`) + submits: u64, } impl Seal { @@ -223,7 +271,8 @@ fn leaves_to_thread(pinned: bool, queues_busy: bool, in_list_reset: bool) -> boo pub unsafe fn hold(res: usize, pinned: bool) { HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(Dead::Resource(res)); let start = Instant::now(); - let busy = leaves_to_thread(pinned, BUSY.is(start), in_list_reset()); + // (with `XCL_LATE_RELEASE_LAG` nothing goes before more submits: no use waiting here) + let busy = leaves_to_thread(pinned, lag() != 0 || BUSY.is(start), in_list_reset()); if !busy { drain_known(true); while start.elapsed() < IDLE_WAIT && HELD.lock().unwrap().as_ref().is_some_and(|h| !h.is_empty()) { @@ -460,6 +509,25 @@ mod tests { assert!(held.is_empty()); } + /// `XCL_LATE_RELEASE_LAG`: a batch the queues are past still waits for that many title + /// submits after it closed, then goes; batches go in order. + #[test] + fn a_lag_holds_a_batch_for_more_title_submits() { + let mut held = Held::default(); + held.open.push(Dead::Resource(0x1000)); + // (no queues: the fences are passed at once; closed at 10 submits, lag 3) + assert!(unsafe { held.drain_at(&[], true, 10, 3) }.is_empty(), "closed at 10: not 3 submits later yet"); + held.open.push(Dead::Resource(0x2000)); + assert!(unsafe { held.drain_at(&[], true, 12, 3) }.is_empty(), "12 submits: the first batch is 2 past"); + assert_eq!(unsafe { held.drain_at(&[], false, 13, 3) }, vec![Dead::Resource(0x1000)], "13: the first batch goes alone"); + assert_eq!(unsafe { held.drain_at(&[], false, 15, 3) }, vec![Dead::Resource(0x2000)]); + assert!(held.is_empty()); + // lag 0: as without the switch + held.open.push(Dead::Resource(0x3000)); + assert_eq!(unsafe { held.drain_at(&[], true, 15, 0) }, vec![Dead::Resource(0x3000)]); + assert!(lag_passed(5, 5, 0) && !lag_passed(5, 4, 1) && lag_passed(5, 9, 4)); + } + /// A pipeline state XCL lets go goes into a batch (a list in flight may bind it), and the /// thread here releases it once the queues are past – through its COM Release. (That a batch /// waits for a busy queue is `a_held_resource_goes_when_the_queue_is_past_its_batch`.) diff --git a/crates/xcl/src/hle/d3d12x/left_out.rs b/crates/xcl/src/hle/d3d12x/left_out.rs new file mode 100644 index 0000000000..5507e86de7 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/left_out.rs @@ -0,0 +1,212 @@ +//! `XCL_RT_LEAVE_OUT_COUNT=1` (off by default; only with `XCL_RT_LEAVE_OUT`): the work the +//! compute programs `XCL_RT_LEAVE_OUT` leaves out would have done, counted and logged every 10 s. +//! +//! What it is for: a retail title's ray-tracing resolve programs (~1,000, ~200 bound in a world +//! frame) are dispatched only indirectly, with group counts its own passes wrote for the rays +//! that hit something of each material. While every ray misses (`XCL_RT_GATE=miss`) those counts +//! should be zero, and leaving the programs out then loses nothing – but their cold driver builds +//! (20 - 39 s and ~1.5 GB each, plus their dispatch chains' pieces) would take an hour of a run. +//! This shows whether the counts are zero: each indirect dispatch of a left-out program has its +//! counts read on the GPU by `indirect_guard`'s pass (which every other ExecuteIndirect already +//! gets), and the CPU reads them back from its ring once the GPU is past them. A direct dispatch +//! (the screen probes' ray activation: 920 groups a frame) has its groups counted on the CPU. + +use std::collections::{HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +/// How long a read-back waits for the GPU before it is given up (a list never submitted). +const STALE: Duration = Duration::from_secs(5); +/// Read-backs waiting at most (the guard's ring has 2^18 slots). +const MOST_PENDING: usize = 1 << 16; +/// How often the line is logged. +const EVERY: Duration = Duration::from_secs(10); + +/// Whether the counting is on: `XCL_RT_LEAVE_OUT_COUNT=1` with `XCL_RT_LEAVE_OUT` set. +pub(super) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + let on = switch(std::env::var("XCL_RT_LEAVE_OUT_COUNT").ok().as_deref()) && crate::gpu::rt_leave_out::enabled(); + if on { + crate::xlog_info!("XCL_RT_LEAVE_OUT_COUNT: the work of the compute programs left out is counted (every 10 s)"); + } + on + }) +} + +fn switch(v: Option<&str>) -> bool { + v.is_some_and(|v| v.trim() == "1") +} + +/// The left-out pipelines (the dummy the title got) and their console programs' records. +static PSOS: Mutex>> = Mutex::new(None); + +/// `pso` is the dummy pipeline of the left-out console program `cs`. +pub(super) fn note(pso: usize, cs: &[u8]) { + if pso != 0 && on() { + PSOS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, crate::gpu::shader::fnv64(cs)); + } +} + +/// `pso` was released (another pipeline may be made at its address). +pub(super) fn forget(pso: usize) { + if let Some(m) = PSOS.lock().unwrap().as_mut() { + m.remove(&pso); + } +} + +fn record_of(pso: usize) -> Option { + PSOS.lock().unwrap().as_ref()?.get(&pso).copied() +} + +/// What was counted since the last line. +#[derive(Default, Debug, PartialEq)] +struct Window { + direct: u64, + direct_groups: u64, + indirect: u64, + /// indirect dispatches whose counts were read back, those with work, and their groups + read: u64, + with_work: u64, + groups: u64, + /// the most groups one indirect dispatch had, and its program's record + most: (u64, u64), + /// not read: not a plain dispatch signature, a count buffer, or the GPU never got to it + unread: u64, +} + +impl Window { + /// An indirect dispatch of `record`'s program whose counts read back as `c`. + fn counted(&mut self, record: u64, c: [u32; 3]) { + self.read += 1; + let groups = c.iter().map(|&n| n as u64).product::(); + if groups > 0 { + self.with_work += 1; + self.groups += groups; + if groups > self.most.0 { + self.most = (groups, record); + } + } + } +} + +struct State { + window: Window, + since: Instant, + /// slots of the guard's ring whose counts are not read back yet, oldest first + pending: VecDeque<(u32, u64, Instant)>, + /// with work so far (all windows) + with_work: u64, +} + +fn state() -> &'static Mutex { + static S: OnceLock> = OnceLock::new(); + S.get_or_init(|| Mutex::new(State { window: Window::default(), since: Instant::now(), pending: VecDeque::new(), with_work: 0 })) +} + +/// A direct dispatch of `pso`, skipped, of `groups` (None: not known). +pub(super) fn direct(pso: usize, groups: Option<[u32; 3]>) { + if !on() || record_of(pso).is_none() { + return; + } + let mut s = state().lock().unwrap(); + s.window.direct += 1; + s.window.direct_groups += groups.map_or(0, |g| g.iter().map(|&n| n as u64).product()); + report(&mut s); +} + +/// An ExecuteIndirect of `pso` (the title's pipeline, `raw` before it was resolved), skipped: +/// its counts are read by the guard's pass recorded on `list` now, and back later. +pub(super) unsafe fn indirect(list: *mut c_void, raw: usize, pso: usize, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize) { + if !on() { + return; + } + let Some(record) = record_of(raw).or_else(|| record_of(pso)) else { return }; + let checked = super::indirect_guard::check(list, pso, sig, max, args, args_off, count_buf); + if let Some(c) = &checked { + // (the guard's pass bound a root signature and a pipeline of its own, and left its buffer + // in UAV state: as after a pass that read the counts in place of the dispatch) + c.read(list); + super::list_x::restore_after_internal_pass(list, false, true); + } + let mut s = state().lock().unwrap(); + s.window.indirect += 1; + match checked { + Some(c) => { + if s.pending.len() >= MOST_PENDING { + s.pending.pop_front(); + s.window.unread += 1; + } + s.pending.push_back((c.slot, record, Instant::now())); + } + None => s.window.unread += 1, + } + report(&mut s); +} + +/// Reads back what the GPU has read, and logs the window every `EVERY`. +fn report(s: &mut State) { + while let Some(&(slot, record, at)) = s.pending.front() { + match super::indirect_guard::counts(slot) { + Some(c) => s.window.counted(record, c), + None if at.elapsed() > STALE => s.window.unread += 1, + None => break, + } + s.pending.pop_front(); + } + if s.since.elapsed() < EVERY { + return; + } + let w = std::mem::take(&mut s.window); + s.since = Instant::now(); + s.with_work += w.with_work; + let most = if w.most.0 > 0 { format!(", the most {} groups (record {:016x})", w.most.0, w.most.1) } else { String::new() }; + let line = format!( + "XCL_RT_LEAVE_OUT: in the last 10 s the programs left out were dispatched {} times directly ({} groups) and {} times indirectly: {} of those read back, {} with work ({} groups{most}), {} not read", + w.direct, w.direct_groups, w.indirect, w.read, w.with_work, w.groups, w.unread + ); + if w.with_work > 0 { + crate::xlog_warn!("{line} – what was left out would have run"); + } else { + crate::xlog_info!("{line} ({} with work so far)", s.with_work); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_switch_is_off_unless_one() { + assert!(switch(Some(" 1 "))); + assert!(!switch(Some("0"))); + assert!(!switch(Some("yes"))); + assert!(!switch(None)); + } + + /// Counts read back add up per window: zeros are dispatches without work, the product of the + /// three is the groups (in 64 bits: a float's bits read as counts are billions), the most is + /// kept with its program. + #[test] + fn read_back_counts_add_up() { + let mut w = Window::default(); + w.counted(0xA, [0, 4, 1]); + w.counted(0xB, [12, 1, 1]); + w.counted(0xC, [0x3F80_0000, 2, 1]); + w.counted(0xD, [5, 1, 0]); + assert_eq!(w.read, 4); + assert_eq!(w.with_work, 2); + assert_eq!(w.groups, 12 + 0x3F80_0000u64 * 2); + assert_eq!(w.most, (0x3F80_0000u64 * 2, 0xC)); + } + + /// A released pipeline's address is not taken for a left-out one's any more. + #[test] + fn a_forgotten_pipeline_is_not_counted() { + PSOS.lock().unwrap().get_or_insert_with(HashMap::new).insert(0x7E57_1E00, 0x1234); + assert_eq!(record_of(0x7E57_1E00), Some(0x1234)); + forget(0x7E57_1E00); + assert_eq!(record_of(0x7E57_1E00), None); + } +} diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 638b133d13..2d82b0374d 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -110,6 +110,8 @@ pub(super) fn tracked_list_type(list: *mut c_void) -> Option(list, PC_SET_PIPELINE_STATE)(list, pso); } @@ -129,6 +131,98 @@ pub(super) unsafe fn transition(list: *mut c_void, res: usize, before: D3D12_RES pc::(list, PC_RESOURCE_BARRIER)(list, 1, &b); } +pub(super) unsafe fn pc_resource_barriers(list: *mut c_void, barriers: &[D3D12_RESOURCE_BARRIER]) { + if !barriers.is_empty() { + pc::(list, PC_RESOURCE_BARRIER)(list, barriers.len() as u32, barriers.as_ptr()); + } +} + +pub(super) unsafe fn pc_copy_resource(list: *mut c_void, dst: usize, src: usize) { + pc::(list, PC_COPY_RESOURCE)(list, dst, src); +} + +pub(super) unsafe fn pc_copy_texture_region( + list: *mut c_void, + dst: *const D3D12_TEXTURE_COPY_LOCATION, + x: u32, + y: u32, + z: u32, + src: *const D3D12_TEXTURE_COPY_LOCATION, + bx: *const D3D12_BOX, +) { + pc::(list, PC_COPY_TEXTURE_REGION)( + list, dst, x, y, z, src, bx, + ); +} + +pub(super) unsafe fn device_of_list(list: *mut c_void) -> Option { + let l = ID3D12GraphicsCommandList::from_raw_borrowed(&list)?; + let mut dev: Option = None; + l.GetDevice(&mut dev).ok()?; + dev +} + +pub(super) unsafe fn acquire_scratch_for_copy(list: *mut c_void, n: u64) -> Option { + if n == 0 || n > MAX_COPY_SCRATCH || list_type(list) == D3D12_COMMAND_LIST_TYPE_BUNDLE { + return None; + } + let bytes = n.next_power_of_two().max(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64).min(MAX_COPY_SCRATCH); + let mut dropped = Vec::new(); + let res = COPY_SCRATCH.lock().unwrap().acquire(list, bytes, &mut dropped); + drop(dropped); + let (raw, cap) = res?; + (cap >= n).then_some(raw) +} + +/// Restore title bindings, PC root signatures, and bound PSO after an internal compute pass. +pub(super) unsafe fn restore_after_internal_pass(list: *mut c_void, clobbered_gfx: bool, clobbered_cs: bool) { + let (bindings, bound_pso, ty, depth_bias, native_bias, had_fallback) = { + let mut g = 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 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); @@ -703,6 +797,14 @@ pub(super) unsafe fn note_render_targets(this: *mut c_void, n: u32, rtvs: *const let handles = if read_count == 0 { Vec::new() } else { std::slice::from_raw_parts(rtvs, read_count).to_vec() }; let d = dsv.as_ref().copied(); with_bindings(this, |b| b.render_targets = Some(RenderTargets { num_targets, handles, single, dsv: d })); + if let Some(d) = d { + super::depth_uav::trace_dsv_bind(this as usize, d); + } + if super::mirror::any() { + let rts: Vec = bound_render_targets(this).into_iter().filter_map(super::present::rtv_resource).collect(); + super::mirror::note_targets(&rts); + mirror_flush(this); + } } /// The render target views bound on `list` (each one of a single descriptor range too). @@ -949,6 +1051,11 @@ struct ListState { own_alloc: Option, /// depth buffers whose depth plane and twin hold the same on this recording (`depth_uav::plan_barriers`) depth_in_step: Vec, + /// depth buffers the title has in UNORDERED_ACCESS whose draws this recording follows + /// (`depth_uav::before_work`) + depth_owed: super::depth_uav::Owed, + /// the light around a mirror's view is owed after its sky's draw (`mirror_flush`) + mirror: Option, } /// A `Dispatch` or a dispatching `ExecuteIndirect` put off to the submit, with its arguments. @@ -1716,10 +1823,13 @@ pub(super) fn queue_identity(raw: usize) -> Option, device: usize, ty: D3D12_COMMAND_LIST_T g.iter().rev().find(|info| info.ty == ty && (device == 0 || info.device == 0 || info.device == device)).map(|info| info.queue) } +/// `XCL_TRACE_MS` (a diagnostic): `[va, va + size)` is read back after the list's submit. +pub(super) fn trace_read_back(list: usize, va: u64, size: u64) { + note_write(list, WriteProducer::InSegmentGpu, va, size); +} + fn note_write(list: usize, producer: WriteProducer, va: u64, size: u64) { + crate::hle::kernelx::pagelog::note("list memory write recorded (the GPU writes it)", va as usize, 0, size as usize); LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(producer, va, size); } @@ -2064,6 +2183,14 @@ fn note_texture_write(list: usize, res: usize, subresource: u32) { /// (what the GPU writes there is its tiles', and the title reads it at the CPU view): the bytes /// come back to the CPU's view after the submit, like the lists' own memory writes. fn note_copy_into(list: usize, dst: usize, offset: u64, n: u64) { + if let Some((lo, hi)) = super::bind::trace_range_of() { + if let Some((p, _)) = real::console_buffer(dst) { + let at = p as u64 + offset; + if at < hi && at.saturating_add(n) > lo { + crate::xlog_info!("trace range: copy into {at:#x}, {n} bytes"); + } + } + } let Some(u) = crate::gpu::uma::get().filter(|u| u.shadowed() || super::bind::view_span().1 != 0) else { return }; let Some((p, bytes)) = real::console_buffer(dst).filter(|&(p, _)| (u.shadowed() && u.is_committed(p)) || u.is_view(p)) else { return }; let offset = offset.min(bytes as u64); @@ -2733,6 +2860,7 @@ unsafe fn publish_cpu_cycle_break_with(va: u64, val: u64, uma: Option<&crate::gp if uma.is_some_and(|u| u.is_sparse(addr)) { return; } + crate::hle::kernelx::pagelog::note("Write64 value published by the CPU (cycle break)", addr, 0, 8); if uma.is_some_and(|u| u.in_committed_window(addr, 8)) { (*(addr as *const AtomicU64)).fetch_max(val, Ordering::AcqRel); } else { @@ -3019,6 +3147,9 @@ fn wake_sync_watchdog() { if PRINTED.fetch_add(1, Ordering::Relaxed) < 3 { crate::xlog_warn!("D3D12.X: wait edges at that time-out: {}", edges_summary()); } + // the work the stuck queue may be running: without it a hang that the kernel + // later resets names no pipeline + super::watch::report("a GPU queue wait exceeded its watchdog"); if wait_timeout_continues() { crate::xlog_warn!("D3D12.X: XCL_WAIT_TIMEOUT_CONTINUE=1 – the timed-out GPU queue waits were released on the CPU and the title goes on"); } else { @@ -3619,6 +3750,7 @@ unsafe fn mapped_after_wait(queue: *mut c_void) { super::sparse::PreparationOutcome::Ready => {} super::sparse::PreparationOutcome::RetryRequired => stop_for_unresolved_wait("sparse upload preparation after a wait inside a submit still failed after bounded retries"), super::sparse::PreparationOutcome::ExecutedUntracked => stop_for_unresolved_wait("a sparse upload after a wait inside a submit executed without a retirement signal"), + super::sparse::PreparationOutcome::MappingUnmarked => stop_for_unresolved_wait("a texture page mapping after a wait inside a submit has no Signal of the mapping queue"), } } } @@ -3873,25 +4005,31 @@ struct CopyScratchCache { } impl CopyScratchCache { - fn collect_released(&mut self) { - self.released.retain_mut(|scratch| { - if !scratch.idle() { - return true; + /// Move idle released scratch entries into `dropped` so callers drop their COM resources + /// outside `COPY_SCRATCH`: `ID3D12Resource::Release` enters `vram::PAGES`, and a thread holding + /// `PAGES` can wait for `COPY_SCRATCH` (lock-order inversion, #3069). + fn collect_released(&mut self, dropped: &mut Vec) { + let mut i = 0; + while i < self.released.len() { + if self.released[i].idle() { + let scratch = self.released.swap_remove(i); + self.bytes -= scratch.bytes; + dropped.push(scratch); + } else { + i += 1; } - self.bytes -= scratch.bytes; - false - }); + } } - fn release(&mut self, list: usize) { + fn release(&mut self, list: usize, dropped: &mut Vec) { if let Some(scratch) = self.active.remove(&list) { self.released.push(scratch); } - self.collect_released(); + self.collect_released(dropped); } - unsafe fn acquire(&mut self, list: *mut c_void, bytes: u64) -> Option<(usize, u64)> { - self.collect_released(); + unsafe fn acquire(&mut self, list: *mut c_void, bytes: u64, dropped: &mut Vec) -> Option<(usize, u64)> { + self.collect_released(dropped); let key = list as usize; if let Some(scratch) = self.active.get_mut(&key) { // Reset can happen while the previous recording is executing on another queue. @@ -3902,8 +4040,10 @@ impl CopyScratchCache { scratch.recorded = true; return Some((scratch.buffer.as_raw() as usize, scratch.bytes)); } - // Drop the old allocation before growing so the peak stays within the budget. - self.bytes -= self.active.remove(&key).unwrap().bytes; + // Account for the old allocation now; its COM resource is dropped outside `COPY_SCRATCH`. + let old = self.active.remove(&key).unwrap(); + self.bytes -= old.bytes; + dropped.push(old); } if bytes > MAX_COPY_SCRATCH - self.bytes { return None; @@ -3921,24 +4061,34 @@ impl CopyScratchCache { static COPY_SCRATCH: LazyLock> = LazyLock::new(|| Mutex::new(CopyScratchCache::default())); fn release_copy_scratch(list: usize) { - let mut cache = COPY_SCRATCH.lock().unwrap(); - cache.release(list); - if cache.reaping || !cache.released.iter().any(|s| !s.untracked_submission) { - return; - } - // A title can stop submitting work after releasing the list. Reclaim its scratch when - // the GPU finishes even if no call touches the cache again. - cache.reaping = std::thread::Builder::new().name("xcl-copy-scratch".into()).spawn(|| loop { - { - let mut cache = COPY_SCRATCH.lock().unwrap(); - cache.collect_released(); - if !cache.released.iter().any(|s| !s.untracked_submission) { - cache.reaping = false; - return; - } + let mut dropped = Vec::new(); + { + let mut cache = COPY_SCRATCH.lock().unwrap(); + cache.release(list, &mut dropped); + if !cache.reaping && cache.released.iter().any(|s| !s.untracked_submission) { + // A title can stop submitting work after releasing the list. Reclaim its scratch when + // the GPU finishes even if no call touches the cache again. + cache.reaping = std::thread::Builder::new().name("xcl-copy-scratch".into()).spawn(|| loop { + let mut reaped = Vec::new(); + let done = { + let mut cache = COPY_SCRATCH.lock().unwrap(); + cache.collect_released(&mut reaped); + if !cache.released.iter().any(|s| !s.untracked_submission) { + cache.reaping = false; + true + } else { + false + } + }; + drop(reaped); + if done { + return; + } + std::thread::sleep(Duration::from_millis(16)); + }).is_ok(); } - std::thread::sleep(Duration::from_millis(16)); - }).is_ok(); + } + drop(dropped); } unsafe fn copy_scratch(list: *mut c_void, n: u64) -> Option<(usize, u64)> { @@ -3946,7 +4096,10 @@ unsafe fn copy_scratch(list: *mut c_void, n: u64) -> Option<(usize, u64)> { return None; } let bytes = n.next_power_of_two().max(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64); - COPY_SCRATCH.lock().unwrap().acquire(list, bytes) + let mut dropped = Vec::new(); + let res = COPY_SCRATCH.lock().unwrap().acquire(list, bytes, &mut dropped); + drop(dropped); + res } fn reset_copy_scratch(list: *mut c_void) { @@ -3958,9 +4111,12 @@ fn reset_copy_scratch(list: *mut c_void) { /// Mark GPU ownership on the queue that actually submitted each PC list or split segment. pub(super) unsafe fn copy_scratch_submitted(queue: *mut c_void, lists: &[*mut c_void]) { + let mut dropped = Vec::new(); let mut cache = COPY_SCRATCH.lock().unwrap(); - cache.collect_released(); + cache.collect_released(&mut dropped); if !lists.iter().any(|l| cache.active.get(&(*l as usize)).is_some_and(|s| s.recorded)) { + drop(cache); + drop(dropped); return; } let mark = (|| { @@ -3987,6 +4143,8 @@ pub(super) unsafe fn copy_scratch_submitted(queue: *mut c_void, lists: &[*mut c_ } } } + drop(cache); + drop(dropped); } unsafe fn make_copy_scratch(list: *mut c_void, bytes: u64) -> Option { @@ -5030,12 +5188,75 @@ unsafe fn emit_uav_barrier_pc(this: *mut c_void) { pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, n: u32, barriers: *const c_void) { let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListBarrier); emit_uav_barrier_pc(this); + barrier_groups_log(n, barriers); + // the title's texture barriers as transitions (`barrier_groups`), which go the way its + // ResourceBarrier calls go: the format aliases and the depth twins are kept from there if super::barrier_groups::enabled() { let moves = super::barrier_groups::transitions(n, barriers, list_type(this) == D3D12_COMMAND_LIST_TYPE_DIRECT); if !moves.is_empty() { resource_barrier_x(this, moves.len() as u32, moves.as_ptr()); } + super::format_alias::on_uav_barrier(this, None); + return; + } + let mut alias_writers: Vec<(usize, u32)> = Vec::new(); + super::format_alias::filter_enhanced_barriers(n, barriers, &mut alias_writers); + if !alias_writers.is_empty() { + super::format_alias::sync_title_writers(this, &alias_writers); } + super::format_alias::on_uav_barrier(this, None); +} + +/// `XCL_BARRIER_LOG=1`: what the title's #146 calls hold, as barrier groups – calls, and the +/// texture barriers by (layout before → after, access before → after, depth buffer or not), +/// logged at each power of two of calls. +unsafe fn barrier_groups_log(n: u32, groups: *const c_void) { + static ON: OnceLock = OnceLock::new(); + if !*ON.get_or_init(|| std::env::var("XCL_BARRIER_LOG").is_ok_and(|v| v.trim() == "1")) { + return; + } + static CALLS: AtomicU64 = AtomicU64::new(0); + static KINDS: Mutex>> = Mutex::new(None); + let calls = CALLS.fetch_add(1, Ordering::Relaxed) + 1; + let mut g = KINDS.lock().unwrap(); + let kinds = g.get_or_insert_with(HashMap::new); + let count = (n as usize).min(64); + if !groups.is_null() && count != 0 && crate::gpu::shader::readable(groups as usize, count * std::mem::size_of::()) { + for grp in std::slice::from_raw_parts(groups as *const D3D12_BARRIER_GROUP, count) { + let nb = (grp.NumBarriers as usize).min(1024); + let p = grp.Anonymous.pTextureBarriers; + if grp.Type != D3D12_BARRIER_TYPE_TEXTURE { + *kinds.entry((grp.Type.0 as u32, 0, 0, 0, 0, false)).or_default() += nb as u64; + continue; + } + if p.is_null() || !crate::gpu::shader::readable(p as usize, nb * std::mem::size_of::()) { + *kinds.entry((99, 0, 0, 0, 0, false)).or_default() += 1; + continue; + } + for tb in std::slice::from_raw_parts(p, nb) { + let res: usize = transmute_copy(&tb.pResource); + let depth = res != 0 && readable_resource(res).is_some_and(|d| d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0); + *kinds.entry((1, tb.LayoutBefore.0 as u32, tb.LayoutAfter.0 as u32, tb.AccessBefore.0 as u32, tb.AccessAfter.0 as u32, depth)).or_default() += 1; + } + } + } else { + *kinds.entry((98, n, 0, 0, 0, false)).or_default() += 1; + } + if calls.is_power_of_two() && calls >= 16 { + let mut v: Vec<_> = kinds.iter().map(|(k, c)| (*c, *k)).collect(); + v.sort_unstable_by(|a, b| b.cmp(a)); + let text: Vec = v.iter().take(24).map(|(c, (ty, lb, la, ab, aa, depth))| format!("{c}x type {ty} layout {lb:#x}->{la:#x} access {ab:#x}->{aa:#x}{}", if *depth { " (depth)" } else { "" })).collect(); + crate::xlog_info!("D3D12.X: #146 barrier groups: {calls} calls, {} kinds: {}", v.len(), text.join("; ")); + } +} + +/// The description of the PC resource a barrier names at `res` (as `is_buffer` reads one). +unsafe fn readable_resource(res: usize) -> Option { + if !crate::gpu::shader::readable(res, 8) { + return None; + } + let r = res as *mut c_void; + ID3D12Resource::from_raw_borrowed(&r).map(|x| x.GetDesc()) } /// A UAV barrier for all resources on `list`, where a list takes one (a copy list and a bundle @@ -5119,6 +5340,8 @@ unsafe fn predication_buffer(list: *mut c_void) -> Option { /// Before `Close()` on a command list: return `pred_buf` to `COMMON` if it is currently in /// `D3D12_RESOURCE_STATE_PREDICATION`. pub(super) unsafe fn before_close(list: *mut c_void) { + mirror_flush(list); + super::format_alias::before_close(list); if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { return; } @@ -5142,6 +5365,7 @@ pub(super) unsafe fn before_close(list: *mut c_void) { /// Clear active predication state when `ID3D12GraphicsCommandList::Reset` resets a recording. pub(super) fn on_pc_reset(list: *mut c_void) { reset_copy_scratch(list); + super::format_alias::list_reset(list as usize); if list.is_null() { return; } @@ -5361,6 +5585,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { super::capture::kickoff(this, queue); let q_raw = queue_pin.as_raw(); + // (the sources of its bake draws: `title_textures::bake_at_submit`) + super::title_textures::ready_bake_sources(&super::bind::bake_sources(&[this])); real::prepare_title_submission(q_raw, &[this]); super::gpu_profile::note_queue(q_raw); type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); @@ -5442,6 +5668,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { super::gpu_times::executed(q_raw, &one); super::lut3d::submitted(&one); super::lut3d::list_reset(this as usize); + super::format_alias::list_reset(this as usize); copy_scratch_submitted(q_raw, &one); super::title_textures::publish_submission_effects(queue_identity(q_raw as usize), &texture_writes, &texture_transitions); if let Some(w) = kickoff_wrapper { @@ -5683,8 +5910,84 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b } } +/// Before a draw (`draw`: its depth target the one bound) or a dispatch on `list`: the copies +/// between depth planes and their twins that the buffers the title has in UNORDERED_ACCESS need +/// first (`depth_uav::before_work`). Copies and barriers only: nothing bound on the list changes. +unsafe fn depth_twins_before_work(list: *mut c_void, draw: bool) { + if !super::depth_uav::any_live() { + return; + } + let (mut owed, dsv) = { + let mut g = LISTS.lock().unwrap(); + let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(list as usize))) else { return }; + if s.list_type != Some(D3D12_COMMAND_LIST_TYPE_DIRECT) { + return; + } + (std::mem::take(&mut s.depth_owed), if draw { s.bindings.render_targets.as_ref().and_then(|rt| rt.dsv) } else { None }) + }; + let copies = super::depth_uav::before_work(&mut owed, dsv); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.depth_owed = owed; + } + for c in copies { + plane_copies_on(list, std::slice::from_ref(&c.copy), c.to_twin); + // (into the plane: from PARK to COPY_DEST there, back where the title has it) + if !c.to_twin { + let tr = [0, 0, c.copy.depth as u32, (c.copy.depth as u64 >> 32) as u32, c.copy.sub, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32, super::depth_uav::PARK, 0]; + pc::(list, PC_RESOURCE_BARRIER)(list, 1, &tr); + } + } +} + +/// Before a draw on `list` of a mirror view's material mask or sky (`mirror`): the colour of +/// the view's surfaces is noted, or the light around is owed the lit image (`mirror_flush`). +unsafe fn mirror_at_draw(list: *mut c_void) { + if !super::mirror::any() { + return; + } + let (pso, rt0, rect) = { + let g = LISTS.lock().unwrap(); + let Some(s) = g.as_ref().and_then(|m| m.get(&(list as usize))) else { return }; + if s.list_type != Some(D3D12_COMMAND_LIST_TYPE_DIRECT) { + return; + } + let b = &s.bindings; + let rect = b.scissors.first().copied().or_else(|| { + b.viewports.first().map(|v| windows::Win32::Foundation::RECT { left: v.TopLeftX as i32, top: v.TopLeftY as i32, right: (v.TopLeftX + v.Width) as i32, bottom: (v.TopLeftY + v.Height) as i32 }) + }); + (s.bound_pso, b.render_targets.as_ref().and_then(|rt| rt.handles.first().copied()), rect) + }; + match super::mirror::part_of(pso) { + Some(super::mirror::Part::Mask) => { + let current: Vec = bound_render_targets(list).into_iter().filter_map(super::present::rtv_resource).collect(); + super::mirror::at_mask(¤t); + } + Some(super::mirror::Part::Sky) => { + let owed = rt0.and_then(|rtv| super::mirror::at_sky(rtv, rect)); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.mirror = owed; + } + } + None => {} + } +} + +/// The light around a mirror's view owed on `list` (`mirror_at_draw`), recorded here – a point +/// between the title's commands – with the title's state set again after it. +unsafe fn mirror_flush(list: *mut c_void) { + if !super::mirror::any() { + return; + } + let Some(p) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))).and_then(|s| s.mirror.take()) else { return }; + if super::mirror::light(list, &p) { + restore_after_internal_pass(list, true, false); + } +} + /// Apply a pending fallback `RSSetDepthBiasX` override before a draw call on `list`. pub(super) unsafe fn prepare_draw(list: *mut c_void) { + depth_twins_before_work(list, true); + mirror_at_draw(list); if !DEPTH_BIAS_USED.load(Ordering::Acquire) { return; } @@ -5739,12 +6042,33 @@ fn pc_va(va: u64) -> u64 { } } +/// Diagnostic: an address the title gave that is not in unified memory goes to the PC as it is. +/// When it is the title's ordinary memory (the CPU can read it) the PC's GPU has nothing there: +/// a page fault at that very address and a device removal. The first ones are logged with the +/// calls that led here. +fn note_cpu_address_as_gpu(va: u64) { + static N: AtomicU64 = AtomicU64::new(0); + // (below the unified-memory windows: where a retail title keeps its ordinary heaps) + if va < 0x1_0000_0000 || va >= 0x10_0000_0000 || !crate::gpu::shader::readable(va as usize, 16) { + return; + } + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 6 { + crate::xlog_error!("D3D12.X: the title's ordinary memory at {va:#x} goes to the GPU as an address (#{n}): {}", std::backtrace::Backtrace::force_capture().to_string().lines().filter(|l| l.contains("xcl::") || l.contains("game_")).take(14).map(|l| l.trim()).collect::>().join(" < ")); + } else if n.is_power_of_two() { + crate::xlog_error!("D3D12.X: the title's ordinary memory went to the GPU as an address {n} times so far (now {va:#x})"); + } +} + /// `pc_va` in `u`, whose windows have the PC addresses `window_va` (`real::uma_window_va`). A /// GPU view of the title's memory without a PC address of its window gets none (0, read as /// nothing): as it is, the console address is no PC address and hangs the device. fn pc_va_in(u: &crate::gpu::uma::Uma, va: u64, window_va: impl Fn(usize) -> Option) -> u64 { let p = va as usize; - let Some(k) = u.window_of(p).filter(|_| u.is_title_address(p)) else { return va }; + let Some(k) = u.window_of(p).filter(|_| u.is_title_address(p)) else { + note_cpu_address_as_gpu(va); + return va; + }; match window_va(k) { Some(w) => w + (p - u.window(k).0) as u64, None if u.is_view_window(k) => 0, @@ -6338,12 +6662,15 @@ unsafe fn reset_pc_inner(this: *mut c_void, alloc: usize, pso: usize) -> i32 { s.pred_in_state = false; s.bindings = Bindings::default(); s.depth_in_step.clear(); + s.depth_owed = Default::default(); + s.mirror = None; (s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE), old_generations) }; drop(old_generations); // (what the new recording puts in unified memory belongs to the PC allocator it is on) prepared.commit(this, on); super::lut3d::list_reset(this as usize); + super::format_alias::list_reset(this as usize); super::dred::reset(this); if pso != 0 && resolved != 0 { super::dred::mark_pipeline(this, pso, resolved); @@ -6365,6 +6692,12 @@ const PC_STATES: u32 = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x80 | 0x100 /// #26 ResourceBarrier(count, barriers): console barriers (D3D12_RESOURCE_BARRIER, 32 bytes) as /// PC ones – state bits the PC does not know are dropped (logged: the console's own), a +/// Strip console-only `D3D12_RESOURCE_BARRIER_FLAGS` bits, keeping standard PC +/// `BEGIN_ONLY` (1) / `END_ONLY` (2). Returns `(pc_flags, stripped_console_bits)`. +fn sanitize_barrier_flags(flags: u32) -> (u32, u32) { + (flags & 3, flags & !3) +} + /// transition left with nothing to do goes, aliasing barriers name placed textures pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u32, barriers: *const [u32; 8]) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBarrier); @@ -6373,36 +6706,40 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 if barriers.is_null() || n == 0 { return; } + // (the light around a mirror's view, owed since its sky's draw, before the title moves its + // lit image to be read) + mirror_flush(this); let capture = super::capture::op(this, || Some(super::capture::barrier(&(0..n as usize).map(|k| barriers.add(k).read_unaligned()).collect::>()))); let mut out: Vec<[u32; 8]> = Vec::with_capacity(n as usize + 1); // a UAV barrier for all resources is in `out` / a transition from or to UNORDERED_ACCESS let (mut any_uav, mut uav_transition) = (false, false); + let mut alias_writers: Vec<(usize, u32)> = Vec::new(); + let mut uav_targets: Vec = Vec::new(); + let mut uav_global = false; for k in 0..n as usize { let mut b = barriers.add(k).read_unaligned(); - let (ty, flags) = (b[0], b[1]); + let (ty, raw_flags) = (b[0], b[1]); if super::present::trace_frame() && ty == 0 { let r = (b[2] as u64 | (b[3] as u64) << 32) as usize; if super::present::is_watched(r) { static W: AtomicU64 = AtomicU64::new(0); if W.fetch_add(1, Ordering::Relaxed) < 24 { - crate::xlog_info!("frame trace: ResourceBarrier on a watched target {r:#x}: subresource {:#x}, {:#x} → {:#x}, flags {flags:#x}", b[4], b[5], b[6]); + crate::xlog_info!("frame trace: ResourceBarrier on a watched target {r:#x}: subresource {:#x}, {:#x} → {:#x}, flags {raw_flags:#x}", b[4], b[5], b[6]); } } } if ty > 2 { if N.fetch_add(1, Ordering::Relaxed) < 16 { - crate::xlog_warn!("D3D12.X: ResourceBarrier: console barrier type {ty} flags {flags:#x} dropped ({:x?})", b); + crate::xlog_warn!("D3D12.X: ResourceBarrier: console barrier type {ty} flags {raw_flags:#x} dropped ({:x?})", b); } continue; } - // Console cache hints must not discard the transition or memory ordering itself. - // Keep the PC split-barrier bits and let the PC perform its normal synchronization. - const PC_FLAGS: u32 = (D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY.0 | D3D12_RESOURCE_BARRIER_FLAG_END_ONLY.0) as u32; - if flags & !PC_FLAGS != 0 { + let (flags, dropped_flags) = sanitize_barrier_flags(raw_flags); + if dropped_flags != 0 { if N.fetch_add(1, Ordering::Relaxed) < 16 { - crate::xlog_warn!("D3D12.X: ResourceBarrier: console flag bits {:#x} dropped", flags & !PC_FLAGS); + crate::xlog_warn!("D3D12.X: ResourceBarrier: console barrier flag bits {dropped_flags:#x} stripped (kept {flags:#x})"); } - b[1] &= PC_FLAGS; + b[1] = flags; } if ty == 1 { // Keep the identity of textures that really share placed GPU memory. @@ -6419,6 +6756,12 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 // window buffers – other resources over the same memory – which a UAV barrier for // the title's resource alone does not order (AMD drivers wait and flush for any UAV // barrier, NVIDIA's need not): a UAV barrier for all resources, once per batch + let uav_res = (b[2] as u64 | (b[3] as u64) << 32) as usize; + if uav_res == 0 { + uav_global = true; + } else { + uav_targets.push(uav_res); + } b[2..4].fill(0); if any_uav { continue; @@ -6446,6 +6789,7 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 // UAV writes before (or after) the transition: the same holds for the window buffers uav_transition |= (b[5] | b[6]) & UNORDERED_ACCESS != 0; let res = (b[2] as u64 | (b[3] as u64) << 32) as usize; + super::format_alias::note_title_transition(res, b[4], b[5], b[6], flags, &mut alias_writers); super::barrier_groups::note_legacy_state(res, b[4], b[6]); } out.push(b); @@ -6461,11 +6805,12 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 let plan = super::depth_uav::plan_barriers(&mut out, direct, &mut in_step); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { s.depth_in_step = in_step; + s.depth_owed.apply(&plan); } plan }); // the states uploads into textures kept in step start from once this list has run - if super::title_textures::any() || super::lut3d::on() { + if (super::title_textures::any() || super::lut3d::on()) && out.iter().any(|b| b[0] == 0) { let t: Vec<(usize, u32, D3D12_RESOURCE_STATES)> = out.iter().filter(|b| b[0] == 0).map(|b| ((b[2] as u64 | (b[3] as u64) << 32) as usize, b[4], D3D12_RESOURCE_STATES(b[6] as i32))).collect(); note_texture_transitions(this as usize, &t); @@ -6492,6 +6837,13 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 plane_copies_on(this, &p.to_twin, true); stencil_copies_on(this, &p.stencil_to_twin, true); } + if !alias_writers.is_empty() { + super::format_alias::sync_title_writers(this, &alias_writers); + } + if any_uav || uav_transition { + let targets = if uav_global || uav_targets.is_empty() { None } else { Some(uav_targets.as_slice()) }; + super::format_alias::on_uav_barrier(this, targets); + } } /// The copies between stencil planes and their twins around a title's barriers @@ -6554,7 +6906,14 @@ unsafe fn plane_copies_on(list: *mut c_void, copies: &[super::depth_uav::PlaneCo let at = |res: usize, k: u32| D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&res), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k } }; let copy = pc::(list, PC_COPY_TEXTURE_REGION); let (copy_src, copy_dst) = (D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32); + let (mut clobbered_gfx, mut clobbered_cs) = (false, false); for c in copies { + if let Some(steps) = c.r24g8_steps { + let (cg, cc) = super::depth_uav::execute_r24g8_copy(list, c, steps, to_twin); + clobbered_gfx |= cg; + clobbered_cs |= cc; + continue; + } let twin = c.twin.as_raw() as usize; let twin_in = if to_twin { copy_dst } else { copy_src }; if to_twin { @@ -6568,6 +6927,9 @@ unsafe fn plane_copies_on(list: *mut c_void, copies: &[super::depth_uav::PlaneCo } barriers(&[tr(twin, all, twin_in, UNORDERED_ACCESS)]); } + if clobbered_gfx || clobbered_cs { + restore_after_internal_pass(list, clobbered_gfx, clobbered_cs); + } } /// D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER | INDEX_BUFFER: valid for buffers only @@ -6578,8 +6940,7 @@ const UNORDERED_ACCESS: u32 = 0x8; /// Whether `res` is a buffer (null / unknown: taken as one – its states are left alone). unsafe fn is_buffer(res: usize) -> bool { - let r = res as *mut c_void; - ID3D12Resource::from_raw_borrowed(&r).is_none_or(|x| x.GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) + super::barrier_groups::is_buffer_cached(res) } /// DMA list #9 Close: as on the PC; a failure is logged (the title stops on it) @@ -6997,6 +7358,7 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES }; note_texture_write(this as usize, r, sub); + super::present::trace_plane_copy("CopyTextureRegion", r, src.as_ref().map_or(0, |s| transmute_copy(&s.pResource))); super::placements::note_use(r); if let Some(s) = src.as_ref() { super::placements::note_use(transmute_copy(&s.pResource)); @@ -7091,7 +7453,9 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds std::mem::forget((d, s)); // borrowed resource pointers return; } - pc::(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); + if !super::format_alias::try_copy_texture_region(this, &d, x, y, z, &s, bx) { + pc::(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); + } std::mem::forget((d, s)); // borrowed resource pointers } @@ -7184,7 +7548,16 @@ unsafe fn clear_uav(this: *mut c_void, slot: usize, gpu: u64, cpu: u64, res: usi return refused(); } }; + if real::is_unaligned_delta_uav(cpu as usize) { + static N: AtomicU64 = AtomicU64::new(0); + if once(&N, 4) { + crate::xlog_warn!("D3D12.X: ClearUnorderedAccessView skipped for unaligned delta buffer UAV (cpu {cpu:#x}, res {res:#x})"); + } + return refused(); + } let Some(res) = uav_clear_resource(res, gpu_slot) else { return refused() }; + // (a clear of a depth twin writes it) + depth_twins_before_work(this, false); pc::(this, slot)(this, gpu, cpu, res, values, n, rects) } @@ -7228,11 +7601,13 @@ unsafe fn trace_resolve(what: &str, dst: usize, src: usize, format: i32, extra: 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 _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListCopy); + let format = super::device_x::pc_target_format(format as u32) as i32; let _c = super::capture::op(this, || { use super::capture as c; Some(c::Op::Resolve { dst: c::describe(dst), dst_sub, src: c::describe(src), src_sub, format, region: None }) }); super::present::note_use(dst, super::present::USE_COPY); + super::present::trace_plane_copy("ResolveSubresource", dst, src); note_texture_write(this as usize, dst, dst_sub); trace_resolve("ResolveSubresource", dst, src, format, ""); pc::(this, PC_RESOLVE_SUBRESOURCE)(this, dst, dst_sub, src, src_sub, format) @@ -7244,6 +7619,7 @@ pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, ds 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 _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListCopy); + let format = super::device_x::pc_target_format(format as u32) as i32; let _c = super::capture::op(this, || { use super::capture as c; let r = rect.as_ref().map(|r| [r.left, r.top, r.right, r.bottom]); @@ -7268,6 +7644,7 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi }); super::present::note_use(dst, super::present::USE_COPY); note_texture_write(this as usize, dst, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES); + super::present::trace_plane_copy("CopyResource", dst, src); super::placements::note_use(dst); super::placements::note_use(src); super::lut3d::wrote(dst, true, || format!("CopyResource from {src:#x}")); @@ -7277,7 +7654,10 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi let (dd, sd) = (real::buffer_delta(dst), real::buffer_delta(src)); if dd == 0 && sd == 0 { note_copy_into(this as usize, dst, 0, u64::MAX); - return pc::(this, PC_COPY_RESOURCE)(this, dst, src); + if !super::format_alias::try_copy_resource(this, dst, src) { + pc::(this, PC_COPY_RESOURCE)(this, dst, src); + } + return; } let n = real::console_buffer(dst).or(real::console_buffer(src)).map_or(0, |b| b.1 as u64); copy_buffer_region_inner(this, dst, 0, src, 0, n); @@ -7962,27 +8342,29 @@ mod tests { let first_raw = first.as_raw(); let second_raw = second.as_raw(); - let initial = cache.acquire(first_raw, small).unwrap(); - assert_eq!(cache.acquire(first_raw, MAX_COPY_SCRATCH), Some(initial)); + let mut dropped = Vec::new(); + let initial = cache.acquire(first_raw, small, &mut dropped).unwrap(); + assert_eq!(cache.acquire(first_raw, MAX_COPY_SCRATCH, &mut dropped), Some(initial)); let scratch = cache.active.get_mut(&(first_raw as usize)).unwrap(); scratch.recorded = false; scratch.marks.insert(fence.as_raw() as usize, (fence.clone(), 1)); - assert!(cache.acquire(first_raw, MAX_COPY_SCRATCH).is_none()); + assert!(cache.acquire(first_raw, MAX_COPY_SCRATCH, &mut dropped).is_none()); fence.Signal(1).unwrap(); - assert_eq!(cache.acquire(first_raw, MAX_COPY_SCRATCH).unwrap().1, MAX_COPY_SCRATCH); + assert_eq!(cache.acquire(first_raw, MAX_COPY_SCRATCH, &mut dropped).unwrap().1, MAX_COPY_SCRATCH); assert_eq!(cache.bytes, MAX_COPY_SCRATCH); - assert!(cache.acquire(second_raw, small).is_none()); + assert!(cache.acquire(second_raw, small, &mut dropped).is_none()); let scratch = cache.active.get_mut(&(first_raw as usize)).unwrap(); scratch.marks.insert(fence.as_raw() as usize, (fence.clone(), 2)); - cache.release(first_raw as usize); + cache.release(first_raw as usize, &mut dropped); assert!(!cache.active.contains_key(&(first_raw as usize))); - assert!(cache.acquire(second_raw, small).is_none()); + assert!(cache.acquire(second_raw, small, &mut dropped).is_none()); fence.Signal(2).unwrap(); - assert!(cache.acquire(second_raw, small).is_some()); + assert!(cache.acquire(second_raw, small, &mut dropped).is_some()); assert_eq!(cache.bytes, small); - cache.release(second_raw as usize); + cache.release(second_raw as usize, &mut dropped); assert_eq!(cache.bytes, 0); + drop(dropped); } } @@ -8005,12 +8387,14 @@ mod tests { let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); let (raw, key) = (list.as_raw(), list.as_raw() as usize); let small = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64; + let mut dropped = Vec::new(); { let mut cache = COPY_SCRATCH.lock().unwrap(); - cache.acquire(raw, small).unwrap(); + cache.acquire(raw, small, &mut dropped).unwrap(); let scratch = cache.active.get_mut(&key).unwrap(); scratch.marks.insert(fence.as_raw() as usize, (fence.clone(), 1)); } + drop(dropped); on_create(raw, alloc.as_raw() as usize, 0, ty); // Read under the lock, assert after it: a failed assert while holding the lock poisons // COPY_SCRATCH, the list's Release hook (`real::cl_release`) then panics on it while the diff --git a/crates/xcl/src/hle/d3d12x/look_stats.rs b/crates/xcl/src/hle/d3d12x/look_stats.rs index 88db61c8df..3026d3a5dd 100644 --- a/crates/xcl/src/hle/d3d12x/look_stats.rs +++ b/crates/xcl/src/hle/d3d12x/look_stats.rs @@ -133,6 +133,63 @@ pub(super) fn own_writes(written: usize, in_look: usize, scanned: usize, unchang OWN.add(4, unchanged as u64); } +/// The parts of the looks besides their write-watch calls (`look_parts`, `hot_blocks`): [looks, +/// ns before the calls (known writes, guarded views, pages found ahead), ns making the hot runs, +/// ns after the calls (blocks made hot, the pages sorted), hot blocks in calls that found pages, +/// then those in calls that found nothing by why they were hot (`HOT_WHY`), then by how long +/// they had been (`HOT_AGES`)]. A call that finds nothing costs a walk of its blocks' page tables: +/// the hot blocks' reasons and ages say what a shorter hot time would leave to the walk. +static PARTS: Sums<13> = Sums::new(); + +/// why a block is hot, the order of `hot_blocks`' counts +pub(super) const HOT_WHY: [&str; 4] = ["a look found it written", "the walk did", "new to the ranges", "committed or placed there"]; +/// the upper ends (ms) of the ages `hot_blocks` counts by; the last has none +pub(super) const HOT_AGES: [u128; 3] = [100, 500, 1000]; + +/// A look's time before its write-watch calls and after them (`deep` only). +pub(super) fn look_parts(before: Duration, after: Duration) { + PARTS.add(0, 1); + PARTS.add(1, before.as_nanos() as u64); + PARTS.add(3, after.as_nanos() as u64); +} + +/// A hot look's runs (`deep` only): `runs` making them, `marking` the blocks it found written +/// made hot, `busy` hot blocks in calls that found pages, and those in calls that found nothing +/// by why (`HOT_WHY`) and how long (`HOT_AGES`) they had been hot. +pub(super) fn hot_blocks(runs: Duration, marking: Duration, busy: u64, idle_why: [u64; 4], idle_age: [u64; 4]) { + PARTS.add(2, runs.as_nanos() as u64); + PARTS.add(3, marking.as_nanos() as u64); + PARTS.add(4, busy); + for k in 0..4 { + PARTS.add(5 + k, idle_why[k]); + PARTS.add(9 + k, idle_age[k]); + } +} + +/// The look parts line of `p` (`PARTS`' sums). +fn parts_line(p: &[u64; 13]) -> String { + let looks = p[0].max(1) as f64; + let idle: u64 = p[5..9].iter().sum(); + let pct = |v: u64| v * 100 / idle.max(1); + let why: Vec = (0..4).map(|k| format!("{} % {}", pct(p[5 + k]), HOT_WHY[k])).collect(); + format!( + "look parts (256 looks): {:.2} ms a look before its calls, {:.2} ms making its hot runs, {:.2} ms after its calls; {:.0} hot blocks a look in calls that found pages, {:.0} in calls that found nothing: {}; hot for <{} ms {} %, <{} ms {} %, <{} ms {} %, longer {} %", + p[1] as f64 / looks / 1e6, + p[2] as f64 / looks / 1e6, + p[3] as f64 / looks / 1e6, + p[4] as f64 / looks, + idle as f64 / looks, + why.join(", "), + HOT_AGES[0], + pct(p[9]), + HOT_AGES[1], + pct(p[10]), + HOT_AGES[2], + pct(p[11]), + pct(p[12]) + ) +} + /// The scans (`scan_split`): [submits, ns gathering, ns scanning, jobs shared, their items, those /// the caller did, ns until a job's first worker began, jobs a worker began] static SCAN: Sums<8> = Sums::new(); @@ -221,6 +278,7 @@ pub(super) fn look(pages: &[usize], ahead: usize, took: Duration, closed: Option (x[5] / 256) >> 20, x[6] / 256 ); + crate::xlog_info!("D3D12.X: {}", parts_line(&PARTS.take())); let c = SCAN.take(); let per = |v: u64, of: u64| v as f64 / of.max(1) as f64; crate::xlog_info!( @@ -362,5 +420,13 @@ mod tests { own_writes(40, 30, 28, 25); own_writes(2, 0, 0, 0); assert_eq!(OWN.take(), [2, 42, 30, 28, 25]); + // (`PARTS` too) + look_parts(Duration::from_micros(30), Duration::from_micros(5)); + hot_blocks(Duration::from_micros(7), Duration::from_micros(2), 9, [1, 0, 2, 1], [0, 3, 0, 1]); + let p = PARTS.take(); + assert_eq!(p, [1, 30_000, 7_000, 7_000, 9, 1, 0, 2, 1, 0, 3, 0, 1]); + let line = parts_line(&p); + assert!(line.contains("4 in calls that found nothing: 25 % a look found it written, 0 % the walk did, 50 % new to the ranges"), "{line}"); + assert!(line.contains("<500 ms 75 %, <1000 ms 0 %, longer 25 %"), "{line}"); } } diff --git a/crates/xcl/src/hle/d3d12x/lut3d.rs b/crates/xcl/src/hle/d3d12x/lut3d.rs index 6f969c56b6..2f049375e0 100644 --- a/crates/xcl/src/hle/d3d12x/lut3d.rs +++ b/crates/xcl/src/hle/d3d12x/lut3d.rs @@ -29,9 +29,23 @@ const DUMPED_MOST: usize = 256; const WRITES_LOGGED: u64 = 12; pub fn on() -> bool { + #[cfg(test)] + if FORCE_ON.load(Ordering::Relaxed) { + return true; + } super::targets::enabled() } +/// Tests: track 3D textures as `XCL_DUMP_TARGETS` does. +#[cfg(test)] +pub static FORCE_ON: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Tests: `res` is one of the 3D textures a dump enumerates. +#[cfg(test)] +pub fn tracked(res: usize) -> bool { + VOLS.lock().unwrap().contains_key(&res) +} + /// Whether `created` is to be told of a resource made (`on`, or `XCL_CAPTURE_FRAME`). pub fn created_on() -> bool { on() || super::capture::enabled() diff --git a/crates/xcl/src/hle/d3d12x/mirror.rs b/crates/xcl/src/hle/d3d12x/mirror.rs new file mode 100644 index 0000000000..b47448116c --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/mirror.rs @@ -0,0 +1,774 @@ +//! Mirrors without the title's rays: light for a mirror's view. +//! +//! A retail title draws what a mirror shows as a second view of its own: the scene again from +//! behind the glass, into images of the view's size, lit by one full-screen draw for each kind of +//! material (`PS_MIRROR_PBR_MATERIAL_*`) into an image of its own, then the sky and the air +//! drawn into the same image (`ps_mirror_volumetric_sky`). That lighting takes its indirect +//! light from the probes the title's rays fill: without the rays the view has the sun's direct +//! light alone, and a room is black in it. +//! +//! So the light around times each texel's own colour is added to that lit image. The light +//! around is what the stand-in for the indirect light (`ambient`) gives the room itself: the +//! mean of the light gathered at its points (or of its cells, when the light is not made in +//! space) with a fifth of the picture's slow mean, at least the sky's level at its share +//! (`XCL_AMBIENT_SKY`) – so a wall in the mirror is about as bright as the wall beside it. It has +//! no direction: the view is seen from behind the glass, where the picture's points are not. The +//! colour is the view's own: at the draw that makes the view's material mask +//! (`ps_generate_material_mask`), the 8-bit colour target of its size drawn into last before it. +//! Where the view drew nothing that colour is black and nothing is added. +//! +//! Neo adds it right before the sky's draw. A draw here is bound in `bind` before XCL sees it +//! (`list_x::prepare_draw`), and a pass of XCL's cannot be put between that binding and the draw, +//! so the pass goes right after the sky's draw, at the next point between the title's commands +//! where XCL records (its next barriers, render targets or the list's close) – before the title +//! moves the lit image to be read. Only the air the sky's draw lays over the surfaces is then not +//! laid over the added light. +//! +//! `XCL_MIRROR_AMBIENT=` of that light (default 1; `0`: off). Nothing is added while +//! the stand-in is off or the title's rays run (`ambient::active`). +//! +//! Ported from VIctory-Neo (https://github.com/KyleS98/VIctory-Neo, GPL-3.0-or-later): +//! `crates/victory-gpu/src/mirror.rs` of a3af274 ("Mirrors: the mirror's view is given the light +//! around") and 9b61dc9 (its programs built in a test) – the programs' parts by name, the switch, +//! and the pass and its programs, adapted to XCL's level buffer, objects and state. + +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, RwLock}; + +use windows::core::{Interface, PCSTR}; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// A pixel program's part in a mirror's view. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Part { + /// makes the view's material mask from its colour and depth + Mask, + /// draws the sky into the view's lit image, after the materials' lighting + Sky, +} + +/// The pixel program's part, by its name in the container. +fn part(container: &[u8]) -> Option { + let has = |name: &[u8]| container.windows(name.len()).any(|w| w == name); + if has(b"ps_mirror_volumetric_sky") { + Some(Part::Sky) + } else if has(b"ps_generate_material_mask") { + Some(Part::Mask) + } else { + None + } +} + +/// The multiple of the light around a mirror's view is given (`XCL_MIRROR_AMBIENT`); 0: none. +pub(super) fn level() -> f32 { + static LEVEL: OnceLock = OnceLock::new(); + *LEVEL.get_or_init(|| parse(std::env::var("XCL_MIRROR_AMBIENT").ok().as_deref())) +} + +fn parse(set: Option<&str>) -> f32 { + match set.map(str::trim) { + None | Some("") => 1.0, + Some(v) => v.parse::().ok().filter(|l| l.is_finite() && *l >= 0.0).unwrap_or(1.0).min(16.0), + } +} + +/// The graphics pipelines (objects as the title has them) whose pixel program has a part. +static PARTS: RwLock>> = RwLock::new(None); +static ANY: AtomicBool = AtomicBool::new(false); + +/// A graphics pipeline `pso` was made with the pixel program `ps` (the console's container). +pub(super) fn note_graphics_pso(pso: usize, ps: Option<&[u8]>) { + if pso == 0 || level() == 0.0 { + return; + } + match ps.and_then(part) { + Some(p) => { + PARTS.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, p); + ANY.store(true, Ordering::Release); + static SAID: AtomicU32 = AtomicU32::new(0); + if SAID.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!("D3D12.X: mirror: pipeline {pso:#x} draws a mirror view's {p:?}"); + } + } + // (another pipeline made at the address of one released) + None if ANY.load(Ordering::Relaxed) => { + if let Some(m) = PARTS.write().unwrap().as_mut() { + m.remove(&pso); + } + } + None => {} + } +} + +/// Whether a pipeline with a part was made: the gate of the draw hooks. +pub(super) fn any() -> bool { + ANY.load(Ordering::Relaxed) +} + +/// The part of the pipeline `pso` (the title's object, or what it resolves to). +pub(super) fn part_of(pso: usize) -> Option { + if pso == 0 { + return None; + } + let g = PARTS.read().unwrap(); + let m = g.as_ref()?; + m.get(&pso).or_else(|| m.get(&super::pso_async::resolve(pso))).copied() +} + +/// 8-bit colour formats (R8G8B8A8 TYPELESS, UNORM, UNORM_SRGB) and their rank as the colour of a +/// view's surfaces (the sRGB one first). +fn colour_rank(format: i32) -> Option { + match format { + 29 => Some(0), + 27 => Some(1), + 28 => Some(2), + _ => None, + } +} + +/// 2D 8-bit colour targets bound lately (newest first): (resource, width, height, format). +static TARGETS: Mutex> = Mutex::new(Vec::new()); +/// The colour of a view's surfaces as the last material mask of each size was made after it: +/// ((width, height), resource, frame). +static COLOUR: Mutex> = Mutex::new(Vec::new()); + +fn frame() -> u64 { + super::present::counters().1 +} + +/// (width, height, format) of a single-sample 2D texture `res`. +unsafe fn shape(res: usize) -> Option<(u32, u32, i32)> { + let r = res as *mut c_void; + let d = ID3D12Resource::from_raw_borrowed(&r)?.GetDesc(); + (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && d.SampleDesc.Count == 1 && d.DepthOrArraySize == 1).then_some((d.Width as u32, d.Height, d.Format.0)) +} + +/// The title bound the render targets `rts` (resources). +pub(super) unsafe fn note_targets(rts: &[usize]) { + for &r in rts.iter().filter(|&&r| r != 0) { + let Some((w, h, f)) = shape(r).filter(|s| colour_rank(s.2).is_some()) else { continue }; + let mut g = TARGETS.lock().unwrap(); + g.retain(|t| t.0 != r); + g.insert(0, (r, w, h, f)); + g.truncate(8); + } +} + +/// The colour among `targets` (newest first) for a mask drawn into `current` (its targets, the +/// first one's size `size`): of that size, not one of `current`, the best rank, the newest. +fn pick_colour(targets: &[(usize, u32, u32, i32)], current: &[usize], size: Option<(u32, u32)>) -> Option<(usize, (u32, u32))> { + let fits = |t: &&(usize, u32, u32, i32)| !current.contains(&t.0) && size.is_none_or(|s| (t.1, t.2) == s); + let first = targets.iter().find(fits)?; + let size = (first.1, first.2); + targets.iter().filter(fits).filter(|t| (t.1, t.2) == size).min_by_key(|t| colour_rank(t.3)).map(|t| (t.0, size)) +} + +/// A draw that makes a view's material mask, into the targets `current` (resources). +pub(super) unsafe fn at_mask(current: &[usize]) { + let size = current.first().and_then(|&r| shape(r)).map(|s| (s.0, s.1)); + let picked = pick_colour(&TARGETS.lock().unwrap(), current, size); + let Some((colour, size)) = picked else { return }; + let mut g = COLOUR.lock().unwrap(); + g.retain(|c| c.0 != size); + g.push((size, colour, frame())); + g.truncate(4); +} + +/// The pass owed a list (`at_sky`), recorded at its next point between the title's commands. +pub(super) struct Pending { + /// the render target view of the lit image, its resource and format + rtv: usize, + lit: usize, + format: DXGI_FORMAT, + size: (u32, u32), + /// the colour of the view's surfaces, its SRV format and whether it is decoded in the pass + colour: usize, + view: DXGI_FORMAT, + decode: bool, + rect: RECT, +} + +/// The format a pass of ours draws into a lit image of `format` with (None: not one it can). +fn lit_format(format: i32) -> Option { + Some(match format { + // R16G16B16A16 FLOAT / TYPELESS, R11G11B10_FLOAT, R32G32B32A32 FLOAT / TYPELESS + 10 | 9 => DXGI_FORMAT_R16G16B16A16_FLOAT, + 26 => DXGI_FORMAT_R11G11B10_FLOAT, + 2 | 1 => DXGI_FORMAT_R32G32B32A32_FLOAT, + _ => return None, + }) +} + +/// A draw of the sky into a view's lit image (render target view `rtv`, the draw's scissor +/// `rect`): the pass that gives the view the light around, owed, if one can be made. +pub(super) unsafe fn at_sky(rtv: usize, rect: Option) -> Option { + if level() == 0.0 || !super::ambient::active() { + return None; + } + let lit = super::present::rtv_resource(rtv)?; + let (w, h, f) = shape(lit)?; + let Some(format) = lit_format(f) else { + static SAID: AtomicBool = AtomicBool::new(false); + if !SAID.swap(true, Ordering::Relaxed) { + crate::xlog_info!("D3D12.X: mirror: a view's lit image of format {f} is not one the light around is added to"); + } + return None; + }; + let now = frame(); + let colour = COLOUR.lock().unwrap().iter().find(|c| c.0 == (w, h) && now.saturating_sub(c.2) <= 1).map(|c| c.1)?; + if colour == lit { + return None; + } + // (still named by a render target view: not released since, and still of the view's size) + let live = super::present::view_resource(colour)?; + let (cw, ch, cf) = shape(live.as_raw() as usize)?; + if (cw, ch) != (w, h) { + return None; + } + let (view, decode) = match cf { + 27 | 29 => (DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, false), + 28 => (DXGI_FORMAT_R8G8B8A8_UNORM, true), + _ => return None, + }; + let rect = rect.unwrap_or(RECT { left: 0, top: 0, right: w as i32, bottom: h as i32 }); + Some(Pending { rtv, lit, format, size: (w, h), colour, view, decode, rect }) +} + +/// What the pass reads and writes: 4 constants, then a table of the colour (t0) and the level +/// buffer (u1), read in both programs. +const SOURCE: &str = r#" +cbuffer Set : register(b0) { float level; float decode; float sky_share; float sky_ready; }; +Texture2D colour : register(t0); +RWStructuredBuffer sky_level : register(u1); +// The level buffer as `ambient` lays it out: the sky's level, the slow mean of the cells, 64x36 +// cells, their places, then 160x90 points of three entries, each colour's light in `w`. +#define CELL_AT 2 +#define POINT_AT 4610 +#define PX 160 +struct Corner { + float4 at : SV_Position; + nointerpolation float3 around : AROUND; +}; +float3 finite(float3 c) { + return all(isfinite(c)) ? max(c, 0.0) : float3(0.0, 0.0, 0.0); +} +// The light around, once for the triangle: the mean of one point (or cell) in a hundred or so, +// with a fifth of the picture's slow mean, at least the sky's level at its share. +Corner corner(uint i : SV_VertexID) { + Corner c; + c.at = float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0); + float4 mean = sky_level[1]; + float3 around = float3(0.0, 0.0, 0.0); + if (mean.a > 0.0) { + float3 points = float3(0.0, 0.0, 0.0), cells = float3(0.0, 0.0, 0.0); + [loop] + for (uint y = 0; y < 9; y++) { + [loop] + for (uint x = 0; x < 16; x++) { + uint at0 = POINT_AT + ((y * 10 + 5) * PX + x * 10 + 5) * 3; + points += finite(float3(sky_level[at0].w, sky_level[at0 + 1].w, sky_level[at0 + 2].w)); + cells += finite(sky_level[CELL_AT + (y * 4 + 2) * 64 + x * 4 + 2].rgb); + } + } + // (the points are gathered while the light is made in space; else the cells) + float3 room = dot(points, float3(1.0, 1.0, 1.0)) > 0.0 ? points / 144.0 : cells / 144.0; + around = clamp(lerp(room, finite(mean.rgb), 0.2), 0.0, 16.0); + } + float3 sky = sky_ready > 0.0 ? clamp(finite(sky_level[0].rgb), 0.0, 0.65) : float3(0.0, 0.0, 0.0); + c.around = max(around, sky * sky_share) * level; + return c; +} +float4 light(Corner at) : SV_Target { + float3 c = max(colour.Load(int3(int2(at.at.xy), 0)).rgb, 0.0); + if (decode > 0.0) c = pow(c, 2.2); + return float4(c * at.around, 0.0); +} +"#; + +fn compile(entry: &str, target: &str) -> Option> { + if let Some(b) = crate::gpu::recomp::dxc::compile_sm6_first(SOURCE, entry, target) { + return Some(b); + } + unsafe { + let mut blob = None; + let (e, t) = (format!("{entry}\0"), format!("{target}\0")); + let r = D3DCompile(SOURCE.as_ptr() as *const c_void, SOURCE.len(), PCSTR::null(), None, None, PCSTR(e.as_ptr()), PCSTR(t.as_ptr()), 0, 0, &mut blob, None); + match (r, blob) { + (Ok(()), Some(b)) => Some(std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()).to_vec()), + _ => None, + } + } +} + +/// The pass's root signature, serialized: [0] 4 constants (b0), [1] a table of t0 and u1. +fn root_signature() -> Option { + let ranges = [ + D3D12_DESCRIPTOR_RANGE { RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, NumDescriptors: 1, BaseShaderRegister: 0, RegisterSpace: 0, OffsetInDescriptorsFromTableStart: 0 }, + D3D12_DESCRIPTOR_RANGE { RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_UAV, NumDescriptors: 1, BaseShaderRegister: 1, RegisterSpace: 0, OffsetInDescriptorsFromTableStart: 1 }, + ]; + let params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 4 } }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: ranges.len() as u32, pDescriptorRanges: ranges.as_ptr() } }, + }, + ]; + let mut blob = None; + unsafe { D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC { NumParameters: params.len() as u32, pParameters: params.as_ptr(), ..Default::default() }, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).ok()? }; + blob +} + +/// Method `slot` of the D3D12 object `obj`: past XCL's hooks when XCL adopted it +/// (`real::orig_fn`), as it is otherwise. +unsafe fn method(obj: *mut c_void, slot: usize) -> usize { + if super::real::is_adopted(obj) { + super::real::orig_fn(obj, slot) + } else { + *(*(obj as *const *const usize)).add(slot) + } +} + +/// Descriptor groups (t0, u1) of a pass in its heap, used in turn. +const GROUPS: u32 = 64; + +struct Pass { + rs: ID3D12RootSignature, + vs: Vec, + ps: Vec, + /// one pipeline for each format of a lit image met + made: Mutex)>>, + heap: ID3D12DescriptorHeap, + cpu: usize, + gpu: u64, + step: u32, + next: AtomicU32, +} + +// D3D12 objects are free-threaded +unsafe impl Send for Pass {} +unsafe impl Sync for Pass {} + +static PASSES: Mutex>>>> = Mutex::new(None); + +/// The pass on `dev`, made the first time (None: it could not be). +unsafe fn pass_on(dev: *mut c_void) -> Option> { + let mut g = PASSES.lock().unwrap(); + g.get_or_insert_with(HashMap::new) + .entry(dev as usize) + .or_insert_with(|| { + let p = make_pass(dev).map(Arc::new); + if p.is_none() { + crate::xlog_warn!("D3D12.X: mirror: the pass that gives a mirror's view the light around could not be made"); + } + p + }) + .clone() +} + +unsafe fn make_pass(dev: *mut c_void) -> Option { + let (vs, ps, blob) = (compile("corner", "vs_5_0")?, compile("light", "ps_5_0")?, root_signature()?); + type CreateRs = unsafe extern "system" fn(*mut c_void, u32, *const c_void, usize, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + type CreateHeap = unsafe extern "system" fn(*mut c_void, *const D3D12_DESCRIPTOR_HEAP_DESC, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + type Increment = unsafe extern "system" fn(*mut c_void, D3D12_DESCRIPTOR_HEAP_TYPE) -> u32; + let create_rs: CreateRs = std::mem::transmute(method(dev, 16)); + let create_heap: CreateHeap = std::mem::transmute(method(dev, 14)); + let increment: Increment = std::mem::transmute(method(dev, 15)); + let mut rs = std::ptr::null_mut(); + if create_rs(dev, 0, blob.GetBufferPointer(), blob.GetBufferSize(), &ID3D12RootSignature::IID as *const _ as *const _, &mut rs) < 0 || rs.is_null() { + return None; + } + let rs = ID3D12RootSignature::from_raw(rs); + let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + let desc = D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: 2 * GROUPS, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }; + let mut heap = std::ptr::null_mut(); + if create_heap(dev, &desc, &ID3D12DescriptorHeap::IID as *const _ as *const _, &mut heap) < 0 || heap.is_null() { + return None; + } + let heap = ID3D12DescriptorHeap::from_raw(heap); + let (cpu, gpu) = (heap.GetCPUDescriptorHandleForHeapStart().ptr, heap.GetGPUDescriptorHandleForHeapStart().ptr); + Some(Pass { rs, vs, ps, made: Mutex::default(), heap, cpu, gpu, step: increment(dev, kind), next: AtomicU32::new(0) }) +} + +impl Pass { + /// The pipeline that adds into a target of `format` on `dev`. + unsafe fn pipeline(&self, dev: *mut c_void, format: DXGI_FORMAT) -> Option { + let mut made = self.made.lock().unwrap(); + if let Some((_, p)) = made.iter().find(|m| m.0 == format.0) { + return p.clone(); + } + let p = self.make(dev, format); + if p.is_none() { + crate::xlog_warn!("D3D12.X: mirror: no pipeline to add the light around into a lit image of format {}", format.0); + } + made.push((format.0, p.clone())); + p + } + + unsafe fn make(&self, dev: *mut c_void, format: DXGI_FORMAT) -> Option { + let code = |b: &[u8]| D3D12_SHADER_BYTECODE { pShaderBytecode: b.as_ptr() as *const c_void, BytecodeLength: b.len() }; + let mut blend = D3D12_BLEND_DESC::default(); + // what is there, plus ours (its alpha kept) + blend.RenderTarget[0] = D3D12_RENDER_TARGET_BLEND_DESC { + BlendEnable: true.into(), + SrcBlend: D3D12_BLEND_ONE, + DestBlend: D3D12_BLEND_ONE, + BlendOp: D3D12_BLEND_OP_ADD, + SrcBlendAlpha: D3D12_BLEND_ZERO, + DestBlendAlpha: D3D12_BLEND_ONE, + BlendOpAlpha: D3D12_BLEND_OP_ADD, + RenderTargetWriteMask: 0xF, + ..Default::default() + }; + let mut formats = [DXGI_FORMAT_UNKNOWN; 8]; + formats[0] = format; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(self.rs.clone())), + VS: code(&self.vs), + PS: code(&self.ps), + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() }, + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { DepthEnable: false.into(), StencilEnable: false.into(), ..Default::default() }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: formats, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + type CreateGfx = unsafe extern "system" fn(*mut c_void, *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + let create: CreateGfx = std::mem::transmute(method(dev, 10)); + let mut p = std::ptr::null_mut(); + let hr = create(dev, &desc, &ID3D12PipelineState::IID as *const _ as *const _, &mut p); + ManuallyDrop::drop(&mut desc.pRootSignature); + (hr >= 0 && !p.is_null()).then(|| ID3D12PipelineState::from_raw(p)) + } +} + +/// What one pass draws: into the render target view `rtv` (format `format`, `size`), within +/// `rect`, the colour `colour` (viewed as `view`, decoded with `decode`) times the light around +/// from `level_buf` (`elements` float4s) times `multiple`, the sky's level at `sky_share` when +/// `sky_ready`. +struct Draw<'a> { + rtv: usize, + format: DXGI_FORMAT, + size: (u32, u32), + rect: RECT, + colour: &'a ID3D12Resource, + view: DXGI_FORMAT, + decode: bool, + level_buf: &'a ID3D12Resource, + elements: u32, + multiple: f32, + sky_share: f32, + sky_ready: bool, +} + +/// Records `d` on `list` (of the device `dev`) with `pass`: it leaves a view heap, a root +/// signature, a pipeline, a render target, a viewport, a scissor and a topology of its own on +/// the list. The lit image is in RENDER_TARGET, the colour readable by pixel programs, the level +/// buffer in UNORDERED_ACCESS (or COMMON). False: nothing was recorded. +unsafe fn record(list: *mut c_void, dev: *mut c_void, pass: &Pass, d: &Draw) -> bool { + let Some(pso) = pass.pipeline(dev, d.format) else { return false }; + let g = pass.next.fetch_add(1, Ordering::Relaxed) % GROUPS; + let (cpu, gpu) = (pass.cpu + (2 * g * pass.step) as usize, pass.gpu + (2 * g * pass.step) as u64); + type CreateSrv = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, usize); + type CreateUav = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + let create_srv: CreateSrv = std::mem::transmute(method(dev, 18)); + let create_uav: CreateUav = std::mem::transmute(method(dev, 19)); + let srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: d.view, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, ..Default::default() } }, + }; + let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: d.elements, StructureByteStride: 16, ..Default::default() } }, + }; + create_srv(dev, d.colour.as_raw(), &srv, cpu); + create_uav(dev, d.level_buf.as_raw(), std::ptr::null_mut(), &uav, cpu + pass.step as usize); + + let barrier: unsafe extern "system" fn(*mut c_void, u32, *const [u32; 8]) = std::mem::transmute(method(list, 26)); + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(method(list, 28)); + let set_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(method(list, 30)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(method(list, 25)); + let set_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(method(list, 32)); + let set_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(method(list, 36)); + let set_targets: unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize) = std::mem::transmute(method(list, 46)); + let set_viewports: unsafe extern "system" fn(*mut c_void, u32, *const D3D12_VIEWPORT) = std::mem::transmute(method(list, 21)); + let set_scissors: unsafe extern "system" fn(*mut c_void, u32, *const RECT) = std::mem::transmute(method(list, 22)); + let set_topology: unsafe extern "system" fn(*mut c_void, u32) = std::mem::transmute(method(list, 20)); + let draw: unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32) = std::mem::transmute(method(list, 12)); + + // (what `ambient` wrote into the level buffer, first) + let level = d.level_buf.as_raw() as usize; + barrier(list, 1, &[2, 0, level as u32, (level as u64 >> 32) as u32, 0, 0, 0, 0]); + let heap = pass.heap.as_raw() as usize; + set_heaps(list, 1, &heap); + set_rs(list, pass.rs.as_raw()); + set_pso(list, pso.as_raw()); + let consts = [d.multiple.to_bits(), if d.decode { 1.0f32 } else { 0.0 }.to_bits(), d.sky_share.to_bits(), if d.sky_ready { 1.0f32 } else { 0.0 }.to_bits()]; + set_consts(list, 0, 4, consts.as_ptr(), 0); + set_table(list, 1, gpu); + set_targets(list, 1, &d.rtv, 0, std::ptr::null()); + let vp = D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: d.size.0 as f32, Height: d.size.1 as f32, MinDepth: 0.0, MaxDepth: 1.0 }; + set_viewports(list, 1, &vp); + set_scissors(list, 1, &d.rect); + set_topology(list, windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32); + draw(list, 3, 1, 0, 0); + true +} + +/// Passes recorded. +static LIT: AtomicU64 = AtomicU64::new(0); + +/// Records the pass `p` owed `list`. True: it was, and it left state of its own on the list +/// (`record`): the caller sets the title's again (`list_x::restore_after_internal_pass`). +pub(super) unsafe fn light(list: *mut c_void, p: &Pending) -> bool { + let multiple = level(); + // (both still named by a view: the title has not released them) + let (Some(lit), Some(colour)) = (super::present::view_resource(p.lit), super::present::view_resource(p.colour)) else { return false }; + let Some(dev) = super::list_x::device_of_list(list) else { return false }; + let Some((level_buf, elements, sky_share, sky_ready)) = super::ambient::level_for_mirror(&dev) else { return false }; + let Some(pass) = pass_on(dev.as_raw()) else { return false }; + let d = Draw { rtv: p.rtv, format: p.format, size: p.size, rect: p.rect, colour: &colour, view: p.view, decode: p.decode, level_buf: &level_buf, elements, multiple, sky_share, sky_ready }; + if !record(list, dev.as_raw(), &pass, &d) { + return false; + } + drop(lit); + let n = LIT.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 3 || n.is_power_of_two() { + let r = p.rect; + crate::xlog_info!( + "D3D12.X: mirror: a mirror's view is given the light around (XCL_MIRROR_AMBIENT={multiple}): lit image {:#x} ({}x{}, format {}), colour {:#x} (view format {}), rect [{}, {}, {}, {}] ({n} so far)", + p.lit, + p.size.0, + p.size.1, + p.format.0, + p.colour, + p.view.0, + r.left, + r.top, + r.right, + r.bottom + ); + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parts_by_name() { + assert_eq!(part(b"..ps_mirror_volumetric_sky_c35156a8_Wrapped.."), Some(Part::Sky)); + assert_eq!(part(b"..ps_generate_material_mask_e3b05401_Wrapped.."), Some(Part::Mask)); + // the other mirror programs are none of ours + assert_eq!(part(b"..ps_mirror_volumetric_scattering_transmittance_c35156a8.."), None); + assert_eq!(part(b"..ps_mirror_taa_default.."), None); + assert_eq!(part(b"..PS_MIRROR_PBR_MATERIAL_STANDARD.."), None); + } + + #[test] + fn levels() { + assert_eq!(parse(None), 1.0); + assert_eq!(parse(Some("")), 1.0); + assert_eq!(parse(Some("0")), 0.0); + assert_eq!(parse(Some(" 2.5 ")), 2.5); + assert_eq!(parse(Some("-1")), 1.0); + assert_eq!(parse(Some("x")), 1.0); + assert_eq!(parse(Some("100")), 16.0); + } + + #[test] + fn the_colour_is_the_newest_8_bit_target_of_the_masks_size_srgb_first() { + let t = |r: usize, w: u32, h: u32, f: i32| (r, w, h, f); + // newest first: the mask's own target, a UNORM and an sRGB one of the view's size, one + // of the picture's size + let targets = [t(1, 1280, 736, 28), t(2, 1280, 736, 28), t(3, 1280, 736, 29), t(4, 1280, 720, 29)]; + assert_eq!(pick_colour(&targets, &[1], Some((1280, 736))), Some((3, (1280, 736))), "the sRGB one before the newer UNORM one"); + assert_eq!(pick_colour(&targets, &[1, 3], Some((1280, 736))), Some((2, (1280, 736)))); + assert_eq!(pick_colour(&targets, &[], Some((1280, 720))), Some((4, (1280, 720)))); + assert_eq!(pick_colour(&targets, &[], Some((640, 360))), None, "none of the mask's size"); + // a mask with no colour target: the newest one's size + assert_eq!(pick_colour(&targets, &[], None), Some((3, (1280, 736)))); + assert_eq!(lit_format(10), Some(DXGI_FORMAT_R16G16B16A16_FLOAT)); + assert_eq!(lit_format(26), Some(DXGI_FORMAT_R11G11B10_FLOAT)); + assert_eq!(lit_format(28), None); + } + + /// Both programs of the pass compile with D3DCompile, and its root signature serializes + /// (VIctory-Neo 9b61dc9: the pass's programs are built in a test). + #[test] + fn the_pass_builds() { + assert!(compile("corner", "vs_5_0").is_some(), "the vertex program"); + assert!(compile("light", "ps_5_0").is_some(), "the pixel program"); + assert!(root_signature().is_some()); + } + + /// An IEEE half as f32. + fn half(h: u16) -> f32 { + let (s, e, m) = ((h >> 15) as u32, ((h >> 10) & 0x1F) as i32, (h & 0x3FF) as f32); + let v = match e { + 0 => m * 2f32.powi(-24), + 31 => f32::INFINITY, + _ => (1.0 + m / 1024.0) * 2f32.powi(e - 15), + }; + if s == 1 { -v } else { v } + } + + /// On the software adapter: a 4x4 lit image holding 0.1, the view's colour (0.5, 0.25, 1) in + /// an sRGB target, a level buffer whose points hold 1 and whose slow mean is 0.5: within the + /// left half the pass adds the colour times lerp(1, 0.5, 0.2) = 0.9, the right half and the + /// alpha stay as they were. + #[test] + fn gpu_the_light_around_is_added_into_the_lit_image_within_the_rect() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let mut dev: Option = None; + let Ok(warp) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)).and_then(|f| f.EnumWarpAdapter::()) else { + return crate::gpu::recomp::runner::skip_test("no WARP device"); + }; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return crate::gpu::recomp::runner::skip_test("no WARP device"); + } + let dev = dev.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let heap = |ty| D3D12_HEAP_PROPERTIES { Type: ty, ..Default::default() }; + let texture = |format, state| { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 4, + Height: 4, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&heap(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap(); + r.unwrap() + }; + let buffer = |ty, bytes: u64, flags, state| { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&heap(ty), D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap(); + r.unwrap() + }; + let lit = texture(DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_RESOURCE_STATE_RENDER_TARGET); + let colour = texture(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, D3D12_RESOURCE_STATE_RENDER_TARGET); + // the level buffer as `ambient` lays it out + const ELEMENTS: u32 = 2 + 2 * 64 * 36 + 3 * 160 * 90; + let mut words = vec![[0f32; 4]; ELEMENTS as usize]; + words[1] = [0.5, 0.5, 0.5, 1.0]; + words[2..2306].iter_mut().for_each(|c| *c = [0.25, 0.25, 0.25, 1.0]); + words[4610..].iter_mut().for_each(|p| *p = [0.0, 0.0, 0.0, 1.0]); + let bytes = (ELEMENTS as u64 * 16).next_multiple_of(256); + let up = buffer(D3D12_HEAP_TYPE_UPLOAD, bytes, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::copy_nonoverlapping(words.as_ptr() as *const u8, p as *mut u8, words.len() * 16); + up.Unmap(0, None); + let level_buf = buffer(D3D12_HEAP_TYPE_DEFAULT, bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + let readback = buffer(D3D12_HEAP_TYPE_READBACK, 256 * 4, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + let rtvs: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 2, ..Default::default() }).unwrap(); + let rtv0 = rtvs.GetCPUDescriptorHandleForHeapStart(); + let rtv1 = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: rtv0.ptr + dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize }; + dev.CreateRenderTargetView(&lit, None, rtv0); + dev.CreateRenderTargetView(&colour, None, rtv1); + let tr = |r: &ID3D12Resource, before, after| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(r), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + ..Default::default() + }; + + list.ClearRenderTargetView(rtv0, &[0.1, 0.1, 0.1, 1.0], None); + list.ClearRenderTargetView(rtv1, &[0.5, 0.25, 1.0, 1.0], None); + list.CopyBufferRegion(&level_buf, 0, &up, 0, bytes); + list.ResourceBarrier(&[ + tr(&colour, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE), + tr(&level_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]); + let pass = make_pass(dev.as_raw()).expect("the pass"); + let d = Draw { + rtv: rtv0.ptr, + format: DXGI_FORMAT_R16G16B16A16_FLOAT, + size: (4, 4), + rect: RECT { left: 0, top: 0, right: 2, bottom: 4 }, + colour: &colour, + view: DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, + decode: false, + level_buf: &level_buf, + elements: ELEMENTS, + multiple: 1.0, + sky_share: 0.35, + sky_ready: false, + }; + assert!(record(list.as_raw(), dev.as_raw(), &pass, &d), "recorded"); + list.ResourceBarrier(&[tr(&lit, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: DXGI_FORMAT_R16G16B16A16_FLOAT, Width: 4, Height: 4, Depth: 1, RowPitch: 256 }, + }; + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&lit), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + let start = std::time::Instant::now(); + while fence.GetCompletedValue() < 1 { + assert!(start.elapsed().as_secs() < 20, "the software adapter did not finish"); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).unwrap(); + let texel = |x: usize, y: usize| -> [f32; 4] { std::array::from_fn(|c| half(*(p as *const u16).add(y * 128 + x * 4 + c))) }; + let (inside, outside) = (texel(1, 2), texel(3, 1)); + readback.Unmap(0, None); + let want = [0.1 + 0.5 * 0.9, 0.1 + 0.25 * 0.9, 0.1 + 1.0 * 0.9, 1.0]; + for c in 0..4 { + assert!((inside[c] - want[c]).abs() < 0.02, "inside the rect: {inside:?}, wanted {want:?}"); + assert!((outside[c] - [0.1, 0.1, 0.1, 1.0][c]).abs() < 0.002, "outside it: {outside:?}"); + } + drop(alloc); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 943bfec115..dc54dea659 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -14,13 +14,15 @@ pub use alloc_pool::AllocatorSubmitStats; mod barrier_groups; mod build_queue; pub mod bind; +mod bvh_spare; mod bvh_want; mod capture; pub mod console_heap; pub mod console_list; pub mod clamp; +mod ambient; mod depth_uav; -mod gpu_awake; +mod format_alias; pub mod device_x; pub mod dxgi_device; mod cpu_writes; @@ -29,16 +31,20 @@ mod fence_x; pub mod file_reads; pub mod frame; pub(crate) mod gfx_records; +mod gpu_awake; mod gpu_profile; mod gpu_times; pub mod guard; +mod indexed; mod indirect_guard; mod late_release; +mod left_out; pub mod layout; pub mod list_x; mod look_stats; mod lut3d; pub mod memory_report; +mod mirror; pub mod null; mod placements; pub mod present; @@ -62,6 +68,7 @@ pub mod view_want; mod uma_driver; mod used_journal; pub mod vram; +mod vram_small; mod worker_pool; use std::ffi::c_void; diff --git a/crates/xcl/src/hle/d3d12x/placements.rs b/crates/xcl/src/hle/d3d12x/placements.rs index 5dda38c2d4..ef3e635c8f 100644 --- a/crates/xcl/src/hle/d3d12x/placements.rs +++ b/crates/xcl/src/hle/d3d12x/placements.rs @@ -12,10 +12,10 @@ //! before (`late_release::hold_unmap`), and come back when the title uses it again (a barrier or a //! copy of it: `note_use`) or releases the newer ones over it while it still holds it. -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::ffi::c_void; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; -use std::sync::Mutex; +use std::sync::{Mutex, RwLock}; use std::time::Instant; use windows::core::Interface; @@ -186,6 +186,8 @@ struct Registry { seq: u64, /// the superseded ones the title holds (`SUPERSEDED`) unmapped: usize, + /// Pending `(res, superseded)` updates to `SUPERSEDED_IDS`, flushed in `sync_superseded`. + superseded_delta: Vec<(usize, bool)>, } /// What a placement found (`Registry::place`). @@ -256,6 +258,7 @@ impl Registry { old.under.push(res); p.over.push(o); self.unmapped += 1; + self.superseded_delta.push((o, true)); out.victims.push(o); } } @@ -277,6 +280,7 @@ impl Registry { if !p.mapped { // (its tiles go with it: `vram::forget`) self.unmapped -= 1; + self.superseded_delta.push((res, false)); } let (over, under) = (std::mem::take(&mut p.over), std::mem::take(&mut p.under)); for n in under { @@ -307,6 +311,7 @@ impl Registry { if newer.is_empty() { old.mapped = true; self.unmapped -= 1; + self.superseded_delta.push((o, false)); remap.push(o); } else { old.under = newer; @@ -337,6 +342,7 @@ impl Registry { let Some(p) = self.live.get_mut(&res).filter(|p| !p.mapped && !p.released) else { return Vec::new() }; p.mapped = true; self.unmapped -= 1; + self.superseded_delta.push((res, false)); let under = std::mem::take(&mut p.under); for n in &under { if let Some(q) = self.live.get_mut(n) { @@ -482,6 +488,25 @@ unsafe fn map_again(remap: &[usize]) -> Vec { held } +/// Leaf lock mirroring currently superseded target resource pointers so `note_use` / `note_uses` +/// (called on every draw/dispatch/barrier) skip `REGISTRY.lock()` with a shared read lock. +static SUPERSEDED_IDS: RwLock>> = RwLock::new(None); + +fn sync_superseded(r: &mut Registry) { + SUPERSEDED.store(r.unmapped, Ordering::Relaxed); + if !r.superseded_delta.is_empty() { + let mut g = SUPERSEDED_IDS.write().unwrap_or_else(|e| e.into_inner()); + let set = g.get_or_insert_with(HashSet::new); + for (res, sup) in r.superseded_delta.drain(..) { + if sup { + set.insert(res); + } else { + set.remove(&res); + } + } + } +} + /// Texture `res` placed at title address `va` on `pages` (`[start, end)`: its own title pages), /// its tiles mapped. Returns the older targets it supersedes: their tiles are to leave the shared /// pages once the queues are past the work submitted before (`late_release::hold_unmap`). @@ -492,7 +517,7 @@ pub(super) fn placed(res: usize, va: usize, pages: (usize, usize), backing: Back let mut g = REGISTRY.lock().unwrap(); let r = g.get_or_insert_with(Registry::default); let out = r.place(res, va, pages, backing, kind, desc, Instant::now(), look, retire); - SUPERSEDED.store(r.unmapped, Ordering::Relaxed); + sync_superseded(r); let victims: Vec = out.victims.iter().filter_map(|&o| unsafe { resource(o) }).collect(); let held = unsafe { map_again(&out.remap) }; (out, victims, held) @@ -510,7 +535,7 @@ fn settle(f: impl FnOnce(&mut Registry) -> Vec) { let mut g = REGISTRY.lock().unwrap(); let Some(r) = g.as_mut() else { return }; let remap = f(r); - SUPERSEDED.store(r.unmapped, Ordering::Relaxed); + sync_superseded(r); unsafe { map_again(&remap) } }; drop(held); @@ -538,6 +563,22 @@ pub(super) unsafe fn unmap_if_superseded(res: &ID3D12Resource) { } } +/// Batch `note_use`: checks all candidate resources under one shared `SUPERSEDED_IDS` read lock +/// and only acquires `REGISTRY` for resources that are actually superseded. +pub(super) fn note_uses(res: &[usize]) { + if res.is_empty() || SUPERSEDED.load(Ordering::Relaxed) == 0 { + return; + } + let hits: Vec = { + let g = SUPERSEDED_IDS.read().unwrap_or_else(|e| e.into_inner()); + let Some(set) = g.as_ref() else { return }; + res.iter().copied().filter(|r| *r != 0 && set.contains(r)).collect() + }; + for r in hits { + note_use(r); + } +} + /// Whether any live target is currently superseded (`SUPERSEDED != 0`). pub(super) fn any_superseded() -> bool { SUPERSEDED.load(Ordering::Relaxed) != 0 @@ -551,12 +592,18 @@ pub(super) fn note_use(res: usize) { if res == 0 || SUPERSEDED.load(Ordering::Relaxed) == 0 { return; } + { + let g = SUPERSEDED_IDS.read().unwrap_or_else(|e| e.into_inner()); + if !g.as_ref().is_some_and(|set| set.contains(&res)) { + return; + } + } static LOGGED: Mutex>> = Mutex::new(None); let held = { let mut g = REGISTRY.lock().unwrap(); let Some(r) = g.as_mut() else { return }; let under = r.use_again(res); - SUPERSEDED.store(r.unmapped, Ordering::Relaxed); + sync_superseded(r); if under.is_empty() { return; } diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index cf37a356d8..0548b7a89c 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -66,9 +66,35 @@ pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, pl // The title can use flip statistics to decide when to reuse its buffer. // Queue our copy before reporting the flip. super::frame::mark_flipped(token); + trim_spares_now_and_then(); 0 } +/// `title_list::trim_idle_spares` every 2 s at most, from the title's presents (`XCL_TRIM_SPARES=0` +/// turns it off). +fn trim_spares_now_and_then() { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + static LAST: Mutex> = Mutex::new(None); + if !*ON.get_or_init(|| std::env::var("XCL_TRIM_SPARES").map_or(true, |v| v.trim() != "0")) { + return; + } + { + let mut last = LAST.lock().unwrap(); + let now = std::time::Instant::now(); + if last.is_some_and(|t| now.duration_since(t) < std::time::Duration::from_secs(2)) { + return; + } + *last = Some(now); + } + super::title_list::trim_idle_spares(); +} + +/// `XCL_PRESENT_PLANE=`: the one plane shown (None: all of them, composed) +fn present_plane_only() -> Option { + static ONLY: std::sync::OnceLock> = std::sync::OnceLock::new(); + *ONLY.get_or_init(|| std::env::var("XCL_PRESENT_PLANE").ok().and_then(|v| v.trim().parse().ok())) +} + const PLANE_STRIDE: usize = 0x48; const MAX_PLANES: usize = 8; @@ -135,6 +161,7 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u if let Some(t) = LAST.lock().unwrap().replace(now) { crate::xlog_info!("D3D12.X: {frames} frames presented, {:.1} fps over the last 300", 300.0 / (now - t).as_secs_f64()); } + crate::gpu::rt_leave_out::check_structures(); } super::real::stop_if_device_removed(); if !PRESENTX.swap(true, Ordering::Relaxed) { @@ -150,6 +177,44 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u } } let extracted = extract_planes(plane_count, planes); + { + // which resources the planes show, when a plane shows one it has not shown before + // (the first 24 times) + static SHOWN: Mutex> = Mutex::new(Vec::new()); + let mut shown = SHOWN.lock().unwrap(); + for (i, &(res, rect)) in extracted.iter().enumerate() { + if !shown.contains(&(i, res)) && shown.len() < 24 { + shown.push((i, res)); + let raw = res as *mut c_void; + let desc = ID3D12Resource::from_raw_borrowed(&raw).map(|r| r.GetDesc()); + crate::xlog_info!( + "D3D12.X: PresentX frame {frames}: plane {i} shows {res:#x} for the first time: {:?}, source rect {rect:?}, the title's address {:x?}, words {:x?}", + desc.map(|d| (d.Width, d.Height, d.Format.0, d.Flags.0)), + super::real::title_address(res), + (0..PLANE_STRIDE / 8).map(|k| (planes.add(i * PLANE_STRIDE) as *const u64).add(k).read_unaligned()).collect::>() + ); + } + } + } + if let Some(from) = trace_planes() { + static LAST: Mutex>> = Mutex::new(None); + let now: HashMap = USES.lock().unwrap().clone().unwrap_or_default(); + let mut last = LAST.lock().unwrap(); + if frames >= from && frames < from + 600 { + for (i, &(res, _)) in extracted.iter().enumerate() { + let n = now.get(&res).copied().unwrap_or_default(); + let o = last.as_ref().and_then(|m| m.get(&res).copied()).unwrap_or_default(); + crate::xlog_info!( + "plane trace: frame {frames} plane {i} {res:#x}: since the last present rt binds {}, UAV views {}, copy destination {}, clears {}", + n[0] - o[0], + n[1] - o[1], + n[2] - o[2], + n[3] - o[3] + ); + } + } + *last = Some(now); + } if super::capture::enabled() { super::capture::present(queue as usize, &extracted.iter().map(|e| e.0).collect::>(), frames); } @@ -248,9 +313,43 @@ pub fn trace_frame() -> bool { *ON.get_or_init(|| std::env::var_os("XCL_TRACE_FRAME").is_some()) } +/// `XCL_TRACE_PLANES=`: from that frame on (the next 600), what console code did with +/// each presented plane's resource since the present before. +fn trace_planes() -> Option { + static FROM: std::sync::OnceLock> = std::sync::OnceLock::new(); + *FROM.get_or_init(|| std::env::var("XCL_TRACE_PLANES").ok().and_then(|v| v.trim().parse().ok())) +} + +/// A copy into a presented resource under `XCL_TRACE_PLANES` (the first 60): where from. +pub unsafe fn trace_plane_copy(what: &str, dst: usize, src: usize) { + if trace_planes().is_none() || !is_presented(dst) { + return; + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) >= 60 { + return; + } + let d = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|r| r.GetDesc()).map(|d| (d.Dimension.0, d.Width, d.Height, d.Format.0, d.Flags.0)); + crate::xlog_info!( + "plane trace: frame {} {what} into {dst:#x} {:?} from {src:#x} {:?} (the title's address {:x?})", + BOUNDARIES.load(Ordering::Relaxed), + d(dst), + if src != 0 { d(src) } else { None }, + super::real::title_address(src) + ); +} + +pub fn trace_planes_from() -> Option { + trace_planes() +} + +pub fn trace_uses() -> bool { + trace_frame() || trace_planes().is_some() +} + /// `res` was used as `what` (USE_*) pub fn note_use(res: usize, what: usize) { - if trace_frame() && res != 0 { + if (trace_frame() || trace_planes().is_some()) && res != 0 { USES.lock().unwrap().get_or_insert_with(HashMap::new).entry(res).or_default()[what] += 1; } } @@ -1037,6 +1136,9 @@ fn mark_pipe_drained(p: &mut Presenter) { } fn compile_fx(src: &str, target: &str) -> Option> { + if let Some(b) = crate::gpu::recomp::dxc::compile_sm6_first(src, "main", target) { + return Some(b); + } unsafe { let mut blob: Option = None; let t = format!("{target}\0"); @@ -1447,6 +1549,11 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, Some((r, desc, uv)) }) .collect(); + // `XCL_PRESENT_PLANE=` (diagnostic): only plane `i` of a PresentX is shown, as it is + let resolved = match present_plane_only() { + Some(i) if i < resolved.len() => vec![resolved[i].clone()], + _ => resolved, + }; if resolved.is_empty() { return; } @@ -1677,6 +1784,14 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, for dump in p.dumps.drain(..) { if dump.tag.starts_with("twin") { super::depth_uav::log_values(&dump.buffer, &dump.footprint, &dump.tag); + // and as a picture of its bytes as they are (a 16-bit twin: the low byte red, + // the high byte green; a 32-bit one: its low three bytes; a stencil twin: grey) + let raw = match dump.format { + DXGI_FORMAT_R16_TYPELESS => DXGI_FORMAT_R16_UINT, + DXGI_FORMAT_R32_TYPELESS => DXGI_FORMAT_R32_UINT, + f => f, + }; + write_frame(&dump.buffer, &dump.footprint, raw, &dump.tag.replace(' ', "_")); continue; } if dump.tag.starts_with("lut") { @@ -1716,7 +1831,9 @@ 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 parse_frame_dump_every(val: Option<&str>) -> u64 { let Some(v) = val else { return 0; }; @@ -1728,9 +1845,26 @@ fn parse_frame_dump_every(val: Option<&str>) -> u64 { } 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(|| parse_frame_dump_every(std::env::var("XCL_FRAME_DUMP").ok().as_deref())); - every > 0 && PRESENTS.load(Ordering::Relaxed) % every == 20.min(every - 1) + let every = *EVERY.get_or_init(|| { + let v = std::env::var("XCL_FRAME_DUMP").ok(); + // with `XCL_FRAME_DUMP_FROM`, `XCL_FRAME_DUMP=1` dumps every frame from there on + if from > 0 && v.as_deref().map(str::trim) == Some("1") { + 1 + } else { + parse_frame_dump_every(v.as_deref()) + } + }); + if every == 0 { + return false; + } + let cur = PRESENTS.load(Ordering::Relaxed); + if cur < from { + return false; + } + every == 1 || cur % every == 20.min(every - 1) } /// Frames shown so far. diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 9a40f455f5..d0907a9701 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -111,6 +111,10 @@ struct Pending { spared: std::sync::atomic::AtomicBool, /// what its first use tells besides `used::note` (`on_first_use`) on_use: Mutex>, + /// what it draws is drawn once and kept (`kept`): its draws wait until it is built + kept: std::sync::atomic::AtomicBool, + /// its shaders' names, for the line of a late one (`named`) + name: Mutex>>, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -194,6 +198,8 @@ struct Build { late: AtomicBool, /// its build gave the driver a huge program (`note_huge`) huge: AtomicBool, + /// a wait of one of the title's threads, or a submit's need, handed it to the urgent workers (`urge`) + urged: AtomicBool, /// a wait for it passed 1 s and was logged (once a build) warned: AtomicBool, /// its translation and DXC compile on their own, until the backlog runs them (`Warm`) @@ -544,6 +550,7 @@ impl Build { used: AtomicBool::new(false), late: AtomicBool::new(false), huge: AtomicBool::new(false), + urged: AtomicBool::new(false), warned: AtomicBool::new(false), warm: Mutex::new(None), } @@ -4265,6 +4272,68 @@ fn fail_unrunnable_build(build: &Arc) { } } +/// The builds handed to the urgent workers (`urge`), oldest first. +static NEEDED: Mutex>> = Mutex::new(std::collections::VecDeque::new()); +/// An urgent worker waits here for `NEEDED` (`spawn_urgent_workers`). +static URGENT_CV: Condvar = Condvar::new(); +/// builds the urgent workers ran +static URGENT_BUILT: AtomicUsize = AtomicUsize::new(0); + +/// `XCL_PSO_URGENT_WORKERS=` (default 2, at most 8; 0: none): workers that build nothing but +/// the pipelines one of the title's threads or a submit is waiting for (`urge`). The regular +/// workers take those first too (`Build::want` promotes them), but only between two builds: on a +/// cold driver cache every one of them may be in a driver compile of tens of seconds. A retail +/// title's loading thread then waited 20 s (`XCL_CS_PSO_WAIT_MS`) for one small compute pipeline +/// after another – programs of 3 - 60 KB of DXIL that no worker had even translated – while the +/// four workers held 160 - 250 KB programs compiled one at a time: 0 frames for 220 s. +fn urgent_workers() -> usize { + static V: OnceLock = OnceLock::new(); + *V.get_or_init(|| urgent_workers_of(std::env::var("XCL_PSO_URGENT_WORKERS").ok().as_deref())) +} + +fn urgent_workers_of(v: Option<&str>) -> usize { + v.and_then(|v| v.trim().parse::().ok()).unwrap_or(2).min(8) +} + +/// The urgent workers (`urgent_workers`), started at the first build waited for. +fn spawn_urgent_workers() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + for k in 0..urgent_workers() { + // (an `xcl-pso` name: its huge driver compile takes its turn as a worker's, `real::driver_compile_identified`) + let _ = std::thread::Builder::new().name(format!("xcl-pso-urgent-{k}")).stack_size(64 << 20).spawn(|| loop { + let build = { + let mut q = NEEDED.lock().unwrap(); + loop { + if let Some(b) = q.pop_front() { + break b; + } + q = URGENT_CV.wait(q).unwrap(); + } + }; + if build_queued(&build) { + let n = URGENT_BUILT.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + crate::xlog_info!("D3D12.X: {n} pipelines a title thread or a submit waited for built by the urgent workers (XCL_PSO_URGENT_WORKERS)"); + } + } + }); + } + }); +} + +/// `build` goes to the urgent workers, once: one of the title's threads waits for it now (or a +/// submit will) and no worker has taken it yet. An urgent worker takes it at once; the job queued +/// for the regular workers then finds it gone (`build_queued`). +fn urge(build: &Arc) { + if urgent_workers() == 0 || build.orphan.load(Ordering::Acquire) || build.job.lock().unwrap().is_none() || build.urged.swap(true, Ordering::AcqRel) { + return; + } + spawn_urgent_workers(); + NEEDED.lock().unwrap().push_back(build.clone()); + URGENT_CV.notify_one(); +} + fn build_queued(build: &Arc) -> bool { // (released by the title meanwhile) if build.orphan.load(Ordering::Acquire) { @@ -4562,6 +4631,8 @@ fn submit_as( late: Default::default(), spared: Default::default(), on_use: Default::default(), + kept: Default::default(), + name: Default::default(), }); build.tracked.store(true, Ordering::Release); if !send { @@ -4608,6 +4679,38 @@ pub(super) fn on_first_use_graphics(standin: usize, payload: Vec) { } } +/// The graphics pipeline behind stand-in `standin` draws what the title draws once and keeps +/// (`real::drawn_once`): its draws wait until it is built, whatever the thread has waited for +/// others (`XCL_GFX_PSO_WAIT_MS`). A retail title bakes its characters' faces into textures of +/// its own with a few draws at the start of its world, among some 500 pipelines never used +/// before: with 50 ms a second to wait, the bake's draws drew nothing and the heads stayed black +/// for the run. Told before the title has the stand-in. +pub(super) fn kept(standin: usize) { + if let Some(p) = entry(standin) { + p.kept.store(true, Ordering::Release); + } +} + +/// Whether what the pipeline behind stand-in `pso` draws is drawn once and kept (`kept`). +pub(super) fn is_kept(pso: usize) -> bool { + entry(pso).is_some_and(|p| p.kept.load(Ordering::Acquire)) +} + +/// The names of the shaders of the pipeline behind stand-in `standin`, for the line of a late +/// one (`XCL_TRACE_LATE=1`). Told before the title has the stand-in. +pub(super) fn named(standin: usize, name: Arc) { + if let Some(p) = entry(standin) { + *p.name.lock().unwrap() = Some(name); + } +} + +/// `XCL_TRACE_LATE=1` (a diagnostic): every graphics pipeline whose draws go on without it is +/// logged with its shaders' names. +pub(super) fn trace_late() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TRACE_LATE").is_ok_and(|v| v.trim() == "1")) +} + /// The shaders of a pipeline's set, told when the set's key is made (`real::OwnedDesc`). pub(crate) fn shaders_of(key: u64, shaders: Vec) { used::parts(key, shaders); @@ -6016,6 +6119,8 @@ mod used_tests { late: AtomicBool::new(false), spared: AtomicBool::new(false), on_use: Mutex::new(None), + kept: Default::default(), + name: Default::default(), }) } @@ -8154,6 +8259,8 @@ mod used_tests { track_used: true, used: AtomicBool::new(false), late: AtomicBool::new(false), spared: AtomicBool::new(false), on_use: Mutex::new(None), + kept: Default::default(), + name: Default::default(), }; pending.note_use(); assert!(!first_build.candidate_queued.load(Ordering::Acquire)); @@ -10428,6 +10535,35 @@ mod used_tests { assert!(dropped.warm.lock().unwrap().is_none(), "an unstarted job's goes with it"); } + /// A bind that waits for a pipeline no worker has taken hands it to the urgent workers, once, + /// and one of them builds it: the regular workers may all be in long driver compiles. (Its job + /// never reaches them here: it is marked sent, as one the queue already holds.) + #[test] + fn a_waited_build_goes_to_an_urgent_worker() { + assert_eq!(urgent_workers_of(None), 2); + assert_eq!(urgent_workers_of(Some("0")), 0); + assert_eq!(urgent_workers_of(Some("99")), 8); + if urgent_workers() == 0 { + return; + } + let standin = 0x7E57_A601usize; + let (tx, rx) = mpsc::channel::(); + submit_lazy(standin, true, Box::new(move || { + let _ = tx.send(std::thread::current().name().unwrap_or_default().to_string()); + 0x7A61 + }), 0); + let p = entry(standin).unwrap(); + p.build.sent.store(true, Ordering::Release); + assert_eq!(resolve_within(&p, standin, std::time::Duration::from_secs(20)), 0x7A61, "built within the wait"); + let by = rx.recv_timeout(std::time::Duration::from_secs(1)).unwrap(); + assert!(by.starts_with("xcl-pso-urgent-"), "built by {by:?}"); + assert!(p.build.urged.load(Ordering::Acquire)); + // (built: urged again, it is not queued again) + urge(&p.build); + assert!(!NEEDED.lock().unwrap().iter().any(|q| Arc::ptr_eq(q, &p.build))); + let _ = released(standin); + } + /// A dispatch is put off to the submit only where it would wait now: not with a pipeline that /// writes only images (its dispatches are left out while it is built) nor with one a bind /// already waited for past its budget. A submit that says it will wait for a pipeline counts @@ -10677,6 +10813,8 @@ mod used_tests { late: Default::default(), spared: Default::default(), on_use: Default::default(), + kept: Default::default(), + name: Default::default(), }); PENDING.insert(standin, p.clone()); assert_eq!(peek(standin), standin, "not built"); @@ -10882,6 +11020,11 @@ fn resolve_pending(p: &Pending, pso: usize) -> usize { } } +/// the console record (`fnv64` of its CS) of the pipeline the title made as `pso`, when known +pub(super) fn record_of(pso: usize) -> Option { + entry(pso).map(|p| p.build.record).filter(|&r| r != 0) +} + /// `resolve` with no side effects (for a report): the real pipeline behind `pso` once built, /// else `pso` itself – no use noted, nothing sent to the workers. pub(super) fn peek(pso: usize) -> usize { @@ -10912,7 +11055,11 @@ fn resolve_wait_bound_for(pso: usize, budget: Option) -> (u /// `resolve_wait` with the budget of every pipeline (`XCL_PSO_WAIT_MS`), the one of graphics /// pipelines (`XCL_GFX_PSO_WAIT_MS`) and the one of compute pipelines (`XCL_CS_PSO_WAIT_MS`). fn resolve_wait_budgets(pso: usize, all: Option, gfx: Option, cs: Option) -> usize { - let Some(compute) = entry(pso).map(|p| p.compute) else { return resolve_wait_for(pso, None) }; + let Some((compute, kept)) = entry(pso).map(|p| (p.compute, p.kept.load(Ordering::Acquire))) else { return resolve_wait_for(pso, None) }; + if kept { + // (what it draws is drawn once: no budget, the draw waits for it) + return resolve_wait_for(pso, None); + } match gfx.filter(|_| !compute) { // the graphics budget is a thread's for a second, not one for each pipeline Some(budget) => { @@ -11161,6 +11308,7 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> let _stall = crate::stall::span(crate::stall::StallKind::PipelineWait); let mut wait = Wait::new(p); p.build.want(); + urge(&p.build); if wait.until_done(Some(budget)) { return built_or(p, pso); } @@ -11180,6 +11328,10 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> if n < 16 || n.is_power_of_two() { crate::xlog_warn!("D3D12.X: a pipeline still being built after {} ms: its binds go on without it until it is built ({} so far)", budget.as_millis(), n + 1); } + if trace_late() { + let name = p.name.lock().unwrap().clone(); + crate::xlog_info!("D3D12.X: late pipeline #{}: {}", n + 1, name.as_deref().unwrap_or("(no names)")); + } p.stand(pso) } @@ -11225,7 +11377,7 @@ fn resolve_spared(p: &Arc, pso: usize) -> usize { static N: AtomicUsize = AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); if n < 16 || n.is_power_of_two() { - crate::xlog_info!("D3D12.X: a compute program that writes only images is still being built: its dispatches are left out until it is ({} so far)", n + 1); + crate::xlog_info!("D3D12.X: a compute program binds go on without (one that writes only images, or the BVH builder's) is still being built: its dispatches are left out until it is ({} so far)", n + 1); } } p.stand(pso) @@ -12046,6 +12198,8 @@ fn pipeline_resolution_for_kind_test( late: AtomicBool::new(false), spared: AtomicBool::new(false), on_use: Mutex::new(None), + kept: Default::default(), + name: Default::default(), }); PipelineResolution( StructuredResolve::initial(original, pending, original, true), @@ -12407,6 +12561,27 @@ fn resolve_wait_bound_and_pin(pso: usize) -> ((usize, bool), Option, + pso: usize, + all: Option, + gfx: Option, + cs: Option, +) -> usize { + if p.kept.load(Ordering::Acquire) { + return resolve_wait_pending(p, pso, None); + } + match gfx.filter(|_| !p.compute) { + Some(budget) => { + let start = std::time::Instant::now(); + let r = resolve_wait_pending(p, pso, Some(gfx_wait_left(budget, start))); + gfx_wait_spent(start.elapsed()); + r + } + None => resolve_wait_pending(p, pso, budget_for(p.compute, all, gfx, cs)), + } +} + /// Resolve one retained Pending to an exactly owned generation without consulting its title /// address. One-shot and recipe-backed builds share the same wait policy at this boundary. fn resolve_retained_for_emission(pso: usize, p: &Arc) -> PipelineChoice { @@ -12416,7 +12591,7 @@ fn resolve_retained_for_emission(pso: usize, p: &Arc) -> PipelineChoice return PipelineChoice::Unavailable; } p.note_use(); - let bound = resolve_wait_pending(p, pso, wait_budget()); + let bound = resolve_wait_pending_budgets(p, pso, wait_budget(), gfx_wait_budget(), cs_wait_budget()); let bound_unbuilt = p.bound_unbuilt(pso, bound); let (raw, generation, _) = pin_resolved(pso, p, bound, bound_unbuilt); match generation { @@ -12529,6 +12704,7 @@ fn need_pending_by_submit(p: &Arc) { } want_ahead(p); schedule(&p.build, Priority::BoundSoon, false, None); + urge(&p.build); // True means all record-time demand work above is complete. Concurrent first callers may // repeat the idempotent promotion/schedule, but no caller observes publication too early. if !p.build.by_submit.swap(true, Ordering::AcqRel) { @@ -12936,4 +13112,56 @@ mod backlog_tests { released(standin); } } + + #[test] + fn retained_resolution_honors_gfx_budget_and_kept_override() { + use std::time::{Duration, Instant}; + let (go, finish) = mpsc::channel::<()>(); + let standin = 0x7E57_C090usize; + submit_lazy( + standin, + false, + Box::new(move || { + let _ = finish.recv_timeout(Duration::from_secs(5)); + 0x6F6F + }), + 0x5EED_C090, + ); + let p = entry(standin).expect("pending graphics pipeline registered"); + let t0 = Instant::now(); + let bound = resolve_wait_pending_budgets(&p, standin, None, Some(Duration::from_millis(20)), None); + assert_eq!(bound, standin, "non-kept retained graphics bind must honor XCL_GFX_PSO_WAIT_MS"); + assert!(t0.elapsed() < Duration::from_secs(1)); + + // Reset late/kept state and verify a kept graphics pipeline still waits past the gfx budget. + let (go2, finish2) = mpsc::channel::<()>(); + let kept_standin = 0x7E57_C091usize; + submit_lazy( + kept_standin, + false, + Box::new(move || { + let _ = finish2.recv_timeout(Duration::from_secs(5)); + 0x6F70 + }), + 0x5EED_C091, + ); + kept(kept_standin); + let pk = entry(kept_standin).expect("kept pending graphics pipeline registered"); + let releaser = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(40)); + let _ = go2.send(()); + }); + let bound_kept = resolve_wait_pending_budgets(&pk, kept_standin, None, Some(Duration::from_millis(10)), None); + assert_eq!(bound_kept, 0x6F70, "kept retained graphics bind must wait past gfx budget"); + let _ = releaser.join(); + let _ = go.send(()); + // Wait for the first build to complete before calling `released`, so the worker does not + // try to COM-Release the synthetic sentinel pointer `0x6f6f` on an orphaned build. + let deadline = Instant::now() + Duration::from_secs(5); + while is_pending(standin) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(released(standin), 0x6F6F); + assert_eq!(released(kept_standin), 0x6F70); + } } diff --git a/crates/xcl/src/hle/d3d12x/queue_submit.rs b/crates/xcl/src/hle/d3d12x/queue_submit.rs index 060160a828..2fb34b8d61 100644 --- a/crates/xcl/src/hle/d3d12x/queue_submit.rs +++ b/crates/xcl/src/hle/d3d12x/queue_submit.rs @@ -46,6 +46,21 @@ impl Lease { } } +impl Lease { + /// `enter`, or None while another thread holds the lease (no wait). + fn try_enter(self: &Arc) -> Option { + let me = std::thread::current().id(); + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if state.owner.is_some_and(|owner| owner != me) { + return None; + } + state.owner = Some(me); + state.depth += 1; + drop(state); + Some(Guard(Arc::clone(self))) + } +} + struct Guard(Arc); impl Drop for Guard { @@ -90,6 +105,18 @@ pub(super) fn with(queue: usize, f: impl FnOnce() -> R) -> R { f() } +/// `with`, or None without running `f` while another thread holds the queue's turn. For callers +/// that may run inside a D3D12 call of the runtime's (a resource's last `Release` from a list's +/// `Reset`): the thread with the turn can be waiting for that call's lock in the runtime (an +/// allocator `Reset` while it submits), so waiting for the turn there would never end. +pub(super) fn try_with(queue: usize, f: impl FnOnce() -> R) -> Option { + if queue == 0 { + return Some(f()); + } + let _guard = lease(queue).try_enter()?; + Some(f()) +} + /// Forward Release and discard the raw-address lease after a final native release. Pointer /// identity prevents a newly created generation at the same address from being removed. pub(super) fn release(queue: usize, f: impl FnOnce() -> u32) -> u32 { @@ -107,6 +134,27 @@ pub(super) fn release(queue: usize, f: impl FnOnce() -> u32) -> u32 { #[cfg(test)] mod tests { use super::*; + + #[test] + fn try_with_does_not_wait_for_another_threads_turn() { + let queue = 0x7e57_0001usize; + created(queue); + let (held_tx, held_rx) = std::sync::mpsc::channel(); + let (done_tx, done_rx) = std::sync::mpsc::channel::<()>(); + let holder = std::thread::spawn(move || { + with(queue, || { + held_tx.send(()).unwrap(); + done_rx.recv().unwrap(); + }) + }); + held_rx.recv().unwrap(); + assert!(try_with(queue, || ()).is_none(), "another thread has the turn"); + done_tx.send(()).unwrap(); + holder.join().unwrap(); + assert_eq!(try_with(queue, || 7), Some(7)); + // re-entrant on the thread that has the turn + assert_eq!(with(queue, || try_with(queue, || 8)), Some(8)); + } use std::ffi::c_void; use std::sync::mpsc; use std::sync::atomic::{AtomicU64, Ordering}; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a9dad2dd11..6831ceb4d1 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -780,11 +780,13 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) { } } let w0_va = bufs.first().map_or(0, |b| b.1); + let win_vas: Vec = bufs.iter().enumerate().filter(|(_, b)| b.1 != 0).map(|(k, b)| format!("w{k}={:#x}", b.1)).collect(); crate::xlog_info!( - "D3D12.X: UMA opened ({} sparse VRAM window(s), {} MB coherent window), window 0 buffer at VA {:#x}", + "D3D12.X: UMA opened ({} sparse VRAM window(s), {} MB coherent window), window 0 buffer at VA {:#x} [{}]", sparse.len(), u.size() >> 20, - w0_va + w0_va, + win_vas.join(", ") ); *UMA_HEAPS.lock().unwrap() = heaps; *UMA_DXGI_BYTES.lock().unwrap() = (device.as_raw() as usize, uma_non_local, uma_local); @@ -1012,6 +1014,7 @@ pub(super) fn init_with_remap(allow_driver_remap: bool) -> Result Option> { + let raw = queue.as_raw(); + type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT; + let f = native_queue_fn(raw, 14); + super::queue_submit::try_with(raw as usize, || { + let f: F = std::mem::transmute(f); + windows::core::HRESULT(f(raw, fence.as_raw(), value)).ok() + }) +} + /// Wait through the PC queue slot, bypassing the title's shifted queue layout. pub(crate) unsafe fn native_queue_wait(queue: &ID3D12CommandQueue, fence: &ID3D12Fence, value: u64) -> windows::core::Result<()> { let raw = queue.as_raw(); @@ -1232,6 +1246,17 @@ fn module_of(addr: usize) -> usize { h as usize } +/// Whether the hook that calls this was called from the module that holds `orig` (the hooked +/// method's original): the D3D12 runtime calling one of its objects' methods itself rather than +/// the title or XCL. Frame 0 is this function, 1 the hook, 2 the hook's caller. +#[inline(never)] +fn called_from_module_of(orig: usize) -> bool { + let mut frame = [std::ptr::null_mut::(); 1]; + let n = unsafe { windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace(2, 1, frame.as_mut_ptr(), std::ptr::null_mut()) }; + let module = module_of(orig); + n == 1 && module != 0 && module_of(frame[0] as usize) == module +} + /// Whether `obj` is an object XCL adopted (its vtable is one of XCL's). pub(super) unsafe fn is_adopted(obj: *mut c_void) -> bool { !obj.is_null() && crate::gpu::shader::readable(obj as usize, 8) && is_ext(*(obj as *const usize)) @@ -1959,11 +1984,48 @@ fn resource_dim_to_view(r: &D3D12_RESOURCE_DESC) -> i32 { static NON_UMA_BUFFER_VIEWS: AtomicU64 = AtomicU64::new(0); +pub(super) fn trace_preskin() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TRACE_PRESKIN").is_ok_and(|v| v.trim() == "1")) +} + +fn trace_preskin_slot(who: &str, at: usize, words: &[u32]) { + if !trace_preskin() { + return; + } + let Some(u) = crate::gpu::uma::get() else { return }; + let rel = at.wrapping_sub(u.base()); + if (0xd580_0000..0xd588_0000).contains(&rel) { + let mod_off = (rel - 0xd580_0000) % 0x1900; + if mod_off == 33 * 32 || mod_off == 84 * 32 || mod_off == 24 * 32 || mod_off == 25 * 32 { + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed); + if k < 64 { + crate::xlog_info!("trace preskin slot #{k} ({who}): rel={rel:#x} (slot {}) words={words:08x?}", mod_off / 32); + } + } + } +} + /// V# of a buffer view (raw: 4-byte elements, num_records in bytes; structured / typed: /// stride = element size, num_records in elements); empty when the buffer is not in UMA. A /// buffer placed in a GPU view asks for the tiles of the range viewed (`view_want`). fn buffer_view(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool) -> [u32; 4] { let Some((at, bytes)) = console_buffer(res) else { + if trace_preskin() { + static M: AtomicU64 = AtomicU64::new(0); + let k = M.fetch_add(1, Ordering::Relaxed); + if k < 64 { + let ptr = res as *mut c_void; + let rd = unsafe { ID3D12Resource::from_raw_borrowed(&ptr).map(|r| r.GetDesc()) }; + let ta = title_address(res); + crate::xlog_info!( + "trace preskin buffer_view MISS #{k}: res={res:#x} title_addr={ta:#x?} rd={:?} fmt={} first={first} n={n} stride={stride} raw={raw}", + rd.map(|d| (d.Dimension.0, d.Width, d.Height, d.Flags.0)), + format.0 + ); + } + } note_buffer_view(); return [0; 4]; }; @@ -2234,7 +2296,16 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: let u = crate::gpu::uma::get()?; let mut d: D3D12_RESOURCE_DESC = std::ptr::read_unaligned(desc.as_ptr() as *const D3D12_RESOURCE_DESC); let bytes = d.Width as usize; - let (k, tiles) = title_buffer_window(u, va, bytes)?; + let Some((k, tiles)) = title_buffer_window(u, va, bytes) else { + if trace_preskin() { + static N: AtomicU64 = AtomicU64::new(0); + let c = N.fetch_add(1, Ordering::Relaxed); + if c < 32 { + crate::xlog_info!("trace preskin place_at_title_address MISS #{c}: title_buffer_window None for va={va:#x} bytes={bytes:#x} state={state:#x} flags={:#x} win_va={:?}", d.Flags.0, u.window_of(va)); + } + } + return None; + }; let base = u.window(k).0; // a placed PC buffer starts at 64 KiB: one at another address starts below it and XCL adds // the difference where PC methods take an offset into it (`buffer_delta`) @@ -2246,6 +2317,13 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: if tiles { let view = super::view_want::want(super::view_want::Path::PlacedBuffer, va as u64, bytes as u64); let Some((hr, delta)) = super::sparse::place_buffer(this, va, &d, state, riid, ppv) else { + if trace_preskin() { + static N: AtomicU64 = AtomicU64::new(0); + let c = N.fetch_add(1, Ordering::Relaxed); + if c < 32 { + crate::xlog_info!("trace preskin place_at_title_address MISS #{c}: sparse::place_buffer None for va={va:#x} bytes={bytes:#x} state={state:#x} flags={:#x} view={view}", d.Flags.0); + } + } if view { static ONCE: AtomicU64 = AtomicU64::new(0); if ONCE.fetch_add(1, Ordering::Relaxed) == 0 { @@ -2435,6 +2513,124 @@ pub(super) fn title_address(res: usize) -> Option { console_buffer(res).map(|b| b.0).or_else(|| TITLE_ADDRESS.lock().unwrap().as_ref().and_then(|m| m.get(&res).copied())) } +/// GPU address ranges of buffers made and let go (the last 16384 events), for a page fault's +/// report: (when, what, GPU address, bytes, let go). +static VA_LOG: Mutex> = Mutex::new(std::collections::VecDeque::new()); + +pub(super) fn note_va(what: &'static str, va: u64, bytes: u64, gone: bool) { + if va == 0 { + return; + } + let mut g = VA_LOG.lock().unwrap_or_else(|e| e.into_inner()); + if g.len() >= 16384 { + g.pop_front(); + } + g.push_back((std::time::Instant::now(), what, va, bytes, gone)); +} + +/// Buffer views in unified memory that compute dispatches were given through their descriptor +/// tables, as the CPU saw the descriptors at the title's call: (address, bytes, pipeline) → +/// (first time, last time, times). For a crash report: which dispatches could write an address. +static DISPATCH_VIEWS: Mutex>> = Mutex::new(None); + +pub(super) fn note_dispatch_view(base: u64, bytes: u64, pso: usize) { + let now = std::time::Instant::now(); + let mut g = DISPATCH_VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + if m.len() >= 400_000 && !m.contains_key(&(base, bytes, pso)) { + return; + } + let e = m.entry((base, bytes, pso)).or_insert((now, now, 0)); + e.1 = now; + e.2 += 1; +} + +fn compute_label(pso: usize) -> String { + let real = super::pso_async::peek(pso); + match pso_shaders(real) { + Some((cs, 0)) => format!(", cs {cs:016x}"), + _ => super::dred::on().then(|| super::dred::label_of(real)).flatten().map_or(String::new(), |l| format!(", {l}")), + } +} + +/// The buffer views dispatches were given that hold `addr` (within 64 bytes), newest first, up to 6. +pub fn dispatch_views_over(addr: usize) -> String { + let Ok(g) = DISPATCH_VIEWS.try_lock() else { return "(busy)".into() }; + let Some(m) = g.as_ref() else { return String::new() }; + let a = addr as u64; + let now = std::time::Instant::now(); + let mut hit: Vec<(&(u64, u64, usize), &(std::time::Instant, std::time::Instant, u64))> = m.iter().filter(|(k, _)| a + 64 > k.0 && a < k.0 + k.1).collect(); + hit.sort_by_key(|(_, v)| std::cmp::Reverse(v.1)); + let v: Vec = hit + .iter() + .take(6) + .map(|(k, v)| { + format!( + "{:#x} +{:#x} (pipeline {:#x}{}; {} dispatches, first {} ms ago, last {} ms ago)", + k.0, + k.1, + k.2, + compute_label(k.2), + v.2, + now.saturating_duration_since(v.0).as_millis(), + now.saturating_duration_since(v.1).as_millis() + ) + }) + .collect(); + if v.is_empty() { format!("none of {} views", m.len()) } else { format!("{} of {} views: {}", hit.len(), m.len(), v.join("; ")) } +} + +/// Root views XCL bound by GPU address (the last 262144): (list, root slot, address), for a page +/// fault's report – a root view has no size, so a shader reaches up to 4 GiB past its address. +static ROOT_VIEWS: Mutex> = Mutex::new(std::collections::VecDeque::new()); + +pub(super) fn note_root_view(list: usize, slot: u32, va: u64) { + static ON: OnceLock = OnceLock::new(); + if !*ON.get_or_init(|| std::env::var("XCL_DIAG_VIEWS").is_ok_and(|v| v.trim() == "1")) { + return; + } + let mut g = ROOT_VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + if g.len() >= 262_144 { + g.pop_front(); + } + g.push_back((list, slot, va)); +} + +/// The root views bound lately from whose address a 32-bit offset reaches `va`: the distinct +/// (slot, address) pairs with how many binds and the list of the newest, newest first (up to 10). +fn root_views_reaching(va: u64) -> String { + let Ok(g) = ROOT_VIEWS.try_lock() else { return "(busy)".into() }; + let mut found: Vec<(u32, u64, usize, usize)> = Vec::new(); + for &(list, slot, at) in g.iter().rev() { + if at <= va && va - at < 1 << 32 { + match found.iter().position(|f| f.0 == slot && f.1 == at) { + Some(i) => found[i].2 += 1, + None if found.len() < 10 => found.push((slot, at, 1, list)), + None => {} + } + } + } + let nulls = g.iter().filter(|e| e.2 == 0).count(); + if found.is_empty() { + return format!("none of {} binds ({nulls} at address 0)", g.len()); + } + found.iter().map(|&(slot, at, n, list)| format!("slot {slot} at {at:#x} (+{:#x}; {n} binds, last on list {list:#x})", va - at)).collect::>().join("; ") + &format!("; {nulls} of {} binds at address 0", g.len()) +} + +/// The last events (up to 6, newest first) of buffers whose GPU range holds `va`. +fn va_history(va: u64) -> String { + let Ok(g) = VA_LOG.try_lock() else { return "(busy)".into() }; + let now = std::time::Instant::now(); + let v: Vec = g + .iter() + .rev() + .filter(|e| va >= e.2 && va < e.2 + e.3) + .take(6) + .map(|e| format!("{} ms ago {} {} at {:#x} ({} KiB)", now.saturating_duration_since(e.0).as_millis(), e.1, if e.4 { "let go" } else { "made" }, e.2, e.3 >> 10)) + .collect(); + if v.is_empty() { format!("none of {} events", g.len()) } else { v.join("; ") } +} + pub(super) fn note_title_address(res: usize, va: usize) { TITLE_ADDRESS.lock().unwrap().get_or_insert_with(HashMap::new).insert(res, va); } @@ -2501,6 +2697,12 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { // whose Release ends the object cleans up after it, as before.) add(this); let last = f(this) == 1; + if last { + let raw = this; + if let Some(d) = ID3D12Resource::from_raw_borrowed(&raw).map(|r| (r.GetDesc(), r)).filter(|(d, _)| d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { + note_va("a buffer's last release", d.1.GetGPUVirtualAddress(), d.0.Width, true); + } + } let held = last && super::late_release::enabled(); let mut pinned = false; let n = if last { 0 } else { f(this) }; @@ -2546,6 +2748,8 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { } super::depth_uav::forget(this as usize); super::barrier_groups::forget(this as usize); + super::format_alias::forget(this as usize); + super::ambient::forget_resource(this as usize); let final_state = super::title_textures::forget(this as usize); super::lut3d::forget(this as usize); if !had_private_data { @@ -2569,6 +2773,12 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { } drop(tracked_srv_lifetime.take()); if held { + // A last release the D3D12 runtime makes itself is left to the late-release thread, not + // drained here (that drain takes XCL's locks, `placements`' registry among them): with + // DRED on, the runtime lets a resource go inside its breadcrumb lock (a list's Reset), + // while a thread of XCL's that holds the registry waited for that lock in an allocator's + // Reset (`vram`'s zero-fill under `placements::note_use`) – the title stood still. + let pinned = pinned && !called_from_module_of(f as usize); super::late_release::hold(this as usize, pinned); } else if last { // (`XCL_LATE_RELEASE=0`: it goes now) @@ -2636,6 +2846,12 @@ static TRANSLATED_GRAPHICS: Sharded<()> = Sharded::new(); /// `XCL_TRACE_FRAME`: the console VS and PS (their dump names' hashes) of a translated PSO. static PSO_SHADERS: Mutex>> = Mutex::new(None); +/// The console record of the compute pipeline `pso`, when XCL translated it (the stand-in +/// lighting finds a pass's role by it). +pub(super) fn pso_record(pso: usize) -> Option { + PSO_SHADERS.lock().unwrap().as_ref().and_then(|m| m.get(&pso)).map(|&(record, _)| record) +} + /// translated pipeline → its input layout as text (`XCL_TRACE_FRAME`) static PSO_LAYOUTS: Mutex>> = Mutex::new(None); @@ -2651,6 +2867,165 @@ pub fn skip_named_cs(pso: usize) -> bool { !list.is_empty() && pso_shaders(pso).is_some_and(|(h, _)| list.contains(&h)) } +/// `XCL_TRACE_MS=` (diagnostic): the mesh shader whose draws `bind::trace_ms_draw` +/// writes down. +pub fn trace_ms() -> Option { + static V: OnceLock> = OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_TRACE_MS").ok().and_then(|v| u64::from_str_radix(v.trim(), 16).ok())) +} + +/// `XCL_TRACE_RECORD=all` (diagnostic): track PSO shaders and log MS/PS names for every mesh pipeline. +pub fn trace_record_all() -> bool { + static V: OnceLock = OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_TRACE_RECORD").is_ok_and(|v| v.trim().eq_ignore_ascii_case("all"))) +} + +fn trace_stage_name(stage: &'static str, hash: u64, blob: &[u8]) { + if !trace_record_all() && !std::env::var("XCL_TRACE_NAMES").is_ok_and(|v| v.trim() == "1") { + return; + } + static SEEN: Mutex>> = Mutex::new(None); + if !SEEN.lock().unwrap().get_or_insert_with(HashSet::new).insert((stage, hash)) { + return; + } + let mut names: Vec = Vec::new(); + let prefixes: &[&[u8]] = &[b"MS_", b"PS_", b"VS_", b"AS_", b"GS_", b"ms_", b"ps_", b"vs_"]; + let mut i = 0; + while i + 3 < blob.len() && names.len() < 4 { + if prefixes.iter().any(|p| &blob[i..i + 3] == *p) { + let n = blob[i..].iter().take_while(|b| b.is_ascii_alphanumeric() || **b == b'_').count(); + if n >= 6 { + let name = String::from_utf8_lossy(&blob[i..i + n]).into_owned(); + if !names.contains(&name) { + names.push(name); + } + } + i += n.max(1); + } else { + i += 1; + } + } + crate::xlog_info!("trace names: {stage} {hash:016x} ({} B): {names:?}", blob.len()); +} + +/// The name a console shader's container gives its program (its debug data: a stage prefix, +/// then letters, digits and underscores – `PS_BakeDecorations_1f2e3d4c_Wrapped`), None when it +/// has none. +fn stage_name(blob: &[u8]) -> Option<&str> { + let mut i = 0; + while i + 6 <= blob.len() { + if blob[i + 2] == b'_' && blob[i + 1] == b'S' && matches!(blob[i], b'P' | b'V' | b'M' | b'A' | b'G') { + let n = blob[i..].iter().take_while(|b| b.is_ascii_alphanumeric() || **b == b'_').count(); + if n >= 6 { + return std::str::from_utf8(&blob[i..i + n]).ok(); + } + i += n.max(1); + } else { + i += 1; + } + } + None +} + +/// The names of a graphics pipeline's shaders (`stage_name`), joined with `+`; None when none +/// has one. `keys`: each shader's key (`shader_key`), by which a name is looked for once. +fn stage_names(blobs: &[std::sync::Arc<[u8]>], keys: &[u64]) -> Option> { + static NAMES: Mutex>>>> = Mutex::new(None); + let mut all = String::new(); + for (b, &key) in blobs.iter().zip(keys) { + let known = NAMES.lock().unwrap().get_or_insert_with(HashMap::new).get(&key).cloned(); + let name = match known { + Some(n) => n, + None => { + let n: Option> = stage_name(b).map(Into::into); + NAMES.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, n.clone()); + n + } + }; + if let Some(n) = name { + if !all.is_empty() { + all.push('+'); + } + all.push_str(&n); + } + } + (!all.is_empty()).then(|| all.into()) +} + +/// Whether a pipeline with shaders of these names (`stage_names`) draws what the title draws +/// once and keeps: its texture bakes (`XCL_KEPT_DRAWS`: name parts, comma-separated; +/// `Bake,DecorationBlend` unless given, empty for none – a retail title's `PS_BakeDecorations_*` +/// and `PS_DecorationBlend_*`, the faces of its characters). Such a draw left out while its +/// pipeline is built (`XCL_GFX_PSO_WAIT_MS`) is never made again. +fn drawn_once(names: &str) -> bool { + static PARTS: OnceLock> = OnceLock::new(); + let parts = PARTS.get_or_init(|| { + let v = std::env::var("XCL_KEPT_DRAWS").unwrap_or_else(|_| "Bake,DecorationBlend".into()); + v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect() + }); + parts.iter().any(|p| names.contains(p.as_str())) +} + +#[cfg(test)] +mod stage_name_tests { + #[test] + fn a_shader_is_named_by_its_container() { + let mut blob = vec![0u8, 1, 2, b'P', b'S', b'_', 7, 9]; + blob.extend_from_slice(b"\0PS_BakeDecorations_1f2e3d4c_Wrapped\0rest"); + assert_eq!(super::stage_name(&blob), Some("PS_BakeDecorations_1f2e3d4c_Wrapped")); + assert_eq!(super::stage_name(b"no name in here PS_"), None); + assert_eq!(super::stage_name(b"CS_NotAGraphicsStage_0"), None); + } + + #[test] + fn a_bake_is_drawn_once() { + assert!(super::drawn_once("VS_FullScreen_0+PS_BakeDecorations_1f2e3d4c_Wrapped")); + assert!(super::drawn_once("VS_FullScreen_0+PS_DecorationBlend_0011_Wrapped")); + assert!(!super::drawn_once("MS_VS_PedTransformPreSkinD_0+PS_PedSkin_1")); + } + + #[test] + fn names_are_joined_and_looked_for_once() { + let blobs: Vec> = vec![b"..VS_TestStage_aa..".as_slice().into(), b"plain".as_slice().into(), b"PS_TestStage_bb".as_slice().into()]; + let keys = [0x7E57_0001_0000_0001u64, 0x7E57_0001_0000_0003, 0x7E57_0001_0000_0005]; + assert_eq!(super::stage_names(&blobs, &keys).as_deref(), Some("VS_TestStage_aa+PS_TestStage_bb")); + // (the same keys: the names kept, whatever the bytes) + let other: Vec> = vec![b"x".as_slice().into(), b"y".as_slice().into(), b"z".as_slice().into()]; + assert_eq!(super::stage_names(&other, &keys).as_deref(), Some("VS_TestStage_aa+PS_TestStage_bb")); + assert_eq!(super::stage_names(&other, &[0x7E57_0001_0000_0007, 0x7E57_0001_0000_0009, 0x7E57_0001_0000_000B]), None); + } +} + +/// `XCL_TRACE_MS` / `XCL_TRACE_NAMES=1` (a diagnostic): the `CS_*` names in a compute program's +/// container (its debug data), logged once per program of record. +fn trace_cs_name(record: u64, cs: &[u8]) { + static ON: OnceLock = OnceLock::new(); + if !*ON.get_or_init(|| trace_ms().is_some() || std::env::var("XCL_TRACE_NAMES").is_ok_and(|v| v.trim() == "1")) { + return; + } + static SEEN: Mutex>> = Mutex::new(None); + if !SEEN.lock().unwrap().get_or_insert_with(HashSet::new).insert(record) { + return; + } + let mut names: Vec = Vec::new(); + let mut i = 0; + while i + 3 < cs.len() && names.len() < 3 { + if &cs[i..i + 3] == b"CS_" { + let n = cs[i..].iter().take_while(|b| b.is_ascii_alphanumeric() || **b == b'_').count(); + if n >= 6 { + let name = String::from_utf8_lossy(&cs[i..i + n]).into_owned(); + if !names.contains(&name) { + names.push(name); + } + } + i += n.max(1); + } else { + i += 1; + } + } + crate::xlog_info!("trace names: compute program of record {record:016x} ({} B): {names:?}", cs.len()); +} + pub fn pso_shaders(pso: usize) -> Option<(u64, u64)> { PSO_SHADERS.lock().unwrap().as_ref()?.get(&pso).copied() } @@ -2734,6 +3109,7 @@ pub(super) fn forget_pso_for_test(pso: usize) { fn forget_pso(pso: usize) { super::dred::forget_pso(pso); dispatch_chain::forget(pso); + super::left_out::forget(pso); TRANSLATED_COMPUTE.remove(pso); if let Some(s) = CONSOLE_COMPUTE.lock().unwrap().as_mut() { s.remove(&pso); @@ -2884,6 +3260,11 @@ unsafe fn copy_console_slots(this: *mut c_void, n: u32, dst: u64, src: u64, ty: let mut tracked_copies = (!d0.sampler && super::vram::srv_tracking_enabled()).then(Vec::new); for k in 0..n as u64 { if let (Some(d), Some(s)) = (slot(dst + k * step), slot(src + k * step)) { + if trace_preskin() && !d.sampler { + let mut w = [0u32; 4]; + std::ptr::copy_nonoverlapping(s.at as *const u32, w.as_mut_ptr(), 4); + trace_preskin_slot("copy_console_slots", d.at, &w); + } if let Some(copies) = tracked_copies.as_mut() { let (source_words, destination_words) = copy_words_captured(&s, &d); copies.push((s, d, source_words, destination_words)); @@ -2924,7 +3305,7 @@ unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u3 if copy_console_slots(this, n, dst, src, ty) { return; } - if super::console_heap::slot(dst).is_some() || super::console_heap::slot(src).is_some() { + if super::console_heap::contains(dst) || super::console_heap::contains(src) { note_mixed_copy(); return; } @@ -2942,10 +3323,10 @@ unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dst let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor); let ty = pc_heap_type(ty); note_copy_call("CopyDescriptors", nd, if dsts.is_null() { 0 } else { *dsts }, if srcs.is_null() { 0 } else { *srcs }); - use super::console_heap::{slot, SAMPLER_SLOT, SLOT}; - let console = !dsts.is_null() && !srcs.is_null() && nd > 0 && slot(*dsts).is_some(); + use super::console_heap::{contains, SAMPLER_SLOT, SLOT}; + let console = !dsts.is_null() && !srcs.is_null() && nd > 0 && contains(*dsts); if !console { - if !srcs.is_null() && ns > 0 && slot(*srcs).is_some() { + if !srcs.is_null() && ns > 0 && contains(*srcs) { note_mixed_copy(); return; } @@ -3089,7 +3470,8 @@ unsafe fn dev_create_uav_checked_inner( let raw_fmt = patched.as_ref().map_or(0, |d| d.Format.0 as u32); let res_fmt = rd.Format.0 as u32; let mapped_fmt = super::device_x::pc_uav_linear_format(if raw_fmt == 0 { res_fmt } else { raw_fmt }); - let eff_fmt = super::device_x::pc_shader_view_format(res_fmt, mapped_fmt); + // (an sRGB texture made typeless: its UAV is the linear format of the family) + let eff_fmt = super::device_x::pc_uav_linear_format(super::device_x::pc_shader_view_format(res_fmt, mapped_fmt)); if let Some(c) = patched.as_mut() { if eff_fmt != 0 && (eff_fmt != raw_fmt && (raw_fmt != 0 || eff_fmt != res_fmt)) { c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(eff_fmt as i32); @@ -3106,12 +3488,7 @@ unsafe fn dev_create_uav_checked_inner( 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 { @@ -3195,10 +3572,18 @@ fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) let mut out = match v { Some(v) => *v, None => { - // only a typeless depth buffer needs a description of its own - if !matches!(rf, 19 | 39 | 44 | 53) { + // only a typeless depth buffer needs a description of its own, and an sRGB texture + // with unordered access, typeless too (`device_x::pc_resource_desc`) + let srgb = matches!(rf, 27 | 90) && rd.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0; + if !matches!(rf, 19 | 39 | 44 | 53) && !srgb { return None; } + if srgb && rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE3D, ..Default::default() }; + v.Anonymous.Texture3D = D3D12_TEX3D_SRV { MipLevels: u32::MAX, ..Default::default() }; + v.Format = DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, 0) as i32); + return Some(v); + } let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ..Default::default() }; let slices = u32::from(rd.DepthOrArraySize); // a multisampled depth buffer has only the MS view dimensions @@ -3281,16 +3666,12 @@ unsafe fn dev_create_srv_inner(this: *mut c_void, res: *mut c_void, desc: *const super::vram::clear_tracked_srv(&slot); // Raytracing acceleration structure SRV (pResource == NULL, Location == console GPU VA): // translated shaders read BVH nodes from UMA (`bvh_intersect`), never from a PC DXR SRV, - // so write the RDNA2 BVH descriptor directly and skip forwarding the console VA to PC. + // so write the RDNA2 BVH descriptor directly without reserving a page in the shared heap. if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE) { + let Some(slot) = super::console_heap::shadow_slot(cpu) else { return f(this, res, desc, cpu) }; let va = v.Anonymous.RaytracingAccelerationStructure.Location; - // in a GPU view: its tiles are asked for from the root's on (the size is not known; the - // build wrote the nodes through views that asked for theirs, and a buffer placed there - // has all its tiles) let view = super::view_want::want(super::view_want::Path::Bvh, va, 0x1_0000); let in_uma = va != 0 && (view || crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize))); - // `XCL_BVH_EMPTY=1` (a test): every acceleration structure is an empty one – the title's - // rays hit nothing. Tells what its ray tracing shaders do to the picture and the device. static EMPTY: std::sync::OnceLock = std::sync::OnceLock::new(); let empty = *EMPTY.get_or_init(|| { let on = std::env::var("XCL_BVH_EMPTY").is_ok_and(|v| v.trim() == "1"); @@ -3300,24 +3681,46 @@ unsafe fn dev_create_srv_inner(this: *mut c_void, res: *mut c_void, desc: *const on }); if in_uma && !empty { - // and what rays read past it: the rest of the top level, its bottom levels, the - // parent pointers (`bvh_want`; `XCL_BVH_WALK=0`: the 64 KiB above only) super::bvh_want::view_made(va); + crate::gpu::rt_leave_out::note_structure(va); let w = crate::gpu::desc::bvh_words(va, true); - return super::console_heap::write(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]); + return super::console_heap::write_shadow(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]); } - // (an all-zero descriptor is no empty structure: the shader reads its root at 0x30 of - // window 0) if let Some(at) = empty.then(empty_bvh).flatten() { let w = crate::gpu::desc::bvh_words(at, true); - return super::console_heap::write(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]); + return super::console_heap::write_shadow(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]); } static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { crate::xlog_warn!("D3D12.X: CreateShaderResourceView(RAYTRACING_ACCELERATION_STRUCTURE) at {va:#x} is not in unified memory – writing empty BVH descriptor"); } - return super::console_heap::write(&slot, &[0; 8]); + return super::console_heap::write_shadow(&slot, &[0; 8]); + } + // Buffer SRVs on pages not yet placed in the shared heap: translated shaders read buffers + // through UMA (`buffer_view`), so write the PC mirror and shadow V# without consuming 512 + // shared-heap descriptors for a buffer-only page. + if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER && !res.is_null()) { + if let Some(slot) = super::console_heap::shadow_slot(cpu).filter(|s| !s.sampler && s.index.is_none()) { + if buffer_delta(res as usize) != 0 { + let null_buf = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + ..Default::default() + }; + f(this, std::ptr::null_mut(), &null_buf, slot.pc_srv); + } else { + f(this, res, desc, slot.pc_srv); + } + super::ambient::note_descriptor(slot.at, 0, 0, 0, 0, false); + let b = &v.Anonymous.Buffer; + let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; + let w = buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + trace_preskin_slot("srv_shadow_buf", slot.at, &w); + return super::console_heap::write_shadow(&slot, &w); + } } + let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, desc, cpu) }; // Placed buffers with `buffer_delta != 0` can have unaligned structured offsets on the PC // backing; write a valid null PC buffer SRV so `slot.pc_srv` and `GLOBAL` never keep a stale // descriptor while translated shaders read the exact UMA address via `buffer_view` below. @@ -3363,6 +3766,8 @@ unsafe fn dev_create_srv_inner(this: *mut c_void, res: *mut c_void, desc: *const // A null image SRV was already created and published at `slot.index`. Writing `[0; 8]` // would point shaders at `ResourceDescriptorHeap[0]` (memory window 0 / uninitialized), // so write a valid T# referencing `slot.index` with the view's format class and type. + let amb_idx = if slot.shared_srv != 0 { slot.index } else { 0 }; + super::ambient::note_descriptor(slot.at, amb_idx, 0, 0, 0, false); if let Some(v) = desc.as_ref() { if let Some(ty) = view_dim_to_image_type(v.ViewDimension.0) { let fmt = view_tsharp_format(v.Format); @@ -3372,19 +3777,37 @@ unsafe fn dev_create_srv_inner(this: *mut c_void, res: *mut c_void, desc: *const } return super::console_heap::write(&slot, &[0; 8]); }; + let amb_idx = if slot.shared_srv != 0 { slot.index } else { 0 }; if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER) { + super::ambient::note_descriptor(slot.at, amb_idx, 0, 0, 0, false); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; - return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); + let w = buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + trace_preskin_slot("srv_buf", slot.at, &w); + return super::console_heap::write(&slot, &w); } let rdesc = r.GetDesc(); + let amb_fmt = desc.as_ref().map(|v| v.Format.0).filter(|&f| f != 0).unwrap_or(rdesc.Format.0); + super::ambient::note_descriptor(slot.at, amb_idx, res as usize, amb_fmt, rdesc.Format.0, false); super::lut3d::viewed(res as usize, &rdesc, desc.as_ref(), slot.index, cpu); match srv_tsharp_from_desc(slot.index, &rdesc, desc.as_ref()) { Some(t) => { + super::indexed::note_made(slot.index, &t, desc.as_ref()); super::console_heap::write(&slot, &t); super::vram::track_srv(this as usize, res as usize, &slot, desc.as_ref().copied(), t); } None => { + if trace_preskin() { + static M: AtomicU64 = AtomicU64::new(0); + let k = M.fetch_add(1, Ordering::Relaxed); + if k < 32 { + crate::xlog_info!( + "trace preskin srv_tsharp None #{k}: cpu={cpu:#x} res={res:p} rd=({},{},{},{:#x}) desc={:?}", + rdesc.Dimension.0, rdesc.Width, rdesc.Format.0, rdesc.Flags.0, + desc.as_ref().map(|v| (v.Format.0, v.ViewDimension.0)) + ); + } + } note_buffer_view(); super::console_heap::write(&slot, &[0; 8]); } @@ -3415,6 +3838,19 @@ fn cube_as_cube_array(v: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> Option bool { + static ALLOWED: OnceLock = OnceLock::new(); + *ALLOWED.get_or_init(|| { + match std::env::var("XCL_RT_GATE").ok().map(|s| s.trim().to_ascii_lowercase()).as_deref() { + Some("miss" | "hold" | "1" | "on" | "true") => false, + _ => true, + } + }) +} + +#[allow(dead_code)] unsafe fn resource_at(this: *mut c_void, desc: *const u8, va: u64) -> *mut c_void { type Key = (u64, [u8; 0x38]); static MADE: Mutex>> = Mutex::new(None); @@ -3459,11 +3895,14 @@ unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; let (words, at, len) = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); super::view_want::want(super::view_want::Path::ViewAt, at, len); + trace_preskin_slot("srv_at_buf", slot.at, &words); return super::console_heap::write(&slot, &words); } - let r = resource_at(this, rdesc, va); + let placed = super::format_alias::placed_srv_resource(this, rdesc, va, v.Format.0 as u32); + let r = placed.as_ref().map_or(std::ptr::null_mut(), Interface::as_raw); let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor); dev_create_srv_inner(this, r, &v, cpu); + drop(placed); } /// device #71: the same for an unordered access view ({ the PC's UAV desc; GPU address @0x28; @@ -3480,15 +3919,21 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u let Some(slot) = super::console_heap::slot(cpu) else { return }; let _tracked_write_lock = super::vram::lock_tracked_srv_write(); super::vram::clear_tracked_srv(&slot); + note_unaligned_delta_uav(slot.pc_uav as usize, false); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; let (words, at, len) = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); super::view_want::want(super::view_want::Path::ViewAt, at, len); + // (no buffer is placed there: with `XCL_SPARSE_LAZY` its tiles would have no video memory) + super::sparse::gpu_writes(at as usize, len as usize); + trace_preskin_slot("uav_at_buf", slot.at, &words); return super::console_heap::write(&slot, &words); } - let r = resource_at(this, rdesc, va); + let placed = super::format_alias::placed_uav_resource(this, rdesc, va, v.Format.0 as u32); + let r = placed.as_ref().map_or(std::ptr::null_mut(), Interface::as_raw); let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor); dev_create_uav_x(this, r, std::ptr::null_mut(), &v, cpu); + drop(placed); } /// V# of `n` elements from element `first` of the buffer at `va`, and the bytes it covers @@ -3526,6 +3971,7 @@ fn null_uav_desc( use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT; let dim = desc .map(|v| v.ViewDimension.0) + .filter(|&d| d != 0) .or_else(|| rd.map(resource_dim_to_view)) .unwrap_or(D3D12_UAV_DIMENSION_TEXTURE2D.0); match dim { @@ -3541,7 +3987,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 { @@ -3563,6 +4009,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`), @@ -3602,7 +4079,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) @@ -3629,6 +4106,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, @@ -3652,7 +4130,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, @@ -3660,7 +4138,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, @@ -3675,6 +4159,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, @@ -3691,9 +4183,238 @@ fn uav_companion_srv( srv = v; } } + srv.Format = concrete_srv_format(srv.Format); Some(srv) } +/// PC UAV CPU descriptor handles that were replaced by a null buffer UAV because the placed +/// buffer's `buffer_delta` was not element-aligned (or its counter offset was not 4096-aligned). +/// `ClearUnorderedAccessView*` checks this before calling PC clear with a non-null resource. +static UNALIGNED_DELTA_UAVS: std::sync::RwLock>> = std::sync::RwLock::new(None); +static UNALIGNED_DELTA_UAV_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +pub(super) fn is_unaligned_delta_uav(pc_uav: usize) -> bool { + if UNALIGNED_DELTA_UAV_COUNT.load(Ordering::Relaxed) == 0 || pc_uav == 0 { + return false; + } + UNALIGNED_DELTA_UAVS.read().unwrap().as_ref().is_some_and(|s| s.contains(&pc_uav)) +} + +fn note_unaligned_delta_uav(pc_uav: usize, unaligned: bool) { + if pc_uav == 0 { + return; + } + if unaligned { + let mut g = UNALIGNED_DELTA_UAVS.write().unwrap(); + if g.get_or_insert_with(HashSet::new).insert(pc_uav) { + UNALIGNED_DELTA_UAV_COUNT.fetch_add(1, Ordering::Relaxed); + } + } else if UNALIGNED_DELTA_UAV_COUNT.load(Ordering::Relaxed) != 0 { + if let Some(s) = UNALIGNED_DELTA_UAVS.write().unwrap().as_mut() { + if s.remove(&pc_uav) { + UNALIGNED_DELTA_UAV_COUNT.fetch_sub(1, Ordering::Relaxed); + } + } + } +} + +/// Element byte size for standard DXGI typed buffer formats (`None` for unknown/block-compressed). +fn dxgi_buffer_format_bytes(fmt: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT) -> Option { + use windows::Win32::Graphics::Dxgi::Common::*; + match fmt { + DXGI_FORMAT_R32G32B32A32_TYPELESS + | DXGI_FORMAT_R32G32B32A32_FLOAT + | DXGI_FORMAT_R32G32B32A32_UINT + | DXGI_FORMAT_R32G32B32A32_SINT => Some(16), + DXGI_FORMAT_R32G32B32_TYPELESS + | DXGI_FORMAT_R32G32B32_FLOAT + | DXGI_FORMAT_R32G32B32_UINT + | DXGI_FORMAT_R32G32B32_SINT => Some(12), + DXGI_FORMAT_R16G16B16A16_TYPELESS + | DXGI_FORMAT_R16G16B16A16_FLOAT + | DXGI_FORMAT_R16G16B16A16_UNORM + | DXGI_FORMAT_R16G16B16A16_UINT + | DXGI_FORMAT_R16G16B16A16_SNORM + | DXGI_FORMAT_R16G16B16A16_SINT + | DXGI_FORMAT_R32G32_TYPELESS + | DXGI_FORMAT_R32G32_FLOAT + | DXGI_FORMAT_R32G32_UINT + | DXGI_FORMAT_R32G32_SINT => Some(8), + DXGI_FORMAT_R10G10B10A2_TYPELESS + | DXGI_FORMAT_R10G10B10A2_UNORM + | DXGI_FORMAT_R10G10B10A2_UINT + | DXGI_FORMAT_R11G11B10_FLOAT + | DXGI_FORMAT_R8G8B8A8_TYPELESS + | DXGI_FORMAT_R8G8B8A8_UNORM + | DXGI_FORMAT_R8G8B8A8_UNORM_SRGB + | DXGI_FORMAT_R8G8B8A8_UINT + | DXGI_FORMAT_R8G8B8A8_SNORM + | DXGI_FORMAT_R8G8B8A8_SINT + | DXGI_FORMAT_B8G8R8A8_TYPELESS + | DXGI_FORMAT_B8G8R8A8_UNORM + | DXGI_FORMAT_B8G8R8A8_UNORM_SRGB + | DXGI_FORMAT_B8G8R8X8_TYPELESS + | DXGI_FORMAT_B8G8R8X8_UNORM + | DXGI_FORMAT_B8G8R8X8_UNORM_SRGB + | DXGI_FORMAT_R16G16_TYPELESS + | DXGI_FORMAT_R16G16_FLOAT + | DXGI_FORMAT_R16G16_UNORM + | DXGI_FORMAT_R16G16_UINT + | DXGI_FORMAT_R16G16_SNORM + | DXGI_FORMAT_R16G16_SINT + | DXGI_FORMAT_R32_TYPELESS + | DXGI_FORMAT_R32_FLOAT + | DXGI_FORMAT_R32_UINT + | DXGI_FORMAT_R32_SINT => Some(4), + DXGI_FORMAT_R8G8_TYPELESS + | DXGI_FORMAT_R8G8_UNORM + | DXGI_FORMAT_R8G8_UINT + | DXGI_FORMAT_R8G8_SNORM + | DXGI_FORMAT_R8G8_SINT + | DXGI_FORMAT_R16_TYPELESS + | DXGI_FORMAT_R16_FLOAT + | DXGI_FORMAT_R16_UNORM + | DXGI_FORMAT_R16_UINT + | DXGI_FORMAT_R16_SNORM + | DXGI_FORMAT_R16_SINT + | DXGI_FORMAT_B5G6R5_UNORM + | DXGI_FORMAT_B5G5R5A1_UNORM + | DXGI_FORMAT_B4G4R4A4_UNORM => Some(2), + DXGI_FORMAT_R8_TYPELESS + | DXGI_FORMAT_R8_UNORM + | DXGI_FORMAT_R8_UINT + | DXGI_FORMAT_R8_SNORM + | DXGI_FORMAT_R8_SINT + | DXGI_FORMAT_A8_UNORM => Some(1), + _ => None, + } +} + +fn buffer_uav_element_bytes(desc: &D3D12_UNORDERED_ACCESS_VIEW_DESC) -> Option { + if desc.ViewDimension != D3D12_UAV_DIMENSION_BUFFER { + return None; + } + let b = unsafe { desc.Anonymous.Buffer }; + if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + Some(4) + } else if b.StructureByteStride != 0 { + Some(b.StructureByteStride as u64) + } else { + dxgi_buffer_format_bytes(desc.Format) + } +} + +/// Adjust a PC buffer UAV description by `res_delta` (and `ctr_delta` when `has_counter`). +fn patch_buffer_uav_delta( + desc: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>, + is_buffer_res: bool, + res_delta: u64, + has_counter: bool, + ctr_delta: u64, +) -> Result, ()> { + if res_delta == 0 && (!has_counter || ctr_delta == 0) { + return Ok(None); + } + let is_buf_view = desc.is_some_and(|d| d.ViewDimension == D3D12_UAV_DIMENSION_BUFFER) || is_buffer_res; + if !is_buf_view { + return Ok(None); + } + let Some(d) = desc else { + return Err(()); + }; + if d.ViewDimension != D3D12_UAV_DIMENSION_BUFFER { + return Err(()); + } + let elem = buffer_uav_element_bytes(d).filter(|&e| e > 0).ok_or(())?; + if res_delta % elem != 0 { + return Err(()); + } + let mut patched = *d; + unsafe { + let b = &mut patched.Anonymous.Buffer; + if has_counter && ctr_delta != 0 { + let new_ctr = b.CounterOffsetInBytes.checked_add(ctr_delta).ok_or(())?; + if new_ctr % 4096 != 0 { + return Err(()); + } + b.CounterOffsetInBytes = new_ctr; + } + b.FirstElement = b.FirstElement.checked_add(res_delta / elem).ok_or(())?; + } + Ok(Some(patched)) +} + +#[cfg(test)] +mod uav_buffer_delta_tests { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::*; + + fn buf_uav(fmt: DXGI_FORMAT, first: u64, num: u32, stride: u32, ctr_off: u64, raw: bool) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: fmt, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + FirstElement: first, + NumElements: num, + StructureByteStride: stride, + CounterOffsetInBytes: ctr_off, + Flags: if raw { D3D12_BUFFER_UAV_FLAG_RAW } else { D3D12_BUFFER_UAV_FLAG_NONE }, + }, + }, + } + } + + #[test] + fn patch_buffer_uav_delta_shifts_raw_structured_and_typed_views() { + let raw = buf_uav(DXGI_FORMAT_R32_TYPELESS, 10, 64, 0, 0, true); + assert!(patch_buffer_uav_delta(Some(&raw), true, 0, false, 0).unwrap().is_none()); + let p = patch_buffer_uav_delta(Some(&raw), true, 0x200, false, 0).unwrap().unwrap(); + assert_eq!(unsafe { p.Anonymous.Buffer.FirstElement }, 10 + 128); + + let structured = buf_uav(DXGI_FORMAT_UNKNOWN, 5, 100, 24, 0, false); + let p = patch_buffer_uav_delta(Some(&structured), true, 0x300, false, 0).unwrap().unwrap(); + assert_eq!(unsafe { p.Anonymous.Buffer.FirstElement }, 5 + 32); + assert!(patch_buffer_uav_delta(Some(&structured), true, 0x100, false, 0).is_err()); + + for (fmt, elem) in [ + (DXGI_FORMAT_R8_UINT, 1u64), + (DXGI_FORMAT_R16_UNORM, 2), + (DXGI_FORMAT_R32_UINT, 4), + (DXGI_FORMAT_R11G11B10_FLOAT, 4), + (DXGI_FORMAT_R10G10B10A2_UNORM, 4), + (DXGI_FORMAT_R32G32_FLOAT, 8), + (DXGI_FORMAT_R32G32B32A32_FLOAT, 16), + ] { + let typed = buf_uav(fmt, 3, 16, 0, 0, false); + let p = patch_buffer_uav_delta(Some(&typed), true, elem * 7, false, 0).unwrap().unwrap(); + assert_eq!(unsafe { p.Anonymous.Buffer.FirstElement }, 10); + if elem > 1 { + assert!(patch_buffer_uav_delta(Some(&typed), true, elem - 1, false, 0).is_err()); + } + } + + let with_ctr = buf_uav(DXGI_FORMAT_UNKNOWN, 0, 16, 16, 4096, false); + let p = patch_buffer_uav_delta(Some(&with_ctr), true, 64, true, 8192).unwrap().unwrap(); + assert_eq!(unsafe { (p.Anonymous.Buffer.FirstElement, p.Anonymous.Buffer.CounterOffsetInBytes) }, (4, 12288)); + assert!(patch_buffer_uav_delta(Some(&with_ctr), true, 64, true, 128).is_err()); + + assert!(patch_buffer_uav_delta(None, true, 0x100, false, 0).is_err()); + let unknown = buf_uav(DXGI_FORMAT_UNKNOWN, 0, 16, 0, 0, false); + assert!(patch_buffer_uav_delta(Some(&unknown), true, 0x100, false, 0).is_err()); + } + + #[test] + fn unaligned_delta_uav_tracking_sets_and_clears() { + let handle = 0xDEAD_BEEF_1234usize; + assert!(!is_unaligned_delta_uav(handle)); + note_unaligned_delta_uav(handle, true); + assert!(is_unaligned_delta_uav(handle)); + note_unaligned_delta_uav(handle, false); + assert!(!is_unaligned_delta_uav(handle)); + } +} + unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, counter: *mut c_void, desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, cpu: u64) { let rd_opt = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()); // a UAV of the stencil plane of a depth buffer with unordered access: a view of its twin @@ -3709,7 +4430,7 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, if let Some(c) = copy.as_mut() { if let Some(rd) = rd_opt.as_ref() { let rf = rd.Format.0 as u32; - c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32) as i32); + c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_uav_linear_format(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32)) as i32); } else { c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_view_format(c.Format.0 as u32) as i32); if c.Format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN && view_dim_to_image_type(c.ViewDimension.0).is_some() { @@ -3735,8 +4456,30 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, // refuses the pair, `device_x::pc_resource_desc`): a null view – a UAV of it is an invalid // call, and the device is removed (0x887A0001) let no_uav = rd_opt.is_some_and(|d| d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0); + // Placed buffers with `buffer_delta != 0` start below the title's VA (`va & !0xFFFF`). Shift + // the PC UAV's `FirstElement` (and `CounterOffsetInBytes`) by the delta so PC UAV clears and + // pipelines hit the title's true buffer instead of `[va & !0xFFFF, va)` in live CPU RAM; if + // the delta is unaligned, bind a null PC UAV and skip PC clears on it. + let res_delta = buffer_delta(res as usize); + let ctr_delta = if counter.is_null() { 0 } else { buffer_delta(counter as usize) }; + let is_buf_res = rd_opt.is_some_and(|d| d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER); + let (pc_uav_desc_patched, unaligned_delta) = if !no_uav { + match patch_buffer_uav_delta(desc.as_ref(), is_buf_res, res_delta, !counter.is_null(), ctr_delta) { + Ok(patched) => (patched, false), + Err(()) => (None, true), + } + } else { + (None, false) + }; + let pc_uav_desc = pc_uav_desc_patched.as_ref().map_or(desc, |d| d as *const _); let null_desc = null_uav_desc(desc.as_ref(), rd_opt.as_ref()); + let null_buf_desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + ..Default::default() + }; let pc_uav = |at: u64| { + note_unaligned_delta_uav(at as usize, unaligned_delta); if no_uav { static N: AtomicU64 = AtomicU64::new(0); if let Some(why) = null_why { @@ -3745,8 +4488,16 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, crate::xlog_warn!("D3D12.X: a UAV of a resource that cannot have one on the PC (a depth buffer) – a null view"); } f(this, std::ptr::null_mut(), std::ptr::null_mut(), &null_desc, at) + } else if unaligned_delta { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!( + "D3D12.X: buffer UAV on placed resource {res:p} has unaligned delta (res_delta={res_delta:#x}, ctr_delta={ctr_delta:#x}) – binding null PC UAV" + ); + } + f(this, std::ptr::null_mut(), std::ptr::null_mut(), &null_buf_desc, at) } else { - f(this, res, counter, desc, at) + f(this, res, counter, pc_uav_desc, at) } }; let Some(slot) = super::console_heap::slot(cpu) else { return pc_uav(cpu) }; @@ -3754,9 +4505,11 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, super::vram::clear_tracked_srv(&slot); pc_uav(slot.pc_uav); super::lut3d::slot_reused(slot.index, cpu, res as usize, || format!("an unordered access view of {res:p} (its companion view)")); - super::console_heap::publish(&slot, true, if no_uav { 0 } else { res as usize }); + super::console_heap::publish(&slot, true, if no_uav || unaligned_delta { 0 } else { res as usize }); super::console_heap::note_resource(&slot, res as usize); + let amb_idx = if slot.shared_srv != 0 { slot.index } else { 0 }; let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else { + super::ambient::note_descriptor(slot.at, amb_idx, 0, 0, 0, true); // A null image UAV was already created and published at `slot.index + 1`. Create a // matching null companion SRV at `slot.index` and write a valid T# referencing // `slot.index` so shaders never fall back to `ResourceDescriptorHeap[0]` / `[1]`. @@ -3775,9 +4528,12 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, }; let rd = rd_opt.unwrap(); if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER) { + super::ambient::note_descriptor(slot.at, amb_idx, 0, 0, 0, true); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; - return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); + let w = buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + trace_preskin_slot("uav_buf", slot.at, &w); + return super::console_heap::write(&slot, &w); } // UAV dimensions: 1 buffer, 2 tex1d, 3 tex1d array, 4 tex2d, 5 tex2d array, 8 tex3d let (format, dim, array, mip) = match desc.as_ref() { @@ -3795,6 +4551,8 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, } None => (rd.Format, resource_dim_to_view(&rd), rd.DepthOrArraySize as u32, 0), }; + let amb_fmt = if format.0 != 0 { format.0 } else { rd.Format.0 }; + super::ambient::note_descriptor(slot.at, amb_idx, res as usize, amb_fmt, rd.Format.0, true); super::lut3d::wrote(res as usize, false, || { let first = desc.as_ref().filter(|v| v.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE3D).map_or(0, |v| v.Anonymous.Texture3D.FirstWSlice); format!("an unordered access view made in console slot {cpu:#x} (T# index {}, the UAV at + 1): format {}, mip {mip}, depth slices {first} (+{})", slot.index, format.0, array as i32) @@ -4182,8 +4940,8 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, in f(this, allocator, resolved as *mut c_void) }; preserve_vtable(this, ext); - if hr >= 0 { - if !super::title_textures::is_own_work() && !super::present::presenting() { + if hr >= 0 && !super::title_textures::is_own_work() { + if !super::present::presenting() { super::title_textures::forget_list_closed(this as usize); } super::list_x::on_pc_reset(this); @@ -4622,6 +5380,19 @@ pub(super) unsafe fn note_reserved(hr: HRESULT, ppv: *mut *mut c_void) -> HRESUL hr } +/// `res` is no longer one of the reserved resources `note_reserved` keeps (a spare or an evicted one +/// of `vram`'s pool, which goes without the title's Release). +pub(super) fn forget_reserved(res: usize) { + if let Some(s) = RESERVED.lock().unwrap().as_mut() { + s.remove(&res); + } +} + +#[cfg(test)] +pub(super) fn is_noted_reserved(res: usize) -> bool { + RESERVED.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&res)) +} + unsafe fn is_reserved(res: *mut c_void) -> bool { let kept = RESERVED.lock().unwrap().as_ref().and_then(|m| m.get(&(res as usize)).copied()); kept.is_some_and(|k| desc_of(res) == Some(k)) @@ -4992,6 +5763,9 @@ fn dummy_mesh() -> Option<&'static (Vec, Vec)> { } pub(super) fn compile(src: &str, target: &str) -> Vec { + // D3DCompile only, unlike the other helpers (`dxc::compile_sm6_first`): built with DXC, + // scatter.rs's program put the title's writes in the wrong places (stretched triangles in the + // G-buffer); Wine's D3DCompile refuses it and its correct copy fallback runs unsafe { let mut blob = None; let t = format!("{target}\0"); @@ -5384,14 +6158,16 @@ unsafe fn abi_rs_raw(this: *mut c_void) -> Option<*mut c_void> { /// A compute pipeline with a console CS: `None` = not a console shader, `Some(Err)` = console /// shader the recompiler could not take, `Some(Ok(hr))` = translated pipeline created (or the /// driver's verdict on it). -/// DXIL size from which a pipeline's driver compile is "huge" (default 256 KB, `XCL_HUGE_PSO_BYTES`): +/// DXIL size from which a pipeline's driver compile is "huge" (default 64 KB, `XCL_HUGE_PSO_BYTES`; +/// 256 KB before: on an RX 9070 XT a retail title's cold 90 – 260 KB compute programs took 1 – 38 s +/// and up to 5.5 GB each, four at a time, and its run was ended for RAM): /// a compute one goes to the background, and any of them built on an `xcl-pso*` worker waits /// for one of the `XCL_HUGE_PSO_CONCURRENCY` slots. NVIDIA's compiler (nvgpucomp64) takes /// minutes and ~1 GB for a 1 – 2 MB program; ~20 of them at once (one per worker) were slower /// in total than 1 – 2 at a time. Small programs (ms each) never wait. pub(super) fn huge_pso_bytes() -> usize { static V: std::sync::OnceLock = std::sync::OnceLock::new(); - *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_BYTES").ok().as_deref(), 256 << 10, 1, usize::MAX)) + *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_BYTES").ok().as_deref(), 64 << 10, 1, usize::MAX)) } /// `XCL_SKIP_CS_KB=`: the DXIL size in bytes from which a compute program gets no pipeline @@ -5416,13 +6192,14 @@ mod skip_cs_tests { } } -/// Huge driver compiles at once on the workers (default 1, `XCL_HUGE_PSO_CONCURRENCY`). +/// Huge driver compiles at once on the workers (default 2, `XCL_HUGE_PSO_CONCURRENCY`; 2 with the +/// 64 KB threshold is what the measured retail runs used: one at a time left its loading waiting). fn huge_pso_concurrency() -> usize { static V: std::sync::OnceLock = std::sync::OnceLock::new(); - *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_CONCURRENCY").ok().as_deref(), 1, 1, 64)) + *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_CONCURRENCY").ok().as_deref(), 2, 1, 64)) } -/// Hard cap on concurrent huge (`>= 256 KB`) driver compiles even when wanted by a title bind +/// Hard cap on concurrent huge (`>= huge_pso_bytes()`) driver compiles even when wanted by a title bind /// (`XCL_HUGE_PSO_WANTED_CONCURRENCY`, default 2, always `>= huge_pso_concurrency()`). Prevents a /// burst of lazy compute binds from launching 10+ huge driver compiles simultaneously and spiking /// process commit into OOM, while still letting a wanted build overtake 1 background build. @@ -5449,18 +6226,37 @@ struct Slots { wanted_most: usize, /// compiles that are not built ahead of their first use waiting for a slot (`big_compile_turn`) urgent: AtomicUsize, + /// compiles a live title thread is currently blocked waiting on (`big_compile_turn`): while + /// non-zero, non-wanted builds (ahead or late) do not take a freed slot ahead of them + wanted_waiters: AtomicUsize, /// a build ahead of its pipeline's first use may take a slot (`big_compile_turn`) ahead: bool, } impl Slots { const fn new(most: usize, wanted_most: usize) -> Slots { - Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most, wanted_most, urgent: AtomicUsize::new(0), ahead: true } + Slots { + n: Mutex::new(0), + cv: std::sync::Condvar::new(), + most, + wanted_most, + urgent: AtomicUsize::new(0), + wanted_waiters: AtomicUsize::new(0), + ahead: true, + } } /// `new` for a lane whose slots no build ahead of its pipeline's first use takes. const fn closed_to_ahead(most: usize, wanted_most: usize) -> Slots { - Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most, wanted_most, urgent: AtomicUsize::new(0), ahead: false } + Slots { + n: Mutex::new(0), + cv: std::sync::Condvar::new(), + most, + wanted_most, + urgent: AtomicUsize::new(0), + wanted_waiters: AtomicUsize::new(0), + ahead: false, + } } fn most(&self) -> usize { @@ -5599,6 +6395,8 @@ fn driver_compile_identified(kind: &str, bytes: usize, gate: bool, record: Op } }); drop(gate_stall); + // (after the slot: a compile holding one waits for RAM, not one that has none yet) + let _ram = (gate && worker).then(|| pso_ram_floor().and_then(|floor| RAM_GATE.turn(bytes, floor, available_ram))).flatten(); let waited = waited.elapsed(); static SEQUENCE: AtomicU64 = AtomicU64::new(0); let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1; @@ -5687,15 +6485,22 @@ fn gate_compute_driver_compile(has_cached_blob: bool) -> bool { fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wanted: impl Fn() -> bool, ahead: impl Fn() -> bool) -> SlotGuard { const LOOK: std::time::Duration = std::time::Duration::from_millis(50); let mut n = slots.n.lock().unwrap(); - // (counted in `urgent` while it waits) + // (counted in `urgent` / `wanted_waiters` while it waits) let mut queued = false; let mut parked = None; + let mut queued_wanted = false; let guard = loop { let is_wanted = wanted(); let cap = if is_wanted { slots.wanted_most() } else { slots.most() }; let ahead = !is_wanted && ahead(); let open = slots.ahead || !ahead; - if open && *n < cap && (is_wanted || commit_free()) && !(ahead && slots.urgent.load(Ordering::Acquire) > 0) { + let yielded_to_wanted = !is_wanted && slots.wanted_waiters.load(Ordering::Acquire) > 0; + if open + && *n < cap + && (is_wanted || commit_free()) + && !yielded_to_wanted + && !(ahead && slots.urgent.load(Ordering::Acquire) > 0) + { *n += 1; break SlotGuard(slots); } @@ -5706,11 +6511,21 @@ fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wante if parked.is_none() { parked = Some(super::pso_async::parked_for_big_compile()); } + if is_wanted && !queued_wanted { + queued_wanted = true; + slots.wanted_waiters.fetch_add(1, Ordering::AcqRel); + } else if !is_wanted && queued_wanted { + queued_wanted = false; + slots.wanted_waiters.fetch_sub(1, Ordering::AcqRel); + } n = slots.cv.wait_timeout(n, LOOK).unwrap().0; }; if queued { slots.urgent.fetch_sub(1, Ordering::AcqRel); } + if queued_wanted { + slots.wanted_waiters.fetch_sub(1, Ordering::AcqRel); + } guard } @@ -5744,6 +6559,103 @@ fn big_compile_headroom(dxil_len: usize) -> u64 { (3u64 << 30).max(dxil_len as u64 * 512) } +/// `XCL_PSO_RAM_FLOOR_MB=` (unset or 0: off): a driver compile of `RAM_GATED_BYTES` of DXIL or +/// more on a pipeline worker starts only while the RAM available, less what the gated compiles +/// still running are expected to take (`compile_ram_estimate`), leaves n MB - or when no other one +/// runs, so one always goes on. The commit headroom of `big_compile_turn` does not see this: on a +/// PC with 32 GB of RAM and 77 GB of commit, four cold compiles of a retail title's 200 KB compute +/// programs (4 - 5.5 GB each in the compact form) took the title from 15 to 25 GB within seconds +/// and the memory guard ended it at 3.6 GB of free RAM, with 49 GB of commit still free. The +/// concurrency then follows the free RAM, up to the slots' caps when there is plenty. +fn pso_ram_floor() -> Option { + static V: std::sync::OnceLock> = std::sync::OnceLock::new(); + *V.get_or_init(|| pso_ram_floor_of(std::env::var("XCL_PSO_RAM_FLOOR_MB").ok().as_deref())) +} + +fn pso_ram_floor_of(v: Option<&str>) -> Option { + v.and_then(|v| v.trim().parse::().ok()).filter(|&mb| mb > 0).map(|mb| mb << 20) +} + +/// DXIL from which a driver compile waits for RAM (`pso_ram_floor`): smaller ones take +/// milliseconds and tens of MB. +const RAM_GATED_BYTES: usize = 64 << 10; + +/// The RAM a cold driver compile of `bytes` of DXIL is expected to take at most: 8 KB a byte. +/// Measured on an RX 9070 XT (amdxc64, cold cache, 2026-11-29): the plain form of a retail +/// title's 140 - 256 KB compute programs took 0.6 - 1.1 GB (4 - 5 KB a byte), the compact form +/// (`XCL_DIRECT_COMPACT_MIN`) of the same programs 2.9 - 6.4 GB (20 - 29 KB a byte). +fn compile_ram_estimate(bytes: usize) -> u64 { + bytes as u64 * 8192 +} + +/// The physical memory available now (None: not known). +fn available_ram() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullAvailPhys) +} + +/// The driver compiles that waited for RAM and still run: how many, and the RAM they are expected +/// to take (`pso_ram_floor`). +struct RamGate { + running: Mutex<(usize, u64)>, + cv: std::sync::Condvar, +} + +static RAM_GATE: RamGate = RamGate { running: Mutex::new((0, 0)), cv: std::sync::Condvar::new() }; + +/// A compile's place among `RamGate::running` until it ends. +struct RamTurn(&'static RamGate, u64); + +impl Drop for RamTurn { + fn drop(&mut self) { + let mut r = self.0.running.lock().unwrap(); + r.0 -= 1; + r.1 = r.1.saturating_sub(self.1); + self.0.cv.notify_all(); + } +} + +impl RamGate { + /// Waits until a compile of `bytes` leaves `floor` of the RAM `available` says is free, less + /// the running ones' estimates, or until none runs (None: below `RAM_GATED_BYTES`). + fn turn(&'static self, bytes: usize, floor: u64, available: impl Fn() -> Option) -> Option { + if bytes < RAM_GATED_BYTES { + return None; + } + let need = compile_ram_estimate(bytes); + let mut r = self.running.lock().unwrap(); + let mut logged = false; + let started = std::time::Instant::now(); + loop { + let fits = available().is_none_or(|a| a.saturating_sub(r.1) >= floor.saturating_add(need)); + if r.0 == 0 || fits { + break; + } + if !logged && started.elapsed() >= std::time::Duration::from_secs(1) { + logged = true; + static N: AtomicUsize = AtomicUsize::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: a driver compile of {bytes} B DXIL waits for RAM (XCL_PSO_RAM_FLOOR_MB: {} MB to stay free; {} running, {} MB expected of them, {} MB available) ({} so far)", + floor >> 20, + r.0, + r.1 >> 20, + available().unwrap_or(0) >> 20, + n + 1 + ); + } + } + r = self.cv.wait_timeout(r, std::time::Duration::from_millis(250)).unwrap().0; + } + r.0 += 1; + r.1 += need; + Some(RamTurn(self, need)) + } +} + /// That much commit is free (true when that is not known). pub(super) fn big_compile_commit_free(need: u64) -> bool { use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; @@ -5821,6 +6733,53 @@ mod big_compile_tests { use std::sync::atomic::AtomicBool; use std::time::{Duration, Instant}; + #[test] + fn the_ram_floor_is_in_mib_and_off_unless_positive() { + assert_eq!(pso_ram_floor_of(Some(" 6144 ")), Some(6144 << 20)); + assert_eq!(pso_ram_floor_of(Some("0")), None); + assert_eq!(pso_ram_floor_of(Some("lots")), None); + assert_eq!(pso_ram_floor_of(None), None); + } + + /// A gated compile starts when it leaves the floor free beside what the running ones are + /// expected to take, or when none runs; a small one is not gated. + #[test] + fn driver_compiles_start_as_the_free_ram_allows() { + static G: RamGate = RamGate { running: Mutex::new((0, 0)), cv: std::sync::Condvar::new() }; + let gb = 1u64 << 30; + // expected: 1 GB + let bytes = 128 << 10; + let available = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(2 * gb)); + let a = available.clone(); + let now = move || Some(a.load(Ordering::Relaxed)); + assert!(G.turn(1024, 8 * gb, now.clone()).is_none(), "a small compile is not gated"); + let first = G.turn(bytes, 8 * gb, now.clone()).expect("the first goes on whatever the RAM"); + let started = std::sync::Arc::new(AtomicBool::new(false)); + let (s, n) = (started.clone(), now.clone()); + let second = std::thread::spawn(move || { + let t = G.turn(bytes, 8 * gb, n); + s.store(true, Ordering::Release); + t + }); + std::thread::sleep(Duration::from_millis(400)); + assert!(!started.load(Ordering::Acquire), "2 GB available: the second waits"); + // the 8 GB floor + 1 GB for it + the 1 GB the first is expected to take + available.store(10 * gb, Ordering::Relaxed); + let t = Instant::now(); + while !started.load(Ordering::Acquire) && t.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(started.load(Ordering::Acquire), "10 GB available: the second goes on"); + let second = second.join().unwrap(); + assert_eq!(*G.running.lock().unwrap(), (2, 2 * gb)); + drop(first); + drop(second); + assert_eq!(*G.running.lock().unwrap(), (0, 0)); + // when no other runs, one goes on with no RAM to spare + available.store(0, Ordering::Relaxed); + assert!(G.turn(bytes, 8 * gb, now).is_some()); + } + #[test] fn a_late_build_waits_for_half_the_headroom() { let bytes = huge_pso_bytes(); @@ -6195,11 +7154,13 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const LAST_COMPUTE_RS.with(|c| c.set(rs)); note_pso_rs(*ppv, rs as *mut c_void); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); + super::ambient::note_compute_pso(*ppv as usize, cs); if let Some(i) = crate::gpu::recomp::pso::compute_interface(cs) { PSO_USER_SGPRS.insert(*ppv as usize, (i.user_sgprs, i.threads)); } note_translated_compute(0, ppv); PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (record, 0)); + trace_cs_name(record, cs); if super::gpu_profile::on() || super::gpu_times::enabled() { super::gpu_profile::note_compute(record, cs, dxil.len(), wave32_only(this)); } @@ -6236,6 +7197,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); + super::ambient::note_compute_pso(*ppv as usize, cs); if let Some(i) = crate::gpu::recomp::pso::compute_interface(cs) { PSO_USER_SGPRS.insert(*ppv as usize, (i.user_sgprs, i.threads)); } @@ -6244,6 +7206,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const wave32_only(this), crate::gpu::recomp::pso::mem_windows(), compiled.dispatch_remap.is_some()); note_translated_compute(hr, ppv); PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (record, 0)); + trace_cs_name(record, cs); if super::gpu_profile::on() || super::gpu_times::enabled() { super::gpu_profile::note_compute(record, cs, dxil.len(), wave32_only(this)); } @@ -8243,6 +9206,8 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", shader_bytes(&d.PS))]); + super::ambient::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); + super::mirror::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); TRANSLATED_GRAPHICS.insert(*ppv as usize, ()); note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); if (super::gpu_profile::on() || super::gpu_times::enabled()) && !super::present::trace_frame() { @@ -8325,9 +9290,38 @@ pub(in crate::hle::d3d12x) mod compute_build_key; /// The title's borrowed root signature is cleared; translated paths install XCL's ABI signature. #[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>), +} + +/// Entries an interning pool of shader bytecode takes between two sweeps of its dead ones: a +/// `Weak` to an `Arc<[u8]>` keeps the whole allocation, bytes and all, until it is dropped, so a +/// pool swept only at 8192 / 16384 entries held thousands of dead shaders' bytes. +pub(super) const SHADER_POOL_SWEEP: usize = 1024; + +/// `intern_shader_blob`'s pool, and its length at which the dead entries are swept next. +#[allow(clippy::type_complexity)] +static SHADER_BLOB_POOL: Mutex>, usize)>> = Mutex::new(None); + +/// Share one heap copy of identical console shader bytecodes across all live `OwnedDesc`s. +fn intern_shader_blob(bytes: &[u8]) -> std::sync::Arc<[u8]> { + use std::sync::{Arc, Weak}; + let key = (crate::gpu::shader::fnv64(bytes), bytes.len()); + let mut g = SHADER_BLOB_POOL.lock().unwrap_or_else(|e| e.into_inner()); + let (m, next_sweep) = g.get_or_insert_with(|| (HashMap::new(), SHADER_POOL_SWEEP)); + if let Some(arc) = m.get(&key).and_then(Weak::upgrade) { + if arc.as_ref() == bytes { + return arc; + } + } + let arc: Arc<[u8]> = Arc::from(bytes); + if m.len() >= *next_sweep { + m.retain(|_, w| w.strong_count() > 0); + *next_sweep = m.len() + SHADER_POOL_SWEEP; + } + m.insert(key, Arc::downgrade(&arc)); + arc } unsafe impl Send for OwnedDesc {} @@ -8381,6 +9375,29 @@ mod shaders_key_tests { assert_ne!(key, super::shaders_key(&[a, [4u8, 6].into()])); assert_ne!(super::shaders_key(&[] as &[Arc<[u8]>]), 0); } + + #[test] + fn interned_shader_blobs_share_one_allocation() { + let a = super::intern_shader_blob(&[0xDE, 0xAD, 0xBE, 0xEF, 1, 2, 3, 4]); + let b = super::intern_shader_blob(&[0xDE, 0xAD, 0xBE, 0xEF, 1, 2, 3, 4]); + assert!(std::sync::Arc::ptr_eq(&a, &b)); + let c = super::intern_shader_blob(&[0xDE, 0xAD, 0xBE, 0xEF, 1, 2, 3, 5]); + assert!(!std::sync::Arc::ptr_eq(&a, &c)); + } + + /// Shaders no pipeline holds any more do not pile up in the pool (each dead entry keeps its + /// bytes): after 3000 short-lived ones, fewer than two sweeps' worth are left. + #[test] + fn interned_shader_blobs_that_died_are_swept() { + for i in 0u32..3000 { + let mut bytes = vec![0xC3u8; 64]; + bytes[..4].copy_from_slice(&i.to_le_bytes()); + drop(super::intern_shader_blob(&bytes)); + } + let g = super::SHADER_BLOB_POOL.lock().unwrap(); + let dead = g.as_ref().map_or(0, |(m, _)| m.values().filter(|w| w.strong_count() == 0).count()); + assert!(dead < 2 * super::SHADER_POOL_SWEEP, "{dead} dead entries kept"); + } } impl OwnedDesc { @@ -8429,7 +9446,7 @@ 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>) { if let Some(bytes) = shader_bytes(b) { - blobs.push(bytes.into()); + blobs.push(intern_shader_blob(bytes)); let v = blobs.last().unwrap(); *b = bytecode(v); } else { @@ -8508,7 +9525,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).into()); + blobs.push(intern_shader_blob(std::slice::from_raw_parts(p as *const u8, n))); buf[at..at + 8].copy_from_slice(&(blobs.last().unwrap().as_ptr() as u64).to_le_bytes()); } else { return None; @@ -8698,6 +9715,27 @@ unsafe fn go_background( // a big compute program that writes nothing but images: binds can go on without it let image_only = compute && super::pso_async::image_skip() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); let lazy = super::pso_async::lazy(); + // one of the BVH builder's programs while its passes are left out: binds go on without it too + let image_only = image_only || compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| super::bvh_spare::spared(b, desc))); + // the stand-in lighting's passes by the pipeline the title binds: the PC pipelines + // built for them later are other objects, so roles noted only there were never found + match &owned { + OwnedDesc::Compute(_, b) => { + if let Some(cs) = b.first() { + super::ambient::note_compute_pso(*ppv as usize, cs); + } + } + OwnedDesc::Graphics(_, b, ..) | OwnedDesc::Stream(_, _, b) => { + for blob in b.iter() { + super::ambient::note_graphics_pso(*ppv as usize, Some(&blob[..])); + } + } + } + // (a graphics pipeline's shaders by name: one that draws once and is kept is waited for) + let names = match &owned { + OwnedDesc::Graphics(_, b, ..) | OwnedDesc::Stream(_, _, b) => stage_names(b, &parts), + OwnedDesc::Compute(..) => None, + }; let owned = std::sync::Arc::new(owned); // (only a lazy pipeline is warmed: the backlog translates what it holds before the driver builds) let warm: Option = (lazy && matches!(*owned, OwnedDesc::Graphics(..))).then(|| { @@ -8727,6 +9765,19 @@ unsafe fn go_background( if driver != 0 { super::pso_async::shared(*ppv as usize, driver); } + if let Some(names) = names { + if drawn_once(&names) { + super::pso_async::kept(*ppv as usize); + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: pipeline of {names}: what it draws is drawn once and kept – its draws wait until it is built (#{n})"); + } + } + if super::pso_async::trace_late() { + super::pso_async::named(*ppv as usize, names); + } + } if image_only { super::pso_async::image_only(*ppv as usize); } @@ -8889,11 +9940,28 @@ unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const hr } +/// Whether `desc`'s console compute program is one `XCL_RT_LEAVE_OUT` leaves out. +unsafe fn rt_left_out(desc: *const c_void) -> bool { + if !crate::gpu::rt_leave_out::enabled() || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return false; + } + let d = &*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC); + shader_bytes(&d.CS).is_some_and(|cs| crate::gpu::recomp::pso::is_console(cs) && crate::gpu::rt_leave_out::left_out(cs)) +} + unsafe fn compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let _cost = crate::hle::api_cost::time(crate::hle::api_cost::Call::Pipeline); super::null::capture_compute_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); - let (mut console, missed) = if super::pso_async::enabled() { attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) } else { (translated_compute_pso(this, f, desc, riid, ppv), false) }; + // `XCL_RT_LEAVE_OUT`: not translated or built; the dummy program below, its dispatches skipped + let left_out = rt_left_out(desc); + let (mut console, missed) = if left_out { + (Some(Err(())), false) + } else if super::pso_async::enabled() { + attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) + } else { + (translated_compute_pso(this, f, desc, riid, ppv), false) + }; if missed { if let Some(hr) = own_compute(desc).and_then(|o| go_background(this, f, desc, riid, ppv, true, o, standin_compute, compute_key, build_compute)) { // a console program the worker is translating (its root signature comes with it); @@ -8929,7 +9997,15 @@ unsafe fn compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, copy.CS = bytecode(&dummy().cs); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let hr2 = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); - note_fallback("compute PSO", hr, hr2 >= 0); + if left_out && hr2 >= 0 && !ppv.is_null() { + // (`XCL_RT_LEAVE_OUT_COUNT`: its dispatches' work is counted) + if let Some(cs) = shader_bytes(&(*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC)).CS) { + super::left_out::note(*ppv as usize, cs); + } + } + if !left_out || hr2 < 0 { + note_fallback("compute PSO", hr, hr2 >= 0); + } if console.is_some() { note_console_compute(hr2, ppv); } @@ -9007,7 +10083,7 @@ pub(super) fn register_two_pass_for_test(pso: usize, kind: &'static str) { compute: 0, compute_rs: 0, mesh_rs: 0, - record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 64, max_vertices: 64, max_primitives: 64 }, + record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 64, max_vertices: 64, max_primitives: 64, params: None }, mesh_groups_per_record: 1, kind, }), @@ -9926,20 +11002,100 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri out.raw(*ty, &p, palign == 8); continue; } + // `XCL_TRACE_MS_FORCE=1` (a diagnostic): the traced mesh shader's pipelines draw with no + // depth or stencil test (DEPTH_STENCIL / 1 / 2: DepthEnable, .., .., StencilEnable) and + // no culling (RASTERIZER / 1 / 2: FillMode, CullMode) + if trace_ms() == Some(crate::gpu::shader::fnv64(ms)) && std::env::var("XCL_TRACE_MS_FORCE").is_ok_and(|v| v.trim() == "1") { + let mut p = payload.to_vec(); + if matches!(*ty, 11 | 21 | 26) && p.len() >= 16 { + p[0..4].copy_from_slice(&0u32.to_le_bytes()); + p[12..16].copy_from_slice(&0u32.to_le_bytes()); + crate::xlog_info!("trace MS force: depth and stencil tests off (subobject {ty})"); + out.raw(*ty, &p, palign == 8); + continue; + } + if matches!(*ty, 10 | 27 | 28) && p.len() >= 8 { + p[4..8].copy_from_slice(&1u32.to_le_bytes()); + crate::xlog_info!("trace MS force: culling off (subobject {ty})"); + out.raw(*ty, &p, palign == 8); + continue; + } + } + // DEPTH_STENCIL / 1 / 2 start alike: DepthEnable, DepthWriteMask, DepthFunc + if matches!(*ty, 11 | 21 | 26) && payload.len() >= 12 { + let word = |k: usize| u32::from_le_bytes(payload[4 * k..4 * k + 4].try_into().unwrap()); + mesh_depth_diag(rt_count, [word(0), word(1), word(2)], crate::gpu::shader::fnv64(ms)); + if let Some(func) = mesh_depth_as(word(1), word(2)).filter(|_| word(0) != 0) { + let mut p = payload.to_vec(); + p[8..12].copy_from_slice(&func.to_le_bytes()); + out.raw(*ty, &p, palign == 8); + continue; + } + } out.raw(*ty, payload, palign == 8); } } let node_mask = stream_node_mask(&subs); let hr = finish_two_pass(this, &out, tp, rs, &ps_samplers, node_mask, "MS", riid, ppv); if hr >= 0 { + super::ambient::note_graphics_pso(*ppv as usize, console_ps); + super::mirror::note_graphics_pso(*ppv as usize, console_ps); super::dred::label(*ppv as usize, &[("ms", Some(ms)), ("ps", console_ps)]); - if super::gpu_times::enabled() { - PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(ms), console_ps.map_or(0, crate::gpu::shader::fnv64))); + if super::gpu_times::enabled() || trace_ms().is_some() || trace_record_all() { + let ms_h = crate::gpu::shader::fnv64(ms); + let ps_h = console_ps.map_or(0, crate::gpu::shader::fnv64); + PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (ms_h, ps_h)); + trace_stage_name("MS", ms_h, ms); + if let Some(ps) = console_ps { + trace_stage_name("PS", ps_h, ps); + } } } Some(hr) } +/// `XCL_MESH_DEPTH_LOG=1` (diagnostic): the depth state of the title's mesh pipelines as they are +/// built – each (render targets, DepthEnable, DepthWriteMask, DepthFunc) the first time, with the +/// mesh shader that came with it, then at every power of two. +fn mesh_depth_diag(rts: u32, depth: [u32; 3], ms: u64) { + static ON: OnceLock = OnceLock::new(); + if !*ON.get_or_init(|| std::env::var("XCL_MESH_DEPTH_LOG").is_ok_and(|v| v == "1")) { + return; + } + static SEEN: Mutex>> = Mutex::new(None); + let n = { + let mut g = SEEN.lock().unwrap(); + let n = g.get_or_insert_with(HashMap::new).entry((rts, depth)).or_insert(0); + *n += 1; + *n + }; + if n.is_power_of_two() { + crate::xlog_info!("D3D12.X: mesh pipeline depth state: {rts} render targets, depth enable {} write {} func {}: {n} so far (MS {ms:016x})", depth[0], depth[1], depth[2]); + } +} + +/// `XCL_MESH_DEPTH_MAP=wf=[,…]` (diagnostic): a mesh pipeline with that depth +/// write mask and comparison gets the comparison on the right instead (`w0f7=8`: the ones that +/// test GREATER_EQUAL without writing always pass) – tells a colour pass that fails its depth +/// test against the pre-pass from one that draws nothing at all. +fn mesh_depth_as(write: u32, func: u32) -> Option { + static V: OnceLock> = OnceLock::new(); + V.get_or_init(|| mesh_depth_map(std::env::var("XCL_MESH_DEPTH_MAP").ok().as_deref())) + .iter() + .find(|m| (m.0, m.1) == (write, func)) + .map(|m| m.2) +} + +fn mesh_depth_map(v: Option<&str>) -> Vec<(u32, u32, u32)> { + let one = |s: &str| -> Option<(u32, u32, u32)> { + let (from, to) = s.trim().split_once('=')?; + let (w, f) = from.strip_prefix('w')?.split_once('f')?; + let to: u32 = to.parse().ok()?; + (1..=8).contains(&to).then_some((w.parse().ok()?, f.parse().ok()?, to)) + }; + v.map(|v| v.split(',').filter_map(one).collect()).unwrap_or_default() +} + /// A graphics PSO with a console VS + GS: the GS pipeline in two passes, as a mesh pipeline /// with the description's state. unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, vs: &[u8], gs: &[u8], riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { @@ -10011,6 +11167,8 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE } let hr = finish_two_pass(this, &out, tp, rs, &ps_samplers, d.NodeMask, "GS", riid, ppv); if hr >= 0 { + super::ambient::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); + super::mirror::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("gs", Some(gs)), ("ps", shader_bytes(&d.PS))]); if super::gpu_times::enabled() { PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(gs), shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64))); @@ -11074,12 +12232,37 @@ pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void let hr = pipeline_state(this, desc, riid, ppv); // `XCL_CAPTURE_FRAME`: a stream the graphics and compute paths did not note (mesh) if super::capture::enabled() && hr >= 0 && !ppv.is_null() { - super::capture::note_stream(*ppv as usize); + if !note_mesh_stream_for_capture(desc, *ppv as usize) { + super::capture::note_stream(*ppv as usize); + } } note_mesh_stream_for_dump(desc, ppv, hr); hr } +/// `XCL_CAPTURE_FRAME`: a pipeline stream with a console mesh shader is noted with its MS and PS +/// and the depth state it names, so a captured frame tells its mesh pipelines apart. False: not +/// such a stream. +unsafe fn note_mesh_stream_for_capture(desc: *const c_void, pso: usize) -> bool { + if !crate::gpu::shader::readable(desc as usize, 16) { + return false; + } + let (size, base) = (*(desc as *const usize), *((desc as usize + 8) as *const usize)); + if !crate::gpu::shader::readable(base, size) { + return false; + } + let subs = known_subobjects(std::slice::from_raw_parts(base as *const u8, size)); + let Some(m) = mesh_stream_for_dump(&subs) else { return false }; + // DEPTH_STENCIL / 1 / 2 start alike: DepthEnable, DepthWriteMask, DepthFunc + let depth = subs.iter().find(|(ty, p)| matches!(*ty, 11 | 21 | 26) && p.len() >= 12).map(|(_, p)| { + let word = |k: usize| u32::from_le_bytes(p[4 * k..4 * k + 4].try_into().unwrap()); + [word(0), word(1), word(2)] + }); + let formats: Vec = m.formats.iter().map(|f| f.0).collect(); + super::capture::note_mesh_stream(pso, &m.stages, depth, &formats); + true +} + /// `XCL_DUMP_TARGETS`: a pipeline stream with a console mesh shader (`translated_mesh_stream`) /// is noted with its MS and PS, render target 0's blend and the formats, as a graphics desc is /// (`note_pipeline_for_dump`): without it a dumped target drawn by mesh pipelines lists them as @@ -11344,6 +12527,11 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de let rf = ID3D12Resource::from_raw_borrowed(&res).map_or(0, |r| r.GetDesc().Format.0 as u32); c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32) as i32); } + // an sRGB target with unordered access is typeless on the PC (`device_x::pc_resource_desc`): + // the view the title gave no description is its sRGB one, all of it + if copy.is_none() { + copy = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()).and_then(|rd| typeless_srgb_rtv(&rd)); + } let desc = copy.as_ref().map_or(desc, |c| c as *const _ as *const c_void); f(this, res, desc, handle); super::present::note_rtv(handle, res); @@ -11363,6 +12551,29 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de } } +/// The render target view of all of a typeless sRGB texture with unordered access (`rd`) that a +/// null description stands for; None: `rd` is not one. +fn typeless_srgb_rtv(rd: &D3D12_RESOURCE_DESC) -> Option { + let rf = rd.Format.0 as u32; + if !matches!(rf, 27 | 90) || rd.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { + return None; + } + let mut v = D3D12_RENDER_TARGET_VIEW_DESC { Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, 0) as i32), ..Default::default() }; + match rd.Dimension { + D3D12_RESOURCE_DIMENSION_TEXTURE2D if rd.DepthOrArraySize > 1 => { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; + v.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_RTV { MipSlice: 0, FirstArraySlice: 0, ArraySize: u32::from(rd.DepthOrArraySize), PlaneSlice: 0 }; + } + D3D12_RESOURCE_DIMENSION_TEXTURE2D => v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D, + D3D12_RESOURCE_DIMENSION_TEXTURE3D => { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D; + v.Anonymous.Texture3D = D3D12_TEX3D_RTV { MipSlice: 0, FirstWSlice: 0, WSize: u32::MAX }; + } + _ => return None, + } + Some(v) +} + /// ClearRenderTargetView: as on the PC (`XCL_TRACE_FRAME`: the colours logged) unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *const [f32; 4], n: u32, rects: *const c_void) { let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailCopy); @@ -11378,6 +12589,8 @@ unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *co if N.fetch_add(1, Ordering::Relaxed) < 16 { crate::xlog_info!("frame trace: ClearRenderTargetView {rtv:#x} → {:?} colour {:?}, {n} rects", super::present::rtv_resource(rtv), color.as_ref()); } + } + if super::present::trace_uses() { if let Some(r) = super::present::rtv_resource(rtv) { super::present::note_use(r, super::present::USE_CLEAR); } @@ -11410,7 +12623,7 @@ unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rt } if n > 0 && !rtvs.is_null() { super::present::note_rt0(this as usize, *rtvs); - if super::present::trace_frame() { + if super::present::trace_uses() { for k in 0..n as usize { let h = if single != 0 { *rtvs + k * 32 } else { *rtvs.add(k) }; if let Some(r) = super::present::rtv_resource(h) { @@ -11523,6 +12736,7 @@ unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { let n = super::queue_submit::release(this as usize, || f(this)); if n == 0 { super::list_x::on_queue_release(this as usize); + super::title_textures::on_queue_release(this as usize); } else if n == 1 { super::present::retire_released_queue(this as usize); } @@ -11555,8 +12769,14 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { || super::alloc_pool::retain_release_probe(this), ); if n == 0 { - dispatch_chain::allocator_reset(this as usize); + // The dispatch chains recorded on it go when `console_list::allocator_reset` says the GPU + // is done with them, not here: `forget` may keep the allocator for lists that still hold + // (and may submit again) a recording on it, or for submits the GPU has not passed. super::alloc_pool::forget(this as usize); + if !super::alloc_pool::retained(this as usize) { + // (no pool, or it never knew this one: as before) + dispatch_chain::allocator_reset(this as usize); + } super::list_x::on_allocator_release(this as usize); } n @@ -11568,8 +12788,8 @@ pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { let f: F = std::mem::transmute(orig_fn(raw, slot!(raw, "Reset"))); let hr = f(raw); if hr >= 0 { - dispatch_chain::allocator_reset(raw as usize); - // The GPU is done with allocations owned by this exact native backing. + // The GPU is done with allocations owned by this exact native backing (and its dispatch + // chains' scratch). super::console_list::allocator_reset(raw); } hr @@ -11997,6 +13217,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis return; } super::gpu_awake::note_activity(); + super::late_release::note_submit(); super::capture::submit(this, std::slice::from_raw_parts(lists, n as usize)); crate::stall::note_submitter(); // from here to the end: XCL's uploads and tile mappings before the lists, then the driver's @@ -12030,6 +13251,9 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis crate::xlog_warn!("D3D12.X: ExecuteCommandLists rejected a poisoned physical recording"); return; } + // the sources of the lists' bake draws as the refresh below must find them + // (`title_textures::bake_at_submit`; the draws ran on the PC lists) + super::title_textures::ready_bake_sources(&super::bind::bake_sources(&mapped)); // textures in title memory the CPU wrote since: uploaded again first prepare_title_submission(this, title_lists); super::list_x::note_queue_for_lists(this as usize, &mapped); @@ -12090,6 +13314,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis super::alloc_pool::note_execute_call(chunks); super::present::note_execute(this, &submitted); stop_if_device_removed(); + gpu_sync_after_submit(this); super::submit_cost::end(t_end.elapsed()); super::submit_cost::done(submit_t0); } @@ -12109,6 +13334,7 @@ pub(super) unsafe fn prepare_title_submission(queue: *mut c_void, lists: &[*mut let reason = match outcome { PreparationOutcome::RetryRequired => "sparse upload preparation still failed after bounded retries", PreparationOutcome::ExecutedUntracked => "a sparse upload executed without a retirement signal", + PreparationOutcome::MappingUnmarked => "a texture page mapping has no Signal of the mapping queue (its own and a retry failed)", PreparationOutcome::Ready => unreachable!(), }; let message = format!("{reason} – the title is stopped before its GPU submission"); @@ -12117,6 +13343,51 @@ pub(super) unsafe fn prepare_title_submission(queue: *mut c_void, lists: &[*mut end_title(0x8000_4005); } +/// `XCL_GPU_SYNC=` (diagnostic, off unless set): a title's submit returns only once its queue +/// has done the work (for `ms` at most: a queue that waits for a value another submit writes is +/// left to it), and what the lists wrote into copied memory is in the CPU's view. With it the +/// title never runs ahead of the GPU: what still goes wrong then is not a matter of timing. +unsafe fn gpu_sync_after_submit(queue: *mut c_void) { + static MS: std::sync::OnceLock = std::sync::OnceLock::new(); + let ms = *MS.get_or_init(|| std::env::var("XCL_GPU_SYNC").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)); + if ms == 0 || super::title_textures::is_own_work() { + return; + } + static FENCES: Mutex>> = Mutex::new(None); + static LATE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + static DONE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let (fence, value) = { + let mut g = FENCES.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + if !m.contains_key(&(queue as usize)) { + let raw = device_raw(); + let Some(dev) = ID3D12Device::from_raw_borrowed(&raw) else { return }; + let Ok(f) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return }; + m.insert(queue as usize, (f, 0)); + } + let e = m.get_mut(&(queue as usize)).unwrap(); + e.1 += 1; + (e.0.clone(), e.1) + }; + if q.Signal(&fence, value).is_err() { + return; + } + let t0 = std::time::Instant::now(); + while fence_completed(&fence) < value { + if t0.elapsed().as_millis() as u64 >= ms { + let k = LATE.fetch_add(1, Ordering::Relaxed) + 1; + if k.is_power_of_two() { + crate::xlog_info!("D3D12.X: XCL_GPU_SYNC: {k} submits so far not done on the GPU after {ms} ms ({} were)", DONE.load(Ordering::Relaxed)); + } + return; + } + std::thread::yield_now(); + } + DONE.fetch_add(1, Ordering::Relaxed); + super::sparse::settle_readbacks(); +} + /// Wait (up to 10 s) until the GPU has finished the work submitted to the queues console code /// used (before the process ends on purpose). pub fn drain_gpu() { @@ -12259,9 +13530,15 @@ mod release_tests { } n } + // (the last release asks for the desc, to log a buffer's address: a texture's has none) + unsafe extern "system" fn get_desc(_this: *mut c_void, out: *mut D3D12_RESOURCE_DESC) -> *mut D3D12_RESOURCE_DESC { + *out = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, ..Default::default() }; + out + } let mut orig = [0usize; 12]; orig[1] = add_ref as usize; orig[2] = release as usize; + orig[pc_slot!("ID3D12Resource", "GetDesc")] = get_desc as usize; let mut ext = vec![0usize; 13]; ext[0] = orig.as_ptr() as usize; ext[1..].copy_from_slice(&orig); @@ -12486,8 +13763,10 @@ pub fn log_device_removed() { v.join(", ") }; let va = pf.PageFaultVA; - let window = uma_window_vas().iter().position(|&w| va >= w && va < w + 0x1_0000_0000).map(|k| format!(" = window {k} + {:#x}", va - uma_window_vas()[k])).unwrap_or_default(); + let window = uma_window_vas().iter().position(|&w| w != 0 && va >= w && va < w + 0x1_0000_0000).map(|k| format!(" = window {k} + {:#x}", va - uma_window_vas()[k])).unwrap_or_default(); crate::xlog_error!("DRED page fault at GPU VA {va:#x}{window}; allocations there: [{}]; recently freed: [{}]", names(pf.pHeadExistingAllocationNode), names(pf.pHeadRecentFreedAllocationNode)); + crate::xlog_error!("DRED page fault: XCL's buffers at that address: {}", va_history(va)); + crate::xlog_error!("DRED page fault: root views a 32-bit offset reaches it from: {}", root_views_reaching(va)); } let breadcrumbs = dred.GetAutoBreadcrumbsOutput(); match &breadcrumbs { @@ -14245,7 +15524,7 @@ mod mesh_stream_tests { let make_tp = || crate::gpu::recomp::pso::TwoPass { cs: vec![0; 16], ms: vec![0; 16], - record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 32, max_vertices: 3, max_primitives: 1 }, + record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 32, max_vertices: 3, max_primitives: 1, params: None }, mesh_groups_per_record: 1, samplers: vec![sampler], }; @@ -14722,6 +16001,7 @@ void main() { list.SetDescriptorHeaps(&[Some(heap.clone())]); list.SetComputeRootSignature(&rs); list.SetComputeRoot32BitConstants(0, 12, idx_consts.as_ptr() as *const c_void, 0); + note_root_view(list.as_raw() as usize, 1, out_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(1, out_buf.GetGPUVirtualAddress()); list.Dispatch(1, 1, 1); @@ -14956,11 +16236,12 @@ mod depth_uav_twin_tests { dev_create_uav_checked_x(d, raw, std::ptr::null_mut(), &uav(DXGI_FORMAT_R24_UNORM_X8_TYPELESS, 0), slot_cpu(1)); // a second stencil UAV takes the same twin dev_create_uav_checked_x(d, raw, std::ptr::null_mut(), &uav(DXGI_FORMAT_R8_UINT, 0), slot_cpu(2)); - let (made2, alive2, redirected2, nulls) = depth_uav::counts(); - assert_eq!((made2 - made, alive2 - alive, redirected2 - redirected), (1, 1, 2), "one twin, two views of it"); - assert_eq!(nulls, ["its depth plane has no twin yet"], "the depth view is a null view, with its reason"); + let (made2, alive2, redirected2, _) = depth_uav::counts(); + assert_eq!((made2 - made, alive2 - alive, redirected2 - redirected), (2, 2, 3), "a stencil twin and a depth twin, three views of them"); let twin = depth_uav::twin_of(raw as usize).expect("a stencil twin"); + let depth_twin = depth_uav::depth_twin_of(raw as usize).expect("a depth twin"); + assert_ne!(twin, depth_twin, "one twin a plane"); let t = ID3D12Resource::from_raw_borrowed(&(twin as *mut c_void)).unwrap().GetDesc(); assert_eq!((t.Format, t.Width, t.Height, t.DepthOrArraySize, t.MipLevels), (DXGI_FORMAT_R8_TYPELESS, 16, 16, 1, 1)); assert!(t.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0); @@ -14974,7 +16255,7 @@ mod depth_uav_twin_tests { assert_eq!((w[0], (w[1] >> 20) & 0x1FF), (s.index, 5), "slot {k}: the T# of an R8_UINT image"); } let s = console_heap::slot(slot_cpu(1)).unwrap(); - assert_eq!(console_heap::names_of(&s).1, 0, "the depth plane's UAV is a null view"); + assert_eq!(console_heap::names_of(&s).1, depth_twin, "the depth plane's UAV is a view of its depth twin"); drop(heap); drop(depth); @@ -15086,13 +16367,14 @@ mod depth_uav_twin_tests { let (done2, not_done2) = depth_uav::clears(); assert_eq!((done2 - done, not_done2 - not_done), (1, 0), "the clear went to the twin"); assert_eq!(GOT.load(Ordering::Relaxed), twin.as_raw() as usize, "the PC clear gets the twin as its resource, not the depth buffer"); - // a depth-plane UAV of the buffer is a null view: its clear is not done, nothing reaches the PC + // a depth-plane UAV of the buffer is a view of its depth twin: the clear goes there let depth_slot = slot + console_heap::SLOT as u64; dev_create_uav_checked_x(d, raw, std::ptr::null_mut(), &uav(DXGI_FORMAT_R24_UNORM_X8_TYPELESS, 0), depth_slot); + let depth_twin = depth_uav::depth_twin_of(raw as usize).expect("a depth twin"); GOT.store(0, Ordering::Relaxed); list_x::clear_uav_uint_x(stand_in.as_ptr() as *mut c_void, depth_slot, depth_slot, raw as usize, [0x11u32; 4].as_ptr(), 0, std::ptr::null()); let (done3, not_done3) = depth_uav::clears(); - assert_eq!((done3 - done2, not_done3 - not_done2, GOT.load(Ordering::Relaxed)), (0, 1, 0), "a clear through the null view is not done"); + assert_eq!((done3 - done2, not_done3 - not_done2, GOT.load(Ordering::Relaxed)), (1, 0, depth_twin), "the clear of the depth view goes to the depth twin"); // the twin to a readback buffer let td = twin.GetDesc(); @@ -15357,6 +16639,53 @@ mod heap_release_order_tests { } } + +#[cfg(test)] +mod runtime_caller_tests { + use super::*; + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + + /// (0 not called, 1 false, 2 true) + static SEEN: AtomicU32 = AtomicU32::new(0); + + /// A hook as `res_release` is one: `lparam` is its "original". + unsafe extern "system" fn hook(_name: windows_sys::core::PCWSTR, _flags: u32, lparam: isize) -> i32 { + SEEN.store(1 + called_from_module_of(lparam as usize) as u32, Ordering::SeqCst); + 0 + } + + /// `res_release` leaves a last release the D3D12 runtime makes itself to the late-release + /// thread; it knows one by the caller's module, that of the original Release. Here the hook + /// is called by XCL's code and by kernelbase (as the runtime calls a hooked Release), with an + /// "original" in either module. + #[test] + fn a_hook_knows_whether_the_originals_module_called_it() { + unsafe { + let kernelbase = GetModuleHandleA(b"kernelbase.dll\0".as_ptr()); + assert!(!kernelbase.is_null()); + let theirs = GetProcAddress(kernelbase, b"EnumSystemLocalesEx\0".as_ptr()).expect("EnumSystemLocalesEx") as usize; + let ours = hook as usize; + let called_by = |via_kernelbase: bool, orig: usize| { + SEEN.store(0, Ordering::SeqCst); + if via_kernelbase { + let f: unsafe extern "system" fn(windows_sys::Win32::Globalization::LOCALE_ENUMPROCEX, u32, isize, *const c_void) -> i32 = std::mem::transmute(theirs); + f(Some(hook), 0, orig as isize, std::ptr::null()); + } else { + hook(std::ptr::null(), 0, orig as isize); + } + match SEEN.load(Ordering::SeqCst) { + 0 => panic!("the hook was not called"), + n => n == 2, + } + }; + assert!(called_by(true, theirs), "kernelbase called it, the original is kernelbase's"); + assert!(!called_by(true, ours), "kernelbase called it, the original is XCL's"); + assert!(called_by(false, ours), "XCL called it, the original is XCL's"); + assert!(!called_by(false, theirs), "XCL called it, the original is kernelbase's"); + } + } +} + #[cfg(test)] mod fence_flags_tests { use super::*; @@ -15421,5 +16750,3 @@ mod fence_flags_tests { } } } - - diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index b968575807..235c826676 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -480,6 +480,8 @@ unsafe fn scratch_for(dev: &ID3D12Device, list: usize, allocator: usize, needed: Some((s, false)) } +/// The GPU is done with what was recorded on the PC allocator `allocator` and no list holds it +/// (`console_list::allocator_reset`): its chains' scratch, indirect commands and pipelines go. pub(in crate::hle::d3d12x) fn allocator_reset(allocator: usize) { let recordings = RECORDINGS.lock().unwrap().remove(&allocator); drop(recordings); @@ -768,30 +770,41 @@ mod tests { assert_eq!(calls, 2, "the successful retry is retained"); } - #[test] - fn failed_binding_keeps_indirect_commands_until_allocator_reset() { + const EMPTY_PIECE: &str = "[numthreads(1,1,1)] void main() {}"; + + /// A split program whose whole form is ready, under its first piece's address. `None`: no GPU + /// or no DXC. + unsafe fn ready_indirect_chain(source: &str) -> Option<(ID3D12Device, usize)> { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; unsafe extern "system" fn never(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { E_INVALIDARG } + let mut dev = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return None; + } + let dev: ID3D12Device = dev.unwrap(); + let Ok(dxil) = crate::gpu::recomp::dxc::compile(source, "main", "cs_6_0", &[]) else { + crate::gpu::recomp::runner::skip_test("no DXC"); + return None; + }; + let rs = pso::dispatch_chain_root_signature(&dev, &[]).unwrap(); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, ..Default::default() }; + let first: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).unwrap(); + let whole = WholeBuild::new(); + whole.get_or_build(std::time::Instant::now(), || Ok(first.clone())).unwrap(); + let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs.clone(), samplers: Vec::new(), + flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0, mode: ComputeBuild::DirectChain }); + let key = first.as_raw() as usize; + CHAINS.lock().unwrap().insert(key, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, + whole_code: Vec::new(), whole, indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(false) })); + Some((dev, key)) + } + + #[test] + fn failed_binding_keeps_indirect_commands_until_allocator_reset() { unsafe { - let mut dev = None; - if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { - return crate::gpu::recomp::runner::skip_test("no GPU"); - } - let dev = dev.unwrap(); - let Ok(dxil) = crate::gpu::recomp::dxc::compile("[numthreads(1,1,1)] void main() {}", "main", "cs_6_0", &[]) else { - return crate::gpu::recomp::runner::skip_test("no DXC"); - }; - let rs = pso::dispatch_chain_root_signature(&dev, &[]).unwrap(); - let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&rs), - CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, ..Default::default() }; - let first: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).unwrap(); - let whole = WholeBuild::new(); - whole.get_or_build(std::time::Instant::now(), || Ok(first.clone())).unwrap(); - let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs.clone(), samplers: Vec::new(), - flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0, mode: ComputeBuild::DirectChain }); - let key = first.as_raw() as usize; - CHAINS.lock().unwrap().insert(key, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, - whole_code: Vec::new(), whole, indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(false) })); + let Some((dev, key)) = ready_indirect_chain(EMPTY_PIECE) else { return }; let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); @@ -878,39 +891,76 @@ mod tests { } } - /// A split program's indirect dispatch runs its chain from the counts the guard let through - /// (`bind::execute_indirect_chain`), not from the title's buffer: the slicer, the one pass that - /// reads them, writes no groups for garbage there, where it would clamp it to 65 535 groups. - /// And the pieces run the groups the slicer wrote: vkd3d-proton ran their ExecuteIndirects - /// from the commands as they were before it (`pso::record_indirect_slicer`). + /// The title releases its allocator while a list still holds a chain recorded on it and the + /// GPU has not run that list: the recording (scratch, indirect commands, pipelines) stays + /// until the GPU is done and no list holds it, and goes then. (It went at the Release, and the + /// GPU read the freed scratch: a page fault, then the device was lost.) + #[test] + fn a_released_allocator_keeps_its_chains_until_the_gpu_is_done() { + use super::super::super::alloc_pool; + unsafe { + let Some((dev, key)) = ready_indirect_chain(EMPTY_PIECE) else { return }; + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + if !super::super::is_adopted(alloc.as_raw()) { + super::super::adopt(alloc.as_raw(), super::super::Kind::CommandAllocator); + } + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + // (a list as XCL has a title's: the slicer is bound through the PC call) + super::super::adopt(list.as_raw(), Kind::CommandList); + super::super::super::list_x::on_create(list.as_raw(), alloc.as_raw() as usize, 0, ty); + let (raw_list, allocator) = (list.as_raw() as usize, alloc.as_raw() as usize); + alloc_pool::created_on(raw_list, allocator, ty.0); + let args = pso::chain_commands_buffer(&dev, 1).unwrap(); + // (a failed binding records no ExecuteIndirect, but keeps the recording as a run would) + let _ = execute_indirect(&list, key, key, allocator, args.GetGPUVirtualAddress(), |_| Err("bind failed".into()), |_| {}); + assert!(RECORDINGS.lock().unwrap().contains_key(&allocator)); + type Close = unsafe extern "system" fn(*mut c_void) -> HRESULT; + let close: Close = std::mem::transmute(super::super::orig_fn(list.as_raw(), 9)); + assert!(close(list.as_raw()) >= 0); + // the queue runs the list only once `gate` is signalled + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + alloc_pool::executed(queue.as_raw(), &[raw_list as *mut c_void]); + + drop(alloc); + assert!(RECORDINGS.lock().unwrap().contains_key(&allocator), "the title's final Release left the recording in flight"); + + gate.Signal(1).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&done, 1).unwrap(); + let start = std::time::Instant::now(); + while done.GetCompletedValue() < 1 && start.elapsed().as_secs() < 10 { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(done.GetCompletedValue() >= 1, "the queue finishes"); + assert!(RECORDINGS.lock().unwrap().contains_key(&allocator), "the list still holds the recording"); + // the list's recording ends: the allocator retires, and its chains with it + alloc_pool::forget_list(raw_list); + list_reset(raw_list); + drop(list); + alloc_pool::sweep_release_owners(); + assert!(!alloc_pool::retained(allocator)); + assert!(!RECORDINGS.lock().unwrap().contains_key(&allocator), "the GPU is done and no list holds it: it goes"); + forget(key); + } + } + + /// The slicer reads the guard's checked counts through its root SRV. Out-of-range counts + /// become zero before the slicer can clamp them into a very large dispatch. + /// The pieces read the slicer's commands from this dispatch. On vkd3d-proton they could + /// read the commands before the slicer ran (`pso::record_indirect_slicer`). #[test] fn a_split_indirect_dispatch_slices_the_counts_the_guard_let_through() { - use super::super::super::{bind, indirect_guard, list_x}; - use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; - unsafe extern "system" fn never(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { E_INVALIDARG } - // the counts in the title's buffer, and the groups the slicer may hand the pieces - let cases: [([u32; 3], u64); 3] = [([3, 2, 1], 6), ([1, 1, 0x1_0000], 0), ([2, 1, 1], 2)]; + use super::super::super::{alloc_pool, bind, indirect_guard, list_x}; + let source = "RWByteAddressBuffer c : register(u0);\n[numthreads(1, 1, 1)]\nvoid main() { c.InterlockedAdd(0, 1u); }"; + let cases = [([3, 2, 1], 6), ([1, 1, 0x1_0000], 0), ([2, 1, 1], 2)]; unsafe { let _one = indirect_guard::tests::ONE.lock().unwrap_or_else(|e| e.into_inner()); - let mut dev = None; - if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { - return crate::gpu::recomp::runner::skip_test("no GPU"); - } - let dev: ID3D12Device = dev.unwrap(); - // (a piece that counts its groups, in the ABI's first root UAV) - let src = "RWByteAddressBuffer c : register(u0);\n[numthreads(1, 1, 1)]\nvoid main() { c.InterlockedAdd(0, 1u); }"; - let Ok(dxil) = crate::gpu::recomp::dxc::compile(src, "main", "cs_6_0", &[]) else { - return crate::gpu::recomp::runner::skip_test("no DXC"); - }; - let rs = pso::dispatch_chain_root_signature(&dev, &[]).unwrap(); - let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&rs), - CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, ..Default::default() }; - let first: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).unwrap(); - let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs.clone(), samplers: Vec::new(), - flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0, mode: ComputeBuild::DirectChain }); - let key = first.as_raw() as usize; - CHAINS.lock().unwrap().insert(key, Arc::new(Chain { builder, tail: Vec::new(), words: 4, whole_code: Vec::new(), - whole: WholeBuild::new(), indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(true) })); + let Some((dev, key)) = ready_indirect_chain(source) else { return }; + let rs = CHAINS.lock().unwrap().get(&key).unwrap().builder.signature.clone(); // buffers the CPU and the GPU see: the title's arguments, the slicer's commands, the // groups run let cpu_buffer = |width: u64| { @@ -951,10 +1001,9 @@ mod tests { super::super::adopt(list.as_raw(), Kind::CommandList); list_x::on_create(list.as_raw(), alloc.as_raw() as usize, 0, ty); let (raw, allocator) = (list.as_raw(), alloc.as_raw() as usize); - super::super::super::alloc_pool::created_on(raw as usize, allocator, ty.0); - let Some(checked) = indirect_guard::check(raw, key, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0) else { - panic!("{want:x?}: checked"); - }; + alloc_pool::created_on(raw as usize, allocator, ty.0); + let checked = indirect_guard::check(raw, key, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0) + .unwrap_or_else(|| panic!("{want:x?}: checked")); let bind = |root: usize| { assert_eq!(root, rs.as_raw() as usize); list.SetComputeRootSignature(&rs); @@ -980,11 +1029,13 @@ mod tests { let total: u64 = (0..rounds).map(|r| groups(pso::chain_tail_offset(r) + pso::CHAIN_DISPATCH_AT)).sum::() + groups(pso::chain_tail_offset(rounds)); assert_eq!(total, runs, "{want:x?}: groups sliced"); - assert_eq!(u64::from(std::ptr::read_volatile(ran_at)), runs, "{want:x?}: groups the pieces ran"); + // ready_indirect_chain gives the chain two counting pieces. + assert_eq!(u64::from(std::ptr::read_volatile(ran_at)), 2 * runs, "{want:x?}: groups the pieces ran"); allocator_reset(allocator); list_reset(raw as usize); - super::super::super::alloc_pool::forget_list(raw as usize); + alloc_pool::forget_list(raw as usize); } + indirect_guard::note_signature(sig.as_raw() as usize, &[]); forget(key); } } diff --git a/crates/xcl/src/hle/d3d12x/scatter.rs b/crates/xcl/src/hle/d3d12x/scatter.rs index c36f734716..f0c6ea0c77 100644 --- a/crates/xcl/src/hle/d3d12x/scatter.rs +++ b/crates/xcl/src/hle/d3d12x/scatter.rs @@ -126,8 +126,11 @@ impl Scatter { pub unsafe fn dispatch(&self, list: &ID3D12GraphicsCommandList, chunks: usize, ring_va: u64, to_va: u64) { debug_assert!(chunks > 0 && chunks <= MAX_CHUNKS); list.SetComputeRoot32BitConstant(0, chunks as u32, 0); + super::real::note_root_view(list.as_raw() as usize, 1, ring_va); list.SetComputeRootShaderResourceView(1, ring_va); + super::real::note_root_view(list.as_raw() as usize, 2, ring_va + Self::data_at(chunks) as u64); list.SetComputeRootShaderResourceView(2, ring_va + Self::data_at(chunks) as u64); + super::real::note_root_view(list.as_raw() as usize, 3, to_va); list.SetComputeRootUnorderedAccessView(3, to_va); list.Dispatch(chunks.div_ceil(GROUP) as u32, 1, 1); } diff --git a/crates/xcl/src/hle/d3d12x/small_tex.rs b/crates/xcl/src/hle/d3d12x/small_tex.rs index 0a2ba2a855..5b195f55e0 100644 --- a/crates/xcl/src/hle/d3d12x/small_tex.rs +++ b/crates/xcl/src/hle/d3d12x/small_tex.rs @@ -1,8 +1,8 @@ //! Small sampled textures of the title that get no shared pages (`vram::place_pages` refuses them: //! a 1D texture cannot be a reserved resource) on 4 KiB placements in heaps of XCL's own -//! (`XCL_SMALL_TEXTURES=1`), instead of a committed resource each: a committed resource takes at -//! least 64 KiB of video memory, and a title's thousands of tiny lookup textures (a few hundred -//! bytes each) took ~300 MiB that way. +//! (off by default, `XCL_SMALL_TEXTURES=1` turns it on), instead of a committed resource each: a +//! committed resource takes at least 64 KiB of video memory, and a title's thousands of tiny +//! lookup textures (a few hundred bytes each) took ~300 MiB that way. //! //! Only what the PC itself allows: no render target, depth or UAV flags, one sample, and //! `GetResourceAllocationInfo` giving `D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT` (4 KiB) for the @@ -32,7 +32,12 @@ const UNITS: usize = (HEAP_BYTES / UNIT) as usize; /// Whether small sampled textures go on 4 KiB placements (`XCL_SMALL_TEXTURES=1`). pub(super) fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_SMALL_TEXTURES").is_ok_and(|v| v.trim() == "1")) + *ON.get_or_init(|| switch_on(std::env::var("XCL_SMALL_TEXTURES").ok().as_deref())) +} + +/// `XCL_SMALL_TEXTURES` as set (`1`: on, anything else: off), including `unset`. +fn switch_on(v: Option<&str>) -> bool { + v.is_some_and(|v| v.trim() == "1") } /// The units of one heap: first fit of a run of `n`. @@ -185,6 +190,15 @@ mod tests { use super::*; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_SAMPLE_DESC}; + /// Off by default (`XCL_SMALL_TEXTURES=1` turns it on). + #[test] + fn small_textures_are_off_by_default() { + assert!(!switch_on(None), "unset: off"); + assert!(switch_on(Some(" 1 "))); + assert!(!switch_on(Some("0"))); + assert!(!switch_on(Some("yes"))); + } + /// Units go first fit and come back: a freed run is taken again, a run longer than any gap is not. #[test] fn units_are_taken_first_fit_and_given_back() { diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index fb532258fd..bf68fbf0be 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -221,6 +221,8 @@ unsafe fn source_holes(tiles: &[usize]) -> Vec { use windows_sys::Win32::System::Threading::GetCurrentProcess; /// tiles a working-set query asks for const BATCH: usize = 256; + // (`XCL_LOOK_STATS=2`: the time Windows is asked, with the sparse lock split line) + let t0 = super::look_stats::deep().then(std::time::Instant::now); let mut out = Vec::with_capacity(tiles.len()); let mut ws: Vec = Vec::with_capacity(BATCH.min(tiles.len()) * PAGES_PER_TILE); // the region the last VirtualQuery reported: [start, end), and whether its pages are accessible @@ -262,9 +264,276 @@ unsafe fn source_holes(tiles: &[usize]) -> Vec { out.push(holes); } } + if let Some(t0) = t0 { + VIEW_SPLIT.add(VS_ASKED_US, t0.elapsed().as_micros() as u64); + VIEW_SPLIT.add(VS_ASKED_TILES, tiles.len() as u64); + } out } +/// `XCL_SOURCE_HOLES_CACHE=0`: query Windows (`source_holes`) on every `holes_now` without +/// caching known-accessible source regions across submits. On by default. +fn source_holes_cache_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SOURCE_HOLES_CACHE").ok().is_none_or(|v| v.trim() != "0")) +} + +/// Sorted, disjoint, coalesced `[lo, hi)` page-aligned spans known to be `MEM_COMMIT` and +/// accessible (`Protect != 0`, not `PAGE_NOACCESS | PAGE_GUARD`). Only accessible spans are +/// cached, so committing new pages needs no invalidation; decommits, frees, and non-writable +/// protection changes punch their exact span out (`invalidate_source_range`). +#[derive(Default)] +struct SourceRegions { + rev: u64, + ranges: Vec<(usize, usize)>, + /// Recent invalidations `(rev, lo, hi)` so an in-flight `VirtualQuery` can still safely + /// populate unaffected regions (`(rev, 0, usize::MAX)` marks a full clear). + recent: VecDeque<(u64, usize, usize)>, +} + +impl SourceRegions { + const RECENT_CAP: usize = 64; + + fn contains_tile(&self, tile: usize) -> bool { + let Some(end) = tile.checked_add(TILE) else { return false }; + let i = self.ranges.partition_point(|&(lo, _)| lo <= tile); + i > 0 && self.ranges[i - 1].1 >= end + } + + fn insert(&mut self, lo: usize, hi: usize) { + if lo >= hi { + return; + } + let mut start = lo; + let mut end = hi; + // First range whose end >= start (touches or overlaps `[start, end)`). + let first = self.ranges.partition_point(|&(_, r_end)| r_end < start); + let mut last = first; + while last < self.ranges.len() && self.ranges[last].0 <= end { + start = start.min(self.ranges[last].0); + end = end.max(self.ranges[last].1); + last += 1; + } + self.ranges.splice(first..last, std::iter::once((start, end))); + } + + fn subtract(&mut self, lo: usize, hi: usize) { + if lo >= hi || self.ranges.is_empty() { + return; + } + let first = self.ranges.partition_point(|&(_, r_end)| r_end <= lo); + let mut last = first; + let mut repl: Vec<(usize, usize)> = Vec::new(); + while last < self.ranges.len() && self.ranges[last].0 < hi { + let (a, b) = self.ranges[last]; + if a < lo { + repl.push((a, lo)); + } + if b > hi { + repl.push((hi, b)); + } + last += 1; + } + if first < last { + self.ranges.splice(first..last, repl); + } + } + + fn note_invalidation(&mut self, lo: usize, hi: usize) { + self.rev = self.rev.wrapping_add(1); + if self.recent.len() >= Self::RECENT_CAP { + self.recent.pop_front(); + } + self.recent.push_back((self.rev, lo, hi)); + } + + fn invalidate(&mut self, a: usize, n: usize) { + if n == 0 { + if a == 0 { + self.ranges.clear(); + self.note_invalidation(0, usize::MAX); + } else { + // Unknown length (`MEM_RELEASE` with size 0): drop any range containing `a`, and + // record a full-clear sentinel in `recent` so an in-flight query won't re-add it. + let i = self.ranges.partition_point(|&(lo, _)| lo <= a); + if i > 0 && self.ranges[i - 1].1 > a { + self.ranges.remove(i - 1); + } + self.note_invalidation(0, usize::MAX); + } + return; + } + let (lo, hi) = page_span(a, n); + self.subtract(lo, hi); + self.note_invalidation(lo, hi); + } +} + +/// Leaf lock (never held across OS syscalls or `STATE`): cached known-accessible source regions for +/// `holes_now`. +static SOURCE_REGIONS: Mutex = Mutex::new(SourceRegions { rev: 0, ranges: Vec::new(), recent: VecDeque::new() }); + +/// Drop `[a, a + n)` (or the region at `a` when `n == 0`) from the `source_holes` region cache. +/// Call around any decommit, release, or non-writable `VirtualProtect` of process memory. +pub fn invalidate_source_range(a: usize, n: usize) { + SOURCE_REGIONS.lock().unwrap_or_else(|e| e.into_inner()).invalidate(a, n); +} + +/// Fast-path check for `gpu::shader::readable`: returns `true` if `[p, end)` lies completely +/// inside a cached committed, readable region (`SOURCE_REGIONS`). Never returns a false positive: +/// every free, decommit, and non-writable protection change in `kernelx` / `sparse` punches out +/// the affected span. +pub(crate) fn known_readable(p: usize, end: usize) -> bool { + if !source_holes_cache_on() || p >= end { + return false; + } + let s = SOURCE_REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + let i = s.ranges.partition_point(|&(lo, _)| lo <= p); + i > 0 && s.ranges[i - 1].1 >= end +} + +/// Snapshot the current invalidation revision of `SOURCE_REGIONS` before querying Windows. +pub(crate) fn source_regions_rev() -> u64 { + SOURCE_REGIONS.lock().unwrap_or_else(|e| e.into_inner()).rev +} + +/// Record `[lo, hi)` (already verified `MEM_COMMIT` + readable via `VirtualQuery`) into +/// `SOURCE_REGIONS`, only for regions whose lifecycle is 100% intercepted by XCL (`uma` windows +/// or `kernelx` graphics reservations) and subtracting any invalidations since `rev0`. +pub(crate) fn cache_readable_region(lo: usize, hi: usize, rev0: u64) { + if !source_holes_cache_on() || lo >= hi { + return; + } + let mut s = SOURCE_REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + let delta = s.rev.wrapping_sub(rev0); + let can_commit = delta == 0 + || (delta <= s.recent.len() as u64 + && s.recent.iter().rev().take(delta as usize).all(|&(_, rlo, rhi)| !(rlo == 0 && rhi == usize::MAX))); + if can_commit { + s.insert(lo, hi); + if delta > 0 { + let subtracts: Vec<(usize, usize)> = s.recent.iter().rev().take(delta as usize).map(|&(_, rlo, rhi)| (rlo, rhi)).collect(); + for (rlo, rhi) in subtracts { + s.subtract(rlo, rhi); + } + } + } +} + +/// Cached `source_holes`: checks `SOURCE_REGIONS` first, then runs sorted `VirtualQuery` over +/// cache misses without `K32QueryWorkingSetEx` working-set-lock contention, caching newly +/// discovered accessible spans (minus any concurrent invalidations or `freeing` ranges). +unsafe fn source_holes_cached(tiles: &[usize], freeing: &[(usize, usize)]) -> Vec { + if tiles.is_empty() { + return Vec::new(); + } + if !source_holes_cache_on() { + return source_holes(tiles); + } + let t0 = super::look_stats::deep().then(std::time::Instant::now); + let mut out = vec![0u16; tiles.len()]; + let mut misses: Vec<(usize, usize)> = Vec::new(); + let rev0 = { + let s = SOURCE_REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + for (idx, &t) in tiles.iter().enumerate() { + if !s.contains_tile(t) { + misses.push((t, idx)); + } + } + s.rev + }; + if !misses.is_empty() { + misses.sort_unstable_by_key(|&(t, _)| t); + let mut region = (0usize, 0usize, false); + let mut newly_accessible: Vec<(usize, usize)> = Vec::new(); + for (t, idx) in misses { + if region.0 <= t && t.saturating_add(TILE) <= region.1 { + out[idx] = if region.2 { 0 } else { 0xFFFF }; + continue; + } + let mut holes = 0xFFFFu16; + for i in 0..PAGES_PER_TILE { + let pg = t + i * PAGE; + if !(region.0..region.1).contains(&pg) { + #[cfg(test)] + tests::VIRTUAL_QUERIES.with(|n| n.set(n.get() + 1)); + let mut mbi: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + region = if VirtualQuery(pg as *const c_void, &mut mbi, std::mem::size_of::()) == 0 || mbi.RegionSize == 0 { + (pg, pg + PAGE, false) + } else { + let ok = mbi.State == MEM_COMMIT && mbi.Protect != 0 && (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) == 0; + let lo = (mbi.BaseAddress as usize).min(pg); + let hi = (mbi.BaseAddress as usize).saturating_add(mbi.RegionSize).max(pg + PAGE); + if ok { + newly_accessible.push((lo, hi)); + } + (lo, hi, ok) + }; + } + if region.2 { + holes &= !(1u16 << i); + } + } + out[idx] = holes; + } + if !newly_accessible.is_empty() { + let mut s = SOURCE_REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + let delta = s.rev.wrapping_sub(rev0); + let can_commit = delta == 0 + || (delta <= s.recent.len() as u64 + && s.recent.iter().rev().take(delta as usize).all(|&(_, lo, hi)| !(lo == 0 && hi == usize::MAX))); + if can_commit { + for (lo, hi) in newly_accessible { + s.insert(lo, hi); + } + if delta > 0 { + let subtracts: Vec<(usize, usize)> = s.recent.iter().rev().take(delta as usize).map(|&(_, lo, hi)| (lo, hi)).collect(); + for (lo, hi) in subtracts { + s.subtract(lo, hi); + } + } + for &(a, end) in freeing { + s.subtract(a, end); + } + } + } + } + if let Some(t0) = t0 { + VIEW_SPLIT.add(VS_ASKED_US, t0.elapsed().as_micros() as u64); + VIEW_SPLIT.add(VS_ASKED_TILES, tiles.len() as u64); + } + out +} + +/// `XCL_LOOK_STATS=2`: where the GPU-view tiles part of a submit's time with the sparse lock goes +/// (`LS_VIEWS`, the sparse lock split line): [µs linking tiles whose page changed +/// (`remap_mirrors`), µs giving asked tiles video memory (`map_mirrors`), µs for the CPU writes +/// their CPU views took (`mirror_writes`), then of all uses of the lock: µs asking Windows which +/// pages of CPU tiles are committed (`source_holes`), the tiles asked about, µs making pool heaps +/// (`take_tile`)] +static VIEW_SPLIT: super::look_stats::Sums<6> = super::look_stats::Sums::new(); +const VS_REMAP_US: usize = 0; +const VS_MAP_US: usize = 1; +const VS_WRITES_US: usize = 2; +const VS_ASKED_US: usize = 3; +const VS_ASKED_TILES: usize = 4; +const VS_HEAPS_US: usize = 5; + +/// The GPU-view tiles part of the sparse lock split line (`VIEW_SPLIT`'s sums over `submits`). +fn view_split_line(x: &[u64; 6], submits: u64) -> String { + let n = submits.max(1) as f64; + let ms = |k: usize| x[k] as f64 / n / 1e3; + format!( + "GPU-view tiles: pages moved {:.3}, asked for {:.3}, CPU views written {:.3} ms a submit; asking Windows which pages are committed {:.3} ms ({:.1} tiles), pool heaps made {:.3} ms a submit (all uses of the lock)", + ms(VS_REMAP_US), + ms(VS_MAP_US), + ms(VS_WRITES_US), + ms(VS_ASKED_US), + x[VS_ASKED_TILES] as f64 / n, + ms(VS_HEAPS_US) + ) +} + /// Query actual OS page commitment across the 64 KiB tile at `tile`. /// Bit `i` in the returned mask is set whenever 4 KiB page `tile + i * PAGE` is not committed /// and accessible (`MEM_RESERVE`, `MEM_FREE`, `PAGE_NOACCESS`, `PAGE_GUARD`, etc.). @@ -2412,6 +2681,9 @@ pub(super) enum PreparationOutcome { Ready, RetryRequired, ExecutedUntracked, + /// a tile mapping is queued that no Signal of the mapping queue covers: its own Signal failed + /// and so did a retry (`vram::before_execute`), so nothing may run that reads it + MappingUnmarked, } impl From for PreparationOutcome { @@ -2533,6 +2805,11 @@ struct State { rb_last_fence: u64, /// the fence value each title queue last waited for waited: FxHashMap, + /// tile mappings were queued since the last `signal` (`map_tiles` / `unmap_tiles` / + /// `poison_all`) + mapping_queued: AtomicBool, + /// the fence value of the last `signal` that came after tile mappings + mapped_value: u64, /// `mapped` as runs of neighbouring tiles (start -> end), kept with it: sorted out of all of /// them again (a retail title has 150,000) for each look behind a commit runs: BTreeMap, @@ -2573,6 +2850,10 @@ struct State { /// tiles over a CPU view left without video memory for `mirror_cap`, or as none was to be had: /// given it once there is room (`retry_refused`), or once their CPU view is written refused: FxHashSet, + /// tile runs (first, end; sorted, apart) the title made unordered-access buffer views by + /// address over (`gpu_writes`): a compute program writes there with no buffer placed on it + /// and no write of the CPU's, so with `lazy_commits` a commit there maps at once + gpu_written: Vec<(usize, usize)>, /// when a tile over a CPU view last found no video memory (`take_tile`): for a moment the /// others do not try to make a heap again (each tried, and logged it), and the refused ones /// wait @@ -2586,6 +2867,41 @@ struct State { poison: Option, /// Dirty CPU pages whose write-watch bits were reset before an upload failed. retry_pages: Vec, + /// a CPU read whose copy back is waited for with the lock released (`readback_now`) + reading: Option, +} + +/// A CPU read's copy back on the GPU (`State::reading`; one at a time, `CPU_READ`): the range it +/// copied, its place among the copies back of the submissions (`ReadbackQueue::job_seq` when it +/// was recorded), and the parts of the range that changed since in a way the chunks' hashes do not +/// show (`spoil`): what copies back and immediates of later submissions landed there (they may +/// hold what the CPU had before, so the hashes stay), and pages decommitted (committed again they +/// hold zeros, and so may the hashes). Its copy does not land there. +struct Reading { + at: usize, + end: usize, + seq: u64, + spoiled: Vec<(usize, usize)>, +} + +impl State { + /// `[a, a + n)` changed while a CPU read's copy back is on the GPU (`Reading`). + fn spoil(&mut self, a: usize, n: usize) { + if let Some(r) = self.reading.as_mut() { + let (lo, hi) = (a.max(r.at), a.saturating_add(n).min(r.end)); + if lo < hi { + r.spoiled.push((lo, hi)); + } + } + } + + /// A copy back or an immediate of the submissions' (`seq`, `RbJob::seq`) landed in `[a, a + n)`: + /// one recorded after the CPU read's copy holds the newer bytes. + fn spoil_if_newer(&mut self, seq: u64, a: usize, n: usize) { + if self.reading.as_ref().is_some_and(|r| seq > r.seq) { + self.spoil(a, n); + } + } } /// The one 64 KiB of video memory the tiles of the windows without video memory of their own are @@ -3336,6 +3652,8 @@ unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) - rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: AtomicBool::new(false), + mapped_value: 0, runs: BTreeMap::new(), scratch_runs: Vec::new(), own_pages: Vec::new(), @@ -3350,6 +3668,7 @@ unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) - fill_pages: fill_pages(), mirrored: 0, mirror_cap: mirror_cap(), + gpu_written: Vec::new(), refused: FxHashSet::default(), no_memory: None, starved: Vec::new(), @@ -3357,6 +3676,7 @@ unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) - diag: ViewDiag { keep: view_switches().keep, stats: view_switches().stats, ..Default::default() }, poison: None, retry_pages: Vec::new(), + reading: None, }) } @@ -3448,6 +3768,8 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { let old_queue = QUEUE.lock().unwrap().replace(s.queue.clone()); let _old_rb = READBACKS.lock().unwrap().replace(Arc::clone(&s.readbacks)); let mut state = STATE.lock().unwrap(); + // (the ranges made of the state before are not this one's: `RANGES_KEPT`) + MAPPED_GEN.fetch_add(1, Ordering::Release); let old = state.replace(s); let s = state.as_mut().unwrap(); for (a, b) in std::mem::take(&mut *EARLY.lock().unwrap()) { @@ -3538,7 +3860,12 @@ impl State { // CPU signal that asks meanwhile gives up after 2 ms) self.flush_pending(); let mut heap: Option = None; - if let Err(e) = super::title_textures::own_work(|| self.dev.CreateHeap(&desc, &mut heap)) { + let t0 = super::look_stats::deep().then(std::time::Instant::now); + let made = super::title_textures::own_work(|| self.dev.CreateHeap(&desc, &mut heap)); + if let Some(t0) = t0 { + VIEW_SPLIT.add(VS_HEAPS_US, t0.elapsed().as_micros() as u64); + } + if let Err(e) = made { crate::xlog_warn!("sparse windows: no video memory for more tiles ({e})"); return None; } @@ -3598,6 +3925,7 @@ impl State { if tiles.is_empty() { return; } + self.mapping_queued.store(true, Ordering::Relaxed); let mut by_heap: FxHashMap> = FxHashMap::default(); debug_assert!(tiles.iter().all(|t| t.1 != LAZY), "a tile with no video memory is mapped nowhere"); for &(a, (h, t)) in tiles { @@ -3649,6 +3977,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()); @@ -3693,6 +4022,7 @@ impl State { if tiles == 0 { return; } + self.mapping_queued.store(true, Ordering::Relaxed); let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); let region = D3D12_TILE_REGION_SIZE { NumTiles: tiles, UseBox: false.into(), ..Default::default() }; let (flag, off) = (D3D12_TILE_RANGE_FLAG_REUSE_SINGLE_TILE, 0u32); @@ -3771,11 +4101,11 @@ impl State { let mut new = false; while t < end { if !self.mapped.contains_key(&t) && !self.mirror_src.contains_key(&t) && self.window_index(t).is_some() { - if self.parked.contains_key(&t) || self.kept.contains_key(&t) { + if self.parked.contains_key(&t) || self.kept.contains_key(&t) || in_runs(&self.gpu_written, t) { self.ensure_mapped(t, TILE, |_| (0xFFFF, 0)); } else { + // (watched once a commit clears a hole of it: `unmask_committed_holes`) self.mapped.insert(t, TileEntry::with_holes(LAZY, 0xFFFF)); - early_add(&mut self.runs, t, t + TILE); new = true; } } @@ -3839,6 +4169,16 @@ impl State { self.to_zero.extend(reused); } + /// The title made unordered-access buffer views by address over `ranges` (`gpu_writes`): + /// their tiles listed with no video memory get it now (`give_memory`), and those committed + /// later get it at the commit (`ensure_listed`). + unsafe fn gpu_written(&mut self, ranges: &[(usize, usize)]) { + for &(a, n) in ranges { + add_run(&mut self.gpu_written, a & !(TILE - 1), a.saturating_add(n).saturating_add(TILE - 1) & !(TILE - 1)); + } + self.give_memory(ranges); + } + /// tiles of `[a, a + n)` get video memory (mapped in their window); `initial_state` supplies /// the initial `(holes, untrusted protection)` masks for each newly mapped 64 KiB tile. Tiles /// over a CPU view (`mirror_src`) are left to `new_mirror`. @@ -3859,7 +4199,10 @@ impl State { let mut entry = TileEntry::with_holes(tile, holes); entry.not_rw = not_rw; self.mapped.insert(t, entry); - early_add(&mut self.runs, t, t + TILE); + // (a tile with no page committed is not watched: the CPU cannot write there) + if holes != 0xFFFF { + early_add(&mut self.runs, t, t + TILE); + } self.to_zero.insert((t, TILE)); unparked = true; } else { @@ -3868,7 +4211,10 @@ impl State { let mut entry = TileEntry::with_holes(tile, holes); entry.not_rw = not_rw; self.mapped.insert(t, entry); - early_add(&mut self.runs, t, t + TILE); + // (a tile with no page committed is not watched: the CPU cannot write there) + if holes != 0xFFFF { + early_add(&mut self.runs, t, t + TILE); + } if reused { self.to_zero.insert((t, TILE)); } @@ -3927,6 +4273,9 @@ impl State { unsafe fn signal(&mut self) { self.value += 1; let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); + if self.mapping_queued.swap(false, Ordering::Relaxed) { + self.mapped_value = self.value; + } } #[inline] @@ -4264,6 +4613,9 @@ impl State { let page = std::slice::from_raw_parts_mut((here + (pg - t)) as *mut u8, PAGE); let source = std::slice::from_raw_parts(p.add(src_off), step); let wrote = land_page(&mut entry.sent[idx], page, at - pg, source, gpu_written); + if wrote { + crate::hle::kernelx::pagelog::note("GPU copy back landed", here + (at - t), 0, step); + } if wrote && self.own_pages.len() < OWN_PAGES_MAX && super::look_stats::deep() { self.own_pages.push(here + (pg - t)); } @@ -4299,6 +4651,7 @@ impl State { 8 => (*(cpu as *const AtomicU64)).store(value, Ordering::Release), _ => return, } + crate::hle::kernelx::pagelog::note("GPU immediate landed", cpu, 0, (bytes & 0x7f) as usize); if self.own_pages.len() < OWN_PAGES_MAX && super::look_stats::deep() { self.own_pages.push(cpu & !(PAGE - 1)); } @@ -4366,6 +4719,7 @@ impl State { ReadyJob::Imm(job) => { for &(va, value, bytes, gen) in &job.writes { self.store_imm(va, value, bytes, gen); + self.spoil_if_newer(job.seq, va, (bytes & 0x7f) as usize); } RB_PENDING.fetch_sub(1, Ordering::Release); } @@ -4374,6 +4728,7 @@ impl State { for &(dst, off, len, gen) in &copies { // (the lists' own GPU writes, `readback_after_execute`) self.copy_back(job.ptr, dst, off, len, gen, true); + self.spoil_if_newer(job.seq, dst, len); } TILE_WORK[3].fetch_add(copies.iter().map(|c| c.2 as u64).sum(), Ordering::Relaxed); RB_PENDING.fetch_sub(1, Ordering::Release); @@ -5444,9 +5799,8 @@ impl State { } /// Synchronize `[va, va + len)` in a sparse window for a CPU read (`ID3D12Resource::Map` with -/// a non-empty read range, or `Map(0, NULL)` on a sparse readback resource): flushes pending -/// tile clears and unsubmitted CPU-changed chunks first so CPU writes are preserved, then -/// copies the range back from VRAM into CPU memory. +/// a non-empty read range, or `Map(0, NULL)` on a sparse readback resource): what the GPU wrote +/// there is copied back into CPU memory, where the CPU did not write since (`readback_now_with`). pub unsafe fn readback_now(va: usize, len: usize) { if len == 0 { return; @@ -5457,12 +5811,28 @@ pub unsafe fn readback_now(va: usize, len: usize) { wait_and_check_ready(&rb, Drain::TitleDone, 2000, None); } } - let measure = super::memory_report::enabled(); + readback_now_with(&STATE, va, len); +} + +/// `readback_now` on the state in `state_lock` (the global one, or a test's). +unsafe fn readback_now_with(state_lock: &Mutex>, va: usize, len: usize) { + let is_global = std::ptr::eq(state_lock, &STATE); + let measure = is_global && super::memory_report::enabled(); let _upload_lifetime = UPLOAD_STATE_LIFETIME.read().unwrap(); + let unlocked = cpu_read_unlocked(); + let _one = unlocked.then(|| CPU_READ.lock().unwrap_or_else(|e| e.into_inner())); let (mut uploads, mut timing) = UploadGateTiming::acquire(measure); - let excess = readback_now_locked(va, len, &mut uploads, &mut timing); + let rest = if unlocked { readback_unlocked(state_lock, va, len, &mut uploads, &mut timing) } else { Err(va) }; + let excess = match rest { + Ok(excess) => excess, + // (`XCL_CPU_READ_UNLOCKED=0`, or no readback queue: the lock is held all the way, as + // before; on the global state only, as `wait_upload_released` is) + Err(at) if is_global => readback_now_locked(at, va.saturating_add(len) - at, &mut uploads, &mut timing), + Err(_) => Vec::new(), + }; let times = timing.finish(); drop(uploads.take()); + drop(_one); drop(_upload_lifetime); // (recycled copy-back jobs past the pool's cap drop outside all locks) drop(excess); @@ -5471,6 +5841,388 @@ pub unsafe fn readback_now(va: usize, len: usize) { } } +/// `XCL_CPU_READ_UNLOCKED=0`: a CPU read (`readback_now`) holds the state's lock while the GPU +/// makes its copy back, as before (`readback_now_locked`). Otherwise (with a readback queue) the +/// copy is waited for with the lock and the upload gate released (`cpu_read_begin`, +/// `cpu_read_land`). A retail title's world on an RX 9070 XT: its threads held the lock 3.6–6.3 ms +/// a submit for CPU reads, and each submit waited 0.4–1.6 ms behind them for its own use of it, +/// its after stage 0.3–0.9 ms more. +fn cpu_read_unlocked() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_CPU_READ_UNLOCKED").map_or(true, |v| v.trim() != "0")) +} + +/// One CPU read's copy back at a time (`cpu_read_unlocked`): the state's readback list and +/// buffer are the read's from the copy's recording until it landed, and the copy is waited for +/// with `STATE` and `UPLOAD_GATE` released. Lock order: `UPLOAD_STATE_LIFETIME` (shared) → +/// `CPU_READ` → `UPLOAD_GATE` → `STATE`; never taken under the gate or `STATE`. +static CPU_READ: Mutex<()> = Mutex::new(()); + +/// `XCL_LOOK_STATS=2`: the CPU reads (`readback_now`) since the last sparse lock split line: +/// [reads, bytes asked for, µs with the state's lock held, µs waiting for the copy with it +/// released, copies made, 64-byte chunks landed] +static CPU_READS: super::look_stats::Sums<6> = super::look_stats::Sums::new(); + +/// The CPU reads part of the sparse lock split line (`CPU_READS`' sums over `submits`). +fn cpu_reads_line(x: &[u64; 6], submits: u64) -> String { + let n = submits.max(1) as f64; + let reads = x[0].max(1) as f64; + format!( + "CPU reads: {:.2} a submit, {:.0} KB each, {:.3} ms each with the lock held and {:.3} ms waiting for the copy without it, {:.1} chunks landed each, {:.1} copies each", + x[0] as f64 / n, + x[1] as f64 / reads / 1024.0, + x[2] as f64 / reads / 1e3, + x[3] as f64 / reads / 1e3, + x[5] as f64 / reads, + x[4] as f64 / reads + ) +} + +/// Wait until `fence` reaches `value`, 5 s at most (true: it did). Not for a holder of `STATE` +/// or `UPLOAD_GATE`. +unsafe fn wait_fence(fence: &ID3D12Fence, value: u64, dev: &ID3D12Device) -> bool { + thread_local! { + /// this thread's event for its waits (`fence::wait` takes a wake for an earlier + /// registration that gave up as no completion) + static EVENT: HANDLE = unsafe { windows::Win32::System::Threading::CreateEventW(None, false, false, None).unwrap_or_default() }; + } + match EVENT.with(|&ev| crate::gpu::fence::wait(fence, value, dev, (!ev.is_invalid()).then_some(ev), 5000)) { + Ok(()) => true, + Err(e) => { + crate::xlog_warn!("sparse: the queue has not reached fence value {value} (at {}: {e}): a CPU read's copy back is left out", super::real::fence_completed(fence)); + false + } + } +} + +/// What `cpu_read_begin` did. +enum CpuReadStep { + /// the read stops here: its tile clears did not go out (back in `to_zero` for the next) + Stop, + /// an upload slot the GPU still holds for the tile clears (back in `to_zero`): waited for + /// with the locks let go, then again + Wait(WaitTicket), + /// the copy before this one is still on the GPU (given up on): wait for the fence, then again + Busy(ID3D12Fence, u64, ID3D12Device), + /// nothing to copy before this address; the copy-back jobs to drop + Skip(usize, Vec), + Copy(CpuReadCopy), +} + +/// A piece of a CPU read's copy (`cpu_read_begin`): `[va, va + len)` of one tile, at `off` in the +/// readback buffer, the tile's video memory and CPU memory when it was recorded +/// (`TileEntry::pool`, `gen`), the hash each 64-byte chunk there was last sent with, and (made +/// with the lock released once the copy is done, `hash_copied`) the hash of each whole chunk the +/// copy holds (0 for a chunk only partly read). +struct CpuReadPart { + va: usize, + off: usize, + len: usize, + pool: (u32, u32), + gen: u32, + sent: Vec, + copied: Vec, +} + +/// A CPU read's copy submitted on the state's queue (`cpu_read_begin`), to land once the fence +/// reaches `value` (`cpu_read_land`). +struct CpuReadCopy { + fence: ID3D12Fence, + value: u64, + dev: ID3D12Device, + /// where the rest of the read begins + next: usize, + /// the readback buffer (`ptr` is its mapping), kept while the copy is read + _buf: ID3D12Resource, + ptr: *const u8, + parts: Vec, + /// copy-back jobs to drop outside the locks + excess: Vec, +} + +impl CpuReadCopy { + /// `CpuReadPart::copied`, made with the lock released: the hashes `cpu_read_land` gives the + /// chunks it lands. + unsafe fn hash_copied(&mut self) { + for part in &mut self.parts { + part.copied.clear(); + let end = part.va + part.len; + let mut c = part.va & !(CHUNK - 1); + while c < end { + let whole = c >= part.va && c + CHUNK <= end; + part.copied.push(if whole { chunk_hash(std::slice::from_raw_parts(self.ptr.add(part.off + (c - part.va)), CHUNK)) } else { 0 }); + c += CHUNK; + } + } + } +} + +/// The hashes the 64-byte chunks of `[a, a + n)` (in the tile at `t`, `e`) were last sent with: +/// `ZERO_HASH` for a page with none (all zero, or a hole). +fn sent_hashes(e: &TileEntry, t: usize, a: usize, n: usize) -> Vec { + let mut out = Vec::with_capacity(n / CHUNK + 2); + let mut c = a & !(CHUNK - 1); + while c < a + n { + let idx = (c - t) / PAGE; + out.push(e.sent[idx].as_deref().map_or(ZERO_HASH, |s| s[(c - t) % PAGE / CHUNK])); + c += CHUNK; + } + out +} + +/// Whether `[lo, hi)` meets one of `runs` (sorted by start). +fn meets(runs: &[(usize, usize)], lo: usize, hi: usize) -> bool { + runs.iter().take_while(|r| r.0 < hi).any(|r| r.1 > lo) +} + +/// `readback_now_with` when `cpu_read_unlocked`, with `CPU_READ` and the upload gate held: the +/// range in copies of the readback buffer one after the other, each waited for and landed with +/// `STATE` and the gate released. The copy-back jobs to drop outside all locks; `Err(at)`: the +/// state has no readback queue, and the read from `at` on holds the lock all the way. +unsafe fn readback_unlocked( + state_lock: &Mutex>, va: usize, len: usize, uploads: &mut Option, timing: &mut UploadGateTiming, +) -> Result, usize> { + let is_global = std::ptr::eq(state_lock, &STATE); + let lock = || if is_global { lock_state() } else { state_lock.lock().unwrap() }; + let deep = is_global && super::look_stats::deep(); + let stamp = || deep.then(std::time::Instant::now); + let since = |t: Option| t.map_or(0, |t| t.elapsed().as_micros() as u64); + let end = va.saturating_add(len); + let mut at = va; + let mut excess: Vec = Vec::new(); + // [µs with the lock, µs waiting without it, copies, chunks landed] + let mut x = [0u64; 4]; + while at < end { + let t = stamp(); + let step = { + let mut g = lock(); + let _held = is_global.then(|| holding(Holder::CpuRead)); + let Some(s) = g.as_mut() else { break }; + if s.window_index(at).is_none() { + break; + } + if s.rbq.is_none() { + return Err(at); + } + s.cpu_read_begin(at, end) + }; + x[0] += since(t); + match step { + CpuReadStep::Stop => break, + CpuReadStep::Wait(ticket) => { + if !timing.with_released(uploads, || wait_upload_released(ticket)) { + break; + } + } + CpuReadStep::Busy(fence, value, dev) => { + let t = stamp(); + let there = timing.with_released(uploads, || wait_fence(&fence, value, &dev)); + x[1] += since(t); + if !there { + break; + } + } + CpuReadStep::Skip(next, done) => { + excess.extend(done); + at = next; + } + CpuReadStep::Copy(mut copy) => { + excess.append(&mut copy.excess); + // (the copy is waited for and lands with the upload gate let go too: a submit's + // preparation goes on meanwhile) + let (there, landed) = timing.with_released(uploads, || { + let t = stamp(); + let there = wait_fence(©.fence, copy.value, ©.dev); + if there { + copy.hash_copied(); + } + x[1] += since(t); + let t = stamp(); + let (done, landed) = { + let mut g = lock(); + let _held = is_global.then(|| holding(Holder::CpuRead)); + match g.as_mut() { + Some(s) => s.cpu_read_land(©, there), + None => (Vec::new(), 0), + } + }; + x[0] += since(t); + excess.extend(done); + (there, landed) + }); + x[2] += 1; + x[3] += landed; + if !there { + break; + } + at = copy.next; + } + } + } + if deep { + CPU_READS.add(0, 1); + CPU_READS.add(1, len as u64); + for (k, v) in x.into_iter().enumerate() { + CPU_READS.add(2 + k, v); + } + } + Ok(excess) +} + +impl State { + /// The first half of a CPU read of `[at, end)` whose copy back is waited for with the lock + /// released (`readback_unlocked`): pending tile clears and mappings go first and the copies + /// back done land (they are older than this one), then a copy of as much of the range as the + /// readback buffer holds is submitted on the state's queue, with the hashes its chunks were + /// last sent with. `reading` follows what lands in the range until `cpu_read_land`. + /// + /// Unlike `readback_now_locked`, the CPU's writes there that are not sent yet are not scanned + /// and sent first: a chunk the CPU wrote since it was sent does not take the copy back + /// (`cpu_read_land`, as `land_page`) and goes up with the next look anyway, so sending it here + /// only had the GPU copy back what the CPU has. + unsafe fn cpu_read_begin(&mut self, at: usize, end: usize) -> CpuReadStep { + // (a copy given up on is still in the readback list and buffer) + if self.rb_last_fence != 0 && super::real::fence_completed(&self.fence) < self.rb_last_fence { + return CpuReadStep::Busy(self.fence.clone(), self.rb_last_fence, self.dev.clone()); + } + let zeroed = zero_runs(std::mem::take(&mut self.to_zero)); + if !zeroed.is_empty() { + for &(a, n) in &zeroed { + self.clear_sent_range(a, n); + } + // (as in `readback_now_locked`: clears that did not go out are journaled again before + // the upload gate is let go) + match self.upload_zeros(&zeroed) { + UploadStep::Done(PreparationOutcome::Ready) => {} + UploadStep::Wait(ticket) => { + rejournal_zeros(&mut self.to_zero, zeroed); + return CpuReadStep::Wait(ticket); + } + UploadStep::Done(_) => { + rejournal_zeros(&mut self.to_zero, zeroed); + return CpuReadStep::Stop; + } + } + } + self.flush_pending(); + let excess = self.land_finished_readbacks(); + let Some((buf, p)) = self.readback_buf() else { return CpuReadStep::Skip(end, excess) }; + let piece_end = end.min(at.saturating_add(READBACK_STAGING)); + let mut parts: Vec = Vec::new(); + let mut used = 0usize; + let mut cur = at; + while cur < piece_end { + let tile = cur & !(TILE - 1); + let Some(wi) = self.window_index(cur) else { + cur = end; + break; + }; + let b = self.windows[wi].0; + let n = (piece_end - cur).min(tile + TILE - cur).min(b + crate::gpu::uma::WINDOW - cur); + // (a tile with no video memory has nothing to copy back, as in `readback_ranges`) + let Some(e) = self.mapped.get(&tile).filter(|e| e.pool != LAZY) else { + cur += n; + continue; + }; + let (pool, gen, sent) = (e.pool, e.gen, sent_hashes(e, tile, cur, n)); + if parts.is_empty() && (self.rb_alloc.Reset().is_err() || self.rb_list.Reset(&self.rb_alloc, None).is_err()) { + return CpuReadStep::Skip(end, excess); + } + self.rb_list.CopyBufferRegion(&buf, used as u64, &self.windows[wi].1, (cur - b) as u64, n as u64); + parts.push(CpuReadPart { va: cur, off: used, len: n, pool, gen, sent, copied: Vec::new() }); + used += n; + cur += n; + } + if parts.is_empty() { + return CpuReadStep::Skip(cur, excess); + } + let list = self.rb_list.Close().ok().and_then(|_| self.rb_list.cast::().ok()); + let Some(list) = list else { return CpuReadStep::Skip(end, excess) }; + super::title_textures::own_work(|| super::real::native_queue_execute(&self.queue, &list)); + self.signal(); + self.rb_last_fence = self.value; + let seq = self.readbacks.lock().unwrap().job_seq; + self.reading = Some(Reading { at, end: cur, seq, spoiled: Vec::new() }); + CpuReadStep::Copy(CpuReadCopy { fence: self.fence.clone(), value: self.value, dev: self.dev.clone(), next: cur, _buf: buf, ptr: p, parts, excess }) + } + + /// The second half of a CPU read (`cpu_read_begin`), its copy done (`there`; else it lands + /// nowhere): the copies back done meanwhile land first, then the copy lands in each chunk of + /// its range that is as the copy found it: the tile has the same video and CPU memory, the + /// chunk the hash it had then and the CPU did not write it since (`land_page`), and nothing + /// landed there that the hashes do not show (`Reading::spoiled`). (A copy back of a submission + /// before the read that lands meanwhile keeps what it changed, as one that landed after the + /// read did when the read held the lock.) The excess copy-back jobs to drop outside the lock, + /// and the chunks landed. + unsafe fn cpu_read_land(&mut self, copy: &CpuReadCopy, there: bool) -> (Vec, u64) { + let excess = self.land_finished_readbacks(); + let reading = self.reading.take(); + // (a state made again while the copy was waited for: not its memory) + let Some(reading) = reading.filter(|_| there && self.fence.as_raw() == copy.fence.as_raw()) else { return (excess, 0) }; + let mut spoiled = reading.spoiled; + spoiled.sort_unstable(); + spoiled.dedup_by(|b, a| { + if b.0 > a.1 { + return false; + } + a.1 = a.1.max(b.1); + true + }); + let deep = super::look_stats::deep(); + let mut landed = 0u64; + for part in ©.parts { + let t = part.va & !(TILE - 1); + let Some(entry) = self.mapped.get_mut(&t).filter(|e| e.pool == part.pool && e.gen == part.gen) else { continue }; + let here = entry.cpu(t); + let end = part.va + part.len; + let mut c = part.va & !(CHUNK - 1); + let mut i = 0; + // (the page of the chunks landed last, and their bytes: noted once a page) + let mut page: Option<(usize, usize)> = None; + while c < end { + let (lo, hi) = (c.max(part.va), (c + CHUNK).min(end)); + let idx = (c - t) / PAGE; + let k = (c - t) % PAGE / CHUNK; + let sent = entry.sent[idx].as_deref().map_or(ZERO_HASH, |s| s[k]); + let whole = lo == c && hi == c + CHUNK; + let copied = part.copied.get(i).copied(); + // (a whole chunk the copy holds as it was sent: the CPU has it, or wrote it since) + let same = whole && copied == Some(sent); + if entry.holes & (1u16 << idx) == 0 && part.sent.get(i) == Some(&sent) && !same && !meets(&spoiled, lo, hi) { + let cpu = (here + (c - t)) as *mut u8; + if chunk_hash(std::slice::from_raw_parts(cpu, CHUNK)) == sent { + std::ptr::copy_nonoverlapping(copy.ptr.add(part.off + (lo - part.va)), cpu.add(lo - c), hi - lo); + let h = match copied { + Some(h) if whole => h, + _ => chunk_hash(std::slice::from_raw_parts(cpu, CHUNK)), + }; + entry.sent[idx].get_or_insert_with(|| Box::new(ZERO_HASHES))[k] = h; + landed += 1; + let pg = here + (c - t) - (c - t) % PAGE; + match page.as_mut() { + Some((p, n)) if *p == pg => *n += hi - lo, + _ => { + if let Some((p, n)) = page.replace((pg, hi - lo)) { + crate::hle::kernelx::pagelog::note("GPU copy back landed", p, 0, n); + } + if deep && self.own_pages.len() < OWN_PAGES_MAX { + self.own_pages.push(pg); + } + } + } + } + } + c += CHUNK; + i += 1; + } + if let Some((p, n)) = page { + crate::hle::kernelx::pagelog::note("GPU copy back landed", p, 0, n); + } + } + (excess, landed) + } +} + /// `readback_now` with the upload gate held. Returns any excess recycled `RbJob`s for the caller /// to drop outside `STATE`. unsafe fn readback_now_locked( @@ -5673,6 +6425,7 @@ pub unsafe fn decommitted(a: usize, n: usize) { if n == 0 { return; } + invalidate_source_range(a, n); let mut g = lock_in_turn(&STATE, &SUBMITS_WAITING); let _held = holding(Holder::Commits); forget_released(&mut g); @@ -5765,6 +6518,47 @@ pub fn send_pending() { } } +/// The pages of `[a, a + n)` committed: their hole bits cleared in the tiles of `mapped` there +/// (`writable` false marks them read-only, `TileEntry::not_rw`). A tile of the window's own that +/// had no page committed (all holes, so not in `runs`) can be written by the CPU from now on: it +/// joins `runs`, and `MAPPED_GEN` goes up so the watched ranges are made again (true). +fn unmask_committed_holes(mapped: &mut FxHashMap, runs: &mut BTreeMap, a: usize, n: usize, writable: bool) -> 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 { + let bit = 1u16 << ((p - t) / PAGE); + entry.holes &= !bit; + if writable { + entry.not_rw &= !bit; + } else { + entry.not_rw |= bit; + } + p += PAGE; + } + // (a tile over a CPU view is never in `runs`: its own address is not the CPU's) + if was_all_holes && entry.holes != 0xFFFF && entry.src == 0 { + early_add(runs, t, t + TILE); + unmasked = true; + } + } + if tile_end <= pg { + break; + } + pg = tile_end; + } + if unmasked { + MAPPED_GEN.fetch_add(1, Ordering::Release); + } + unmasked +} + impl State { /// `committed` with the state locked unsafe fn commit_range(&mut self, a: usize, n: usize) { @@ -5781,11 +6575,10 @@ impl State { if self.unlink_mirror(t) { if let Some(e) = self.mapped.get_mut(&t).filter(|e| e.src != 0) { // (what it held was the CPU view's: cleared, and the pages committed here - // are no holes below) + // are no holes below, where it joins `runs`) *e = TileEntry::with_holes(e.pool, 0xFFFF); self.to_zero.insert((t, TILE)); self.mirrored -= 1; - early_add(&mut self.runs, t, t + TILE); MAPPED_GEN.fetch_add(1, Ordering::Release); } } @@ -5800,35 +6593,16 @@ impl State { } else { self.ensure_mapped(a, n, |_| (0xFFFF, 0)); } - 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 { - let bit = 1u16 << ((p - t) / PAGE); - entry.holes &= !bit; - if writable { - entry.not_rw &= !bit; - } else { - entry.not_rw |= bit; - } - p += PAGE; - } - } - if tile_end <= pg { - break; - } - pg = tile_end; - } + unmask_committed_holes(&mut self.mapped, &mut self.runs, a, n, writable); self.mapping_epoch = self.mapping_epoch.wrapping_add(1); } /// `decommitted` with the state locked: the tiles that go are parked (`flush_parked` unmaps /// them and frees their pool tiles) unsafe fn decommit_range(&mut self, a: usize, n: usize) { + invalidate_source_range(a, n); + // (committed again, these pages hold zeros: a CPU read's copy back of them is old) + self.spoil(a, n); let mut pools: Vec<(usize, (u32, u32))> = Vec::new(); let end = a.saturating_add(n); // tiles over a CPU view go as a whole (their holes are the CPU view's pages, not these) @@ -6410,10 +7184,12 @@ pub unsafe fn source_decommit(a: usize, n: usize, os: impl FnOnce() -> R) -> return os(); } let (span, shown) = freeing_begins(&SOURCES, a, n); + invalidate_source_range(a, n); if shown { source_decommitted(a, n); } let r = os(); + invalidate_source_range(a, n); freeing_ends(&SOURCES, span); r } @@ -6427,10 +7203,12 @@ pub unsafe fn source_release(a: usize, n: usize, os: impl FnOnce() -> R) -> R return os(); } let (span, shown) = freeing_begins(&SOURCES, a, n); + invalidate_source_range(a, n); if shown { source_decommitted(a, n); } let r = os(); + invalidate_source_range(a, n); forget_mirrors(a, n); freeing_ends(&SOURCES, span); r @@ -6466,6 +7244,7 @@ pub fn forget_mirrors(a: usize, n: usize) { if n == 0 { return; } + invalidate_source_range(a, n); let end = a.saturating_add(n); // (out of the queue before out of the set: an ask in between finds the tile still asked // for, or stays queued, and the count after it has the thread ask again. The other way @@ -6494,6 +7273,36 @@ pub fn forget_mirrors(a: usize, n: usize) { unsafe { s.forget_mirrors_in(a, end) }; } +/// `XCL_TRACE_MS` (a diagnostic): what the window tile of GPU-view address `va` is now: asked +/// for or not, what it is linked over, its video memory (source, holes, pages sent), and +/// whether it waits or was refused. +pub fn view_tile_diag(va: usize) -> String { + let w = va & !(TILE - 1); + let asked = MIRROR_ASKED.contains(w); + let queued = MIRROR_ASKS.lock().unwrap().contains(&w); + let shows = match tile_shows(w) { + Under::Cpu(c) => format!("cpu {c:#x}"), + Under::Nothing => "nothing".to_string(), + Under::NoView => "no view".to_string(), + }; + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return format!("tile {w:#x}: no sparse state") }; + let mapped = s.mapped.get(&w).map(|e| { + let page = (va & (TILE - 1)) / PAGE; + format!("pool {:?} src {:#x} holes {:04x} sent pages {} (page {page} sent: {})", e.pool, e.src, e.holes, e.sent.iter().filter(|p| p.is_some()).count(), e.sent[page].is_some()) + }); + format!( + "tile {w:#x}: asked {asked} queued {queued} shows {shows} linked {:x?} mapped {mapped:?} later {} refused {} parked {} kept {} asks {} remaps {}", + s.mirror_src.get(&w), + s.later.iter().any(|&(t, _)| t == w), + s.refused.contains(&w), + s.parked.contains_key(&w), + s.kept.contains_key(&w), + s.asks.contains(&w), + s.remaps.contains(&w), + ) +} + /// The CPU address behind window address `va`, for what reads or writes the title's memory /// there: `va` itself, unless it lies in a GPU view of the title's CPU memory, whose tiles show /// their CPU view (`State::map_mirrors` takes them by the same rule), or where the page the @@ -6880,7 +7689,7 @@ impl State { /// is in the list read here. unsafe fn holes_now(&self, tiles: &[usize]) -> Vec { let freeing = lock_sources(self.sources).freeing.clone(); - let mut holes = source_holes(tiles); + let mut holes = source_holes_cached(tiles, &freeing); for &(a, end) in &freeing { for (h, &t) in holes.iter_mut().zip(tiles) { let (lo, hi) = (a.max(t), end.min(t + TILE)); @@ -6982,6 +7791,7 @@ impl State { /// holes (`decommit_tiles`); a tile all holes is parked, and stays in `mirrors` (a commit and /// write there gives it video memory again). unsafe fn source_decommitted_in(&mut self, a: usize, n: usize) { + invalidate_source_range(a, n); let end = a.saturating_add(n); for t in self.src_tiles_in(a, end) { let (lo, hi) = (a.max(t), end.min(t + TILE)); @@ -7086,6 +7896,12 @@ impl State { /// tiles of GPU views show (never the views' own addresses): where a CPU write has to reach the /// GPU. pub fn mapped_ranges() -> Vec<(usize, usize)> { + if let Some((gen, r)) = RANGES_KEPT.lock().unwrap().as_ref() { + if *gen == MAPPED_GEN.load(Ordering::Acquire) { + RANGES_TAKEN.add(1, 1); + return r.clone(); + } + } let t0 = super::look_stats::deep().then(std::time::Instant::now); let g = lock_for_submit(); let _held = holding(Holder::Ranges); @@ -7093,7 +7909,11 @@ pub fn mapped_ranges() -> Vec<(usize, usize)> { HELD.add(HELD_RANGES_WAIT, t0.elapsed().as_micros() as u64); } let Some(s) = g.as_ref() else { return Vec::new() }; - s.watched_ranges() + let out = s.watched_ranges(); + // (read with the lock held: the runs change, and it goes up, only under it) + *RANGES_KEPT.lock().unwrap() = Some((MAPPED_GEN.load(Ordering::Acquire), out.clone())); + RANGES_TAKEN.add(0, 1); + out } const LOOK_FIELDS: usize = 37; @@ -7134,6 +7954,16 @@ const VRAM_CALLS: usize = 33; const VRAM_MAPPING_WAITS: usize = 34; const VRAM_RECLAIM_PASSES: usize = 35; const VRAM_RETIREMENT_PASSES: usize = 36; +/// The last `mapped_ranges` and the `MAPPED_GEN` they were made at: asked again with no tile +/// mapped, unmapped or made writable since, they are answered without `STATE`. The watched ranges +/// are made again whenever any part of their key changed (`title_textures::watch_key`: the +/// textures' blocks, the reservations, the shown pages too), and the lock may be held then by a +/// placed buffer, a commit, a CPU read or another queue's submit (a retail title's world: a submit +/// waited 0.1–0.3 ms for it there). Taken alone or under `STATE`, never around it. +static RANGES_KEPT: Mutex)>> = Mutex::new(None); +/// `mapped_ranges` [made under the lock, answered from `RANGES_KEPT`] (`XCL_LOOK_STATS=2`, with the +/// sparse lock split line) +static RANGES_TAKEN: super::look_stats::Sums<2> = super::look_stats::Sums::new(); /// time spent and pages found by the write-watch scans (`refresh_once`), for the timing line static WATCH: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; @@ -7535,6 +8365,48 @@ unsafe fn run_copies(jobs: &mut Vec<(usize, usize, usize)>, staging: *mut u8) { /// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB /// pages from the write-watch, sorted) and the reused tiles are copied asynchronously into video /// memory, and `queue` GPU-waits for that and for new tile mappings. +/// `[a, end)` joined to the sorted runs `runs` that lie apart; whether it added anything. +fn add_run(runs: &mut Vec<(usize, usize)>, a: usize, end: usize) -> bool { + if a >= end { + return false; + } + let first = runs.partition_point(|r| r.1 < a); + let after = runs.partition_point(|r| r.0 <= end); + if after == first + 1 && runs[first].0 <= a && end <= runs[first].1 { + return false; + } + let joined = runs[first..after].iter().fold((a, end), |j, r| (j.0.min(r.0), j.1.max(r.1))); + runs.splice(first..after, [joined]); + true +} + +/// Whether `t` lies in one of the sorted runs `runs`. +fn in_runs(runs: &[(usize, usize)], t: usize) -> bool { + let i = runs.partition_point(|r| r.1 <= t); + runs.get(i).is_some_and(|r| r.0 <= t) +} + +/// The ranges `gpu_writes` was told of that no submit has taken yet, and all of them so far as +/// tile runs (a title makes the same views again every frame: each range is queued once). +static GPU_WRITE_ASKS: Mutex<(Vec<(usize, usize)>, Vec<(usize, usize)>)> = Mutex::new((Vec::new(), Vec::new())); +static GPU_WRITE_ASKING: AtomicBool = AtomicBool::new(false); + +/// The title made an unordered-access buffer view by address over `[va, va + len)` of a sparse +/// window: no buffer is placed there and the CPU may never write it, so with `lazy_commits` its +/// tiles would have no video memory and what a compute program writes through the view would go +/// nowhere (a retail title's lighting and video planes: black rooms, wrong colours). Its tiles +/// get video memory from the next submit on (`State::gpu_written`). Never waits for the state. +pub(super) fn gpu_writes(va: usize, len: usize) { + if len == 0 || !lazy_commits() { + return; + } + let mut g = GPU_WRITE_ASKS.lock().unwrap_or_else(|e| e.into_inner()); + if add_run(&mut g.1, va & !(TILE - 1), va.saturating_add(len).saturating_add(TILE - 1) & !(TILE - 1)) { + g.0.push((va, len)); + GPU_WRITE_ASKING.store(true, Ordering::Release); + } +} + /// What the title's lists being recorded will write on the GPU in the sparse windows (address, /// bytes; `will_write`), taken by the next submit: with `lazy_commits` a tile there may have no /// video memory yet, and the write would go nowhere. @@ -7725,7 +8597,9 @@ impl State { // them: before the flushes below, so their mappings reach the title's work (a tile taken // back from `parked` needs none) s.remap_mirrors(); + let t_remap = stamp(); s.map_mirrors(); + let t_asks = stamp(); s.diag.submits += 1; if s.diag.stats && !(s.later.is_empty() && s.asks.is_empty()) { s.diag.deferred += 1; @@ -7755,6 +8629,11 @@ impl State { LOCK_SPLIT.add(LS_BACK, us(t0, t_back)); LOCK_SPLIT.add(LS_BACK_BYTES, work(3)); LOCK_SPLIT.add(LS_VIEWS, us(t_back, t_views)); + if let (Some(t_remap), Some(t_asks)) = (t_remap, t_asks) { + VIEW_SPLIT.add(VS_REMAP_US, us(t_back, t_remap)); + VIEW_SPLIT.add(VS_MAP_US, us(t_remap, t_asks)); + VIEW_SPLIT.add(VS_WRITES_US, us(t_asks, t_views)); + } LOCK_SPLIT.add(LS_MAP, us(t_views, t_map)); LOCK_SPLIT.add(LS_MAP_TILES, work(0)); LOCK_SPLIT.add(LS_MAP_CALLS, work(1)); @@ -7762,7 +8641,14 @@ impl State { LOCK_SPLIT.add(LS_UNMAP_TILES, work(2)); if LOCK_SPLIT.add(LS_SUBMITS, 1) >= 1024 { let x = LOCK_SPLIT.take(); - crate::xlog_info!("D3D12.X: {}; {}", lock_split_line(&x), holders_line(&HELD.take(), x[LS_SUBMITS])); + let [made, kept] = RANGES_TAKEN.take(); + crate::xlog_info!( + "D3D12.X: {}; {}; {}; {}; mapped ranges asked for {made} times under the lock, {kept} times not", + lock_split_line(&x), + view_split_line(&VIEW_SPLIT.take(), x[LS_SUBMITS]), + holders_line(&HELD.take(), x[LS_SUBMITS]), + cpu_reads_line(&CPU_READS.take(), x[LS_SUBMITS]) + ); } } let t_maintained = t_started.map(|_| t_locked); @@ -8129,6 +9015,10 @@ unsafe fn before_execute_locked( let asks = std::mem::take(&mut *WRITE_ASKS.lock().unwrap_or_else(|e| e.into_inner())); s.give_memory(&asks); } + if GPU_WRITE_ASKING.swap(false, Ordering::AcqRel) { + let asks = std::mem::take(&mut GPU_WRITE_ASKS.lock().unwrap_or_else(|e| e.into_inner()).0); + s.gpu_written(&asks); + } let waited = t_lock.elapsed().as_micros() as u64; PHASES[0].fetch_add(waited, Ordering::Relaxed); // (the gates before the lock count with it: all of `before_execute` is the submit's sparse time) @@ -8181,13 +9071,21 @@ unsafe fn before_execute_locked( // the queue waits for the uploads and tile mappings (outside the lock; given back if it fails) let value = s.value; let previous = s.waited.get(&q).copied(); - let wait = reserve_queue_wait(&mut s.waited, q, value).then(|| (s.fence.clone(), value, previous)); + let mappings = waits_for_mappings(s.mapped_value, previous); + let wait = reserve_queue_wait(&mut s.waited, q, value).then(|| (s.fence.clone(), value, previous, s.dev.clone())); drop(held); drop(g); drop(observed); // (recycled copy-back jobs past the pool's cap drop outside all locks) drop(excess); - if let Some((fence, value, previous)) = wait { + if let Some((fence, value, previous, dev)) = wait { + // tile mappings among them: waited for here, with the upload gate let go, and the queue + // holds none of its work behind them (`XCL_SPARSE_CPU_WAIT_MS`). This thread holds no + // queue's submit turn: the title's lists go out after this (`prepare_title_submission`). + if mappings && timing.with_released(uploads, || cpu_waited_for_mappings(&fence, value, &dev, "sparse uploads and tile mappings")) { + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); + return PreparationOutcome::Ready; + } if super::real::native_queue_wait(queue, &fence, value).is_err() { let mut g = lock_state(); if let Some(s) = g.as_mut().filter(|s| s.fence.as_raw() == fence.as_raw() && s.waited.get(&q) == Some(&value)) { @@ -8203,6 +9101,74 @@ unsafe fn before_execute_locked( } } +/// Whether a title queue's wait for the sparse fence, from `previous` (the value it waited for +/// last) to the fence's value now, covers tile mappings: a `signal` after them gave +/// `mapped_value`. +fn waits_for_mappings(mapped_value: u64, previous: Option) -> bool { + mapped_value > previous.unwrap_or(0) +} + +/// `XCL_SPARSE_CPU_WAIT_MS` (1 000 by default, 0: off): how long a title submit waits on the +/// CPU for a mapping queue's tile mappings (the sparse windows', the video memory pages') before +/// its lists go, instead of the title's queue waiting for them on the GPU. +/// +/// With the GPU wait every queue of a retail title held its queued work behind the sparse +/// queue's tile mappings. On an AMD RX 9070 (16 GB, at its memory budget) the sparse queue's +/// fence then stopped short of the value they waited for, for 15 s – while AMD's crash analysis +/// found no command buffer in flight – and the device was removed (five runs in a row, 63–140 s +/// into the world). A tile mapping is the video memory manager's work: it can have to evict, and +/// it cannot take memory from queues whose work is already queued behind that very mapping. With +/// the wait on the CPU no queue holds work behind a mapping; past the limit the GPU wait is used +/// as before (logged). +/// +/// Under the D3D12 debug layer the GPU wait held the title's next lists too: with synchronized +/// command queue validation (on by default) the layer keeps a queue's calls after a `Wait` for a +/// value the fence has not reached on its own thread, and the test title's lists and its fence +/// `Signal` after a tile mapping did not run for more than 5 s, though the mapping was done +/// within a millisecond (`e2e`: `test_title_*_under_the_debug_layer*`). +fn sparse_cpu_wait_ms() -> u32 { + static MS: std::sync::OnceLock = std::sync::OnceLock::new(); + *MS.get_or_init(|| std::env::var("XCL_SPARSE_CPU_WAIT_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1000)) +} + +/// Whether `fence` (of the mapping queue `what`) reached `value` within `sparse_cpu_wait_ms`, +/// waited for on the CPU. False at once with the wait off, and past the limit (logged): the +/// caller then has the queue wait for it on the GPU. +pub(super) unsafe fn cpu_waited_for_mappings(fence: &ID3D12Fence, value: u64, dev: &ID3D12Device, what: &str) -> bool { + cpu_waited_within(fence, value, dev, what, sparse_cpu_wait_ms()) +} + +unsafe fn cpu_waited_within(fence: &ID3D12Fence, value: u64, dev: &ID3D12Device, what: &str, ms: u32) -> bool { + if ms == 0 { + return false; + } + thread_local! { + static EVENT: HANDLE = unsafe { windows::Win32::System::Threading::CreateEventW(None, false, false, None).unwrap_or_default() }; + } + let t = std::time::Instant::now(); + // (one event for this thread's waits: `fence::wait` takes a wake for an earlier registration + // that gave up as no completion) + let waited = EVENT.with(|&ev| crate::gpu::fence::wait(fence, value, dev, (!ev.is_invalid()).then_some(ev), ms)); + let took = t.elapsed(); + static SLOW: AtomicU64 = AtomicU64::new(0); + match waited { + Ok(()) => { + if took >= std::time::Duration::from_millis(200) && SLOW.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: {what} waited {} ms on the CPU for fence {value}", took.as_millis()); + } + true + } + Err(e) => { + crate::xlog_warn!( + "D3D12.X: {what} did not reach {value} in {} ms (at {}: {e}): the title's queue waits for it on the GPU", + took.as_millis(), + super::real::fence_completed(fence) + ); + false + } + } +} + /// A buffer the title places at `va` in a sparse window (`bytes` long, `desc` the PC /// description): a reserved resource over the window's tiles there, starting at the 64 KiB /// below `va` (returned: its distance from there). @@ -8441,6 +9407,77 @@ fn forget_in(s: &mut State, res: usize) { mod tests { use super::*; + /// Adapted from CallMeBrado's #1916: consumed CPU writes still reach first GPU exposure. + #[test] + fn private_physical_pages_reach_the_gpu_on_mapping() { + const CHILD: &str = "XCL_TEST_PRIVATE_PHYSICAL_PAGES"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::sparse::tests::private_physical_pages_reach_the_gpu_on_mapping", "--nocapture"]) + .env(CHILD, "1").env("XCL_DEFER_PRIVATE_HOME_TILES", "1") + .env("XCL_SPARSE_LAZY", "1").env("XCL_DS_KNOWN_WRITES", "0") + .output().unwrap(); + print!("{}", String::from_utf8_lossy(&output.stdout)); + eprint!("{}", String::from_utf8_lossy(&output.stderr)); + assert!(output.status.success()); + return; + } + use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, write_physical_pages}; + unsafe { + let dev = test_device(); + if software(&dev) { + return crate::gpu::recomp::runner::skip_test("no hardware sparse adapter"); + } + let Some(u) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no UMA"); }; + if !u.has_sparse() { return crate::gpu::recomp::runner::skip_test("no sparse windows"); } + let windows = init(&dev); + if windows.is_empty() { return crate::gpu::recomp::runner::skip_test("no reserved sparse buffers"); } + for (_, raw, _) in windows { drop(ID3D12Resource::from_raw(raw as *mut c_void)); } + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let mut pages = [0usize; 3]; + let mut n = pages.len(); + let null = std::ptr::null_mut(); + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1); + let first = vec![0xa7; TILE]; + let last = vec![0x38; TILE]; + let before = mapped_ranges(); + assert!(write_physical_pages(&pages[..1], 0, &first)); + assert!(write_physical_pages(&pages[2..], 0, &last)); + super::super::title_textures::refresh(queue.as_raw()); + assert_eq!(mapped_ranges(), before, "storage-only homes acquired sparse GPU tiles"); + let first_home = MapTitlePhysicalPages(null, 1, 0, 4, pages.as_mut_ptr()); + assert!(!first_home.is_null()); + let home = MapTitlePhysicalPages(null, n, 0, 4, pages.as_mut_ptr()) as usize; + assert_eq!(home, first_home as usize); + assert!(mapped_ranges().iter().any(|&(a, b)| a <= home && home + n * TILE <= b)); + assert_eq!(windows_sys::Win32::System::Memory::ResetWriteWatch(home as *const c_void, n * TILE), 0); + super::super::title_textures::refresh(queue.as_raw()); + std::ptr::write_bytes(home as *mut u8, 0xdd, n * TILE); + readback_after_execute(&queue, &[(home, n * TILE)], &[]); + let started = std::time::Instant::now(); + while RB_PENDING.load(Ordering::Acquire) != 0 && started.elapsed().as_secs() < 5 { + settle_readbacks(); + std::thread::yield_now(); + } + assert_eq!(RB_PENDING.load(Ordering::Acquire), 0, "copy back did not finish"); + let result = std::slice::from_raw_parts(home as *const u8, n * TILE); + assert_eq!(&result[..TILE], &first); + // The untouched middle page got no upload. With lazy commits its tile has no video + // memory (the window reads zeros there), so there is nothing to copy back and the + // CPU's own bytes stay. + let mid = home + TILE; + if lazy_commits() { + let pool = STATE.lock().unwrap().as_ref().and_then(|s| s.mapped.get(&mid).map(|e| e.pool)); + assert_eq!(pool, Some(LAZY), "the untouched page got video memory"); + assert!(result[TILE..2 * TILE].iter().all(|&b| b == 0xdd)); + } else { + assert!(result[TILE..2 * TILE].iter().all(|&b| b == 0)); + } + assert_eq!(&result[2 * TILE..], &last); + assert_eq!(FreeTitlePhysicalPages(null, n, pages.as_mut_ptr()), 1); + } + } + thread_local! { /// The VirtualQuery calls `source_holes` made on this thread. pub(super) static VIRTUAL_QUERIES: std::cell::Cell = const { std::cell::Cell::new(0) }; @@ -8459,10 +9496,40 @@ mod tests { pub(super) static NO_TILES: std::cell::Cell = const { std::cell::Cell::new(false) }; } + /// A tile with no page committed (a placed buffer's over reserved memory) is left out of the + /// watched runs; the commit of one of its pages puts it there and makes the watched ranges + /// again, once (#2754). + #[test] + fn a_tile_with_no_page_committed_is_watched_from_its_first_commit() { + let t0 = 0x2000_0000usize; + let mut mapped: FxHashMap = FxHashMap::default(); + mapped.insert(t0, TileEntry::with_holes((0, 0), 0)); + mapped.insert(t0 + TILE, TileEntry::with_holes((0, 1), 0xFFFF)); + mapped.insert(t0 + 2 * TILE, TileEntry::with_holes((0, 2), 0x00FF)); + // a tile over a CPU view: its holes are the CPU view's pages, and it is never in `runs` + mapped.insert(t0 + 3 * TILE, TileEntry { src: 0x3000_0000, ..TileEntry::with_holes((0, 3), 0xFFFF) }); + let mut runs = BTreeMap::from([(t0, t0 + TILE), (t0 + 2 * TILE, t0 + 3 * TILE)]); + + let gen = mapped_gen(); + assert!(unmask_committed_holes(&mut mapped, &mut runs, t0 + TILE, PAGE, true)); + assert_eq!(mapped[&(t0 + TILE)].holes, 0xFFFE); + assert_eq!(runs, BTreeMap::from([(t0, t0 + 3 * TILE)])); + assert!(mapped_gen() > gen, "the watched ranges are made again"); + + // a page of a tile watched already, and of one over a CPU view: nothing new to watch + assert!(!unmask_committed_holes(&mut mapped, &mut runs, t0 + TILE + PAGE, PAGE, true)); + assert!(!unmask_committed_holes(&mut mapped, &mut runs, t0 + 2 * TILE, 8 * PAGE, true)); + assert!(!unmask_committed_holes(&mut mapped, &mut runs, t0 + 3 * TILE, PAGE, true)); + assert_eq!((mapped[&(t0 + TILE)].holes, mapped[&(t0 + 2 * TILE)].holes, mapped[&(t0 + 3 * TILE)].holes), (0xFFFC, 0, 0xFFFE)); + assert_eq!(runs, BTreeMap::from([(t0, t0 + 3 * TILE)])); + // a range over unmapped addresses changes nothing + assert!(!unmask_committed_holes(&mut mapped, &mut runs, t0 + 8 * TILE, 2 * TILE, true)); + } + /// The runs of the tiles mapped, made from all of them (but those over a CPU view: their /// own addresses are no CPU memory). fn runs_of(s: &State) -> BTreeMap { - let mut tiles: Vec = s.mapped.iter().filter(|(_, e)| e.src == 0).map(|(&t, _)| t).collect(); + let mut tiles: Vec = s.mapped.iter().filter(|(_, e)| e.src == 0 && e.holes != 0xFFFF).map(|(&t, _)| t).collect(); tiles.sort_unstable(); let mut runs: Vec<(usize, usize)> = Vec::new(); for t in tiles { @@ -8747,6 +9814,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: AtomicBool::new(false), + mapped_value: 0, runs: BTreeMap::new(), scratch_runs: Vec::new(), own_pages: Vec::new(), @@ -8761,6 +9830,7 @@ mod tests { fill_pages: fill_pages(), mirrored: 0, mirror_cap: mirror_cap(), + gpu_written: Vec::new(), refused: FxHashSet::default(), no_memory: None, starved: Vec::new(), @@ -8768,6 +9838,7 @@ mod tests { diag: ViewDiag::default(), poison: None, retry_pages: Vec::new(), + reading: None, }; s.commit_range(base, TILE); assert!(s.mapped.contains_key(&base)); @@ -10247,6 +11318,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: AtomicBool::new(false), + mapped_value: 0, runs: BTreeMap::new(), scratch_runs: Vec::new(), own_pages: Vec::new(), @@ -10261,6 +11334,7 @@ mod tests { fill_pages: fill_pages(), mirrored: 0, mirror_cap: mirror_cap(), + gpu_written: Vec::new(), refused: FxHashSet::default(), no_memory: None, starved: Vec::new(), @@ -10268,6 +11342,7 @@ mod tests { diag: ViewDiag::default(), poison: None, retry_pages: Vec::new(), + reading: None, }; let (first, reused) = s.take_tile().expect("a tile from a new pool"); @@ -10665,6 +11740,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: AtomicBool::new(false), + mapped_value: 0, runs: BTreeMap::new(), scratch_runs: Vec::new(), own_pages: Vec::new(), @@ -10679,6 +11756,7 @@ mod tests { fill_pages: fill_pages(), mirrored: 0, mirror_cap: mirror_cap(), + gpu_written: Vec::new(), refused: FxHashSet::default(), no_memory: None, starved: Vec::new(), @@ -10686,6 +11764,7 @@ mod tests { diag: ViewDiag::default(), poison: None, retry_pages: Vec::new(), + reading: None, }; // Mirrors `place_buffer`: map both tiles probing real OS page commitment. @@ -10798,6 +11877,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: AtomicBool::new(false), + mapped_value: 0, runs: BTreeMap::new(), scratch_runs: Vec::new(), own_pages: Vec::new(), @@ -10812,6 +11893,7 @@ mod tests { fill_pages: fill_pages(), mirrored: 0, mirror_cap: mirror_cap(), + gpu_written: Vec::new(), refused: FxHashSet::default(), no_memory: None, starved: Vec::new(), @@ -10819,6 +11901,7 @@ mod tests { diag: ViewDiag::default(), poison: None, retry_pages: Vec::new(), + reading: None, }; s.commit_range(base, TILE); @@ -10988,6 +12071,46 @@ mod tests { (base, s) } + /// The signal after tile mappings is the one a title queue's wait for them is told by + /// (`mapped_value`): a wait across it is waited for on the CPU, one for uploads alone stays + /// on the GPU. The CPU wait returns once the fence is there, and gives up at its limit (and + /// at once with the limit 0) for the GPU wait to take over. + #[test] + fn a_wait_across_tile_mappings_is_waited_for_on_the_cpu() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + s.commit_range(base, TILE); + // (as before the title's submit: the tile's mapping and the signal after it) + s.flush_pending(); + assert!(s.value > 0 && s.mapped_value == s.value, "value {} mapped {}", s.value, s.mapped_value); + assert!(!s.mapping_queued.load(Ordering::Relaxed)); + assert!(waits_for_mappings(s.mapped_value, None)); + assert!(waits_for_mappings(s.mapped_value, Some(s.mapped_value - 1))); + let mapped = s.mapped_value; + // a signal with no mapping before it (uploads alone) + s.signal(); + assert_eq!(s.mapped_value, mapped); + assert!(!waits_for_mappings(s.mapped_value, Some(mapped)), "a queue past the mapping waits for uploads alone"); + + assert!(cpu_waited_within(&s.fence, s.value, &s.dev, "test mappings", 5000), "the sparse queue's fence was not reached"); + let never: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let t = std::time::Instant::now(); + assert!(!cpu_waited_within(&never, 1, &s.dev, "test mappings", 50)); + assert!(t.elapsed() >= std::time::Duration::from_millis(45), "gave up after {:?}", t.elapsed()); + let t = std::time::Instant::now(); + assert!(!cpu_waited_within(&never, 1, &s.dev, "test mappings", 0)); + assert!(t.elapsed() < std::time::Duration::from_millis(45), "the wait is off at 0"); + // a later fence value reached after a wait that gave up on the same event + never.Signal(1).expect("CPU signal"); + assert!(cpu_waited_within(&never, 1, &s.dev, "test mappings", 50)); + + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + unsafe fn add_upload_slot(s: &mut State, fence_val: u64, close: bool) { let alloc = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("upload allocator"); let list: ID3D12GraphicsCommandList = s.dev @@ -11387,6 +12510,44 @@ mod tests { drop(lazy); } + /// Memory the title made an unordered-access view by address over: a tile listed with no + /// video memory gets it when the view is made known, and one committed afterwards gets it at + /// its commit; a tile outside the view stays listed. + #[test] + fn a_lazy_tile_under_an_unordered_access_view_by_address_gets_video_memory() { + unsafe { + let lazy = Lazy::on(true); + let Some((base, mut s, _queue)) = lazy_state(4) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") }; + s.commit_range(base, TILE); + s.commit_range(base + 3 * TILE, TILE); + assert_eq!(s.mapped[&base].pool, LAZY, "listed at the commit"); + // a view of tiles 0 and 1 (bytes inside them) + s.gpu_written(&[(base + 0x100, TILE + 0x40)]); + assert_ne!(s.mapped[&base].pool, LAZY, "the listed tile under the view got memory"); + assert_eq!(s.mapped[&(base + 3 * TILE)].pool, LAZY, "the tile outside it did not"); + s.commit_range(base + TILE, TILE); + assert_ne!(s.mapped[&(base + TILE)].pool, LAZY, "committed under the view: mapped at the commit"); + s.commit_range(base + 2 * TILE, TILE); + assert_eq!(s.mapped[&(base + 2 * TILE)].pool, LAZY, "committed outside it: listed"); + drop(lazy); + } + } + + #[test] + fn runs_join_and_find() { + let mut r = Vec::new(); + assert!(add_run(&mut r, 0x30000, 0x40000)); + assert!(add_run(&mut r, 0x10000, 0x20000)); + assert!(!add_run(&mut r, 0x10000, 0x20000), "known already"); + assert!(!add_run(&mut r, 0x5000, 0x5000), "empty"); + assert_eq!(r, vec![(0x10000, 0x20000), (0x30000, 0x40000)]); + assert!(in_runs(&r, 0x10000) && in_runs(&r, 0x3ffff) && !in_runs(&r, 0x20000) && !in_runs(&r, 0x40000) && !in_runs(&r, 0)); + assert!(add_run(&mut r, 0x20000, 0x30000), "the gap between two runs joins them"); + assert_eq!(r, vec![(0x10000, 0x40000)]); + assert!(add_run(&mut r, 0x8000, 0x50000)); + assert_eq!(r, vec![(0x8000, 0x50000)]); + } + /// Decommitting a tile with no video memory frees and parks nothing; committed again it is /// listed again. With the switch off a commit maps at once, as before. #[test] @@ -12097,6 +13258,53 @@ mod tests { } } + /// `source_holes_cached` caches known-accessible regions across calls (zero VirtualQuery on + /// repeat queries even for unsorted tiles), keeps unrelated regions cached when another range + /// is freed, immediately exposes a decommitted hole after `invalidate_source_range`, and sees + /// a newly re-committed page without needing commit invalidation. + #[test] + fn source_holes_cached_reuses_regions_and_invalidates_only_freed_ranges() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + const TILES: usize = 32; + unsafe { + let a = VirtualAlloc(std::ptr::null(), TILES * TILE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + let b = VirtualAlloc(std::ptr::null(), 4 * TILE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert!(a != 0 && b != 0); + // Unsorted tiles inside `a` populate the region cache in one VirtualQuery. + let tiles_a: Vec = [20, 3, 31, 0, 10].into_iter().map(|k| a + k * TILE).collect(); + let q0 = VIRTUAL_QUERIES.with(|n| n.get()); + assert_eq!(source_holes_cached(&tiles_a, &[]), vec![0; tiles_a.len()]); + let q1 = VIRTUAL_QUERIES.with(|n| n.get()); + assert!(q1 - q0 >= 1 && q1 - q0 <= 2, "initial miss should populate `a` in <= 2 queries, got {}", q1 - q0); + + // Second query over different tiles in `a` makes zero VirtualQuery calls. + let more_a: Vec = [1, 15, 29, 7].into_iter().map(|k| a + k * TILE).collect(); + assert_eq!(source_holes_cached(&more_a, &[]), vec![0; more_a.len()]); + assert_eq!(VIRTUAL_QUERIES.with(|n| n.get()), q1, "cache hit must do 0 VirtualQuery calls"); + + // Invalidating unrelated region `b` must not evict `a`. + invalidate_source_range(b, 4 * TILE); + assert_eq!(source_holes_cached(&tiles_a, &[]), vec![0; tiles_a.len()]); + assert_eq!(VIRTUAL_QUERIES.with(|n| n.get()), q1, "unrelated free must not evict `a`"); + + // Decommitting one page in tile 10 and invalidating it exposes the hole immediately. + let hole_pg = a + 10 * TILE + 5 * PAGE; + assert_ne!(VirtualFree(hole_pg as *mut c_void, PAGE, MEM_DECOMMIT), 0); + invalidate_source_range(hole_pg, PAGE); + let holes = source_holes_cached(&[a + 10 * TILE, a + 20 * TILE], &[]); + assert_eq!(holes, vec![1 << 5, 0]); + + // Re-committing the hole is seen immediately (holes are never cached). + assert!(!VirtualAlloc(hole_pg as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + assert_eq!(source_holes_cached(&[a + 10 * TILE], &[]), vec![0]); + + invalidate_source_range(a, TILES * TILE); + invalidate_source_range(b, 4 * TILE); + assert_ne!(VirtualFree(a as *mut c_void, 0, MEM_RELEASE), 0); + assert_ne!(VirtualFree(b as *mut c_void, 0, MEM_RELEASE), 0); + } + } + /// A tile of a GPU view holds what its CPU view holds once it is asked for (the CPU wrote it /// before), and follows the CPU's writes, the many small ones too (dispatches) – far into the /// window and across the 1 GiB a dispatch reaches on a GPU. Before, the GPU read zeros there. @@ -13565,4 +14773,201 @@ mod tests { assert_eq!(iso.rb.lock().unwrap().submitting, 0); } } + + /// `mapped_ranges` asked again with no tile mapped or unmapped since answers without the state's + /// lock; once `MAPPED_GEN` moved it takes the lock again. + #[test] + fn mapped_ranges_made_at_this_generation_need_no_lock() { + let fake = vec![(0x7000_0000usize, 0x7001_0000usize)]; + // (other tests move the generation too: tried a few times) + let mut answered = false; + for _ in 0..20 { + let g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let gen = MAPPED_GEN.load(Ordering::Acquire); + *RANGES_KEPT.lock().unwrap() = Some((gen, fake.clone())); + let (tx, rx) = std::sync::mpsc::channel(); + let asker = std::thread::spawn(move || { + let _ = tx.send(mapped_ranges()); + }); + let got = rx.recv_timeout(std::time::Duration::from_millis(500)); + let moved = MAPPED_GEN.load(Ordering::Acquire) != gen; + drop(g); + asker.join().unwrap(); + if moved { + continue; + } + assert_eq!(got.expect("answered with the state's lock held elsewhere"), fake); + answered = true; + break; + } + assert!(answered, "the generation never stood still"); + // a tile mapped or unmapped since: made again, under the lock + let g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + MAPPED_GEN.fetch_add(1, Ordering::Release); + let (tx, rx) = std::sync::mpsc::channel(); + let asker = std::thread::spawn(move || { + let _ = tx.send(mapped_ranges()); + }); + assert!(rx.recv_timeout(std::time::Duration::from_millis(50)).is_err(), "a stale answer without the lock"); + drop(g); + let again = rx.recv_timeout(std::time::Duration::from_secs(10)).expect("answered once the lock was free"); + asker.join().unwrap(); + assert_ne!(again, fake); + } + + /// `len` bytes of `byte` put into the window's video memory at `va`, not into its CPU memory: + /// what the GPU wrote there. + unsafe fn gpu_fill(s: &mut State, va: usize, len: usize, byte: u8) { + // (the tiles' clears first, as a submit sends them before the title's work) + let zeroed = zero_runs(std::mem::take(&mut s.to_zero)); + for &(a, n) in &zeroed { + s.clear_sent_range(a, n); + } + assert!(matches!(s.upload_zeros(&zeroed), UploadStep::Done(PreparationOutcome::Ready)), "the tiles' clears went out"); + let mut d = buffer_desc(len as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + let mut up: Option = None; + s.dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut up).expect("upload buffer"); + let up = up.expect("upload buffer"); + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).expect("Map"); + std::ptr::write_bytes(p as *mut u8, byte, len); + up.Unmap(0, None); + let (base, window) = (s.windows[0].0, s.windows[0].1.clone()); + let alloc: ID3D12CommandAllocator = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list"); + list.CopyBufferRegion(&window, (va - base) as u64, &up, 0, len as u64); + list.Close().expect("Close"); + s.flush_pending(); + s.queue.ExecuteCommandLists(&[Some(list.cast().expect("list"))]); + s.signal(); + s.wait_for(s.value); + } + + /// A CPU read longer than the readback buffer goes in copies of it one after the other, each + /// waited for with the lock released, and one that begins and ends inside a 64-byte chunk lands + /// those bytes only. + #[test] + fn a_long_cpu_read_lands_in_pieces_and_its_ends_only_in_range() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + if !cpu_read_unlocked() { + return crate::gpu::recomp::runner::skip_test("XCL_CPU_READ_UNLOCKED=0"); + } + unsafe { + let tiles = READBACK_STAGING / TILE + 2; + let (base, mut s) = test_state_with_reserved(tiles); + if s.rbq.is_none() { + let _ = VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + return crate::gpu::recomp::runner::skip_test("no readback queue"); + } + assert!(!VirtualAlloc(base as *const c_void, tiles * TILE, MEM_COMMIT, PAGE_READWRITE).is_null()); + s.commit_range(base, tiles * TILE); + s.flush_pending(); + gpu_fill(&mut s, base, tiles * TILE, 0x3C); + let state = Mutex::new(Some(s)); + // (from 0x1234 into the first tile to 7 bytes into a chunk of the last) + let (va, end) = (base + 0x1234, base + (tiles - 1) * TILE + 0x5007); + readback_now_with(&state, va, end - va); + // (the first byte that is not as it should be, by its distance from `base`) + let other = |a: usize, n: usize, b: u8| std::slice::from_raw_parts(a as *const u8, n).iter().position(|&x| x != b).map(|k| a + k - base); + assert_eq!(other(va, end - va, 0x3C), None, "the whole read has the GPU's bytes, past the readback buffer's size too"); + assert_eq!((other(base, va - base, 0), other(end, base + tiles * TILE - end, 0)), (None, None), "nothing lands outside the read"); + let mut g = state.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(s.reading.is_none()); + assert_eq!(s.rb_last_fence, s.value, "the last copy was the read's"); + s.wait_for(s.value); + drop(g); + let _ = VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + + #[test] + fn meets_finds_overlaps_with_sorted_runs() { + let runs = [(0x100, 0x140), (0x800, 0x900)]; + assert!(!meets(&runs, 0x140, 0x180), "ends are exclusive"); + assert!(meets(&runs, 0x13F, 0x141)); + assert!(meets(&runs, 0x8C0, 0x900)); + assert!(!meets(&runs, 0x900, 0x940)); + assert!(!meets(&[], 0, usize::MAX)); + } + + /// A CPU read (`readback_now_with`) waits for its copy back with the state's lock released, and + /// what changed in its range meanwhile keeps its bytes: a chunk the CPU wrote, a page + /// decommitted and committed again (zeros), and what a later submission's copy back landed + /// (here the zeros the CPU had: the hashes cannot tell it from an untouched chunk). The rest + /// gets what the GPU wrote, with its hashes. Before, the read held the lock until its copy was + /// done (a retail title: 3.6–6.3 ms a submit, the submits waiting behind it). + #[test] + fn cpu_read_waits_unlocked_and_keeps_what_changed_meanwhile() { + if !cpu_read_unlocked() { + return crate::gpu::recomp::runner::skip_test("XCL_CPU_READ_UNLOCKED=0"); + } + unsafe { + let iso = IsolatedAsyncState::new(); + let base = iso.base; + let blocker: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let _unblock = SignalOnDrop(blocker.clone(), 1); + { + let mut g = iso.state.lock().unwrap(); + let s = g.as_mut().unwrap(); + gpu_fill(s, base, 4 * PAGE, 0x5A); + // (the state's queue held until the test lets it go: the read's copy waits behind it) + s.queue.Wait(&blocker, 1).expect("Wait"); + } + let state = Arc::clone(&iso.state); + let reader = std::thread::spawn(move || readback_now_with(&state, base, 4 * PAGE)); + let t0 = std::time::Instant::now(); + while iso.state.lock().unwrap().as_ref().is_some_and(|s| s.reading.is_none()) { + assert!(t0.elapsed() < std::time::Duration::from_secs(10), "the read's copy was never submitted"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + for _ in 0..5 { + assert!(iso.state.try_lock().is_ok(), "the state's lock is free while the read waits for its copy"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + // the CPU writes a chunk + std::ptr::write_bytes((base + 0x100) as *mut u8, 0x77, CHUNK); + // a page is decommitted and committed again + let p2 = base + 2 * PAGE; + assert!(VirtualFree(p2 as *mut c_void, PAGE, MEM_DECOMMIT) != 0); + iso.state.lock().unwrap().as_mut().unwrap().decommit_range(p2, PAGE); + assert!(!VirtualAlloc(p2 as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + iso.state.lock().unwrap().as_mut().unwrap().commit_range(p2, PAGE); + // a later submission's copy back lands + let at = base + 3 * PAGE + 0x800; + let done: ID3D12Fence = iso.dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).expect("fence"); + let mut job = take_or_alloc_rb_job(&iso.dev, &iso.rb, 256, D3D12_COMMAND_LIST_TYPE_DIRECT).expect("readback job"); + std::ptr::write_bytes(job.ptr, 0, 256); + job.copies.clear(); + job.copies.push((at, 0, 256, iso.gen)); + (job.rb_v, job.done_v, job.fences) = (1, 1, Some((done.clone(), done))); + { + let mut rq = iso.rb.lock().unwrap(); + rq.job_seq += 1; + job.seq = rq.job_seq; + rq.rb_jobs.push_back(job); + } + RB_PENDING.fetch_add(1, Ordering::Release); + drop(iso.state.lock().unwrap().as_mut().unwrap().land_finished_readbacks()); + assert!(iso.rb.lock().unwrap().rb_jobs.is_empty(), "the later copy back landed"); + blocker.Signal(1).expect("Signal"); + reader.join().unwrap(); + + let bytes = |a: usize, n: usize| std::slice::from_raw_parts(a as *const u8, n).to_vec(); + let all = |a: usize, n: usize, b: u8| bytes(a, n).iter().all(|&x| x == b); + assert!(all(base, 0x100, 0x5A) && all(base + 0x140, PAGE - 0x140, 0x5A), "the GPU's bytes landed around the CPU's chunk"); + assert!(all(base + 0x100, CHUNK, 0x77), "the chunk the CPU wrote while the copy was made keeps its bytes"); + assert!(all(base + PAGE, PAGE, 0x5A)); + assert!(all(p2, PAGE, 0), "the page committed again keeps its zeros"); + assert!(all(base + 3 * PAGE, 0x800, 0x5A) && all(at + 256, PAGE - 0x900, 0x5A)); + assert!(all(at, 256, 0), "what the later copy back landed stays"); + assert!(all(base + 4 * PAGE, PAGE, 0), "nothing lands past the read"); + let g = iso.state.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert!(s.reading.is_none()); + let sent = s.mapped[&base].sent[1].as_deref().expect("hashes of a landed page"); + assert_eq!(sent[0], chunk_hash(&[0x5A; CHUNK]), "a landed chunk has the hash of its bytes: the next look sends nothing"); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/texture_upload.rs b/crates/xcl/src/hle/d3d12x/texture_upload.rs index dfc1b7fce4..ae1b0a4590 100644 --- a/crates/xcl/src/hle/d3d12x/texture_upload.rs +++ b/crates/xcl/src/hle/d3d12x/texture_upload.rs @@ -78,6 +78,9 @@ pub(super) struct Pages { last: Vec, /// what goes up again, and the uploads it has to come behind (`sent`) again: Option<(Change, Vec)>, + /// parts (from, to) a mapping changed under since they were last looked at: compared with + /// what they held at its next upload, as written pages are (`recheck`) + recheck: Vec<(usize, usize)>, } /// Where an upload went: the queue, the fence of that queue's uploads and the value behind it. @@ -113,6 +116,7 @@ pub(super) fn all_sent(known: &Known, src: usize, size: usize) { k.hashes.clear(); k.hashes.resize(pages_of(src, size), 0); k.again = None; + k.recheck.clear(); } /// Nothing is known about what the PC texture holds: its next upload is of all of it. @@ -144,6 +148,28 @@ pub(super) fn stale(known: &Known, parts: Vec<(usize, usize)>) { }); } +/// `parts` of a texture (from, to) show other pages now (a mapping changed under them): its next +/// upload compares their bytes with what its pages held when they last went up, as for written +/// pages (`take_recheck`), and sends only those that differ. A page whose hash is not known (0) +/// differs; what is known of a page is what the PC texture got (`Hashes::note`), so equal bytes +/// are what it holds there. +pub(super) fn recheck(known: &Known, parts: Vec<(usize, usize)>) { + known.lock().unwrap().recheck.extend(parts); +} + +/// The pages of a texture at `src` to compare at this upload (`recheck`): their addresses, sorted. +pub(super) fn take_recheck(known: &Known, src: usize) -> Vec { + let parts = std::mem::take(&mut known.lock().unwrap().recheck); + let mut out: Vec = parts + .into_iter() + .filter(|r| r.0 < r.1) + .flat_map(|(from, to)| ((src + from) / PAGE * PAGE..src + to).step_by(PAGE)) + .collect(); + out.sort_unstable(); + out.dedup(); + out +} + /// `changed` of a texture (None: all of it) went up on `to`. An older upload of the texture on /// another queue that has not run yet (and that `to`'s queue has not waited for: `waited`) can land /// over it: it goes up again, behind that one (`take_again`). True when there is such a thing. @@ -777,8 +803,50 @@ unsafe impl Send for Job {} /// jobs the GPU is done with static FREE: Mutex> = Mutex::new(Vec::new()); + +/// Bytes of idle upload buffers kept for the next batches (`title_textures::upload_line`). +pub(super) fn idle_bytes() -> u64 { + FREE.lock().unwrap().iter().map(|j| j.bytes).sum() +} /// the smallest upload buffer made, and the most bytes of them kept const BUFFER_MIN: u64 = 1 << 20; +/// the lists of jobs whose buffers went (`give_back`), the GPU done with them too: a batch that +/// none of the kept buffers fits makes a buffer, not a list as well (on an RX 9070 XT a list with +/// its allocator took 0.1-0.35 ms to make, 3-11 µs to reset). Kept whatever `XCL_UPLOAD_KEEP_MB` +/// is: they are small next to the buffers +static SPARE: Mutex> = Mutex::new(Spares::new(SPARE_MAX)); +/// the most spare lists kept of one device +const SPARE_MAX: usize = 16; + +/// A list and its allocator. +type Lists = (ID3D12CommandAllocator, ID3D12GraphicsCommandList); + +/// Things kept for later by device, the newest taken first, at most `max` of one device. +struct Spares { + kept: Vec<(usize, T)>, + max: usize, +} + +impl Spares { + const fn new(max: usize) -> Self { + Spares { kept: Vec::new(), max } + } + + /// The newest kept of `dev`'s. + fn take(&mut self, dev: usize) -> Option { + let i = self.kept.iter().rposition(|(d, _)| *d == dev)?; + Some(self.kept.remove(i).1) + } + + /// `x` is kept, unless `dev` has `max` kept already: then it comes back. + fn keep(&mut self, dev: usize, x: T) -> Option { + if self.kept.iter().filter(|(d, _)| *d == dev).count() >= self.max { + return Some(x); + } + self.kept.push((dev, x)); + None + } +} /// The size of the buffer made for `bytes`: up to 64 MiB a power of two (few sizes, so one fits /// again), then the next 16 MiB. @@ -792,7 +860,17 @@ fn capacity(bytes: u64) -> Option { } } -const FREE_BYTES: u64 = 512 << 20; +/// The most bytes of idle upload buffers kept for the next batches (`XCL_UPLOAD_KEEP_MB`, default +/// 64): memory of the system's (upload heaps), the process's commit and RAM while kept. (A +/// retail title's world ran with 64 MB kept: ~60 MB idle, a few MB in flight.) +fn free_bytes() -> u64 { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| keep_bytes_of(std::env::var("XCL_UPLOAD_KEEP_MB").ok().as_deref())) +} + +fn keep_bytes_of(v: Option<&str>) -> u64 { + v.and_then(|v| v.trim().parse::().ok()).map_or(64, |mb| mb.min(4096)) << 20 +} /// A job whose buffer takes `bytes` bytes. unsafe fn take(dev: &ID3D12Device, bytes: u64) -> Result { @@ -804,12 +882,14 @@ unsafe fn take(dev: &ID3D12Device, bytes: u64) -> Result { return Ok(g.swap_remove(i)); } } + let spare = SPARE.lock().unwrap().take(key); + make_job(dev, bytes, spare) +} + +/// A job with a new buffer for `bytes` bytes, and `lists` (the GPU done with them) or new ones. +unsafe fn make_job(dev: &ID3D12Device, bytes: u64, lists: Option) -> Result { let e = |x: windows::core::Error| format!("texture upload: {x}"); let cap = capacity(bytes).ok_or("texture upload buffer size overflow")?; - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(e)?; - list.Close().map_err(e)?; - let _ = list.SetName(windows::core::w!("xcl texture upload list")); let mut buf: Option = None; dev.CreateCommittedResource( &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, @@ -832,17 +912,34 @@ unsafe fn take(dev: &ID3D12Device, bytes: u64) -> Result { let buf = buf.ok_or("texture upload buffer")?; let mut p: *mut c_void = std::ptr::null_mut(); buf.Map(0, None, Some(&mut p)).map_err(e)?; - Ok(Job { dev: key, alloc, list, buf, ptr: p as *mut u8, bytes: cap }) + let (alloc, list) = match lists { + Some(l) => l, + None => { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(e)?; + list.Close().map_err(e)?; + let _ = list.SetName(windows::core::w!("xcl texture upload list")); + (alloc, list) + } + }; + Ok(Job { dev: dev.as_raw() as usize, alloc, list, buf, ptr: p as *mut u8, bytes: cap }) } /// The GPU is done with `job`. pub(super) fn give_back(job: Job) { - let mut g = FREE.lock().unwrap(); - g.push(job); - // (the biggest goes first: one burst does not keep its buffers for good) - while g.iter().map(|j| j.bytes).sum::() > FREE_BYTES { - let Some(i) = g.iter().enumerate().max_by_key(|(_, j)| j.bytes).map(|(i, _)| i) else { break }; - g.swap_remove(i); + let mut gone = Vec::new(); + { + let mut g = FREE.lock().unwrap(); + g.push(job); + // (the biggest goes first: one burst does not keep its buffers for good) + while g.iter().map(|j| j.bytes).sum::() > free_bytes() { + let Some(i) = g.iter().enumerate().max_by_key(|(_, j)| j.bytes).map(|(i, _)| i) else { break }; + gone.push(g.swap_remove(i)); + } + } + // (their buffers go, out of the lock: that can take milliseconds; their lists stay) + for j in gone { + let _ = SPARE.lock().unwrap().keep(j.dev, (j.alloc, j.list)); } } @@ -882,6 +979,15 @@ pub(super) unsafe fn submit(dev: &ID3D12Device, queue: &ID3D12CommandQueue, item mod tests { use super::*; + #[test] + fn the_idle_upload_buffers_kept_follow_the_switch() { + assert_eq!(keep_bytes_of(None), 64 << 20, "unset: 64 MB"); + assert_eq!(keep_bytes_of(Some(" 512 ")), 512 << 20); + assert_eq!(keep_bytes_of(Some("0")), 0, "none kept"); + assert_eq!(keep_bytes_of(Some("lots")), 64 << 20); + assert_eq!(keep_bytes_of(Some("100000")), 4096 << 20); + } + /// The written pages of a texture are compared one by one: a page never compared has changed, /// one that holds what it held has not, the bytes next to the texture on its first and last /// page are not the texture's, and a texture nothing is known of changed as a whole. @@ -1292,6 +1398,76 @@ mod tests { assert_eq!(capacity(u64::MAX), None); } + /// Spares: none kept when the most is 0, the newest of a device first, no more of one device + /// than the most (the one past it comes back), and each device's apart. + #[test] + fn spares_are_kept_by_device_newest_first_up_to_the_most() { + let mut none = Spares::::new(0); + assert_eq!(none.keep(1, 10), Some(10)); + assert_eq!(none.take(1), None); + + let mut s = Spares::::new(2); + assert_eq!(s.take(1), None); + assert_eq!(s.keep(1, 10), None); + assert_eq!(s.keep(2, 99), None); + assert_eq!(s.keep(1, 20), None); + assert_eq!(s.keep(1, 30), Some(30), "past the most of a device it comes back, to go"); + assert_eq!(s.keep(2, 98), None, "another device's are counted apart"); + assert_eq!(s.take(1), Some(20)); + assert_eq!(s.take(1), Some(10)); + assert_eq!(s.take(1), None); + assert_eq!(s.take(2), Some(98)); + assert_eq!(s.take(2), Some(99)); + assert_eq!(s.take(2), None); + } + + /// A job whose buffer goes (more is kept than `XCL_UPLOAD_KEEP_MB`) leaves its list, and a job + /// made next for the device takes it with a new buffer, not a new list: what goes up through it + /// is the texture's texels. + #[test] + fn gpu_a_list_whose_buffer_went_goes_on_with_a_new_one() { + unsafe { + let Some(dev) = test_device() else { return }; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let m = make(&dev, KINDS[1]); + let size = m.tex.size() as usize; + // all of the texture through `job` as `submit` sends it, waited for and read back + let up = |job: &Job, seed: u64| { + let mem = random_bytes(size, seed); + let items = [Item { res: m.res.clone(), src: mem.as_ptr() as usize, tex: Arc::clone(&m.tex), states: vec![D3D12_RESOURCE_STATE_COMMON], changed: None, known: None, pages: None }]; + let (mut pieces, mut bytes) = (Vec::new(), 0u64); + plan_item(&dev, 0, &items[0], &mut bytes, &mut pieces).unwrap(); + assert!(bytes <= job.bytes, "{bytes} B in a {} B buffer", job.bytes); + fill(&items, &pieces, job.ptr, bytes); + job.alloc.Reset().unwrap(); + job.list.Reset(&job.alloc, None).unwrap(); + record(&job.list, &items, &pieces, &job.buf); + job.list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(job.list.cast().unwrap())]); + crate::gpu::texture::wait(&dev, &queue).unwrap(); + let want = super::super::title_textures::subresources(mem.as_ptr() as usize, &m.tex); + assert!(read_back(&dev, &queue, &m.res, want.len()) == want.iter().map(|w| w.data.clone()).collect::>(), "upload {seed}"); + }; + let mut first = make_job(&dev, 1, None).unwrap(); + assert_eq!(first.bytes, BUFFER_MIN); + up(&first, 1); + let list = first.list.as_raw() as usize; + // (taken for a device of its own, and for more than is ever kept: it goes at once, + // whatever the other tests keep, and its list is that device's only spare) + let own = Box::new(0u8); + let key = &*own as *const u8 as usize; + first.dev = key; + first.bytes = 1 << 62; + give_back(first); + let lists = SPARE.lock().unwrap().take(key).expect("its list stays"); + assert_eq!(lists.1.as_raw() as usize, list); + let second = make_job(&dev, 4 << 20, Some(lists)).unwrap(); + assert_eq!((second.list.as_raw() as usize, second.bytes), (list, 4 << 20), "the spare list, with a new buffer"); + up(&second, 2); + dev.GetDeviceRemovedReason().unwrap(); + } + } + /// A page the title decommits while it is read (or that never was committed) reads as zeros. #[test] fn memory_that_is_not_there_reads_as_zeros() { diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 9e99212213..494176c574 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -214,6 +214,7 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: old.extend(std::mem::replace(&mut b.first, stand_in).filter(|first| Some(*first) != stand_in)); old.extend(b.failed.take().filter(|failed| Some(*failed) != stand_in)); b.spares.extend(old.iter().copied()); + parked_anew(&old); old } else { Vec::new() @@ -369,7 +370,101 @@ pub(super) fn pop_spare(wrapper: *mut c_void) -> Option<*mut c_void> { let mut sg = SEGMENTS.lock().unwrap(); let spares = &mut sg.as_mut()?.get_mut(&(wrapper as usize))?.spares; let k = spares.iter().rposition(|&p| !super::alloc_pool::in_flight(p))?; - Some(spares.remove(k) as *mut c_void) + let pc = spares.remove(k); + // (in use again: it is idle anew when it is parked again) + parked_anew(&[pc]); + Some(pc as *mut c_void) +} + +/// `pcs` were just parked (or taken again, or released): what `trim_idle_spares` saw at their +/// addresses before does not count. A list released with its title list, or a new list the +/// driver made at a released one's address, must not be taken for a spare idle long since – +/// a list parked at a `KickoffX` is submitted after it is parked. (SEGMENTS may be held: it is +/// taken before SPARE_SEEN everywhere.) +fn parked_anew(pcs: &[usize]) { + if let Some(m) = SPARE_SEEN.lock().unwrap().as_mut() { + for p in pcs { + m.remove(p); + } + } +} + +/// Spare PC lists `trim_idle_spares` has seen parked, and when it first saw each. +static SPARE_SEEN: Mutex>> = Mutex::new(None); +/// Spare PC lists released by `trim_idle_spares` so far. +static SPARES_RELEASED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// A spare idle this long (seen parked, not reused, its last submit done) can go. +const SPARE_IDLE: std::time::Duration = std::time::Duration::from_secs(2); +/// Spares kept per title list whatever their age (the latest parked: the next split takes them). +const SPARES_KEPT: usize = 2; + +/// Which of `spares` (oldest first) go: past the last `keep`, seen parked for `idle` at `now` +/// (`seen`; a spare not seen yet is noted as seen now) and not in flight. +fn idle_spares(spares: &[usize], seen: &mut HashMap, keep: usize, idle: std::time::Duration, now: std::time::Instant, in_flight: impl Fn(usize) -> bool) -> Vec { + let old = spares.len().saturating_sub(keep); + let mut gone = Vec::new(); + for (i, &p) in spares.iter().enumerate() { + let since = *seen.entry(p).or_insert(now); + if i < old && now.duration_since(since) >= idle && !in_flight(p) { + gone.push(p); + } + } + gone +} + +/// Releases the spare PC lists of the title's lists that have been idle for `SPARE_IDLE`, past +/// the last `SPARES_KEPT` of each. A spare holds the memory of the driver's list object and of +/// what it last recorded until it is released, and the pools grew to the largest burst of +/// splits a list ever had (AMD: 1,800–4,000 spares; xcl-dev/xcl#3110, #3122). Returns the +/// spares left and released now. +pub(super) fn trim_idle_spares() -> (usize, usize) { + let now = std::time::Instant::now(); + let mut gone: Vec<(usize, usize)> = Vec::new(); + let mut left = 0; + { + let mut sg = SEGMENTS.lock().unwrap(); + let Some(m) = sg.as_mut() else { return (0, 0) }; + let mut seen_g = SPARE_SEEN.lock().unwrap(); + let seen = seen_g.get_or_insert_with(HashMap::new); + let mut parked = std::collections::HashSet::new(); + for (&wrapper, b) in m.iter_mut() { + let go = idle_spares(&b.spares, seen, SPARES_KEPT, SPARE_IDLE, now, super::alloc_pool::in_flight); + if !go.is_empty() { + b.spares.retain(|p| !go.contains(p)); + gone.extend(go.into_iter().map(|p| (wrapper, p))); + } + left += b.spares.len(); + parked.extend(b.spares.iter().copied()); + } + seen.retain(|p, _| parked.contains(p)); + } + if gone.is_empty() { + return (left, 0); + } + { + let mut wg = WRAPPER_OF.lock().unwrap(); + if let Some(m) = wg.as_mut() { + for &(wrapper, seg) in &gone { + if m.get(&seg) == Some(&wrapper) { + m.remove(&seg); + } + } + } + } + for &(_, seg) in &gone { + let raw = seg as *mut c_void; + super::alloc_pool::forget_list(seg); + super::bind::forget(raw); + unsafe { + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(raw, 2)); + rel(raw); + } + } + let n = gone.len(); + let total = SPARES_RELEASED.fetch_add(n, std::sync::atomic::Ordering::Relaxed) + n; + crate::xlog_info!("D3D12.X: title lists: {n} idle spare PC lists released ({total} so far), {left} spares kept"); + (left, n) } /// Give back to `wrapper`'s spare pool a closed PC command list that did not become a segment. @@ -377,6 +472,7 @@ 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); + parked_anew(&[pc as usize]); } /// Take segment `pc` out of `wrapper`'s recording, so it is not submitted. Its failed Close left @@ -505,6 +601,9 @@ pub(super) unsafe fn reclaim_for_kickoff(active_pc: *mut c_void) -> Option<(*mut } } book.spares.extend(extra.iter().copied()); + // (they are submitted after this, outside the lock: not idle yet whatever was seen at + // their address before) + parked_anew(&extra); (prior, extra) }; drop(sg); @@ -587,6 +686,7 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 { } } if let Some(b) = book { + parked_anew(&b.spares); for seg in b.extra_active.into_iter().chain(b.spares.into_iter()).chain(b.first).chain(b.failed).chain(b.unresettable) { let raw = seg as *mut c_void; super::alloc_pool::forget_list(seg); @@ -1123,4 +1223,41 @@ mod tests { drop(Box::from_raw(fake)); } } + + /// Idle spares go once seen parked for the idle time, oldest first, past the last ones kept, + /// and never while their last submit is on the GPU; a spare seen for the first time is only + /// noted. + #[test] + fn idle_spares_go_once_seen_idle_past_the_kept_ones() { + let t0 = std::time::Instant::now(); + let idle = std::time::Duration::from_secs(2); + let spares = [10usize, 11, 12, 13, 14]; + let mut seen = HashMap::new(); + // first sight: noted, none goes + assert!(idle_spares(&spares, &mut seen, 2, idle, t0, |_| false).is_empty()); + assert_eq!(seen.len(), 5); + // not idle long enough yet + assert!(idle_spares(&spares, &mut seen, 2, idle, t0 + std::time::Duration::from_secs(1), |_| false).is_empty()); + // idle: the three oldest go, the last two stay; one still on the GPU stays too + let t = t0 + idle; + assert_eq!(idle_spares(&spares, &mut seen, 2, idle, t, |p| p == 11), vec![10, 12]); + // a spare seen only now (parked again after a reuse) waits its own idle time + seen.remove(&10); + assert_eq!(idle_spares(&spares, &mut seen, 2, idle, t, |_| false), vec![11, 12]); + // fewer than kept: nothing goes + assert!(idle_spares(&spares[..2], &mut seen, 2, idle, t + idle, |_| false).is_empty()); + } + + /// A list parked where a released spare was seen long ago (the driver reuses addresses; a + /// list parked at a KickoffX is submitted only after it is parked) starts its idle time again. + #[test] + fn a_list_parked_anew_starts_its_idle_time_again() { + let (wrapper, pc) = (0x7e57_0000_1000usize, 0x7e57_0000_2000usize); + let now = std::time::Instant::now(); + let long_ago = now.checked_sub(std::time::Duration::from_secs(60)).unwrap_or(now); + SPARE_SEEN.lock().unwrap().get_or_insert_with(HashMap::new).insert(pc, long_ago); + put_spare(wrapper as *mut c_void, pc as *mut c_void); + assert!(!SPARE_SEEN.lock().unwrap().as_ref().unwrap().contains_key(&pc)); + SEGMENTS.lock().unwrap().as_mut().unwrap().remove(&wrapper); + } } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d809b1c2a2..4890ed1871 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -19,10 +19,10 @@ //! transitions of these textures are captured in each physical command-list segment's immutable //! submission effects and applied in submission order – per subresource once one is named. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::ffi::c_void; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, RwLock}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; @@ -52,6 +52,10 @@ struct Due { whole: bool, /// what of it goes up again (`texture_upload::sent`) again: texture_upload::Change, + /// the pages a mapping changed under it, to be compared (`texture_upload::recheck`) + recheck: Vec, + /// the CPU wrote one of its pages since its last upload + written: bool, /// (`Entry::target`) target: bool, /// where its pages are read (`Entry::paged`) @@ -105,7 +109,7 @@ struct Entry { /// not uploaded yet (made since the last submit) pending: bool, /// the title's GPU work wrote it (CopyTextureRegion into it): its CPU view is stale from - /// then on and no longer uploaded + /// then on and no longer uploaded, nor watched for (`Table::coarse`) gpu_written: bool, /// the calls of the queue's page mappings made when a list that writes it was last submitted /// (`kernelx::mirrors::calls`): a mapping changed under it by a later call is newer than the @@ -141,7 +145,7 @@ struct Table { by_res: BTreeMap, /// Active `(va, PC texture)` → end address (`va + size`); entries with different `(va, end)` are disjoint by_va: BTreeMap<(usize, usize), usize>, - /// Older overlapped textures kept dormant until released or uncovered when a newer one is released + /// Older overlapped textures kept dormant until sampled again or uncovered by a release shadowed: BTreeMap, /// Shadowed `(va, PC texture)` → end address (may overlap) shadowed_by_va: BTreeMap<(usize, usize), usize>, @@ -154,11 +158,33 @@ struct Table { src_pieces: BTreeMap>, /// textures whose first upload is still to come (`Entry::pending`; may name ones that went) pending_res: std::collections::BTreeSet, - /// 16 MiB blocks of the textures' sources -> how many active ones cover it: the part of the - /// watched ranges that textures make (cheap to rebuild from, unlike all textures) + /// shadowed textures `uncover` shadowed again: a draw recorded before may still sample them, + /// so their source stays linked and refreshes upload them until `Displaced::until` + displaced: BTreeMap, + /// 16 MiB blocks of the textures' sources -> how many active ones cover it (and displaced + /// ones; not GPU-written ones, which no CPU write there sends up): the part of the watched + /// ranges that textures make (cheap to rebuild from, unlike all textures) coarse: BTreeMap, + /// O(1) count of `by_res` entries with `cpu_backed == true` (avoids scanning 55k+ entries on + /// every texture placement/release under `TEXTURES` lock). + cpu_backed_count: usize, + /// Pending `(res, inserted)` updates to `SHADOWED_IDS`, flushed in `update_lengths`. + shadowed_delta: Vec<(usize, bool)>, + /// True only for the process-global `TEXTURES` table (local test tables skip global mirrors). + is_global: bool, +} + +/// A texture of `Table::displaced`. +struct Displaced { + /// the frame (`present::counters`) from which it is no longer uploaded as shadowed + until: u64, + /// its first upload is still to come (it stays `Entry::pending`, uncounted in `PENDING`) + whole: bool, } +/// how many frames a draw that sampled a texture `uncover` shadowed again may wait for its submit +const DISPLACED_FRAMES: u64 = 2; + /// the size of `Table::coarse`'s blocks const SRC_COARSE_SHIFT: usize = 24; @@ -175,7 +201,16 @@ fn in_view_window(src: usize) -> bool { } impl Table { + #[cfg(test)] const fn new() -> Self { + Self::with_global(false) + } + + const fn new_global() -> Self { + Self::with_global(true) + } + + const fn with_global(is_global: bool) -> Self { Table { by_res: BTreeMap::new(), by_va: BTreeMap::new(), @@ -185,14 +220,61 @@ impl Table { next_generation: 0, src_pieces: BTreeMap::new(), pending_res: std::collections::BTreeSet::new(), + displaced: BTreeMap::new(), coarse: BTreeMap::new(), + cpu_backed_count: 0, + shadowed_delta: Vec::new(), + is_global, + } + } + + #[inline] + fn insert_active(&mut self, res: usize, e: Entry) { + if e.cpu_backed { + self.cpu_backed_count += 1; + } + if let Some(prev) = self.by_res.insert(res, e) { + if prev.cpu_backed { + self.cpu_backed_count -= 1; + } } } - fn link_src(&mut self, res: usize, src: usize, size: usize) { + #[inline] + fn remove_active(&mut self, res: usize) -> Option { + let old = self.by_res.remove(&res)?; + if old.cpu_backed { + self.cpu_backed_count -= 1; + } + Some(old) + } + + #[inline] + fn insert_shadowed(&mut self, res: usize, e: Entry) { + self.shadowed.insert(res, e); + self.shadowed_delta.push((res, true)); + } + + #[inline] + fn remove_shadowed(&mut self, res: usize) -> Option { + let old = self.shadowed.remove(&res)?; + self.shadowed_delta.push((res, false)); + Some(old) + } + + /// `watched`: the texture is not GPU-written, so its source's blocks of `coarse` are watched + /// for it too (`unlink_src` is told the same). + fn link_src(&mut self, res: usize, src: usize, size: usize, watched: bool) { for p in (src >> SRC_PIECE_SHIFT)..=((src + size.max(1) - 1) >> SRC_PIECE_SHIFT) { self.src_pieces.entry(p).or_default().push(res); } + if watched { + self.watch_blocks(src, size); + } + } + + /// One texture more has its source `[src, src + size)` watched (`coarse`). + fn watch_blocks(&mut self, src: usize, size: usize) { if in_view_window(src) { return; } @@ -205,7 +287,7 @@ impl Table { } } - fn unlink_src(&mut self, res: usize, src: usize, size: usize) { + fn unlink_src(&mut self, res: usize, src: usize, size: usize, watched: bool) { for p in (src >> SRC_PIECE_SHIFT)..=((src + size.max(1) - 1) >> SRC_PIECE_SHIFT) { if let Some(v) = self.src_pieces.get_mut(&p) { v.retain(|&r| r != res); @@ -214,6 +296,13 @@ impl Table { } } } + if watched { + self.unwatch_blocks(src, size); + } + } + + /// One texture fewer has its source `[src, src + size)` watched. + fn unwatch_blocks(&mut self, src: usize, size: usize) { if in_view_window(src) { return; } @@ -233,7 +322,40 @@ impl Table { } } - /// The textures (active) whose source the dirty pages `dirty` (sorted) may touch. + /// The title's GPU work writes `res` (`note_gpu_write`, `submitted`): what the CPU writes over + /// it never goes up again, so its source is no longer watched for it – a block of `coarse` + /// only GPU-written textures lie in is left out of the looks for CPU writes. Whether it was + /// not GPU-written before. + fn mark_gpu_written(&mut self, res: usize) -> bool { + let linked = self.by_res.contains_key(&res) || self.displaced.contains_key(&res); + let Some(e) = self.get_mut(res).filter(|e| !e.gpu_written) else { return false }; + e.gpu_written = true; + let (src, size) = (e.src, e.tex.size() as usize); + if linked { + self.unwatch_blocks(src, size); + } + true + } + + /// `res` (shadowed, `e`) leaves `displaced`: its source is no longer watched for it. + fn undisplace(&mut self, res: usize, e: &Entry) { + if self.displaced.remove(&res).is_some() { + self.unlink_src(res, e.src, e.tex.size() as usize, !e.gpu_written); + } + } + + /// The displaced textures kept until `frame` or before stay shadowed only. + fn expire_displaced(&mut self, frame: u64) { + let gone: Vec = self.displaced.iter().filter(|(_, d)| d.until <= frame).map(|(&r, _)| r).collect(); + for r in gone { + self.displaced.remove(&r); + if let Some((src, size, watched)) = self.shadowed.get(&r).map(|e| (e.src, e.tex.size() as usize, !e.gpu_written)) { + self.unlink_src(r, src, size, watched); + } + } + } + + /// The textures (active and displaced) whose source the dirty pages `dirty` (sorted) may touch. fn touched_by(&self, dirty: &[usize]) -> std::collections::BTreeSet { let mut out = std::collections::BTreeSet::new(); let mut last = usize::MAX; @@ -293,8 +415,11 @@ impl Table { let (mut pending_delta, mut retired, mut to_unmap) = (0isize, 0usize, Vec::new()); for (ova, ores, _) in self.active_overlaps(va, end) { self.by_va.remove(&(ova, ores)); - if let Some(old) = self.by_res.remove(&ores) { - self.unlink_src(ores, old.src, old.tex.size() as usize); + if let Some(old) = self.remove_active(ores) { + if self.is_global { + res_generation_remove(ores); + } + self.unlink_src(ores, old.src, old.tex.size() as usize, !old.gpu_written); if old.pending { pending_delta -= 1; } @@ -306,7 +431,11 @@ impl Table { } for (sva, sres, _) in self.shadowed_overlaps(va, end) { self.shadowed_by_va.remove(&(sva, sres)); - if let Some(old) = self.shadowed.remove(&sres) { + if let Some(old) = self.remove_shadowed(sres) { + if self.is_global { + res_generation_remove(sres); + } + self.undisplace(sres, &old); if old.placed && !old.unmapped { to_unmap.push(sres); } @@ -329,23 +458,24 @@ impl Table { let end = va.saturating_add(entry.tex.size() as usize); let mut pending_delta = 0isize; let mut to_unmap = Vec::new(); - if let Some(old) = self.by_res.remove(&res) { - self.unlink_src(res, old.src, old.tex.size() as usize); + if let Some(old) = self.remove_active(res) { + self.unlink_src(res, old.src, old.tex.size() as usize, !old.gpu_written); self.by_va.remove(&(old.va, res)); if old.pending { pending_delta -= 1; } } - if let Some(old) = self.shadowed.remove(&res) { + if let Some(old) = self.remove_shadowed(res) { self.shadowed_by_va.remove(&(old.va, res)); + self.undisplace(res, &old); } for (ova, ores, oend) in self.active_overlaps(va, end) { if !entry.placed && ova == va && oend == end && self.by_res.get(&ores).is_some_and(|e| !e.placed) { continue; } self.by_va.remove(&(ova, ores)); - if let Some(mut old) = self.by_res.remove(&ores) { - self.unlink_src(ores, old.src, old.tex.size() as usize); + if let Some(mut old) = self.remove_active(ores) { + self.unlink_src(ores, old.src, old.tex.size() as usize, !old.gpu_written); if old.pending { pending_delta -= 1; } @@ -358,7 +488,7 @@ impl Table { } self.max_shadowed_size = self.max_shadowed_size.max(oend.saturating_sub(ova)); self.shadowed_by_va.insert((ova, ores), oend); - self.shadowed.insert(ores, old); + self.insert_shadowed(ores, old); } } // Also release tiles of any already-shadowed exact-range sibling now overwritten by a @@ -380,25 +510,113 @@ impl Table { self.pending_res.insert(res); } self.by_va.insert((va, res), end); - let (src, size) = (entry.src, entry.tex.size() as usize); - self.link_src(res, src, size); - self.by_res.insert(res, entry); + let (src, size, generation) = (entry.src, entry.tex.size() as usize, entry.generation); + self.link_src(res, src, size, !entry.gpu_written); + self.insert_active(res, entry); + if self.is_global { + res_generation_set(res, generation); + } (pending_delta, to_unmap) } + /// Reactivate a sampled texture and return its pending-count change and whether it needs + /// remapping. Keep displaced textures mapped for work that may still be using them, and + /// uploaded until frame `until`. + fn uncover(&mut self, res: usize, until: u64) -> Option<(isize, bool)> { + let mut e = self.remove_shadowed(res)?; + self.shadowed_by_va.remove(&(e.va, res)); + self.undisplace(res, &e); + let size = e.tex.size() as usize; + let (va, end) = (e.va, e.va.saturating_add(size)); + let mut pending_delta = 0; + for (ova, ores, oend) in self.active_overlaps(va, end) { + // Committed textures at the exact same range can coexist as format aliases. + if !e.placed && ova == va && oend == end && self.by_res.get(&ores).is_some_and(|o| !o.placed) { + continue; + } + self.by_va.remove(&(ova, ores)); + if let Some(old) = self.remove_active(ores) { + if old.pending { + self.pending_res.remove(&ores); + pending_delta -= 1; + } + if old.pending || !old.gpu_written { + // (its source stays linked: what the title writes there goes up too) + self.displaced.insert(ores, Displaced { until, whole: old.pending }); + } else { + self.unlink_src(ores, old.src, old.tex.size() as usize, !old.gpu_written); + } + self.max_shadowed_size = self.max_shadowed_size.max(oend.saturating_sub(ova)); + self.shadowed_by_va.insert((ova, ores), oend); + self.insert_shadowed(ores, old); + } + } + if self.shadowed.is_empty() { + self.max_shadowed_size = 0; + } + let remap = std::mem::take(&mut e.unmapped); + texture_upload::forget(&e.known); + if !e.gpu_written { + e.pending = true; + } + if e.pending { + self.pending_res.insert(res); + pending_delta += 1; + } + self.by_va.insert((va, res), end); + self.link_src(res, e.src, size, !e.gpu_written); + self.insert_active(res, e); + Some((pending_delta, remap)) + } + + /// The sources `res` of a bake whose list is about to be submitted (`ready_bake_sources`): one + /// shadowed now – a texture placed over it since the draw, or one a later draw made active + /// again – is made active again (`uncover`; the last of overlapping ones wins, as at the + /// draw); an active one whose bytes are the CPU's goes up whole at this submit, as the title's + /// memory has it now rather than at an earlier upload. Not one the GPU wrote. + fn ready_for_bake(&mut self, res: &[usize], until: u64) -> BakeReady { + let mut out = BakeReady::default(); + for &r in res { + if self.shadowed.contains_key(&r) { + if let Some((d, unmapped)) = self.uncover(r, until) { + out.uncovered += 1; + out.pending_delta += d; + if unmapped { + out.remap.push(r); + } + } + continue; + } + let Table { by_res, pending_res, .. } = self; + let Some(e) = by_res.get_mut(&r).filter(|e| e.cpu_backed && !e.gpu_written && !e.pending) else { continue }; + e.pending = true; + pending_res.insert(r); + out.pending_delta += 1; + out.whole += 1; + } + out + } + /// Remove `res` on COM release, reactivating any shadowed older textures it uncovered (newest /// first). Returns `(was_present, pending_delta, unmapped_res_to_remap, uniform_state)`. fn remove(&mut self, res: usize) -> (bool, isize, Vec, Option) { - if let Some(old) = self.shadowed.remove(&res) { + if let Some(old) = self.remove_shadowed(res) { + if self.is_global { + res_generation_remove(res); + } self.shadowed_by_va.remove(&(old.va, res)); + self.undisplace(res, &old); if self.shadowed.is_empty() { self.max_shadowed_size = 0; } let st = (old.states.len() == 1).then(|| old.states[0]); return (true, 0, Vec::new(), st); } - let Some(old) = self.by_res.remove(&res) else { return (false, 0, Vec::new(), None) }; - self.unlink_src(res, old.src, old.tex.size() as usize); + let Some(old) = self.remove_active(res) else { return (false, 0, Vec::new(), None) }; + if self.is_global { + res_generation_remove(res); + } + self.unlink_src(res, old.src, old.tex.size() as usize, !old.gpu_written); let st = (old.states.len() == 1).then(|| old.states[0]); self.by_va.remove(&(old.va, res)); let mut pending_delta = if old.pending { -1 } else { 0 }; @@ -416,7 +634,8 @@ impl Table { continue; } self.shadowed_by_va.remove(&(sva, sres)); - if let Some(mut e) = self.shadowed.remove(&sres) { + if let Some(mut e) = self.remove_shadowed(sres) { + self.undisplace(sres, &e); // (the one that lay over it may have been uploaded over the same video memory) texture_upload::forget(&e.known); if e.unmapped { @@ -431,11 +650,11 @@ impl Table { } self.by_va.insert((sva, sres), send); let (src, size) = (e.src, e.tex.size() as usize); - self.link_src(sres, src, size); + self.link_src(sres, src, size, !e.gpu_written); if e.pending { self.pending_res.insert(sres); } - self.by_res.insert(sres, e); + self.insert_active(sres, e); } } if self.shadowed.is_empty() { @@ -477,12 +696,15 @@ unsafe fn clone_resources(ptrs: &[usize]) -> Vec { } /// PC texture → its place in the title's memory -static TEXTURES: Mutex = Mutex::new(Table::new()); +static TEXTURES: Mutex
= Mutex::new(Table::new_global()); // The dirty-page scan consumes write-watch state for every submission thread. // Keep the scan, pending-list update and GPU uploads together. static REFRESH: Mutex<()> = Mutex::new(()); static TEXTURES_GEN: AtomicU64 = AtomicU64::new(0); static TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static HAS_SHADOWED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// a texture of `Table::displaced` waits for its first upload (`Displaced::whole`) +static HAS_DISPLACED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// cached `watch_ranges` keyed by `watch_key` static WATCH_CACHE: Mutex>)>> = Mutex::new(None); @@ -511,9 +733,43 @@ unsafe fn committed_allocation_bytes(device: *mut c_void, resource: *mut c_void, if bytes == u64::MAX { 0 } else { bytes } } -fn update_lengths(t: &Table) { +/// Leaf lock mirroring `Table::shadowed` keys so `uncover_drawn` (called on every draw/dispatch) +/// can reject non-shadowed textures with a shared read lock instead of contending on `TEXTURES`. +static SHADOWED_IDS: RwLock>> = RwLock::new(None); +/// Leaf lock mirroring `res -> generation` for `by_res ∪ shadowed` so per-barrier +/// `capture_transitions` and per-copy/clear `capture_gpu_write` read generations with a shared +/// read lock instead of blocking behind `TEXTURES` during submit texture selection. +static RES_GENERATIONS: RwLock>> = RwLock::new(None); + +#[inline] +fn res_generation_set(res: usize, generation: u64) { + let mut g = RES_GENERATIONS.write().unwrap_or_else(|e| e.into_inner()); + g.get_or_insert_with(HashMap::new).insert(res, generation); +} + +#[inline] +fn res_generation_remove(res: usize) { + let mut g = RES_GENERATIONS.write().unwrap_or_else(|e| e.into_inner()); + if let Some(m) = g.as_mut() { + m.remove(&res); + } +} + +fn update_lengths(t: &mut Table) { TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); - CPU_TEXTURES_LEN.store(t.by_res.values().filter(|e| e.cpu_backed).count(), Ordering::Relaxed); + CPU_TEXTURES_LEN.store(t.cpu_backed_count, Ordering::Relaxed); + HAS_SHADOWED.store(!t.shadowed.is_empty(), Ordering::Relaxed); + if !t.shadowed_delta.is_empty() { + let mut g = SHADOWED_IDS.write().unwrap_or_else(|e| e.into_inner()); + let set = g.get_or_insert_with(HashSet::new); + for (res, inserted) in t.shadowed_delta.drain(..) { + if inserted { + set.insert(res); + } else { + set.remove(&res); + } + } + } } /// Whether a non-depth render target / UAV texture is small enough to be a CPU-filled glyph or UI @@ -573,7 +829,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, } let in_gpu_view = crate::hle::kernelx::mirrors::source(va).is_some(); let placed = super::vram::is_placed_texture(res as usize); - let e = Entry { + let mut e = Entry { device: device as usize, committed_bytes: committed_allocation_bytes(device, res, placed), va, @@ -594,16 +850,42 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, target: u32::from_le_bytes(desc[0x30..0x34].try_into().unwrap()) & 0x7 != 0, }; let (hot_src, hot_bytes) = (e.src, e.tex.size() as usize); + // (Some: made over a texture the GPU wrote; whether it keeps the GPU's texels) + let mut over_gpu_write = None; let to_unmap = { let mut t = TEXTURES.lock().unwrap(); + // a texture made over one the GPU wrote, at its range with its description, shares its + // video memory: it holds the GPU's texels, as the memory does on the console (`over_gpu_written`) + if let Some(call) = over_gpu_written(&t, res, &e) { + let keep = gpu_write_inherit(); + if keep { + (e.gpu_written, e.written_call, e.pending) = (true, call, false); + } + over_gpu_write = Some(keep); + } let (delta, unmap_ptrs) = t.insert(res as usize, e); adjust_pending(delta); - update_lengths(&t); + update_lengths(&mut t); clone_resources(&unmap_ptrs) }; for r in &to_unmap { super::vram::unmap_superseded(r); } + if let Some(keep) = over_gpu_write { + let n = STAYED[2].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + let what = if keep { "keeps the GPU's texels instead of reading the memory (XCL_GPU_WRITE_INHERIT=0 reads it)" } else { "reads the memory (XCL_GPU_WRITE_INHERIT=1 keeps the GPU's texels)" }; + crate::xlog_info!("D3D12.X: a texture made at {va:#x} ({hot_bytes} bytes) over one the GPU wrote, with its description, {what} (#{n})"); + } + } + if over_gpu_write == Some(true) { + // (lazy levels: all of them get their pages, as for a GPU write) + if super::vram::level_pages() { + if let Some(r) = ID3D12Resource::from_raw_borrowed(&res) { + super::vram::map_levels(r, None); + } + } + } TEXTURES_GEN.fetch_add(1, Ordering::Release); // the data the title is about to write there is for the next submit mark_hot(hot_src, hot_bytes); @@ -684,7 +966,7 @@ pub(super) unsafe fn register_gpu_owned( let mut t = TEXTURES.lock().unwrap(); let (delta, unmap_ptrs) = t.insert(res as usize, e); adjust_pending(delta); - update_lengths(&t); + update_lengths(&mut t); clone_resources(&unmap_ptrs) }; for r in &to_unmap { @@ -694,6 +976,32 @@ pub(super) unsafe fn register_gpu_owned( Ok(()) } +/// `XCL_GPU_WRITE_INHERIT=0`: a texture made over one the GPU wrote (`over_gpu_written`) goes up +/// from the title's memory as any new texture, over the shared video memory. On (the default), +/// it starts as the GPU's: it holds the GPU's texels, as the memory does on the console, and the +/// CPU's writes there do not go up over them. If the title gives the memory to new texels while +/// the old texture still lives, those do not reach it either (count: the upload line). +fn gpu_write_inherit() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_GPU_WRITE_INHERIT").map_or(true, |v| v.trim() != "0")) +} + +/// The written call of an active texture the GPU wrote that `e`, PC texture `res`, is made over: +/// both placed on the video memory of their range (`vram`: shared tiles or slot), the same +/// range, and the same PC description (the same texels where they are). None for any other. +unsafe fn over_gpu_written(t: &Table, res: *mut c_void, e: &Entry) -> Option { + if !e.placed { + return None; + } + let end = e.va + e.tex.size() as usize; + let desc = ID3D12Resource::from_raw_borrowed(&res)?.GetDesc(); + t.active_overlaps(e.va, end).into_iter().find_map(|(ova, ores, oend)| { + let o = t.by_res.get(&ores).filter(|o| ova == e.va && oend == end && o.placed && !o.unmapped && o.gpu_written && o.tex.mips == e.tex.mips)?; + let p = ores as *mut c_void; + (ID3D12Resource::from_raw_borrowed(&p)?.GetDesc() == desc).then_some(o.written_call) + }) +} + /// Where a texture at `va` is read from: the CPU view behind a GPU view (`kernelx::mirrors`) /// when nothing is mapped at `va` itself, else `va`. A physical page mapped at `va` counts /// before its first use too, while it is still reserved memory (`kernelx::physical_page_at`). @@ -812,15 +1120,17 @@ fn recheck_gpu_view_sources() { s.extend(remapped.keys().copied()); s }); - let mut moved: Vec<(usize, usize, usize, usize, bool)> = Vec::new(); + let mut moved: Vec<(usize, usize, usize, usize, bool, bool)> = Vec::new(); + // (textures `mapping_changed` gave back to the CPU: their source is watched for them again) + let mut regained: Vec = Vec::new(); let mut again: Vec = Vec::new(); let Table { by_res, shadowed, .. } = t; let mut look = |res: usize, e: &mut Entry, active: bool| { - let (old, size) = (e.src, e.tex.size() as usize); + let (old, size, watched) = (e.src, e.tex.size() as usize, !e.gpu_written); if recheck_source(e) { changed = true; if active { - moved.push((res, old, e.src, size, e.pending)); + moved.push((res, old, e.src, size, e.pending, watched)); } } if let Some((call, parts)) = remapped.remove(&res) { @@ -828,6 +1138,9 @@ fn recheck_gpu_view_sources() { again.push(res); } } + if !watched && !e.gpu_written { + regained.push(res); + } }; match &names { Some(s) => { @@ -848,13 +1161,21 @@ fn recheck_gpu_view_sources() { } } } - for (res, old, new, size, pending) in moved { - t.unlink_src(res, old, size); - t.link_src(res, new, size); + for (res, old, new, size, pending, watched) in moved { + t.unlink_src(res, old, size, watched); + t.link_src(res, new, size, watched); if pending { t.pending_res.insert(res); } } + for res in regained { + if !t.by_res.contains_key(&res) && !t.displaced.contains_key(&res) { + continue; + } + if let Some((src, size)) = t.get_mut(res).map(|e| (e.src, e.tex.size() as usize)) { + t.watch_blocks(src, size); + } + } drop(g); if !again.is_empty() { AGAIN.lock().unwrap().extend(again); @@ -864,28 +1185,88 @@ fn recheck_gpu_view_sources() { } } +/// `XCL_GPU_WRITE_STAYS=0`: a texture the title's GPU work wrote gives way to a later page +/// mapping or source change under it, and is read again from the title's memory. On (the +/// default), it stays as the GPU left it until it is released, as over CPU writes: that memory +/// never got the GPU's texels (the copy went to the PC texture), so reading it again put stale +/// bytes over them – a retail title's GPU-written character head textures (8 to 10 levels, 12 to +/// 352 KiB, two or three written by one call) gave way to the next mapping of their page and +/// were black from then on. VIctory-Neo keeps a texture the host GPU copied into the same way +/// (`texture::host_written`). +fn gpu_write_stays() -> bool { + #[cfg(test)] + if let Some(v) = tests::STAYS.with(|s| s.get()) { + return v; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_GPU_WRITE_STAYS").map_or(true, |v| v.trim() != "0")) +} + +/// GPU writes kept over a page mapping and over a source change under them (`gpu_write_stays`), +/// and textures made over GPU-written ones (`over_gpu_written`) +static STAYED: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; + +/// `e`, written by the GPU, stays the GPU's over a change of what is under it (`k`: 0 a page +/// mapping of call `call`, 1 its source): said now and then. +fn note_stayed(e: &Entry, k: usize, call: u64) { + let n = STAYED[k].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + let what = if k == 0 { format!("the page mapping of call {call}") } else { "a change of its source".into() }; + let levels = e.tex.texels().map_or(0, |s| s.chain.levels.len()); + crate::xlog_info!("D3D12.X: the GPU's write of the title texture at {:#x} ({} bytes, {levels} levels; written by call {}) stays over {what} under it (#{n}; XCL_GPU_WRITE_STAYS=0 reads it again from memory)", e.va, e.tex.size(), e.written_call); + } +} + /// The queue's page mappings changed `parts` (from, to) of `e` by call `call`. A texture read -/// through its pages sends them again with its next upload, as known changes with no comparison -/// (a clean pool page newly mapped holds bytes the PC texture never had): true, and it goes into -/// AGAIN. A shadowed one goes up whole once it is uncovered, as on a change of its source. The -/// GPU's write of a list submitted at or after that call stays; an older one gives way. +/// through its pages compares them with what they held at its next upload (`remap_compare`; no +/// write watch fires for a clean pool page newly mapped, whose bytes the PC texture may never have +/// had), or sends them again with no comparison: true, and it goes into AGAIN. A shadowed one goes +/// up whole once it is uncovered, as on a change of its source. The +/// GPU's write of a list submitted at or after that call stays; an older one stays too +/// (`gpu_write_stays`), or gives way. fn mapping_changed(e: &mut Entry, call: u64, parts: Vec<(usize, usize)>, active: bool) -> bool { if !e.paged || e.pending || (e.gpu_written && e.written_call >= call) { return false; } - e.gpu_written = false; + if e.gpu_written && gpu_write_stays() { + note_stayed(e, 0, call); + return false; + } + let was_gpu_written = std::mem::take(&mut e.gpu_written); REREAD.fetch_add(1, Ordering::Relaxed); if !active { e.pending = true; PENDING.fetch_add(1, Ordering::Relaxed); return false; } - texture_upload::stale(&e.known, parts); + // (a render target or UAV the GPU may have written: no comparison with what the CPU's bytes + // were; nor one the GPU wrote, whose pages' hashes are not what it holds) + if remap_compare() && !e.target && !was_gpu_written { + texture_upload::recheck(&e.known, parts); + } else { + texture_upload::stale(&e.known, parts); + } true } +/// `XCL_TEXTURE_REMAP_COMPARE=0`: the pages a mapping changed under a texture go up again with no +/// comparison. On (the default), they are compared with what they held when they last went up, +/// as written pages are, and only those that differ go up. A title's streaming can map pages with +/// the bytes a texture already has (the same page again after an unmap, a page moved within its +/// pool); in a retail title's open world about 4400 textures a 1024 submits were read again for a +/// mapping changed under them, next to 7903 uploads of 2 GB in all. VIctory-Neo does the same: a +/// remapped slot is digested again and uploaded only when its bytes differ. +fn remap_compare() -> bool { + #[cfg(test)] + if let Some(v) = tests::REMAP_COMPARE.with(|s| s.get()) { + return v; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TEXTURE_REMAP_COMPARE").map_or(true, |v| v.trim() != "0")) +} + /// `e`'s source again (a texture in a GPU view): when it changed, `e` reads the new one and is -/// uploaded at the next submit. Whether it changed. +/// uploaded at the next submit (one the GPU wrote: not, `gpu_write_stays`). Whether it changed. fn recheck_source(e: &mut Entry) -> bool { if !e.cpu_backed || !e.in_gpu_view { return false; @@ -898,6 +1279,10 @@ fn recheck_source(e: &mut Entry) -> bool { note_paged(e.va); } (e.src, e.paged) = (src, paged); + if e.gpu_written && !e.pending && gpu_write_stays() { + note_stayed(e, 1, 0); + return true; + } if !e.pending { e.pending = true; PENDING.fetch_add(1, Ordering::Relaxed); @@ -917,9 +1302,9 @@ pub(super) fn capture_gpu_write(res: usize, subresource: u32) -> Option, writes: & e.gpu_written = true; GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); newly_written.push(write.res); + // (no longer watched for it: what the CPU writes over it never goes up, `coarse`) + let (src, size) = (e.src, e.tex.size() as usize); + if t.by_res.contains_key(&write.res) || t.displaced.contains_key(&write.res) { + t.unwatch_blocks(src, size); + } } } } @@ -980,6 +1370,24 @@ pub(super) fn publish_submission_effects(queue: Option, writes: & } } +/// (`format_alias`) Texture `res` is written by GPU work XCL itself recorded, with no title +/// submit to publish it through (`publish_submission_effects`): its CPU view is stale from now on +/// and is not uploaded again. `_list` is kept for the caller's form (0: none). +pub fn note_gpu_write(_list: usize, res: usize) { + let marked = TEXTURES.lock().unwrap().mark_gpu_written(res); + if marked { + GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); + STREAM_RECHECK.lock().unwrap().remove(&res); + } +} + +/// (`XCL_HEAP_COUNT=1`) What the texture upload buffers hold now, for the periodic log line. +pub fn upload_line() -> String { + let states: Vec = ON_QUEUE.lock().unwrap().values().cloned().collect(); + let in_flight: u64 = states.iter().filter_map(|q| q.lock().ok().and_then(|g| g.as_ref().map(|q| q.bytes))).sum(); + format!("texture upload buffers: {} MB idle, {} MB submitted and not taken back yet", texture_upload::idle_bytes() >> 20, in_flight >> 20) +} + static GPU_WRITTEN: AtomicU64 = AtomicU64::new(0); static NEXT_GPU_EPOCH: AtomicU64 = AtomicU64::new(0); @@ -1016,7 +1424,7 @@ pub(super) unsafe fn retire_overlapping(va: usize, len: usize) { unmap_ptrs.extend(u3); } adjust_pending(delta); - update_lengths(&t); + update_lengths(&mut t); (retired, clone_resources(&unmap_ptrs)) }; for r in &to_unmap { @@ -1035,7 +1443,7 @@ pub fn forget(res: usize) -> Option { let mut t = TEXTURES.lock().unwrap(); let (removed, delta, remap_ptrs, state) = t.remove(res); adjust_pending(delta); - update_lengths(&t); + update_lengths(&mut t); (removed, unsafe { clone_resources(&remap_ptrs) }, state) }; for r in &to_remap { @@ -1053,6 +1461,164 @@ pub fn forget(res: usize) -> Option { state } +/// Whether a draw's descriptor tables might name a shadowed texture. +pub(super) fn has_shadowed() -> bool { + HAS_SHADOWED.load(Ordering::Relaxed) +} + +/// How many of `res` are shadowed now. +pub(super) fn shadowed_among(res: &[usize]) -> usize { + let t = TEXTURES.lock().unwrap(); + res.iter().filter(|r| t.shadowed.contains_key(r)).count() +} + +/// Restore sampled shadowed textures while recording so the next submit can upload them. +pub(super) fn uncover_drawn(res: &[usize]) { + if res.is_empty() || !has_shadowed() { + return; + } + // Fast path: shared read lock on the shadowed ID mirror avoids locking the global `TEXTURES` + // mutex on the 99.9% of draws/dispatches that touch zero shadowed textures. + { + let g = SHADOWED_IDS.read().unwrap_or_else(|e| e.into_inner()); + let Some(set) = g.as_ref() else { return }; + if !res.iter().any(|r| set.contains(r)) { + return; + } + } + let until = { + let (p, b) = super::present::counters(); + p.max(b) + DISPLACED_FRAMES + }; + let (restored, remap) = { + let mut t = TEXTURES.lock().unwrap(); + let (mut restored, mut remap, mut delta) = (0, Vec::new(), 0); + for &r in res { + if let Some((d, unmapped)) = t.uncover(r, until) { + restored += 1; + delta += d; + if unmapped { + remap.push(r); + } + } + } + if restored == 0 { + return; + } + adjust_pending(delta); + update_lengths(&mut t); + if t.displaced.values().any(|d| d.whole) { + HAS_DISPLACED.store(true, Ordering::Release); + } + (restored, unsafe { clone_resources(&remap) }) + }; + unsafe { remap_uncovered(&remap) }; + TEXTURES_GEN.fetch_add(1, Ordering::Release); + static N: AtomicU64 = AtomicU64::new(0); + let before = N.fetch_add(restored, Ordering::Relaxed); + let n = before + restored; + if before == 0 || before.ilog2() != n.ilog2() { + crate::xlog_info!("D3D12.X: {n} shadowed textures sampled by draws so far were made active again ({} needed remapping in this batch)", remap.len()); + } +} + +/// Textures `uncover` made active again whose tiles were unmapped get them back. +unsafe fn remap_uncovered(remap: &[ID3D12Resource]) { + for r in remap { + super::vram::remap_if_unmapped(r); + // Lazy levels of a GPU-written texture cannot wait for a CPU upload to map them. + if super::vram::level_pages() && TEXTURES.lock().unwrap().get_mut(r.as_raw() as usize).is_some_and(|e| e.gpu_written) { + super::vram::map_levels(r, None); + } + } +} + +/// `XCL_BAKE_AT_SUBMIT` (on by default; `0`: off): the sources of a bake's draws are seen to +/// again at the submit of the list that holds them (`ready_bake_sources`), not only when the +/// draw is recorded (`bind::uncover_indexed`). +/// +/// The title places the textures a bake reads in the frame it bakes, packed 8 KiB apart over +/// each other's larger levels (only their small levels are there; GFX10 keeps them first), and +/// it goes on placing there while the frame is recorded. A placement over a source between the +/// bake's draw and its list's submit shadows the source again: the submit's refresh does not +/// upload it, and its tiles are unmapped once the work submitted before that placement is done +/// – before the bake, which then samples zeros. What it bakes is kept for the run: a head and +/// skin black at mid range (next-r9). A draw recorded on another list in between that makes an +/// overlapping texture active again takes the shared pages the same way. The active sources go +/// up whole at that submit too, as title memory has them then – the idea of Whiplash +/// (`Kalmarv/whiplash` 699f191, GPL-3.0-or-later: `early_budgets` and `bake_exact` in its +/// `Whiplash-AMD/crates/victory-gpu/src/draw.rs`), which uploads every texture a bake picks just +/// before its draw; see THIRD_PARTY.md. +pub(super) fn bake_at_submit() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var("XCL_BAKE_AT_SUBMIT").map_or(true, |v| v.trim() != "0"); + if !on { + crate::xlog_info!("D3D12.X: XCL_BAKE_AT_SUBMIT=0 - a bake's sources are made active only when its draw is recorded"); + } + on + }) +} + +/// What `Table::ready_for_bake` did. +#[derive(Debug, Default, PartialEq, Eq)] +struct BakeReady { + /// shadowed ones made active again (`Table::uncover`) + uncovered: usize, + /// active ones that go up whole at this submit + whole: usize, + /// the change of the count of pending textures (`PENDING`) + pending_delta: isize, + /// of the uncovered, those whose tiles were unmapped + remap: Vec, +} + +/// Before a submit of lists that hold a bake's draws (`XCL_BAKE_AT_SUBMIT`): `res`, the textures +/// those draws pick by index (`bind::bake_sources`), are made ready for it as the submit's +/// refresh, which comes next, finds them (`Table::ready_for_bake`): its uploads go ahead of the +/// lists on the queue. +pub(super) fn ready_bake_sources(res: &[usize]) { + if res.is_empty() || !bake_at_submit() { + return; + } + let until = { + let (p, b) = super::present::counters(); + p.max(b) + DISPLACED_FRAMES + }; + let (r, remap, nothing) = { + let mut t = TEXTURES.lock().unwrap(); + let r = t.ready_for_bake(res, until); + adjust_pending(r.pending_delta); + if r.uncovered > 0 { + update_lengths(&mut t); + if t.displaced.values().any(|d| d.whole) { + HAS_DISPLACED.store(true, Ordering::Release); + } + } + // (those read through the title's page mappings whose first page shows nothing now: the + // title had not mapped what the bake reads when its list was submitted) + use crate::hle::kernelx::mirrors; + let nothing = res.iter().filter_map(|r| t.by_res.get(r)).filter(|e| e.paged && mirrors::shows(e.va) == mirrors::Shows::Nothing).count(); + let remap = unsafe { clone_resources(&r.remap) }; + (r, remap, nothing) + }; + unsafe { remap_uncovered(&remap) }; + if r.uncovered + r.whole > 0 { + TEXTURES_GEN.fetch_add(1, Ordering::Release); + } + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if r.uncovered > 0 || nothing > 0 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: a submit of a bake's list (#{n}): its draws pick {} textures by index; {} of them shadowed since the draw was recorded, made active again ({} remapped); {} active ones go up whole again; {nothing} where the title's page mappings show nothing now (XCL_BAKE_AT_SUBMIT=0: as at the draw)", + res.len(), + r.uncovered, + remap.len(), + r.whole + ); + } +} + /// The title-memory address of a texture kept in step with it. pub fn address(res: usize) -> Option { let t = TEXTURES.lock().unwrap(); @@ -1069,6 +1635,34 @@ pub(super) struct Transition { pub(super) after: D3D12_RESOURCE_STATES, } +/// How a title texture is kept now (`XCL_TRACE_INDEXED`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub(super) struct Kept { + pub va: usize, + /// the newest texture over its memory; else shadowed: not uploaded, it shows what it held + pub active: bool, + /// shadowed again by `uncover`, its source still linked for a few frames + pub displaced: bool, + /// its first upload is still to come + pub pending: bool, + pub gpu_written: bool, + pub placed: bool, + /// its tiles were unmapped when a placement over another range superseded it + pub unmapped: bool, + /// its pages are read where the title's page mappings put them + pub paged: bool, +} + +/// How texture `res` is kept (None: not a title texture). +pub(super) fn kept(res: usize) -> Option { + let t = TEXTURES.lock().unwrap(); + let (e, active) = match t.by_res.get(&res) { + Some(e) => (e, true), + None => (t.shadowed.get(&res)?, false), + }; + Some(Kept { va: e.va, active, displaced: t.displaced.contains_key(&res), pending: e.pending, gpu_written: e.gpu_written, placed: e.placed, unmapped: e.unmapped, paged: e.paged }) +} + /// Whether any texture is kept in step (callers skip collecting transitions otherwise). pub fn any() -> bool { TEXTURES_LEN.load(Ordering::Relaxed) != 0 @@ -1079,12 +1673,15 @@ pub(super) fn capture_transitions(transitions: &[(usize, u32, D3D12_RESOURCE_STA if !any() || transitions.is_empty() { return Vec::new(); } - let t = TEXTURES.lock().unwrap(); + let g = RES_GENERATIONS.read().unwrap_or_else(|e| e.into_inner()); + let Some(map) = g.as_ref() else { + return Vec::new(); + }; transitions .iter() .filter_map(|&(res, subresource, after)| { - let e = t.by_res.get(&res).or_else(|| t.shadowed.get(&res))?; - Some(Transition { res, generation: e.generation, subresource, after }) + let &generation = map.get(&res)?; + Some(Transition { res, generation, subresource, after }) }) .collect() } @@ -1500,15 +2097,44 @@ fn hot_for() -> std::time::Duration { #[derive(Default)] struct HotBlocks { - /// block -> when a look or the walk last found a written page in it - hot: BTreeMap, - /// the ranges `known` was made for + /// block -> when a look or the walk last found a written page in it, and why it is hot + /// (`HOT_WRITTEN`, `HOT_WALKED`, `HOT_NEW`, `HOT_MARKED`: `look_stats::HOT_WHY`) + hot: BTreeMap, + /// the ranges of the last look (a block new to the ranges starts hot: `new_blocks`) ranges: Option>>, - /// the blocks of those ranges (a block new to the ranges starts hot) - known: std::collections::HashSet, +} + +/// The `HOT_BLOCK`s of `ranges` that no range of `old` meets (both sorted and apart, as `watch_ranges` +/// makes them): a range found in `old` as it is has none, so the ranges changed by a mapping are +/// gone over and not all blocks of all of them. (Before, a set of all the blocks was made again +/// at each change of the ranges: ~1,800 blocks, 3.5 GB, in a retail title's world.) +fn new_blocks(old: &[(usize, usize)], ranges: &[(usize, usize)]) -> Vec { + let met = |lo: usize, hi: usize| { + let i = old.partition_point(|&(a, n)| a + n <= lo); + old.get(i).is_some_and(|&(a, _)| a < hi) + }; + let mut out = Vec::new(); + for &(base, size) in ranges { + if old.binary_search(&(base, size)).is_ok() { + continue; + } + let mut b = base & !(HOT_BLOCK - 1); + while b < base + size { + if !met(b, b + HOT_BLOCK) { + out.push(b); + } + b += HOT_BLOCK; + } + } + out } static HOT: Mutex> = Mutex::new(None); +/// why a block is hot (`HotBlocks::hot`, in the order of `look_stats::HOT_WHY`) +const HOT_WRITTEN: u8 = 0; +const HOT_WALKED: u8 = 1; +const HOT_NEW: u8 = 2; +const HOT_MARKED: u8 = 3; /// the ranges of the last look, for the walk static WALK_RANGES: Mutex>>> = Mutex::new(None); /// a look is at its write-watch calls: the walk stays out of the way (the kernel does one such @@ -1525,22 +2151,13 @@ fn hot_runs(ranges: &Arc>, now: std::time::Instant) -> (Vec< let h = g.get_or_insert_with(HotBlocks::default); // a block new to the ranges starts hot: memory just mapped is often written and used at once if !h.ranges.as_ref().is_some_and(|r| Arc::ptr_eq(r, ranges)) { - let mut known = std::collections::HashSet::with_capacity(h.known.len()); - for &(base, size) in ranges.iter() { - let mut b = base & !(HOT_BLOCK - 1); - while b < base + size { - if !h.known.contains(&b) { - h.hot.insert(b, now); - } - known.insert(b); - b += HOT_BLOCK; - } + let old = h.ranges.replace(Arc::clone(ranges)); + for b in new_blocks(old.as_deref().map_or(&[], |v| &v[..]), ranges) { + h.hot.insert(b, (now, HOT_NEW)); } - h.known = known; - h.ranges = Some(Arc::clone(ranges)); } let keep = hot_for(); - h.hot.retain(|_, t| now.saturating_duration_since(*t) < keep); + h.hot.retain(|_, (t, _)| now.saturating_duration_since(*t) < keep); let mut runs: Vec<(usize, usize)> = Vec::new(); for (&b, _) in h.hot.iter() { let mut j = ranges.partition_point(|&(base, size)| base + size <= b); @@ -1573,13 +2190,39 @@ fn keep_hot(pages: &[usize], now: std::time::Instant) { for &p in pages { let b = p & !(HOT_BLOCK - 1); if b != last { - h.hot.insert(b, now); + h.hot.insert(b, (now, HOT_WRITTEN)); last = b; } } } } +/// `XCL_LOOK_STATS=2`: the hot blocks of a look's `runs` by whether their call found pages +/// (`found`, a count a run), and those of the calls that found nothing by why and how long +/// before `now` they were made hot (`look_stats::hot_blocks`, with `made`: the runs' making, and +/// `marking`: the found blocks made hot). +fn note_hot_blocks(runs: &[(usize, usize)], found: &[usize], now: std::time::Instant, made: std::time::Duration, marking: std::time::Duration) { + let (mut busy, mut why, mut age) = (0u64, [0u64; 4], [0u64; 4]); + if let Some(h) = HOT.lock().unwrap().as_ref() { + for (&(base, size), &n) in runs.iter().zip(found) { + let mut b = base & !(HOT_BLOCK - 1); + while b < base + size { + if let Some(&(t, w)) = h.hot.get(&b) { + if n > 0 { + busy += 1; + } else { + why[(w as usize).min(3)] += 1; + let ms = now.saturating_duration_since(t).as_millis(); + age[super::look_stats::HOT_AGES.partition_point(|&e| e <= ms)] += 1; + } + } + b += HOT_BLOCK; + } + } + } + super::look_stats::hot_blocks(made, marking, busy, why, age); +} + /// `XCL_LOOK_AHEAD=ms` (off unless given): a thread takes the written pages of the hot blocks every /// so many milliseconds while the title submits. They are dirty by XCL's account from then on /// (`AHEAD`): the next submit takes them with what its own look finds, and one whose lists were @@ -1679,13 +2322,25 @@ unsafe fn take_hot( start_walk(ranges); let now = std::time::Instant::now(); let (runs, hot_now) = hot_runs(ranges, now); + // (`XCL_LOOK_STATS=2`: the hot runs' making timed, and the pages each call found) + let deep = super::look_stats::deep(); + let made = deep.then(|| now.elapsed()); + let mut found: Vec = Vec::new(); let first = dirty.len(); LOOKING.store(true, Ordering::Release); for &(base, size) in &runs { + let before = dirty.len(); take_written(base, size, buf, dirty, page, measurement.as_deref_mut()); + if deep { + found.push(dirty.len() - before); + } } LOOKING.store(false, Ordering::Release); + let t_keep = deep.then(std::time::Instant::now); keep_hot(&dirty[first..], now); + if let (Some(made), Some(t_keep)) = (made, t_keep) { + note_hot_blocks(&runs, &found, now, made, t_keep.elapsed()); + } let n = HOT_STATS[0].fetch_add(1, Ordering::Relaxed) + 1; let r = HOT_STATS[1].fetch_add(runs.len() as u64, Ordering::Relaxed) + runs.len() as u64; let covered: usize = runs.iter().map(|r| r.1).sum(); @@ -1769,7 +2424,7 @@ unsafe fn walk() { let h = g.get_or_insert_with(HotBlocks::default); for b in found.drain(..) { if let std::collections::btree_map::Entry::Vacant(v) = h.hot.entry(b) { - v.insert(now); + v.insert((now, HOT_WALKED)); HOT_STATS[3].fetch_add(1, Ordering::Relaxed); WALK_FOUND.fetch_max(now_us(), Ordering::Release); } @@ -1792,6 +2447,14 @@ unsafe fn walk() { /// the other (each block of them stayed hot for `hot_for`, and every look walked it). static KNOWN: Mutex> = Mutex::new(Vec::new()); +/// Newly GPU-visible backing must be scanned even if a prior look consumed its CPU writes. +/// Unlike an optional storage hint, this is required for the first upload after exposure. +pub(crate) fn rescan_cpu_backing(at: usize, len: usize) { + if len != 0 { + KNOWN.lock().unwrap().push((at, len)); + } +} + /// `XCL_DS_KNOWN_WRITES=0`: what DirectStorage writes is found by the write watch, as before. fn known_writes() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -1849,7 +2512,7 @@ pub(super) fn mark_hot(at: usize, len: usize) { let now = std::time::Instant::now(); let mut b = at & !(HOT_BLOCK - 1); while b < at + len { - h.hot.insert(b, now); + h.hot.insert(b, (now, HOT_MARKED)); b += HOT_BLOCK; } } @@ -1954,6 +2617,7 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut let _one = look.then(|| ONE_LOOK.lock().unwrap_or_else(|e| e.into_inner())); // (a submit without a look of its own takes these too: they are dirty by XCL's account) take_known(&mut dirty); + crate::hle::kernelx::guards::take_uploads(&mut dirty, page as usize); { let mut found = AHEAD.lock().unwrap(); ahead = found.len(); @@ -1972,6 +2636,8 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut super::sparse::note_look(); } note_look_began(began, frame); + // (`XCL_LOOK_STATS=2`: the look's time before its calls and after them) + let t_calls = super::look_stats::deep().then(std::time::Instant::now); WATCH_BUF.with(|wcell| { let mut buf = wcell.borrow_mut(); if buf.len() < 16384 { @@ -1986,8 +2652,12 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut } } }); + let t_sort = t_calls.map(|_| std::time::Instant::now()); dirty.sort_unstable(); dirty.dedup(); + if let (Some(t_calls), Some(t_sort)) = (t_calls, t_sort) { + super::look_stats::look_parts(t_calls - watch_t0, t_sort.elapsed()); + } dirty.len() }); if look { @@ -2063,7 +2733,9 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut if outcome != super::sparse::PreparationOutcome::Ready { return outcome; } - super::vram::before_execute(q); + if !super::vram::before_execute(q) { + return super::sparse::PreparationOutcome::MappingUnmarked; + } } // a write where a page the queue's page mappings show is kept is a write to the GPU-view pages // that show it: the textures read through their pages find it by their own range (sparse had @@ -2089,7 +2761,7 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut p.max(b) }; recheck_streamed_unwatched(&ranges, recheck_frame); - if dirty_len == 0 && PENDING.load(Ordering::Relaxed) == 0 && AGAIN.lock().unwrap().is_empty() { + if dirty_len == 0 && PENDING.load(Ordering::Relaxed) == 0 && !HAS_DISPLACED.load(Ordering::Acquire) && AGAIN.lock().unwrap().is_empty() { return super::sparse::PreparationOutcome::Ready; } let target = upload_target(ID3D12CommandQueue::from_raw_borrowed(&queue)); @@ -2102,18 +2774,35 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut let mut t = TEXTURES.lock().unwrap(); let locked_at = wait_started.map(|_| std::time::Instant::now()); let (mut visited, mut dirty_tests, mut matches, mut retained) = (0usize, 0usize, 0usize, 0usize); + t.expire_displaced(recheck_frame); let mut names = t.touched_by(&dirty); names.extend(std::mem::take(&mut t.pending_res)); + names.extend(t.displaced.iter().filter(|(_, d)| d.whole).map(|(&r, _)| r)); + HAS_DISPLACED.store(false, Ordering::Release); let waiting = std::mem::take(&mut *AGAIN.lock().unwrap()); names.extend(waiting.iter().copied()); let mut later = std::collections::BTreeSet::new(); - let mut todo = Vec::new(); + let Table { by_res, shadowed, displaced, .. } = &mut *t; + let mut todo: Vec<(bool, Due)> = Vec::new(); for res in names { - let Some(e) = t.by_res.get_mut(&res) else { continue }; + // a displaced texture (shadowed, named by a draw's tables again: `displaced`) goes up + // as the active one does, whole when it was asked for whole + let active = by_res.contains_key(&res); + let (e, whole) = if active { + let Some(e) = by_res.get_mut(&res) else { continue }; + let whole = e.pending; + (e, whole) + } else if let Some(d) = displaced.get_mut(&res) { + let Some(e) = shadowed.get_mut(&res).filter(|e| !e.unmapped) else { continue }; + (e, std::mem::take(&mut d.whole)) + } else { + continue; + }; if measure_selection { visited += 1; } let mut again = texture_upload::Change::None; + let mut recheck = Vec::new(); if waiting.contains(&res) && e.cpu_backed && !e.gpu_written { let (queue, waited) = target.on(e.device); match texture_upload::take_again(&e.known, queue, waited) { @@ -2121,19 +2810,21 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut texture_upload::Again::NotYet => drop(later.insert(res)), texture_upload::Again::Nothing => {} } + recheck = texture_upload::take_recheck(&e.known, e.src); } if measure_selection && e.cpu_backed && !e.pending && !e.gpu_written { dirty_tests += 1; } + let written = e.cpu_backed && !e.gpu_written && { + let i = dirty.partition_point(|&p| p + page as usize <= e.src); + dirty.get(i).is_some_and(|&p| p < e.src + e.tex.size() as usize) + }; // (a GPU-owned texture is never uploaded: `texture_needs_upload`) let wanted = texture_needs_upload( e.cpu_backed, - e.pending || again != texture_upload::Change::None, + whole || again != texture_upload::Change::None || !recheck.is_empty(), e.gpu_written, - || { - let i = dirty.partition_point(|&p| p + page as usize <= e.src); - dirty.get(i).is_some_and(|&p| p < e.src + e.tex.size() as usize) - }, + || written, ); if !wanted { continue; @@ -2141,8 +2832,8 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut if measure_selection { matches += 1; } - let whole = e.pending; - if e.pending { + // (a displaced one stays pending: it goes up whole again if it is uncovered) + if e.pending && active { e.pending = false; PENDING.fetch_sub(1, Ordering::Relaxed); } @@ -2150,7 +2841,7 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut // (its pages resolved once, for all reads of this upload) let pages = if e.paged { page_map(e.va, e.tex.size() as usize, true) } else { None }; if let Some(r) = ID3D12Resource::from_raw_borrowed(&p) { - todo.push(Due { + todo.push((active, Due { res: r.clone(), device: e.device, src: e.src, @@ -2159,10 +2850,12 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut known: Arc::clone(&e.known), whole, again, + recheck, + written, target: e.target, pages, generation: e.generation, - }); + })); if measure_selection { retained += 1; } @@ -2174,7 +2867,9 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut let measurement = wait_started.zip(locked_at).zip(finished_at).map(|((started, locked), finished)| { (locked.duration_since(started), finished.duration_since(locked), visited, dirty_tests, matches, retained) }); - (todo, measurement) + // (displaced ones first: an active one over the same video memory goes up after them) + todo.sort_by_key(|&(active, _)| active); + (todo.into_iter().map(|(_, d)| d).collect(), measurement) }); if let (Some(sample), Some((wait, hold, visited, dirty_tests, matches, retained))) = (sample.as_deref_mut(), selection_measurement) { super::sparse::note_texture_selection(sample, wait, hold, visited, dirty_tests, matches, retained); @@ -2284,6 +2979,42 @@ impl TextureSelectionBench { static UNCHANGED: AtomicU64 = AtomicU64::new(0); +/// What an upload is for (`UPLOADS_FOR`). +#[derive(Clone, Copy)] +enum Why { + /// all of it: a new texture, a source changed, one uncovered or tried again + Whole, + /// pages the CPU wrote that differ + Written, + /// pages a mapping changed under it that differ (`remap_compare`), or sent with no comparison + Remapped, + /// parts sent again behind another queue's upload (`texture_upload::sent`) + Again, +} + +/// [textures, bytes] that went up for each `Why` since the last `upload_line_now` +static UPLOADS_FOR: [[AtomicU64; 2]; 4] = [const { [AtomicU64::new(0), AtomicU64::new(0)] }; 4]; +/// textures whose remapped pages were compared, and those of them (with no CPU-written page) +/// found holding what they held +static REMAPS_COMPARED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; +/// `upload_all` calls with something to upload +static UPLOAD_CALLS: AtomicU64 = AtomicU64::new(0); + +/// Every 1024 submits that upload: what went up, and for what. +fn upload_line_now() { + if UPLOAD_CALLS.fetch_add(1, Ordering::Relaxed) % 1024 != 1023 { + return; + } + let take = |c: &AtomicU64| c.swap(0, Ordering::Relaxed); + let [whole, written, remapped, again] = UPLOADS_FOR.each_ref().map(|w| (take(&w[0]), take(&w[1]) as f64 / (1u64 << 20) as f64)); + let held = take(&REMAPS_COMPARED[1]); + let compared = take(&REMAPS_COMPARED[0]) + held; + crate::xlog_info!( + "title texture uploads in the last 1024 submits that uploaded: {} whole ({:.1} MB: new textures, sources changed, uncovered); {} for CPU-written pages ({:.1} MB); {} for pages a mapping changed under them ({:.1} MB); {} sent again behind another queue ({:.1} MB); textures remapped: {compared} compared, {held} of them held what they held (left out); GPU writes kept so far over mappings {}, over source changes {}; textures made over GPU-written ones {}", + whole.0, whole.1, written.0, written.1, remapped.0, remapped.1, again.0, again.1, STAYED[0].load(Ordering::Relaxed), STAYED[1].load(Ordering::Relaxed), STAYED[2].load(Ordering::Relaxed) + ); +} + /// `XCL_TEXTURE_PARTS=0`: a texture that changed goes up as a whole. fn upload_parts() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -2621,6 +3352,25 @@ unsafe fn reclaim(q: &mut QueueUploads, cap: u64, wait_ms: u64) -> Vec(job: T, wait: impl FnOnce() -> Result<(), String>, release: impl FnOnce(T)) -> Result<(), String> { + let job = std::mem::ManuallyDrop::new(job); + wait()?; + release(std::mem::ManuallyDrop::into_inner(job)); + Ok(()) +} + +/// Drop tracked upload state for a released command queue so its fence and staging buffers do not +/// leak and a later queue at the same address cannot reuse a stale fence. +pub(super) fn on_queue_release(queue_key: usize) { + if queue_key == 0 { + return; + } + ON_QUEUE.lock().unwrap().remove(&queue_key); +} + /// The queue a submit's uploads go to, by device, and the one it waits for first. struct Target { /// the title's queue, when they go to it @@ -2660,7 +3410,9 @@ unsafe fn submit_on(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[tex // another thread after `refresh_once`'s wait, or its levels mapped just now by // `map_levels_with_texels`): a copy into a tile still unmapped is a copy-engine page fault // on NVIDIA (`DmaPageFaultWrite`). - super::vram::before_execute(queue); + if !super::vram::before_execute(queue) { + return Err("a texture page mapping has no Signal of the mapping queue yet".into()); + } let key = queue.as_raw() as usize; let state = queue_upload_state(key); let mut slot = state.lock().unwrap(); @@ -2679,10 +3431,7 @@ unsafe fn submit_on(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[tex if let Err(e) = super::real::native_queue_signal(queue, &q.fence, q.value + 1) { drop(slot); // the GPU may still run the list and read the buffer: they stay when it does not get there - match texture::wait(dev, queue) { - Ok(()) => drop(f), - Err(_) => std::mem::forget(f), - } + let _ = release_after_upload_wait(f, || texture::wait(dev, queue), drop); return Err(e.to_string()); } q.value += 1; @@ -2781,6 +3530,7 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option // The written pages that hold what they held at their texture's last upload are nothing to do: // the write watch is per page and a title writes next to its textures (and rewrites what it // wrote). + let any = !todo.is_empty(); let t = std::time::Instant::now(); let mut changes: std::collections::VecDeque = { let pages: Vec> = todo @@ -2794,10 +3544,11 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option // it would go up in part as it was and in part as it is; not for one read through // its pages, whose own address is not watched) let also = if mine.is_empty() || d.pages.is_some() || all_hot(d.src, size) { Vec::new() } else { written_pages(d.src, size) }; - if also.iter().all(|p| mine.binary_search(p).is_ok()) { + if d.recheck.is_empty() && also.iter().all(|p| mine.binary_search(p).is_ok()) { return mine.into(); } - let mut all = [mine, &also].concat(); + // (and the pages a mapping changed under it) + let mut all = [mine, &also, &d.recheck].concat(); all.sort_unstable(); all.dedup(); all.into() @@ -2820,6 +3571,17 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option }; let mut todo = todo.into_iter().filter_map(|d| { let change = if d.whole { texture_upload::Change::All } else { changes.pop_front()? }; + let found = change != texture_upload::Change::None; + let why = match () { + _ if d.whole => Why::Whole, + _ if d.written && found => Why::Written, + _ if !d.recheck.is_empty() && found => Why::Remapped, + _ => Why::Again, + }; + if !d.whole && !d.recheck.is_empty() { + // (the pages of one with no CPU-written ones held what they held: none of them goes up) + REMAPS_COMPARED[usize::from(!d.written && !found)].fetch_add(1, Ordering::Relaxed); + } let changed = match texture_upload::join(change, d.again.clone()) { texture_upload::Change::None => return None, texture_upload::Change::All => None, @@ -2832,6 +3594,8 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option let volume = d.tex.texels().is_some_and(|s| s.depth > 0); let parts = changed.as_ref().filter(|_| !volume); let bytes = parts.map_or(size, |p| p.iter().map(|r| (r.1.div_ceil(BLOCK) - r.0 / BLOCK) * BLOCK).sum::().min(size)); + UPLOADS_FOR[why as usize][0].fetch_add(1, Ordering::Relaxed); + UPLOADS_FOR[why as usize][1].fetch_add(bytes as u64, Ordering::Relaxed); Some((d, changed, bytes)) }).peekable(); while todo.peek().is_some() { @@ -2916,6 +3680,9 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option } } } + if any { + upload_line_now(); + } } /// textures of batches that could not be uploaded, with their registration generation, and when @@ -2953,8 +3720,7 @@ pub unsafe fn upload_and_wait(dev: &ID3D12Device, queue: &ID3D12CommandQueue, re } let item = texture_upload::Item { res: res.clone(), src: mem.as_ptr() as usize, tex, states, changed, known: None, pages: None }; let (failed, job, _) = own_work(|| texture_upload::submit(dev, queue, &[item]))?; - texture::wait(dev, queue)?; - job.into_iter().for_each(texture_upload::give_back); + release_after_upload_wait(job, || texture::wait(dev, queue), |job| job.into_iter().for_each(texture_upload::give_back))?; failed.into_iter().next().map_or(Ok(()), |(_, e)| Err(e)) } @@ -3065,7 +3831,9 @@ pub unsafe fn probe_gpu_content(res: usize) { dev.GetCopyableFootprints(&rd, 0, levels as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), Some(&mut total)); let result = own_work(|| -> Result>, String> { let queue = upload_queue(dev, device)?; - super::vram::before_execute(&queue); + if !super::vram::before_execute(&queue) { + return Err("a texture page mapping has no Signal of the mapping queue yet".into()); + } let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(|e| e.to_string())?; let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(|e| e.to_string())?; let mut rb: Option = None; @@ -3166,10 +3934,12 @@ unsafe fn upload_queue(dev: &ID3D12Device, device: usize) -> Result = const { std::cell::Cell::new(0) }; + /// `gpu_write_stays` on this thread (None: as the environment says) + pub(super) static STAYS: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// `remap_compare` on this thread (None: as the environment says) + pub(super) static REMAP_COMPARE: std::cell::Cell> = const { std::cell::Cell::new(None) }; + } + + /// `gpu_write_stays` is `on` on this thread while it lives. + struct Stays; + impl Stays { + fn set(on: bool) -> Stays { + STAYS.with(|s| s.set(Some(on))); + Stays + } + } + impl Drop for Stays { + fn drop(&mut self) { + STAYS.with(|s| s.set(None)); + } } /// One call of the queue's page-mapping method: `ranges` (kind, start, count) from GPU-view @@ -4976,7 +5775,16 @@ pub(super) mod tests { recheck_gpu_view_sources(); assert!(state().0, "the GPU's write came after the mapping"); assert_eq!(again(), (false, Again::Nothing)); - // a mapping changed by a later call takes it back + // a mapping changed by a later call leaves it the GPU's (`gpu_write_stays`) ... + let stays = STAYED[0].load(Ordering::Relaxed); + let _on = Stays::set(true); + map_pages(gpu, &[[0, 0, 1]], home, 2); + recheck_gpu_view_sources(); + assert!(state().0, "the GPU's write stays over a later mapping"); + assert_eq!(again(), (false, Again::Nothing), "nothing of it goes up again"); + assert!(STAYED[0].load(Ordering::Relaxed) > stays, "counted"); + // ... or, with that off, takes it back + let _off = Stays::set(false); map_pages(gpu, &[[2, 0, 1]], home, 2); recheck_gpu_view_sources(); assert!(!state().0, "an older GPU write gives way"); @@ -5000,6 +5808,123 @@ pub(super) mod tests { } } + /// A texture the GPU wrote keeps the GPU's texels when its source changes (here: a page is + /// named under one read through the CPU view) with `gpu_write_stays`: it reads the new source + /// from then on, and nothing goes up. With that off it goes up again, whole, from there. + #[test] + fn a_gpu_written_texture_stays_over_a_change_of_its_source() { + use crate::hle::kernelx::mirrors::PAGE; + let _guard = TEST_LOCK.lock().unwrap(); + // (no submit looks while a texture of no resource is in the table) + let _refresh = REFRESH.lock().unwrap(); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let (cpu, gpu, pages, home) = paged_views(183 * PAGE, 2); + let tex = Arc::new(xg::Texture::new(&console_desc(3, 128, 128, 1, 1, 28, 0x105)).unwrap()); + assert_eq!(tex.size() as usize, PAGE); + // keys of no resource, never dereferenced + let (on, off) = (0x7E57_0000_9000usize, 0x7E57_0000_A000usize); + for (res, at) in [(on, gpu), (off, gpu + 2 * PAGE)] { + assert_eq!(source_of(at, PAGE), (cpu + (at - gpu), false), "read through the CPU view"); + let e = Entry { device: 0, va: at, src: cpu + (at - gpu), in_gpu_view: true, paged: false, tex: Arc::clone(&tex), states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, written_call: 0, placed: false, unmapped: false, generation: 0, committed_bytes: 0, gpu_writers: Vec::new(), cpu_backed: true, known: Default::default(), target: false }; + TEXTURES.lock().unwrap().insert(res, e); + TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); + } + let state = |res: usize| TEXTURES.lock().unwrap().by_res.get(&res).map(|e| (e.src, e.paged, e.pending, e.gpu_written)).unwrap(); + recheck_gpu_view_sources(); + let stays = STAYED[1].load(Ordering::Relaxed); + { + let _on = Stays::set(true); + map_pages(gpu, &[[0, 0, 1]], home, 2); + recheck_gpu_view_sources(); + } + assert_eq!(state(on), (gpu, true, false, true), "the new source, and still the GPU's"); + assert!(STAYED[1].load(Ordering::Relaxed) > stays, "counted"); + { + let _off = Stays::set(false); + map_pages(gpu + 2 * PAGE, &[[0, 1, 1]], home, 2); + recheck_gpu_view_sources(); + } + assert_eq!(state(off), (gpu + 2 * PAGE, true, true, true), "it goes up again, whole, from the new source"); + forget(on); + forget(off); + drop_paged_views(cpu, gpu, pages); + } + } + + /// The pages a mapping changed under a texture read through its pages are compared with what + /// they held at its last upload (`remap_compare`): a page with the same bytes sends nothing, + /// other bytes and an unmapped page go up. With the comparison off, and for a render target, + /// they go up as they are. + #[test] + fn remapped_pages_are_compared_with_what_they_held() { + use crate::hle::kernelx::mirrors::PAGE; + use texture_upload::{Again, Change}; + let _guard = TEST_LOCK.lock().unwrap(); + // (no submit looks while a texture of no resource is in the table) + let _refresh = REFRESH.lock().unwrap(); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let (cpu, gpu, pages, home) = paged_views(185 * PAGE, 3); + // pool pages 0 and 1 hold the same bytes, page 2 others + std::ptr::write_bytes(home as *mut u8, 0x3C, 2 * PAGE); + std::ptr::write_bytes((home + 2 * PAGE) as *mut u8, 0x4D, PAGE); + map_pages(gpu, &[[0, 0, 1]], home, 3); + map_pages(gpu + PAGE, &[[0, 0, 1]], home, 3); + recheck_gpu_view_sources(); + let tex = Arc::new(xg::Texture::new(&console_desc(3, 128, 128, 1, 1, 28, 0x105)).unwrap()); + assert_eq!(tex.size() as usize, PAGE); + // keys of no resource, never dereferenced: a texture, a render target + let (res, rt) = (0x7E57_0000_B000usize, 0x7E57_0000_C000usize); + let known: texture_upload::Known = Default::default(); + let rt_known: texture_upload::Known = Default::default(); + for (r, at, k, target) in [(res, gpu, &known, false), (rt, gpu + PAGE, &rt_known, true)] { + texture_upload::all_sent(k, at, PAGE); + let e = Entry { device: 0, va: at, src: at, in_gpu_view: true, paged: true, tex: Arc::clone(&tex), states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, written_call: 0, placed: false, unmapped: false, generation: 0, committed_bytes: 0, gpu_writers: Vec::new(), cpu_backed: true, known: Arc::clone(k), target }; + TEXTURES.lock().unwrap().insert(r, e); + TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); + } + let all: Vec = (gpu..gpu + PAGE).step_by(0x1000).collect(); + // what an upload compares (and remembers) + let look = |dirty: &[usize]| { + let m = page_map(gpu, PAGE, false).unwrap(); + texture_upload::changed(&[texture_upload::Written { src: gpu, size: PAGE, dirty, known: &known, pages: Some(&m) }], true).0.remove(0) + }; + let whole = Change::Parts(vec![(0, PAGE)]); + assert_eq!(look(&all), whole, "nothing known of it yet: all of it differs"); + REMAP_COMPARE.with(|c| c.set(Some(true))); + let remap = |ranges: &[[u32; 3]]| { + map_pages(gpu, ranges, home, 3); + recheck_gpu_view_sources(); + assert!(AGAIN.lock().unwrap().remove(&res), "due at the next upload"); + assert_eq!(texture_upload::take_again(&known, 0, 0), Again::Nothing, "nothing sent with no comparison"); + let pages = texture_upload::take_recheck(&known, gpu); + assert_eq!(pages, all, "its pages under the mapping, to compare"); + look(&pages) + }; + assert_eq!(remap(&[[0, 1, 1]]), Change::None, "a page with the same bytes: nothing goes up"); + assert_eq!(remap(&[[0, 2, 1]]), whole, "other bytes go up"); + assert_eq!(remap(&[[2, 0, 1]]), whole, "unmapped: zeros"); + // a render target goes up as it is + map_pages(gpu + PAGE, &[[0, 1, 1]], home, 3); + recheck_gpu_view_sources(); + assert!(AGAIN.lock().unwrap().remove(&rt)); + assert_eq!(texture_upload::take_again(&rt_known, 0, 0), Again::Now(whole.clone()), "a render target: with no comparison"); + assert!(texture_upload::take_recheck(&rt_known, gpu + PAGE).is_empty()); + // and so does everything with the comparison off + REMAP_COMPARE.with(|c| c.set(Some(false))); + map_pages(gpu, &[[0, 0, 1]], home, 3); + recheck_gpu_view_sources(); + assert!(AGAIN.lock().unwrap().remove(&res)); + assert_eq!(texture_upload::take_again(&known, 0, 0), Again::Now(whole), "off: with no comparison"); + assert!(texture_upload::take_recheck(&known, gpu).is_empty()); + REMAP_COMPARE.with(|c| c.set(None)); + forget(res); + forget(rt); + drop_paged_views(cpu, gpu, pages); + } + } + /// A texture read through its pages finds its written pages through the GPU-view pages a /// write reaches: a write where a mapped page is kept, and one in the CPU view under a page /// the queue's page mappings never named; those that differ from what went up are sent. @@ -5636,6 +6561,70 @@ pub(super) mod tests { assert_eq!(watch_ranges(®ions, vec![(0x1000_0000, 0x1000_1000), (0x2008_0000, 0x2009_0000)]), vec![(0x2008_0000, 0x1_0000)]); } + /// `new_blocks` finds the blocks a set of all the old ranges' blocks did not have (what + /// `hot_runs` made before), going over the changed ranges only. + #[test] + fn new_blocks_are_those_no_old_range_meets() { + let blocks_of = |ranges: &[(usize, usize)]| -> std::collections::BTreeSet { + let mut out = std::collections::BTreeSet::new(); + for &(base, size) in ranges { + let mut b = base & !(HOT_BLOCK - 1); + while b < base + size { + out.insert(b); + b += HOT_BLOCK; + } + } + out + }; + let reference = |old: &[(usize, usize)], new: &[(usize, usize)]| -> Vec { + let known = blocks_of(old); + let mut v: Vec = Vec::new(); + for &(base, size) in new { + let mut b = base & !(HOT_BLOCK - 1); + while b < base + size { + if !known.contains(&b) { + v.push(b); + } + b += HOT_BLOCK; + } + } + v + }; + let g = 0x4000_0000usize; + let m = 1usize << 20; + let old = vec![(g, 8 * m), (g + 64 * m, 3 * m), (g + 70 * m + 0x1000, 0x1000), (g + 200 * m, 64 * m)]; + let cases: Vec> = vec![ + old.clone(), + vec![], + // one grown at its end, one shifted inside its blocks, one new, one gone + vec![(g, 13 * m), (g + 64 * m + 0x1000, 3 * m), (g + 100 * m, 5 * m), (g + 200 * m, 64 * m)], + // a range now over what two were + vec![(g, 80 * m)], + // pieces of blocks the old ranges met only in part + vec![(g + 67 * m - 0x1000, 0x2000), (g + 71 * m, 0x1000), (g + 264 * m, 0x1000)], + ]; + for new in &cases { + assert_eq!(new_blocks(&old, new), reference(&old, new), "{new:x?}"); + assert_eq!(new_blocks(&[], new), reference(&[], new)); + } + assert!(new_blocks(&old, &old).is_empty()); + assert_eq!(new_blocks(&old, &cases[2]), vec![g + 8 * m, g + 10 * m, g + 12 * m, g + 100 * m, g + 102 * m, g + 104 * m]); + // (the measured case: ~1,800 blocks in 16 ranges, one of them changed) + let big: Vec<(usize, usize)> = (0..16).map(|k| (g + k * (256 * m), 224 * m)).collect(); + let mut changed = big.clone(); + changed[7].1 += 2 * m; + let t = std::time::Instant::now(); + for _ in 0..100 { + assert_eq!(new_blocks(&big, &changed), vec![changed[7].0 + 224 * m]); + } + let ours = t.elapsed(); + let t = std::time::Instant::now(); + for _ in 0..100 { + assert_eq!(reference(&big, &changed), vec![changed[7].0 + 224 * m]); + } + println!("new blocks of 16 ranges, one changed: {:?} a time, a set of all blocks {:?}", ours / 100, t.elapsed() / 100); + } + #[test] fn watch_ranges_merge_at_the_gap_limit_and_split_past_it() { let base = 0x1000_0000usize; @@ -5646,6 +6635,10 @@ pub(super) mod tests { let past_limit = (first.1 + WATCH_GAP + 1, first.1 + WATCH_GAP + 0x1001); assert_eq!(watch_ranges(®ions, vec![past_limit, first]), vec![(base, 0x1000), (past_limit.0, 0x1000)]); + + // (#2891) ranges 6 MiB apart are two scans: the gap is not walked + let six_away = (first.1 + (6 << 20), first.1 + (6 << 20) + 0x1000); + assert_eq!(watch_ranges(&[(base, 64 << 20)], vec![first, six_away]), vec![(base, 0x1000), (six_away.0, 0x1000)]); } #[test] @@ -5819,6 +6812,65 @@ pub(super) mod tests { assert!(!table.by_res[&3].pending, "GPU-written content must not be overwritten by a retry"); } + /// A bake's source made active again at its draw (`uncover`) that the title places another + /// texture over before the list's submit is shadowed at that submit, its tiles to be + /// unmapped: the submit's refresh uploads only active and displaced textures, and the bake + /// read nothing (next-r9: a head black for the run). At the submit it is made active again + /// and goes up whole; an active source goes up whole again; one the GPU wrote does not. + #[test] + fn a_bake_source_placed_over_after_its_draw_is_made_ready_at_its_submit() { + let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 28, 0x105)).unwrap()); + assert!(tex.size() > 0x2000); + let entry = |va: usize, pending: bool, gpu_written: bool| Entry { + device: 0, + committed_bytes: 0, + va, + src: va, + in_gpu_view: false, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending, + gpu_written, + gpu_writers: Vec::new(), + cpu_backed: true, + placed: true, + unmapped: false, + generation: 0, + paged: false, + written_call: 0, + known: Default::default(), + target: false, + }; + const A: usize = 1; + const B: usize = 2; + const C: usize = 3; + const D: usize = 4; + const G: usize = 5; + let mut t = Table::new(); + // the title places A, then B 8 KiB on, over A's larger levels + t.insert(A, entry(0x10_0000, true, false)); + t.insert(B, entry(0x10_2000, true, false)); + assert!(t.shadowed[&A].unmapped); + // the bake's draw makes A active again (`bind::uncover_indexed`) + assert!(t.uncover(A, 10).is_some_and(|(_, remap)| remap)); + assert!(t.by_res.contains_key(&A) && !t.by_res[&A].unmapped); + // before the list's submit the title places C over A: the submit found A shadowed, not + // to be uploaded, its tiles to be unmapped + t.insert(C, entry(0x10_1000, true, false)); + assert!(!t.by_res.contains_key(&A) && t.shadowed[&A].unmapped && !t.displaced.contains_key(&A)); + // the bake's other sources: D active and uploaded, G written by the GPU (99: none) + t.insert(D, entry(0x20_0000, false, false)); + t.insert(G, entry(0x30_0000, false, true)); + let r = t.ready_for_bake(&[A, D, G, 99], 10); + assert_eq!(r, BakeReady { uncovered: 1, whole: 1, pending_delta: 1, remap: vec![A] }); + assert!(t.by_res[&A].pending && !t.by_res[&A].unmapped && t.pending_res.contains(&A)); + assert!(t.displaced.get(&C).is_some_and(|d| d.whole), "the texture placed over it goes up first, as at a draw"); + assert!(t.by_res[&D].pending && t.pending_res.contains(&D)); + assert!(!t.by_res[&G].pending && !t.pending_res.contains(&G)); + // a second time: nothing left to do + assert_eq!(t.ready_for_bake(&[A, D, G], 10), BakeReady::default()); + } + #[test] fn small_cpu_filled_target_accepts_wide_glyph_atlas_and_rejects_large_or_depth() { @@ -6123,6 +7175,75 @@ pub(super) mod tests { assert!(!tbl.by_res.contains_key(&10) && !tbl.by_res.contains_key(&11) && tbl.by_res.contains_key(&12)); } + /// Real GPU: one draw samples two overlapping textures, A then B. B shadows A again before + /// the submit, and A is uploaded all the same (it read its old texels before). + #[test] + fn gpu_both_overlapping_textures_a_draw_samples_go_up() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + struct Registered(usize); + impl Drop for Registered { + fn drop(&mut self) { forget(self.0); } + } + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let console = console_desc(3, 64, 64, 1, 1, DXGI_FORMAT_R8_UNORM.0 as u32, 1); + let size = xg::Texture::new(&console).unwrap().size() as usize; + let base = VirtualAlloc(std::ptr::null(), 2 * size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + let make = || { + let mut t = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut t, + ).unwrap(); + t.unwrap() + }; + let (a, b): (ID3D12Resource, ID3D12Resource) = (make(), make()); + let (ka, kb) = (a.as_raw() as usize, b.as_raw() as usize); + std::ptr::write_bytes(base as *mut u8, 0x11, 2 * size); + register(raw_device, a.as_raw(), base, &console, D3D12_RESOURCE_STATE_COMMON).unwrap(); + let _ra = Registered(ka); + refresh(queue.as_raw()); + // B lies over the second half of A and shadows it + register(raw_device, b.as_raw(), base + size / 2, &console, D3D12_RESOURCE_STATE_COMMON).unwrap(); + let _rb = Registered(kb); + refresh(queue.as_raw()); + assert!(TEXTURES.lock().unwrap().shadowed.contains_key(&ka)); + assert_eq!(read_r8(dev, &queue, &a), vec![0x11; 64 * 64]); + // the title writes the memory under both, then one draw samples A and B + std::ptr::write_bytes(base as *mut u8, 0x33, 2 * size); + uncover_drawn(&[ka, kb]); + assert!(TEXTURES.lock().unwrap().shadowed.contains_key(&ka), "B is the active one"); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &a), vec![0x33; 64 * 64], "A goes up although B shadowed it again"); + assert_eq!(read_r8(dev, &queue, &b), vec![0x33; 64 * 64]); + // the frames the draw could wait go by and A is only shadowed while the title writes + // again; then a draw samples A and B, and B (the GPU wrote it) shadows A again + TEXTURES.lock().unwrap().expire_displaced(u64::MAX); + std::ptr::write_bytes(base as *mut u8, 0x44, 2 * size); + refresh(queue.as_raw()); + note_gpu_write(0, kb); + uncover_drawn(&[ka, kb]); + assert_eq!(PENDING.load(Ordering::Relaxed), 0); + assert!(TEXTURES.lock().unwrap().displaced[&ka].whole); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &a), vec![0x44; 64 * 64], "displaced A goes up with no written page and no pending texture"); + drop((_rb, _ra)); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + /// Real GPU (#248): placed title textures share `vram::Pages` so streaming unreleased /// overlapping placements stays bounded in video memory, superseded textures never corrupt /// newer placements on shared tiles, 4 KiB-aligned neighbours never false-alias, and mip @@ -6301,6 +7422,26 @@ pub(super) mod tests { refresh(queue.as_raw()); assert_eq!(read_sub(&same_a, 0), subresources(base + 0x1000, &xg::Texture::new(&same_desc).unwrap())[0].data, "row 6: releasing newer placement reactivates older one"); drop(same_a); + // (a2) A texture made over one the GPU wrote, at its range with its description, holds + // the GPU's texels (the memory never got them; here: what went up before the write) + let gw_a = place_tex(base + 0x1000, &same_desc); + write_tiled(base + 0x1000, &same_desc, 0x4D); + refresh(queue.as_raw()); + let want_4d = subresources(base + 0x1000, &xg::Texture::new(&same_desc).unwrap()).swap_remove(0).data; + let list = 0x7E57_0000_D000usize; + // (main: XCL marks the write at once, with no submit of a list) + note_gpu_write(list, gw_a.as_raw() as usize); + write_tiled(base + 0x1000, &same_desc, 0x5E); + refresh(queue.as_raw()); + assert_eq!(read_sub(&gw_a, 0), want_4d, "the GPU's, not the memory's"); + let made = STAYED[2].load(Ordering::Relaxed); + let gw_b = place_tex(base + 0x1000, &same_desc); + refresh(queue.as_raw()); + assert!(TEXTURES.lock().unwrap().by_res.get(&(gw_b.as_raw() as usize)).is_some_and(|e| e.gpu_written && !e.pending), "the GPU's from the start"); + assert!(STAYED[2].load(Ordering::Relaxed) > made, "counted"); + assert_eq!(read_sub(&gw_b, 0), want_4d, "made over a GPU-written texture: the GPU's texels, not the memory's"); + drop(gw_b); + drop(gw_a); // (b) Partial / different-range overlap (row 5 + unmap dead tail + remap on release): let old_desc = console_desc(3, 512, 512, 1, 1, 28, 0x109); // 1 MiB @@ -6696,6 +7837,8 @@ pub(super) mod tests { known: Default::default(), whole, again: texture_upload::Change::None, + recheck: Vec::new(), + written: false, target: false, pages: None, generation, @@ -6809,6 +7952,8 @@ pub(super) mod tests { known: Default::default(), whole, again: texture_upload::Change::None, + recheck: Vec::new(), + written: false, target: false, pages: None, generation, @@ -7324,4 +8469,32 @@ pub(super) mod tests { VirtualFree(base as *mut c_void, 0, MEM_RELEASE); } } + + /// An upload job whose wait failed is neither given back nor dropped (the GPU may still read + /// it); one whose wait came back is, once. + #[test] + fn failed_upload_wait_retains_submitted_resources() { + use std::cell::Cell; + use std::rc::Rc; + + struct Probe(Rc>); + impl Drop for Probe { + fn drop(&mut self) { + self.0.set(self.0.get() + 1); + } + } + + let (drops, released) = (Rc::new(Cell::new(0)), Cell::new(0)); + let release = |p: Probe| { + released.set(released.get() + 1); + drop(p); + }; + let err = release_after_upload_wait(Probe(Rc::clone(&drops)), || Err("wait timed out".into()), release); + assert!(err.is_err()); + assert_eq!((drops.get(), released.get()), (0, 0), "failed wait must retain submitted resources without recycling"); + + let ok = release_after_upload_wait(Probe(Rc::clone(&drops)), || Ok(()), release); + assert!(ok.is_ok()); + assert_eq!((drops.get(), released.get()), (1, 1), "successful wait must drop and recycle submitted resources"); + } } diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 3311c24ede..2b4de60449 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -737,6 +737,294 @@ fn reserved_pool_enabled() -> bool { *ON.get_or_init(|| std::env::var("XCL_RESERVED_POOL").ok().as_deref() != Some("0")) } +/// Hand the title reserved textures whose VA predates the work in flight where possible: the +/// pool also takes render targets, depth and UAV textures, spares are made ahead per description +/// (`reserved_spares`), and a placement that still has to make a new one waits for its page +/// tables (`wait_new_placement`). +/// +/// This works around amdgpu, the Linux kernel driver: it runs a process's page-table updates in +/// order on one queue, and every unmap and every sparse rebind (REPLACE frees the old range) waits +/// for all command submissions of the VM first. So while a frame is in flight, a reserved texture +/// made after its submit has no page-table entries at all, not even PRT ones, until that frame is +/// done. A console title may write a descriptor of a texture it has just placed that work it +/// already submitted reads (on the console the memory is there): a GPU page fault (a retail title on +/// Wine + RADV). A texture from the pool has had its entries since before: a rebind still lands +/// late, but the work in flight reads the NULL (PRT) tile meanwhile, not an invalid page. +/// +/// Windows drivers do not order page-table updates behind running work like that, and the extra +/// CreateReservedResource calls and waits cost time on the title's thread, so it is on by default +/// only under Wine on an AMD adapter (`live_decide`). `XCL_LIVE_RESERVED=1` / `0` forces it on or +/// off anywhere; `XCL_RESERVED_POOL=0` turns it off with the pool. +fn live_reserved_for(dev: &ID3D12Device) -> bool { + let forced = std::env::var("XCL_LIVE_RESERVED").ok(); + reserved_pool_enabled() && live_decide(forced.as_deref(), crate::util::under_wine(), || unsafe { pick_vendor(vulkan_vendor(dev), || adapter_vendor(dev)) }) +} + +/// The GPU's vendor: the Vulkan physical device's when known, else DXGI's. Under Proton, DXVK's +/// DXGI may report an NVIDIA GPU as AMD (for games that check), while the Vulkan device that +/// vkd3d-proton drives (and the kernel driver behind it) is the real one. +fn pick_vendor(vulkan: Option, dxgi: impl FnOnce() -> Option) -> Option { + vulkan.or_else(dxgi) +} + +/// `VkPhysicalDeviceProperties::vendorID` of the physical device vkd3d-proton made `dev` on, +/// through its `ID3D12DXVKInteropDevice` (None: not vkd3d-proton, or no Vulkan loader). +unsafe fn vulkan_vendor(dev: &ID3D12Device) -> Option { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress, LoadLibraryA}; + // ID3D12DXVKInteropDevice (vkd3d-proton's include/vkd3d_device_vkd3d_ext.idl) + const IID_INTEROP: windows::core::GUID = windows::core::GUID::from_u128(0x39da4e09_bd1c_4198_9fae_86bbe3be41fd); + let mut interop: *mut c_void = std::ptr::null_mut(); + if dev.query(&IID_INTEROP, &mut interop).is_err() || interop.is_null() { + return None; + } + let interop = windows::core::IUnknown::from_raw(interop); + let vtbl = *(interop.as_raw() as *const *const usize); + // IUnknown (3), GetDXGIAdapter, GetInstanceExtensions, GetDeviceExtensions, GetDeviceFeatures, + // then GetVulkanHandles(VkInstance *, VkPhysicalDevice *, VkDevice *) + type Handles = unsafe extern "system" fn(*mut c_void, *mut usize, *mut usize, *mut usize) -> windows::core::HRESULT; + let get_handles: Handles = std::mem::transmute(*vtbl.add(7)); + let (mut instance, mut physical, mut device) = (0usize, 0usize, 0usize); + get_handles(interop.as_raw(), &mut instance, &mut physical, &mut device).ok().ok()?; + if physical == 0 { + return None; + } + let mut vulkan = GetModuleHandleA(c"vulkan-1.dll".as_ptr() as *const u8); + if vulkan.is_null() { + vulkan = LoadLibraryA(c"vulkan-1.dll".as_ptr() as *const u8); + } + if vulkan.is_null() { + return None; + } + let f = GetProcAddress(vulkan, c"vkGetPhysicalDeviceProperties".as_ptr() as *const u8)?; + type Props = unsafe extern "system" fn(usize, *mut u8); + let props: Props = std::mem::transmute(f); + // VkPhysicalDeviceProperties: apiVersion, driverVersion, vendorID, ... (824 bytes; room to spare) + let mut buf = vec![0u8; 4096]; + props(physical, buf.as_mut_ptr()); + let vendor = u32::from_le_bytes(buf[8..12].try_into().unwrap()); + (vendor != 0).then_some(vendor) +} + +/// `live_reserved_for`'s choice: `forced` from `XCL_LIVE_RESERVED`, else Wine on AMD (0x1002). +fn live_decide(forced: Option<&str>, wine: bool, vendor: impl FnOnce() -> Option) -> bool { + match forced.map(str::trim) { + Some("1") => true, + Some("0") => false, + _ => wine && vendor() == Some(0x1002), + } +} + +/// PCI vendor id of `dev`'s adapter. +unsafe fn adapter_vendor(dev: &ID3D12Device) -> Option { + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory4}; + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let adapter: IDXGIAdapter = factory.EnumAdapterByLuid(dev.GetAdapterLuid()).ok()?; + Some(adapter.GetDesc().ok()?.VendorId) +} + +/// Spare reserved textures kept made ahead per description (`XCL_RESERVED_SPARES`, default 2; +/// only where `live_reserved_for` holds): made next to a placement, they enter the pool once the +/// mapping queue passes a Signal after them, which is once their page-table entries exist. +fn reserved_spares() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_RESERVED_SPARES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2).min(16)) +} + +/// How many spares to make for a description with `have` pooled or pending ones. +fn spares_to_make(have: usize, want: usize) -> usize { + want.saturating_sub(have) +} + +/// (placements from the pool, new ones, spares made, µs spent making them, longest one call) +static LIVE_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +fn note_live_stats(pooled: bool) { + use std::sync::atomic::Ordering::Relaxed; + let n = LIVE_STATS[if pooled { 0 } else { 1 }].fetch_add(1, Relaxed) + LIVE_STATS[if pooled { 1 } else { 0 }].load(Relaxed) + 1; + if n.is_power_of_two() && n >= 64 { + crate::xlog_info!( + "D3D12.X: reserved textures placed: {} from the pool (VA live before), {} new (VA maybe not live for work in flight); {} spares made ahead, in {} ms on the placing threads (longest call {} µs)", + LIVE_STATS[0].load(Relaxed), + LIVE_STATS[1].load(Relaxed), + LIVE_STATS[2].load(Relaxed), + LIVE_STATS[3].load(Relaxed) / 1000, + LIVE_STATS[4].load(Relaxed) + ); + } +} + +/// How long a placement that had to make a new reserved texture waits on the CPU for a Signal of +/// the mapping queue sent after it (`XCL_PLACE_MAP_WAIT_MS`, default 1000; 0: no wait). That +/// Signal completes once the texture's page-table entries exist, which is once the work in flight +/// before it is done, so the title cannot write a descriptor of it that work reads. Each such +/// placement waits on its own, also after one that timed out. +fn place_map_wait_ms() -> u64 { + static MS: std::sync::OnceLock = std::sync::OnceLock::new(); + *MS.get_or_init(|| std::env::var("XCL_PLACE_MAP_WAIT_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1000)) +} + +/// (new placements that waited, of them timed out, total µs, longest µs) +static NEW_WAITS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// How a wait for a fence value ended. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum FenceWait { + /// it had completed already + Done, + /// it completed within the time, after this long + Waited(std::time::Duration), + /// it had not completed after this long + TimedOut(std::time::Duration), +} + +/// Wait up to `ms` for `fence` to reach `value`, polling it with short sleeps. No event is +/// registered with the fence: vkd3d-proton keeps a registered handle until the value is reached, +/// so an event closed after a timeout could be signalled later under a reused handle. +unsafe fn wait_fence(fence: &ID3D12Fence, value: u64, ms: u64) -> FenceWait { + if super::real::fence_completed(fence) >= value { + return FenceWait::Done; + } + let t0 = std::time::Instant::now(); + let limit = std::time::Duration::from_millis(ms); + loop { + if super::real::fence_completed(fence) >= value { + return FenceWait::Waited(t0.elapsed()); + } + let left = limit.saturating_sub(t0.elapsed()); + if left.is_zero() { + return FenceWait::TimedOut(t0.elapsed()); + } + std::thread::sleep(left.min(std::time::Duration::from_micros(500))); + } +} + +/// How `wait_new_placement` ended. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum NewWait { + /// `XCL_PLACE_MAP_WAIT_MS=0`: no wait asked for + Off, + /// a Signal was queued and waited for (or timed out) + Signalled(FenceWait), + /// no Signal could be queued, twice: nothing tells when the texture's page tables exist + Failed, +} + +/// A placement that had to make a new reserved texture: a Signal of the mapping queue after it +/// (one retry if it cannot be queued), and a wait for it up to `place_map_wait_ms`. +unsafe fn wait_new_placement(dev_key: usize) -> NewWait { + use std::sync::atomic::Ordering::Relaxed; + let ms = place_map_wait_ms(); + if ms == 0 { + return NewWait::Off; + } + let (fence, value) = { + let mut g = PAGES.lock().unwrap(); + let Some(Some(pages)) = g.get_mut(&dev_key) else { return NewWait::Failed }; + let Some(value) = pages.signal_now().or_else(|| pages.signal_now()) else { return NewWait::Failed }; + (pages.fence.clone(), value) + }; + let end = wait_fence(&fence, value, ms); + let (took, timed_out) = match end { + FenceWait::Done => return NewWait::Signalled(end), + FenceWait::Waited(d) => (d, false), + FenceWait::TimedOut(d) => (d, true), + }; + let us = took.as_micros().min(u64::MAX as u128) as u64; + let n = NEW_WAITS[0].fetch_add(1, Relaxed) + 1; + if timed_out { + NEW_WAITS[1].fetch_add(1, Relaxed); + } + NEW_WAITS[2].fetch_add(us, Relaxed); + NEW_WAITS[3].fetch_max(us, Relaxed); + if n.is_power_of_two() || timed_out { + crate::xlog_info!( + "D3D12.X: new reserved textures waited for their page tables: {n} ({} timed out after {ms} ms), {} ms in all, longest {} ms", + NEW_WAITS[1].load(Relaxed), + NEW_WAITS[2].load(Relaxed) / 1000, + NEW_WAITS[3].load(Relaxed) / 1000 + ); + } + NewWait::Signalled(end) +} + +/// Spares `place_on_pages` reserved; dropped before `take`, the reservation is given back. +struct SpareReservation { + dev_key: usize, + key: Option, + n: usize, +} + +impl SpareReservation { + /// The reserved count, now `make_spares`' to give back. + fn take(&mut self) -> usize { + std::mem::take(&mut self.n) + } +} + +impl Drop for SpareReservation { + fn drop(&mut self) { + if let (Some(key), true) = (self.key, self.n != 0) { + if let Some(Some(pages)) = PAGES.lock().unwrap().get_mut(&self.dev_key) { + pages.end_spare_reservation(key, self.n); + } + } + } +} + +/// Make the `n` spare reserved textures like `tiled` that `place_on_pages` reserved under +/// `PAGES.lock()` (`Pages::spares_in_flight`), and queue them for the pool behind one Signal of +/// the mapping queue (`reserved_spares`). The reservation is given back whatever happens; spares +/// without a Signal (it failed) are released instead. +unsafe fn make_spares(dev: &ID3D12Device, this: *mut c_void, tiled: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void, key: ReservedKey, n: usize) { + if n == 0 { + return; + } + let started = std::time::Instant::now(); + let mut made: Vec<(usize, u32)> = Vec::with_capacity(n); + for _ in 0..n { + let mut p: *mut c_void = std::ptr::null_mut(); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + // (the PC creator, not the title-facing one: an idle spare is no resource of the title's, + // so nothing that tracks those - `note_reserved`, `lut3d` - may know it; it is registered + // when handed out, as a title's released one is: `place_on_pages`, then `device_x`) + let hr = super::real::pc_create_reserved_resource(this, tiled as *const _ as usize, state as usize, clear as usize, riid, &mut p); + if hr < 0 || p.is_null() { + break; + } + let Some(res) = ID3D12Resource::from_raw_borrowed(&p) else { break }; + let mut total = 0u32; + dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + made.push((p as usize, total)); + } + let unsignalled = { + let mut g = PAGES.lock().unwrap(); + match g.get_mut(&(dev.as_raw() as usize)) { + Some(Some(pages)) => { + pages.end_spare_reservation(key, n); + match (made.is_empty(), pages.signal_now()) { + (true, _) => Vec::new(), + (false, Some(mark)) => { + LIVE_STATS[2].fetch_add(made.len() as u64, std::sync::atomic::Ordering::Relaxed); + PENDING_RECYCLES.fetch_add(made.len(), std::sync::atomic::Ordering::Release); + for &(raw, total) in &made { + pages.pending_recycles.push_back(PendingRecycle { key, raw, total, mark }); + } + Vec::new() + } + (false, None) => made, + } + } + _ => made, + } + }; + for (raw, _) in unsignalled { + drop(windows::core::IUnknown::from_raw(raw as *mut c_void)); + } + let us = started.elapsed().as_micros() as u64; + LIVE_STATS[3].fetch_add(us, std::sync::atomic::Ordering::Relaxed); + LIVE_STATS[4].fetch_max(us, std::sync::atomic::Ordering::Relaxed); +} + /// Exact description and uniform D3D12 resource state of a recyclable reserved sampled texture. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] struct ReservedKey { @@ -751,11 +1039,29 @@ struct ReservedKey { sample_quality: u32, flags: i32, state: u32, + /// the optimized clear value's bytes (`D3D12_CLEAR_VALUE`), all zero without one + clear: [u8; CLEAR_VALUE_BYTES], } +const CLEAR_VALUE_BYTES: usize = std::mem::size_of::(); + impl ReservedKey { + /// `clear`: null or a `D3D12_CLEAR_VALUE`. Only its meaningful bytes count: the format, and + /// the four colour floats, or for a depth-stencil texture the depth float and the stencil + /// byte (the rest of the union is not initialised then). + unsafe fn from_desc_clear(desc: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void) -> Self { + let mut key = Self::from_desc(desc, state); + if !clear.is_null() { + // (only those bytes are read: the rest may not even be readable memory) + let used = if desc.Flags.contains(D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) { 4 + 4 + 1 } else { CLEAR_VALUE_BYTES }; + std::ptr::copy_nonoverlapping(clear as *const u8, key.clear.as_mut_ptr(), used); + } + key + } + fn from_desc(desc: &D3D12_RESOURCE_DESC, state: u32) -> Self { Self { + clear: [0; CLEAR_VALUE_BYTES], dimension: desc.Dimension.0, alignment: desc.Alignment, width: desc.Width, @@ -809,6 +1115,10 @@ impl ReservedPool { } } + fn count(&self, key: &ReservedKey) -> usize { + self.by_key.get(key).map_or(0, Vec::len) + } + fn take(&mut self, key: &ReservedKey) -> Option<(usize, u32)> { let bucket = self.by_key.get_mut(key)?; let (raw, total, _gen) = bucket.pop()?; @@ -852,6 +1162,9 @@ impl ReservedPool { } } +/// A `PendingRecycle::mark` no Signal reaches yet (`Pages::mark_pending_recycles`). +const UNMARKED: u64 = u64::MAX; + /// Owns a retired reserved texture until the tile-mapping queue passes its last update mark. struct PendingRecycle { key: ReservedKey, @@ -901,6 +1214,7 @@ pub(super) unsafe fn drain_recycled() { { let mut g = PAGES.lock().unwrap(); for pages in g.values_mut().flatten() { + pages.mark_pending_recycles(); let before = pages.pending_recycles.len(); evicted.extend(promote_pending( &mut pages.reserved_pool, @@ -910,7 +1224,14 @@ pub(super) unsafe fn drain_recycled() { PENDING_RECYCLES.fetch_sub(before - pages.pending_recycles.len(), std::sync::atomic::Ordering::Release); } } + release_evicted(evicted); +} + +/// Release reserved textures evicted from the pool (outside `PAGES.lock()`), with nothing of +/// XCL's left that names them. +unsafe fn release_evicted(evicted: Vec) { for old in evicted { + super::real::forget_reserved(old); let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(old as *mut c_void, 2)); f(old as *mut c_void); } @@ -921,7 +1242,7 @@ pub(super) fn forget_for_recycle(resource: usize, held: bool) -> Option bool { pages.unmap(res, info.total); } } + // (its unmap's Signal failed and so did one now: kept out of the pool until one is queued) + let mark = pages.mark().unwrap_or(UNMARKED); pages.pending_recycles.push_back(PendingRecycle { key: info.key, raw: resource, total: info.total, - mark: pages.value, + mark, }); PENDING_RECYCLES.fetch_add(1, std::sync::atomic::Ordering::Release); } @@ -1082,6 +1405,8 @@ unsafe fn arena_heap(dev: &ID3D12Device, va: usize, size: usize, align: usize) - const PAGE: usize = 0x1_0000; /// pages of a video-memory pool heap (64 MiB) const POOL_PAGES: u32 = 1024; +/// words of a pool heap's recycled-tile bits (`TilePool::dirty_bits`) +const DIRTY_WORDS: usize = (POOL_PAGES as usize).div_ceil(64); /// a page no target uses any more is kept this long for the next target at its address (with /// what it holds – a title may make a target again over memory it rendered to) const IDLE: std::time::Duration = std::time::Duration::from_secs(2); @@ -1199,24 +1524,32 @@ fn take_level_tiles(levels: Option<&mut Levels>) -> Vec<(Vec, Vec<(usize, .unwrap_or_default() } -/// `XCL_TEXTURE_LEVEL_PAGES=1` (off by default): a sampled 2D texture of one slice on the -/// shared pages gets the pages of a level when an upload first has texels for it. A retail game -/// places its streamed textures at full size and maps memory under their levels as it loads -/// them, the small ones first; with a page for every 64 KiB a texture covers most of the pages -/// are for levels that are not loaded. +/// Level pages (off by default, `XCL_TEXTURE_LEVEL_PAGES=1` turns them on): a sampled 2D texture +/// of one slice on the shared pages gets the pages of a level when an upload first has texels for +/// it. A retail game places its streamed textures at full size and maps memory under their levels +/// as it loads them, the small ones first; with a page for every 64 KiB a texture covers most of +/// the pages are for levels that are not loaded (its world: 32,000 textures standing for 18 GB +/// held 1.3 GB of pages – and video memory is charged to the system's commit like RAM). pub(super) fn level_pages() -> bool { + // (a test chooses with `LEVEL_PAGES_FOR_TEST`) #[cfg(test)] - if LEVEL_PAGES_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed) { - return true; + return LEVEL_PAGES_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = level_pages_on(std::env::var("XCL_TEXTURE_LEVEL_PAGES").ok().as_deref()); + if on { + crate::xlog_info!("D3D12.X: XCL_TEXTURE_LEVEL_PAGES=1 - a sampled texture's levels get their video memory pages when an upload first has texels for them"); + } + on + }) } - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| { - let on = std::env::var("XCL_TEXTURE_LEVEL_PAGES").is_ok_and(|v| v.trim() == "1"); - if on { - crate::xlog_info!("D3D12.X: XCL_TEXTURE_LEVEL_PAGES=1 - a sampled texture's levels get their video memory pages when an upload first has texels for them"); - } - on - }) +} + +/// `XCL_TEXTURE_LEVEL_PAGES` as set: on only when it is `1`. +fn level_pages_on(v: Option<&str>) -> bool { + v.is_some_and(|v| v.trim() == "1") } /// `level_pages` for a test (under `VRAM_TEST_LOCK`) @@ -1484,6 +1817,10 @@ struct TilePool { free_by_heap: Vec>, /// Whether `free_by_heap[h]` must be sorted descending before popping. dirty_sort: Vec, + /// Per-heap bitmap of recycled tiles (`1` = previously allocated & returned, holds stale VRAM + /// contents that must be zeroed before handing to a new texture under `XCL_ZERO_TARGET_PAGES`). + /// Freshly created heaps start all `0` (already zeroed by D3D12). + dirty_bits: Vec<[u64; DIRTY_WORDS]>, /// Fresh-allocation packing class for heap `h`. Shared address pages may give either class /// live owners here, so this is never proof that a heap is safe to evict. heap_evictable: Vec, @@ -1501,6 +1838,7 @@ impl TilePool { TilePool { free_by_heap: Vec::new(), dirty_sort: Vec::new(), + dirty_bits: Vec::new(), heap_evictable: Vec::new(), free_total: 0, cooling: std::collections::VecDeque::new(), @@ -1508,17 +1846,39 @@ impl TilePool { } } + #[inline] + fn mark_dirty(&mut self, h: usize, t: u32) { + let word = (t as usize) >> 6; + if let Some(w) = self.dirty_bits.get_mut(h).and_then(|bits| bits.get_mut(word)) { + *w |= 1u64 << (t & 63); + } + } + + #[inline] + fn take_dirty(&mut self, h: usize, t: u32) -> bool { + let word = (t as usize) >> 6; + if let Some(w) = self.dirty_bits.get_mut(h).and_then(|bits| bits.get_mut(word)) { + let mask = 1u64 << (t & 63); + let was = (*w & mask) != 0; + *w &= !mask; + return was; + } + false + } + fn add_heap_at(&mut self, slot: u32, pool_pages: u32, evictable: bool) { let idx = slot as usize; if idx >= self.free_by_heap.len() { self.free_by_heap.resize_with(idx + 1, Vec::new); self.dirty_sort.resize(idx + 1, false); + self.dirty_bits.resize(idx + 1, [0u64; DIRTY_WORDS]); self.live.resize(idx + 1, false); self.heap_evictable.resize(idx + 1, false); } debug_assert!(self.free_by_heap[idx].is_empty()); self.free_by_heap[idx] = (0..pool_pages).rev().collect(); self.dirty_sort[idx] = false; + self.dirty_bits[idx] = [0u64; DIRTY_WORDS]; self.live[idx] = true; self.heap_evictable[idx] = evictable; self.free_total += pool_pages as usize; @@ -1545,6 +1905,7 @@ impl TilePool { self.free_by_heap[h].clear(); self.free_by_heap[h].shrink_to_fit(); self.dirty_sort[h] = false; + self.dirty_bits[h] = [0u64; DIRTY_WORDS]; self.live[h] = false; self.heap_evictable[h] = false; self.free_total -= full; @@ -1566,12 +1927,28 @@ impl TilePool { if idx < self.free_by_heap.len() && self.live[idx] { self.free_by_heap[idx].push(t); self.dirty_sort[idx] = true; + self.mark_dirty(idx, t); self.free_total += 1; } } } + #[cfg(test)] fn return_tiles(&mut self, tiles: &[Tile]) { + for &(h, t) in tiles { + let idx = h as usize; + if idx < self.free_by_heap.len() && self.live[idx] { + self.free_by_heap[idx].push(t); + self.dirty_sort[idx] = true; + self.mark_dirty(idx, t); + self.free_total += 1; + } + } + } + + /// Tiles a failed `take_batch_recycled` took, back untouched: the recycled ones of them + /// (`dirty`) still need their zero-fill. + fn return_rollback_tiles(&mut self, tiles: &[Tile], dirty: &[Tile]) { for &(h, t) in tiles { let idx = h as usize; if idx < self.free_by_heap.len() && self.live[idx] { @@ -1580,6 +1957,9 @@ impl TilePool { self.free_total += 1; } } + for &(h, t) in dirty { + self.mark_dirty(h as usize, t); + } } /// Pick a pool heap in the requested allocation class to take up to `rem` tiles from: @@ -1623,6 +2003,7 @@ impl TilePool { /// Allocate `count` tiles in one allocation class, preferring a single heap and ascending /// contiguous offsets. `make_heap` allocates a new backing pool heap when the class has no /// free tiles. On failure, any tiles already taken are returned untouched. + #[cfg(test)] fn take_batch( &mut self, count: usize, @@ -1630,6 +2011,23 @@ impl TilePool { evictable: bool, now: std::time::Instant, pool_pages: u32, + make_heap: impl FnMut() -> Option, + ) -> Option> { + let mut ignored = Vec::new(); + self.take_batch_recycled(count, preferred, evictable, now, pool_pages, &mut ignored, make_heap) + } + + /// `take_batch`, the recycled tiles among those taken (they hold another texture's bytes) + /// added to `recycled_out` for their zero-fill (`Pages::flush_zero_tiles`). + #[allow(clippy::too_many_arguments)] + fn take_batch_recycled( + &mut self, + count: usize, + preferred: Option, + evictable: bool, + now: std::time::Instant, + pool_pages: u32, + recycled_out: &mut Vec, mut make_heap: impl FnMut() -> Option, ) -> Option> { if count == 0 { @@ -1637,13 +2035,15 @@ impl TilePool { } self.drain_cooling(now); let mut out = Vec::with_capacity(count); + let recycled_start = recycled_out.len(); while out.len() < count { let rem = count - out.len(); let h = match self.pick_heap(rem, preferred, evictable) { Some(h) => h, None => { let Some(new_h) = make_heap() else { - self.return_tiles(&out); + let rolled_dirty = recycled_out.split_off(recycled_start); + self.return_rollback_tiles(&out, &rolled_dirty); return None; }; self.add_heap_at(new_h, pool_pages, evictable); @@ -1654,10 +2054,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; @@ -1666,6 +2068,41 @@ 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`). +/// Disabled by default (`XCL_ZERO_TARGET_PAGES=1` enables). +fn zero_target_pages() -> bool { + #[cfg(test)] + return ZERO_TARGET_PAGES_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_ZERO_TARGET_PAGES").is_ok_and(|v| v.trim() == "1")) + } +} + +/// `zero_target_pages` for a test (under `VRAM_TEST_LOCK`). +#[cfg(test)] +pub(super) static ZERO_TARGET_PAGES_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + /// Allocate one 64 MiB default heap for `Pages`. unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { let desc = D3D12_HEAP_DESC { @@ -1690,6 +2127,10 @@ unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { /// are reclaimed back to local VRAM. `len()` reports the count of live heaps. struct PoolHeaps { slots: Vec>, + /// Aliased 64 MiB `BUFFER` placed at offset 0 of each pool heap for GPU zero-fills of recycled + /// tiles (0 bytes of extra VRAM; lazily created on first recycled tile in that heap). Made in + /// `own_work`: a plain PC object, its `Release` reaches none of XCL's hooks. + zero_bufs: Vec>, free_slots: Vec, live: usize, /// slots whose heap got `HIGH` for the pages of a target (`Pages::keep_pools`) @@ -1698,7 +2139,7 @@ struct PoolHeaps { impl PoolHeaps { fn new() -> Self { - Self { slots: Vec::new(), free_slots: Vec::new(), live: 0, high: HashSet::new() } + Self { slots: Vec::new(), zero_bufs: Vec::new(), free_slots: Vec::new(), live: 0, high: HashSet::new() } } fn len(&self) -> usize { @@ -1710,15 +2151,20 @@ impl PoolHeaps { if let Some(idx) = self.free_slots.pop() { debug_assert!(self.slots[idx as usize].is_none()); self.slots[idx as usize] = Some(heap); + self.zero_bufs[idx as usize] = None; idx } else { let idx = self.slots.len() as u32; self.slots.push(Some(heap)); + self.zero_bufs.push(None); idx } } + /// The heap at `idx` out of the pool. Its zero-fill alias goes with it (a zero-fill still on + /// the GPU keeps its own reference in its `ZeroSlot`), so the heap's memory can be freed. fn take_heap(&mut self, idx: u32) -> Option { + drop(self.zero_bufs.get_mut(idx as usize).and_then(Option::take)); let h = self.slots.get_mut(idx as usize)?.take()?; self.live -= 1; self.high.remove(&idx); @@ -1726,6 +2172,37 @@ impl PoolHeaps { Some(h) } + unsafe fn zero_buffer(&mut self, dev: &ID3D12Device, idx: usize) -> Option { + if let Some(b) = self.zero_bufs.get(idx)?.as_ref() { + return Some(b.clone()); + } + let heap = self.slots.get(idx)?.as_ref()?; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: POOL_PAGES as u64 * PAGE as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_NONE, + }; + let mut res: Option = None; + let ok = super::title_textures::own_work(|| { + dev.CreatePlacedResource(heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut res) + }) + .is_ok(); + if !ok { + return None; + } + let buf = res?; + let _ = buf.SetName(windows::core::w!("xcl vram zero_alias")); + self.zero_bufs[idx] = Some(buf.clone()); + Some(buf) + } + /// The live heap at `idx` (None: reclaimed or never made). fn get(&self, idx: usize) -> Option<&ID3D12Heap> { self.slots.get(idx).and_then(Option::as_ref) @@ -1739,6 +2216,64 @@ impl std::ops::Index for PoolHeaps { } } +/// Reusable 4-slot command ring + 1 MiB pre-zeroed upload buffer for asynchronous GPU zero-fills +/// of recycled VRAM pool tiles on `Pages::queue`. +const ZERO_BUF_BYTES: u64 = 1 << 20; +const ZERO_SLOTS: usize = 4; + +struct ZeroSlot { + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + // None while an executed zero-fill is waiting for a successful mapping-queue Signal. + fence_val: Option, + 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: Some(0), kept_bufs: Vec::new() }); + } + Some(ZeroRing { zero_src, slots }) + } +} + fn keep_spare_pools() -> usize { static N: std::sync::OnceLock = std::sync::OnceLock::new(); *N.get_or_init(|| { @@ -1795,6 +2330,12 @@ struct Pages { held_unmaps: Vec, /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device reservable_cache: std::collections::HashMap<(i32, u32), bool>, + /// `live_reserved_for` this device + live: bool, + /// a mapping was queued whose Signal failed: `value` does not cover it (`mark`) + unmarked: bool, + /// spares `place_on_pages` reserved and `make_spares` is making, by description + spares_in_flight: std::collections::HashMap, /// idle reserved sampled textures kept for reuse by `(desc, state)` (#1268) reserved_pool: ReservedPool, /// retired reserved textures held until the tile-mapping queue passes their unmap fence mark @@ -1804,6 +2345,12 @@ struct Pages { scratch_flags: Vec, scratch_offsets: Vec, scratch_counts: Vec, + /// recycled tiles awaiting batched GPU zero-fill on `self.queue` before next `before_execute` + pending_zero_tiles: Vec, + /// lazily initialized command ring + 1 MiB zero source for `flush_zero_tiles` + zero_ring: Option, + /// true once `ZeroRing::new` failed so we don't retry every submit + zero_ring_failed: bool, } // D3D12 objects are free-threaded @@ -1944,13 +2491,125 @@ impl Pages { unmap_fences: std::collections::HashMap::new(), held_unmaps: Vec::new(), reservable_cache: std::collections::HashMap::new(), + live: live_reserved_for(dev), + unmarked: false, + spares_in_flight: std::collections::HashMap::new(), reserved_pool: ReservedPool::new(RESERVED_POOL_MAX), pending_recycles: std::collections::VecDeque::new(), scratch_heaps: Vec::new(), scratch_flags: Vec::new(), scratch_offsets: Vec::new(), scratch_counts: Vec::new(), + pending_zero_tiles: Vec::new(), + zero_ring: None, + zero_ring_failed: false, + }) + } + + /// Asynchronously zero all queued recycled pool tiles on `self.queue` in one batched command + /// list, then emit an aliasing barrier + `self.fence` signal so any title queue waiting in + /// `before_execute` sees zeroed tiles before reading or writing newly mapped textures. + unsafe fn flush_zero_tiles(&mut self, dev: &ID3D12Device) { + if self.pending_zero_tiles.is_empty() { + return; + } + if !zero_target_pages() || self.zero_ring_failed { + self.pending_zero_tiles.clear(); + return; + } + let runs = coalesce_tile_runs(&mut self.pending_zero_tiles); + self.pending_zero_tiles.clear(); + if runs.is_empty() { + return; + } + if self.zero_ring.is_none() { + match ZeroRing::new(dev) { + Some(r) => self.zero_ring = Some(r), + None => { + crate::xlog_warn!("D3D12.X: no zero-fill ring for recycled texture pages: they keep what they held"); + self.zero_ring_failed = true; + return; + } + } + } + let mut heap_bufs: std::collections::HashMap = std::collections::HashMap::new(); + for &(h, _, _) in &runs { + if let std::collections::hash_map::Entry::Vacant(e) = heap_bufs.entry(h) { + if let Some(buf) = self.pools.zero_buffer(dev, h as usize) { + e.insert(buf); + } + } + } + if heap_bufs.is_empty() { + return; + } + // (XCL's own fence: not through the title's GetCompletedValue hook) + let done = super::real::fence_completed(&self.fence); + let ring = self.zero_ring.as_mut().unwrap(); + let slot_idx = match ring.slots.iter().position(|s| s.fence_val.is_some_and(|v| v <= done)) { + Some(i) => i, + None => { + let Some((oldest_idx, oldest_val)) = ring.slots.iter().enumerate() + .filter_map(|(i, slot)| slot.fence_val.map(|value| (i, value))) + .min_by_key(|&(_, value)| value) else { + crate::xlog_warn!("D3D12.X: zero-fill of recycled texture pages skipped: no ring slot has a fence mark"); + return; + }; + // (the mapping queue waits for nothing of the title's: its work gets done) + if let Err(e) = crate::gpu::fence::wait(&self.fence, oldest_val, dev, None, 5_000) { + crate::xlog_warn!("D3D12.X: zero-fill of recycled texture pages skipped: its ring slot is still on the GPU ({e})"); + return; + } + oldest_idx + } + }; + let zero_src = ring.zero_src.clone(); + let slot = &mut ring.slots[slot_idx]; + slot.kept_bufs.clear(); + let queue = self.queue.clone(); + let ok = super::title_textures::own_work(|| -> windows::core::Result<()> { + slot.alloc.Reset()?; + slot.list.Reset(&slot.alloc, None)?; + for &(h, start, count) in &runs { + let Some(dst) = heap_bufs.get(&h) else { continue }; + let mut offset = start as u64 * PAGE as u64; + let mut rem = count as u64 * PAGE as u64; + while rem > 0 { + let chunk = rem.min(ZERO_BUF_BYTES); + slot.list.CopyBufferRegion(dst, offset, &zero_src, 0, chunk); + offset += chunk; + rem -= chunk; + } + } + let mut barriers: Vec = Vec::with_capacity(heap_bufs.len()); + for buf in heap_bufs.values() { + slot.kept_bufs.push(buf.clone()); + barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::transmute_copy(buf), + pResourceAfter: std::mem::zeroed(), + }), + }, + }); + } + if !barriers.is_empty() { + slot.list.ResourceBarrier(&barriers); + } + slot.list.Close()?; + let cmd: ID3D12CommandList = slot.list.cast()?; + // (through the PC queue slot in the queue's turn, as `map`'s signal) + super::real::native_queue_execute(&queue, &cmd); + Ok(()) }) + .is_ok(); + if ok { + slot.fence_val = None; + self.unmarked = true; + let _ = self.signal_now(); + } } /// Pages no resource used for `IDLE` go back to the pools. @@ -2025,8 +2684,77 @@ impl Pages { D3D12_TILE_MAPPING_FLAG_NONE, ); } - self.value += 1; - let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); + // (a failed Signal leaves the mapping `unmarked`: `mark` gets it a later one) + self.unmarked = true; + let _ = self.signal_now(); + } + + /// Reserve the spares `key` lacks (pooled, pending and in-flight ones count), up to `want`. + fn reserve_spares(&mut self, key: ReservedKey, want: usize) -> usize { + let in_flight = self.spares_in_flight.get(&key).copied().unwrap_or(0); + let have = self.reserved_pool.count(&key) + self.pending_recycles.iter().filter(|p| p.key == key).count() + in_flight; + let n = spares_to_make(have, want); + if n != 0 { + self.spares_in_flight.insert(key, in_flight + n); + } + n + } + + /// Give back `n` reserved spares of `key` (`make_spares` made or failed them). + fn end_spare_reservation(&mut self, key: ReservedKey, n: usize) { + if let Some(v) = self.spares_in_flight.get_mut(&key) { + *v = v.saturating_sub(n); + if *v == 0 { + self.spares_in_flight.remove(&key); + } + } + } + + /// A Signal of `fence` with the next value now: its submission waits for every page-table + /// update the process queued before (amdgpu syncs a submit to the VM's last update), so the + /// value completes once reserved textures made before have their entries (`make_spares`). + /// `value` moves only when the Signal was queued: queues wait for `value` (`before_execute`), + /// and a value no Signal reaches would hold them forever. A mapping whose Signal failed is + /// covered by the next one that succeeds (the queue runs in order). + unsafe fn signal_now(&mut self) -> Option { + let next = self.value + 1; + #[cfg(test)] + if FAIL_SIGNALS.with(|f| f.get() > 0 && { f.set(f.get() - 1); true }) { + return None; + } + super::real::native_queue_signal(&self.queue, &self.fence, next).ok()?; + self.value = next; + self.unmarked = false; + if let Some(ring) = &mut self.zero_ring { + for slot in &mut ring.slots { + slot.fence_val.get_or_insert(next); + } + } + Some(next) + } + + /// The value that covers every mapping queued so far: `value`, or a new Signal if a mapping's + /// own Signal failed (`unmarked`). None: no Signal could be queued for it - nothing may count + /// on that mapping yet (a queue's work, a texture back to the pool). + unsafe fn mark(&mut self) -> Option { + if self.unmarked { + self.signal_now() + } else { + Some(self.value) + } + } + + /// Retired textures queued with `UNMARKED` (their unmap had no Signal) get the mark of one now, + /// if one can be queued; till then they stay out of the pool. + unsafe fn mark_pending_recycles(&mut self) { + if !self.pending_recycles.iter().any(|p| p.mark == UNMARKED) { + return; + } + if let Some(mark) = self.mark() { + for p in self.pending_recycles.iter_mut().filter(|p| p.mark == UNMARKED) { + p.mark = mark; + } + } } /// Unmap every tile of `res` (`D3D12_TILE_RANGE_FLAG_NULL`) so its unshared tiles can return @@ -2056,8 +2784,9 @@ impl Pages { Some(&total), D3D12_TILE_MAPPING_FLAG_NONE, ); - self.value += 1; - let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); + // (a failed Signal leaves the mapping `unmarked`: `mark` gets it a later one) + self.unmarked = true; + let _ = self.signal_now(); } /// Mark work submitted so far on every active queue. Retirement marks cover queues which @@ -2224,7 +2953,8 @@ impl Pages { let pools = &mut self.pools; let pool = &mut self.pool; - let fresh = pool.take_batch(missing, preferred, evictable, now, POOL_PAGES, || { + let pending_zero = &mut self.pending_zero_tiles; + let fresh = pool.take_batch_recycled(missing, preferred, evictable, now, POOL_PAGES, pending_zero, || { let heap = alloc_pool_heap(dev)?; Some(pools.push_heap(heap)) })?; @@ -2270,6 +3000,9 @@ impl Pages { tiles.push(tile); } self.map(res, sub, &tiles); + if self.pending_zero_tiles.len() >= 256 { + self.flush_zero_tiles(dev); + } Some((used, used_extra)) } } @@ -2406,20 +3139,41 @@ unsafe fn place_on_pages( } }; let dev_key = dev.as_raw() as usize; - let recycle_key = (!require_aligned && clear.is_null() && tiled.Flags.0 == 0 && reserved_pool_enabled()) - .then(|| ReservedKey::from_desc(&tiled, state)); + let live; + let recycle_key; let mut pooled = None; + let mut spares = 0usize; + let mut evicted = Vec::new(); let is_reservable = { let mut g = PAGES.lock().unwrap(); let pages = g.entry(dev_key).or_insert_with(|| Pages::new(dev)).as_mut()?; let ok = *pages.reservable_cache.entry((tiled.Format.0, tiled.SampleDesc.Count)).or_insert_with(|| reservable(dev, &tiled)); + live = pages.live; + // (`live_reserved_for`: render targets, depth and UAV textures, those with a clear value, too) + recycle_key = if live { + Some(ReservedKey::from_desc_clear(&tiled, state, clear)) + } else { + (!require_aligned && clear.is_null() && tiled.Flags.0 == 0 && reserved_pool_enabled()).then(|| ReservedKey::from_desc(&tiled, state)) + }; if ok { if let Some(key) = recycle_key { + if live && pending_recycles() { + pages.mark_pending_recycles(); + let before = pages.pending_recycles.len(); + evicted = promote_pending(&mut pages.reserved_pool, &mut pages.pending_recycles, pages.fence.GetCompletedValue()); + PENDING_RECYCLES.fetch_sub(before - pages.pending_recycles.len(), std::sync::atomic::Ordering::Release); + } pooled = pages.reserved_pool.take(&key); + if live { + spares = pages.reserve_spares(key, reserved_spares()); + } } } ok }; + release_evicted(evicted); + // (given back on every way out of here but `make_spares`) + let mut reservation = SpareReservation { dev_key, key: recycle_key, n: spares }; if !is_reservable { log("no tiled support for its format or sample count"); return None; @@ -2472,6 +3226,16 @@ unsafe fn place_on_pages( None }; let texels = (!require_aligned && super::memory_report::enabled()).then(|| TexelMeta::from_desc(desc, levels.is_none())); + // (no live one in the pool: wait until its VA has page-table entries, before the pages know + // it. A texture with lazy levels queues no mapping here, so that Signal is all that tells; + // when none can be queued the placement fails as a failed creation does: nothing is mapped + // or noted yet, and the spare reservation goes back with `reservation`.) + if cached_total.is_none() && live && wait_new_placement(dev_key) == NewWait::Failed { + crate::xlog_warn!("D3D12.X: texture at {va:#x}: no Signal of the mapping queue after its new reserved texture - not placed on pages"); + drop(windows::core::IUnknown::from_raw(raw)); + *ppv = std::ptr::null_mut(); + return None; + } let bound = { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { @@ -2506,6 +3270,10 @@ unsafe fn place_on_pages( for r in super::placements::placed(raw as usize, va, (first, first + own * PAGE), super::placements::Backing::Pages(dev_key), kind, desc) { super::late_release::hold_unmap(r); } + if let (true, Some(key)) = (live, recycle_key) { + note_live_stats(cached_total.is_some()); + make_spares(dev, this, &tiled, state, clear, key, reservation.take()); + } Some(hr) } @@ -2833,7 +3601,10 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla /// release any previously retired heaps whose GPU fences have completed, and periodically (once /// per second per device) retire completely empty 64 MiB VRAM pool heaps and idle arenas behind /// per-queue GPU fence signals across all live queues on the device. -pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { +/// +/// false: a tile mapping is queued that no Signal of the mapping queue covers (its own failed, and +/// so did one queued now): the work must not go (`PreparationOutcome::MappingUnmarked`). +pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) -> bool { let measure = before_execute_timing_active(); let mut measured = BeforeExecuteTiming { calls: measure as usize, ..Default::default() }; let gate_started = measure.then(std::time::Instant::now); @@ -2861,7 +3632,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { if measure { record_before_execute_timing(measured); } - return; + return true; }; if let Some(started) = device_started { measured.device = started.elapsed(); @@ -2878,6 +3649,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { let mut unmap_mark: Option<(ID3D12Fence, u64)> = None; let mut completed_unmaps = Vec::new(); let mut wait = None; + let mut unmarked = false; let state_started = measure.then(std::time::Instant::now); { let mut g = PAGES.lock().unwrap(); @@ -2885,11 +3657,17 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { completed_unmaps = pages.release_held_unmaps(now, |fence| { observed_completion(&unmap_completions, fence, |known, current| known.as_raw() == current.as_raw()) }); - let value = pages.value; - if reserve_page_wait(&mut pages.waited, queue_key, value) { - wait = Some((pages.fence.clone(), value)); + // (the recycled tiles of textures mapped since: zeroed before the queue's work uses them) + pages.flush_zero_tiles(&dev); + match pages.mark() { + Some(value) => { + if reserve_page_wait(&mut pages.waited, queue_key, value) { + wait = Some((pages.fence.clone(), value)); + } + } + None => unmarked = true, } - if now.duration_since(pages.last_reclaim) >= std::time::Duration::from_secs(1) { + if !unmarked && now.duration_since(pages.last_reclaim) >= std::time::Duration::from_secs(1) { pages.last_reclaim = now; do_reclaim = true; newly_reclaimed = pages.sweep_and_reclaim(now); @@ -2906,8 +3684,11 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { } let queue_wait_started = measure.then(std::time::Instant::now); if let Some((fence, value)) = wait { - let _ = super::real::native_queue_wait(queue, &fence, value); - super::list_x::note_internal_wait(queue_key, "texture page mappings", &fence, value); + // (on the CPU first, as the sparse windows' mappings: `sparse::cpu_waited_for_mappings`) + if !super::sparse::cpu_waited_for_mappings(&fence, value, &dev, "texture page mappings") { + let _ = super::real::native_queue_wait(queue, &fence, value); + super::list_x::note_internal_wait(queue_key, "texture page mappings", &fence, value); + } } if let Some(started) = queue_wait_started { measured.queue_wait = started.elapsed(); @@ -2928,6 +3709,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { if measure { record_before_execute_timing(measured); } + !unmarked } #[cfg(test)] @@ -2940,9 +3722,13 @@ pub(super) static VRAM_TEST_LOCK: Mutex<()> = Mutex::new(()); pub(super) unsafe fn note_mapping_for_test(dev: &ID3D12Device) -> Option { let mut g = PAGES.lock().unwrap(); let pages = g.entry(dev.as_raw() as usize).or_insert_with(|| Pages::new(dev)).as_mut()?; - pages.value += 1; - super::real::native_queue_signal(&pages.queue, &pages.fence, pages.value).ok()?; - Some(pages.value) + pages.signal_now() +} + +#[cfg(test)] +thread_local! { + /// `signal_now` fails this many times on this thread (tests of a failed Signal) + static FAIL_SIGNALS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The page mapping value of `dev` now: every mapping and unmapping on the device raises it. @@ -3049,20 +3835,70 @@ pub fn page_owners() -> String { ) } -pub fn page_bytes() -> (usize, usize) { +/// 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(); - g.values().flatten().fold((0, 0), |(used, pools), p| { - (used + (p.pages.len() + p.extra_pages.len()) * PAGE, pools + p.pools.len() * POOL_PAGES as usize * PAGE) - }) -} - -/// Heaps of every kind of resource in one (resource heap tier 2) – else no arenas. -fn tier2(dev: &ID3D12Device) -> bool { - let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); - 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 } + 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))) } -/// A sampled texture of the title at `va` (`desc`: the PC description, `console_bytes` its size on +/// Immediately evict all unreferenced idle pages and small-pool slots on `device` so GPU tests +/// sharing the process's singleton `ID3D12Device` do not observe stale `IDLE` expiries mid-test. +#[cfg(test)] +pub(super) fn flush_idle_for(device: usize) { + super::vram_small::flush_idle_for(device); + let mut g = PAGES.lock().unwrap(); + if let Some(Some(p)) = g.get_mut(&device) { + let now = std::time::Instant::now(); + while let Some((key, since)) = p.idle.pop_front() { + let still_idle = |pg: &Page| pg.idle_since == Some(since); + let page = match key { + PageKey::Own(a) if p.pages.get(&a).is_some_and(still_idle) => p.pages.remove(&a), + PageKey::Extra(va, i) if p.extra_pages.get(&(va, i)).is_some_and(still_idle) => p.extra_pages.remove(&(va, i)), + _ => None, + }; + if let Some(pg) = page { + p.pool.push_cooling(pg.tile, now); + } + } + } +} + +/// (bytes of pages in use by tiled textures and small-pool blocks, bytes of pool heaps and small +/// pools) – `XCL_ACTIVITY` +pub fn page_bytes() -> (usize, usize) { + let (su, sp) = super::vram_small::bytes(); + let g = PAGES.lock().unwrap(); + g.values().flatten().fold((su, sp), |(used, pools), p| { + (used + (p.pages.len() + p.extra_pages.len()) * PAGE, pools + p.pools.len() * POOL_PAGES as usize * PAGE) + }) +} + +/// Heaps of every kind of resource in one (resource heap tier 2) – else no arenas. +fn tier2(dev: &ID3D12Device) -> bool { + let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + 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). #[allow(clippy::too_many_arguments)] @@ -3083,8 +3919,17 @@ pub unsafe fn place_pages( if console_has_packed_3d_mips(desc) { return None; } + // a texture of less than 64 KiB that does not alias a live page: a block of a shared heap + // (`vram_small`), with no reserved resource and no tile mappings of its own + let aliases_live = va % PAGE == 0 && has_live_page(dev.as_raw() as usize, canonical_va(va)); + if !aliases_live { + if let Some(hr) = super::vram_small::place(dev, this, va, desc, state, clear, console_bytes, riid, ppv) { + PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + return Some(hr); + } + } // (one slice: the tiles of an array's packed levels are not asked about here) - let lazy = level_pages() && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.DepthOrArraySize == 1 && desc.SampleDesc.Count == 1 && desc.Flags == D3D12_RESOURCE_FLAG_NONE; + let lazy = should_use_lazy_levels(level_pages(), aliases_live, desc); // (as `place`: without a size every PC tile went on the title's pages from `va` on) let console_bytes = console_bytes.or_else(|| { let least = least_texture_bytes(desc); @@ -3234,6 +4079,14 @@ pub(super) fn has_unmapped_levels(resource: usize) -> bool { PAGES.lock().unwrap().values().flatten().any(|p| p.targets.get(&resource).and_then(|t| t.levels.as_ref()).is_some_and(|l| l.groups.iter().any(|g| !g.3))) } +/// For a texture with lazy levels: whether each of its levels has pages now (the levels of a +/// group have them together). None: `resource` is not such a texture. +pub(super) fn levels_with_pages(resource: usize) -> Option> { + let g = PAGES.lock().unwrap(); + let l = g.values().flatten().find_map(|p| p.targets.get(&resource).and_then(|t| t.levels.as_ref()))?; + Some((0..l.mips).map(|i| l.groups[l.group_of(i)].3).collect()) +} + /// XG and the PC driver pack volume mip tails differently. Keep these textures on the /// detile/upload path rather than mapping title pages directly onto the driver's packed tail. fn console_has_packed_3d_mips(desc: &D3D12_RESOURCE_DESC) -> bool { @@ -4463,6 +5316,186 @@ mod tests { assert_eq!(pool.free_total, P as usize - 2); } + #[test] + fn tile_pool_tracks_dirty_bits_only_for_recycled_tiles() { + let mut pool = TilePool::new(); + let now = Instant::now(); + let mut recycled = Vec::new(); + let mut next_h = 0u32; + + // Fresh heap tiles are never marked recycled (D3D12 guarantees fresh heaps are zeroed). + let first = pool + .take_batch_recycled(4, None, false, now, POOL_PAGES, &mut recycled, || { + let h = next_h; + next_h += 1; + Some(h) + }) + .unwrap(); + assert_eq!(first, vec![(0, 0), (0, 1), (0, 2), (0, 3)]); + assert!(recycled.is_empty(), "freshly allocated heap tiles must not need GPU zeroing"); + + // Returned tiles are marked dirty and reported in `recycled` when re-taken. + pool.return_tiles(&[(0, 1), (0, 2)]); + let again = pool.take_batch_recycled(3, Some(0), false, now, POOL_PAGES, &mut recycled, || None).unwrap(); + assert_eq!(again, vec![(0, 1), (0, 2), (0, 4)]); + assert_eq!(recycled, vec![(0, 1), (0, 2)], "only previously returned tiles require zeroing"); + + // Cooled tiles also mark dirty when drained back into free_by_heap. + recycled.clear(); + pool.push_cooling((0, 0), now); + let later = now + COOL + Duration::from_millis(1); + let cooled = pool.take_batch_recycled(1, Some(0), false, later, POOL_PAGES, &mut recycled, || None).unwrap(); + assert_eq!(cooled, vec![(0, 0)]); + assert_eq!(recycled, vec![(0, 0)]); + + // A take that fails gives its tiles back with the recycled ones still recycled. + recycled.clear(); + pool.push_cooling((0, 3), now); + let free = pool.free_total; + assert!(pool.take_batch_recycled(free + 2, Some(0), false, later, POOL_PAGES, &mut recycled, || None).is_none()); + assert!(recycled.is_empty(), "a failed take reports nothing to zero"); + assert_eq!(pool.free_total, free + 1); + let back = pool.take_batch_recycled(1, Some(0), false, later, POOL_PAGES, &mut recycled, || None).unwrap(); + assert_eq!(back, vec![(0, 3)]); + assert_eq!(recycled, vec![(0, 3)], "the rolled-back recycled tile still needs zeroing"); + } + + /// Level pages are off unless `XCL_TEXTURE_LEVEL_PAGES=1`, and a sampled view over a live + /// page (a render target's) maps all of its levels at once: its texels come from the GPU. + #[test] + fn level_pages_are_off_by_default_but_not_for_a_view_over_a_live_page() { + assert!(!level_pages_on(None), "unset: off"); + assert!(level_pages_on(Some("1"))); + assert!(!level_pages_on(Some(" 0 ")), "0: off"); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 512, + Height: 512, + DepthOrArraySize: 1, + MipLevels: 10, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + assert!(should_use_lazy_levels(true, false, &desc)); + assert!(!should_use_lazy_levels(true, true, &desc), "a view over a live page maps at once"); + assert!(!should_use_lazy_levels(false, false, &desc)); + let target = D3D12_RESOURCE_DESC { Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, ..desc }; + assert!(!should_use_lazy_levels(true, false, &target)); + let array = D3D12_RESOURCE_DESC { DepthOrArraySize: 6, ..desc }; + assert!(!should_use_lazy_levels(true, false, &array)); + } + + #[test] + fn coalesce_tile_runs_merges_adjacent_tiles_per_heap() { + let mut tiles = vec![(1, 5), (0, 3), (0, 2), (1, 6), (0, 3), (0, 10), (1, 4)]; + assert_eq!(coalesce_tile_runs(&mut tiles), vec![(0, 2, 2), (0, 10, 1), (1, 4, 3)]); + let mut empty = Vec::new(); + assert!(coalesce_tile_runs(&mut empty).is_empty()); + } + + /// A pool tile given back holds what its last texture had; when zero-fill is enabled + /// (`XCL_ZERO_TARGET_PAGES=1`), the next texture mapped onto it gets it zeroed on the mapping + /// queue first, so a queue that waits for the mappings reads zeros there, not the old + /// texture's bytes. + #[test] + fn a_recycled_page_is_zeroed_before_a_new_texture_uses_it() { + unsafe { + struct RestoreBool<'a>(&'a std::sync::atomic::AtomicBool, bool); + impl Drop for RestoreBool<'_> { + fn drop(&mut self) { + self.0.store(self.1, std::sync::atomic::Ordering::Relaxed); + } + } + let was_zero = ZERO_TARGET_PAGES_FOR_TEST.swap(true, std::sync::atomic::Ordering::Relaxed); + let _restore_zero = RestoreBool(&ZERO_TARGET_PAGES_FOR_TEST, was_zero); + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: PAGE as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let reserved = || { + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).expect("reserved buffer"); + r.unwrap() + }; + let committed = |kind: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| { + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r) + .expect("committed buffer"); + r.unwrap() + }; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.Close().unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + // (a copy on the title's queue after its wait for the mappings, then waited for) + let copy = |pages: &Pages, dst: &ID3D12Resource, src: &ID3D12Resource, v: u64| { + alloc.Reset().unwrap(); + list.Reset(&alloc, None).unwrap(); + list.CopyBufferRegion(dst, 0, src, 0, PAGE as u64); + list.Close().unwrap(); + queue.Wait(&pages.fence, pages.value).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + queue.Signal(&done, v).unwrap(); + crate::gpu::fence::wait(&done, v, &dev, None, 5000).expect("the copy"); + }; + + // the first texture's page gets its bytes + let first = reserved(); + let (used, extra) = pages.bind(&dev, &first, 0x2000_0000, Some(PAGE as u64), 1).expect("bind"); + assert!(pages.pending_zero_tiles.is_empty(), "a fresh heap's tile needs no zero-fill"); + let up = committed(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::write_bytes(p as *mut u8, 0xab, PAGE); + copy(&pages, &first, &up, 1); + + // given back (cooled already), and taken by the next texture + pages.unmap(&first, 1); + let past = Instant::now().checked_sub(COOL + Duration::from_millis(10)).expect("an earlier instant"); + pages.release_tiles(used, extra, past, true); + let second = reserved(); + let (used2, extra2) = pages.bind(&dev, &second, 0x2010_0000, Some(PAGE as u64), 1).expect("bind again"); + assert_eq!(pages.pending_zero_tiles, vec![(0, 0)], "the second texture got the first one's page"); + let mapped = pages.value; + FAIL_SIGNALS.with(|f| f.set(1)); + pages.flush_zero_tiles(&dev); + assert!(pages.pending_zero_tiles.is_empty()); + assert!(pages.unmarked); + assert_eq!(pages.value, mapped, "a failed zero-fill Signal cannot advance the mapping fence"); + let slot = pages.zero_ring.as_ref().unwrap().slots.iter().position(|s| s.fence_val.is_none()) + .expect("the zero-fill slot stays in flight until it has a mark"); + let mark = pages.mark().expect("a later Signal covers the zero-fill"); + assert_eq!(mark, mapped + 1); + assert_eq!(pages.zero_ring.as_ref().unwrap().slots[slot].fence_val, Some(mark)); + + let rb = committed(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + copy(&pages, &rb, &second, 2); + let mut r = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut r)).unwrap(); + let bytes = std::slice::from_raw_parts(r as *const u8, PAGE); + let left = bytes.iter().filter(|&&b| b != 0).count(); + rb.Unmap(0, None); + assert_eq!(left, 0, "{left} bytes of the first texture showed in the second"); + + pages.unmap(&second, 1); + pages.release_tiles(used2, extra2, Instant::now(), true); + crate::gpu::fence::wait(&pages.fence, pages.value, &dev, None, 5000).expect("the mapping queue"); + } + } + #[test] fn tile_pool_keeps_evictable_and_pinned_tiles_in_separate_heaps() { let t0 = Instant::now(); @@ -5570,6 +6603,644 @@ mod tests { assert_eq!(cap3.take(&k_b), Some((0x2000, 1))); } + #[test] + fn reserved_key_tells_clear_values_apart_and_spares_top_up() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let state = D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32; + let black = D3D12_CLEAR_VALUE { Format: desc.Format, Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0, 0.0, 0.0, 1.0] } }; + let white = D3D12_CLEAR_VALUE { Format: desc.Format, Anonymous: D3D12_CLEAR_VALUE_0 { Color: [1.0; 4] } }; + let (none, k_black, k_white, k_black2) = unsafe { + ( + ReservedKey::from_desc_clear(&desc, state, std::ptr::null()), + ReservedKey::from_desc_clear(&desc, state, &black as *const _ as *const c_void), + ReservedKey::from_desc_clear(&desc, state, &white as *const _ as *const c_void), + ReservedKey::from_desc_clear(&desc, state, &black as *const _ as *const c_void), + ) + }; + assert_eq!(none, ReservedKey::from_desc(&desc, state)); + assert_ne!(none, k_black); + assert_ne!(k_black, k_white); + assert_eq!(k_black, k_black2); + + let mut pool = ReservedPool::new(8); + assert_eq!(pool.count(&k_black), 0); + assert_eq!(pool.push(k_black, 0x1000, 1), None); + assert_eq!(pool.push(k_black, 0x2000, 1), None); + assert_eq!(pool.count(&k_black), 2); + assert_eq!(pool.count(&k_white), 0); + assert!(pool.take(&k_white).is_none()); + assert!(pool.take(&k_black).is_some()); + assert_eq!(pool.count(&k_black), 1); + + assert_eq!(spares_to_make(0, 2), 2); + assert_eq!(spares_to_make(1, 2), 1); + assert_eq!(spares_to_make(5, 2), 0); + assert_eq!(spares_to_make(0, 0), 0); + } + + #[test] + fn live_reserved_is_on_by_default_only_under_wine_on_amd() { + assert!(live_decide(None, true, || Some(0x1002))); + assert!(!live_decide(None, true, || Some(0x10de)), "NVIDIA under Wine"); + assert!(!live_decide(None, false, || Some(0x1002)), "AMD on Windows"); + assert!(!live_decide(None, true, || None), "no adapter"); + assert!(!live_decide(Some(""), false, || Some(0x10de))); + assert!(live_decide(Some("1"), false, || Some(0x10de)), "forced on"); + assert!(live_decide(Some(" 1 "), false, || None), "forced on"); + assert!(!live_decide(Some("0"), true, || Some(0x1002)), "forced off"); + // (forced either way: the adapter is not even asked) + assert!(live_decide(Some("1"), false, || panic!("asked"))); + // DXVK's DXGI says AMD, the Vulkan device is NVIDIA's: off + assert!(!live_decide(None, true, || pick_vendor(Some(0x10de), || Some(0x1002)))); + assert!(live_decide(None, true, || pick_vendor(Some(0x1002), || Some(0x10de)))); + // no Vulkan device known: DXGI's vendor + assert!(live_decide(None, true, || pick_vendor(None, || Some(0x1002)))); + } + + /// Under vkd3d-proton the vendor comes from the Vulkan physical device. + #[test] + fn the_vendor_comes_from_vkd3d_protons_vulkan_device() { + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + match vulkan_vendor(&dev) { + Some(v) => assert!(v != 0 && Some(v) == pick_vendor(Some(v), || None)), + None => assert!(!crate::util::under_wine(), "vkd3d-proton under Wine has a Vulkan device"), + } + } + } + + #[test] + fn a_depth_clear_key_ignores_the_union_tail() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D32_FLOAT, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let state = D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as u32; + // format DXGI_FORMAT_D32_FLOAT (40), depth 1.0, stencil 7, then garbage + let clear = |stencil: u8, tail: u8| { + let mut b = [tail; CLEAR_VALUE_BYTES]; + b[..4].copy_from_slice(&40u32.to_le_bytes()); + b[4..8].copy_from_slice(&1.0f32.to_le_bytes()); + b[8] = stencil; + b + }; + let key = |b: &[u8; CLEAR_VALUE_BYTES]| unsafe { ReservedKey::from_desc_clear(&desc, state, b.as_ptr() as *const c_void) }; + assert_eq!(key(&clear(7, 0x00)), key(&clear(7, 0xCD)), "the uninitialised tail must not split keys"); + assert_ne!(key(&clear(7, 0x00)), key(&clear(8, 0x00)), "the stencil value counts"); + let mut deeper = clear(7, 0); + deeper[4..8].copy_from_slice(&0.0f32.to_le_bytes()); + assert_ne!(key(&clear(7, 0)), key(&deeper), "the depth value counts"); + // a colour clear uses all four floats + let mut colour_desc = desc; + colour_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + let mut c1 = clear(7, 0); + let mut c2 = c1; + c2[19] = 0x3F; + c1[19] = 0x00; + unsafe { + assert_ne!( + ReservedKey::from_desc_clear(&colour_desc, state, c1.as_ptr() as *const c_void), + ReservedKey::from_desc_clear(&colour_desc, state, c2.as_ptr() as *const c_void), + "a colour clear's alpha counts" + ); + } + } + + /// The mapping queue's fence of `dev_key`. + fn queue_fence(dev_key: usize) -> ID3D12Fence { + match PAGES.lock().unwrap().get(&dev_key) { + Some(Some(p)) => p.fence.clone(), + _ => panic!("no pages"), + } + } + + /// Owns a fence for a thread that signals it later. + struct SendFence(ID3D12Fence); + unsafe impl Send for SendFence {} + + fn signal_later(fence: &ID3D12Fence, value: u64, after_ms: u64) -> std::thread::JoinHandle<()> { + let f = SendFence(fence.clone()); + std::thread::spawn(move || { + let f = f; + std::thread::sleep(std::time::Duration::from_millis(after_ms)); + unsafe { f.0.Signal(value).unwrap() }; + }) + } + + #[test] + fn wait_fence_returns_at_the_signal_or_times_out() { + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + assert_eq!(wait_fence(&fence, 0, 1000), FenceWait::Done); + let t = signal_later(&fence, 1, 40); + match wait_fence(&fence, 1, 5000) { + FenceWait::Waited(d) => assert!(d >= std::time::Duration::from_millis(30) && d < std::time::Duration::from_millis(4000), "{d:?}"), + other => panic!("{other:?}"), + } + t.join().unwrap(); + match wait_fence(&fence, 2, 30) { + FenceWait::TimedOut(d) => assert!(d >= std::time::Duration::from_millis(25), "{d:?}"), + other => panic!("{other:?}"), + } + // the timed-out wait left nothing registered: a new event is not signalled when the + // fence reaches that value afterwards + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + let event = CreateEventW(None, false, false, None).unwrap(); + fence.Signal(2).unwrap(); + let got = WaitForSingleObject(event, 50); + let _ = windows::Win32::Foundation::CloseHandle(event); + assert_eq!(got, windows::Win32::Foundation::WAIT_TIMEOUT, "an old wait signalled a new event"); + } + } + + /// A clear value is read only as far as it means something: a depth-stencil one that ends + /// right before an unreadable page. + #[test] + fn a_depth_clear_key_reads_only_its_prefix() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, VirtualProtect, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + unsafe { + let base = VirtualAlloc(std::ptr::null(), 0x2000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; + assert!(!base.is_null()); + let mut old = 0; + assert!(VirtualProtect(base.add(0x1000) as *const c_void, 0x1000, PAGE_NOACCESS, &mut old) != 0); + let at = base.add(0x1000 - 9); + at.copy_from_nonoverlapping([40u8, 0, 0, 0].as_ptr(), 4); + at.add(4).copy_from_nonoverlapping(1.0f32.to_le_bytes().as_ptr(), 4); + *at.add(8) = 7; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D32_FLOAT, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let key = ReservedKey::from_desc_clear(&desc, 0, at as *const c_void); + assert_eq!(&key.clear[..9], std::slice::from_raw_parts(at, 9)); + assert!(key.clear[9..].iter().all(|&b| b == 0)); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + + /// With 3D textures tracked for dumps (`XCL_DUMP_TARGETS`): spares are made by the PC creator, + /// so an idle one is neither a title's reserved resource nor a dumped 3D texture, and one + /// released from the pool leaves nothing the dump enumerates; a spare handed to the title by + /// a placement is tracked. + #[test] + fn spares_stay_out_of_dump_tracking_until_handed_out() { + use std::sync::atomic::Ordering::Relaxed; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let Some(uma) = crate::gpu::uma::get() else { + return crate::gpu::recomp::runner::skip_test("no UMA"); + }; + let dev_key = dev.as_raw() as usize; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + pages.live = true; + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + super::super::lut3d::FORCE_ON.store(true, Relaxed); + let console = super::super::title_textures::tests::console_desc(4, 32, 32, 32, 1, 28, 0x105); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let Some(base) = uma.alloc(4 << 20, 0x1_0000).map(|p| p as usize) else { + super::super::lut3d::FORCE_ON.store(false, Relaxed); + PAGES.lock().unwrap().remove(&dev_key); + return crate::gpu::recomp::runner::skip_test("no UMA block"); + }; + let place = |va: usize| -> Option { + let mut p = std::ptr::null_mut(); + let hr = super::super::device_x::create_placed_resource_x(dev.as_raw(), va as u64, console.as_ptr(), D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), riid, &mut p); + (hr >= 0 && !p.is_null()).then(|| ID3D12Resource::from_raw(p)) + }; + let with = |f: &mut dyn FnMut(&mut Pages)| { + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + f(p) + } + }; + let pending = || { + let mut v = Vec::new(); + with(&mut |p| v = p.pending_recycles.iter().map(|r| (r.key, r.raw)).collect()); + v + }; + + // 1. a new 3D texture: tracked; the spares made for its description are not + let Some(first) = place(base) else { + super::super::lut3d::FORCE_ON.store(false, Relaxed); + PAGES.lock().unwrap().remove(&dev_key); + return crate::gpu::recomp::runner::skip_test("no reserved 3D texture on pages here"); + }; + assert!(first.GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D); + assert!(super::super::lut3d::tracked(first.as_raw() as usize), "the title's 3D texture is tracked"); + let spares = pending(); + assert!(!spares.is_empty(), "spares were made for it"); + for &(_, raw) in &spares { + assert!(!super::super::lut3d::tracked(raw), "an idle spare is not dumped"); + assert!(!super::super::real::is_noted_reserved(raw), "nor kept as a title's reserved resource"); + } + + // 2. its spares reach the pool; one is released as an eviction releases it: the dump's + // enumeration does not know it + with(&mut |p| { + let last = p.signal_now().unwrap(); + assert!(matches!(wait_fence(&p.fence, last, 5000), FenceWait::Done | FenceWait::Waited(_))); + }); + drain_recycled(); + let key = spares[0].0; + let mut evicted = None; + with(&mut |p| evicted = p.reserved_pool.take(&key)); + let (evicted, _) = evicted.expect("a spare in the pool"); + release_evicted(vec![evicted]); + assert!(!super::super::lut3d::tracked(evicted)); + assert!(super::super::lut3d::to_dump().iter().all(|(_, r, _, _)| r.as_raw() as usize != evicted), "a released spare is not enumerated"); + + // 3. the next placement of that description takes a spare from the pool: tracked now + let left: Vec = spares.iter().map(|s| s.1).filter(|&r| r != evicted).collect(); + let second = place(base + (1 << 20)).expect("placed"); + let raw2 = second.as_raw() as usize; + assert!(left.contains(&raw2), "the placement took a spare"); + assert!(super::super::lut3d::tracked(raw2), "a spare handed to the title is tracked"); + assert!(super::super::real::is_noted_reserved(raw2), "and kept as its reserved resource"); + + super::super::lut3d::FORCE_ON.store(false, Relaxed); + drop((first, second)); + let rest: Vec = { + let mut v = Vec::new(); + with(&mut |p| { + let last = p.signal_now().unwrap(); + let _ = wait_fence(&p.fence, last, 5000); + v = p.pending_recycles.drain(..).map(|r| r.raw).collect(); + while let Some((raw, _)) = p.reserved_pool.take(&key) { + v.push(raw); + } + }); + v + }; + release_evicted(rest); + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// A cold texture with lazy levels queues no mapping, so the Signal after its new reserved + /// texture is all that says its page tables exist: when it cannot be queued a retry is, and + /// waited for; when that fails too the placement fails with nothing left behind. + #[test] + fn a_lazy_placement_without_a_readiness_signal_is_not_handed_out() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + pages.live = true; + let queue = pages.queue.clone(); + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + let with = |f: &mut dyn FnMut(&mut Pages)| { + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + f(p) + } + }; + let desc = |w: u64| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w, + Height: 512, + DepthOrArraySize: 1, + MipLevels: 10, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let place = |va: usize, d: &D3D12_RESOURCE_DESC| -> (Option, *mut c_void) { + let mut p = std::ptr::null_mut(); + let hr = place_on_pages(&dev, dev.as_raw(), va, d, 0, std::ptr::null(), Some(4 << 20), false, true, riid, &mut p); + (hr, p) + }; + let snapshot = || { + let mut t = (0, 0, 0, 0); + with(&mut |p| t = (p.value, p.targets.len(), p.pending_recycles.len(), p.spares_in_flight.len())); + t + }; + + // 1. the first Signal fails, the retry is queued behind a held mapping queue: the + // placement returns only once that retry has completed + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + open_at_the_latest(&gate); + let (v0, ..) = snapshot(); + FAIL_SIGNALS.with(|f| f.set(1)); + let opener = signal_later(&gate, 1, 80); + let t0 = std::time::Instant::now(); + let (hr, p) = place(0x7000_0000, &desc(512)); + let took = t0.elapsed(); + FAIL_SIGNALS.with(|f| f.set(0)); + opener.join().unwrap(); + assert!(hr.is_some_and(|h| h >= 0) && !p.is_null(), "placed after the retry"); + assert!(took >= std::time::Duration::from_millis(60), "it waited for the retried Signal: {took:?}"); + let mut retried = 0; + with(&mut |pg| retried = pg.value); + assert!(retried > v0, "a later Signal was queued"); + assert!(matches!(wait_fence(&queue_fence(dev_key), v0 + 1, 0), FenceWait::Done), "and completed before the title got the texture"); + assert!(has_lazy_levels(p as usize), "a lazy-level texture"); + let first = ID3D12Resource::from_raw(p); + + // 2. no Signal at all: no resource, nothing kept of it (the spares of 1. in the pool + // first, so nothing moves meanwhile) + with(&mut |pg| { + let v = pg.value; + let _ = wait_fence(&pg.fence, v, 5000); + }); + drain_recycled(); + let before = snapshot(); + let placed_before = PLACED_TEXTURES.lock().unwrap().as_ref().map_or(0, |t| t.len()); + FAIL_SIGNALS.with(|f| f.set(2)); + let (hr, p) = place(0x7100_0000, &desc(256)); + FAIL_SIGNALS.with(|f| f.set(0)); + assert!(hr.is_none() && p.is_null(), "no texture without a readiness Signal"); + assert_eq!(snapshot(), before, "no value, target, spare or reservation left behind"); + assert_eq!(PLACED_TEXTURES.lock().unwrap().as_ref().map_or(0, |t| t.len()), placed_before); + + drop(first); + let spares: Vec = { + let mut v = Vec::new(); + with(&mut |pg| { + let last = pg.signal_now().unwrap(); + let _ = wait_fence(&pg.fence, last, 5000); + v = pg.pending_recycles.drain(..).map(|r| r.raw).collect(); + v.extend(pg.reserved_pool.by_key.drain().flat_map(|(_, b)| b.into_iter().map(|e| e.0))); + pg.reserved_pool.live_gen.clear(); + pg.reserved_pool.order.clear(); + }); + v + }; + release_evicted(spares); + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// Placements of one description at once reserve their spares under the lock: together they + /// make no more than `reserved_spares`. The mapping queue is held, so no spare reaches the pool + /// (and gets topped up again) meanwhile. + #[test] + fn concurrent_placements_make_at_most_the_spares_of_one() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + use std::sync::atomic::Ordering::Relaxed; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + pages.live = true; + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + pages.queue.Wait(&gate, 1).unwrap(); + open_at_the_latest(&gate); + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + const THREADS: usize = 4; + let made0 = LIVE_STATS[2].load(Relaxed); + let barrier = std::sync::Arc::new(std::sync::Barrier::new(THREADS)); + struct SendDev(ID3D12Device); + unsafe impl Send for SendDev {} + let workers: Vec<_> = (0..THREADS) + .map(|i| { + let (d, b) = (SendDev(dev.clone()), barrier.clone()); + std::thread::spawn(move || { + let d = d; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let mut p = std::ptr::null_mut(); + b.wait(); + let hr = place_on_pages(&d.0, d.0.as_raw(), 0x5000_0000 + i * 0x10_0000, &desc, 0, std::ptr::null(), Some(256 * 256 * 4), false, false, riid, &mut p); + assert!(hr.is_some_and(|h| h >= 0) && !p.is_null()); + p as usize + }) + }) + .collect(); + // (every placement waits for its page tables behind the gate; open it once all reserved) + std::thread::sleep(std::time::Duration::from_millis(300)); + gate.Signal(1).unwrap(); + let placed: Vec = workers.into_iter().map(|w| w.join().unwrap()).collect(); + let made = LIVE_STATS[2].load(Relaxed) - made0; + assert!(made <= reserved_spares() as u64, "{made} spares made for {THREADS} placements at once"); + for raw in placed { + drop(ID3D12Resource::from_raw(raw as *mut c_void)); + } + let spares: Vec = match PAGES.lock().unwrap().get_mut(&dev_key) { + Some(Some(p)) => { + assert!(p.spares_in_flight.is_empty(), "all reservations given back"); + let last = p.signal_now().unwrap(); + let _ = wait_fence(&p.fence, last, 5000); + p.pending_recycles.drain(..).map(|r| r.raw).collect() + } + _ => Vec::new(), + }; + for raw in spares { + drop(ID3D12Resource::from_raw(raw as *mut c_void)); + } + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// `place_on_pages` with the device's `live` flag set: a new texture waits for its page tables + /// and tops its description up with spares; the next one comes from the pool without a wait; + /// with the flag off, no spares and no wait. + #[test] + fn live_placements_wait_when_new_and_take_spares_without_waiting() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + use std::sync::atomic::Ordering::Relaxed; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + pages.live = true; + let queue = pages.queue.clone(); + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + let desc = |w: u64| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let state = D3D12_RESOURCE_STATE_COMMON.0 as u32; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let place = |va: usize, d: &D3D12_RESOURCE_DESC| -> ID3D12Resource { + let mut p = std::ptr::null_mut(); + let hr = place_on_pages(&dev, dev.as_raw(), va, d, state, std::ptr::null(), Some(d.Width * 256 * 4), false, false, riid, &mut p); + assert!(hr.is_some_and(|h| h >= 0) && !p.is_null(), "placed at {va:#x}"); + ID3D12Resource::from_raw(p) + }; + let key = |d: &D3D12_RESOURCE_DESC| ReservedKey::from_desc(&D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, ..*d }, state); + let pending = |k: &ReservedKey| match PAGES.lock().unwrap().get(&dev_key) { + Some(Some(p)) => p.pending_recycles.iter().filter(|r| r.key == *k).count() + p.reserved_pool.count(k), + _ => 0, + }; + let waits = || NEW_WAITS[0].load(Relaxed); + + // 1. new: held behind a gate on the mapping queue, it waits until the gate opens + let d256 = desc(256); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + open_at_the_latest(&gate); + let opener = signal_later(&gate, 1, 60); + let (w0, t0) = (waits(), std::time::Instant::now()); + let first = place(0x4000_0000, &d256); + let took = t0.elapsed(); + opener.join().unwrap(); + assert_eq!(waits(), w0 + 1, "a new reserved texture waits for its page tables"); + assert!(took >= std::time::Duration::from_millis(40), "it waited for the gate: {took:?}"); + assert_eq!(pending(&key(&d256)), 2, "two spares made ahead"); + + // 2. the next one of that description: a spare from the pool, no wait + let (fence, value) = match PAGES.lock().unwrap().get(&dev_key) { + Some(Some(p)) => (p.fence.clone(), p.value), + _ => unreachable!(), + }; + assert!(matches!(wait_fence(&fence, value, 5000), FenceWait::Done | FenceWait::Waited(_))); + let w1 = waits(); + let second = place(0x4010_0000, &d256); + assert_eq!(waits(), w1, "a spare from the pool does not wait"); + assert_eq!(pending(&key(&d256)), 2, "and its description is topped up again"); + + // 3. gated off: no spares, no wait + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + p.live = false; + } + let d512 = desc(512); + let w2 = waits(); + let third = place(0x4020_0000, &d512); + assert_eq!(waits(), w2, "no wait when off"); + assert_eq!(pending(&key(&d512)), 0, "no spares when off"); + + drop((first, second, third)); + let _ = queue; + let spares: Vec = match PAGES.lock().unwrap().get_mut(&dev_key) { + Some(Some(p)) => { + let last = p.signal_now().unwrap(); + let _ = wait_fence(&p.fence, last, 5000); + let mut v: Vec = p.pending_recycles.drain(..).map(|r| r.raw).collect(); + for k in [key(&d256), key(&d512)] { + while let Some((raw, _)) = p.reserved_pool.take(&k) { + v.push(raw); + } + } + v + } + _ => Vec::new(), + }; + for raw in spares { + assert!(!super::super::real::is_noted_reserved(raw), "a spare is not kept as a title's reserved resource"); + drop(ID3D12Resource::from_raw(raw as *mut c_void)); + } + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// A spare made while the mapping queue is held enters the pool only once a Signal sent + /// after it completes - before that its VA may have no page table entries. + #[test] + fn a_spare_reaches_the_pool_only_after_its_signal() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let state = D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32; + let key = ReservedKey::from_desc(&desc, state); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + pages.queue.Wait(&gate, 1).unwrap(); + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_RENDER_TARGET, None, &mut r).unwrap(); + let raw = r.unwrap().into_raw() as usize; + let mark = pages.signal_now().unwrap(); + pages.pending_recycles.push_back(PendingRecycle { key, raw, total: 1, mark }); + assert!(promote_pending(&mut pages.reserved_pool, &mut pages.pending_recycles, pages.fence.GetCompletedValue()).is_empty()); + assert_eq!(pages.reserved_pool.count(&key), 0, "a spare behind the held queue is not live yet"); + gate.Signal(1).unwrap(); + let _ = pages.fence.SetEventOnCompletion(mark, windows::Win32::Foundation::HANDLE::default()); + assert!(promote_pending(&mut pages.reserved_pool, &mut pages.pending_recycles, pages.fence.GetCompletedValue()).is_empty()); + assert_eq!(pages.reserved_pool.take(&key), Some((raw, 1))); + drop(ID3D12Resource::from_raw(raw as *mut c_void)); + } + } + #[test] fn reserved_resource_recycle_unmaps_reuses_and_remaps_on_gpu() { use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_BC1_UNORM, DXGI_SAMPLE_DESC}; @@ -5644,6 +7315,7 @@ mod tests { fn reserved_resource_with_private_data_is_excluded_from_recycle() { use crate::hle::d3d12x::{late_release, real, title_textures}; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_BC1_UNORM, DXGI_SAMPLE_DESC}; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); unsafe { let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { return crate::gpu::recomp::runner::skip_test("no GPU"); @@ -5763,4 +7435,265 @@ mod tests { late_release::drain_known(true); } } + + /// A Signal that fails leaves `value` where a Signal reached it, so queues waiting for it + /// (`before_execute`) are not held forever. + #[test] + fn a_failed_signal_leaves_the_value_a_signal_reached() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let Some(pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + let reached_value = p.signal_now().expect("a Signal"); + FAIL_SIGNALS.with(|f| f.set(1)); + assert_eq!(p.signal_now(), None); + assert_eq!(p.value, reached_value, "a failed Signal does not move the value queues wait for"); + assert!(reached(&p.fence, p.value, 5000), "the value is reached"); + FAIL_SIGNALS.with(|f| f.set(0)); + } + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// A watchdog for a test fence that holds a queue: it opens it after 10 s at the latest, so a + /// test that holds a shared device's mapping queue can fail but never hang the test process. + fn open_at_the_latest(fence: &ID3D12Fence) { + struct F(ID3D12Fence); + unsafe impl Send for F {} + let f = F(fence.clone()); + std::thread::spawn(move || { + let f = f; + std::thread::sleep(std::time::Duration::from_secs(10)); + unsafe { + if f.0.GetCompletedValue() < 1 { + let _ = f.0.Signal(1); + } + } + }); + } + + /// `fence` reaches `value` within `ms` (polled). + fn reached(fence: &ID3D12Fence, value: u64, ms: u64) -> bool { + let end = std::time::Instant::now() + std::time::Duration::from_millis(ms); + loop { + if unsafe { fence.GetCompletedValue() } >= value { + return true; + } + if std::time::Instant::now() >= end { + return false; + } + std::thread::sleep(std::time::Duration::from_micros(200)); + } + } + + /// A bind and a NULL unmap whose Signals fail are covered by a later Signal before anything + /// counts on them: `before_execute` queues one and has the title's queue wait for it (or says + /// the work must not go when it cannot), and a retired texture stays out of the pool until one + /// completes. The mapping queue is held behind a test fence meanwhile. + #[test] + fn mappings_whose_signal_failed_get_a_later_mark_before_use() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let Some(pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + let (mq, mfence) = (pages.queue.clone(), pages.fence.clone()); + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + let with = |f: &mut dyn FnMut(&mut Pages)| { + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + f(p) + } + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + let res = r.unwrap(); + let mut total = 0u32; + dev.GetResourceTiling(&res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + let title: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let title_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done = |f: &ID3D12Fence, v: u64| reached(f, v, 5000); + + // mark N, completed + let mut n = 0; + with(&mut |p| n = p.signal_now().unwrap()); + assert!(done(&mfence, n)); + assert!(before_execute(&title)); + + // a bind whose Signal fails, behind a held mapping queue + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + mq.Wait(&gate, 1).unwrap(); + open_at_the_latest(&gate); + FAIL_SIGNALS.with(|f| f.set(1)); + let mut bound = None; + with(&mut |p| bound = p.bind(&dev, &res, 0x6000_0000, Some(total as u64 * PAGE as u64), total)); + let (used, extra) = bound.expect("bound"); + with(&mut |p| assert!(p.unmarked && p.value == n, "the bind has no mark of its own")); + + // the title's next work: a Signal N+1 is queued now and the work waits for it + assert!(before_execute(&title), "a later Signal could be queued"); + with(&mut |p| assert!(!p.unmarked && p.value == n + 1)); + super::super::real::native_queue_signal(&title, &title_fence, 1).unwrap(); + assert!(!reached(&title_fence, 1, 100), "the title's work waits for N+1"); + gate.Signal(1).unwrap(); + assert!(done(&title_fence, 1), "and goes once N+1 is done"); + + // no Signal at all: the work must not go + with(&mut |p| p.unmarked = true); + FAIL_SIGNALS.with(|f| f.set(1)); + assert!(!before_execute(&title), "no mark: the submit must wait for one"); + FAIL_SIGNALS.with(|f| f.set(0)); + + // a held unmap that becomes releasable inside before_execute, its NULL mapping's Signal + // failing: before_execute queues a later mark after it and the work waits for that + let held = |va: usize| -> ID3D12Resource { + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + let r = r.unwrap(); + let done_fence: ID3D12Fence = dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).unwrap(); + with(&mut |p| { + let (used, used_extra) = p.bind(&dev, &r, va, Some(total as u64 * PAGE as u64), total).expect("bound"); + let mark = p.signal_now().expect("a Signal"); + assert!(reached(&p.fence, mark, 5000)); + p.held_unmaps.push(HeldUnmap { res: r.clone(), total, used, used_extra, level_tiles: Vec::new(), marks: vec![(done_fence.clone(), 1)], immediate_cool: false }); + }); + r + }; + let held_a = held(0x6100_0000); + let mut before = 0; + with(&mut |p| before = p.value); + let gate3: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + mq.Wait(&gate3, 1).unwrap(); + open_at_the_latest(&gate3); + FAIL_SIGNALS.with(|f| f.set(1)); + assert!(before_execute(&title), "a later Signal could be queued"); + FAIL_SIGNALS.with(|f| f.set(0)); + with(&mut |p| { + assert!(p.held_unmaps.is_empty(), "the held unmap was released"); + assert!(!p.unmarked && p.value == before + 1, "and a later Signal covers its NULL mapping"); + }); + super::super::real::native_queue_signal(&title, &title_fence, 2).unwrap(); + assert!(!reached(&title_fence, 2, 100), "the title's work waits for it"); + gate3.Signal(1).unwrap(); + assert!(done(&title_fence, 2)); + // the same with no Signal at all: the work must not go + let held_b = held(0x6200_0000); + FAIL_SIGNALS.with(|f| f.set(2)); + assert!(!before_execute(&title), "no mark for the released unmap: the submit waits for one"); + FAIL_SIGNALS.with(|f| f.set(0)); + with(&mut |p| assert!(p.held_unmaps.is_empty() && p.unmarked)); + assert!(before_execute(&title), "a Signal again: the work goes"); + drop((held_a, held_b)); + + // a retired texture's NULL unmap whose Signal fails, and the retry too + let raw = res.clone().into_raw() as usize; + with(&mut |p| { + p.release_tiles(used.clone(), extra.clone(), std::time::Instant::now(), false); + }); + let gate2: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + mq.Wait(&gate2, 1).unwrap(); + open_at_the_latest(&gate2); + let key = ReservedKey::from_desc(&desc, 0); + park_recyclable(raw, RecycleInfo { dev_key, key, total, was_mapped: true }, 0); + FAIL_SIGNALS.with(|f| f.set(2)); + assert!(recycle_ready(raw)); + FAIL_SIGNALS.with(|f| f.set(0)); + with(&mut |p| assert!(p.pending_recycles.iter().any(|r| r.raw == raw && r.mark == UNMARKED), "no mark yet")); + drain_recycled(); + let mut later = 0; + with(&mut |p| { + assert_eq!(p.reserved_pool.count(&key), 0, "not in the pool before a mark completes"); + later = p.pending_recycles.iter().find(|r| r.raw == raw).expect("still pending").mark; + assert!(later != UNMARKED && later > n + 1, "a later Signal was queued for it"); + }); + gate2.Signal(1).unwrap(); + assert!(done(&mfence, later)); + drain_recycled(); + let mut back = None; + with(&mut |p| { + assert_eq!(p.reserved_pool.count(&key), 1, "in the pool once its mark completed"); + back = p.reserved_pool.take(&key); + }); + assert_eq!(back.map(|b| b.0), Some(raw)); + drop(ID3D12Resource::from_raw(raw as *mut c_void)); + drop(res); + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// Spares whose Signal fails are released instead of queued for the pool, no value is published + /// for them, and their reservation is given back. + #[test] + fn spares_without_their_signal_are_released() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let Some(pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + let with = |f: &mut dyn FnMut(&mut Pages)| { + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + f(p) + } + }; + let mut reached_value = 0; + with(&mut |p| reached_value = p.signal_now().expect("a Signal")); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + ..Default::default() + }; + let key = ReservedKey::from_desc(&desc, 0); + let mut n = 0; + with(&mut |p| n = p.reserve_spares(key, 2)); + assert_eq!(n, 2); + FAIL_SIGNALS.with(|f| f.set(1)); + make_spares(&dev, dev.as_raw(), &desc, 0, std::ptr::null(), key, n); + with(&mut |p| { + assert_eq!(p.value, reached_value, "no value published for the spares"); + assert!(p.pending_recycles.iter().all(|r| r.key != key), "no spares queued without their Signal"); + assert!(!p.spares_in_flight.contains_key(&key), "the reservation is given back"); + assert_eq!(p.reserve_spares(key, 2), 2, "so the next placement reserves them again"); + p.end_spare_reservation(key, 2); + }); + FAIL_SIGNALS.with(|f| f.set(0)); + PAGES.lock().unwrap().remove(&dev_key); + } + } } 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..b99c1cf9bb --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/vram_small.rs @@ -0,0 +1,678 @@ +//! 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=1` enables this path. + +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use crate::util::HRESULT; + +/// Allocation unit: 4 KiB (`D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT`). +const UNIT: usize = 0x1000; +/// Largest small-resource size handled here: 60 KiB (`15 * 4 KiB < 64 KiB`). +const MAX_UNITS: u32 = 15; +/// Units per shared default heap: 16 MiB (`4096 * 4 KiB`). +const POOL_UNITS: u32 = 4096; +/// Keep an unreferenced `(va, units)` slot this long so immediate re-placements reuse it. +const IDLE: Duration = Duration::from_secs(2); +/// Wait before reusing a freed block for a different address (in-flight GPU work). +const COOL: Duration = Duration::from_secs(2); + +/// Key identifying a shared small-texture backing slot: `(title_va, size_in_4k_units)`. +type SlotKey = (usize, u32); + +/// Block location inside a device's small pools: `(pool_index, offset_in_4k_units, size_in_4k_units)`. +type Block = (u32, u32, u32); + +/// GPU fence snapshot captured when a pooled block enters `cooling`. A block cannot be recycled +/// until BOTH wall-clock `COOL` has elapsed AND every captured title-queue fence has completed, +/// preventing premature aliasing across multi-second pipeline-compile stalls. +#[derive(Default)] +struct GpuMarks(Vec<(ID3D12Fence, u64)>); + +unsafe impl Send for GpuMarks {} + +impl GpuMarks { + fn capture() -> Self { + Self(super::alloc_pool::pending_gpu_marks()) + } + + fn is_complete(&self) -> bool { + self.0.iter().all(|(f, v)| unsafe { super::real::fence_completed(f) } >= *v) + } +} + +struct Pool { + heap: H, + /// Bump pointer in 4 KiB units (`0..=POOL_UNITS`). + next_unit: u32, +} + +struct Slot { + pool: u32, + offset: u32, + users: u32, + idle_since: Option, +} + +struct SmallPools { + pools: Vec>, + /// Per-size-class (`1..=MAX_UNITS`) reusable blocks `(pool, offset)`. + free: [Vec<(u32, u32)>; (MAX_UNITS as usize) + 1], + /// Blocks given back, reusable only after `COOL` AND GPU fence completion (`G`). + cooling: VecDeque<(Block, Instant, G)>, + /// Live or idle-kept `(va, units)` → backing block. + slots: HashMap, + /// Idle slots, oldest first (`sweep_idle`). + idle: VecDeque<(SlotKey, Instant)>, + /// Live resource raw pointer → `(va, units)`. + resources: HashMap, + /// Total 4 KiB units currently held by `slots` (live + idle-kept). + used_units: usize, +} + +impl SmallPools { + fn new() -> Self { + SmallPools { + pools: Vec::new(), + free: std::array::from_fn(|_| Vec::new()), + cooling: VecDeque::new(), + slots: HashMap::new(), + idle: VecDeque::new(), + resources: HashMap::new(), + used_units: 0, + } + } + + fn sweep_idle_with(&mut self, now: Instant, mut capture_gate: impl FnMut() -> G) { + while self.idle.front().is_some_and(|&(_, since)| now.duration_since(since) >= IDLE) { + let Some((key, since)) = self.idle.pop_front() else { break }; + if self.slots.get(&key).is_some_and(|s| s.idle_since == Some(since)) { + if let Some(s) = self.slots.remove(&key) { + self.used_units -= key.1 as usize; + self.cooling.push_back(((s.pool, s.offset, key.1), now, capture_gate())); + } + } + } + } + + fn drain_cooling_with(&mut self, now: Instant, mut gpu_ready: impl FnMut(&G) -> bool) { + while self.cooling.front().is_some_and(|(_, at, gate)| now.duration_since(*at) >= COOL && gpu_ready(gate)) { + if let Some(((pool, offset, units), _, _)) = self.cooling.pop_front() { + self.free[units as usize].push((pool, offset)); + } + } + } + + /// Try to acquire an existing shared slot for `(va, units)` or allocate a block from existing + /// pools / free lists without creating a new D3D12 heap. + fn try_acquire_with(&mut self, key: SlotKey, now: Instant, capture_gate: impl FnMut() -> G, gpu_ready: impl FnMut(&G) -> bool) -> Option<(H, u32)> { + self.sweep_idle_with(now, capture_gate); + if let Some(s) = self.slots.get_mut(&key) { + s.users += 1; + s.idle_since = None; + return Some((self.pools[s.pool as usize].heap.clone(), s.offset)); + } + let units = key.1; + debug_assert!((1..=MAX_UNITS).contains(&units)); + self.drain_cooling_with(now, gpu_ready); + let (pool, offset) = if let Some(b) = self.free[units as usize].pop() { + b + } else if let Some((idx, p)) = self.pools.iter_mut().enumerate().rev().find(|(_, p)| p.next_unit + units <= POOL_UNITS) { + let off = p.next_unit; + p.next_unit += units; + (idx as u32, off) + } else { + return None; + }; + let heap = self.pools[pool as usize].heap.clone(); + self.slots.insert(key, Slot { pool, offset, users: 1, idle_since: None }); + self.used_units += units as usize; + Some((heap, offset)) + } + + /// Register a newly created pool heap and acquire `(va, units)`. + /// Re-checks `try_acquire` first under the lock so two threads racing to create a new 16 MiB + /// pool do not push a redundant empty heap (the extra `heap` drops cleanly if another thread + /// already added room or created the same slot). + fn add_pool_and_acquire_with(&mut self, heap: H, key: SlotKey, now: Instant, mut capture_gate: impl FnMut() -> G, mut gpu_ready: impl FnMut(&G) -> bool) -> (H, u32) { + if let Some(got) = self.try_acquire_with(key, now, &mut capture_gate, &mut gpu_ready) { + return got; + } + let pool_idx = self.pools.len() as u32; + self.pools.push(Pool { heap, next_unit: 0 }); + if let Some(got) = self.try_acquire_with(key, now, &mut capture_gate, &mut gpu_ready) { + return got; + } + // `pool_idx` has `next_unit == 0` and `units <= MAX_UNITS < POOL_UNITS`, so `try_acquire` + // above always succeeds. + unreachable!("fresh pool {pool_idx} must fit {} units", key.1); + } + + fn note_resource(&mut self, res: usize, key: SlotKey) { + self.resources.insert(res, key); + } + + /// Release one user of `key`. When `rollback` is true (creation failed before the GPU ever saw + /// the resource), the block returns directly to `free` if this was its only user. + fn release_key(&mut self, key: SlotKey, now: Instant, rollback: bool) { + let Some(s) = self.slots.get_mut(&key) else { return }; + s.users = s.users.saturating_sub(1); + if s.users == 0 { + if rollback { + if let Some(s) = self.slots.remove(&key) { + self.used_units -= key.1 as usize; + self.free[key.1 as usize].push((s.pool, s.offset)); + } + } else { + s.idle_since = Some(now); + self.idle.push_back((key, now)); + } + } + } + + fn forget(&mut self, res: usize, now: Instant) -> bool { + let Some(key) = self.resources.remove(&res) else { + return false; + }; + self.release_key(key, now, false); + true + } + + fn bytes(&self) -> (usize, usize) { + (self.used_units * UNIT, self.pools.len() * POOL_UNITS as usize * UNIT) + } + + #[cfg(test)] + fn flush_idle_with(&mut self, now: Instant, mut capture_gate: impl FnMut() -> G) { + while let Some((key, since)) = self.idle.pop_front() { + if self.slots.get(&key).is_some_and(|s| s.idle_since == Some(since)) { + if let Some(s) = self.slots.remove(&key) { + self.used_units -= key.1 as usize; + self.cooling.push_back(((s.pool, s.offset, key.1), now, capture_gate())); + } + } + } + } +} + +impl SmallPools { + #[cfg(test)] + fn try_acquire(&mut self, key: SlotKey, now: Instant) -> Option<(H, u32)> { self.try_acquire_with(key, now, || (), |_| true) } + #[cfg(test)] + fn add_pool_and_acquire(&mut self, heap: H, key: SlotKey, now: Instant) -> (H, u32) { self.add_pool_and_acquire_with(heap, key, now, || (), |_| true) } + #[cfg(test)] + fn sweep_idle(&mut self, now: Instant) { self.sweep_idle_with(now, || ()); } + #[cfg(test)] + fn flush_idle(&mut self, now: Instant) { self.flush_idle_with(now, || ()); } +} + +impl SmallPools { + fn try_acquire(&mut self, key: SlotKey, now: Instant) -> Option<(H, u32)> { self.try_acquire_with(key, now, GpuMarks::capture, GpuMarks::is_complete) } + fn add_pool_and_acquire(&mut self, heap: H, key: SlotKey, now: Instant) -> (H, u32) { self.add_pool_and_acquire_with(heap, key, now, GpuMarks::capture, GpuMarks::is_complete) } + fn sweep_idle(&mut self, now: Instant) { self.sweep_idle_with(now, GpuMarks::capture); } + #[cfg(test)] + fn flush_idle(&mut self, now: Instant) { self.flush_idle_with(now, GpuMarks::capture); } +} + +// D3D12 heaps are free-threaded. +unsafe impl Send for SmallPools {} + +static SMALL_POOLS: Mutex>> = Mutex::new(BTreeMap::new()); + +fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_VRAM_SMALL").is_ok_and(|v| v.trim() == "1")) +} + +/// Whether `desc` and `console_bytes` are eligible for 4 KiB small-resource sub-allocation. +fn candidate(desc: &D3D12_RESOURCE_DESC, console_bytes: Option) -> bool { + const PAGE: u64 = 0x1_0000; + desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN + && desc.SampleDesc.Count <= 1 + && desc.Flags.0 & 0x7 == 0 + && matches!(desc.Dimension, D3D12_RESOURCE_DIMENSION_TEXTURE1D | D3D12_RESOURCE_DIMENSION_TEXTURE2D | D3D12_RESOURCE_DIMENSION_TEXTURE3D) + && console_bytes.is_some_and(|b| b > 0 && b < PAGE) +} + +/// Place a sub-64 KiB sampled texture at 4 KiB granularity in a shared default heap. +/// Returns `None` if the texture is not a small resource (the caller falls back to `vram::Pages` +/// or a committed resource). +#[allow(clippy::too_many_arguments)] +pub(super) unsafe fn place( + dev: &ID3D12Device, + this: *mut c_void, + va: usize, + desc: &D3D12_RESOURCE_DESC, + state: u32, + clear: *const c_void, + console_bytes: Option, + riid: *const windows_sys::core::GUID, + ppv: *mut *mut c_void, +) -> Option { + if !enabled() || !candidate(desc, console_bytes) { + return None; + } + let small_desc = D3D12_RESOURCE_DESC { Alignment: D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64, ..*desc }; + let info = dev.GetResourceAllocationInfo(0, &[small_desc]); + if info.SizeInBytes == u64::MAX || info.SizeInBytes == 0 || info.Alignment != UNIT as u64 || info.SizeInBytes >= 0x1_0000 { + return None; + } + let units = (info.SizeInBytes as usize).div_ceil(UNIT) as u32; + if !(1..=MAX_UNITS).contains(&units) { + return None; + } + let dev_key = dev.as_raw() as usize; + let key = (va, units); + let now = Instant::now(); + + let (heap, offset_units) = { + let mut g = SMALL_POOLS.lock().unwrap(); + let pools = g.entry(dev_key).or_insert_with(SmallPools::new); + pools.try_acquire(key, now) + } + .or_else(|| { + // Create a new 16 MiB default heap outside `SMALL_POOLS.lock()`. + let heap_desc = D3D12_HEAP_DESC { + SizeInBytes: POOL_UNITS as u64 * UNIT as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + // 64 KiB heap alignment is valid for 4 KiB-aligned small resources at any 4 KiB offset. + Alignment: D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut new_heap: Option = None; + if let Err(e) = super::title_textures::own_work(|| dev.CreateHeap(&heap_desc, &mut new_heap)) { + crate::xlog_warn!("D3D12.X: small texture pool CreateHeap: {e}"); + return None; + } + let new_heap = new_heap?; + let mut g = SMALL_POOLS.lock().unwrap(); + let pools = g.entry(dev_key).or_insert_with(SmallPools::new); + Some(pools.add_pool_and_acquire(new_heap, key, Instant::now())) + })?; + + let hr = super::real::dev_create_placed_resource( + this, + heap.as_raw() as usize, + offset_units as usize * UNIT, + &small_desc as *const _ as usize, + state as usize, + clear as usize, + riid, + ppv, + ); + if hr < 0 || (*ppv).is_null() { + let mut g = SMALL_POOLS.lock().unwrap(); + if let Some(pools) = g.get_mut(&dev_key) { + pools.release_key(key, Instant::now(), true); + } + return None; + } + let raw = *ppv as usize; + SMALL_POOLS.lock().unwrap().entry(dev_key).or_insert_with(SmallPools::new).note_resource(raw, key); + Some(hr) +} + +/// Release a small-pool texture on COM release. Returns `true` if `resource` belonged to a small +/// pool (so `vram::forget` can skip locking `PAGES`). +pub(super) fn forget(resource: usize) -> bool { + let mut g = SMALL_POOLS.lock().unwrap(); + let now = Instant::now(); + for pools in g.values_mut() { + if pools.forget(resource, now) { + return true; + } + } + false +} + +/// `(used_bytes, pool_bytes)` across all devices. +pub(super) fn bytes() -> (usize, usize) { + let g = SMALL_POOLS.lock().unwrap(); + g.values().fold((0, 0), |(used, pools), p| { + let (u, t) = p.bytes(); + (used + u, pools + t) + }) +} + +#[cfg(test)] +pub(super) fn bytes_for(device: usize) -> (usize, usize) { + let mut g = SMALL_POOLS.lock().unwrap(); + let Some(p) = g.get_mut(&device) else { return (0, 0) }; + p.sweep_idle(Instant::now()); + p.bytes() +} + +#[cfg(test)] +pub(super) fn flush_idle_for(device: usize) { + let mut g = SMALL_POOLS.lock().unwrap(); + if let Some(p) = g.get_mut(&device) { + p.flush_idle(Instant::now()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn small_pool_packs_shares_and_recycles_by_size_class() { + let t0 = Instant::now(); + let at = |ms: u64| t0 + Duration::from_millis(ms); + let mut p: SmallPools = SmallPools::new(); + let alloc = |p: &mut SmallPools, va: usize, units: u32, res: usize, now: Instant| -> (u32, u32) { + let got = p.try_acquire((va, units), now).unwrap_or_else(|| { + let id = p.pools.len() as u32; + p.add_pool_and_acquire(id, (va, units), now) + }); + p.note_resource(res, (va, units)); + got + }; + + // Sixteen 4 KiB textures pack into 64 KiB (not 16 * 64 KiB = 1 MiB). + for i in 0..16usize { + let (h, off) = alloc(&mut p, 0x10_0000 + i * UNIT, 1, 100 + i, at(0)); + assert_eq!((h, off), (0, i as u32)); + } + assert_eq!(p.bytes(), (16 * UNIT, POOL_UNITS as usize * UNIT)); + + // Re-placing the exact same (va, units) shares the exact same (heap, offset) with zero growth. + let (h_dup, off_dup) = alloc(&mut p, 0x10_4000, 1, 200, at(10)); + assert_eq!((h_dup, off_dup), (0, 4)); + assert_eq!(p.bytes().0, 16 * UNIT); + + // Releasing one of the two aliases keeps the slot alive; releasing both makes it idle. + assert!(p.forget(200, at(20))); + assert_eq!(p.slots[&(0x10_4000, 1)].users, 1); + assert!(p.forget(104, at(30))); + assert_eq!(p.slots[&(0x10_4000, 1)].users, 0); + + // Re-acquiring within IDLE reuses the exact same slot. + let (h_re, off_re) = alloc(&mut p, 0x10_4000, 1, 201, at(1000)); + assert_eq!((h_re, off_re), (0, 4)); + assert!(p.forget(201, at(1100))); + + // After IDLE (2 s) + COOL (2 s), the 4 KiB block is recycled for a new address. + let (h_wait, off_wait) = alloc(&mut p, 0x20_0000, 1, 202, at(3200)); + assert_eq!((h_wait, off_wait), (0, 16), "still cooling at +2.1s, must not reuse yet"); + let (h_rec, off_rec) = alloc(&mut p, 0x20_1000, 1, 203, at(5300)); + assert_eq!((h_rec, off_rec), (0, 4), "block (0, 4) recycled after IDLE + COOL"); + + // Rollback on creation failure immediately returns the block to the free list. + let (h_fail, off_fail) = p.try_acquire((0x30_0000, 4), at(5400)).unwrap(); + assert_eq!((h_fail, off_fail), (0, 17)); + p.release_key((0x30_0000, 4), at(5400), true); + let (h_next, off_next) = alloc(&mut p, 0x30_4000, 4, 204, at(5400)); + assert_eq!((h_next, off_next), (0, 17)); + + // Concurrent CreateHeap race: if room already exists in pool 0, `add_pool_and_acquire` + // must reuse existing room instead of pushing a redundant empty 16 MiB pool. + let pools_before = p.pools.len(); + let (h_raced, _) = p.add_pool_and_acquire(999, (0x40_0000, 1), at(5500)); + assert_eq!(h_raced, 0); + assert_eq!(p.pools.len(), pools_before, "must not push redundant pool when room already exists"); + + // `flush_idle` clears unreferenced idle slots while keeping live (`users > 0`) slots intact. + let used_before_flush = p.bytes().0; + let _ = alloc(&mut p, 0x50_0000, 2, 205, at(5600)); + assert!(p.forget(205, at(5610))); + assert_eq!(p.bytes().0, used_before_flush + 2 * UNIT); + p.flush_idle(at(5620)); + assert_eq!(p.bytes().0, used_before_flush, "flush_idle must reclaim unreferenced slots immediately"); + } + + #[test] + fn candidate_filters_large_gpu_owned_and_msaa_textures() { + let mut d = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + assert!(candidate(&d, Some(16 * 1024))); + assert!(!candidate(&d, Some(64 * 1024)), "64 KiB stays on vram::Pages"); + assert!(!candidate(&d, None)); + assert!(!candidate(&d, Some(0))); + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + assert!(!candidate(&d, Some(16 * 1024))); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + d.SampleDesc.Count = 4; + assert!(!candidate(&d, Some(16 * 1024))); + d.SampleDesc.Count = 1; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + assert!(!candidate(&d, Some(16 * 1024))); + } + + /// On the GPU: 512 small 4 KiB (64x64 BC1) and 16 KiB (64x64 RGBA8) sampled textures pack at + /// 4 KiB granularity inside a single 16 MiB heap (16x and 4x smaller than 64 KiB tiles), + /// same-address placements alias their pixels on hardware, adjacent 4 KiB textures have zero + /// crosstalk, and a small sampled texture over an existing 64 KiB GPU target falls back to + /// `vram::Pages` so target aliasing is preserved. + #[test] + fn gpu_small_textures_pack_at_4k_granularity_and_preserve_pixels() { + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let factory: IDXGIFactory6 = CreateDXGIFactory1().expect("DXGI factory"); + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let mut dev: Option = None; + for (adapter, _) in crate::gpu::adapter::candidates(&factory, &sel) { + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() && dev.is_some() { + break; + } + } + let Some(dev) = dev else { + crate::gpu::recomp::runner::skip_test("no D3D12 device"); + return; + }; + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + if dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut opts as *mut _ as *mut c_void, std::mem::size_of_val(&opts) as u32).is_err() + || opts.ResourceHeapTier.0 < 2 + { + crate::gpu::recomp::runner::skip_test(&format!("resource heap tier {} < 2", opts.ResourceHeapTier.0)); + return; + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + + let desc_of = |w: u64, h: u32, fmt: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w, + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: fmt, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: flags, + ..Default::default() + }; + let place_sampled = |va: usize, d: &D3D12_RESOURCE_DESC, cbytes: u64| -> ID3D12Resource { + let mut p = std::ptr::null_mut(); + let hr = super::super::vram::place_pages(dev.as_raw(), va, d, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), Some(cbytes), riid, &mut p); + assert!(hr.is_some_and(|h| h >= 0) && !p.is_null(), "place_pages at {va:#x} failed: {hr:x?}"); + assert!(super::super::vram::is_placed_texture(p as usize)); + ID3D12Resource::from_raw(p) + }; + + // 1. 512 x 64x64 BC1 (2 KiB on console -> 4 KiB small resource on PC): must pack into + // 2 MiB (16x smaller than 512 x 64 KiB = 32 MiB!) inside a single 16 MiB heap. + super::super::vram::flush_idle_for(dev_key); + let bc1 = desc_of(64, 64, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE); + let bc1_info = dev.GetResourceAllocationInfo(0, &[D3D12_RESOURCE_DESC { Alignment: D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64, ..bc1 }]); + if bc1_info.SizeInBytes == u64::MAX || bc1_info.SizeInBytes == 0 || bc1_info.Alignment != UNIT as u64 || bc1_info.SizeInBytes >= 0x1_0000 { + crate::gpu::recomp::runner::skip_test(&format!( + "adapter does not support 4 KiB small-resource placement for 64x64 BC1 (align={}, size={})", + bc1_info.Alignment, bc1_info.SizeInBytes + )); + return; + } + let (small0, _) = bytes_for(dev_key); + let (pages0, _) = super::super::vram::page_bytes_for(dev_key); + let bc1_base = 0x60_0000_0000usize; + let mut bc1_res = Vec::with_capacity(512); + for k in 0..512usize { + bc1_res.push(place_sampled(bc1_base + k * 0x1000, &bc1, 2048)); + } + let (small_after_bc1, small_pool_after_bc1) = bytes_for(dev_key); + let bc1_small_delta = small_after_bc1 - small0; + // (`vram::page_bytes_for` counts the 64 KiB pages alone on this branch) + let bc1_page_delta = super::super::vram::page_bytes_for(dev_key).0 - pages0; + println!("512 x 64x64 BC1: +{bc1_small_delta} B in small pools (pool={small_pool_after_bc1} B), +{bc1_page_delta} B of 64 KiB pages (vs 33554432 B as 64 KiB tiles)"); + assert_eq!(bc1_small_delta, 512 * UNIT, "each 64x64 BC1 must take 4 KiB in small pool"); + assert_eq!(bc1_page_delta, 0, "zero 64 KiB Pages tiles allocated for 4 KiB BC1 textures"); + drop(bc1_res); + + // 2. Hardware upload + readback: two adjacent 64x64 RGBA8 (16 KiB) textures and a + // same-address alias verify zero crosstalk and exact pixel sharing on the GPU. + super::super::vram::flush_idle_for(dev_key); + let rgba = desc_of(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE); + let rgba_info = dev.GetResourceAllocationInfo(0, &[D3D12_RESOURCE_DESC { Alignment: D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64, ..rgba }]); + if rgba_info.SizeInBytes != 16384 || rgba_info.Alignment != UNIT as u64 { + crate::gpu::recomp::runner::skip_test(&format!( + "step 2: adapter does not support 4 KiB 16 KiB placement for 64x64 RGBA8 (align={}, size={})", + rgba_info.Alignment, rgba_info.SizeInBytes + )); + return; + } + let va_a = 0x61_0000_1000usize; + let va_b = 0x61_0000_5000usize; + let a1 = place_sampled(va_a, &rgba, 16384); + let (small_after_a1, _) = bytes_for(dev_key); + let a2 = place_sampled(va_a, &rgba, 16384); + assert_eq!(bytes_for(dev_key).0, small_after_a1, "same-va small texture must share slot"); + let b = place_sampled(va_b, &rgba, 16384); + assert_eq!(bytes_for(dev_key).0 - small_after_a1, 16384, "64x64 RGBA8 must take 16 KiB"); + + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let fill_a = vec![0x3Cu8; 64 * 64 * 4]; + let fill_b = vec![0xA5u8; 64 * 64 * 4]; + let sub = |data: Vec| crate::gpu::texture::Subresource { rows: 64, row_bytes: 64 * 4, depth: 1, data }; + // (this branch has no `texture::upload_batch`: one upload each) + for (res, fill) in [(&a2, &fill_a), (&b, &fill_b)] { + crate::gpu::texture::upload(&dev, &queue, res, &[sub(fill.clone())], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COMMON).expect("upload failed"); + } + + let readback_tex = |r: &ID3D12Resource| -> Vec { + let rd = r.GetDesc(); + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let (mut rows, mut row_bytes, mut total) = (0u32, 0u64, 0u64); + dev.GetCopyableFootprints(&rd, 0, 1, 0, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut total)); + let mut rb: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb, + ).unwrap(); + let rb = rb.unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + crate::gpu::texture::wait(&dev, &queue).unwrap(); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let mut out = Vec::with_capacity(rows as usize * row_bytes as usize); + for y in 0..rows as usize { + out.extend_from_slice(std::slice::from_raw_parts((p as *const u8).add(y * fp.Footprint.RowPitch as usize), row_bytes as usize)); + } + rb.Unmap(0, None); + out + }; + + assert_eq!(readback_tex(&a1), fill_a, "same-va alias a1 must see pixels uploaded to a2"); + assert_eq!(readback_tex(&b), fill_b, "adjacent 4 KiB texture b must not crosstalk with a"); + drop((b, a2, a1)); + + // 3. A small sampled texture at a 64 KiB-aligned va occupied by an existing GPU-owned + // render target must stay on vram::Pages (not vram_small) so it aliases the target. + if opts.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0 { + crate::gpu::recomp::runner::skip_test(&format!("step 3: tiled resources tier {} < 2", opts.TiledResourcesTier.0)); + return; + } + super::super::vram::flush_idle_for(dev_key); + let rt_va = 0x62_0000_0000usize; + let rt_desc = desc_of(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + let mut rt_raw = std::ptr::null_mut(); + let hr = super::super::vram::place(dev.as_raw(), rt_va, &rt_desc, D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32, std::ptr::null(), Some(16384), riid, &mut rt_raw); + assert!(hr.is_some_and(|h| h >= 0) && !rt_raw.is_null()); + let rt = ID3D12Resource::from_raw(rt_raw); + let small_before_alias = bytes_for(dev_key).0; + let sampled_view = place_sampled(rt_va, &rgba, 16384); + assert_eq!(bytes_for(dev_key).0, small_before_alias, "sampled view over live GPU target must alias vram::Pages, not vram_small"); + drop((sampled_view, rt)); + } + } + + #[test] + fn small_pool_blocks_recycle_until_gpu_fence_completes_even_after_cool() { + use std::sync::{atomic::{AtomicBool, Ordering}, Arc}; + let t0 = Instant::now(); + let at = |ms: u64| t0 + Duration::from_millis(ms); + let gpu_done = Arc::new(AtomicBool::new(false)); + let mut p: SmallPools> = SmallPools::new(); + + let (h0, off0) = p.add_pool_and_acquire_with(1, (0x1000, 2), at(0), || gpu_done.clone(), |d| d.load(Ordering::Acquire)); + assert_eq!((h0, off0), (1, 0)); + p.note_resource(0x2001, (0x1000, 2)); + assert!(p.forget(0x2001, at(10))); + + p.sweep_idle_with(at(2_500), || gpu_done.clone()); + let (h1, off1) = p.try_acquire_with((0x2000, 2), at(12_500), || gpu_done.clone(), |d| d.load(Ordering::Acquire)).unwrap(); + assert_eq!((h1, off1), (1, 2), "must not alias cooling small-pool block before GPU fence completes"); + + gpu_done.store(true, Ordering::Release); + let (h2, off2) = p.try_acquire_with((0x3000, 2), at(12_600), || gpu_done.clone(), |d| d.load(Ordering::Acquire)).unwrap(); + assert_eq!((h2, off2), (1, 0)); + } + + #[test] + fn candidate_accepts_small_texture1d_for_4k_small_pool() { + let mut d = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE1D, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + assert!(candidate(&d, Some(4096)), "small sampled TEXTURE1D must qualify for 4 KiB SmallPools"); + assert!(!candidate(&d, Some(64 * 1024)), "64 KiB TEXTURE1D stays on default placement"); + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + assert!(!candidate(&d, Some(4096)), "UAV TEXTURE1D must not enter SmallPools"); + } +} diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 92cd2e86d3..64fdcd35a7 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -28,9 +28,8 @@ //! 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, 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. +//! 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 swizzle modes above 4, are refused. #![allow(non_snake_case)] @@ -256,6 +255,57 @@ pub struct BcpackUnpackStats { pub failed: u64, } +/// Per-group stream chunk lengths (bytes) for each supported `DSTORAGE_SWIZZLE_MODE`. +/// Modes 1..=4 interleave whole-buffer per-stream arrays into 16 KiB or 32 KiB groups so a +/// title's compute shader can reconstruct the final BCn blocks in place: +/// - 1 (`4K_4K_8K`, 16 KiB): BC1 endpoints and indices +/// - 2 (`4K_4K_24K`, 32 KiB): BC4 endpoints and indices +/// - 3 (`4K_12K_4K_4K_8K`, 32 KiB): BC3 alpha and colour streams +/// - 4 (`4K_12K_4K_12K`, 32 KiB): BC5 two-channel streams +fn swizzle_chunks(mode: u16) -> Option<&'static [usize]> { + const K: usize = 1024; + match mode { + 1 => Some(&[4 * K, 4 * K, 8 * K]), + 2 => Some(&[4 * K, 4 * K, 24 * K]), + 3 => Some(&[4 * K, 12 * K, 4 * K, 4 * K, 8 * K]), + 4 => Some(&[4 * K, 12 * K, 4 * K, 12 * K]), + _ => None, + } +} + +/// Group alignment (bytes) required by `mode` (0 = none; None = unsupported mode). +fn swizzle_group_size(mode: u16) -> Option { + if mode == 0 { + return Some(0); + } + swizzle_chunks(mode).map(|chunks| chunks.iter().sum()) +} + +/// Rearrange stream-grouped bytes `src` into interleaved 16 KiB / 32 KiB groups for `mode` (1..=4). +fn swizzle_interleave(mode: u16, src: &[u8]) -> Result, HRESULT> { + let Some(chunks) = swizzle_chunks(mode) else { + return Err(E_DECOMPRESSION); + }; + let group_size: usize = chunks.iter().sum(); + if src.is_empty() || src.len() % group_size != 0 { + return Err(E_DESTINATION_SIZE); + } + let groups = src.len() / group_size; + let mut dst = vec![0u8; src.len()]; + let mut stream_base = 0usize; + let mut group_off = 0usize; + for &chunk_len in chunks { + for g in 0..groups { + let s = stream_base + g * chunk_len; + let d = g * group_size + group_off; + dst[d..d + chunk_len].copy_from_slice(&src[s..s + chunk_len]); + } + stream_base += groups * chunk_len; + group_off += chunk_len; + } + Ok(dst) +} + /// The BCPack stage of a request: `packed` to the `n` bytes of blocks of its mode. fn bcpack_unpack(r: &Request, packed: &[u8], n: usize) -> Result, HRESULT> { let bc = r.bcpack(); @@ -737,9 +787,13 @@ impl Request { if self.options & !KNOWN_OPTIONS_MASK != 0 { warn_once("DSTORAGE_REQUEST_OPTIONS", format_args!("unknown high option bits {:#x}", self.options & !KNOWN_OPTIONS_MASK)); } - if self.swizzle() != 0 { - warn_once("SwizzleMode", format_args!("hardware swizzle mode {} unsupported", self.swizzle())); + let swiz = self.swizzle(); + let Some(swiz_group) = swizzle_group_size(swiz) else { + warn_once("SwizzleMode", format_args!("swizzle mode {swiz} unsupported")); return Err(E_DECOMPRESSION); + }; + if swiz_group != 0 && (self.destination_size == 0 || self.destination_size as usize % swiz_group != 0) { + return Err(E_DESTINATION_SIZE); } match (self.zlib(), self.bcpack()) { // Uncompressed copy: source and destination sizes must match. @@ -865,7 +919,7 @@ fn cpu_range_in(p: usize, n: usize, in_view: impl Fn(usize) -> bool) -> Option bool { let Some(end) = p.checked_add(n) else { return false }; - crate::hle::kernelx::lazy::ensure(p, n); + let _opened = crate::hle::kernelx::lazy::ensure(p, n); if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(p, n)) { return true; } @@ -999,11 +1053,12 @@ unsafe fn execute( }; let bc = r.bcpack(); - if r.swizzle() != 0 || (bc != 0 && !super::bcpack::can_decode(bc)) { + let swiz = r.swizzle(); + if (swiz != 0 && swizzle_chunks(swiz).is_none()) || (bc != 0 && !super::bcpack::can_decode(bc)) { return Err(E_DECOMPRESSION); } - // the stages in the console's order: zlib, then BCPack + // the stages in the console's order: zlib, BCPack, then swizzle interleave let stage1 = if r.zlib() { let stage1_len = if r.intermediate_size != 0 { r.intermediate_size as usize } else { n }; let mut d = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&src, stage1_len).map_err(|_| E_ZLIB_DATA)?; @@ -1022,7 +1077,8 @@ unsafe fn execute( } else { src }; - let payload = if bc != 0 { Cow::Owned(bcpack_unpack(r, &stage1, n)?) } else { stage1 }; + let unpacked = if bc != 0 { Cow::Owned(bcpack_unpack(r, &stage1, n)?) } else { stage1 }; + let payload = if swiz != 0 { Cow::Owned(swizzle_interleave(swiz, &unpacked[..n])?) } else { unpacked }; if r.dest_physical_pages() { let pages = dest_pages.ok_or(E_ACCESS_VIOLATION)?; @@ -2235,8 +2291,11 @@ mod tests { assert_eq!(Request::parse(&request_ex(bc2, 0x1000, 0, 256, 0x2000, 0, 20, 0, 0)).check(false), Err(E_DECOMPRESSION)); assert_eq!(Request::parse(&request_ex(bc1, 0x1000, 0, 256, 0x2000, 0, 20, 0, 0)).check(false), Ok(())); assert_eq!(Request::parse(&request_ex(bc1, 0x1000, 0, 256, 0x2000, 0, 20, 64, 0)).check(false), Err(E_DESTINATION_SIZE)); - // Hardware swizzle mode unsupported - assert_eq!(Request::parse(&request_ex(swiz, 0x1000, 0, 64, 0x2000, 0, 64, 0, 0)).check(false), Err(E_DECOMPRESSION)); + // Swizzle modes 1..=4 validate group alignment (16 KiB / 32 KiB); modes > 4 are refused + let swiz_bad = 5u64 << SWIZZLE_SHIFT; + assert_eq!(Request::parse(&request_ex(swiz, 0x1000, 0, 64, 0x2000, 0, 64, 0, 0)).check(false), Err(E_DESTINATION_SIZE)); + assert_eq!(Request::parse(&request_ex(swiz, 0x1000, 0, 16 * 1024, 0x2000, 0, 16 * 1024, 0, 0)).check(false), Ok(())); + assert_eq!(Request::parse(&request_ex(swiz_bad, 0x1000, 0, 32 * 1024, 0x2000, 0, 32 * 1024, 0, 0)).check(false), Err(E_DECOMPRESSION)); // SourceIsPhysicalPages requires memory source assert_eq!(Request::parse(&request_ex(SOURCE_PHYS_PAGES_BIT, 0x1000, 0, 64, 0x2000, 0, 64, 0, 0)).check(false), Err(E_SOURCE_TYPE)); @@ -3186,4 +3245,145 @@ mod tests { status_release(s); } } + + #[test] + fn swizzle_interleave_all_four_modes_and_validation() { + const K: usize = 1024; + let cases: [(u16, &[usize]); 4] = [ + (1, &[4 * K, 4 * K, 8 * K]), + (2, &[4 * K, 4 * K, 24 * K]), + (3, &[4 * K, 12 * K, 4 * K, 4 * K, 8 * K]), + (4, &[4 * K, 12 * K, 4 * K, 12 * K]), + ]; + assert_eq!(swizzle_interleave(0, &[0u8; 16 * K]), Err(E_DECOMPRESSION)); + assert_eq!(swizzle_interleave(5, &[0u8; 32 * K]), Err(E_DECOMPRESSION)); + for (mode, chunks) in cases { + let group_size: usize = chunks.iter().sum(); + assert_eq!(swizzle_group_size(mode), Some(group_size)); + assert_eq!(swizzle_interleave(mode, &[]), Err(E_DESTINATION_SIZE)); + assert_eq!(swizzle_interleave(mode, &vec![0u8; group_size - 1]), Err(E_DESTINATION_SIZE)); + assert_eq!(swizzle_interleave(mode, &vec![0u8; group_size + 4096]), Err(E_DESTINATION_SIZE)); + + // 3 groups: fill each (stream, group) chunk with a unique deterministic pattern. + let groups = 3usize; + let total = groups * group_size; + let mut src = vec![0u8; total]; + let mut stream_base = 0usize; + for (si, &clen) in chunks.iter().enumerate() { + for g in 0..groups { + let slice = &mut src[stream_base + g * clen..stream_base + (g + 1) * clen]; + for (i, b) in slice.iter_mut().enumerate() { + *b = ((si as u8).wrapping_mul(53)) + ^ ((g as u8).wrapping_mul(17)) + ^ ((i & 0xFF) as u8) + ^ (((i >> 8) & 0xFF) as u8); + } + } + stream_base += groups * clen; + } + let out = swizzle_interleave(mode, &src).unwrap(); + assert_eq!(out.len(), total); + for g in 0..groups { + let mut off = g * group_size; + for (si, &clen) in chunks.iter().enumerate() { + let slice = &out[off..off + clen]; + for (i, &b) in slice.iter().enumerate() { + let expected = ((si as u8).wrapping_mul(53)) + ^ ((g as u8).wrapping_mul(17)) + ^ ((i & 0xFF) as u8) + ^ (((i >> 8) & 0xFF) as u8); + assert_eq!(b, expected, "mode {mode} group {g} stream {si} byte {i}"); + } + off += clen; + } + } + } + } + + #[test] + fn swizzle_end_to_end_single_stage_and_zlib() { + // Test mode 1 (4K/4K/8K, 2 groups = 32 KiB) both single-stage and two-stage (zlib + swizzle) + // on a memory queue, reconstructing original BC1 blocks from each 16 KiB group. + let total = 32 * 1024usize; + let blocks = total / 8; + let mut orig = vec![0u8; total]; + for b in 0..blocks { + let p = b * 8; + orig[p] = (b & 0xFF) as u8; + orig[p + 1] = ((b >> 8) & 0xFF) as u8; + orig[p + 2] = (b.wrapping_mul(3) & 0xFF) as u8; + orig[p + 3] = (b.wrapping_mul(7) & 0xFF) as u8; + orig[p + 4..p + 8].copy_from_slice(&(b as u32).wrapping_mul(0x9E37_79B9).to_le_bytes()); + } + // Group BC1 streams across the whole buffer (e0, e1, indices). + let mut grouped = vec![0u8; total]; + let (mut o0, mut o1, mut o2) = (0usize, total / 4, total / 2); + for b in 0..blocks { + let p = b * 8; + grouped[o0..o0 + 2].copy_from_slice(&orig[p..p + 2]); + grouped[o1..o1 + 2].copy_from_slice(&orig[p + 2..p + 4]); + grouped[o2..o2 + 4].copy_from_slice(&orig[p + 4..p + 8]); + o0 += 2; + o1 += 2; + o2 += 4; + } + let zlib_grouped = miniz_oxide::deflate::compress_to_vec_zlib(&grouped, 6); + assert!(zlib_grouped.len() < grouped.len()); + + unsafe { + let mut f = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&IID_FACTORY, &mut f), S_OK); + let vt = *(f as *const *const usize); + let create_queue: unsafe extern "system" fn(*mut c_void, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(3)); + let create_status: unsafe extern "system" fn(*mut c_void, u32, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(5)); + let mut desc = [0u8; 0x18]; + desc[0..4].copy_from_slice(&1u32.to_le_bytes()); + desc[8..10].copy_from_slice(&8u16.to_le_bytes()); + desc[10] = 2; + let mut q = std::ptr::null_mut(); + assert_eq!(create_queue(f, desc.as_ptr(), &IID_QUEUE, &mut q), S_OK); + let mut s = std::ptr::null_mut(); + assert_eq!(create_status(f, 2, std::ptr::null(), &IID_STATUS_ARRAY, &mut s), S_OK); + let qv = *(q as *const *const usize); + let enqueue: unsafe extern "system" fn(*mut c_void, *const u8) = std::mem::transmute(*qv.add(3)); + let status: unsafe extern "system" fn(*mut c_void, *mut c_void, u32) = std::mem::transmute(*qv.add(4)); + let submit: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(*qv.add(6)); + let sv = *(s as *const *const usize); + let complete: unsafe extern "system" fn(*mut c_void, u32) -> bool = std::mem::transmute(*sv.add(3)); + let hresult: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT = std::mem::transmute(*sv.add(4)); + + let mut dst_raw = vec![0u8; total]; + let mut dst_zlib = vec![0u8; total]; + let r0 = request(SOURCE_MEMORY_BIT | (1u64 << SWIZZLE_SHIFT), dst_raw.as_mut_ptr() as u64, total as u32, grouped.as_ptr() as u64, 0, grouped.len() as u32); + let r1 = request(SOURCE_MEMORY_BIT | ZLIB_BIT | (1u64 << SWIZZLE_SHIFT), dst_zlib.as_mut_ptr() as u64, total as u32, zlib_grouped.as_ptr() as u64, 0, zlib_grouped.len() as u32); + enqueue(q, r0.as_ptr()); + status(q, s, 0); + enqueue(q, r1.as_ptr()); + status(q, s, 1); + submit(q); + let t = std::time::Instant::now(); + while (!complete(s, 0) || !complete(s, 1)) && t.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + assert_eq!(hresult(s, 0), S_OK); + assert_eq!(hresult(s, 1), S_OK); + assert_eq!(dst_raw, dst_zlib); + + // Reconstruct original BC1 blocks from each 16 KiB group in place and verify exact equality. + let mut rebuilt = vec![0u8; total]; + for g in 0..2 { + let grp = &dst_zlib[g * 16384..(g + 1) * 16384]; + for k in 0..2048 { + let out = (g * 2048 + k) * 8; + rebuilt[out..out + 2].copy_from_slice(&grp[k * 2..k * 2 + 2]); + rebuilt[out + 2..out + 4].copy_from_slice(&grp[4096 + k * 2..4096 + k * 2 + 2]); + rebuilt[out + 4..out + 8].copy_from_slice(&grp[8192 + k * 4..8192 + k * 4 + 4]); + } + } + assert_eq!(rebuilt, orig); + queue_close(q); + queue_release(q); + status_release(s); + } + } } diff --git a/crates/xcl/src/hle/ffx.rs b/crates/xcl/src/hle/ffx.rs new file mode 100644 index 0000000000..b5b8b34eeb --- /dev/null +++ b/crates/xcl/src/hle/ffx.rs @@ -0,0 +1,198 @@ +//! The title's calls to its FidelityFX loader (`amd_fidelityfx_loader_xbox.dll`), seen on their +//! way to it. On a Series S the retail title upscales with the console's FSR4 (1280x720 → +//! 1920x1080, a history kept across frames); its people show copies along their path and the +//! last shot shows through a camera cut, as if the history were neither rejected nor reset. +//! +//! - `XCL_FFX_TRACE=1` (off): each upscale dispatch with `reset` set, the first four, and every +//! 120th is logged with what the upscaler is told (reset, jitter, motion vector scale, sizes, +//! frame time, camera) and its textures (object, format, size, state); every 120 dispatches a +//! line counts the resets since the last one. +//! - `XCL_FFX_RESET=1` (off): every upscale dispatch goes to the upscaler with `reset` set, so +//! it keeps no history (no ghosts, no previous shot; the picture is the current frame's, +//! upscaled, with its aliasing and dither). To tell the history apart from the other inputs. +//! +//! The dispatch description is `ffxDispatchDescUpscale` of the FidelityFX API (the console's has +//! the PC layout: HANDOFF "FSR4"), 432 bytes. + +#![allow(non_snake_case)] + +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::OnceLock; + +/// `FFX_API_DISPATCH_DESC_TYPE_UPSCALE` +const DISPATCH_UPSCALE: u64 = 0x0001_0001; +/// bytes of `ffxDispatchDescUpscale` +const DESC_BYTES: usize = 432; +/// its `reset` (a bool) +const RESET_AT: usize = 408; +/// its textures (`FfxApiResource`, 48 bytes each) and their names +const RESOURCES_AT: usize = 24; +const RESOURCE_NAMES: [&str; 7] = ["colour", "depth", "motion", "exposure", "reactive", "t&c", "output"]; + +static REAL_DISPATCH: AtomicUsize = AtomicUsize::new(0); +static DISPATCHES: AtomicU64 = AtomicU64::new(0); +static RESETS: AtomicU64 = AtomicU64::new(0); + +/// "1" on, anything else (or nothing) off. +fn switch(var: &str) -> bool { + std::env::var(var).is_ok_and(|v| v.trim() == "1") +} + +fn trace_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| switch("XCL_FFX_TRACE")) +} + +fn reset_always() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| switch("XCL_FFX_RESET")) +} + +/// Lowercase DLL key of the FidelityFX loader. +pub fn is_loader_dll(key: &str) -> bool { + key == "amd_fidelityfx_loader_xbox.dll" +} + +/// `real_addr` of `function` of the loader, or the wrapper standing in for it when a switch of +/// this module is on. +pub fn wrap(function: &str, real_addr: usize) -> usize { + if real_addr == 0 || function != "ffxDispatch" || !(trace_on() || reset_always()) { + return real_addr; + } + REAL_DISPATCH.store(real_addr, Ordering::Release); + crate::xlog_info!( + "FidelityFX: the title's ffxDispatch is watched (XCL_FFX_TRACE={}, XCL_FFX_RESET={})", + trace_on() as u8, + reset_always() as u8 + ); + ffxDispatch_hook as usize +} + +fn word(d: &[u8], at: usize) -> u32 { + u32::from_le_bytes(d[at..at + 4].try_into().unwrap()) +} + +fn float(d: &[u8], at: usize) -> f32 { + f32::from_bits(word(d, at)) +} + +/// Whether `d` (a whole description) asks for a reset. +fn reset_of(d: &[u8]) -> bool { + d[RESET_AT] != 0 +} + +/// `d` with `reset` set (the rest as it was: the chain `next` still names the title's own). +fn with_reset(d: &[u8; DESC_BYTES]) -> [u8; DESC_BYTES] { + let mut c = *d; + c[RESET_AT] = 1; + c +} + +/// One line of what an upscale dispatch is told. +fn describe(d: &[u8]) -> String { + let mut s = format!( + "reset {}, jitter ({:.3}, {:.3}), motion vector scale ({}, {}), render {}x{} → {}x{}, frame time {:.1} ms, pre-exposure {}, camera near {} far {} fov {:.3}, flags {:#x}", + reset_of(d) as u8, + float(d, 360), + float(d, 364), + float(d, 368), + float(d, 372), + word(d, 376), + word(d, 380), + word(d, 384), + word(d, 388), + float(d, 400), + float(d, 404), + float(d, 412), + float(d, 416), + float(d, 420), + word(d, 428) + ); + for (k, name) in RESOURCE_NAMES.iter().enumerate() { + let at = RESOURCES_AT + 48 * k; + let obj = u64::from_le_bytes(d[at..at + 8].try_into().unwrap()); + if obj == 0 { + continue; + } + // description: type, format, width, height, depth, mips, flags, usage; then the state + s += &format!("; {name} {obj:#x} fmt {} {}x{} state {:#x}", word(d, at + 12), word(d, at + 16), word(d, at + 20), word(d, at + 40)); + } + s +} + +type Dispatch = unsafe extern "C" fn(*mut *mut c_void, *const u8) -> u32; + +/// `ffxDispatch(context, desc)` of the title. +unsafe extern "C" fn ffxDispatch_hook(context: *mut *mut c_void, desc: *const u8) -> u32 { + let real: Dispatch = std::mem::transmute(REAL_DISPATCH.load(Ordering::Acquire)); + if desc.is_null() || !crate::gpu::shader::readable(desc as usize, DESC_BYTES) || (desc as *const u64).read_unaligned() != DISPATCH_UPSCALE { + return real(context, desc); + } + let d: [u8; DESC_BYTES] = (desc as *const [u8; DESC_BYTES]).read_unaligned(); + let n = DISPATCHES.fetch_add(1, Ordering::Relaxed); + let reset = reset_of(&d); + if reset { + RESETS.fetch_add(1, Ordering::Relaxed); + } + if trace_on() { + if reset || n < 4 || n % 120 == 0 { + crate::xlog_info!("FidelityFX: upscale #{n} at present {}: {}", crate::hle::d3d12x::present::presents(), describe(&d)); + } + if n % 120 == 119 { + crate::xlog_info!("FidelityFX: {} upscales, {} of them with reset", n + 1, RESETS.load(Ordering::Relaxed)); + } + } + if reset_always() && !reset { + let c = with_reset(&d); + return real(context, c.as_ptr()); + } + real(context, desc) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn desc(reset: bool) -> [u8; DESC_BYTES] { + let mut d = [0u8; DESC_BYTES]; + d[0..8].copy_from_slice(&DISPATCH_UPSCALE.to_le_bytes()); + d[8..16].copy_from_slice(&0x1234_5678u64.to_le_bytes()); + d[376..392].copy_from_slice(&[1280u32, 720, 1920, 1080].map(u32::to_le_bytes).concat()); + d[RESET_AT] = reset as u8; + d + } + + #[test] + fn a_forced_reset_sets_only_the_reset_byte() { + let d = desc(false); + assert!(!reset_of(&d)); + let c = with_reset(&d); + assert!(reset_of(&c)); + let changed: Vec = (0..DESC_BYTES).filter(|&i| c[i] != d[i]).collect(); + assert_eq!(changed, vec![RESET_AT], "the chain pointer and the rest stay the title's"); + } + + #[test] + fn the_description_line_names_sizes_and_reset() { + let mut d = desc(true); + // colour: an object, format 10, 1280x720, state 4 + d[24..32].copy_from_slice(&0xabcdu64.to_le_bytes()); + d[36..40].copy_from_slice(&10u32.to_le_bytes()); + d[40..48].copy_from_slice(&[1280u32, 720].map(u32::to_le_bytes).concat()); + d[64..68].copy_from_slice(&4u32.to_le_bytes()); + let s = describe(&d); + assert!(s.starts_with("reset 1,"), "{s}"); + assert!(s.contains("render 1280x720 → 1920x1080"), "{s}"); + assert!(s.contains("colour 0xabcd fmt 10 1280x720 state 0x4"), "{s}"); + assert!(!s.contains("depth"), "textures the title left out are not named: {s}"); + } + + #[test] + fn only_the_loaders_dispatch_is_wrapped() { + assert!(is_loader_dll("amd_fidelityfx_loader_xbox.dll")); + assert!(!is_loader_dll("amd_fidelityfx_upscaler_xbox.dll")); + // no switch in the test environment: the title's own address + assert_eq!(wrap("ffxCreateContext", 0x1000), 0x1000); + } +} diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index a29d3c4498..cada87eb43 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -108,6 +108,9 @@ pub fn exports() -> Vec<(&'static str, usize)> { pub const MEM_GRAPHICS: u32 = 0x1000_0000; mod placeholders; +pub mod alias; +pub mod guards; +mod sections; pub mod lazy; pub const MEM_TITLE: u32 = 0x4000_0000; const STD_ALLOC_MASK: u32 = 0x1000 | 0x2000 | 0x8_0000 | 0x10_0000 | 0x20_0000 | 0x100_0000; @@ -216,6 +219,7 @@ pub mod mirrors { if t & PAGES_64K != PAGES_64K || t & 0x1000 != 0 { return false; } + crate::hle::d3d12x::sparse::invalidate_source_range(base, size); let mut s = STATE.lock().unwrap(); if p & GRAPHICS_NOACCESS != 0 && p & 0xFF == super::mem::PAGE_NOACCESS { if let Some(cpu) = unpaired_cpu(&s, size) { @@ -498,6 +502,17 @@ pub mod mirrors { PAGES.write().unwrap_or_else(|e| e.into_inner()) } + /// The mapped backing CPU address for a GPU-view address `va`: `Some(Some(addr))` if mapped, + /// `Some(None)` if explicitly unmapped, `None` if `CopyPageMappingsBatchX` never touched it. + pub fn mapped_source(va: usize) -> Option> { + if MAPPED.load(Ordering::Acquire) == 0 { + return None; + } + let off = va & (PAGE - 1); + let e = *read_pages().shown.get(&(va - off))?; + Some((e.at != 0).then(|| e.at + off)) + } + /// What one `apply_batches` call did, in 64 KiB pages. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Mapped { @@ -527,6 +542,11 @@ pub mod mirrors { .into_iter() .map(|(g, to)| { let to = to.map(|pool| { + if super::alias::enabled() { + let page = super::alias::page_at(pool).unwrap_or(0); + let (at, home) = super::alias::backing(page).unwrap_or((0, false)); + return (page, at, at != 0 && (home || super::freeing_is_seen(at))); + } let page = away.as_ref().and_then(|a| a.title.get(&pool).copied()).unwrap_or(0); let (at, home) = if page != 0 { super::place_of(away.as_ref(), page) } else { (0, false) }; (page, at, at != 0 && (home || super::freeing_is_seen(at))) @@ -940,6 +960,28 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: u.view_release(q); } } + if alias::enabled() && !addr.is_null() && t & 0x1000 != 0 && alias::in_space(addr as usize) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("VirtualAlloc: a commit at {addr:p} in a reservation of 64 KiB pages that holds physical pages (XCL_PAGE_ALIAS) – refused")); + fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); + return std::ptr::null_mut(); + } + // Keep GPU write-combined 64 KiB reservations (`MEM_GRAPHICS` + `PAGE_WRITECOMBINE`, e.g. + // a title's GPU UAV/PreSkin buffer heap) in sparse UMA so `CreatePlacedResourceX` buffers + // placed in them register in `UMA_BUFFERS` and get valid shader V# descriptors. + if alias::enabled() + && addr.is_null() + && t & 0x2000 != 0 + && t & 0x1000 == 0 + && t & MEM_64K_PAGES == MEM_64K_PAGES + && !(t & MEM_GRAPHICS != 0 && p & mem::PAGE_WRITECOMBINE != 0) + { + if let Some(q) = alias::reserve_space(size) { + mirrors::reserved(q, size, t, p); + trace_mem("VirtualAlloc (64K pages, physical page space)", 0, size, t as u64, p, q); + return q as *mut c_void; + } + } // the title's own reservations of 64 KiB pages: in a sparse window, so the GPU sees them. // Skip CPU-inaccessible GPU-view mirror reservations (`PAGE_NOACCESS | PAGE_GRAPHICS_NOACCESS`): // their pixels live in the paired CPU view (`mirrors::source`), so putting them in sparse VA @@ -1199,8 +1241,19 @@ unsafe fn source_part_going(part: Option<(usize, usize)>, release: bool, os: pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32) -> BOOL { let _cost = super::api_cost::time(super::api_cost::Call::Memory); if let Some(ok) = placeholders::free(addr, size, t) { + if ok != 0 { + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); + } return ok; } + if alias::enabled() { + if let Some(ok) = alias::free_space(addr as usize, size, t) { + if ok { + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); + } + return ok as BOOL; + } + } // 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)) { @@ -1282,6 +1335,9 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 mirrors::released(addr as usize); } let ok = source_part_going(part, release, || mem::VirtualFree(addr, size, t)); + if ok != 0 { + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, whole); + } if ok != 0 && t & 0x8000 != 0 { let released = GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)); if let Some(len) = released { @@ -1318,9 +1374,14 @@ pub unsafe extern "system" fn VirtualFreeEx(proc_: HANDLE, addr: *mut c_void, si if own_process(proc_) { let a = addr as usize; // (a graphics reservation's decommits too: one may be a paired CPU view, `source_going`) - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(a) || u.contains(a) || u.is_view(a)) || in_graphics_reservation(a) { + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(a) || u.contains(a) || u.is_view(a)) || in_graphics_reservation(a) || alias::in_space(a) { return VirtualFree(addr, size, t); } + let ok = mem::VirtualFreeEx(proc_, addr, size, t); + if ok != 0 { + crate::hle::d3d12x::sparse::invalidate_source_range(a, size); + } + return ok; } mem::VirtualFreeEx(proc_, addr, size, t) } @@ -1337,10 +1398,15 @@ pub unsafe extern "system" fn VirtualProtect(addr: *const c_void, size: usize, p let writable = read_write(protection); if !writable { note_protection(addr, size, protection); + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); } let ok = mem::VirtualProtect(addr, size, protection, old); - if ok != 0 && writable { - note_protection(addr, size, protection); + if ok != 0 { + if writable { + note_protection(addr, size, protection); + } else { + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); + } } ok } @@ -1351,10 +1417,15 @@ pub unsafe extern "system" fn VirtualProtectEx(proc_: HANDLE, addr: *const c_voi let writable = read_write(protection); if own && !writable { note_protection(addr, size, protection); + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); } let ok = mem::VirtualProtectEx(proc_, addr, size, protection, old); - if ok != 0 && own && writable { - note_protection(addr, size, protection); + if ok != 0 && own { + if writable { + note_protection(addr, size, protection); + } else { + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); + } } ok } @@ -1391,6 +1462,9 @@ unsafe fn aligned_heap_alloc(size: usize, align: usize) -> *mut c_void { fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); return std::ptr::null_mut(); } + if crate::heap_count::counting() { + crate::heap_count::title_added(total); + } let aligned = (raw + 16 + align - 1) & !(align - 1); *((aligned - 8) as *mut usize) = raw; aligned as *mut c_void @@ -1401,14 +1475,20 @@ unsafe fn aligned_heap_free(p: *mut c_void) { return; } let raw = *((p as usize - 8) as *const usize); + if crate::heap_count::counting() { + let size = mem::HeapSize(mem::GetProcessHeap(), 0, raw as *const c_void); + if size != usize::MAX { + crate::heap_count::title_removed(size); + } + } mem::HeapFree(mem::GetProcessHeap(), 0, raw as *const c_void); } /// Rounded byte size and alignment for an XMem graphics allocation honoring `page_size` -/// (`2` = `XALLOC_PAGESIZE_4MB`, otherwise 64 KiB sparse tile grain) and `alignment`. +/// (`2` = 2 MiB pages, otherwise 64 KiB sparse tile grain) and `alignment`. fn xmem_graphics_layout(size: usize, a: XAllocAttrs) -> Option<(usize, usize)> { let page_grain = match a.page_size { - 2 => 4 << 20, // XALLOC_PAGESIZE_4MB + 2 => 2 << 20, _ => crate::gpu::uma::GRAIN, }; let align = (1usize << a.alignment.min(usize::BITS - 2)).max(page_grain); @@ -1493,7 +1573,7 @@ pub unsafe fn adopt_title_hooks(main: &crate::modules::MappedModule) { /// asserts that they start there. pub const D3D_DESCRIPTOR_HEAP: u64 = 4 | 1 << 14 | 0x80 << 16 | 16 << 24 | 1 << 29; -/// XALLOC_ATTRIBUTES of a display target's memory: 4 MiB pages (the retail game's hook for its back buffers +/// XALLOC_ATTRIBUTES of a display target's memory: 2 MiB pages (the retail game's hook for its back buffers /// takes every request with them), allocator 0x80, graphics memory. pub const D3D_DISPLAY_TARGET: u64 = 2 << 14 | 0x80 << 16 | 16 << 24 | 1 << 29; @@ -1514,16 +1594,32 @@ pub unsafe fn runtime_free(p: usize, attrs: u64) { } } -/// `void* XMemVirtualAlloc(void* address, SIZE_T size, DWORD type, XALLOC_ATTRIBUTES attributes, -/// DWORD protect)`: VirtualAlloc with an allocator's attributes – a graphics memory type is -/// GPU-visible memory (as MEM_GRAPHICS: sparse VRAM pool). -pub unsafe extern "system" fn XMemVirtualAlloc(addr: *const c_void, size: usize, t: u32, attrs: u64, p: u32) -> *mut c_void { - let a = XAllocAttrs::decode(attrs); - let mut t = if a.memory_type != 0 { t | MEM_GRAPHICS } else { t }; - if a.memory_type != 0 && a.page_size == 2 { - t |= 0x8000_0000; +/// Map `XMemVirtualAlloc`'s `XMemFlags` (bit 1 marks graphics memory: `XMEM_GRAPHICS = 0x3`, +/// `XMEM_GRAPHICS_32BIT_ADDRESS = 0x7`; also tolerating legacy `XALLOC_ATTRIBUTES` with +/// `memory_type != 0` in bits 29..=32) into `VirtualAlloc` allocation flags. +/// +/// A commit with a GPU-accessible protection (`p`) and only the `XMemFlags` graphics bit is one of +/// the title's GPU heaps: it gets no `MEM_GRAPHICS`, so `VirtualAlloc` puts it in the coherent +/// window (one copy, as before the bit was decoded). With `MEM_GRAPHICS` a retail title's 4.4 GB +/// of heaps went to the sparse windows (as much video memory again, and the CPU's copy) while the +/// coherent window, sized for them from the last run, was committed empty: 25.4 GB peak commit in +/// a 60 s smoke run, 14.5 GB with the heaps in the window. +fn xmem_virtual_alloc_flags(t: u32, xmem_flags: u64, p: u32) -> u32 { + let legacy = XAllocAttrs::decode(xmem_flags); + let heap = t & 0x1000 != 0 && p & PAGE_GRAPHICS_GPU_ACCESS != 0; + let is_graphics = (xmem_flags & 0x2 != 0 && !heap) || legacy.memory_type != 0; + let mut out = if is_graphics { t | MEM_GRAPHICS } else { t }; + if legacy.memory_type != 0 && legacy.page_size == 2 { + out |= 0x8000_0000; } - VirtualAlloc(addr, size, t, p) + out +} + +/// `void* XMemVirtualAlloc(void* address, SIZE_T size, DWORD type, ULONGLONG xmem_flags, +/// DWORD protect)`: VirtualAlloc with Xbox memory flags – graphics flags route to GPU-visible +/// memory (`MEM_GRAPHICS`). +pub unsafe extern "system" fn XMemVirtualAlloc(addr: *const c_void, size: usize, t: u32, attrs: u64, p: u32) -> *mut c_void { + VirtualAlloc(addr, size, xmem_virtual_alloc_flags(t, attrs, p), p) } /// Fast-path `VirtualQuery` / `VirtualQueryEx` / `XMemVirtualQuery` for a committed coherent @@ -1687,7 +1783,7 @@ pub struct TitleMemoryStatusT { pub title_page_table_used: u64, } -fn process_private_bytes() -> u64 { +pub(crate) fn process_private_bytes() -> u64 { use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; unsafe { let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); @@ -1814,6 +1910,71 @@ pub mod pagelog { } } +/// A measurement: the addresses pages were moved away from (`move_away`: a page the title maps +/// at a second address while it is still mapped at the first is copied there, and the first +/// address is given up). On the console both addresses show the page until the title unmaps one. +/// So: how long after a move does the title unmap or map the address the page left – at once (it +/// moves pages), or not at all (it keeps two views of a page, and here the first is gone)? +pub mod given_up { + use std::collections::HashMap; + use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::Mutex; + use std::time::Instant; + + /// address the page left → (page, where it went, when, in the coherent window) + static LEFT: Mutex>> = Mutex::new(None); + static MOVES: AtomicU64 = AtomicU64::new(0); + /// the title's next call at such an address: unmapped it (page 0) within 1 ms, 100 ms, 10 s, + /// later; mapped another page there within the same steps + static NEXT: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; + + pub fn moved(old: usize, at: usize, page: usize) { + let coherent = crate::gpu::uma::get().is_some_and(|u| u.is_committed(old)); + let n = MOVES.fetch_add(1, Ordering::Relaxed) + 1; + let mut g = LEFT.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + m.insert(old, (page, at, Instant::now(), coherent)); + if n.is_power_of_two() || n % 8192 == 0 { + let now = Instant::now(); + let ages: Vec = m.values().map(|v| now.saturating_duration_since(v.2).as_millis()).collect(); + let old_ones = ages.iter().filter(|&&a| a >= 1000).count(); + let in_coherent = m.values().filter(|v| v.3).count(); + let c: Vec = NEXT.iter().map(|c| c.load(Ordering::Relaxed)).collect(); + crate::xlog_info!( + "physical pages: {n} pages moved to a second address so far; the address they left was unmapped by the title {} times (within 1 ms {}, 100 ms {}, 10 s {}, later {}) and given another page {} times (within 1 ms {}, 100 ms {}, 10 s {}, later {}); {} such addresses the title has not touched since ({old_ones} for a second or more, the oldest {} s; {in_coherent} in the coherent window, where the old bytes stay readable)", + c[0] + c[1] + c[2] + c[3], c[0], c[1], c[2], c[3], + c[4] + c[5] + c[6] + c[7], c[4], c[5], c[6], c[7], + m.len(), + ages.iter().max().copied().unwrap_or(0) / 1000 + ); + } + } + + /// The title maps `page` (0: unmaps) at `at`. + pub fn title_maps(at: usize, page: usize) { + let mut g = LEFT.lock().unwrap_or_else(|e| e.into_inner()); + let Some((_, _, when, _)) = g.as_mut().and_then(|m| m.remove(&at)) else { return }; + let ms = when.elapsed().as_millis(); + let step = if ms < 1 { 0 } else if ms < 100 { 1 } else if ms < 10_000 { 2 } else { 3 }; + NEXT[step + if page == 0 { 0 } else { 4 }].fetch_add(1, Ordering::Relaxed); + } + + /// For a crash report: whether `addr` is in a page-sized range a page was moved away from + /// and the title has not mapped or unmapped since. + pub fn describe(addr: usize) -> String { + let Ok(g) = LEFT.try_lock() else { return String::new() }; + let Some(m) = g.as_ref() else { return String::new() }; + match m.get(&(addr & !(super::PHYS_PAGE - 1))) { + Some(&(page, to, when, coherent)) => format!( + "page {page:#x} was moved away from here to {to:#x} {} ms ago, and the title has not unmapped this address since{}", + when.elapsed().as_millis(), + if coherent { " (the coherent window: the old bytes stay readable here)" } else { "" } + ), + None => String::new(), + } + } +} + /// Size of one console physical page (64 KiB). pub const PHYS_PAGE_SIZE: usize = PHYS_PAGE; @@ -1852,9 +2013,14 @@ static PHYS_BLOCKS: std::sync::Mutex, at: std::collections::BTreeMap, page: std::collections::HashMap, /// homes in a sparse window whose pages went away in this call, given back at its end in @@ -1890,9 +2056,21 @@ fn forget_title_mappings(base: usize, len: usize) { /// Whether a physical page is mapped at the page holding `va` away from its home – committed /// or not yet (`lazy`: a page never used is committed at its first access). pub fn physical_page_at(va: usize) -> bool { + if alias::enabled() { return alias::physical_page_at(va); } AWAY.lock().unwrap().as_ref().is_some_and(|a| a.at.contains_key(&(va & !(PHYS_PAGE - 1)))) } +/// 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> { + if alias::enabled() { return (0..n).map(|i| va.checked_add(i.checked_mul(PHYS_PAGE)?).and_then(alias::page_at)).collect(); } + let g = AWAY.lock().unwrap(); + let Some(a) = g.as_ref() else { return vec![None; n] }; + (0..n).map(|i| va.checked_add(i * PHYS_PAGE).and_then(|at| a.at.get(&at).copied())).collect() +} + /// 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); @@ -1968,6 +2146,7 @@ fn page_home(page: usize) -> Option { /// Whether every page of `pages` (at least one) is a physical page allocated now. pub fn physical_pages_live(pages: &[usize]) -> bool { + if alias::enabled() { return !pages.is_empty() && pages.iter().all(|&p| alias::page_live(p)); } !pages.is_empty() && pages.iter().all(|&p| page_home(p).is_some()) } @@ -1979,7 +2158,7 @@ fn lazy_home(home: usize) -> bool { /// Resolve the live virtual addresses of the physical pages covering `offset..offset+len`. /// Caller must hold `AWAY`. -unsafe fn resolve_physical_pages(away: Option<&Away>, pages: &[usize], offset: usize, len: usize) -> Option> { +unsafe fn resolve_physical_pages(away: &mut Away, pages: &[usize], offset: usize, len: usize) -> Option> { if offset >= PHYS_PAGE { return None; } @@ -1991,9 +2170,9 @@ unsafe fn resolve_physical_pages(away: Option<&Away>, pages: &[usize], offset: u let mut addrs = Vec::with_capacity(need); for &p in &pages[..need] { let home = page_home(p)?; - let addr = match away.and_then(|a| a.page.get(&p).copied()) { + let addr = match away.page.get(&p).copied() { Some(at) => at, - None => home_again(home)?, + None => home_again(home, p, away)?, }; addrs.push(addr); } @@ -2004,11 +2183,12 @@ 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; } - let g = AWAY.lock().unwrap(); - let Some(addrs) = resolve_physical_pages(g.as_ref(), pages, offset, dst.len()) else { return false }; + let mut g = AWAY.lock().unwrap(); + let Some(addrs) = resolve_physical_pages(g.get_or_insert_with(Away::default), pages, offset, dst.len()) else { return false }; let mut done = 0; let mut page_off = offset; for addr in addrs { @@ -2023,11 +2203,12 @@ 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; } - let g = AWAY.lock().unwrap(); - let Some(addrs) = resolve_physical_pages(g.as_ref(), pages, offset, src.len()) else { return false }; + let mut g = AWAY.lock().unwrap(); + let Some(addrs) = resolve_physical_pages(g.get_or_insert_with(Away::default), pages, offset, src.len()) else { return false }; let mut done = 0; let mut page_off = offset; for addr in addrs { @@ -2120,14 +2301,31 @@ unsafe fn give_back_homes(away: &mut Away) { } } +/// `XCL_DEFER_PRIVATE_HOME_TILES`: on by default (`=0` turns it off), off in unit tests unless +/// they ask for it. +fn defer_private_home_tiles() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_DEFER_PRIVATE_HOME_TILES").map_or(!cfg!(test), |v| v.trim() == "1")) +} + +/// Once its home was exposed, later recommits keep the existing GPU-visible behavior. +fn private_home(away: &mut Away, page: usize, enabled: bool) -> bool { + if enabled && away.sparse_homes.get(&page) != Some(&SparseHome::Exposed) { + away.sparse_homes.insert(page, SparseHome::CpuOnly); + true + } else { + false + } +} + /// The page's home, committed again if `move_home_away` gave it back (None: it could not be). -unsafe fn home_again(home: usize) -> Option { +unsafe fn home_again(home: usize, page: usize, away: &mut Away) -> Option { if lazy_home(home) && !committed_page(home) { if mem::VirtualAlloc(home as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { crate::xlog_warn!("physical page: its home {home:#x} could not be committed again"); return None; } - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(home)) { + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(home)) && !private_home(away, page, defer_private_home_tiles()) { crate::hle::d3d12x::sparse::committed(home, PHYS_PAGE); } } @@ -2145,12 +2343,11 @@ const HOMES_AHEAD: usize = 1024; /// already (another page may be mapped at that address, given up in this call), or that cannot /// be, is left to `home_again`. unsafe fn commit_homes_ahead(away: &mut Away, ats: impl Iterator) { - let mut homes: Vec = ats - .filter_map(|at| away.at.get(&at).filter(|_| !lazy::is_marked(at)).and_then(|&p| page_home(p))) - .filter(|&h| lazy_home(h) && !away.gone.contains(&h)) + let home_pages: std::collections::BTreeMap = ats + .filter_map(|at| away.at.get(&at).filter(|_| !lazy::is_marked(at)).and_then(|&p| page_home(p).map(|h| (h, p)))) + .filter(|&(h, _)| lazy_home(h) && !away.gone.contains(&h)) .collect(); - homes.sort_unstable(); - homes.dedup(); + let homes: Vec = home_pages.keys().copied().collect(); let mut i = 0; while i < homes.len() { let start = homes[i]; @@ -2174,7 +2371,13 @@ unsafe fn commit_homes_ahead(away: &mut Away, ats: impl Iterator) && !mem::VirtualAlloc(first as *const c_void, last - first, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(first)) { - crate::hle::d3d12x::sparse::committed(first, last - first); + let mut exposed = SparseRun::new(crate::hle::d3d12x::sparse::committed); + for at in (first..last).step_by(PHYS_PAGE) { + if !private_home(away, home_pages[&at], defer_private_home_tiles()) { + exposed.add(at); + } + } + exposed.flush(); } #[cfg(test)] tests::HOME_RUNS.with(|c| c.set(c.get() + 1)); @@ -2186,23 +2389,40 @@ unsafe fn commit_homes_ahead(away: &mut Away, ats: impl Iterator) } /// `n` pages from `home` committed (a sparse home is only reserved until it is used). -unsafe fn commit_homes(home: usize, n: usize) -> bool { - let Some(u) = crate::gpu::uma::get() else { return false }; +unsafe fn commit_homes(home: usize, pages: &[usize], away: &mut Away) -> Option> { + let Some(u) = crate::gpu::uma::get() else { return None }; if !lazy_home(home) { - return true; + return Some(Vec::new()); } + let n = pages.len(); let len = n * PHYS_PAGE; - if committed_range(home, len) { - return true; - } - if mem::VirtualAlloc(home as *const c_void, len, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { + let ready = committed_range(home, len); + if !ready && mem::VirtualAlloc(home as *const c_void, len, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { crate::xlog_warn!("physical pages: {n} at their home {home:#x} could not be committed"); - return false; + return None; } + let mut replay = Vec::new(); if u.is_sparse(home) { - crate::hle::d3d12x::sparse::committed(home, len); + let private = |p: &usize| away.sparse_homes.get(p) == Some(&SparseHome::CpuOnly); + let has_private = defer_private_home_tiles() && pages.iter().any(private); + if !ready || has_private { + crate::hle::d3d12x::sparse::committed(home, len); + } + if has_private { + let mut at = home; + for run in pages.chunk_by(|a, b| private(a) == private(b)) { + let bytes = run.len() * PHYS_PAGE; + if private(&run[0]) { + replay.push((at, bytes)); + } + at += bytes; + } + } + if defer_private_home_tiles() { + away.sparse_homes.extend(pages.iter().map(|&p| (p, SparseHome::Exposed))); + } } - true + Some(replay) } /// Whether all of `[a, a + len)` is committed: one VirtualQuery per run of pages in one state @@ -2291,7 +2511,7 @@ unsafe fn unmap_away(away: &mut Away, at: usize, committed: &std::ops::Range *mut c_void { + if va.is_null() || n == 0 || n.checked_mul(PHYS_PAGE).and_then(|len| (va as usize).checked_add(len)).is_none() { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return std::ptr::null_mut(); + } + let empty; + let pages = if arr.is_null() { empty = vec![0; n]; empty.as_slice() } else { std::slice::from_raw_parts(arr, n) }; + if alias::map(va as usize, pages) { + note_mapping_range(va as usize, n * PHYS_PAGE); + return va; + } + std::ptr::null_mut() +} + /// `MapTitlePhysicalPages` with `AWAY` held; the homes it moves away are given back by the /// caller (`give_back_homes`). unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) -> *mut c_void { @@ -2506,10 +2761,10 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) fnd::SetLastError(fnd::ERROR_NOT_SUPPORTED); // scattered pages need an address return std::ptr::null_mut(); }; - if !commit_homes(home, n) { + let Some(replay) = commit_homes(home, &pages, away) else { fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); return std::ptr::null_mut(); - } + }; // (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() { @@ -2520,6 +2775,12 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) unmap_away(away, at, &(home..home + n * PHYS_PAGE)); } } + // After copies home: a prior write-watch look may have consumed the storage writes + // while these pages had no GPU tiles. Queue their bytes even when known-write hints + // are disabled, and even when the next submit skips its ordinary write-watch look. + for (at, bytes) in replay { + crate::hle::d3d12x::title_textures::rescan_cpu_backing(at, bytes); + } return home as *mut c_void; } let base = va as usize; @@ -2537,6 +2798,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) let mut sparse_run = SparseRun::new(crate::hle::d3d12x::sparse::committed); for (i, &p) in pages.iter().enumerate() { let at = base + i * PHYS_PAGE; + given_up::title_maps(at, p); // what was mapped at `at` goes; the new page is written down once it is in place away.title.remove(&at); if unmap_away(away, at, &(0..0)) { @@ -2648,6 +2910,9 @@ pub unsafe extern "system" fn XMemMapPhysicalPagesScatter(addresses: *const *mut } let mut g = AWAY.lock().unwrap(); let away = g.get_or_insert_with(Away::default); + if alias::enabled() { + return (0..n).all(|i| !map_aliased(*addresses.add(i), 1, if pages.is_null() { std::ptr::null_mut() } else { pages.add(i).cast() }).is_null()) as BOOL; + } // no page array: page 0 (unmap) for every address let ok = (0..n).all(|i| { // a part of the call that only unmaps @@ -3035,11 +3300,31 @@ pub unsafe extern "system" fn RegCloseKey(key: usize) -> u32 { const LOAD_AS_DATA: u32 = 0x2 | 0x20 | 0x40; // DATAFILE | IMAGE_RESOURCE | DATAFILE_EXCLUSIVE +/// The console's FidelityFX upscaler, which the title's FidelityFX loader loads by name. +const FFX_UPSCALER_DLL: &str = "amd_fidelityfx_upscaler_xbox.dll"; + +/// `XCL_FFX_UPSCALER=0`: the title's FidelityFX loader finds no upscaler (LoadLibrary of +/// `amd_fidelityfx_upscaler_xbox.dll` fails as for a missing DLL), and the title upscales its own +/// way. With the console's FSR the people left copies along their path and the last shot showed +/// through a camera cut, though the title asked for a reset at the cuts (`ffx.rs`). Whiplash (a +/// VIctory descendant, GPL-3.0-or-later) never loads that DLL either: its loader refuses host DLLs +/// outside its policy, and the title runs without it. On (loaded) unless set to `0`. +fn ffx_upscaler_refused(name: &str, switch: Option<&str>) -> bool { + switch.is_some_and(|v| v.trim() == "0") + && name.rsplit(['\\', '/']).next().is_some_and(|file| file.eq_ignore_ascii_case(FFX_UPSCALER_DLL)) +} + fn load_library_impl(name: Option) -> usize { let Some(name) = name else { unsafe { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER) }; return 0; }; + static UPSCALER: std::sync::OnceLock> = std::sync::OnceLock::new(); + if ffx_upscaler_refused(&name, UPSCALER.get_or_init(|| std::env::var("XCL_FFX_UPSCALER").ok()).as_deref()) { + crate::xlog_info!("LoadLibrary({name}) → NULL: the console's FidelityFX upscaler is left out (XCL_FFX_UPSCALER=0)"); + unsafe { fnd::SetLastError(fnd::ERROR_MOD_NOT_FOUND) }; + return 0; + } match resolver::load_library(&name) { Some(h) => { crate::xlog_debug!("LoadLibrary({name}) → {h:#x}"); @@ -3283,6 +3568,31 @@ pub unsafe extern "system" fn DisableThreadLibraryCalls(h: usize) -> BOOL { mod tests { use super::*; + /// `XCL_FFX_UPSCALER=0` refuses the console's FidelityFX upscaler by its file name (any case, + /// any folder) and nothing else; unset or any other value loads it as before. + #[test] + fn the_ffx_upscaler_is_refused_only_with_the_switch_off() { + for name in ["amd_fidelityfx_upscaler_xbox.dll", "AMD_FidelityFX_Upscaler_Xbox.DLL", "G:\\amd_fidelityfx_upscaler_xbox.dll", "d:/x/amd_fidelityfx_upscaler_xbox.dll"] { + assert!(ffx_upscaler_refused(name, Some("0")), "{name}"); + assert!(!ffx_upscaler_refused(name, None), "{name} unset"); + assert!(!ffx_upscaler_refused(name, Some("1")), "{name} on"); + } + for name in ["amd_fidelityfx_loader_xbox.dll", "amd_fidelityfx_upscaler_xbox.dll.bak", "xamd_fidelityfx_upscaler_xbox.dll", "Bink2Scarlett.dll"] { + assert!(!ffx_upscaler_refused(name, Some("0")), "{name}"); + } + } + + #[test] + fn exposed_physical_home_is_never_made_private_again() { + let mut away = Away::default(); + assert!(!private_home(&mut away, 7, false)); + assert!(away.sparse_homes.is_empty()); + assert!(private_home(&mut away, 7, true)); + away.sparse_homes.insert(7, SparseHome::Exposed); + assert!(!private_home(&mut away, 7, true), "a later recommit keeps explicit home exposure"); + assert!(private_home(&mut away, 8, true), "another private page is independent"); + } + /// `XCL_COHERENT_HEAPS=sparse[:N]`: which heaps go to the sparse windows #[test] fn sparse_heaps_setting() { @@ -3511,16 +3821,33 @@ mod tests { assert_eq!(sanitize_alloc_type(MEM_TITLE), 0x3000); assert_eq!(sanitize_protect(0x1000_0004), 0x04); assert_eq!(sanitize_protect(0x2000_0000), mem::PAGE_READWRITE); - // PAGE_NOCACHE (0x200), PAGE_WRITECOMBINE (0x400) and PAGE_GRAPHICS_* bits go; PAGE_GUARD (0x100) stays + // Strip PAGE_NOCACHE (0x200), PAGE_WRITECOMBINE (0x400), and PAGE_GRAPHICS_* bits; keep PAGE_GUARD (0x100) assert_eq!(sanitize_protect(0x2404), mem::PAGE_READWRITE); assert_eq!(sanitize_protect(0x1204), mem::PAGE_READWRITE); assert_eq!(sanitize_protect(mem::PAGE_READWRITE | mem::PAGE_GUARD), mem::PAGE_READWRITE | mem::PAGE_GUARD); - // PAGE_GRAPHICS_NOACCESS alone is not GPU-accessible; READONLY / READWRITE / COHERENT are + // XMemVirtualAlloc XMemFlags decoding: XMEM_CPU (0x1) stays CPU-only, XMEM_GRAPHICS (0x3) / 32BIT (0x7) set MEM_GRAPHICS + assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x1, 0x04), 0x3000); + assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x11, 0x04), 0x3000); + assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x3, 0x04), 0x3000 | MEM_GRAPHICS); + assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x7, 0x04), 0x3000 | MEM_GRAPHICS); + assert_eq!(xmem_virtual_alloc_flags(0x2040_6000, 0x27, 0x04), 0x2040_6000 | MEM_GRAPHICS); + // a GPU heap (a commit with a GPU-accessible protection) stays out of MEM_GRAPHICS: the coherent window + assert_eq!(xmem_virtual_alloc_flags(0x2000_3000, 0x3, 0x2404), 0x2000_3000); + assert_eq!(xmem_virtual_alloc_flags(0x2000_3000, 0x3, 0x2_2004), 0x2000_3000); + // reserving it, or committing with PAGE_GRAPHICS_NOACCESS only, still does + assert_eq!(xmem_virtual_alloc_flags(0x2000_2000, 0x3, 0x2404), 0x2000_2000 | MEM_GRAPHICS); + assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x3, 0x801), 0x3000 | MEM_GRAPHICS); + // PAGE_GRAPHICS_NOACCESS alone is not GPU-accessible, whereas READONLY/READWRITE/COHERENT are let null = std::ptr::null(); assert!(!gpu_visible_fallback(null, 0x2000, mem::PAGE_READWRITE | 0x800)); assert!(gpu_visible_fallback(null, 0x2000, mem::PAGE_READWRITE | 0x1000)); assert!(gpu_visible_fallback(null, 0x2000, mem::PAGE_READWRITE | 0x2000)); assert!(gpu_visible_fallback(null, 0x2000, mem::PAGE_READWRITE | 0x20000)); + // Device memory budgets for Anaconda (Series X) and Lockhart (Series S) + let mut cfg = crate::config::Config::default(); + assert_eq!(cfg.title_memory_budget_mb(), 13_824); + assert_eq!(cfg.apply_device_type_override("lockhart"), Some("lockhart")); + assert_eq!(cfg.title_memory_budget_mb(), 8_192); unsafe { let p = VirtualAlloc(std::ptr::null(), 0x10000, MEM_GRAPHICS | MEM_TITLE | 0x3000, 0x0400_0004); assert!(!p.is_null()); @@ -3564,6 +3891,60 @@ mod tests { } } + #[test] + fn xmem_graphics_page_size_two_uses_two_mib_grain() { + const PAGE: usize = 2 << 20; + let attrs = XAllocAttrs::decode((2 << 14) | (1 << 29)); + for (size, rounded) in [(0, PAGE), (1, PAGE), (PAGE - 1, PAGE), (PAGE, PAGE), (PAGE + 1, 2 * PAGE), (2 * PAGE, 2 * PAGE)] { + assert_eq!(xmem_graphics_layout(size, attrs), Some((rounded, PAGE)), "size {size}"); + } + let larger_alignment = XAllocAttrs::decode((2 << 14) | (23 << 24) | (1 << 29)); + assert_eq!(xmem_graphics_layout(1, larger_alignment), Some((PAGE, 8 << 20)), "alignment does not enlarge the allocation's page grain"); + } + + #[test] + fn xmem_graphics_page_grain_preserves_other_codes_and_checks_overflow() { + const PAGE: usize = 2 << 20; + // Code 3 is reserved; keep its existing fallback rather than defining a new contract here. + for code in [0, 1, 3] { + let attrs = XAllocAttrs::decode((code << 14) | (1 << 29)); + assert_eq!(xmem_graphics_layout(0x1_0001, attrs), Some((0x2_0000, 0x1_0000))); + assert!(xmem_graphics_layout(usize::MAX, attrs).is_none()); + } + let attrs = XAllocAttrs::decode((2 << 14) | (1 << 29)); + let largest = usize::MAX & !(PAGE - 1); + assert_eq!(xmem_graphics_layout(largest, attrs), Some((largest, PAGE))); + assert!(xmem_graphics_layout(largest + 1, attrs).is_none()); + assert!(xmem_graphics_layout(usize::MAX, attrs).is_none()); + } + + #[test] + fn xmem_two_mib_layout_accounts_and_releases_owned_memory() { + const PAGE: usize = 2 << 20; + // An owned CPU-only window keeps global UMA state and GPU initialization out of the fixture. + let u = crate::gpu::uma::Uma::with_windows(1, 16 << 20).expect("owned memory window"); + let attrs = XAllocAttrs::decode((2 << 14) | (1 << 29)); + for (requested, expected) in [(1, PAGE), (PAGE, PAGE), (PAGE + 1, 2 * PAGE)] { + let (size, align) = xmem_graphics_layout(requested, attrs).unwrap(); + let p = u.alloc(size, align).expect("owned allocation"); + let (recorded, used) = (u.block_len(p as usize), u.used()); + let address = p as usize; + unsafe { + p.write(0x37); + p.add(requested - 1).write(0x69); + } + // Reclaim before assertions so the negative control also leaves no live allocation. + let released = u.free(address); + assert!(released); + assert_eq!(u.used(), 0); + assert_eq!(u.block_len(address), None); + assert!(!u.free(address), "one allocation is released only once"); + assert_eq!(address % PAGE, 0); + assert_eq!(recorded, Some(expected), "request {requested}: recorded allocation size"); + assert_eq!(used, expected, "request {requested}: memory charged"); + } + } + #[test] fn xmem_alignment_and_zeroing() { let attrs = |align_log2: u64, mtype: u64| (align_log2 << 24) | (mtype << 29); @@ -3794,7 +4175,7 @@ mod tests { // Freeing the physical page directly must drop the lazy entry so `r` is not // silently committed later by `lazy::ensure` or the VEH handler. assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, &mut page), 1); - lazy::ensure(r, 4); + drop(lazy::ensure(r, 4)); assert!(!committed_page(r), "freed away-mapped page must not remain in lazy::LAZY"); mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); } diff --git a/crates/xcl/src/hle/kernelx/alias.rs b/crates/xcl/src/hle/kernelx/alias.rs new file mode 100644 index 0000000000..1e67370ded --- /dev/null +++ b/crates/xcl/src/hle/kernelx/alias.rs @@ -0,0 +1,711 @@ +//! Physical pages that show at every address they are mapped at (`XCL_PAGE_ALIAS=1`). +//! +//! Without it a physical page is kept at one address at a time and moved (copied) when the +//! title maps it elsewhere. With it a block of physical pages is a section (`sections`): the +//! title's reservations of 64 KiB pages are placeholders ("spaces"), and mapping a page there +//! maps a view of its slice, so every address the title mapped it at shows the same memory. +//! The views are guarded (`guards`): a write through one is uploaded at all of them. +//! +//! Each block also has a view of its own (its home, never given to the title) through which +//! XCL reads and writes pages by number (DirectStorage destinations). A retail title never maps +//! a page at its home, so homes are plain address space, not the GPU-visible sparse windows. +//! +//! A page mapped at an address outside a space (a placeholder region the title made in a +//! sparse window) is moved there as before: its bytes are copied there and back again when it +//! is unmapped. While it is away its views show what it held when it left. + +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use windows_sys::Win32::Foundation as fnd; +use windows_sys::Win32::System::Memory as mem; + +use super::sections::{self, Section, PAGE}; +use super::{guards, lazy, page_index, page_number, NEXT_PAGE_INDEX}; + +/// `XCL_PAGE_ALIAS=1` turns physical page aliasing on (default: off). +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PAGE_ALIAS").is_ok_and(|v| v.trim() == "1")) +} + +struct Block { + section: Arc
, + /// XCL's own view of the whole block + home: usize, + /// pages not freed yet + live: usize, + /// one bit a page: committed (asking Windows walked the rest of a block's uncommitted run – + /// a retail title mapping 100 000 fresh pages one at a time waited 20 s for its first frame) + committed: Arc>, +} + +#[derive(Default)] +struct State { + /// first page index → block + blocks: BTreeMap, + /// the title's reservations kept as placeholders: base → size + spaces: BTreeMap, + /// address (64 KiB) in a space → (page number, its section, the page's index in it) + views: BTreeMap, usize)>, + /// pages moved to an address outside the spaces: page → address, and address → page + away: HashMap, + away_at: BTreeMap, +} + +static STATE: Mutex> = Mutex::new(None); +/// Whether any aliased view was ever mapped: `committed_at` sits on the lazy fault path and takes +/// no lock before then. +static ACTIVE: AtomicBool = AtomicBool::new(false); + +fn with(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +impl State { + /// (block's section, the page's index in it, its address in the home view) of page number `page` + fn page(&self, page: usize) -> Option<(Arc
, usize, usize)> { + let index = page_index(page)?; + let (&first, b) = self.blocks.range(..=index).next_back()?; + let i = index - first; + (i < b.section.pages()).then(|| (b.section.clone(), i, b.home + i * PAGE)) + } + + /// The commit bits of page number `page`'s block and its index there. + fn bits(&self, page: usize) -> Option<(Arc>, usize)> { + let index = page_index(page)?; + let (&first, b) = self.blocks.range(..=index).next_back()?; + (index - first < b.section.pages()).then(|| (b.committed.clone(), index - first)) + } + + fn in_space(&self, at: usize) -> bool { + self.spaces.range(..=at).next_back().is_some_and(|(&b, &n)| at < b + n) + } +} + +/// Whether page number `page` is committed (a page never used is not). +fn committed(page: usize) -> bool { + with(|s| s.bits(page)).is_some_and(|(b, i)| b[i / 64].load(Ordering::Acquire) & (1 << (i % 64)) != 0) +} + +/// Page number `page` is committed now. +fn note_committed(page: usize) { + if let Some((b, i)) = with(|s| s.bits(page)) { + b[i / 64].fetch_or(1 << (i % 64), Ordering::AcqRel); + } +} + +/// The view at `view` was committed by the lazy handler (its page's first use). +pub fn committed_at(view: usize) { + if !ACTIVE.load(Ordering::Acquire) { + return; + } + if let Some(page) = with(|s| s.views.get(&(view & !(PAGE - 1))).map(|v| v.0)) { + note_committed(page); + } +} + +/// A reservation of 64 KiB pages the title will map physical pages into: a space. None if +/// Windows refuses the address space. +pub fn reserve_space(size: usize) -> Option { + let len = size.checked_next_multiple_of(PAGE)?; + // SAFETY: only address space is reserved; `free_space` releases it. + let at = unsafe { sections::reserve(None, len) }?; + with(|s| s.spaces.insert(at, len)); + Some(at) +} + +/// Whether `p` lies in a space. +pub fn in_space(p: usize) -> bool { + enabled() && with(|s| s.in_space(p)) +} + +/// `VirtualFree` of an address in a space: release (the whole space) unmaps its pages and gives +/// the address space back; decommit unmaps the pages of the range. None: not a space. +pub unsafe fn free_space(addr: usize, size: usize, t: u32) -> Option { + let (base, len) = with(|s| s.spaces.range(..=addr).next_back().filter(|(&b, &n)| addr < b + n).map(|(&b, &n)| (b, n)))?; + if t & mem::MEM_RELEASE != 0 { + if addr != base || size != 0 { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return Some(false); + } + let part = super::source_part(base, len); + unmap_range(base, len); + with(|s| s.spaces.remove(&base)); + super::source_part_going(part, true, || { + super::mirrors::released(base); + sections::release_all(base, len); + }); + return Some(true); + } + let end = if size == 0 { base + len } else { addr.saturating_add(size).min(base + len) }; + unmap_range(addr & !(PAGE - 1), end - (addr & !(PAGE - 1))); + Some(true) +} + +unsafe fn unmap_range(at: usize, len: usize) { + let views: Vec = with(|s| { + let keys: Vec = s.views.range(at..at + len).map(|(&a, _)| a).collect(); + for &a in &keys { + s.views.remove(&a); + } + keys + }); + if views.is_empty() { + return; + } + for &a in &views { + guards::forget(a); + lazy::unmark(a); + } + let lo = *views.first().unwrap(); + let hi = *views.last().unwrap() + PAGE; + super::source_going(lo, hi - lo, false, || { + for &a in &views { + sections::unmap(a); + } + }); +} + +/// `count` physical pages for the title; their numbers in `arr`. +pub unsafe fn allocate(n: usize, arr: *mut usize) -> bool { + let Some(section) = Section::new(n) else { + crate::xlog_warn!("physical pages: a section of {n} pages could not be made"); + return false; + }; + let Some(home) = sections::reserve(None, n * PAGE) else { return false }; + if !section.map(0, n, home) { + sections::release(home); + return false; + } + let first = NEXT_PAGE_INDEX.fetch_add(n, Ordering::Relaxed); + for i in 0..n { + *arr.add(i) = page_number(first + i); + } + let committed = Arc::new((0..n.div_ceil(64)).map(|_| AtomicU64::new(0)).collect()); + with(|s| s.blocks.insert(first, Block { section: Arc::new(section), home, live: n, committed })); + true +} + +/// The title frees `pages`. Addresses that show one keep showing it (the title is meant to unmap +/// first); a block whose pages are all freed loses its home. +pub unsafe fn free(pages: &[usize]) { + let mut homes = Vec::new(); + with(|s| { + for &page in pages { + if let Some(at) = s.away.remove(&page) { + s.away_at.remove(&at); + } + let Some(index) = page_index(page) else { continue }; + let Some((&first, b)) = s.blocks.range_mut(..=index).next_back() else { continue }; + if index >= first + b.section.pages() { + continue; + } + b.live = b.live.saturating_sub(1); + if b.live == 0 { + homes.push((b.home, b.section.pages() * PAGE)); + s.blocks.remove(&first); + } + } + }); + for (home, len) in homes { + super::source_going(home, len, true, || { + sections::unmap(home); + sections::release(home); + }); + } +} + +/// Map `n` pages (`pages[i]`, 0: unmap) at `va`. Pages at an address in a space are views of +/// them; elsewhere they are moved there. False with the last error set if a page is not one of +/// the title's or Windows refuses. +pub unsafe fn map(va: usize, pages: &[usize]) -> bool { + if !va.is_multiple_of(PAGE) { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return false; + } + if pages.is_empty() { + return true; + } + let end = match pages.len().checked_mul(PAGE).and_then(|n| va.checked_add(n)) { + Some(e) => e, + None => { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return false; + } + }; + // Validate every non-zero page and pull out any existing views in `[va, end)` under one lock + // so unmapping a batch of views takes a single `source_going` / `sparse::STATE` round-trip. + let (valid, old_views) = with(|s| { + if pages.iter().any(|&p| p != 0 && s.page(p).is_none()) { + return (false, Vec::new()); + } + let keys: Vec = s.views.range(va..end).map(|(&a, _)| a).collect(); + for &a in &keys { + s.views.remove(&a); + } + (true, keys) + }); + if !valid { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return false; + } + if !old_views.is_empty() { + for &a in &old_views { + guards::forget(a); + lazy::unmark(a); + } + let lo = *old_views.first().unwrap(); + let hi = *old_views.last().unwrap() + PAGE; + super::source_going(lo, hi - lo, false, || { + for &a in &old_views { + sections::unmap(a); + } + }); + } + for (i, &page) in pages.iter().enumerate() { + let at = va + i * PAGE; + if !map_one(at, page) { + fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); + return false; + } + } + true +} + +unsafe fn map_one(at: usize, page: usize) -> bool { + // what was at `at` goes first (any prior view in `[va, end)` was already unmapped by `map`) + let (had_away, old_away, info, in_sp) = with(|s| { + let had_away = s.away_at.contains_key(&at); + if page == 0 { + return (had_away, None, None, false); + } + let old_away = s.away.get(&page).copied(); + let info = s.page(page); + let in_sp = s.in_space(at); + (had_away, old_away, info, in_sp) + }); + if had_away { + unmap_away(at); + } + if page == 0 { + return true; + } + // a page moved elsewhere comes home first (it is at one address outside the spaces at most, + // as before): its views then show what it holds + if let Some(old) = old_away { + unmap_away(old); + } + let (section, index, home) = info.unwrap(); + if in_sp { + if !section.map(index, 1, at) { + return false; + } + let is_committed = committed(page); + ACTIVE.store(true, Ordering::Release); + with(|s| s.views.insert(at, (page, section, index))); + guards::watch_with(page, at, is_committed); + if is_committed { + // an already-committed page mapped at a new view: sparse / title_textures must see it + guards::written(page); + } else { + // a page never used: committed at its first touch here (or through its home) + lazy::mark(at); + } + return true; + } + move_to(at, page, home) +} + +/// Page `page` moved to `at`, an address outside the spaces: committed there with its bytes. +unsafe fn move_to(at: usize, page: usize, home: usize) -> bool { + let u = crate::gpu::uma::get(); + let ok = if u.is_some_and(|u| u.is_committed(at)) { + true + } else if u.is_some_and(|u| u.is_sparse(at)) { + !super::commit_sparse(at, PAGE, mem::PAGE_READWRITE).is_null() + } else { + !mem::VirtualAlloc(at as *const c_void, PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() + }; + if !ok { + return false; + } + if committed(page) { + std::ptr::copy_nonoverlapping(home as *const u8, at as *mut u8, PAGE); + } else if !u.is_some_and(|u| u.is_sparse(at)) { + std::ptr::write_bytes(at as *mut u8, 0, PAGE); + } + with(|s| { + s.away.insert(page, at); + s.away_at.insert(at, page); + }); + true +} + +/// The page moved to `at` (if any) goes home with what `at` holds; `at` is decommitted. +unsafe fn unmap_away(at: usize) { + let Some((page, home)) = with(|s| { + let page = s.away_at.remove(&at)?; + s.away.remove(&page); + Some((page, s.page(page)?.2)) + }) else { + return; + }; + if sections::commit(home, PAGE) { + note_committed(page); + std::ptr::copy_nonoverlapping(at as *const u8, home as *mut u8, PAGE); + guards::written(page); + } + let u = crate::gpu::uma::get(); + if u.is_some_and(|u| u.is_committed(at)) { + return; + } + if u.is_some_and(|u| u.is_sparse(at)) { + crate::hle::d3d12x::sparse::decommitted(at, PAGE); + } + super::source_going(at, PAGE, false, || mem::VirtualFree(at as *mut c_void, PAGE, mem::MEM_DECOMMIT)); +} + +/// Whether a physical page is mapped at the page holding `va` (a view, or a page moved there). +pub fn physical_page_at(va: usize) -> bool { + let at = va & !(PAGE - 1); + with(|s| s.views.contains_key(&at) || s.away_at.contains_key(&at)) +} + +/// Whether `page` is a physical page allocated now. +pub fn page_live(page: usize) -> bool { + with(|s| s.page(page).is_some()) +} + +/// The physical page mapped at the page holding `va` (a view, or a page moved there), or None. +pub fn page_at(va: usize) -> Option { + let at = va & !(PAGE - 1); + with(|s| s.views.get(&at).map(|v| v.0).or_else(|| s.away_at.get(&at).copied())) +} + +/// Current storage for a page in the GPU-view mapping record. Section-backed aliases +/// all share the block's home. Ordinary sparse reservations can temporarily own its bytes. +pub(super) fn backing(page: usize) -> Option<(usize, bool)> { + with(|s| s.away.get(&page).map(|&at| (at, false)).or_else(|| s.page(page).map(|(_, _, home)| (home, true)))) +} + +/// The spaces and the blocks' homes as (base, bytes), each by address (`mem_map`). +pub fn ranges() -> (Vec<(usize, usize)>, Vec<(usize, usize)>) { + let (spaces, mut homes): (Vec<_>, Vec<_>) = with(|s| (s.spaces.iter().map(|(&b, &n)| (b, n)).collect(), s.blocks.values().map(|b| (b.home, b.section.pages() * PAGE)).collect())); + homes.sort_unstable(); + (spaces, homes) +} + +/// What one call of the queue's page-mapping method did, in 64 KiB pages. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Applied { + /// destination pages that show a physical page now + pub mapped: u64, + /// destination pages unmapped (by the call, or because nothing was mapped at their pool page) + pub unmapped: u64, + /// of those, pages whose pool page had nothing mapped + pub empty_pool: u64, +} + +/// The queue's page-mapping method (`CopyPageMappingsBatchX`, decoded by +/// `mirrors::decode_batches`): each destination page shows the physical page mapped at its pool +/// page now – on the console the method copies the pool page's mapping – or nothing. +pub unsafe fn apply_page_mappings(changes: &[(usize, Option)]) -> Option { + let mut out = Applied::default(); + for &(dest, pool) in changes { + let page = pool.and_then(page_at); + if !map_one(dest & !(PAGE - 1), page.unwrap_or(0)) { + return None; + } + match (pool, page) { + (_, Some(_)) => out.mapped += 1, + (Some(_), None) => { + out.unmapped += 1; + out.empty_pool += 1; + } + (None, _) => out.unmapped += 1, + } + } + Some(out) +} + +/// Where page `page`'s bytes are now (committing its home if `write`), or None. +unsafe fn bytes_of(page: usize, write: bool) -> Option<(usize, bool)> { + let (away, home) = with(|s| (s.away.get(&page).copied(), s.page(page).map(|p| p.2))); + if let Some(at) = away { + return Some((at, true)); + } + let home = home?; + if committed(page) { + return Some((home, true)); + } + if write { + if !sections::commit(home, PAGE) { + return None; + } + note_committed(page); + return Some((home, true)); + } + Some((home, false)) +} + +/// `read_physical_pages` in alias mode. +pub unsafe fn read(pages: &[usize], offset: usize, dst: &mut [u8]) -> bool { + copy_pages(pages, offset, dst.len(), |addr, done, n| { + match addr { + Some(a) => std::ptr::copy_nonoverlapping(a as *const u8, dst.as_mut_ptr().add(done), n), + None => std::ptr::write_bytes(dst.as_mut_ptr().add(done), 0, n), + } + }, false) +} + +/// `write_physical_pages` in alias mode. +pub unsafe fn write(pages: &[usize], offset: usize, src: &[u8]) -> bool { + copy_pages(pages, offset, src.len(), |addr, done, n| { + if let Some(a) = addr { + std::ptr::copy_nonoverlapping(src.as_ptr().add(done), a as *mut u8, n); + } + }, true) +} + +/// Walk `len` bytes from `offset` in `pages`, calling `f(address or None for a page never used, +/// bytes done, bytes here)`. All pages are checked before any byte is touched. +unsafe fn copy_pages(pages: &[usize], offset: usize, len: usize, mut f: impl FnMut(Option, usize, usize), write: bool) -> bool { + if len == 0 { + return offset < PAGE; + } + let Some(need) = offset.checked_add(len).map(|end| end.div_ceil(PAGE)) else { return false }; + if offset >= PAGE || pages.len() < need { + return false; + } + let mut addrs = Vec::with_capacity(need); + for &p in &pages[..need] { + let Some(a) = bytes_of(p, write) else { return false }; + addrs.push((p, a)); + } + let (mut done, mut off) = (0, offset); + for (page, (addr, used)) in addrs { + let n = (PAGE - off).min(len - done); + f(used.then_some(addr + off), done, n); + if write && with(|s| !s.away.contains_key(&page)) { + guards::written(page); + } + done += n; + off = 0; + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + /// alias state and guards are one per process: these tests run one at a time, and not + /// beside the guards' own + use super::guards::tests::SERIAL; + + unsafe fn read64(at: usize) -> u64 { + std::ptr::read_volatile(at as *const u64) + } + + unsafe fn write64(at: usize, v: u64) { + std::ptr::write_volatile(at as *mut u64, v) + } + + fn pages(n: usize) -> Vec { + let mut arr = vec![0usize; n]; + assert!(unsafe { allocate(n, arr.as_mut_ptr()) }); + arr + } + + fn dirty() -> Vec { + let mut out = Vec::new(); + guards::take_dirty(&mut out, PAGE); + out.sort_unstable(); + out + } + + /// Whether the first write through a view of a page never used faults into `lazy`, which + /// commits the page and sets its bit – what these tests rely on. Wine (11.21) does not + /// fault there: the write lands in the section and `VirtualQuery` still says `MEM_RESERVE`, + /// so the page's bit stays clear and its views are never guarded. + fn first_write_commits() -> bool { + let p = pages(1); + let s = reserve_space(PAGE).unwrap(); + unsafe { + assert!(map(s, &p)); + write64(s, 1); + let ok = committed(p[0]); + free_space(s, 0, mem::MEM_RELEASE); + free(&p); + dirty(); + ok + } + } + + /// Skip a test that needs `first_write_commits` where it does not hold. + fn needs_first_write_commit() -> bool { + if first_write_commits() { + return true; + } + crate::gpu::recomp::runner::skip_test("a write to an uncommitted section view does not fault (Wine)"); + false + } + + #[test] + fn a_page_mapped_into_two_spaces_is_one_page_and_writes_reach_both() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + if !needs_first_write_commit() { + return; + } + let p = pages(4); + let cpu = reserve_space(8 * PAGE).unwrap(); + let gpu = reserve_space(8 * PAGE).unwrap(); + unsafe { + assert!(map(cpu + 2 * PAGE, &p[1..3])); + assert!(map(gpu + 5 * PAGE, &[p[2]])); + assert!(physical_page_at(gpu + 5 * PAGE + 123)); + write64(cpu + 3 * PAGE + 8, 0xABCD); // page p[2] through the first space + assert_eq!(read64(gpu + 5 * PAGE + 8), 0xABCD, "the other space shows the same page"); + dirty(); + write64(gpu + 5 * PAGE, 1); + let mut want = vec![cpu + 3 * PAGE, gpu + 5 * PAGE]; + want.sort_unstable(); + assert_eq!(dirty(), want, "a write through one view: both are uploaded"); + assert_eq!(free_space(cpu, 0, mem::MEM_RELEASE), Some(true)); + assert_eq!(read64(gpu + 5 * PAGE + 8), 0xABCD, "releasing one space leaves the page at the other"); + assert_eq!(free_space(gpu, 0, mem::MEM_RELEASE), Some(true)); + free(&p); + } + } + + #[test] + fn remapping_an_address_shows_the_new_page_and_keeps_the_old_one() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(2); + let s = reserve_space(2 * PAGE).unwrap(); + unsafe { + assert!(map(s, &[p[0]])); + write64(s, 11); + assert!(map(s, &[p[1]])); + assert_eq!(read64(s), 0, "a page never written reads zeros"); + assert!(map(s, &[0])); + assert!(!physical_page_at(s)); + assert!(map(s + PAGE, &[p[0]])); + assert_eq!(read64(s + PAGE), 11, "the first page kept what was written to it"); + free_space(s, 0, mem::MEM_RELEASE); + free(&p); + } + } + + #[test] + fn pages_read_and_written_by_number_are_the_pages_the_title_sees() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + if !needs_first_write_commit() { + return; + } + 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()); + if !needs_first_write_commit() { + return; + } + let p = pages(1); + let s = reserve_space(PAGE).unwrap(); + // address space outside the spaces (as a title's own placeholder region would be) + 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()); + if !needs_first_write_commit() { + return; + } + let p = pages(2); + let pool = reserve_space(4 * PAGE).unwrap(); + let cpu = reserve_space(4 * PAGE).unwrap(); + let gpu = reserve_space(4 * PAGE).unwrap(); + unsafe { + // a streamed page: in the pool and in the CPU view, written through the CPU view + assert!(map(pool + PAGE, &[p[0]])); + assert!(map(cpu + 2 * PAGE, &[p[0]])); + write64(cpu + 2 * PAGE, 0x5EED); + // kind 0 / 1: pool pages at GPU-view pages; pool page 3 holds nothing; kind 2: unmapped + let changes = [(gpu, Some(pool + PAGE)), (gpu + PAGE, Some(pool + PAGE)), (gpu + 2 * PAGE, Some(pool + 3 * PAGE)), (gpu + 3 * PAGE, None)]; + let done = apply_page_mappings(&changes).unwrap(); + assert_eq!(done, Applied { mapped: 2, unmapped: 2, empty_pool: 1 }); + assert_eq!(read64(gpu), 0x5EED, "the GPU view shows the page the CPU view wrote"); + assert_eq!(read64(gpu + PAGE), 0x5EED, "one pool page at two GPU-view pages"); + assert!(!physical_page_at(gpu + 2 * PAGE) && !physical_page_at(gpu + 3 * PAGE)); + dirty(); + write64(gpu + PAGE + 8, 1); + let mut want = vec![pool + PAGE, cpu + 2 * PAGE, gpu, gpu + PAGE]; + want.sort_unstable(); + assert_eq!(dirty(), want, "a write in the GPU view: every view of the page is uploaded"); + // the pool page is given another physical page later: the GPU view keeps the one it was given + assert!(map(pool + PAGE, &[p[1]])); + assert_eq!(read64(gpu), 0x5EED); + assert_eq!(page_at(gpu), Some(p[0])); + for s in [pool, cpu, gpu] { + free_space(s, 0, mem::MEM_RELEASE); + } + free(&p); + } + } + + #[test] + fn a_page_not_from_the_title_is_refused() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let s = reserve_space(PAGE).unwrap(); + unsafe { + assert!(!map(s, &[page_number(1 << 40)])); + assert!(!map(s + 4, &[0]), "an address not on a page boundary is refused"); + free_space(s, 0, mem::MEM_RELEASE); + } + } +} diff --git a/crates/xcl/src/hle/kernelx/guards.rs b/crates/xcl/src/hle/kernelx/guards.rs new file mode 100644 index 0000000000..309adc18df --- /dev/null +++ b/crates/xcl/src/hle/kernelx/guards.rs @@ -0,0 +1,480 @@ +//! CPU writes to the views of physical pages, caught page by page. +//! +//! The upload of title memory to video memory (`d3d12x::sparse`) learns what the CPU wrote from +//! the write watch, and a view of a section (`sections`) cannot be write-watched. So the views +//! of a physical page are kept read-only: the first write through any of them faults, the +//! handler makes that view writable again and notes the page, and the write goes on. Before the +//! title's next submit `take_dirty` hands over the pages of every view of each page written – +//! a write through one view is a write to all of them – and guards them again. +//! +//! A kernel call does not fault into the handler: it fails. Memory a kernel call or XCL is about +//! to write goes through `lazy::ensure`, which opens the guards there first (`open`). + +use std::collections::{HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, Once}; + +use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; +use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS}; +use windows_sys::Win32::System::Memory::{VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_READONLY, PAGE_READWRITE}; + +const PAGE: usize = 0x1_0000; +const EXCEPTION_CONTINUE_EXECUTION: i32 = -1; +const EXCEPTION_CONTINUE_SEARCH: i32 = 0; + +#[derive(Default)] +struct State { + /// view page (64 KiB aligned) → the physical page it shows + at: HashMap, + /// physical page → the view pages that show it + views: HashMap>, + /// physical pages written since the last `take_dirty` + dirty: HashSet, + /// views opened for a write still going on (`Opened`): not guarded again until it ends + pinned: HashMap, + /// overlapped reads into views: (the OVERLAPPED, its views kept open until it is done) + pending: Vec<(usize, Opened)>, +} + +static STATE: Mutex> = Mutex::new(None); + +/// Whether any view was ever watched: `open` and `committed` sit on the file-read and +/// DirectStorage paths and take no lock before then. +static WATCHING: AtomicBool = AtomicBool::new(false); + +fn with(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +fn install() { + static ONCE: Once = Once::new(); + ONCE.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(handler)); + }); +} + +unsafe fn protect(view: usize, p: u32) -> bool { + let mut old = 0; + VirtualProtect(view as *const c_void, PAGE, p, &mut old) != 0 +} + +unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + let r = &*(*info).ExceptionRecord; + // a write (access 1) to a guarded view + if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 || r.ExceptionInformation[0] != 1 { + return EXCEPTION_CONTINUE_SEARCH; + } + let view = r.ExceptionInformation[1] & !(PAGE - 1); + // (a view not committed yet cannot be opened: that fault is `lazy`'s, which commits the page + // and counts it as written – claimed here, the write would fault again for ever) + let ours = with(|s| match s.at.get(&view) { + Some(&page) if unsafe { protect(view, PAGE_READWRITE) } => { + s.dirty.insert(page); + true + } + _ => false, + }); + // (another thread may have opened the view between the fault and here: writable now) + if ours || writable(view) { + EXCEPTION_CONTINUE_EXECUTION + } else { + EXCEPTION_CONTINUE_SEARCH + } +} + +/// Whether `view` is a guarded view that is writable now. +fn writable(view: usize) -> bool { + if !with(|s| s.at.contains_key(&view)) { + return false; + } + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: VirtualQuery only reads the address space description. + let n = unsafe { VirtualQuery(view as *const c_void, &mut m, std::mem::size_of_val(&m)) }; + n != 0 && m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE +} + +/// Physical page `page` is shown at `view` (64 KiB aligned): writes there are caught from now on. +/// A view not committed yet cannot be guarded; `committed` notes it when it is. +pub fn watch(page: usize, view: usize) { + watch_with(page, view, true); +} + +/// Like `watch`, but skips the `VirtualProtect` syscall when `already_committed` is false +/// (an uncommitted view cannot be protected yet and will be marked dirty when lazily committed). +pub fn watch_with(page: usize, view: usize, already_committed: bool) { + install(); + WATCHING.store(true, Ordering::Release); + with(|s| { + if let Some(old) = s.at.insert(view, page).filter(|&old| old != page) { + if let Some(v) = s.views.get_mut(&old) { + v.retain(|&a| a != view); + } + } + let v = s.views.entry(page).or_default(); + if !v.contains(&view) { + v.push(view); + } + if already_committed { + unsafe { protect(view, PAGE_READONLY) }; + } + }); +} + +/// `view` no longer shows a physical page (it was unmapped): its writes are not looked for. +pub fn forget(view: usize) { + with(|s| { + if let Some(page) = s.at.remove(&view) { + if let Some(v) = s.views.get_mut(&page) { + v.retain(|&a| a != view); + if v.is_empty() { + s.views.remove(&page); + s.dirty.remove(&page); + } + } + } + }); +} + +/// `view` was committed just now (it reads zeros and is writable): its page counts as written. +pub fn committed(view: usize) { + if !WATCHING.load(Ordering::Acquire) { + return; + } + with(|s| { + if let Some(&page) = s.at.get(&(view & !(PAGE - 1))) { + s.dirty.insert(page); + } + }); +} + +/// Physical page `page` was written other than through a view (XCL by page number, or the page +/// came back from an address outside the views): every view of it counts as written. +pub fn written(page: usize) { + if !WATCHING.load(Ordering::Acquire) { + return; + } + with(|s| { + if s.views.contains_key(&page) { + s.dirty.insert(page); + } + }); +} + +/// Views opened by `open` for a write: they stay writable until this is dropped, when the write +/// is over and their pages count as written again. +#[must_use = "the views stay open only while this lives"] +pub struct Opened(Vec); + +impl Drop for Opened { + fn drop(&mut self) { + if self.0.is_empty() { + return; + } + with(|s| { + for view in self.0.drain(..) { + if let Some(n) = s.pinned.get_mut(&view) { + *n -= 1; + if *n == 0 { + s.pinned.remove(&view); + } + } + if let Some(&page) = s.at.get(&view) { + s.dirty.insert(page); + } + } + }); + } +} + +/// `[p, p + len)` is about to be written by a kernel call or XCL: the views there are made +/// writable, stay so while the returned `Opened` lives (a kernel call fails on a view guarded +/// again under it), and their pages count as written. +pub fn open(p: usize, len: usize) -> Opened { + if len == 0 || !WATCHING.load(Ordering::Acquire) { + return Opened(Vec::new()); + } + with(|s| { + let mut opened = Vec::new(); + if s.at.is_empty() { + return Opened(opened); + } + let mut view = p & !(PAGE - 1); + while view < p.saturating_add(len) { + if let Some(&page) = s.at.get(&view) { + s.dirty.insert(page); + unsafe { protect(view, PAGE_READWRITE) }; + *s.pinned.entry(view).or_default() += 1; + opened.push(view); + } + view += PAGE; + } + Opened(opened) + }) +} + +/// An overlapped read (`ov`) writes into the views `opened` holds after its call returned: they +/// stay open until it is done (`take_dirty` looks). +pub fn open_until_done(opened: Opened, ov: usize) { + if !opened.0.is_empty() { + with(|s| s.pending.push((ov, opened))); + } +} + +/// Whether the overlapped I/O at `ov` is still going on (its `Internal` is STATUS_PENDING). The +/// title may have freed the OVERLAPPED once it is done, so it is read without faulting. +fn still_pending(ov: usize) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + const STATUS_PENDING: usize = 0x103; + let mut internal = 0usize; + let mut n = 0usize; + // SAFETY: ReadProcessMemory on our own process fails instead of faulting on an unreadable address. + let ok = unsafe { ReadProcessMemory(GetCurrentProcess(), ov as *const c_void, &mut internal as *mut usize as *mut c_void, std::mem::size_of::(), &mut n) } != 0; + ok && n == std::mem::size_of::() && internal == STATUS_PENDING +} + +/// The pages written since the last call, as the `step`-sized pages (4 KiB for the write watch) +/// of every view of each, appended to `out`; those views are guarded again. +pub(super) fn take_dirty(out: &mut Vec, step: usize) { + collect_dirty(out, step, &mut Vec::new()); +} + +/// Also mark the canonical storage used for copies to GPU-view tiles. +pub(crate) fn take_uploads(out: &mut Vec, step: usize) { + let mut pages = Vec::new(); + collect_dirty(out, step, &mut pages); + for page in pages { + if let Some((at, true)) = super::alias::backing(page) { + out.extend((at..at + PAGE).step_by(step)); + } + } +} + +fn collect_dirty(out: &mut Vec, step: usize, pages: &mut Vec) { + if !WATCHING.load(Ordering::Acquire) { + return; + } + // overlapped reads that are done let their views go (dropped outside the lock: it takes it) + let done: Vec<(usize, Opened)> = with(|s| { + let (done, pending) = std::mem::take(&mut s.pending).into_iter().partition(|&(ov, _)| !still_pending(ov)); + s.pending = pending; + done + }); + drop(done); + with(|s| { + for page in std::mem::take(&mut s.dirty) { + pages.push(page); + for &view in s.views.get(&page).map(Vec::as_slice).unwrap_or_default() { + // guarded before its bytes are read for the upload: a write from here on is + // caught again, one before this is in what the upload reads. A view opened for a + // write still going on stays open (`Opened` counts its page as written at the end) + if !s.pinned.contains_key(&view) { + unsafe { protect(view, PAGE_READONLY) }; + } + out.extend((view..view + PAGE).step_by(step)); + } + } + }); +} + +#[cfg(test)] +pub(super) mod tests { + use super::super::sections::{commit, reserve, unmap, Section}; + use super::*; + use std::sync::Mutex as TestLock; + + /// the guard state is one per process: tests that use it (here and in `alias`) run one at a time + pub(in crate::hle::kernelx) static SERIAL: TestLock<()> = TestLock::new(()); + + /// A section of `pages` pages and placeholder space for `views` views; page `i` of the + /// section at view slot `j` is `space + j * PAGE`. + struct Fixture { + section: Section, + space: usize, + mapped: Vec, + } + impl Fixture { + fn new(pages: usize, views: usize) -> Fixture { + Fixture { section: Section::new(pages).unwrap(), space: unsafe { reserve(None, views * PAGE) }.unwrap(), mapped: Vec::new() } + } + /// Section page `page` at view slot `slot`, committed and guarded; its physical page id is `page`. + fn show(&mut self, page: usize, slot: usize) -> usize { + let at = self.space + slot * PAGE; + unsafe { + assert!(self.section.map(page, 1, at)); + assert!(commit(at, PAGE)); + } + watch(page, at); + self.mapped.push(at); + at + } + } + impl Drop for Fixture { + fn drop(&mut self) { + for &at in &self.mapped { + forget(at); + unsafe { unmap(at) }; + } + } + } + + fn dirty() -> Vec { + let mut out = Vec::new(); + take_dirty(&mut out, PAGE); + out.sort_unstable(); + out + } + + unsafe fn write(at: usize, v: u64) { + std::ptr::write_volatile(at as *mut u64, v) + } + + #[test] + fn a_write_through_one_view_reports_every_view_of_the_page() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(4, 8); + let a = f.show(2, 1); + let b = f.show(2, 5); + let c = f.show(3, 6); + dirty(); + unsafe { write(b + 16, 9) }; + assert_eq!(unsafe { std::ptr::read_volatile((a + 16) as *const u64) }, 9); + assert_eq!(dirty(), vec![a, b], "both views of the written page, not the other page's"); + assert_eq!(dirty(), Vec::::new(), "nothing written since"); + unsafe { write(a, 1) }; + unsafe { write(c, 1) }; + assert_eq!(dirty(), vec![a, b, c], "the views are guarded again after a take"); + } + + #[test] + fn steps_of_4_kib_cover_the_view() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(1, 1); + let a = f.show(0, 0); + dirty(); + unsafe { write(a + 0x8000, 1) }; + let mut out = Vec::new(); + take_dirty(&mut out, 0x1000); + assert_eq!(out, (a..a + PAGE).step_by(0x1000).collect::>()); + } + + #[test] + fn open_makes_views_writable_for_a_kernel_call_and_counts_the_write() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(2, 4); + let a = f.show(0, 0); + let b = f.show(1, 1); + dirty(); + let opened = open(a + PAGE - 8, 16); // straddles both views + assert!(writable(a) && writable(b)); + assert_eq!(dirty(), vec![a, b]); + assert!(writable(a) && writable(b), "a take leaves views open while their write goes on"); + drop(opened); + assert_eq!(dirty(), vec![a, b], "the end of the write counts as a write"); + assert!(!writable(a), "guarded again after the take that follows"); + } + + #[test] + fn views_an_overlapped_read_writes_stay_open_until_it_is_done() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(1, 1); + let a = f.show(0, 0); + dirty(); + // an OVERLAPPED whose Internal says pending, then done + let mut ov = [0x103usize, 0, 0, 0]; + open_until_done(open(a, 16), ov.as_mut_ptr() as usize); + assert_eq!(dirty(), vec![a]); + assert!(writable(a), "still open while the read is pending"); + ov[0] = 0; + assert_eq!(dirty(), vec![a], "the end of the read counts as a write"); + assert!(!writable(a), "guarded again once the read is done"); + } + + #[test] + fn a_forgotten_view_is_no_longer_reported() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(1, 2); + let a = f.show(0, 0); + let b = f.show(0, 1); + dirty(); + forget(b); + unsafe { write(a, 3) }; + assert_eq!(dirty(), vec![a]); + } + + #[test] + fn writes_from_many_threads_are_all_caught_and_kept() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + const PAGES: usize = 64; + const THREADS: usize = 8; + let mut f = Fixture::new(PAGES, PAGES); + let views: Vec = (0..PAGES).map(|i| f.show(i, i)).collect(); + dirty(); + let barrier = std::sync::Arc::new(std::sync::Barrier::new(THREADS)); + let handles: Vec<_> = (0..THREADS) + .map(|t| { + let (views, barrier) = (views.clone(), barrier.clone()); + std::thread::spawn(move || { + barrier.wait(); + for (i, &v) in views.iter().enumerate() { + unsafe { write(v + t * 64, (i * THREADS + t) as u64) }; + } + }) + }) + .collect(); + for h in handles { + h.join().unwrap(); + } + for (i, &v) in views.iter().enumerate() { + for t in 0..THREADS { + assert_eq!(unsafe { std::ptr::read_volatile((v + t * 64) as *const u64) }, (i * THREADS + t) as u64); + } + } + assert_eq!(dirty(), views); + } + + /// A write to a guarded view that is not committed yet is not the guards' to handle (the + /// lazy handler commits it): claimed, it faulted again for ever whenever this handler ran + /// before the lazy one. + #[test] + fn a_write_to_a_view_not_committed_yet_is_left_to_the_next_handler() { + use windows_sys::Win32::System::Diagnostics::Debug::{CONTEXT, EXCEPTION_RECORD}; + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(2, 2); + // page 0 mapped but never committed; page 1 committed and guarded + let fresh = f.space; + unsafe { assert!(f.section.map(0, 1, fresh)) }; + watch(0, fresh); + f.mapped.push(fresh); + let used = f.show(1, 1); + let fault = |at: usize| unsafe { + let mut rec: EXCEPTION_RECORD = std::mem::zeroed(); + rec.ExceptionCode = EXCEPTION_ACCESS_VIOLATION as NTSTATUS; + rec.NumberParameters = 2; + rec.ExceptionInformation[0] = 1; + rec.ExceptionInformation[1] = at + 8; + let mut ctx: CONTEXT = std::mem::zeroed(); + let mut ptrs = EXCEPTION_POINTERS { ExceptionRecord: &mut rec, ContextRecord: &mut ctx }; + handler(&mut ptrs) + }; + assert_eq!(fault(fresh), EXCEPTION_CONTINUE_SEARCH, "not committed: left to the lazy handler"); + assert_eq!(fault(used), EXCEPTION_CONTINUE_EXECUTION, "committed and guarded: opened here"); + } + + #[test] + fn a_view_committed_later_counts_as_written() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let f = Fixture::new(1, 1); + let at = f.space; + unsafe { assert!(f.section.map(0, 1, at)) }; + watch(0, at); // not committed: cannot be guarded yet + dirty(); + unsafe { assert!(commit(at, PAGE)) }; + committed(at); + assert_eq!(dirty(), vec![at]); + forget(at); + unsafe { unmap(at) }; + } +} diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index 8745eec184..982543bba5 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -41,7 +41,15 @@ unsafe fn commit(page: usize) -> bool { if !g.remove(&page) { return false; } - !VirtualAlloc(page as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null() + if VirtualAlloc(page as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null() { + g.insert(page); + return false; + } + drop(g); + // (a view of a physical page committed here is writable, not guarded: count it as written) + super::guards::committed(page); + super::alias::committed_at(page); + true } unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { @@ -89,20 +97,22 @@ pub(super) fn is_marked(page: usize) -> bool { } /// The lazy pages of `[p, p + len)` committed – memory a kernel call or XCL writes. -pub fn ensure(p: usize, len: usize) { +pub fn ensure(p: usize, len: usize) -> super::guards::Opened { + let opened = super::guards::open(p, len); if len == 0 { - return; + return opened; } let pages: Vec = { let g = LAZY.read().unwrap_or_else(|e| e.into_inner()); if g.is_empty() { - return; + return opened; } g.range(p & !(PAGE - 1)..p.saturating_add(len)).copied().collect() }; for page in pages { unsafe { commit(page) }; } + opened } #[cfg(test)] @@ -122,7 +132,7 @@ mod tests { std::ptr::write_volatile((r + 8) as *mut u32, 7); assert_eq!(std::ptr::read_volatile((r + 8) as *const u32), 7); assert!(!unmark(r), "used: no longer lazy"); - ensure(r + PAGE + 4, 4); + let _open = ensure(r + PAGE + 4, 4); assert!(!LAZY.read().unwrap().contains(&(r + PAGE))); assert!(crate::gpu::shader::readable(r + PAGE, 4)); VirtualFree(r as *mut c_void, 0, MEM_RELEASE); diff --git a/crates/xcl/src/hle/kernelx/sections.rs b/crates/xcl/src/hle/kernelx/sections.rs new file mode 100644 index 0000000000..7af7bc4a02 --- /dev/null +++ b/crates/xcl/src/hle/kernelx/sections.rs @@ -0,0 +1,324 @@ +//! Physical pages that show at every address they are mapped at. +//! +//! On the console a physical page mapped at several addresses is one page: a write through one +//! address is read at all of them. A retail title maps its streamed pages into a pool, into the +//! CPU view of a 24 GB reservation and, through its queue, into that reservation's GPU view. +//! Here a block of physical pages is one pagefile-backed section, and mapping a page puts a view +//! of its 64 KiB slice into a placeholder at the address: every view of the slice is the same +//! memory, with no copy. The section is `SEC_RESERVE`, so a page takes commit only once it is +//! committed through one of its views, and then once for all of them. +//! +//! Address space that may hold such views is reserved as a placeholder (`reserve`). A view +//! replaces the placeholder at its address (`map`); unmapping it leaves a placeholder again +//! (`unmap`), ready for the next view. Ordinary memory can replace part of a placeholder too +//! (`replace_with_reservation`), write-watched if asked – but `GetWriteWatch` refuses a range +//! that holds a view, so the watch must ask about such reservations one by one. + +use std::ffi::c_void; + +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; +use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MapViewOfFile3, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQuery, MEMORY_BASIC_INFORMATION, + MEMORY_MAPPED_VIEW_ADDRESS, MEM_COMMIT, MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, + MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, PAGE_READWRITE, SEC_RESERVE, VIRTUAL_ALLOCATION_TYPE, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +/// One console physical page (64 KiB, the Windows allocation granularity too). +pub const PAGE: usize = 0x1_0000; + +const MEM_WRITE_WATCH: VIRTUAL_ALLOCATION_TYPE = 0x20_0000; + +/// A block of physical pages: one pagefile-backed section of `pages` 64 KiB pages. +pub struct Section { + handle: HANDLE, + pages: usize, +} + +// SAFETY: a section handle may be used from any thread; the section itself is kernel state. +unsafe impl Send for Section {} +unsafe impl Sync for Section {} + +impl Section { + /// A section of `pages` pages, none committed. None if Windows refuses it. + pub fn new(pages: usize) -> Option
{ + let bytes = pages.checked_mul(PAGE).filter(|&b| b > 0)?; + // SAFETY: a pagefile-backed mapping with no name and default security. + let handle = unsafe { CreateFileMappingW(INVALID_HANDLE_VALUE, std::ptr::null(), PAGE_READWRITE | SEC_RESERVE, (bytes >> 32) as u32, bytes as u32, std::ptr::null()) }; + (!handle.is_null()).then_some(Section { handle, pages }) + } + + pub fn pages(&self) -> usize { + self.pages + } + + /// Map pages `first..first + n` of the section at `at`, which must be a placeholder or lie in + /// one (`reserve`). The view is one Windows mapping: `unmap` takes all of it at once. + /// + /// # Safety + /// `[at, at + n * PAGE)` must be address space the caller owns as a placeholder. + pub unsafe fn map(&self, first: usize, n: usize, at: usize) -> bool { + if n == 0 || first.checked_add(n).is_none_or(|end| end > self.pages) || !at.is_multiple_of(PAGE) { + return false; + } + let len = n * PAGE; + if !split(at, len) { + return false; + } + let v = MapViewOfFile3(self.handle, GetCurrentProcess(), at as *const c_void, (first * PAGE) as u64, len, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, std::ptr::null_mut(), 0); + v.Value as usize == at + } +} + +impl Drop for Section { + fn drop(&mut self) { + // views still mapped keep the section alive until they are unmapped + // SAFETY: the handle is ours and closed once. + unsafe { CloseHandle(self.handle) }; + } +} + +/// Reserve `len` bytes of placeholder address space, at `at` if given. None if it is taken. +/// +/// # Safety +/// Only reserves address space; the caller releases it with `release`. +pub unsafe fn reserve(at: Option, len: usize) -> Option { + if len == 0 || !len.is_multiple_of(PAGE) { + return None; + } + let want = at.unwrap_or(0); + let p = VirtualAlloc2(GetCurrentProcess(), want as *const c_void, len, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, std::ptr::null_mut(), 0) as usize; + (p != 0 && (at.is_none() || p == want)).then_some(p) +} + +/// The allocation `p` lies in: (base, size, state, type), from one VirtualQuery. +fn allocation_at(p: usize) -> Option<(usize, usize, u32, u32)> { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: VirtualQuery only reads the address space description. + if unsafe { VirtualQuery(p as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 { + return None; + } + Some((m.AllocationBase as usize, m.RegionSize, m.State, m.Type)) +} + +/// Make `[at, at + len)` a placeholder of its own, splitting the placeholder it lies in. True if +/// it is one now (already exactly one, too). +/// +/// # Safety +/// `[at, at + len)` must lie in one placeholder the caller owns. +pub unsafe fn split(at: usize, len: usize) -> bool { + match allocation_at(at) { + // a placeholder is a reservation (MEM_RESERVE) with no protection; one that is already + // exactly this range cannot be split again – it is what was asked for + Some((base, size, MEM_RESERVE, _)) if base == at && size == len => true, + Some((_, _, MEM_RESERVE, _)) => VirtualFree(at as *mut c_void, len, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != 0, + _ => false, + } +} + +/// Unmap the view at `at` (all of it) and leave a placeholder in its place. +/// +/// # Safety +/// `at` must be the start of a view made by `Section::map`. +pub unsafe fn unmap(at: usize) -> bool { + UnmapViewOfFile2(GetCurrentProcess(), MEMORY_MAPPED_VIEW_ADDRESS { Value: at as *mut c_void }, MEM_PRESERVE_PLACEHOLDER) != 0 +} + +/// Commit `[at, at + len)` of a view: the section's pages there are committed for every view of +/// them. True if they are committed now. +/// +/// # Safety +/// The range must lie in views made by `Section::map`. +pub unsafe fn commit(at: usize, len: usize) -> bool { + !VirtualAlloc(at as *const c_void, len, MEM_COMMIT, PAGE_READWRITE).is_null() +} + +/// Ordinary reserved memory in place of `[at, at + len)` of a placeholder, write-watched if +/// `write_watch` (commit it with `VirtualAlloc` as usual). +/// +/// # Safety +/// `[at, at + len)` must lie in one placeholder the caller owns. +pub unsafe fn replace_with_reservation(at: usize, len: usize, write_watch: bool) -> bool { + if !split(at, len) { + return false; + } + let t = MEM_RESERVE | MEM_REPLACE_PLACEHOLDER | if write_watch { MEM_WRITE_WATCH } else { 0 }; + VirtualAlloc2(GetCurrentProcess(), at as *const c_void, len, t, PAGE_READWRITE, std::ptr::null_mut(), 0) as usize == at +} + +/// Turn the reservation `replace_with_reservation` made at `[at, at + len)` back into a +/// placeholder (what was committed there is gone). +/// +/// # Safety +/// `[at, at + len)` must be exactly such a reservation. +pub unsafe fn reservation_to_placeholder(at: usize, len: usize) -> bool { + VirtualFree(at as *mut c_void, len, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != 0 +} + +/// Release every placeholder in `[at, at + len)`, which splitting may have cut into many (views +/// in it must be unmapped first). True if all of it went. +/// +/// # Safety +/// `[at, at + len)` must be placeholders the caller owns. +pub unsafe fn release_all(at: usize, len: usize) -> bool { + let mut p = at; + while p < at + len { + match allocation_at(p) { + Some((base, size, MEM_RESERVE, _)) if base == p && release(p) => p += size, + _ => return false, + } + } + true +} + +/// Release the placeholder at `at` (its whole extent; views in it must be unmapped first). +/// +/// # Safety +/// `at` must be the start of a placeholder the caller owns. +pub unsafe fn release(at: usize) -> bool { + VirtualFree(at as *mut c_void, 0, MEM_RELEASE) != 0 +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{GetWriteWatch, MEM_MAPPED}; + + /// Placeholder address space for a test, released at the end (views unmapped first by the test). + struct Space(usize, usize); + impl Space { + fn new(pages: usize) -> Space { + let len = pages * PAGE; + Space(unsafe { reserve(None, len) }.expect("placeholder"), len) + } + fn at(&self, i: usize) -> usize { + self.0 + i * PAGE + } + } + impl Drop for Space { + fn drop(&mut self) { + // the test leaves placeholders behind; release each piece + let mut p = self.0; + while p < self.0 + self.1 { + let (base, size, _, _) = allocation_at(p).unwrap(); + assert_eq!(base, p); + unsafe { release(p) }; + p += size; + } + } + } + + unsafe fn read(at: usize) -> u64 { + std::ptr::read_volatile(at as *const u64) + } + + unsafe fn write(at: usize, v: u64) { + std::ptr::write_volatile(at as *mut u64, v) + } + + #[test] + fn a_page_mapped_at_two_addresses_is_one_page() { + let s = Section::new(8).unwrap(); + let space = Space::new(16); + unsafe { + assert!(s.map(5, 1, space.at(2))); + assert!(s.map(5, 1, space.at(11))); + assert!(commit(space.at(2), PAGE)); + write(space.at(2) + 0x40, 0xDEAD_BEEF); + assert_eq!(read(space.at(11) + 0x40), 0xDEAD_BEEF, "a write at one address is read at the other"); + write(space.at(11) + 0x40, 7); + assert_eq!(read(space.at(2) + 0x40), 7); + assert_eq!(allocation_at(space.at(11)).unwrap().3, MEM_MAPPED); + assert!(unmap(space.at(2)) && unmap(space.at(11))); + } + } + + #[test] + fn committing_through_one_view_commits_the_page_for_all() { + let s = Section::new(2).unwrap(); + let space = Space::new(4); + unsafe { + assert!(s.map(1, 1, space.at(0))); + assert!(s.map(1, 1, space.at(3))); + assert_eq!(allocation_at(space.at(3)).unwrap().2, MEM_RESERVE, "a page is not committed before it is used"); + assert!(commit(space.at(0), PAGE)); + assert_eq!(allocation_at(space.at(3)).unwrap().2, MEM_COMMIT); + assert_eq!(read(space.at(3)), 0, "a new page reads zeros"); + assert!(unmap(space.at(0)) && unmap(space.at(3))); + } + } + + #[test] + fn unmapping_leaves_a_placeholder_for_the_next_page() { + let s = Section::new(4).unwrap(); + let space = Space::new(2); + unsafe { + assert!(s.map(0, 1, space.at(1)) && commit(space.at(1), PAGE)); + write(space.at(1), 1); + assert!(unmap(space.at(1))); + let (base, size, state, _) = allocation_at(space.at(1)).unwrap(); + assert_eq!((base, size, state), (space.at(1), PAGE, MEM_RESERVE), "a placeholder of the page's size is left"); + assert!(s.map(3, 1, space.at(1)) && commit(space.at(1), PAGE)); + assert_eq!(read(space.at(1)), 0, "the other page is there now"); + // the first page kept its contents while it was mapped nowhere + assert!(s.map(0, 1, space.at(0))); + assert_eq!(read(space.at(0)), 1); + assert!(unmap(space.at(0)) && unmap(space.at(1))); + } + } + + #[test] + fn a_run_of_pages_is_one_view() { + let s = Section::new(8).unwrap(); + let space = Space::new(8); + unsafe { + assert!(s.map(2, 4, space.at(1))); + assert_eq!(allocation_at(space.at(1)).unwrap().0, space.at(1)); + assert_eq!(allocation_at(space.at(4)).unwrap().0, space.at(1), "one view covers the run"); + assert!(commit(space.at(1), 4 * PAGE)); + assert!(s.map(4, 1, space.at(7))); + write(space.at(3), 42); // page 4 of the section, third of the run + assert_eq!(read(space.at(7)), 42); + assert!(!s.map(6, 4, space.at(0)), "pages past the end of the section are refused"); + assert!(unmap(space.at(1)) && unmap(space.at(7))); + } + } + + #[test] + fn write_watched_memory_lives_beside_views_in_one_placeholder() { + let s = Section::new(1).unwrap(); + let space = Space::new(8); + unsafe { + assert!(replace_with_reservation(space.at(0), 4 * PAGE, true)); + assert!(!VirtualAlloc(space.at(0) as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + assert!(s.map(0, 1, space.at(6)) && commit(space.at(6), PAGE)); + write(space.at(1), 1); + write(space.at(6), 2); + let mut out = [std::ptr::null_mut::(); 64]; + let (mut n, mut gran) = (out.len(), 0u32); + assert_eq!(GetWriteWatch(1, space.at(0) as *const c_void, 4 * PAGE, out.as_mut_ptr(), &mut n, &mut gran), 0); + assert_eq!((n, out[0] as usize), (1, space.at(1)), "the write-watched reservation reports its write"); + let mut n = out.len(); + assert_ne!(GetWriteWatch(0, space.at(0) as *const c_void, 8 * PAGE, out.as_mut_ptr(), &mut n, &mut gran), 0, "a range with a view in it is refused"); + assert!(reservation_to_placeholder(space.at(0), 4 * PAGE)); + assert_eq!(allocation_at(space.at(0)).unwrap().2, MEM_RESERVE); + assert!(unmap(space.at(6))); + } + } + + #[test] + fn splitting_a_range_that_is_already_a_placeholder_is_a_no_op() { + let space = Space::new(3); + unsafe { + assert!(split(space.at(1), PAGE)); + assert!(split(space.at(1), PAGE)); + assert_eq!(allocation_at(space.at(1)).unwrap().0, space.at(1)); + assert_eq!(allocation_at(space.at(2)).unwrap().0, space.at(2)); + } + } + + #[test] + fn a_section_of_no_pages_is_refused() { + assert!(Section::new(0).is_none()); + } +} diff --git a/crates/xcl/src/hle/mod.rs b/crates/xcl/src/hle/mod.rs index 1555d4d8d8..fdb7dc47d3 100644 --- a/crates/xcl/src/hle/mod.rs +++ b/crates/xcl/src/hle/mod.rs @@ -18,6 +18,7 @@ pub mod d3d12_layout; pub mod d3d12x; pub mod dstorage; pub mod dxcompiler; +pub mod ffx; pub mod gameinput; pub mod kbm; pub mod kernelx; diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 50ef5302f1..1b0dfd86a8 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -119,6 +119,7 @@ pub fn host_main(boot_path: &Path) -> i32 { let mut views = crate::hle::d3d12x::view_want::totals(); let mut tile_calls = crate::hle::d3d12x::sparse::tile_calls(); let mut last_tick = std::time::Instant::now(); + let mut heap_tick = 0u32; loop { std::thread::sleep(std::time::Duration::from_secs(2)); let window_ms = last_tick.elapsed().as_millis() as u64; @@ -229,6 +230,17 @@ pub fn host_main(boot_path: &Path) -> i32 { if pages != 0 { crate::xlog_info!("{}", crate::hle::d3d12x::vram::page_owners()); } + // `XCL_HEAP_COUNT=1`: XCL's own part of that commit, every 20 s + heap_tick += 1; + if heap_tick % 10 == 0 { + crate::xlog_info!("{}", crate::hle::d3d12x::title_textures::upload_line()); + for l in crate::heap_count::lines(16).unwrap_or_default() { + crate::xlog_info!("{l}"); + } + for l in crate::mem_map::lines().unwrap_or_default() { + crate::xlog_info!("{l}"); + } + } // past the budget Windows moves the process's video memory off the card and // every frame pays for bringing it back; a run at the card's limit is also // where the driver gave up (the guard script ends a run that stays there) diff --git a/crates/xcl/src/lib.rs b/crates/xcl/src/lib.rs index 335c09e78e..adf7af9b8a 100644 --- a/crates/xcl/src/lib.rs +++ b/crates/xcl/src/lib.rs @@ -13,6 +13,9 @@ pub mod config; pub mod disasm; pub mod eh; pub mod gpu; +pub mod heap_count; +pub mod mem_map; +pub mod ram_budget; pub mod hle; pub mod hooks; pub mod host; @@ -23,7 +26,6 @@ pub mod loader; pub mod modules; pub mod pe; pub mod preflight; -pub mod ram_budget; pub mod report; pub mod resolver; pub mod rpf; @@ -34,7 +36,12 @@ mod source_hash; pub mod stall; pub mod state; pub mod stubs; +pub mod title_patch; pub mod tls; pub mod util; pub mod vfs; pub mod vfs_hooks; + +/// XCL's own allocations go through the counters of `heap_count` (`XCL_HEAP_COUNT=1`). +#[global_allocator] +static HEAP: heap_count::Counting = heap_count::Counting; diff --git a/crates/xcl/src/loader.rs b/crates/xcl/src/loader.rs index 27e47736e5..e5e64676b3 100644 --- a/crates/xcl/src/loader.rs +++ b/crates/xcl/src/loader.rs @@ -235,6 +235,10 @@ fn map_image_ex(path: &Path, is_main: bool) -> Result, String> unsafe { crate::eh::patch_clzero_loops(base + s.va as usize, len, &name) }; } } + // 10. places of a retail title's code the switches change (`title_patch`: XCL_UPSCALER) + if !module.is_dll { + unsafe { crate::title_patch::apply(base, size, &name) }; + } Ok(module) } diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index 8e57d1f8b5..c86379bea7 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -41,7 +41,10 @@ Usage: --export-hlsl DIR [--count N] [--min-kb N] [--record-hash HEX]: writes deterministic compute HLSL for investigation; an exact hash bypasses the size threshold. --measure-pso HEX [--repeat N]: times cache-disabled driver compilation of one exact - compute record with XCL's real root signature and static samplers. + compute record with XCL's real root signature and static samplers, and the commit + the driver took; with --direct the runtime's translation (XCL_DIRECT_* switches), + and of a split program every piece, then its whole form. + --measure-dxil [--repeat N]: the same for a DXIL file or translated-cache entry. --direct [--sample N] [--seed S] [--validate] [--compare]: direct DXIL translator coverage over a seeded sample (default 200 programs, 0 = all); also --timeout, --max-bytes, --threads, --json, --hash H, --dump DIR. diff --git a/crates/xcl/src/mem_map.rs b/crates/xcl/src/mem_map.rs new file mode 100644 index 0000000000..1a72abc0d6 --- /dev/null +++ b/crates/xcl/src/mem_map.rs @@ -0,0 +1,401 @@ +//! Where the process's memory is (`XCL_MEM_MAP=1`): every 20 s, with the memory lines of the +//! activity log, a walk of the process's own address space adds up the committed and the resident +//! (working-set) bytes by whose they are: the title's in the UMA windows, the physical pages of +//! `XCL_PAGE_ALIAS`, the images, and the rest by the size of its regions, with the largest +//! allocations of the rest by address. +//! +//! The process's counters (`memory: N MB committed by the process`) hold the title's memory, the +//! driver's, Direct3D's and XCL's own in one number. The walk tells them apart by address and by +//! the type of each region (`VirtualQuery`), and finds the pages that are resident with +//! `K32QueryWorkingSetEx`, `CHUNK` pages a call. It only asks Windows: no page is touched. + +use std::ffi::c_void; +use std::sync::OnceLock; + +use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_FREE, MEM_IMAGE, MEM_MAPPED}; +use windows_sys::Win32::System::ProcessStatus::{K32GetMappedFileNameW, K32GetProcessMemoryInfo, K32QueryWorkingSetEx, PROCESS_MEMORY_COUNTERS_EX, PSAPI_WORKING_SET_EX_INFORMATION}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +/// `XCL_MEM_MAP=1` turns the report on (default: off). +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_MEM_MAP").is_ok_and(|v| v.trim() == "1")) +} + +/// the pages the working set is asked about +const PAGE: usize = 4 << 10; +/// pages one `K32QueryWorkingSetEx` call asks about +const CHUNK: usize = 4096; + +// Whose committed memory is, the first that fits: by its address (the UMA windows, the physical +// pages' spaces and homes), then by the type of its region, the private rest by the region's size. +const SPARSE: usize = 0; +const COHERENT: usize = 1; +const VIEW: usize = 2; +const SPACES: usize = 3; +const HOMES: usize = 4; +const IMAGE: usize = 5; +const MAPPED: usize = 6; +const PRIVATE_LARGE: usize = 7; +const PRIVATE_MID: usize = 8; +const PRIVATE_SMALL: usize = 9; +const CLASSES: usize = 10; +const NAMES: [&str; CLASSES] = [ + "title memory in sparse windows", + "title memory in the coherent window", + "GPU-view windows", + "physical pages: views in the title's spaces (views of the same pages as the homes)", + "physical pages: XCL's home views", + "images (exe and DLLs)", + "other mapped (sections, files)", + "other private, regions >= 64 MiB", + "other private, regions 1-64 MiB", + "other private, regions < 1 MiB", +]; + +/// the largest images listed +const TOP_IMAGES: usize = 3; +/// the largest other private allocations listed +const TOP_ALLOCS: usize = 12; + +#[derive(Clone, Copy, Default)] +struct Bytes { + committed: usize, + resident: usize, + /// of `resident`, pages mapped more than once (`ShareCount` > 1) + shared: usize, + /// committed regions + regions: usize, +} + +impl Bytes { + fn resident_page(&mut self, shared: bool) { + self.resident += PAGE; + if shared { + self.shared += PAGE; + } + } +} + +/// One allocation of the walk (its regions' `AllocationBase`): an image, or other private memory. +struct Item { + base: usize, + /// the end of its last region seen, committed or reserved + end: usize, + bytes: Bytes, + /// `Protect` of its first committed region; `mixed`: another one has another + protect: u32, + mixed: bool, + alloc_protect: u32, +} + +/// Whose a page of the walk is: a class, and an item of the class (`NO_ITEM`: none). +#[derive(Clone, Copy)] +struct Tag { + class: usize, + item: usize, +} + +const NO_ITEM: usize = usize::MAX; + +/// What a walk adds up: whose each committed region is, and its pages found resident. +trait Sink { + /// The committed part `[at, at + len)` of the region `m`: whose it is. + fn committed(&mut self, m: &MEMORY_BASIC_INFORMATION, at: usize, len: usize) -> Tag; + /// A page of `tag`'s is in the working set (`shared`: mapped more than once). + fn resident(&mut self, tag: Tag, shared: bool); + /// A region reserved but not committed. + fn reserved(&mut self, _m: &MEMORY_BASIC_INFORMATION) {} +} + +/// The pages of committed regions waiting for one `K32QueryWorkingSetEx` call (one buffer for the +/// whole walk), with whose each one is. +struct Pages { + info: Vec, + tags: Vec, + /// calls Windows refused (their pages are not counted resident) + failed: usize, +} + +impl Pages { + fn new() -> Pages { + Pages { info: Vec::with_capacity(CHUNK), tags: Vec::with_capacity(CHUNK), failed: 0 } + } + + /// The pages of `[at, at + len)`, committed and `tag`'s, asked about `CHUNK` at a time. + fn add(&mut self, at: usize, len: usize, tag: Tag, sink: &mut impl Sink) { + for p in (at..at + len).step_by(PAGE) { + if self.info.len() == CHUNK { + self.flush(sink); + } + self.info.push(PSAPI_WORKING_SET_EX_INFORMATION { VirtualAddress: p as *mut c_void, VirtualAttributes: Default::default() }); + self.tags.push(tag); + } + } + + /// One `K32QueryWorkingSetEx` call for the pages waiting: each resident one goes to `sink`. + fn flush(&mut self, sink: &mut impl Sink) { + if self.info.is_empty() { + return; + } + let bytes = (self.info.len() * std::mem::size_of::()) as u32; + if unsafe { K32QueryWorkingSetEx(GetCurrentProcess(), self.info.as_mut_ptr() as *mut c_void, bytes) } != 0 { + for (i, &tag) in self.info.iter().zip(&self.tags) { + // bit 0: Valid (in the working set), bits 1..=3: ShareCount + let flags = unsafe { i.VirtualAttributes.Flags }; + if flags & 1 != 0 { + sink.resident(tag, (flags >> 1) & 7 > 1); + } + } + } else { + self.failed += 1; + } + self.info.clear(); + self.tags.clear(); + } +} + +/// Walk `[lo, hi)` region by region (`VirtualQuery`): the committed part of each goes to `sink`, +/// and its pages to the working-set queries of `pages`; a region not committed costs its query +/// only. The regions walked. +fn walk(lo: usize, hi: usize, pages: &mut Pages, sink: &mut impl Sink) -> usize { + let mut walked = 0; + let mut p = lo; + while p < hi { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + if unsafe { VirtualQuery(p as *const c_void, &mut m, std::mem::size_of::()) } == 0 { + // past the user address space + break; + } + walked += 1; + let base = m.BaseAddress as usize; + let end = base.saturating_add(m.RegionSize); + if m.State == MEM_COMMIT { + let (from, to) = (base.max(lo), end.min(hi)); + if to > from { + let tag = sink.committed(&m, from, to - from); + pages.add(from, to - from, tag, sink); + } + } else if m.State != MEM_FREE { + sink.reserved(&m); + } + if end <= p { + break; + } + p = end; + } + pages.flush(sink); + walked +} + +/// Whether `p` lies in one of `ranges` ((base, bytes), by address, not overlapping). +fn within(ranges: &[(usize, usize)], p: usize) -> bool { + let i = ranges.partition_point(|r| r.0 <= p); + i > 0 && p - ranges[i - 1].0 < ranges[i - 1].1 +} + +/// The item of `m`'s allocation in `items` with `len` committed bytes more: the last one, or a new +/// one (the walk goes by address, and the regions of an allocation are side by side). +fn item_of(items: &mut Vec, m: &MEMORY_BASIC_INFORMATION, len: usize) -> usize { + let base = m.AllocationBase as usize; + if items.last().is_none_or(|i| i.base != base) { + items.push(Item { base, end: base, bytes: Bytes::default(), protect: m.Protect, mixed: false, alloc_protect: m.AllocationProtect }); + } + let n = items.len() - 1; + let i = &mut items[n]; + i.bytes.committed += len; + i.bytes.regions += 1; + i.mixed |= i.protect != m.Protect; + i.end = (m.BaseAddress as usize).saturating_add(m.RegionSize); + n +} + +/// The report's sink: the classes, and the images and other private allocations one by one. +#[derive(Default)] +struct Map { + uma: Option<&'static crate::gpu::uma::Uma>, + /// the physical pages' spaces and homes (`alias::ranges`), by address + spaces: Vec<(usize, usize)>, + homes: Vec<(usize, usize)>, + classes: [Bytes; CLASSES], + /// committed bytes by the type of their region: private, mapped, image + by_type: [usize; 3], + /// the images and the other private allocations, by address + images: Vec, + allocs: Vec, +} + +impl Map { + fn class_of(&self, m: &MEMORY_BASIC_INFORMATION, at: usize, len: usize) -> usize { + if let Some(u) = self.uma { + if u.is_sparse(at) { + return SPARSE; + } + if u.is_committed(at) { + return COHERENT; + } + if u.is_view(at) { + return VIEW; + } + } + if within(&self.spaces, at) { + SPACES + } else if within(&self.homes, at) { + HOMES + } else if m.Type == MEM_IMAGE { + IMAGE + } else if m.Type == MEM_MAPPED { + MAPPED + } else if len >= 64 << 20 { + PRIVATE_LARGE + } else if len >= 1 << 20 { + PRIVATE_MID + } else { + PRIVATE_SMALL + } + } + + /// The items kept one by one of `class` (None: the class is only added up). + fn items(&mut self, class: usize) -> Option<&mut Vec> { + match class { + IMAGE => Some(&mut self.images), + PRIVATE_LARGE | PRIVATE_MID | PRIVATE_SMALL => Some(&mut self.allocs), + _ => None, + } + } +} + +impl Sink for Map { + fn committed(&mut self, m: &MEMORY_BASIC_INFORMATION, at: usize, len: usize) -> Tag { + self.by_type[match m.Type { + MEM_MAPPED => 1, + MEM_IMAGE => 2, + _ => 0, + }] += len; + let class = self.class_of(m, at, len); + self.classes[class].committed += len; + self.classes[class].regions += 1; + let item = self.items(class).map_or(NO_ITEM, |items| item_of(items, m, len)); + Tag { class, item } + } + + fn resident(&mut self, tag: Tag, shared: bool) { + self.classes[tag.class].resident_page(shared); + if tag.item != NO_ITEM { + if let Some(items) = self.items(tag.class) { + items[tag.item].bytes.resident_page(shared); + } + } + } + + fn reserved(&mut self, m: &MEMORY_BASIC_INFORMATION) { + // (the reserved rest of an allocation listed: a thread stack, a heap's segment) + if let Some(i) = self.allocs.last_mut().filter(|i| i.base == m.AllocationBase as usize) { + i.end = (m.BaseAddress as usize).saturating_add(m.RegionSize); + } + } +} + +/// The file name of the image at `base` (its mapped file's, without the path). +fn image_name(base: usize) -> String { + let mut buf = [0u16; 512]; + let n = unsafe { K32GetMappedFileNameW(GetCurrentProcess(), base as *const c_void, buf.as_mut_ptr(), buf.len() as u32) } as usize; + let path = String::from_utf16_lossy(&buf[..n.min(buf.len())]); + path.rsplit('\\').next().filter(|s| !s.is_empty()).unwrap_or("?").to_string() +} + +/// The lines of the activity log, each starting `mem map:`: the totals and how long the walk +/// took, each class, the largest images, the largest other private allocations. None: off. +pub fn lines() -> Option> { + if !enabled() { + return None; + } + let t = std::time::Instant::now(); + let (spaces, homes) = crate::hle::kernelx::alias::ranges(); + let mut map = Map { uma: crate::gpu::uma::get(), spaces, homes, ..Map::default() }; + let mut pages = Pages::new(); + let walked = walk(0, usize::MAX, &mut pages, &mut map); + let ms = t.elapsed().as_millis(); + let (private_usage, working_set) = unsafe { + let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); + c.cb = std::mem::size_of_val(&c) as u32; + K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb); + (c.PrivateUsage, c.WorkingSetSize) + }; + let mb = |b: usize| b >> 20; + let [private, mapped, image] = map.by_type; + let resident: usize = map.classes.iter().map(|c| c.resident).sum(); + let failed = if pages.failed != 0 { format!("; {} working-set queries failed (their pages are not counted resident)", pages.failed) } else { String::new() }; + let mut out = vec![format!( + "mem map: walked {walked} regions in {ms} ms: committed {} MB private, {} MB mapped, {} MB image ({} MB in all); {} MB resident; the process's counters: {} MB private commit, {} MB working set{failed}", + mb(private), + mb(mapped), + mb(image), + mb(private + mapped + image), + mb(resident), + mb(private_usage), + mb(working_set) + )]; + for (name, b) in NAMES.iter().zip(&map.classes) { + out.push(format!("mem map: {name}: {} MB committed, {} MB resident, {} regions, {} MB of the resident shared", mb(b.committed), mb(b.resident), b.regions, mb(b.shared))); + } + map.images.sort_by_key(|i| std::cmp::Reverse(i.bytes.committed)); + for i in map.images.iter().take(TOP_IMAGES) { + out.push(format!("mem map: image {} at {:#x}: {} MB committed, {} MB resident", image_name(i.base), i.base, mb(i.bytes.committed), mb(i.bytes.resident))); + } + map.allocs.sort_by_key(|i| std::cmp::Reverse(i.bytes.committed)); + for (k, i) in map.allocs.iter().take(TOP_ALLOCS).enumerate() { + out.push(format!( + "mem map: other private allocation {} at {:#x}: {} MB committed, {} MB resident, {} regions, {} MB reserved, protect {:#x}{} (allocation protect {:#x})", + k + 1, + i.base, + mb(i.bytes.committed), + mb(i.bytes.resident), + i.bytes.regions, + mb(i.end - i.base), + i.protect, + if i.mixed { " and others" } else { "" }, + i.alloc_protect + )); + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + + /// A private allocation of which the first half is committed, and every other page of that + /// touched: the walk over it counts the committed half in one region of one allocation, the + /// touched pages resident and not the others. + #[test] + fn a_walk_counts_the_committed_bytes_and_the_touched_pages_resident() { + // (more pages than one working-set query asks about) + const SIZE: usize = 20 << 20; + let p = unsafe { VirtualAlloc(std::ptr::null(), 2 * SIZE, MEM_RESERVE, PAGE_READWRITE) } as usize; + assert_ne!(p, 0); + assert_eq!(unsafe { VirtualAlloc(p as *const c_void, SIZE, MEM_COMMIT, PAGE_READWRITE) } as usize, p); + for k in (0..SIZE / PAGE).step_by(2) { + unsafe { std::ptr::write_volatile((p + k * PAGE) as *mut u8, 1) }; + } + let mut map = Map::default(); + let walked = walk(p, p + 2 * SIZE, &mut Pages::new(), &mut map); + // the same memory as one of the physical pages' homes: by its address first + let mut home = Map { homes: vec![(p, 2 * SIZE)], ..Map::default() }; + walk(p, p + 2 * SIZE, &mut Pages::new(), &mut home); + unsafe { VirtualFree(p as *mut c_void, 0, MEM_RELEASE) }; + + assert_eq!(walked, 2, "the committed half and the reserved half"); + let b = map.classes[PRIVATE_MID]; + assert_eq!((b.committed, b.regions), (SIZE, 1)); + assert!(b.resident >= SIZE / 2 && b.resident < SIZE, "{} KiB resident of {} KiB committed, {} KiB touched", b.resident >> 10, SIZE >> 10, SIZE >> 11); + assert_eq!(map.by_type, [SIZE, 0, 0]); + assert_eq!(map.classes.iter().map(|c| c.committed).sum::(), SIZE, "in no other class"); + assert_eq!(map.allocs.len(), 1); + let a = &map.allocs[0]; + assert_eq!((a.base, a.end, a.bytes.committed, a.bytes.resident), (p, p + 2 * SIZE, SIZE, b.resident), "one allocation, with its reserved half"); + assert_eq!(home.classes[HOMES].committed, SIZE); + assert!(home.allocs.is_empty() && home.classes[PRIVATE_MID].committed == 0); + } +} diff --git a/crates/xcl/src/resolver.rs b/crates/xcl/src/resolver.rs index 72dbacae7b..13fa3f25c7 100644 --- a/crates/xcl/src/resolver.rs +++ b/crates/xcl/src/resolver.rs @@ -324,6 +324,9 @@ pub fn resolve_import(dll: &str, what: &ImportName, importer: &str, delay: bool) if matches!(source, Source::GameDll(_)) && crate::hle::bink::is_bink_dll(&key) { addr = crate::hle::bink::wrap(&fname(what), addr); } + if matches!(source, Source::GameDll(_)) && crate::hle::ffx::is_loader_dll(&key) { + addr = crate::hle::ffx::wrap(&fname(what), addr); + } crate::xlog_debug!("import {importer}: {key}!{what} → {source:?}"); if let Some(f) = trace_filter() { if f.wants(&key, &fname(what), &source) { diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 9945b2849d..07358d3858 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -39,7 +39,11 @@ fn semantic_pipeline_setting(name: &str) -> bool { "XCL_RECOMP_DXIL" | "XCL_RECOMP_NO_STRUCTURED" | "XCL_SAFE_BARRIER" | "XCL_SPLIT_WAVE64" | "XCL_WAVE64_SPIN" | "XCL_WT" | "XCL_X64_ALL_MASKS" | "XCL_XC" | "XCL_XS" | "XCL_XW" | "XCL_X_FAIL" | "XCL_X_LDS_ORDER" | - "XCL_X_LDS_TOP" | "XCL_X_SLOT" | "XCL_X_SPIN" | "XCL_X_THREADS" | "XCL_X_WAVES") + "XCL_X_LDS_TOP" | "XCL_X_SLOT" | "XCL_X_SPIN" | "XCL_X_THREADS" | "XCL_X_WAVES" | + // amd-dev's translation switches (also in `pso::translation_cache_identity`) + "XCL_COHERENT_PER_ACCESS" | "XCL_DECLARED_LDS" | "XCL_DIRECT_COMPACT_MIN" | + "XCL_DIRECT_FORMS_ONLY" | "XCL_DOT_OP_SEL" | "XCL_NAN_GUARD" | "XCL_ONE_WAVE_GROUP_IDS" | + "XCL_PS_QUAD_READS" | "XCL_RT_GATE") } fn warm_settings(vars: impl IntoIterator) -> u64 { @@ -137,6 +141,9 @@ fn warm_settings_ignore_waits_watchdogs_and_traces_but_keep_pipeline_switches() all.extend(left_out); assert_eq!(plain, key(&all)); assert_ne!(plain, key(&[("XCL_DIRECT_DXIL", "1"), ("XCL_PAGE_ALIAS", "1")]), "page alias stays in the key"); + for knob in [("XCL_DOT_OP_SEL", "0"), ("XCL_DIRECT_FORMS_ONLY", "all"), ("XCL_DIRECT_COMPACT_MIN", "0"), ("XCL_PS_QUAD_READS", "0")] { + assert_ne!(plain, key(&[("XCL_DIRECT_DXIL", "1"), knob]), "{} stays in the key", knob.0); + } assert_eq!(plain, key(&[("XCL_DIRECT_DXIL", "1"), ("XCL_TRACEX", "1")]), "unknown diagnostics stay cache-neutral until reviewed"); } @@ -949,6 +956,8 @@ struct ShadersOptions { count: usize, record_hash: Option, measure_pso: Option, + /// `--measure-dxil`: the input is one DXIL file or translated-cache entry to time + measure_dxil: bool, repeat: usize, precompile: bool, prepare_corpus: bool, @@ -990,6 +999,7 @@ fn parse_args(args: &[String]) -> Result { count: 2, record_hash: None, measure_pso: None, + measure_dxil: false, repeat: 1, precompile: false, prepare_corpus: false, @@ -1033,6 +1043,7 @@ fn parse_args(args: &[String]) -> Result { "--count" => opts.count = p.parse_usize("--count")?, "--record-hash" => opts.record_hash = Some(p.parse_hex_u64("--record-hash")?), "--measure-pso" => opts.measure_pso = Some(p.parse_hex_u64("--measure-pso")?), + "--measure-dxil" => opts.measure_dxil = true, "--repeat" => opts.repeat = p.parse_usize("--repeat")?, "--precompile" => opts.precompile = true, "--prepare-corpus" => opts.prepare_corpus = true, @@ -1162,6 +1173,9 @@ pub fn run(path: &Path, args: &[String]) -> i32 { if opts.graphics_records { return graphics_worker(path, runtime_windows(), opts.threads); } + if opts.measure_dxil { + return measure_dxil(path, opts.repeat.max(1)); + } let top = opts.top; let json = opts.json; let compile = opts.compile; @@ -1224,6 +1238,7 @@ pub fn run(path: &Path, args: &[String]) -> i32 { opts.repeat.max(1), runtime_windows(), opts.split, + if opts.direct { PsoSource::Runtime } else { PsoSource::Hlsl }, ); } if opts.precompile { @@ -1483,8 +1498,8 @@ mod worker_stack_tests { /// `CreateComputePipelineState`. The implicit D3D and driver caches must both be disabled; /// refusing to do that is an error rather than a misleading warm-cache measurement. /// This is the HLSL path the runtime uses by default (not `XCL_DIRECT_DXIL`). -fn measure_pso(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option) -> i32 { - match on_worker_stack("xcl-measure-pso", || measure_pso_result(input, hash, repeat, windows, split)) { +fn measure_pso(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option, source: PsoSource) -> i32 { + match on_worker_stack("xcl-measure-pso", || measure_pso_result(input, hash, repeat, windows, split, source)) { Ok(()) => 0, Err(MeasureError::Unavailable(e) | MeasureError::Failed(e)) => { eprintln!("xcl shaders --measure-pso: {e}"); @@ -1493,51 +1508,205 @@ fn measure_pso(input: &Input, hash: u64, repeat: usize, windows: u32, split: Opt } } -fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option) -> Result<(), MeasureError> { +/// Where `--measure-pso` takes a console program's DXIL from. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum PsoSource { + /// the HLSL path through DXC + Hlsl, + /// `--direct`: the runtime's translation (`pso::console_dxil_uncached`: the direct DXIL + /// translator with the environment's `XCL_DIRECT_*` / `XCL_DXIL_NO_OPT` switches, or its HLSL + /// fallback), so a form can be timed before a run builds it + Runtime, +} + +/// A D3D12 device whose implicit driver and D3D caches are off for this process: every +/// `CreateComputePipelineState` is a cold compile. Refusing to turn them off is an error rather +/// than a misleading warm-cache measurement. +fn cacheless_pipelines() -> Result { use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; + use MeasureError::Unavailable; + let pipeline = Pipelines::new().map_err(|e| Unavailable(format!("no GPU device: {e}")))?; + let dev9 = pipeline.dev.cast::().map_err(|e| Unavailable(format!("ID3D12Device9 is required to disable the driver cache: {e}")))?; + let cache_kinds = D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_DRIVER_MANAGED | D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CACHE_FOR_DRIVER; + unsafe { dev9.ShaderCacheControl(cache_kinds, D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) } + .map_err(|e| Unavailable(format!("cannot disable the driver cache (Windows Developer Mode is required): {e}")))?; + Ok(pipeline) +} + +fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option, source: PsoSource) -> Result<(), MeasureError> { use MeasureError::{Failed, Unavailable}; let (name, blob) = record_by_hash(input, hash).map_err(Failed)?; if !is_compute_container(&blob) { return Err(Failed(format!("{name} is not a console compute shader"))); } - recomp::dxc::location().map_err(|e| Unavailable(format!("DXC: {e}")))?; - let pipeline = Pipelines::new().map_err(|e| Unavailable(format!("no GPU device: {e}")))?; + if source == PsoSource::Hlsl { + recomp::dxc::location().map_err(|e| Unavailable(format!("DXC: {e}")))?; + } // before translating and compiling (tens of seconds for a big program): a machine that // cannot turn the caches off fails at once - let dev9 = pipeline.dev.cast::().map_err(|e| Unavailable(format!("ID3D12Device9 is required to disable the driver cache: {e}")))?; - let cache_kinds = D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_DRIVER_MANAGED | D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CACHE_FOR_DRIVER; - unsafe { dev9.ShaderCacheControl(cache_kinds, D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) } - .map_err(|e| Unavailable(format!("cannot disable the driver cache (Windows Developer Mode is required): {e}")))?; + let pipeline = cacheless_pipelines()?; let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::pso::wave32_only_for_device(&pipeline.dev)); - let dxc_start = std::time::Instant::now(); - // `XCL_DIRECT_DXIL=1`: the direct translator's container instead (no HLSL fallback, so the - // number is never silently the other path's) - let (dxil, samplers) = if crate::gpu::dxil::kernel::enabled() { - let c = recomp::pso::direct_compute(&blob, 0, windows, split).map_err(|e| Failed(format!("{name}: direct: {e}")))?; - (c.dxil, c.samplers) - } else { - let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split, false).map_err(|e| Failed(format!("{name}: {e}")))?; - let dxil = recomp::dxc::compile(&translation.hlsl, "main", profile, &[]).map_err(|e| Failed(format!("DXC: {e}")))?; - (dxil, translation.static_samplers) + let made = std::time::Instant::now(); + let (dxil, samplers, how) = match source { + // `XCL_DIRECT_DXIL=1`: the direct translator's container instead (no HLSL fallback, so the + // number is never silently the other path's) + PsoSource::Hlsl if crate::gpu::dxil::kernel::enabled() => { + let c = recomp::pso::direct_compute(&blob, 0, windows, split).map_err(|e| Failed(format!("{name}: direct: {e}")))?; + (c.dxil, c.samplers, format!("{} ms to translate, direct", made.elapsed().as_millis())) + } + PsoSource::Hlsl => { + let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split, false).map_err(|e| Failed(format!("{name}: {e}")))?; + let dxc_start = std::time::Instant::now(); + let dxil = recomp::dxc::compile(&translation.hlsl, "main", profile, &[]).map_err(|e| Failed(format!("DXC: {e}")))?; + (dxil, translation.static_samplers, format!("{} ms DXC", dxc_start.elapsed().as_millis())) + } + PsoSource::Runtime => { + let c = recomp::pso::console_dxil_uncached(&blob, recomp::pso::Stage::Compute, 0, windows, split).map_err(|e| Failed(format!("{name}: {e}")))?; + let path = recomp::pso::compute_path(shader::fnv64(&blob)).unwrap_or("runtime"); + let how = format!("{} ms to translate, {path}", made.elapsed().as_millis()); + // (before the driver's compiles, which may not end: what the translation made, and the + // commit it left) + let pieces = c.dispatch_chain.as_ref().map_or(String::new(), |chain| format!(", pieces {:?} bytes", chain.pieces.iter().map(Vec::len).collect::>())); + println!("PSO {hash:016x}: translated, {how}: whole {} bytes{pieces}; process commit {} MB", c.dxil.len(), process_memory().0 >> 20); + // a split program: each piece (what a direct dispatch runs) with the chain's root + // signature, then its whole form (what an indirect dispatch runs) with the ABI one + if let Some(chain) = &c.dispatch_chain { + let rs = recomp::pso::dispatch_chain_root_signature(&pipeline.dev, &c.samplers).map_err(|e| Failed(format!("chain root signature: {e}")))?; + for (i, piece) in chain.pieces.iter().enumerate() { + let label = format!("PSO {hash:016x}: piece {}/{} {} bytes DXIL, {how}", i + 1, chain.pieces.len(), piece.len()); + time_compute_pso_in(&pipeline, rs.clone(), piece, repeat, &label, &name)?; + } + let pieces: usize = chain.pieces.iter().map(Vec::len).sum(); + let label = format!("PSO {hash:016x}: whole form {} bytes DXIL, {how}, a chain of {} pieces ({pieces} bytes)", c.dxil.len(), chain.pieces.len()); + return time_compute_pso(&pipeline, &c.dxil, &c.samplers, repeat, &label, &name); + } + (c.dxil, c.samplers, how) + } }; - let dxc_ms = dxc_start.elapsed().as_millis(); // `XCL_MEASURE_DUMP=`: the measured container as ..dxil there if let Ok(dir) = std::env::var("XCL_MEASURE_DUMP") { - let _ = std::fs::write(Path::new(&dir).join(format!("{hash:016x}.{}.dxil", if crate::gpu::dxil::kernel::enabled() { "direct" } else { "hlsl" })), &dxil); + let path = if matches!(source, PsoSource::Runtime) { "runtime" } else if crate::gpu::dxil::kernel::enabled() { "direct" } else { "hlsl" }; + let _ = std::fs::write(Path::new(&dir).join(format!("{hash:016x}.{path}.dxil")), &dxil); + } + let label = format!("PSO {hash:016x}: {} bytes DXIL, {how}", dxil.len()); + time_compute_pso(&pipeline, &dxil, &samplers, repeat, &label, &name) +} + +/// `--measure-dxil`: one exact compute DXIL – a file the translator wrote (`XCL_DXIL_DUMP`), or +/// an entry of the translated cache (`\translated\v2\\_Compute_….bin`, +/// with its static samplers) – timed as `--measure-pso` times a record's. An entry is what a run +/// handed the driver, byte for byte, so its compile can be measured long after the run. +fn measure_dxil(path: &Path, repeat: usize) -> i32 { + let r = std::fs::read(path).map_err(|e| MeasureError::Failed(format!("{}: {e}", path.display()))).and_then(|bytes| { + let (dxil, samplers) = translated_entry(&bytes).map_err(MeasureError::Failed)?; + let pipeline = cacheless_pipelines()?; + let label = format!("PSO file: {} bytes DXIL, {} static sampler(s)", dxil.len(), samplers.len()); + time_compute_pso(&pipeline, &dxil, &samplers, repeat, &label, &path.display().to_string()) + }); + match r { + Ok(()) => 0, + Err(MeasureError::Unavailable(e) | MeasureError::Failed(e)) => { + eprintln!("xcl shaders --measure-dxil: {e}"); + 2 + } } - let rs = recomp::pso::abi_root_signature_with(&pipeline.dev, true, &samplers).map_err(|e| Failed(format!("root signature: {e}")))?; +} + +/// The DXIL and static samplers of a translated-cache entry (`XCLTRAN3`: the layout +/// `pso::translated::store_in` writes, with the dispatch remap after the header; `XCLTRAN2` +/// without it), or a bare DXIL container with none. +fn translated_entry(bytes: &[u8]) -> Result<(Vec, Vec), String> { + let (remap, rest) = match bytes.strip_prefix(b"XCLTRAN3".as_slice()) { + Some(r) => (8, Some(r)), + None => (0, bytes.strip_prefix(b"XCLTRAN2".as_slice())), + }; + let Some(mut r) = rest else { + return if bytes.starts_with(b"DXBC") { Ok((bytes.to_vec(), Vec::new())) } else { Err("neither a DXIL container nor a translated-cache entry".into()) }; + }; + let short = || "a translated-cache entry cut short".to_string(); + let u32_ = |r: &mut &[u8]| -> Result { + let (v, rest) = r.split_first_chunk::<4>().ok_or_else(short)?; + *r = rest; + Ok(u32::from_le_bytes(*v)) + }; + // identity, length and second hash of the console bytes (and the dispatch remap) + r = r.get(24 + remap..).ok_or_else(short)?; + let n = u32_(&mut r)? as usize; + if n > r.len() / 17 { + return Err(short()); + } + let mut samplers = Vec::with_capacity(n); + for _ in 0..n { + let s = [u32_(&mut r)?, u32_(&mut r)?, u32_(&mut r)?, u32_(&mut r)?]; + let (&cmp, rest) = r.split_first().ok_or_else(short)?; + r = rest; + samplers.push((s, cmp != 0)); + } + let len = u32_(&mut r)? as usize; + let dxil = r.get(..len).filter(|d| d.starts_with(b"DXBC")).ok_or_else(short)?; + Ok((dxil.to_vec(), samplers)) +} + +/// The process's private commit and working set now, in bytes. The commit comes from +/// `kernelx::process_private_bytes`, which has a fallback for Wine leaving `PrivateUsage` 0. +fn process_memory() -> (u64, u64) { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + unsafe { + let mut c: PROCESS_MEMORY_COUNTERS = std::mem::zeroed(); + c.cb = std::mem::size_of_val(&c) as u32; + K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c, c.cb); + (crate::hle::kernelx::process_private_bytes(), c.WorkingSetSize as u64) + } +} + +/// `f`'s result and the most private commit and working set the process had while it ran +/// (sampled every 2 ms by another thread: the driver's compiler may use threads of its own). +fn with_peak_memory(f: impl FnOnce() -> R) -> (R, (u64, u64)) { + let stop = std::sync::atomic::AtomicBool::new(false); + std::thread::scope(|s| { + let sampler = s.spawn(|| { + let mut peak = process_memory(); + while !stop.load(Ordering::Relaxed) { + let now = process_memory(); + peak = (peak.0.max(now.0), peak.1.max(now.1)); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + peak + }); + let r = f(); + stop.store(true, Ordering::Relaxed); + let peak = sampler.join().unwrap_or((0, 0)); + let now = process_memory(); + (r, (peak.0.max(now.0), peak.1.max(now.1))) + }) +} + +/// `repeat` cold driver compiles of `dxil` with XCL's ABI root signature and `samplers`, each +/// with its time and the most commit and working set the process grew by meanwhile. +fn time_compute_pso(pipeline: &Pipelines, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], repeat: usize, label: &str, name: &str) -> Result<(), MeasureError> { + let rs = recomp::pso::abi_root_signature_with(&pipeline.dev, true, samplers).map_err(|e| MeasureError::Failed(format!("root signature: {e}")))?; + time_compute_pso_in(pipeline, rs, dxil, repeat, label, name) +} + +/// `time_compute_pso` with the root signature `rs` (a dispatch chain's piece has its own). +fn time_compute_pso_in(pipeline: &Pipelines, rs: windows::Win32::Graphics::Direct3D12::ID3D12RootSignature, dxil: &[u8], repeat: usize, label: &str, name: &str) -> Result<(), MeasureError> { + use windows::Win32::Graphics::Direct3D12::*; + use MeasureError::Failed; let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::ManuallyDrop::new(Some(rs)), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, ..Default::default() }; let mut times = Vec::with_capacity(repeat); + let mut most = (0u64, 0u64); let mut failure = None; + let mb = |b: u64| b >> 20; for run in 1..=repeat { + let before = process_memory(); let start = std::time::Instant::now(); - let result = unsafe { pipeline.dev.CreateComputePipelineState::(&desc) }; + let (result, peak) = with_peak_memory(|| unsafe { pipeline.dev.CreateComputePipelineState::(&desc) }); let elapsed = start.elapsed(); match result { Ok(pso) => drop(pso), @@ -1546,7 +1715,11 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl break; } } - println!("PSO run {run}/{repeat}: {:.3} s", elapsed.as_secs_f64()); + let grew = (peak.0.saturating_sub(before.0), peak.1.saturating_sub(before.1)); + most = (most.0.max(grew.0), most.1.max(grew.1)); + // (what the driver keeps once the pipeline is gone: a run's builds keep it as long) + let left = process_memory().0.saturating_sub(before.0); + println!("PSO run {run}/{repeat}: {:.3} s, peak +{} MB commit, +{} MB working set (from {} MB / {} MB), +{} MB commit left after", elapsed.as_secs_f64(), mb(grew.0), mb(grew.1), mb(before.0), mb(before.1), mb(left)); times.push(elapsed.as_secs_f64()); } // the root signature's reference, on every path @@ -1557,12 +1730,12 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl times.sort_by(f64::total_cmp); let median = if times.len() & 1 == 0 { (times[times.len() / 2 - 1] + times[times.len() / 2]) / 2.0 } else { times[times.len() / 2] }; println!( - "PSO {hash:016x} [{}]: {} bytes DXIL, {dxc_ms} ms translate, {repeat} cache-off run(s), median {:.3} s, min {:.3} s, max {:.3} s, {name}", - if crate::gpu::dxil::kernel::enabled() { "direct" } else { "hlsl" }, - dxil.len(), + "{label}, {repeat} cache-off run(s), median {:.3} s, min {:.3} s, max {:.3} s, peak +{} MB commit / +{} MB working set, {name}", median, times[0], - times[times.len() - 1] + times[times.len() - 1], + mb(most.0), + mb(most.1) ); Ok(()) } @@ -1748,6 +1921,41 @@ fn split_whole_roots(prewarm_indirect: bool) -> &'static [PipelineRoot] { } } +/// A pipeline of a split program that native preparation builds: its pieces, or its whole form, +/// under a root signature. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum SplitBuild { + Pieces(PipelineRoot), + Whole(PipelineRoot), +} + +/// What `prepare_compiled_compute` builds of a split program, in order. The title runs its pieces +/// (`dispatch_chain::build`); it takes the whole form under the ABI root only from a kept driver +/// blob or the pipeline library (`ComputeBuild::CachedWhole`), and builds the one under the chain +/// root only at an indirect dispatch (`dispatch_chain::whole_ready`). So without that keeping +/// (`whole_kept` false: AMD by default) the whole forms are built only for the programs earlier +/// runs dispatched indirectly, as `make_selected` builds them: a retail title's 49 split programs +/// had whole forms of 64 – 486 KB of DXIL, whose cold driver compiles took 53 of the 60 s one +/// such program cost (RX 9070 XT), for pipelines the title never asked the driver for. +fn split_builds(prewarm_indirect: bool, whole_kept: bool) -> Vec { + let mut builds = Vec::new(); + if whole_kept { builds.push(SplitBuild::Whole(PipelineRoot::Whole)); } + for &root in split_piece_roots(prewarm_indirect) { + builds.push(SplitBuild::Pieces(root)); + if whole_kept || split_whole_roots(prewarm_indirect).contains(&root) { + builds.push(SplitBuild::Whole(root)); + } + } + builds +} + +/// Whether the title can take a split program's whole form without the driver compiling it: from +/// XCL's driver-blob files or its pipeline library (`XCL_PSO_DISK_CACHE`, `XCL_PSO_LIBRARY`; both +/// off on AMD by default, where the driver keeps its own cache). +fn whole_form_kept() -> bool { + crate::hle::d3d12x::real::driver_cache::enabled() || pipeline_library::enabled() +} + fn required_piece_workers(piece_count: usize, root: PipelineRoot) -> usize { if root == PipelineRoot::IndirectChain { piece_count.min(2) } else { 1 } } @@ -1856,6 +2064,25 @@ mod inflight_build_tests { ); } + /// Without kept whole forms (AMD by default), native preparation builds a split program's + /// pieces and no whole form the title would not use: the whole ones only for a program earlier + /// runs dispatched indirectly, as `make_selected` does. With them it builds all, as before. + #[test] + fn split_programs_get_whole_forms_only_where_the_title_takes_them() { + use super::SplitBuild::{Pieces, Whole}; + use PipelineRoot::{DirectChain, IndirectChain}; + assert_eq!(super::split_builds(false, false), [Pieces(DirectChain)]); + assert_eq!( + super::split_builds(true, false), + [Pieces(DirectChain), Whole(DirectChain), Pieces(IndirectChain), Whole(IndirectChain)], + ); + assert_eq!(super::split_builds(false, true), [Whole(PipelineRoot::Whole), Pieces(DirectChain), Whole(DirectChain)]); + assert_eq!( + super::split_builds(true, true), + [Whole(PipelineRoot::Whole), Pieces(DirectChain), Whole(DirectChain), Pieces(IndirectChain), Whole(IndirectChain)], + ); + } + #[test] fn required_indirect_piece_preparation_is_capped_at_two_workers() { assert_eq!(super::required_piece_workers(0, PipelineRoot::IndirectChain), 0); @@ -2396,7 +2623,8 @@ mod pipeline_cap_tests { } /// Startup preparation (`prepare_compiled_compute`) of a split program builds its whole once, - /// under the ABI root, and no chain; with the whole over the cap it builds the pieces instead. + /// under the ABI root, and no chain, where whole forms are kept; with the whole over the cap it + /// builds the pieces instead. Without kept whole forms it builds the pieces (`split_builds`). #[test] fn startup_preparation_builds_a_split_programs_whole_and_no_chain() { use super::{Pipelines, recomp}; @@ -2460,6 +2688,11 @@ mod pipeline_cap_tests { Scratch(dir) }; + // kept whole forms, as with `XCL_PSO_LIBRARY=1` (the driver-blob files have no test hook): on + // AMD both are off by default, and preparation would then build for that case (below) + let library_on = crate::shaders::pipeline_library::force_on_for_test(); + assert!(super::whole_form_kept()); + // the whole is built and kept: nothing else, an indirect dispatch included let kept = scratch("kept"); pipelines.cache_dir = Some(kept.0.clone()); @@ -2478,6 +2711,28 @@ mod pipeline_cap_tests { let mut want = vec![driver_cache::name_for(&piece0, 0, true), driver_cache::name_for(&piece1, 0, true)]; want.sort(); assert_eq!(blobs(&capped.0), want, "the pieces only"); + drop(library_on); + + // no kept whole forms (AMD by default): the title runs the pieces and never takes the ABI + // whole, so that is not built; the chain-root wholes only for a program dispatched indirectly + if super::whole_form_kept() { + recomp::runner::skip_test("whole forms are kept on this adapter (XCL_PSO_DISK_CACHE): no case without them"); + return; + } + pipelines.max_dxil = 0; + let chain_name = |dxil: &[u8], root| driver_cache::name_for_chain_root_node(dxil, 0, root, &[], 0); + let (direct, indirect) = (driver_cache::ChainRoot::DirectConstants, driver_cache::ChainRoot::IndirectCbv); + for prewarm_indirect in [false, true] { + let unkept = scratch(if prewarm_indirect { "unkept-indirect" } else { "unkept" }); + pipelines.cache_dir = Some(unkept.0.clone()); + pipelines.prepare_compiled_compute(&compiled, prewarm_indirect).expect("prepared without kept wholes"); + let mut want = vec![chain_name(&piece0, direct), chain_name(&piece1, direct)]; + if prewarm_indirect { + want.extend([chain_name(&whole, direct), chain_name(&piece0, indirect), chain_name(&piece1, indirect), chain_name(&whole, indirect)]); + } + want.sort(); + assert_eq!(blobs(&unkept.0), want, "no ABI whole (indirect: {prewarm_indirect})"); + } } } @@ -2501,6 +2756,7 @@ impl Pipelines { (crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?, desc.VendorId) }; crate::hle::d3d12x::real::driver_cache::note_vendor(vendor); + crate::shaders::pipeline_library::note_vendor(vendor); let most = pipeline_threads(); let max_dxil = pipeline_cap_kb(std::env::var("XCL_PIPELINE_MAX_KB").ok().as_deref()).saturating_mul(1024); Ok(Pipelines { @@ -2575,8 +2831,21 @@ impl Pipelines { let make = |dxil: &[u8], root| { self.make_required(dxil, &program.samplers, root, None, true) }; + let Some(chain) = program.dispatch_chain.as_deref().filter(|c| c.pieces.len() >= 2) else { + return make(&program.dxil, PipelineRoot::Whole); + }; + if !whole_form_kept() { + // (the title cannot take the whole forms: its pieces, and the whole forms of the + // programs earlier runs dispatched indirectly) + for build in split_builds(prewarm_indirect, false) { + match build { + SplitBuild::Pieces(root) => self.make_chain_pieces_required(&chain.pieces, &program.samplers, root)?, + SplitBuild::Whole(root) => make(&program.dxil, root)?, + } + } + return Ok(()); + } let whole = make(&program.dxil, PipelineRoot::Whole); - let Some(chain) = program.dispatch_chain.as_deref().filter(|c| c.pieces.len() >= 2) else { return whole }; let on_disk = whole.is_ok() && self.whole_blob_path(&program.dxil, &program.samplers).is_some_and(|p| p.is_file()); if !chain_needed(whole.is_ok(), on_disk) { return Ok(()); @@ -3371,7 +3640,9 @@ fn prepare_title_inputs(root: &Path, progress: &LaunchPreparation, corpus: Optio let pack = root.join("shaders.rpf"); progress.total.store(inputs.iter().map(Input::len).sum(), Ordering::Relaxed); let mut windows = crate::gpu::uma::configured_runtime_windows() as u32; - if windows > 1 && recomp::pso::heap_windows() { windows |= recomp::HEAP_WINDOWS; } + if windows > 1 && recomp::pso::heap_windows() { + windows |= recomp::HEAP_WINDOWS | if recomp::pso::heap_flat() { recomp::HEAP_FLAT } else { 0 }; + } let workers = prepare_workers(); for input in &inputs { let coverage = corpus.filter(|c| c.compute_directory().is_some()) @@ -3469,26 +3740,31 @@ impl ComputeCoverage<'_> { } /// `XCL_PREPARE_WORKERS`: the processes that build a pack's compute pipelines before a title -/// starts (1: in this process, as before). Unset: the logical processors less four, and no -/// more than 3 GB of the commit the system has left for each. +/// starts (1: in this process, as before). Unset: the logical processors less four, no more +/// than 3 GB of the commit the system has left for each, and no more than 2 GB of the RAM +/// available for each with 4 GB left over (a worker held 1.4–3 GB of RAM on a retail title's +/// pack: 16 of them took a 32 GB PC to under 6 GB available before the title had started). fn prepare_workers() -> usize { if let Some(n) = std::env::var("XCL_PREPARE_WORKERS").ok().and_then(|v| v.parse::().ok()) { return n.clamp(1, 32); } let cores = std::thread::available_parallelism().map_or(4, |n| n.get()); + // (`system_commit` is in bytes) let (used, limit) = crate::host::system_commit(); - workers_for_commit(cores, used, limit) + workers_for_commit(cores, used, limit, crate::ram_budget::available()) } -/// The workers for `cores` logical processors and the system's commit charge `used` and its -/// `limit`, both in bytes as `host::system_commit` gives them. -fn workers_for_commit(cores: usize, used: u64, limit: u64) -> usize { - workers_for(cores, limit.saturating_sub(used) >> 20) +/// The workers for `cores` logical processors, the system's commit charge `used` and its +/// `limit`, and `ram` available, all in bytes as `host::system_commit` and +/// `ram_budget::available` give them. +fn workers_for_commit(cores: usize, used: u64, limit: u64, ram: u64) -> usize { + workers_for(cores, limit.saturating_sub(used) >> 20, ram >> 20) } -/// The workers for `cores` logical processors (threads, not cores) and `free_mb` of commit left. -fn workers_for(cores: usize, free_mb: u64) -> usize { - cores.saturating_sub(4).min(32).min((free_mb / 3072) as usize).max(1) +/// The workers for `cores` logical processors (threads, not cores), `free_mb` of commit left +/// and `ram_mb` of RAM available. +fn workers_for(cores: usize, free_mb: u64, ram_mb: u64) -> usize { + cores.saturating_sub(4).min(32).min((free_mb / 3072) as usize).min((ram_mb.saturating_sub(4096) / 2048) as usize).max(1) } /// The record count of a builder's progress line (` 400/26503 (12 s)`). @@ -3529,7 +3805,8 @@ fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usiz /// that profile's used-pipeline list (`used_pipelines_name`). fn pipeline_worker_command(me: &Path, pack: &Path, windows: u32, used_only: bool, slice: &str, series_s: bool) -> std::process::Command { let mut c = worker_command(me); - c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); + // (the count alone: the worker adds the heap flags as the title takes them, `runtime_windows`) + c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT)).to_string()); if used_only { c.arg("--used-only"); } c.env("XCL_PRECOMPILE_SLICE", slice); c.env("XCL_DEVICE_TYPE", if series_s { "lockhart" } else { "anaconda" }); @@ -3768,7 +4045,7 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: progress.graphics.store(true, Ordering::Relaxed); let (cancelled, failed, summaries) = in_workers(workers, buildable.len(), progress, |i| { let mut c = worker_command(&me); - c.arg("shaders").arg(&jobs[i].0).args(["--graphics-records", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); + c.arg("shaders").arg(&jobs[i].0).args(["--graphics-records", "--windows"]).arg((windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT)).to_string()); // (the title's adapter: its blobs are the ones it takes) if std::env::var_os("XCL_ADAPTER").is_none() && !progress.adapter.is_empty() { c.env("XCL_ADAPTER", &progress.adapter); } c @@ -4223,6 +4500,11 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on Ok(false) => {} } } + // the title's pipeline would leave it out too (`gpu::rt_leave_out`) + if crate::gpu::rt_leave_out::left_out(&blob) { + record_done(); + continue; + } match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { if let Some(p) = pipelines { @@ -4406,6 +4688,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on skipped.into_inner(), t0.elapsed().as_secs_f64() ); + if crate::gpu::rt_leave_out::enabled() { + println!("compute programs passed over (XCL_RT_LEAVE_OUT): {}", crate::gpu::rt_leave_out::left_out_count()); + } if let Some(p) = pipelines { if startup.is_none() { make_pipelines(p, pipeline_jobs.into_inner().unwrap()); @@ -4796,23 +5081,47 @@ mod tests { /// 3 GB of commit for each, and one where there is no room. #[test] fn preparation_workers_leave_two_processors_and_follow_the_commit_left() { - assert_eq!(workers_for(32, 100_000), 28); - assert_eq!(workers_for(8, 100_000), 4); - assert_eq!(workers_for(32, 10_000), 3); - assert_eq!(workers_for(2, 100_000), 1); - assert_eq!(workers_for(64, 1_000_000), 32); - assert_eq!(workers_for(32, 0), 1); + const RAM: u64 = 1_000_000; + assert_eq!(workers_for(32, 100_000, RAM), 28); + assert_eq!(workers_for(8, 100_000, RAM), 4); + assert_eq!(workers_for(32, 10_000, RAM), 3); + assert_eq!(workers_for(2, 100_000, RAM), 1); + assert_eq!(workers_for(64, 1_000_000, RAM), 32); + assert_eq!(workers_for(32, 0, RAM), 1); + } + + /// The workers also follow the RAM available: 2 GB for each with 4 GB left over (a 32 GB + /// PC with 18 GB available and a large page file: 6, not one for every logical processor). + #[test] + fn preparation_workers_follow_the_ram_available() { + assert_eq!(workers_for(20, 54_000, 18_000), 6); + assert_eq!(workers_for(20, 54_000, 40_000), 16); + assert_eq!(workers_for(20, 54_000, 5_000), 1); + assert_eq!(workers_for(20, 54_000, 0), 1); + } + + /// `prepare_workers` gives `workers_for` megabytes: `host::system_commit` is in bytes, and a + /// commit left in bytes divided as megabytes never limited anything. + #[test] + fn preparation_workers_are_bounded_by_this_systems_commit_in_megabytes() { + let (used, limit) = crate::host::system_commit(); + let free_mb = limit.saturating_sub(used) >> 20; + assert!(free_mb < 1 << 24, "the commit left is in megabytes here ({free_mb})"); + assert!(workers_for(64, free_mb, 1 << 20) <= (free_mb / 3072).max(1) as usize); } /// The commit figures come in bytes: 6 GiB left on 16 logical processors is room for two - /// workers, not twelve; a commit that is not known (0, 0) gives one. + /// workers, not twelve; a commit that is not known (0, 0) gives one. The RAM available is in + /// bytes too (with plenty of it the commit decides). #[test] fn preparation_workers_take_the_commit_left_in_bytes() { const GIB: u64 = 1 << 30; - assert_eq!(workers_for_commit(16, 10 * GIB, 16 * GIB), 2); - assert_eq!(workers_for_commit(16, 0, 64 * GIB), 12); - assert_eq!(workers_for_commit(16, 0, 0), 1); - assert_eq!(workers_for_commit(16, 20 * GIB, 16 * GIB), 1); + const RAM: u64 = 64 * GIB; + assert_eq!(workers_for_commit(16, 10 * GIB, 16 * GIB, RAM), 2); + assert_eq!(workers_for_commit(16, 0, 64 * GIB, RAM), 12); + assert_eq!(workers_for_commit(16, 0, 0, RAM), 1); + assert_eq!(workers_for_commit(16, 20 * GIB, 16 * GIB, RAM), 1); + assert_eq!(workers_for_commit(16, 0, 64 * GIB, 10 * GIB), 3); } /// A builder's progress line gives its record count; its other lines give none. @@ -5031,6 +5340,18 @@ mod tests { assert_eq!(dev_env(false).as_deref(), Some("anaconda")); } + /// A compute worker gets the title's window count alone: with `XCL_HEAP_FLAT=1` the flat bit + /// made `--windows 528`, which the worker refused (`valid_window_count`), and every worker + /// failed the launch's preparation. + #[test] + fn pipeline_worker_command_passes_the_window_count_without_heap_flags() { + let windows = 16 | crate::gpu::recomp::HEAP_WINDOWS | crate::gpu::recomp::HEAP_FLAT; + let cmd = super::pipeline_worker_command(Path::new("xcl.exe"), Path::new("shaders.rpf"), windows, false, "0/2", true); + let args: Vec<_> = cmd.get_args().map(|a| a.to_string_lossy().into_owned()).collect(); + let at = args.iter().position(|a| a == "--windows").expect("--windows"); + assert_eq!(args[at + 1], "16"); + } + use super::*; use crate::gpu::xbox::tests::{fssm, sample, CODE}; @@ -5194,7 +5515,7 @@ mod tests { let blob = compute_sample(); std::fs::write(&path.0, &blob).unwrap(); let hash = shader::fnv64(&blob); - match measure_pso_result(&Input::Files(vec![path.0.clone()]), hash, 1, 4, None) { + match measure_pso_result(&Input::Files(vec![path.0.clone()]), hash, 1, 4, None, PsoSource::Hlsl) { Ok(()) => {} // no DXC, a WARP-only or cacheless device, cache control without Developer Mode Err(MeasureError::Unavailable(e)) => recomp::runner::skip_test(&e), @@ -5202,6 +5523,40 @@ mod tests { } } + /// `--measure-dxil` reads a translated-cache entry (its static samplers and DXIL, as + /// `pso::translated::store_in` writes them) or a bare container, and refuses anything else. + #[test] + fn a_translated_cache_entry_gives_its_dxil_and_samplers() { + let dxil = b"DXBC and the rest of a container".to_vec(); + let mut entry = b"XCLTRAN2".to_vec(); + entry.extend([7u8; 24]); + entry.extend(1u32.to_le_bytes()); + for w in [1u32, 2, 3, 4] { + entry.extend(w.to_le_bytes()); + } + entry.push(1); + entry.extend((dxil.len() as u32).to_le_bytes()); + entry.extend(&dxil); + let (d, samplers) = translated_entry(&entry).unwrap(); + assert_eq!(d, dxil); + assert_eq!(samplers, vec![([1, 2, 3, 4], true)]); + assert_eq!(translated_entry(&dxil).unwrap(), (dxil.clone(), vec![])); + assert!(translated_entry(&entry[..entry.len() - 4]).is_err(), "cut short"); + assert!(translated_entry(b"not a shader").is_err()); + } + + /// The peak a compile is measured by sees memory the process took and gave back meanwhile. + #[test] + fn the_peak_memory_counts_what_was_given_back() { + let before = process_memory().0; + let ((), (peak_commit, _)) = with_peak_memory(|| { + let v = vec![1u8; 256 << 20]; + std::thread::sleep(std::time::Duration::from_millis(50)); + drop(std::hint::black_box(v)); + }); + assert!(peak_commit >= before + (128 << 20), "peak {} MB, before {} MB", peak_commit >> 20, before >> 20); + } + #[test] fn aggregates_console_shaders() { let mut a = Agg::default(); diff --git a/crates/xcl/src/shaders/pipeline_library.rs b/crates/xcl/src/shaders/pipeline_library.rs index f9a538e59e..a279100376 100644 --- a/crates/xcl/src/shaders/pipeline_library.rs +++ b/crates/xcl/src/shaders/pipeline_library.rs @@ -28,7 +28,50 @@ struct Active { static ACTIVE: std::sync::OnceLock = std::sync::OnceLock::new(); +static AMD_VENDOR: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +fn env_override() -> Option { + static OVERRIDE: std::sync::OnceLock> = std::sync::OnceLock::new(); + *OVERRIDE.get_or_init(|| match std::env::var("XCL_PSO_LIBRARY") { + Ok(v) => match v.trim() { + "" => None, + "0" => Some(false), + _ => Some(true), + }, + Err(_) => None, + }) +} + +fn enabled_for(env: Option, amd: bool) -> bool { + env.unwrap_or(!amd) +} + +/// Record the adapter PCI vendor ID. On AMD (`0x1002`), `ID3D12PipelineLibrary1` stores only tiny +/// stub entries (e.g. ~0.2 MiB for 1,000+ pipelines) and loading/serializing two-pass pipelines +/// through it triggers GPU page faults (`0x887a0006`) on RDNA4 (amd-dev f33df5a7). Default it off +/// on AMD (which relies on the driver's own DxCache) unless `XCL_PSO_LIBRARY=1` forces it on. +pub(crate) fn note_vendor(vendor: u32) { + let is_amd = vendor == 0x1002; + let was = AMD_VENDOR.fetch_or(is_amd, std::sync::atomic::Ordering::Relaxed); + if is_amd && !was && !enabled() { + crate::xlog_info!("D3D12.X: pipeline library off on AMD by default (XCL_PSO_LIBRARY=1: force on)"); + } +} + +/// Whether the native pipeline library is used (`XCL_PSO_LIBRARY=0` disables, `XCL_PSO_LIBRARY=1` +/// forces on; defaults off on AMD `0x1002` and on for other vendors). +pub(crate) fn enabled() -> bool { + #[cfg(test)] + if FORCED_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed) { + return true; + } + enabled_for(env_override(), AMD_VENDOR.load(std::sync::atomic::Ordering::Relaxed)) +} + pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { + if !enabled() { + return Ok(()); + } let Some(ready) = super::warm_library::take_ready() else { return Ok(()) }; let driver = crate::hle::d3d12x::real::preparation_driver_identity(device) .ok_or("Pipeline library: runtime driver identity is unavailable")?; @@ -84,7 +127,7 @@ pub(crate) fn load_stream(name: &str, desc: &D3D12_PIPELINE_STATE_STREAM_DESC) - pub(crate) fn building() -> bool { BUILD.lock().unwrap().is_some() } pub(crate) fn begin(device: &ID3D12Device, previous: Option<&std::path::Path>) -> std::result::Result { - if !NativeLibrary::supported(device) { return Ok(false) } + if !enabled() || !NativeLibrary::supported(device) { return Ok(false) } let library = NativeLibrary::empty(device).map_err(|e| format!("Creating pipeline library: {e}"))?; let previous = previous .and_then(|path| std::fs::read(path).ok()) @@ -155,6 +198,21 @@ pub(crate) fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Res #[cfg(test)] pub(crate) static BUILD_TEST: std::sync::Mutex<()> = std::sync::Mutex::new(()); +#[cfg(test)] +static FORCED_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// The tests of the library itself, holding `BUILD_TEST`: the library is on (as with +/// `XCL_PSO_LIBRARY=1`) until this is dropped, also on AMD, where it is off by default. +#[cfg(test)] +pub(crate) fn force_on_for_test() -> impl Drop { + struct On; + impl Drop for On { + fn drop(&mut self) { FORCED_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); } + } + FORCED_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + On +} + pub(crate) struct NativeLibrary { library: ID3D12PipelineLibrary1, _serialized: std::sync::Arc<[u8]>, @@ -239,6 +297,14 @@ impl NativeLibrary { #[cfg(test)] mod tests { + #[test] + fn vendor_default_disables_pipeline_library_on_amd_unless_overridden() { + assert!(!super::enabled_for(None, true)); + assert!(super::enabled_for(None, false)); + assert!(super::enabled_for(Some(true), true)); + assert!(!super::enabled_for(Some(false), false)); + } + use super::{abort, begin, finish, store, NativeLibrary, BUILD_TEST}; use crate::gpu::recomp; use crate::shaders::Pipelines; @@ -383,6 +449,7 @@ void main() {{ output.Store(0, {n}); }} #[test] fn builder_deduplicates_names_and_atomically_replaces_output() { let _serial = BUILD_TEST.lock().unwrap_or_else(|e| e.into_inner()); + let _on = super::force_on_for_test(); let Some((pipelines, dxil, root)) = fixture() else { return }; let desc = compute_desc(&dxil, &root); let pso = unsafe { pipelines.dev.CreateComputePipelineState::(&desc) } @@ -425,6 +492,7 @@ void main() {{ output.Store(0, {n}); }} #[test] fn graphics_pipeline_round_trips_through_serialized_library() { let _serial = BUILD_TEST.lock().unwrap_or_else(|e| e.into_inner()); + let _on = super::force_on_for_test(); let Some((pipelines, _, _)) = fixture() else { return }; let source = r#" #define RS "" @@ -489,6 +557,7 @@ struct V { float4 p : SV_Position; }; #[test] fn mesh_pipeline_round_trips_through_serialized_library() { let _serial = BUILD_TEST.lock().unwrap_or_else(|e| e.into_inner()); + let _on = super::force_on_for_test(); let Some((pipelines, _, _)) = fixture() else { return }; let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); if unsafe { diff --git a/crates/xcl/src/shaders/warm_library.rs b/crates/xcl/src/shaders/warm_library.rs index 657ace839b..e03d7733b0 100644 --- a/crates/xcl/src/shaders/warm_library.rs +++ b/crates/xcl/src/shaders/warm_library.rs @@ -454,6 +454,7 @@ mod tests { }; let pso = unsafe { pipelines.dev.CreateComputePipelineState::(&desc) }.unwrap(); let _serial = super::super::pipeline_library::BUILD_TEST.lock().unwrap_or_else(|e| e.into_inner()); + let _on = super::super::pipeline_library::force_on_for_test(); super::super::pipeline_library::abort(); assert!(super::super::pipeline_library::begin(&pipelines.dev, None).unwrap()); super::super::pipeline_library::store("fixture.pso".into(), &pso).unwrap(); diff --git a/crates/xcl/src/title_patch.rs b/crates/xcl/src/title_patch.rs new file mode 100644 index 0000000000..55b5526200 --- /dev/null +++ b/crates/xcl/src/title_patch.rs @@ -0,0 +1,240 @@ +//! Places in a retail title's code changed when its executable is mapped, each only where the +//! title's bytes are the ones expected (another build of the title is left alone, said so). +//! +//! - `XCL_UPSCALER=6` (or `7`; unset: as the title picks): the title's upscaler picker +//! (game_scarlett_master.exe 1.0.2.1, image offset +0x7e93f0) returns that kind: 6 the title's +//! own upscaler, 7 AMD FidelityFX. The title picks FidelityFX on a Series S whose feature flags +//! have bit 0x40 set (XCL's do), its own otherwise. With the console's FidelityFX (FSR4) the +//! people left copies along their path and the last shot showed through a camera cut, though +//! the title asked for a reset at the cuts (`hle::ffx`); its jitter phase count is what the +//! title divides by at +0x28f03e8, so leaving the upscaler's DLL out instead ends the title there. +//! With 6, Series S's heap 2 grows too (`SERIES_S_HEAPS`): the title sized it for FidelityFX. +//! +//! The picker's bytes and offsets are from Whiplash (a VIctory descendant, GPL-3.0-or-later, +//! `Kalmarv/whiplash` 699f191, `Whiplash-AMD/crates/victory-loader/src/resolution.rs`, +//! `VICTORY_UPSCALER`, after VIctory pull request #53); see `THIRD_PARTY.md`. The heap sizes are +//! XCL's own finding (Whiplash runs the title as a Series X, whose picker returns 6 anyway). + +/// A place to change: its offset in the image and the bytes expected there (the replacement is +/// at most as long). +pub struct Site { + pub at: usize, + pub what: &'static str, + pub bytes: &'static [u8], +} + +/// The upscaler picker, +0x7e93f0, to its first `ret`: 6 unless a check passes and a feature +/// flag has bit 0x40, then 7. +pub const PICKER: Site = Site { + at: 0x7e93f0, + what: "upscaler picker", + bytes: &[ + 0x48, 0x83, 0xec, 0x28, 0x80, 0x3d, 0x6d, 0xf0, 0x3a, 0x07, 0x00, 0x75, 0x09, 0x83, 0x3d, 0x68, 0xf0, 0x3a, 0x07, 0x00, + 0x74, 0x28, 0xe8, 0x35, 0xbd, 0x88, 0xff, 0x8a, 0x0d, 0x5b, 0xf0, 0x3a, 0x07, 0x80, 0xe1, 0x40, 0x80, 0xf9, 0x01, 0xb9, + 0x07, 0x00, 0x00, 0x00, 0x83, 0xd9, 0x00, 0x84, 0xc0, 0xb8, 0x06, 0x00, 0x00, 0x00, 0x0f, 0x45, 0xc1, 0x48, 0x83, 0xc4, + 0x28, 0xc3, + ], +}; + +/// The title's heap sizes per console, +0x6186250 (read at start by +0x1e1ced0, the heaps made +/// by +0x1e1cf60): Series S's row, ten 8-byte sizes – the total, then heaps 0 to 8 (8572 MB in +/// all); Series X's row (13312 MB) follows it. Heap 2 is 1277 MB on Series S, 2199 MB on Series +/// X: with the title's own upscaler on a Series S it runs out at start (a 576 KiB allocation of +/// it fails, the title stops at its `int3` at +0x2219650: runs next-r12/r13), so it is sized for +/// FidelityFX there. +pub const SERIES_S_HEAPS: Site = Site { + at: 0x6186250, + what: "Series S heap sizes", + bytes: &[ + 0x00, 0x00, 0xc0, 0x17, 0x02, 0x00, 0x00, 0x00, // total 8572 MB + 0x00, 0x00, 0xa0, 0x48, 0x00, 0x00, 0x00, 0x00, // 0: 1162 MB + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 1 + 0x00, 0x00, 0xd0, 0x4f, 0x00, 0x00, 0x00, 0x00, // 2: 1277 MB + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 3 + 0x00, 0x00, 0x20, 0x0c, 0x00, 0x00, 0x00, 0x00, // 4: 194 MB + 0x00, 0x00, 0x20, 0x10, 0x00, 0x00, 0x00, 0x00, // 5: 258 MB + 0x00, 0x00, 0x80, 0x23, 0x00, 0x00, 0x00, 0x00, // 6: 568 MB + 0x00, 0x00, 0x20, 0x27, 0x01, 0x00, 0x00, 0x00, // 7: 4722 MB + 0x00, 0x00, 0x70, 0x18, 0x00, 0x00, 0x00, 0x00, // 8: 391 MB + ], +}; + +/// What Series S's heap 2 (and so the total) gains with the title's own upscaler by default. +/// Overridable via `XCL_UPSCALER_HEAP_MB` (e.g. `256` to save 256 MB VRAM on 16 GB cards). +pub const OWN_UPSCALER_HEAP_GROWTH: u64 = 512 << 20; + +fn upscaler_heap_growth(raw: Option<&str>) -> u64 { + let Some(v) = raw else { return OWN_UPSCALER_HEAP_GROWTH }; + match v.trim().parse::() { + Ok(mb) if mb <= 2048 => mb << 20, + _ => { + crate::xlog_warn!("XCL_UPSCALER_HEAP_MB={v}: expected 0..=2048 MB; using default {} MB", OWN_UPSCALER_HEAP_GROWTH >> 20); + OWN_UPSCALER_HEAP_GROWTH + } + } +} + +/// Series S's row of heap sizes with heap 2 and the total grown by `growth` bytes. +pub fn series_s_heaps_grown(growth: u64) -> Vec { + let mut row = SERIES_S_HEAPS.bytes.to_vec(); + for at in [0, 3 * 8] { + let size = u64::from_le_bytes(row[at..at + 8].try_into().unwrap()) + growth; + row[at..at + 8].copy_from_slice(&size.to_le_bytes()); + } + row +} + +/// `mov eax, kind ; ret`. +pub fn picker_code(kind: u32) -> Vec { + let mut c = vec![0xb8]; + c.extend(kind.to_le_bytes()); + c.push(0xc3); + c +} + +/// `XCL_UPSCALER`: 6 or 7 (None: unset or anything else, said so). +fn parse_upscaler(v: Option<&str>) -> Option { + let v = v?; + let kind = v.trim().parse::().ok().filter(|k| matches!(k, 6 | 7)); + if kind.is_none() { + crate::xlog_warn!("XCL_UPSCALER={v}: expected 6 (the title's own upscaler) or 7 (FidelityFX): left as the title picks"); + } + kind +} + +#[derive(Debug, PartialEq, Eq)] +pub enum Patched { + Done, + /// the title's bytes there are not the ones expected (another build) + Differs, + Failed(&'static str), +} + +/// `code` written over `site` in `image` (its bytes in memory) when the bytes there are +/// `site.bytes`; nothing written otherwise. +pub fn patch_bytes(image: &mut [u8], site: &Site, code: &[u8]) -> Patched { + debug_assert!(code.len() <= site.bytes.len()); + match image.get_mut(site.at..site.at + site.bytes.len()) { + None => Patched::Failed("outside the image"), + Some(at) if at != site.bytes => Patched::Differs, + Some(at) => { + at[..code.len()].copy_from_slice(code); + Patched::Done + } + } +} + +/// What the switches ask for, applied to the mapped image of `size` bytes at `base` (its code +/// writable or made so for the write); a line each in the log. +/// +/// # Safety +/// The image is mapped and no thread runs its code yet. +pub unsafe fn apply(base: usize, size: usize, image: &str) { + let Some(kind) = parse_upscaler(std::env::var("XCL_UPSCALER").ok().as_deref()) else { return }; + let picked = write_site(base, size, &PICKER, &picker_code(kind)); + match picked { + Patched::Done => crate::xlog_info!("{image}: {} at +{:#x} returns {kind} (XCL_UPSCALER: 6 the title's own upscaler, 7 FidelityFX)", PICKER.what, PICKER.at), + ref other => crate::xlog_warn!("{image}: {} at +{:#x} not patched: {other:?} (another build of the title?)", PICKER.what, PICKER.at), + } + // the title's own upscaler on a Series S: room for it in heap 2 (`SERIES_S_HEAPS`) + if kind == 6 && picked == Patched::Done { + let growth = upscaler_heap_growth(std::env::var("XCL_UPSCALER_HEAP_MB").ok().as_deref()); + if growth > 0 { + match write_site(base, size, &SERIES_S_HEAPS, &series_s_heaps_grown(growth)) { + Patched::Done => crate::xlog_info!( + "{image}: {} at +{:#x}: heap 2 is {} MB (+{} MB) for the title's own upscaler", + SERIES_S_HEAPS.what, + SERIES_S_HEAPS.at, + (0x4fd0_0000 + growth) >> 20, + growth >> 20 + ), + other => crate::xlog_warn!("{image}: {} at +{:#x} not changed: {other:?} (another build of the title?)", SERIES_S_HEAPS.what, SERIES_S_HEAPS.at), + } + } + } +} + +/// `code` over `site` of the mapped image at `base` (`patch_bytes`), its pages made writable for +/// the write and given back their protection after it. +unsafe fn write_site(base: usize, size: usize, site: &Site, code: &[u8]) -> Patched { + use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; + if site.at + site.bytes.len() > size { + return Patched::Failed("outside the image"); + } + let at = base + site.at; + let mut old = 0u32; + if VirtualProtect(at as *const std::ffi::c_void, site.bytes.len(), PAGE_EXECUTE_READWRITE, &mut old) == 0 { + return Patched::Failed("its page could not be made writable"); + } + let bytes = std::slice::from_raw_parts_mut(at as *mut u8, site.bytes.len()); + // (`patch_bytes` sees the site's bytes as an image starting at the site) + let local = Site { at: 0, what: site.what, bytes: site.bytes }; + let done = patch_bytes(bytes, &local, code); + VirtualProtect(at as *const std::ffi::c_void, site.bytes.len(), old, &mut old); + windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache(windows_sys::Win32::System::Threading::GetCurrentProcess(), at as *const std::ffi::c_void, site.bytes.len()); + done +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_picker_returns_the_kind_asked_for() { + assert_eq!(picker_code(6), [0xb8, 6, 0, 0, 0, 0xc3]); + assert_eq!(picker_code(7), [0xb8, 7, 0, 0, 0, 0xc3]); + } + + #[test] + fn the_upscaler_switch_takes_6_or_7_only() { + assert_eq!(parse_upscaler(Some("6")), Some(6)); + assert_eq!(parse_upscaler(Some(" 7 ")), Some(7)); + assert_eq!(parse_upscaler(Some("8")), None); + assert_eq!(parse_upscaler(Some("own")), None); + assert_eq!(parse_upscaler(None), None); + } + + /// The bytes are written only where the title has the expected ones, and only the first + /// `code.len()` of them. + #[test] + fn a_site_is_patched_only_over_the_expected_bytes() { + let mut image = vec![0xccu8; PICKER.at + PICKER.bytes.len() + 16]; + image[PICKER.at..PICKER.at + PICKER.bytes.len()].copy_from_slice(PICKER.bytes); + assert_eq!(patch_bytes(&mut image, &PICKER, &picker_code(6)), Patched::Done); + assert_eq!(&image[PICKER.at..PICKER.at + 6], &[0xb8, 6, 0, 0, 0, 0xc3]); + assert_eq!(&image[PICKER.at + 6..PICKER.at + PICKER.bytes.len()], &PICKER.bytes[6..]); + // patched once, the bytes there differ: a second patch leaves them + let before = image.clone(); + assert_eq!(patch_bytes(&mut image, &PICKER, &picker_code(7)), Patched::Differs); + assert_eq!(image, before); + // an image too short for the site + assert_eq!(patch_bytes(&mut [0u8; 16], &PICKER, &picker_code(6)), Patched::Failed("outside the image")); + } + + /// Series S's row: the heaps add up to its total; grown, heap 2 and the total gain the same + /// and nothing else changes. + #[test] + fn series_s_heap_2_grows_with_the_total() { + let sizes = |row: &[u8]| row.chunks(8).map(|c| u64::from_le_bytes(c.try_into().unwrap())).collect::>(); + let before = sizes(SERIES_S_HEAPS.bytes); + assert_eq!(before.len(), 10); + assert_eq!(before[0], before[1..].iter().sum::()); + assert_eq!((before[0] >> 20, before[3] >> 20), (8572, 1277)); + let after = sizes(&series_s_heaps_grown(512 << 20)); + assert_eq!(after[0], before[0] + (512 << 20)); + assert_eq!(after[3], before[3] + (512 << 20)); + assert_eq!(after[0], after[1..].iter().sum::()); + for i in [1, 2, 4, 5, 6, 7, 8, 9] { + assert_eq!(after[i], before[i]); + } + } + + #[test] + fn upscaler_heap_mb_switch_overrides_growth() { + assert_eq!(upscaler_heap_growth(None), OWN_UPSCALER_HEAP_GROWTH); + assert_eq!(upscaler_heap_growth(Some("256")), 256 << 20); + assert_eq!(upscaler_heap_growth(Some(" 0 ")), 0); + assert_eq!(upscaler_heap_growth(Some("9999")), OWN_UPSCALER_HEAP_GROWTH); + assert_eq!(upscaler_heap_growth(Some("bad")), OWN_UPSCALER_HEAP_GROWTH); + } +} diff --git a/crates/xcl/src/vfs_hooks.rs b/crates/xcl/src/vfs_hooks.rs index 06efde6467..20f3ba2cb2 100644 --- a/crates/xcl/src/vfs_hooks.rs +++ b/crates/xcl/src/vfs_hooks.rs @@ -553,61 +553,78 @@ unsafe extern "system" fn hk_remove_dir_w(n: *const u16) -> i32 { unsafe extern "system" fn hk_read_file(h: *mut c_void, buf: *mut c_void, n: u32, read: *mut u32, ov: *mut c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut u32, *mut c_void) -> i32; let orig = orig!(O_READ_FILE as F); - if !buf.is_null() { - crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); - } + let opened = (!buf.is_null()).then(|| crate::hle::kernelx::lazy::ensure(buf as usize, n as usize)); let r = orig(h, buf, n, read, ov); let error = windows_sys::Win32::Foundation::GetLastError(); + if !ov.is_null() && r == 0 && error == windows_sys::Win32::Foundation::ERROR_IO_PENDING { + if let Some(opened) = opened { crate::hle::kernelx::guards::open_until_done(opened, ov as usize); } + } crate::hle::d3d12x::file_reads::returned(r != 0, error, buf, n, read, ov); SetLastError(error); r } +/// The views `kernelx::lazy::ensure` opened for a call's buffer close when the call returns. With +/// an OVERLAPPED they are handed to `guards::open_until_done`, which keeps them until the +/// OVERLAPPED no longer says pending: a pending ReadFile returns FALSE + ERROR_IO_PENDING, but +/// ReadFileEx / WriteFileEx return TRUE while their I/O is still queued. +unsafe fn keep_open_while_pending(opened: Option, r: i32, ov: *mut c_void) { + let error = windows_sys::Win32::Foundation::GetLastError(); + if let Some(opened) = opened { + let failed = r == 0 && error != windows_sys::Win32::Foundation::ERROR_IO_PENDING; + if !ov.is_null() && !failed { + crate::hle::kernelx::guards::open_until_done(opened, ov as usize); + } + } + SetLastError(error); +} + // ReadFileEx, WriteFile and WriteFileEx reach NtReadFile / NtWriteFile without ReadFile, and // the scatter / gather calls NtReadFileScatter / NtWriteFileGather: their buffers too. unsafe extern "system" fn hk_read_file_ex(h: *mut c_void, buf: *mut c_void, n: u32, ov: *mut c_void, done: *const c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut c_void, *const c_void) -> i32; let orig = orig!(O_READ_FILE_EX as F); - if !buf.is_null() { - crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); - } - orig(h, buf, n, ov, done) + let opened = (!buf.is_null()).then(|| crate::hle::kernelx::lazy::ensure(buf as usize, n as usize)); + let r = orig(h, buf, n, ov, done); + keep_open_while_pending(opened, r, ov); + r } unsafe extern "system" fn hk_write_file(h: *mut c_void, buf: *const c_void, n: u32, written: *mut u32, ov: *mut c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *const c_void, u32, *mut u32, *mut c_void) -> i32; let orig = orig!(O_WRITE_FILE as F); - if !buf.is_null() { - crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); - } - orig(h, buf, n, written, ov) + let opened = (!buf.is_null()).then(|| crate::hle::kernelx::lazy::ensure(buf as usize, n as usize)); + let r = orig(h, buf, n, written, ov); + keep_open_while_pending(opened, r, ov); + r } unsafe extern "system" fn hk_write_file_ex(h: *mut c_void, buf: *const c_void, n: u32, ov: *mut c_void, done: *const c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *const c_void, u32, *mut c_void, *const c_void) -> i32; let orig = orig!(O_WRITE_FILE_EX as F); - if !buf.is_null() { - crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); - } - orig(h, buf, n, ov, done) + let opened = (!buf.is_null()).then(|| crate::hle::kernelx::lazy::ensure(buf as usize, n as usize)); + let r = orig(h, buf, n, ov, done); + keep_open_while_pending(opened, r, ov); + r } /// The buffers of a FILE_SEGMENT_ELEMENT array: one system page each, as many as `n` bytes /// fill (a null one ends the array). Reads each entry through `ReadProcessMemory` so an /// invalid or unreadable segment pointer never faults here and is left for the kernel API to /// reject with its normal error. -unsafe fn ensure_segments(segs: *const u64, n: u32) { +unsafe fn ensure_segments(segs: *const u64, n: u32) -> Vec { const SYSTEM_PAGE: usize = 0x1000; + let mut opened = Vec::new(); if segs.is_null() || n == 0 { - return; + return opened; } let me = windows_sys::Win32::System::Threading::GetCurrentProcess(); let base = segs as usize; for i in 0..(n as usize).div_ceil(SYSTEM_PAGE) { let Some(addr) = base.checked_add(i * std::mem::size_of::()) else { - return; + return opened; }; - crate::hle::kernelx::lazy::ensure(addr, std::mem::size_of::()); + opened.push(crate::hle::kernelx::lazy::ensure(addr, std::mem::size_of::())); let mut entry: u64 = 0; let mut read: usize = 0; let ok = windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory( @@ -618,28 +635,37 @@ unsafe fn ensure_segments(segs: *const u64, n: u32) { &mut read, ); if ok == 0 || read != std::mem::size_of::() { - return; + return opened; } let p = entry as usize; if p == 0 { break; } - crate::hle::kernelx::lazy::ensure(p, SYSTEM_PAGE); + opened.push(crate::hle::kernelx::lazy::ensure(p, SYSTEM_PAGE)); } + opened } unsafe extern "system" fn hk_read_file_scatter(h: *mut c_void, segs: *const u64, n: u32, rsv: *mut u32, ov: *mut c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *const u64, u32, *mut u32, *mut c_void) -> i32; let orig = orig!(O_READ_FILE_SCATTER as F); - ensure_segments(segs, n); - orig(h, segs, n, rsv, ov) + let opened = ensure_segments(segs, n); + let r = orig(h, segs, n, rsv, ov); + for o in opened { + keep_open_while_pending(Some(o), r, ov); + } + r } unsafe extern "system" fn hk_write_file_gather(h: *mut c_void, segs: *const u64, n: u32, rsv: *mut u32, ov: *mut c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *const u64, u32, *mut u32, *mut c_void) -> i32; let orig = orig!(O_WRITE_FILE_GATHER as F); - ensure_segments(segs, n); - orig(h, segs, n, rsv, ov) + let opened = ensure_segments(segs, n); + let r = orig(h, segs, n, rsv, ov); + for o in opened { + keep_open_while_pending(Some(o), r, ov); + } + r } unsafe extern "system" fn hk_delete_file_w(n: *const u16) -> i32 { diff --git a/crates/xcl/tests/console_dlls_e2e.rs b/crates/xcl/tests/console_dlls_e2e.rs index 0c6e9f5cfb..9cc5632400 100644 --- a/crates/xcl/tests/console_dlls_e2e.rs +++ b/crates/xcl/tests/console_dlls_e2e.rs @@ -1169,6 +1169,395 @@ fn fsr4_console_upscaler_creates_a_context_probe() { } } +/// f32 -> f16 bits for the probe's inputs (normal values and zero; the mantissa truncated). +fn f16_bits(x: f32) -> u16 { + let b = x.to_bits(); + let sign = ((b >> 16) & 0x8000) as u16; + let e = ((b >> 23) & 0xFF) as i32 - 127 + 15; + if x == 0.0 || e <= 0 { + return sign; + } + if e >= 31 { + return sign | 0x7C00; + } + sign | (e as u16) << 10 | ((b >> 13) & 0x3FF) as u16 +} + +/// Probe (`XCL_PROBE_FSR_TEMPORAL=1`, with `XCL_SAMPLE_DLLS` and `XCL_CONSOLE_LISTS=1`): the +/// console FSR4 upscaler's history over several frames on the GPU, as the retail title's camera +/// cuts and walking characters need it. A bright square on a dark background holds still for six +/// frames (the first with `reset`), then moves 600 pixels right with motion vectors that say +/// so: the place it left must show the background again (else a ghost stays behind). Then a +/// frame with `reset` and a flat grey picture must be grey everywhere (else the last shot shows +/// through a camera cut). It prints the mean red of each region per frame it reads back. +#[test] +fn fsr4_console_upscaler_drops_history_it_should_probe() { + let Some(dir) = setup() else { return }; + if std::env::var_os("XCL_PROBE_FSR_TEMPORAL").is_none() { + return; + } + let m = load(dir, "amd_fidelityfx_upscaler_xbox.dll"); + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::*; + use xcl::hle::d3d12x::console_list; + unsafe { + let iid: [u8; 16] = [0xf1, 0x19, 0x98, 0x18, 0xb6, 0x1d, 0x57, 0x4b, 0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7]; + let mut dev: *mut std::ffi::c_void = std::ptr::null_mut(); + assert!(xcl::hle::d3d12x::D3D12XboxCreateDevice(std::ptr::null_mut(), std::ptr::null(), iid.as_ptr() as _, &mut dev) >= 0); + let mut backend = FfxBackend { header: FfxHeader { ty: 0x0100_0002, next: std::ptr::null_mut() }, device: dev }; + let mut desc = FfxCreateUpscale { + header: FfxHeader { ty: 0x0001_0000, next: &mut backend.header }, + // the game's configuration, the only one the DLL takes: HDR | inverted depth | auto + // exposure, 1280x720 -> 1920x1080 + flags: 1 | 1 << 3 | 1 << 5, + max_render: [1280, 720], + max_upscale: [1920, 1080], + message: 0, + }; + let create: extern "C" fn(*mut usize, *mut FfxHeader, *const u8) -> u32 = std::mem::transmute(proc(&m, "ffxCreateContext")); + let dispatch: extern "C" fn(*mut usize, *const u32) -> u32 = std::mem::transmute(proc(&m, "ffxDispatch")); + let mut ctx = 0usize; + assert_eq!(create(&mut ctx, &mut desc.header, std::ptr::null()), 0, "ffxCreateContext"); + let device = ID3D12Device::from_raw_borrowed(&dev).unwrap(); + let tex = |w: u32, h: u32, f: DXGI_FORMAT, uav: bool| -> ID3D12Resource { + let mut r: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w as u64, + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: f, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: if uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, + ..Default::default() + }, + if uav { D3D12_RESOURCE_STATE_UNORDERED_ACCESS } else { D3D12_RESOURCE_STATE_COPY_DEST }, + None, + &mut r, + ) + .unwrap(); + r.unwrap() + }; + let buffer = |bytes: u64, heap: D3D12_HEAP_TYPE| -> ID3D12Resource { + let mut r: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + if heap == D3D12_HEAP_TYPE_READBACK { D3D12_RESOURCE_STATE_COPY_DEST } else { D3D12_RESOURCE_STATE_GENERIC_READ }, + None, + &mut r, + ) + .unwrap(); + r.unwrap() + }; + let footprint = |r: &ID3D12Resource| -> (D3D12_PLACED_SUBRESOURCE_FOOTPRINT, u64) { + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0u64; + device.GetCopyableFootprints(&r.GetDesc(), 0, 1, 0, Some(&mut fp), None, None, Some(&mut total)); + (fp, total) + }; + let barrier = |r: &ID3D12Resource, before, after| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(r), Subresource: 0, StateBefore: before, StateAfter: after }), + }, + ..Default::default() + }; + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut fence_value = 0u64; + let mut run = |list: &ID3D12GraphicsCommandList| { + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + fence_value += 1; + queue.Signal(&fence, fence_value).unwrap(); + let t0 = std::time::Instant::now(); + while fence.GetCompletedValue() < fence_value && t0.elapsed().as_secs() < 60 { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let removed = device.GetDeviceRemovedReason(); + assert!(removed.is_ok() && fence.GetCompletedValue() != u64::MAX, "device removed: {removed:?}"); + assert!(fence.GetCompletedValue() >= fence_value, "GPU work did not finish in 60 s"); + }; + let new_list = || -> (ID3D12CommandAllocator, ID3D12GraphicsCommandList) { + let a: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let l: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &a, None).unwrap(); + (a, l) + }; + let (w, h) = (1280u32, 720u32); + let color = tex(w, h, DXGI_FORMAT_R16G16B16A16_FLOAT, false); + let depth = tex(w, h, DXGI_FORMAT_R32_FLOAT, false); + let motion = tex(w, h, DXGI_FORMAT_R16G16_FLOAT, false); + let output = tex(1920, 1080, DXGI_FORMAT_R16G16B16A16_FLOAT, true); + let uploads: Vec<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> = [&color, &depth, &motion] + .iter() + .map(|r| { + let (fp, total) = footprint(r); + (buffer(total, D3D12_HEAP_TYPE_UPLOAD), fp) + }) + .collect(); + let (ofp, ototal) = footprint(&output); + let rb = buffer(ototal, D3D12_HEAP_TYPE_READBACK); + // the scene: background 0.05 at depth 0.1, a 200x200 square of 1.0 at depth 0.9 (inverted + // depth: nearer), its left edge at `sq` (None: no square, the whole picture `flat`); + // `mv`: the square's motion vector in UV (previous position = current + mv) + // variants for finding what the history depends on: `XCL_PROBE_FSR_TEMPORAL_SCALE=` + // multiplies every colour, `XCL_PROBE_FSR_TEMPORAL_FLAT_DEPTH=1` gives the square the + // background's depth, `XCL_PROBE_FSR_TEMPORAL_JITTER=1` jitters as a title does (Halton 2/3) + let var = |name: &str| std::env::var(format!("XCL_PROBE_FSR_TEMPORAL_{name}")).ok(); + let scale: f32 = var("SCALE").and_then(|v| v.parse().ok()).unwrap_or(1.0); + let flat_depth = var("FLAT_DEPTH").is_some_and(|v| v == "1"); + let jitter = var("JITTER").is_some_and(|v| v == "1"); + // `XCL_PROBE_FSR_TEMPORAL_IMAGE=`: a still picture (raw RGB8, 1280x720) for eight + // frames instead of the square, each output written to `..._DUMP=` as a BMP; + // `..._RESET_ALL=1`: every frame with `reset` (no history) + let image: Option> = var("IMAGE").map(|f| std::fs::read(f).unwrap()); + let reset_all = var("RESET_ALL").is_some_and(|v| v == "1"); + let dump = var("DUMP"); + let (bg, lit, sq_y) = (0.05f32 * scale, 1.0f32 * scale, 260u32..460u32); + let upload = |sq: Option, flat: f32, mv: f32| { + let (prep_alloc, prep) = new_list(); + for (k, (r, (up, fp))) in [&color, &depth, &motion].iter().zip(&uploads).enumerate() { + let mut p: *mut std::ffi::c_void = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).unwrap(); + for y in 0..fp.Footprint.Height { + let mut row: Vec = Vec::with_capacity(fp.Footprint.RowPitch as usize); + for x in 0..fp.Footprint.Width { + let on = sq.is_some_and(|s| (s..s + 200).contains(&x) && sq_y.contains(&y)); + match k { + 0 => { + let c = f16_bits(if sq.is_none() { flat * scale } else if on { lit } else { bg }); + let px = image.as_ref().map(|i| { + let at = 3 * (y * w + x) as usize; + // sRGB-ish to linear + [0, 1, 2].map(|c| f16_bits(scale * (i[at + c] as f32 / 255.0).powf(2.2))) + }); + let [r, g, b] = px.unwrap_or([c, c, c]); + for v in [r, g, b, f16_bits(1.0)] { + row.extend(v.to_le_bytes()); + } + } + 1 => row.extend((if on && !flat_depth { 0.9f32 } else { 0.1f32 }).to_le_bytes()), + _ => { + row.extend(f16_bits(if on { mv } else { 0.0 }).to_le_bytes()); + row.extend(0u16.to_le_bytes()); + } + } + } + std::ptr::copy_nonoverlapping(row.as_ptr(), (p as *mut u8).add(fp.Offset as usize + (y * fp.Footprint.RowPitch) as usize), row.len()); + } + up.Unmap(0, None); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(*r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(up), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *fp } }; + prep.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + // the state the dispatch names for its inputs (FFX COMPUTE_READ) + prep.ResourceBarrier(&[&color, &depth, &motion].map(|r| barrier(r, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE))); + prep.Close().unwrap(); + (prep_alloc, prep) + }; + let back_to_copy_dest = || { + let (a, l) = new_list(); + l.ResourceBarrier(&[&color, &depth, &motion].map(|r| barrier(r, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST))); + l.Close().unwrap(); + (a, l) + }; + let res = |r: &ID3D12Resource, fmt: u32, w: u32, h: u32, usage: u32, state: u32| -> [u32; 12] { + let p = r.as_raw() as usize; + [p as u32, (p >> 32) as u32, 2, fmt, w, h, 1, 1, 0, usage, state, 0] + }; + // mean red of output rectangles (x0, x1, y0, y1) + let read_regions = |regions: &[(u32, u32, u32, u32)]| -> Vec { + let half = |v: u16| -> f32 { + let (s, e, m) = ((v >> 15) as u32, ((v >> 10) & 0x1F) as i32, (v & 0x3FF) as f32); + let x = if e == 0 { m / 1024.0 * 2f32.powi(-14) } else if e == 31 { if m == 0.0 { f32::INFINITY } else { f32::NAN } } else { (1.0 + m / 1024.0) * 2f32.powi(e - 15) }; + if s == 1 { -x } else { x } + }; + let mut p: *mut std::ffi::c_void = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let out = regions + .iter() + .map(|&(x0, x1, y0, y1)| { + let (mut sum, mut n) = (0f64, 0u32); + for y in (y0..y1).step_by(2) { + let row = (p as *const u8).add(ofp.Offset as usize + (y * ofp.Footprint.RowPitch) as usize) as *const u16; + for x in (x0..x1).step_by(2) { + let r = half(*row.add(4 * x as usize)); + assert!(r.is_finite(), "FSR4 output at ({x}, {y}) is {r}"); + sum += r as f64; + n += 1; + } + } + sum / n as f64 + }) + .collect(); + rb.Unmap(0, None); + out + }; + // output rectangles (1.5x the input): where the square was, where it went, background + let (old, new, back) = ((310u32, 590u32, 400u32, 680u32), (1210u32, 1490u32, 400u32, 680u32), (1650u32, 1850u32, 100u32, 300u32)); + // (square's left edge, flat colour, motion vector, reset, read back) + let frames: Vec<(Option, f32, f32, bool, bool)> = (0..6) + .map(|i| (Some(200), 0.0, 0.0, i == 0, i == 5)) + .chain([(Some(800), 0.0, -600.0 / 1280.0, false, true)]) + .chain((0..3).map(|_| (Some(800), 0.0, 0.0, false, true))) + .chain([(None, 0.5, 0.0, true, true)]) + .collect(); + // `XCL_PROBE_FSR_TEMPORAL_GONE=1`: from frame 6 the square is gone (no motion anywhere): the + // history there is only told apart by its colour + let frames: Vec<(Option, f32, f32, bool, bool)> = if var("GONE").is_some_and(|v| v == "1") { + frames.into_iter().enumerate().map(|(i, fr)| if (6..10).contains(&i) { (Some(4000), 0.0, 0.0, false, true) } else { fr }).collect() + } else { + frames + }; + let frames = if image.is_some() { (0..8).map(|i| (None, 0.0, 0.0, i == 0, true)).collect() } else { frames }; + let mut seen = Vec::new(); + // the upscaler's small buffers (its exposure among them): the V#s of at most 64 bytes in + // the descriptor tables its first frame names (`XCL_PROBE_FSR_TEMPORAL_SMALL=1` prints them) + let small_on = var("SMALL").is_some_and(|v| v == "1"); + let mut small: std::collections::BTreeSet<(usize, usize)> = std::collections::BTreeSet::new(); + for (f, &(sq, flat, mv, reset, read)) in frames.iter().enumerate() { + if f > 0 { + let (_a, l) = back_to_copy_dest(); + run(&l); + } + let (_pa, prep) = upload(sq, flat, mv); + run(&prep); + let (alloc, pc) = new_list(); + let console = console_list::create_with_allocator(pc.into_raw(), alloc.as_raw()); + let mut d = vec![0u32; 432 / 4]; + let put = |d: &mut Vec, at: usize, w: &[u32]| d[at / 4..at / 4 + w.len()].copy_from_slice(w); + put(&mut d, 0, &[0x0001_0001, 0, 0, 0]); + put(&mut d, 16, &[console as usize as u32, (console as usize >> 32) as u32]); + put(&mut d, 24, &res(&color, 4, w, h, 0, 4)); + put(&mut d, 72, &res(&depth, 28, w, h, 0, 4)); + put(&mut d, 120, &res(&motion, 18, w, h, 0, 4)); + put(&mut d, 312, &res(&output, 4, 1920, 1080, 2, 2)); + if jitter { + // Halton (2, 3) in pixels, -0.5..0.5, as the title's projection would be offset + let halton = |mut i: u32, b: u32| { + let (mut f, mut r) = (1f32, 0f32); + while i > 0 { + f /= b as f32; + r += f * (i % b) as f32; + i /= b; + } + r + }; + let i = f as u32 % 8 + 1; + put(&mut d, 360, &[(halton(i, 2) - 0.5).to_bits(), (halton(i, 3) - 0.5).to_bits()]); + } + put(&mut d, 368, &[(w as f32).to_bits(), (h as f32).to_bits()]); // motion vector scale + put(&mut d, 376, &[w, h, 1920, 1080]); + put(&mut d, 400, &[33.3f32.to_bits(), 1f32.to_bits()]); // frameTimeDelta, preExposure + put(&mut d, 408, &[(reset || reset_all) as u32]); + put(&mut d, 412, &[0.1f32.to_bits(), 1000f32.to_bits(), 1.0f32.to_bits(), 1f32.to_bits()]); + assert_eq!(dispatch(&mut ctx, d.as_ptr()), 0, "ffxDispatch of frame {f}"); + if small_on && f == 0 { + use xcl::hle::d3d12x::console_heap; + for &wd in &console_list::recorded_words(console) { + for k in 0..24 { + if let Some(v) = console_heap::words_at(wd.wrapping_add(32 * k)) { + if v[3] & 0xFFF == 0xFAC && v[3] >> 30 == 0 && v[2] != 0 && v[2] <= 64 { + small.insert((v[0] as usize | ((v[1] & 0xFFFF) as usize) << 32, v[2] as usize)); + } + } + } + } + } + let t = console_list::close(console).unwrap(); + // (`XCL_SKIP_CS`: the passes it names are left out on purpose) + let left_out_ok = std::env::var_os("XCL_SKIP_CS").is_some(); + assert!(t.unknown.is_none() && t.skipped == 0 && (t.skipped_dispatches == 0 || left_out_ok), "frame {f}: {t:?}"); + let pc_raw = console_list::pc_list(console).expect("the console list's PC list"); + run(ID3D12GraphicsCommandList::from_raw_borrowed(&pc_raw).unwrap()); + if read { + let (_ra, l) = new_list(); + l.ResourceBarrier(&[barrier(&output, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: ofp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&output), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + l.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + l.ResourceBarrier(&[barrier(&output, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + l.Close().unwrap(); + run(&l); + if let Some(dir) = &dump { + // the output as a BMP (sqrt for display) and how much it differs from its 4 + // neighbours on average (a dot or checker pattern raises it) + let mut p: *mut std::ffi::c_void = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let texel = |x: u32, y: u32, c: usize| -> f32 { + let v = *((p as *const u8).add(ofp.Offset as usize + (y * ofp.Footprint.RowPitch) as usize) as *const u16).add(4 * x as usize + c); + let (e, m) = (((v >> 10) & 0x1F) as i32, (v & 0x3FF) as f32); + if e == 0 { m / 1024.0 * 2f32.powi(-14) } else { (1.0 + m / 1024.0) * 2f32.powi(e - 15) } + }; + let (ow, oh) = (1920u32, 1080u32); + let mut bmp = Vec::with_capacity(54 + (ow * oh * 3) as usize); + bmp.extend(b"BM"); + for v in [54 + ow * oh * 3, 0, 54, 40, ow, oh] { + bmp.extend(v.to_le_bytes()); + } + bmp.extend(1u16.to_le_bytes()); + bmp.extend(24u16.to_le_bytes()); + for v in [0u32, ow * oh * 3, 2835, 2835, 0, 0] { + bmp.extend(v.to_le_bytes()); + } + let mut busy = 0f64; + for y in (0..oh).rev() { + for x in 0..ow { + for c in [2, 1, 0] { + bmp.push(((texel(x, y, c) / scale).clamp(0.0, 1.0).sqrt() * 255.0) as u8); + } + if (1..ow - 1).contains(&x) && (1..oh - 1).contains(&y) { + let n = (texel(x - 1, y, 1) + texel(x + 1, y, 1) + texel(x, y - 1, 1) + texel(x, y + 1, 1)) / 4.0; + busy += ((texel(x, y, 1) - n) / scale).abs() as f64; + } + } + } + rb.Unmap(0, None); + let file = std::path::Path::new(dir).join(format!("fsr4_frame{f}.bmp")); + std::fs::write(&file, bmp).unwrap(); + println!("FSR4 frame {f} written to {} (reset {}): mean |texel - its 4 neighbours| {:.5}", file.display(), reset || reset_all, busy / ((ow - 2) * (oh - 2)) as f64); + } + for &(at, n) in &small { + xcl::hle::d3d12x::sparse::readback_now(at, n); + let words: Vec = (0..n / 4).map(|k| { + let v = (at as *const u32).add(k).read_volatile(); + format!("{v:#x} ({})", f32::from_bits(v)) + }).collect(); + println!("FSR4 frame {f}: buffer {at:#x} ({n} bytes): {}", words.join(", ")); + } + let r = read_regions(&[old, new, back]); + println!("FSR4 frame {f} (square at {sq:?}, flat {flat}, mv {mv:.4}, reset {reset}): red where the square was {:.3}, where it went {:.3}, background {:.3}", r[0], r[1], r[2]); + seen.push((f, r)); + } + } + if image.is_some() { + return; + } + let at = |f: usize| seen.iter().find(|s| s.0 == f).unwrap().1.iter().map(|v| v / scale as f64).collect::>(); + assert!(at(5)[0] > 0.5 && at(5)[2] < 0.2, "a still square is upscaled where it is: {:?}", at(5)); + assert!(at(6)[0] < 0.25, "the place the square left shows the background in the frame it moved, not a ghost: {:?}", at(6)); + assert!(at(9)[0] < 0.25, "and three frames later: {:?}", at(9)); + assert!(at(10).iter().all(|v| (0.35..0.65).contains(v)), "a reset frame of flat grey is grey everywhere: {:?}", at(10)); + } +} + /// No GPU: every compute shader inside XboxBvhBuilder.dll (found by its DXBC header) against /// what XCL does with its root arguments. The shader's stage descriptor says how many user /// SGPRs it has; its RTS0 part gives the argument layout. Arguments must not be put into diff --git a/crates/xcl/tests/lazy_file_io.rs b/crates/xcl/tests/lazy_file_io.rs index a072d2eca6..b481accd93 100644 --- a/crates/xcl/tests/lazy_file_io.rs +++ b/crates/xcl/tests/lazy_file_io.rs @@ -46,7 +46,7 @@ impl Lazy { impl Drop for Lazy { fn drop(&mut self) { - lazy::ensure(self.0, self.1 * PAGE); + drop(lazy::ensure(self.0, self.1 * PAGE)); unsafe { VirtualFree(self.0 as *mut c_void, 0, MEM_RELEASE) }; } } diff --git a/docs/specs/2026-11-24-direct-dxil.md b/docs/specs/2026-11-24-direct-dxil.md index 8abb513891..db0a43cce1 100644 --- a/docs/specs/2026-11-24-direct-dxil.md +++ b/docs/specs/2026-11-24-direct-dxil.md @@ -23,10 +23,6 @@ XCL is GPL-2.0-only. References used: local bitstream reader, as the layout oracle. - Mesa `src/microsoft/compiler` (MIT) may be ported with a provenance note. -**Not used:** the VIctory project (GPL-3.0-or-later, incompatible). Its -public architecture description informed the approach below; no code was -read for porting or copied. - ## Layers (done) | Module | Role | diff --git a/scripts/gen_bcpack_victory_tables.py b/scripts/gen_bcpack_victory_tables.py index 46d62cd72f..ebc9220b12 100644 --- a/scripts/gen_bcpack_victory_tables.py +++ b/scripts/gen_bcpack_victory_tables.py @@ -6,7 +6,7 @@ Layout is that of the format's constant tables: 128 x 9 u16 model frequencies, the rank tables, 512 u16 BC7 control words, then 255 dictionary entries per format. BC7 entry 0 stores all 32 signed indices directly after its two index widths; entries -1..254 repeat the two width bytes first and store 16 + 15 signed indices (VIctory PR #658). +1..254 repeat the two width bytes first and store 16 + 15 signed indices. python -I scripts/gen_bcpack_victory_tables.py """ diff --git a/tests/testtitle/src/main.rs b/tests/testtitle/src/main.rs index d5ae267a44..92aaa31e17 100644 --- a/tests/testtitle/src/main.rs +++ b/tests/testtitle/src/main.rs @@ -348,12 +348,12 @@ fn main() { ensure!(c == a, "freed blocks merge and are reused: {c:?}"); ensure!(std::slice::from_raw_parts(c as *const u8, 0x30000).iter().all(|&x| x == 0), "reused block not zeroed"); XMemFree(c, attrs); - // 4 MiB page-size semantics (XALLOC_PAGESIZE_4MB = 2 << 14): 4 MiB-aligned & zeroed - let attrs_4m = (1u64 << 29) | (2u64 << 14); - let big = XMemAlloc(0x1000, attrs_4m); - ensure!(!big.is_null() && (big as usize) % (4 << 20) == 0, "4MB page alloc not 4 MiB aligned: {big:?}"); - ensure!(*(big as *const u64) == 0 && *((big as usize + (4 << 20) - 8) as *const u64) == 0, "4MB page alloc not zeroed"); - XMemFree(big, attrs_4m); + // Page-size code 2 requests 2 MiB-aligned, zeroed memory. + let attrs_2m = (1u64 << 29) | (2u64 << 14); + let big = XMemAlloc(0x1000, attrs_2m); + ensure!(!big.is_null() && (big as usize) % (2 << 20) == 0, "2MB page alloc not 2 MiB aligned: {big:?}"); + ensure!(*(big as *const u64) == 0 && *((big as usize + (2 << 20) - 8) as *const u64) == 0, "2MB page alloc not zeroed"); + XMemFree(big, attrs_2m); Ok(()) });