diff --git a/README.md b/README.md
index 1388bd2..ee9f3b2 100644
--- a/README.md
+++ b/README.md
@@ -1,11 +1,30 @@
# XCL Mac Native — Apple Silicon & macOS Compatibility Layer for Xbox Series X|S
[](https://discord.gg/dYuNEsQMQ)
+[-blue?logo=github)](https://github.com/utkarshxdev/xcl-mac/releases/tag/v0.1.0-stage6.4-menu)
[](https://github.com/utkarshxdev/xcl-mac/actions/workflows/mac-cross.yml?query=branch%3Amain)
-[-success?logo=apple&color=34D399)](https://github.com/utkarshxdev/xcl-mac)
+[-success?logo=apple&color=34D399)](https://github.com/utkarshxdev/xcl-mac)
[](LICENSE)
[](https://github.com/utkarshxdev/xcl-mac)
+
+
+
+
+ Grand Theft Auto VI running natively on Apple Silicon via XCL Mac Native under CrossOver & Apple D3DMetal (30.0 FPS locked presentation & intro sequence).
+
+
+
+
+
+
+
+
+ 🎬 Watch Full 70-Second High-Resolution Gameplay Capture (MP4)
+
+
+---
+
**XCL Mac Native** (`utkarshxdev/xcl-mac`) is the dedicated, production-ready macOS and Apple Silicon distribution of [XCL](https://github.com/ivall/xcl) — the Xbox Series X|S (GDK) compatibility layer.
By executing console x86_64 code seamlessly via Apple's Rosetta 2 and mapping RDNA2 console GPU pipelines through DirectX 12 into Apple **D3DMetal (Game Porting Toolkit 2+)**, XCL enables GDK retail titles to run on macOS under Wine and CrossOver **without CPU emulation**.
@@ -97,7 +116,12 @@ All Mac-specific subsystems are strictly gated behind `crate::util::mac_host()`
5. **D3D12 Agility SDK:** Place `D3D12Core.dll` into a `D3D12\` folder next to `xcl.exe` or configure `XCL_D3D12_DIR`.
### Pre-Built Binaries
-Download the latest `xcl-mac-wine-x86_64` build directly from the **[GitHub Actions Releases](https://github.com/utkarshxdev/xcl-mac/actions/workflows/mac-cross.yml)**.
+- **Latest Verified Release (Stage 6.4 — Menu & Intro, Pre-Series S):**
+ 👉 **[Download `xcl-mac-stage6.4-menu.zip`](https://github.com/utkarshxdev/xcl-mac/releases/download/v0.1.0-stage6.4-menu/xcl-mac-stage6.4-menu.zip)** *(includes `xcl.exe`, `dxcompiler.dll`, `dxil.dll` — SHA-256: `d0cf51561411a8ebb83c66b043174ebc56226dc6df5ddae33463720a24263f23`)*
+- **Experimental Series S / Multi-Plane Pre-release (Run 15):**
+ 👉 **[Download `xcl-run15-window-checked.zip`](https://github.com/utkarshxdev/xcl-mac/releases/download/v0.1.0-stage6.4-run15-planes/xcl-run15-window-checked.zip)** *(includes `xcl.exe`, `dxcompiler.dll`, `dxil.dll` — SHA-256: `4ed9133051d74df5e30bc1be9c81d80773e5122711eaf743c72430dc32fc6d97`)*
+- View all releases and changelogs on the **[GitHub Releases Page](https://github.com/utkarshxdev/xcl-mac/releases)**.
+- Automated CI builds are available on the **[GitHub Actions Workflows](https://github.com/utkarshxdev/xcl-mac/actions/workflows/mac-cross.yml)**.
### Launch Command
Launch your title through your Wine environment with the recommended Mac environment flags:
@@ -119,8 +143,10 @@ env XCL_TEXTURE_SKIP_UNCHANGED=0 XCL_NETWORK=0 wine64 xcl.exe run "C:\Games\Your
| `XCL_COHERENT_HEAPS` | `0` (Off) | `1` (On) | Avoids write-watch page protection traps on coherent heaps |
| `XCL_WATCHDOG_BYPASS` | Off | — | Enables recovery for recognized watchdog sites. Unknown traps still follow normal exception handling. |
| `XCL_DSTORAGE_BCPACK_ACCEPT` | Off | — | Set to `1` to complete eligible BCPack requests with solid placeholder blocks. Texture decompression is required for the original pixels. |
+| `XCL_DSTORAGE_AUTO_SUBMIT_DISABLED` | On | On | A DirectStorage queue made with AutoSubmitDisabled waits for the title's Submit. Set to `0` to ignore that option: such a queue then submits by itself at half full, like any other. |
| `XCL_TRACE_GPU_STALL` | Off | `1` | Logs command lists, recent dispatches and pipeline IDs when a bottom-of-pipe fence stalls |
-| `XCL_PRESENT_PLANE` | `0` | `0` | Set to `1` to try the second PresentX plane. The log shows the requested and active planes and whether the resources can be presented. |
+| `XCL_MS_IN_AS_SLOT` | On | On | A console mesh shader in a pipeline's AS slot, with no MS subobject, is translated as the mesh shader. Set to `0` to refuse such pipelines instead. |
+| `XCL_PRESENT_PLANE` | Unset | Unset | Unset: two PresentX planes or more are composed, as the console's display does. Set to `n` to show plane `n` alone (plane `0` when the title presents fewer planes or plane `n` has no presentable resource); `0` shows plane 0 alone and turns composition off. The log shows the requested and active planes and whether the resources can be presented. |
| `XCL_FRAME_DUMP` | `0` | `0` | Dumps every Nth presented frame to disk with luminance telemetry |
| `XCL_FRAME_DUMP_FROM` | `0` | `0` | Delays frame sampling until frame index N is reached |
@@ -157,7 +183,7 @@ cargo build --release --locked --target x86_64-pc-windows-gnullvm -p xcl
## 🧪 Subsystem Verification
-We provide an automated verification suite that audits all 22 Mac-native architectural subsystems:
+We provide an automated verification suite that audits all 39 Mac-native architectural subsystems:
```bash
./scripts/verify_mac_build.sh
@@ -173,24 +199,41 @@ Checking: Stand-in PS dual-source blending (SV_Target0 + SV_Target1) [PASS]
Checking: D3DMetal shader refusal host fallback (refused_on_mac_host) [PASS]
Checking: Compute blob cache charging fix (insert_compute_blob) [PASS]
Checking: Rosetta missing AMD instruction handlers (CLZERO, INSERTQ) [PASS]
-Checking: Rosetta AVX masked store decoder module (maskmov.rs) [PASS]
-Checking: Rosetta masked store fault helper patching [PASS]
+Checking: Rosetta AVX masked store decoder module (crates/xcl/src/maskmov.rs) [PASS]
+Checking: Rosetta masked store fault helper patching (replace_masked_stores) [PASS]
Checking: Rosetta CPU detection (util::rosetta) [PASS]
-Checking: UMA Shadowed fallback implementation [PASS]
+Checking: UMA Shadowed fallback implementation (OpenExistingHeapFromAddress) [PASS]
Checking: UMA note_copy_into for readback buffers [PASS]
-Checking: GPU-visible fallback write-watch disable [PASS]
+Checking: GPU-visible fallback write-watch disable (XCL_WATCHED_FALLBACK) [PASS]
Checking: Command queue #31 GPU view page mappings (gpu_views) [PASS]
Checking: Unwatched title textures content comparison (poll_unwatched) [PASS]
-Checking: Unchanged title texture upload skip override [PASS]
+Checking: Unchanged title texture upload skip override (XCL_TEXTURE_SKIP_UNCHANGED) [PASS]
Checking: CopyMemoryToMemoryX CPU fallback for non-UMA ranges [PASS]
-Checking: D3DMetal depth-only format mapping [PASS]
+Checking: D3DMetal depth-only format mapping (pc_depth_view_format) [PASS]
Checking: Mac host utility detection (util::mac_host) [PASS]
Checking: Wine isolated thread heap for DXC (own_heaps) [PASS]
Checking: Network isolation default off (netoff) [PASS]
Checking: 16 MiB title stacks under Wine [PASS]
+Checking: Sparse buffer lock safety (try_lock in forget_buffer) [PASS]
+Checking: World-load watchdog & fatal crash bypass at 0x23cf683 [PASS]
+Checking: DirectStorage BCPack acceptance (XCL_DSTORAGE_BCPACK_ACCEPT) [PASS]
+Checking: Mesh root-argument layout (user_data_ms, inline_ms) [PASS]
+Checking: Mesh companion DISPATCH signature creation [PASS]
+Checking: Real D3D12 DispatchMesh hooking (slot 127 / newer 129) [PASS]
+Checking: GPU-side root-changing ExecuteIndirect repack [PASS]
+Checking: Two-pass DispatchMesh & ExecuteIndirect execution harness [PASS]
Checking: Mac cross-build CI workflow (.github/workflows/mac-cross.yml) [PASS]
+Checking: CreateShaderCacheSession translation layer fallback [PASS]
+Checking: Pointer alignment guard in is_adopted (align_of::) [PASS]
+Checking: Heap mirroring and bounded root SRVs [PASS]
+Checking: Lock-free atomic pipeline building accounting (pso_async::counts) [PASS]
+Checking: XUserCompare 64-bit pointer overflow prevention [PASS]
+Checking: XAsyncGetResult zero-used out parameter preservation [PASS]
+Checking: GetModuleFileName ERROR_INSUFFICIENT_BUFFER on size 0 [PASS]
+Checking: Vertex buffer slot unbind & purge on null/zero views [PASS]
+Checking: QueryInterface wrapper interface vtable release dispatch [PASS]
======================================================================
-Verification Summary: 22 Passed, 0 Failed
+Verification Summary: 39 Passed, 0 Failed
======================================================================
Status: Verification SUCCESSFUL! All Mac host subsystems present.
```
diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs
index 7a29e57..053e5df 100644
--- a/crates/xcl/src/eh.rs
+++ b/crates/xcl/src/eh.rs
@@ -7,7 +7,7 @@
//! * An unhandled-exception filter logs crashes with module+RVA and writes the report.
use std::ffi::c_void;
-use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
use std::sync::Mutex;
use windows_sys::Win32::System::Diagnostics::Debug::{
@@ -87,11 +87,10 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i
let c = &*ctx;
// registers that point at objects: the module of their vtable (which object it is)
let obj = |v: u64| -> String {
- let p = v as usize;
- if p < 0x10000 || !crate::gpu::shader::readable(p, 8) {
+ // (copied: memory unmapped meanwhile must not fault in the filter, `qwords_at`)
+ let Some(vt) = qwords_at(v as usize, 1).map(|q| q[0] as usize) else {
return String::new();
- }
- let vt = (p as *const usize).read_unaligned();
+ };
let d = modules::describe_address(vt);
if d.contains('+') { format!(" (vtable {d})") } else { String::new() }
};
@@ -112,6 +111,10 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i
crate::xlog_error!("{msg}");
crate::report::write_final(Some(msg));
crate::log::flush();
+ if !ctx.is_null() {
+ crash_memory(&*ctx, &mut |line| crate::xlog_error!("{line}"));
+ crate::log::flush();
+ }
}
match TITLE_FILTER.load(Ordering::Acquire) {
0 => 0, // EXCEPTION_CONTINUE_SEARCH
@@ -119,6 +122,128 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i
}
}
+/// `n` qwords at `at`, if all of them could be read. A copy by ReadProcessMemory: memory another
+/// thread unmaps or decommits meanwhile fails the copy, not the exception filter that asks (a
+/// fault there is a nested exception, and the title's own filter never runs); `readable` only
+/// spares the call where nothing is.
+unsafe fn qwords_at(at: usize, n: usize) -> Option> {
+ use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
+ use windows_sys::Win32::System::Threading::GetCurrentProcess;
+ if at < 0x10000 || n == 0 || !crate::gpu::shader::readable(at, n * 8) {
+ return None;
+ }
+ let mut q = vec![0u64; n];
+ let mut done = 0usize;
+ (ReadProcessMemory(GetCurrentProcess(), at as *const std::ffi::c_void, q.as_mut_ptr().cast(), n * 8, &mut done) != 0 && done == n * 8).then_some(q)
+}
+
+/// What is left of a crash report's wait for XCL's locks, in ms: 100 in all, once – a thread
+/// stopped while it held one would hold it for good, and the faulting thread may hold one itself.
+/// Once it is spent, each lock is looked at once.
+static CRASH_WAIT_MS: AtomicU32 = AtomicU32::new(100);
+
+/// The wait a crash's report has left (`try_lock_within`), shared by every lock it tries.
+pub(crate) fn crash_wait() -> &'static AtomicU32 {
+ &CRASH_WAIT_MS
+}
+
+/// `m` tried every ms while `left_ms` lasts – each wait takes the time it took from it (a
+/// Sleep(1) may take more here); a poisoned lock is taken as it is. None: still busy.
+pub(crate) fn try_lock_within<'a, T>(m: &'a Mutex, left_ms: &AtomicU32) -> Option> {
+ loop {
+ match m.try_lock() {
+ Ok(g) => return Some(g),
+ Err(std::sync::TryLockError::Poisoned(e)) => return Some(e.into_inner()),
+ Err(std::sync::TryLockError::WouldBlock) => {
+ if left_ms.load(Ordering::Relaxed) == 0 {
+ return None;
+ }
+ let t = std::time::Instant::now();
+ std::thread::sleep(std::time::Duration::from_millis(1));
+ let spent = (t.elapsed().as_millis() as u32).max(1);
+ let _ = left_ms.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| Some(n.saturating_sub(spent)));
+ }
+ }
+ }
+}
+
+/// (tests) Thread `tid`'s description (Rust's thread names reach it), empty if none
+#[cfg(test)]
+pub(crate) fn thread_name_of(tid: u32) -> String {
+ use windows_sys::Win32::System::Threading::{OpenThread, THREAD_QUERY_LIMITED_INFORMATION};
+ unsafe {
+ let h = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, 0, tid);
+ if h.is_null() {
+ return String::new();
+ }
+ let s = thread_name(h);
+ windows_sys::Win32::Foundation::CloseHandle(h);
+ s
+ }
+}
+
+/// One line of a crash's memory: `what` (`p`), the qwords around it – 8 before and 8 from the
+/// one holding `p` on (that one in brackets); near the start or the end of what is readable, as
+/// many from that one on as are –, where they are, and the DirectStorage request that last wrote
+/// their 64 KiB page. With the qwords from the one holding `p` on.
+unsafe fn crash_memory_line(what: &str, p: usize) -> Option<(String, Vec)> {
+ let at = p & !0x7;
+ let (base, q) = match qwords_at(at.saturating_sub(0x40), 16) {
+ Some(q) => (at - 0x40, q),
+ None => (at, (1..=8).rev().find_map(|n| qwords_at(at, n))?),
+ };
+ let words: Vec = q
+ .iter()
+ .enumerate()
+ .map(|(k, v)| if base + 8 * k == at { format!("[{v:#018x}]") } else { format!("{v:#018x}") })
+ .collect();
+ let line = format!(
+ "crash memory: {what} {p:#x} ({}; last DirectStorage write to its 64 KiB page: {}): from {base:#x}: {}",
+ modules::describe_address(p),
+ crate::hle::dstorage::last_write_at_for_crash(p),
+ words.join(" ")
+ );
+ Some((line, q[(at - base) / 8..].to_vec()))
+}
+
+/// The label of a step further: the qword `k` from the one `p` points into, as `[reg±offset]`
+/// from `p` (`p` need not be 8-aligned: a tagged pointer).
+fn step_label(reg: &str, p: usize, k: usize) -> String {
+ let off = (8 * k) as isize - (p & 0x7) as isize;
+ if off < 0 { format!("[{reg}-{:#x}] ->", off.unsigned_abs()) } else { format!("[{reg}+{off:#x}] ->") }
+}
+
+/// The memory an unhandled exception's registers point at, and one step further – what the
+/// first qwords there point at: whether a table the title read held pointers or something
+/// streamed over it (run 63: a garbage tagged pointer read from [[rsi+0x10] + 8 * index]). Each
+/// window once; one line at a time to `out`.
+unsafe fn crash_memory(c: &windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, out: &mut dyn FnMut(String)) {
+ let regs = [
+ ("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), ("rsp", c.Rsp),
+ ];
+ let mut seen = std::collections::HashSet::new();
+ for (n, v) in regs {
+ let p = v as usize;
+ if p < 0x10000 || !seen.insert(p & !0x7) {
+ continue;
+ }
+ let Some((line, after)) = crash_memory_line(n, p) else { continue };
+ out(line);
+ // one step further: the first 8 qwords from the register's that point at readable memory
+ for (k, &q) in after.iter().take(8).enumerate() {
+ let q = q as usize;
+ if q >= 0x10000 && seen.insert(q & !0x7) {
+ if let Some((line, _)) = crash_memory_line(&step_label(n, p, k), q) {
+ out(line);
+ }
+ }
+ }
+ }
+}
+
static ORIG_NT_TERMINATE: AtomicUsize = AtomicUsize::new(0);
static ENDING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
@@ -206,6 +331,73 @@ pub fn install_crash_handler() {
let _ = std::thread::Builder::new().name("xcl-probe".into()).spawn(move || arm_probes(&offsets));
}
}
+ // local diagnostic `XCL_WATCHDOG_PROBE=` (GTA VI 1.0.2.1 only): every 2 s, the
+ // state of the title's stall watchdog (`title_watchdog_resume`) – its active-scope
+ // counter (active: while it is not 0 the countdown starts again every second), flags (the
+ // pause, reset and stop flags), the age of the heartbeat it counts down on (last_age:
+ // with no scope open it fires 30 checks after the last write, about 30 s; a resume does
+ // not write the heartbeat, so the next fires come about 30 s apart, at ages of about 61,
+ // 91 s …), the report hook armed (cb: none, or the bare `ret` at title+0x4380 when
+ // func_81b200 armed it), the QPC scale it uses, and the age of every open scope in its
+ // 64-group table (in its first loop a scope of 300 s or more fires when the title's
+ // tunable 0x89aee1d6 is on), measured with the same QueryPerformanceCounter – appended
+ // to (not the log).
+ if let Ok(path) = std::env::var("XCL_WATCHDOG_PROBE") {
+ let _ = std::thread::Builder::new().name("xcl-watchdog-probe".into()).spawn(move || {
+ use std::io::Write;
+ #[link(name = "kernel32")]
+ extern "system" {
+ fn QueryPerformanceCounter(c: *mut i64) -> i32;
+ }
+ let Ok(mut out) = std::fs::OpenOptions::new().create(true).append(true).open(&path) else { return };
+ let m = loop {
+ match modules::main_module() {
+ Some(m) => break m,
+ None => std::thread::sleep(std::time::Duration::from_millis(200)),
+ }
+ };
+ let at = |va: usize| m.base + (va - 0x1_4000_0000);
+ let _ = writeln!(out, "=== watchdog probe: title at {:#x} ===", m.base);
+ loop {
+ std::thread::sleep(std::time::Duration::from_secs(2));
+ let mut now = 0i64;
+ QueryPerformanceCounter(&mut now);
+ let scale = (at(0x1_49e4_f5c0) as *const f32).read_volatile();
+ let active = (at(0x1_471b_6334) as *const i32).read_volatile();
+ let (f30, f31, f40) = (
+ (at(0x1_471b_6330) as *const u8).read_volatile(),
+ (at(0x1_471b_6331) as *const u8).read_volatile(),
+ (at(0x1_471b_6340) as *const u8).read_volatile(),
+ );
+ let last = (at(0x1_471b_6338) as *const i64).read_volatile();
+ let cb = (at(0x1_471b_6348) as *const usize).read_volatile();
+ let mut ages = Vec::new();
+ for g in 0..64usize {
+ let count = (at(0x1_4684_4a20 + 72 * g + 4) as *const u32).read_volatile();
+ if count == 0 {
+ continue;
+ }
+ let mut e = Vec::new();
+ for i in 0..(count as usize).min(8) {
+ let ts = (at(0x1_4684_4a28 + 72 * g + 8 * i) as *const i64).read_volatile();
+ e.push(if ts == 0 { "0".to_string() } else { format!("{:.1}s", (now - ts) as f32 * scale) });
+ }
+ ages.push(format!("g{g} n={count}{} [{}]", if count > 8 { " OVERFLOW" } else { "" }, e.join(" ")));
+ }
+ let _ = writeln!(out, "t={:.1} {}", crate::log::uptime(), crate::hle::d3d12x::cpu_writes_probe());
+ let _ = writeln!(out, "t={:.1} {}", crate::log::uptime(), crate::hle::dstorage::probe_line());
+ let _ = writeln!(
+ out,
+ "t={:.1} qpc={now} scale={scale:e} active={active} flags={f30}/{f31}/{f40} last_age={:.1}s cb={} | {}",
+ crate::log::uptime(),
+ if last == 0 { -1.0 } else { (now - last) as f32 * scale },
+ if cb == 0 { "none".to_string() } else { modules::image_base_for_addr(cb).map_or(format!("{cb:#x}"), |b| format!("title+{:#x}", cb - b)) },
+ ages.join("; ")
+ );
+ let _ = out.flush();
+ }
+ });
+ }
// `XCL_DUMP_THREADS_ON=`: the same each time that file is written (its time
// changes) – for a stall whose time is not known beforehand; what is in the file is
// logged with the dump
@@ -213,11 +405,16 @@ pub fn install_crash_handler() {
let _ = std::thread::Builder::new().name("xcl-thread-dump".into()).spawn(move || {
let modified = |p: &str| std::fs::metadata(p).and_then(|m| m.modified()).ok();
let mut seen = modified(&path);
+ // local diagnostic: opened now, while nothing is stuck
+ let mut raw = std::fs::OpenOptions::new().create(true).append(true).open(format!("{path}.raw.txt")).ok();
loop {
std::thread::sleep(std::time::Duration::from_millis(500));
let now = modified(&path);
if now.is_some() && now != seen {
seen = now;
+ if let Some(f) = raw.as_mut() {
+ dump_threads_raw(f);
+ }
crate::xlog_info!("thread stacks {:.1} s into the run (XCL_DUMP_THREADS_ON: {}):", crate::log::uptime(), std::fs::read_to_string(&path).unwrap_or_default().trim());
dump_threads();
crate::log::flush();
@@ -338,8 +535,20 @@ const HELPERS_SIZE: usize = 0x1_0000;
/// Serialises site patching; `XCL_ISA_REDIRECT=0` turns it off (every use then traps).
static PATCHING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static REDIRECT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
+/// A thread was once stepped into a CLZERO loop's body (`emulate_console_only`'s fallback): a
+/// loop redirected after that could have that thread return into the call's bytes, so none is.
+static CLZERO_LOOP_STEPPED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static WATCHDOG: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+/// `XCL_PATCH_MWAITX=1`: a MONITORX site becomes a 3-byte NOP and an MWAITX site PAUSE; NOP after
+/// their first use (`patch_in_place`), instead of trapping at every use. Off by default: a trap
+/// under Rosetta costs tens of microseconds, which a title's MONITORX / MWAITX wait loop then
+/// spends waiting (GTA VI's, about 20 a second); patched, the loop spins a whole core.
+fn patch_mwaitx() -> bool {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var("XCL_PATCH_MWAITX").is_ok_and(|v| v.trim() == "1"))
+}
+
/// Free address space for helpers within reach of a `call rel32` from `near`: the nearest
/// `size` bytes (a multiple of 64 KiB) above it, else below; committed, readable, writable and
/// executable. 0: none.
@@ -418,6 +627,9 @@ unsafe fn redirect(site: usize, code: &[u8], t: &isa::Thunk, helper: &[u8; isa::
if std::slice::from_raw_parts(site as *const u8, n) != code {
return true;
}
+ if t.op == isa::Op::ClzeroLoop && CLZERO_LOOP_STEPPED.load(Ordering::Acquire) {
+ return false;
+ }
let mut pool = HELPERS.load(Ordering::Relaxed);
if pool == 0 {
pool = alloc_near(site, HELPERS_SIZE).max(1);
@@ -463,6 +675,61 @@ unsafe fn redirect(site: usize, code: &[u8], t: &isa::Thunk, helper: &[u8; isa::
done
}
+/// Replaces the instruction `old` at `site` by `new` of the same length (instruction boundaries
+/// stay where they are), in one locked 16-byte compare-exchange of the aligned block holding it –
+/// a thread sees the old instruction or the new one, never a mix. `true`: replaced.
+unsafe fn patch_in_place(site: usize, old: &[u8], new: &[u8]) -> bool {
+ use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache;
+ use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE};
+ use windows_sys::Win32::System::Threading::GetCurrentProcess;
+ let n = old.len();
+ let block = site & !15;
+ let off = site - block;
+ if n != new.len() || n == 0 || off + n > 16 || !REDIRECT.load(Ordering::Relaxed) {
+ return false;
+ }
+ if PATCHING.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
+ return false;
+ }
+ let mut prot = 0u32;
+ let mut done = false;
+ if VirtualProtect(block as *const _, 16, PAGE_EXECUTE_READWRITE, &mut prot) != 0 {
+ let cur = std::ptr::read_volatile(block as *const [u8; 16]);
+ if &cur[off..off + n] == old {
+ let mut want = cur;
+ want[off..off + n].copy_from_slice(new);
+ done = cas16(block as *mut u8, cur, want);
+ }
+ VirtualProtect(block as *const _, 16, prot, &mut prot);
+ FlushInstructionCache(GetCurrentProcess(), site as *const _, n);
+ }
+ PATCHING.store(false, Ordering::Release);
+ done
+}
+
+/// `lock cmpxchg16b` on the 16-byte aligned `p`.
+unsafe fn cas16(p: *mut u8, old: [u8; 16], new: [u8; 16]) -> bool {
+ let q = |b: &[u8]| u64::from_le_bytes(b.try_into().unwrap());
+ let (old_lo, old_hi, new_lo, new_hi) = (q(&old[..8]), q(&old[8..]), q(&new[..8]), q(&new[8..]));
+ let ok: u64;
+ // RBX cannot be named: the new low quadword comes in RSI and is swapped into RBX around the
+ // instruction. Every operand is in a register named here – one LLVM chose could be RBX.
+ core::arch::asm!(
+ "xchg rbx, rsi",
+ "lock cmpxchg16b xmmword ptr [rdi]",
+ "sete r9b",
+ "movzx r9d, r9b",
+ "xchg rbx, rsi",
+ in("rdi") p,
+ inout("rsi") new_lo => _,
+ inout("rax") old_lo => _,
+ inout("rdx") old_hi => _,
+ in("rcx") new_hi,
+ out("r9") ok,
+ );
+ ok != 0
+}
+
/// One log line per instruction kind, and one when emulation by exception turns out to be
/// frequent: each such trap costs tens of microseconds.
unsafe fn note_insn(kind: usize, what: &str, redirected: bool, ip: usize) {
@@ -510,8 +777,9 @@ unsafe extern "system" fn unsupported_insn_handler(info: *mut EXCEPTION_POINTERS
return -1;
}
}
- // likewise a CLWB site that became NOPs: a NOP does not raise this exception
- if code.first() == Some(&0x90) {
+ // likewise a CLWB site that became NOPs, or a MONITORX / MWAITX site that became a NOP /
+ // PAUSE (`patch_in_place`): those do not raise this exception
+ if code.first() == Some(&0x90) || code.starts_with(&[0x0F, 0x1F, 0x00]) || code.starts_with(&[0xF3, 0x90, 0x90]) {
return -1;
}
let mut helper = [0u8; isa::THUNK_MAX];
@@ -555,19 +823,41 @@ fn isa_memory_accessible(addr: usize, bytes: usize, write: bool) -> bool {
true
}
-/// A retail title's stall watchdog (GTA VI 1.0.2.1, exe+0x2215b91..): a thread walks 64
-/// heartbeat slots and, when one is older than its limit, calls a hook (which stores to
-/// address 0 and returns) and then stores to address 0 itself – a deliberate crash that sends
-/// a report. A host that is slow for a moment (shader compiles, other programs) trips it
-/// although nothing hangs. `XCL_WATCHDOG_BYPASS=1` on a Mac resumes the recognized
-/// stores. `XCL_TITLE_WATCHDOG=1` keeps the crash.
+/// A retail title's stall watchdog (GTA VI 1.0.2.1: its thread runs exe+0x2215a60) ends the title
+/// on purpose when its render thread has not gone through a frame for a while. What it measures
+/// is a heartbeat – a QueryPerformanceCounter stamp at exe+0x71b6338 that the render thread's
+/// per-frame function (func_120790) writes at its start and, through func_c9e330/func_c9e350, at
+/// its end, that func_1c82b20's loading loop writes, and that the watchdog itself writes after a
+/// Sleep measured over 2.0 s or when the title's pause or reset flag is set –, not any one wait.
+/// It picks one of its two loops once, at its start (the second when exe+0x71b62f0 was set then:
+/// no writer of it was found, so it likely never runs). Every second it sleeps 1000 ms; while no
+/// scope is open (exe+0x71b6334 = 0) it counts 30 checks in a row with the stamp unchanged – an
+/// open scope, the title's pause or reset flag (exe+0x71b6330, exe+0x71b6331) or a Sleep measured
+/// over 2.0 s (the process stopped from outside) starts the count again – and then, or in its
+/// first loop when one of its 64 groups has a scope open 300 s or more and the title's tunable
+/// 0x89aee1d6 is on, it calls the report hook the title armed (exe+0x71b6348: a hook `mov dword
+/// ptr [0], imm32`, the imm32 naming the report, then `ret` or `add rsp, imm8; ret`; or none, or
+/// the bare `ret` at exe+0x4380) and then stores to address 0 itself – a deliberate crash that
+/// sends a report. A frame the host holds that long trips it although nothing hangs (run 65: the
+/// first world frame's pipelines waited for at their binds, 27.5 s on one recording thread).
+/// `XCL_WATCHDOG_BYPASS=1` on a Mac resumes:
+/// - a hook's store, only when the hook's return address (above its frame) is right after the
+/// watchdog's `call rax` and on the watchdog's own store, in the hook's image: the hook's
+/// epilogue runs and returns there;
+/// - the watchdog's own store, in either of its two loops, at the loop's heartbeat check, which
+/// starts the count again without writing the heartbeat: while the frame is still held it
+/// fires again 30 checks (about 30 s) later, at a heartbeat about 61 s old, then about 91 s …
+/// Any other store to address 0 still crashes. `XCL_TITLE_WATCHDOG=1` keeps the crash. Each
+/// resume's line waits a few ms for a log file another thread is writing (`log::try_write_soon`):
+/// one fire's line may be its only record.
unsafe fn title_watchdog_resume(ctx: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT) -> bool {
if !cfg!(test) && (!crate::util::mac_host() || !WATCHDOG.load(Ordering::Acquire)) {
return false;
}
static SEEN: AtomicUsize = AtomicUsize::new(0);
+ static HOOKS: AtomicUsize = AtomicUsize::new(0);
let rip = ctx.Rip as usize;
- if rip < 0x1_0000 || !crate::gpu::shader::readable(rip, 12) {
+ if rip < 0x1_0000 || !crate::gpu::shader::readable(rip, 16) {
return false;
}
let at = |a: usize, n: usize| std::slice::from_raw_parts(a as *const u8, n);
@@ -575,20 +865,31 @@ unsafe fn title_watchdog_resume(ctx: &mut windows_sys::Win32::System::Diagnostic
if at(rip, 7) != [0xC7, 0x04, 0x25, 0, 0, 0, 0] {
return false;
}
- // the hook: `mov dword ptr [0], 0x2ef1e94b; ret`
- if at(rip + 7, 5) == [0x4B, 0xE9, 0xF1, 0x2E, 0xC3] {
- ctx.Rip += 11;
- return true;
- }
- // the fatal error / GPU hang watchdog (`mov dword ptr [0], 0x4d8bd421`): deliberate crash
- // tripped when world-load decompression or background compute pipeline builds take >30s
- if at(rip + 7, 5) == [0x21, 0xD4, 0x8B, 0x4D, 0xC3] {
- let n = SEEN.fetch_add(1, Ordering::Relaxed);
+ // a report hook (the five GTA VI arms: 0x4d8bd421 – render sync, the only one with a frame:
+ // `add rsp, 0x48; ret` –, 0x2ef1e94b, 0x4d795ee1, 0xb90ee778, 0x18283088): its epilogue next,
+ // and the return address above its frame the watchdog's call
+ if let Some(frame) = hook_frame(at(rip + 11, 5)) {
+ let image = modules::image_base_for_addr(rip);
+ let Some(slot) = (ctx.Rsp as usize).checked_add(frame) else { return false };
+ if image.is_none() || !crate::gpu::shader::readable(slot, 8) {
+ return false;
+ }
+ let ret = (slot as *const usize).read_unaligned();
+ if !watchdog_call(ret) || modules::image_base_for_addr(ret) != image {
+ return false;
+ }
+ let imm = (rip as *const u8).add(7).cast::().read_unaligned();
+ let n = HOOKS.fetch_add(1, Ordering::Relaxed);
+ #[cfg(test)]
+ WATCHDOG_RESUMED.with(|r| r.set([r.get()[0] + 1, r.get()[1], r.get()[2]]));
if n < 4 || n.is_power_of_two() {
- crate::log::try_write(crate::log::Level::Warn,
- format_args!("the title's fatal error / GPU hang watchdog triggered (#{n}: 0x4d8bd421 at rip={rip:#x}); resuming at the existing RET"));
+ let said = crate::log::try_write_soon(crate::log::Level::Warn, format_args!(
+ "the title's stall watchdog called its report hook (#{n}): hook {imm:#010x} at {rip:#x} (image+{:#x}); resuming at the hook's epilogue, which returns into the watchdog's own store",
+ rip - image.unwrap_or(0)
+ ));
+ watchdog_said(0, said);
}
- // Let the existing RET execute with the title's stack and unwind state intact.
+ // the hook's epilogue runs with its stack as it is and returns to the watchdog's store
ctx.Rip += 11;
return true;
}
@@ -601,17 +902,89 @@ unsafe fn title_watchdog_resume(ctx: &mut windows_sys::Win32::System::Diagnostic
&& at(rip - 0x3B, 8) == [0x49, 0x89, 0xF6, 0xBD, 0x1E, 0, 0, 0]
{
let n = SEEN.fetch_add(1, Ordering::Relaxed);
+ #[cfg(test)]
+ WATCHDOG_RESUMED.with(|r| r.set([r.get()[0], r.get()[1] + 1, r.get()[2]]));
if n < 4 || n.is_power_of_two() {
- crate::log::try_write(crate::log::Level::Warn,
+ let said = crate::log::try_write_soon(crate::log::Level::Warn,
format_args!("the title's stall watchdog fired (#{n}); resuming at the recognized heartbeat check"));
+ watchdog_said(1, said);
}
ctx.Rsi = ctx.R14;
ctx.Rip -= 0x42;
return true;
}
+ // its second loop (picked once, at the thread's start, when exe+0x71b62f0 was set: likely never;
+ // its walk of the scopes never fires, so only its countdown does): `mov r15, [rip+..]; mov ebp,
+ // 0x1e; jmp` – the path to the loop's heartbeat check when no slot is stale – 0x49 bytes
+ // before, its `call rax` right before, `xor eax, eax; int3` after. The loop's rsi, rdi, rbx,
+ // r14 and xmm6 live through the clock's and the hook's calls: no register to fix.
+ if crate::gpu::shader::readable(rip.wrapping_sub(0x49), 0x49 + 14)
+ && at(rip + 7, 7) == [0, 0, 0, 0, 0x31, 0xC0, 0xCC]
+ && at(rip - 2, 2) == [0xFF, 0xD0]
+ && at(rip - 0x49, 3) == [0x4C, 0x8B, 0x3D]
+ && at(rip - 0x42, 5) == [0xBD, 0x1E, 0, 0, 0]
+ && at(rip - 0x3D, 1) == [0xE9]
+ {
+ let n = SEEN.fetch_add(1, Ordering::Relaxed);
+ #[cfg(test)]
+ WATCHDOG_RESUMED.with(|r| r.set([r.get()[0], r.get()[1], r.get()[2] + 1]));
+ if n < 4 || n.is_power_of_two() {
+ let said = crate::log::try_write_soon(crate::log::Level::Warn,
+ format_args!("the title's stall watchdog fired in its second loop (#{n}); resuming at the recognized heartbeat check"));
+ watchdog_said(2, said);
+ }
+ ctx.Rip -= 0x49;
+ return true;
+ }
false
}
+/// The bytes of a report hook's frame – between its stack pointer at the store and its return
+/// address, which lies above them –, from the epilogue after the hook's store: `ret` (0) or `add
+/// rsp, imm8; ret` (imm8, below 0x80) – None for any other.
+fn hook_frame(epilogue: &[u8]) -> Option {
+ match epilogue {
+ [0xC3, ..] => Some(0),
+ &[0x48, 0x83, 0xC4, ib, 0xC3, ..] if ib < 0x80 => Some(ib as usize),
+ _ => None,
+ }
+}
+
+/// `ret` is where the title's stall watchdog's `call rax` (`ff d0`) returns: on the watchdog's own
+/// `mov dword ptr [0], 0`.
+unsafe fn watchdog_call(ret: usize) -> bool {
+ let Some(call) = ret.checked_sub(2) else { return false };
+ crate::gpu::shader::readable(call, 13)
+ && std::slice::from_raw_parts(call as *const u8, 2) == [0xFF, 0xD0]
+ && std::slice::from_raw_parts(ret as *const u8, 11) == [0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0]
+}
+
+#[cfg(test)]
+thread_local! {
+ /// (tests) this thread's `title_watchdog_resume`s: of a report hook, of the watchdog's store in
+ /// its first loop, in its second
+ static WATCHDOG_RESUMED: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
+ /// (tests) the same three kinds: this thread's resumes whose line was due (`#n` below 4 or a
+ /// power of two – of the counts all threads share), and of those the lines not given up for a
+ /// busy log file (`log::try_write_soon`)
+ static WATCHDOG_SAID: std::cell::Cell<[[usize; 2]; 3]> = const { std::cell::Cell::new([[0; 2]; 3]) };
+}
+
+/// A resume of kind `k` (`WATCHDOG_SAID`: a hook, the first loop, the second) had its line due;
+/// `said`: not given up for a busy log file. Counted for the tests only.
+#[cfg_attr(not(test), inline(always))]
+fn watchdog_said(k: usize, said: bool) {
+ #[cfg(test)]
+ WATCHDOG_SAID.with(|s| {
+ let mut v = s.get();
+ v[k][0] += 1;
+ v[k][1] += said as usize;
+ s.set(v);
+ });
+ #[cfg(not(test))]
+ let _ = (k, said);
+}
+
/// A call or jump through a null (or near-null) pointer: logged with the return address and
/// the registers, since the faulting address itself says nothing about the caller.
/// the probes of `XCL_PROBE_MOV`: (address, the 7 bytes that were there)
@@ -935,9 +1308,21 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics
unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) };
}
}
- ConsoleOnly::Monitorx => {}
+ ConsoleOnly::Monitorx => {
+ crate::waitwatch::note_monitorx(ctx.Rax);
+ // (`XCL_PATCH_MWAITX=1`) the bare instruction: a 3-byte NOP (`nop dword [rax]`) from now on
+ if patch_mwaitx() && code.starts_with(&[0x0F, 0x01, 0xFA]) && patch_in_place(rip, &[0x0F, 0x01, 0xFA], &[0x0F, 0x1F, 0x00]) {
+ note_insn(16, "MONITORX", true, rip);
+ }
+ }
ConsoleOnly::Mwaitx => {
+ crate::waitwatch::note_mwaitx(rip);
std::hint::spin_loop();
+ // (`XCL_PATCH_MWAITX=1`) the bare instruction: PAUSE; NOP from now on (an MWAITX may
+ // return at once)
+ if patch_mwaitx() && code.starts_with(&[0x0F, 0x01, 0xFB]) && patch_in_place(rip, &[0x0F, 0x01, 0xFB], &[0xF3, 0x90, 0x90]) {
+ note_insn(17, "MWAITX", true, rip);
+ }
}
ConsoleOnly::Clzero => {
// with an address-size prefix (0x67, among the prefixes before 0F 01 FC) the line
@@ -973,9 +1358,28 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics
ctx.Rax = final_rax;
ctx.EFlags = cmp_eflags(ctx.EFlags, final_rax, end);
}
+ // an end not past the start: the do-while loop zeroes one line and leaves
+ _ if end <= start && start <= u64::MAX - 0x40 && is_writable(line, 64) => {
+ std::ptr::write_bytes(line as *mut u8, 0, 64);
+ ctx.Rax = start + 0x40;
+ ctx.EFlags = cmp_eflags(ctx.EFlags, ctx.Rax, end);
+ }
_ if is_writable(line, 64) => {
// Fall back to stepping the single `clzero` (len - 9) so the title's own
- // `add / cmp / jb` runs natively for end <= start, huge/wrapping, or partial ranges.
+ // `add / cmp / jb` runs natively for huge/wrapping or partial ranges.
+ // Not into a loop another thread has redirected meanwhile (the call's bytes are
+ // there now: run the site again), and no loop is redirected after this.
+ while PATCHING.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
+ std::hint::spin_loop();
+ }
+ let still = std::slice::from_raw_parts((rip + len - 12) as *const u8, 3) == [0x0F, 0x01, 0xFC];
+ if still {
+ CLZERO_LOOP_STEPPED.store(true, Ordering::Release);
+ }
+ PATCHING.store(false, Ordering::Release);
+ if !still {
+ return -1;
+ }
std::ptr::write_bytes(line as *mut u8, 0, 64);
step = len - 9;
}
@@ -1235,6 +1639,244 @@ unsafe fn unwind(ctx: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTE
out
}
+/// (diagnostic, `waitwatch`) Thread `tid` stopped for a moment: its RIP, RSP, the frames
+/// unwound from there (after it runs again – the unwinder takes locks a stopped thread may
+/// hold) and the module return addresses on its stack from RSP up (up to `n` each).
+pub fn context_frames(tid: u32, n: usize) -> Option<(usize, usize, Vec, Vec)> {
+ use windows_sys::Win32::Foundation::CloseHandle;
+ use windows_sys::Win32::System::Diagnostics::Debug::{GetThreadContext, CONTEXT, CONTEXT_CONTROL_AMD64, CONTEXT_INTEGER_AMD64};
+ use windows_sys::Win32::System::Threading::{OpenThread, ResumeThread, SuspendThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME};
+ unsafe {
+ let h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, 0, tid);
+ if h.is_null() {
+ return None;
+ }
+ #[repr(align(16))]
+ struct Aligned(CONTEXT);
+ let mut c: Aligned = std::mem::zeroed();
+ c.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64;
+ let got = SuspendThread(h) != u32::MAX && {
+ let ok = GetThreadContext(h, &mut c.0) != 0;
+ ResumeThread(h);
+ ok
+ };
+ CloseHandle(h);
+ if !got {
+ return None;
+ }
+ let (rip, rsp) = (c.0.Rip as usize, c.0.Rsp as usize);
+ let mut scanned = Vec::new();
+ for k in 0..4096usize {
+ let at = rsp + 8 * k;
+ if !crate::gpu::shader::readable(at, 8) {
+ break;
+ }
+ let v = (at as *const usize).read_unaligned();
+ if modules::image_base_for_addr(v).is_some() || modules::describe_address(v).contains('+') {
+ if scanned.last() != Some(&v) {
+ scanned.push(v);
+ }
+ if scanned.len() == n {
+ break;
+ }
+ }
+ }
+ let frames = unwind(&mut c.0, n);
+ Some((rip, rsp, frames, scanned))
+ }
+}
+
+/// (diagnostic, `waitwatch`) Where thread `tid` is inside a system call, without stopping it:
+/// Wine keeps the registers a thread entered its current (or last) system call with in a
+/// syscall frame, `amd64_thread_data.syscall_frame` at TEB+0x328 (rax … r15 @0, rip @0x70,
+/// rsp @0x88, rbp @0x98). A thread held in a wait stays in that call: its RIP and RSP there,
+/// the frames unwound from them and the module return addresses on its stack (up to `n`), and
+/// the thread's CPU time (ms) – unchanged between looks: it is held, not running.
+pub fn syscall_frames(tid: u32, n: usize) -> Option<(usize, usize, Vec, Vec, u64)> {
+ use windows_sys::Win32::Foundation::{CloseHandle, FILETIME};
+ use windows_sys::Win32::System::Diagnostics::Debug::{CONTEXT, CONTEXT_CONTROL_AMD64, CONTEXT_INTEGER_AMD64};
+ use windows_sys::Win32::System::Threading::{GetThreadTimes, OpenThread, THREAD_QUERY_INFORMATION};
+ #[link(name = "ntdll")]
+ extern "system" {
+ fn NtQueryInformationThread(h: *mut c_void, class: u32, info: *mut c_void, len: u32, ret: *mut u32) -> i32;
+ }
+ unsafe {
+ let h = OpenThread(THREAD_QUERY_INFORMATION, 0, tid);
+ if h.is_null() {
+ return None;
+ }
+ let mut tbi = [0usize; 6];
+ let teb = if NtQueryInformationThread(h, 0, tbi.as_mut_ptr() as *mut c_void, 48, std::ptr::null_mut()) >= 0 { tbi[1] } else { 0 };
+ let (mut c0, mut e0, mut k0, mut u0): (FILETIME, FILETIME, FILETIME, FILETIME) = (std::mem::zeroed(), std::mem::zeroed(), std::mem::zeroed(), std::mem::zeroed());
+ let cpu_ms = if GetThreadTimes(h, &mut c0, &mut e0, &mut k0, &mut u0) != 0 {
+ let t = |f: FILETIME| ((f.dwHighDateTime as u64) << 32 | f.dwLowDateTime as u64) / 10_000;
+ t(k0) + t(u0)
+ } else {
+ 0
+ };
+ CloseHandle(h);
+ if teb == 0 || !crate::gpu::shader::readable(teb + 0x328, 8) {
+ return None;
+ }
+ let frame = *((teb + 0x328) as *const usize);
+ if frame == 0 || !crate::gpu::shader::readable(frame, 0xa8) {
+ return None;
+ }
+ let r = |o: usize| *((frame + o) as *const u64);
+ #[repr(align(16))]
+ struct Aligned(CONTEXT);
+ let mut c: Aligned = std::mem::zeroed();
+ c.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64;
+ c.0.Rax = r(0);
+ c.0.Rbx = r(0x8);
+ c.0.Rcx = r(0x10);
+ c.0.Rdx = r(0x18);
+ c.0.Rsi = r(0x20);
+ c.0.Rdi = r(0x28);
+ c.0.R8 = r(0x30);
+ c.0.R9 = r(0x38);
+ c.0.R10 = r(0x40);
+ c.0.R11 = r(0x48);
+ c.0.R12 = r(0x50);
+ c.0.R13 = r(0x58);
+ c.0.R14 = r(0x60);
+ c.0.R15 = r(0x68);
+ c.0.Rip = r(0x70);
+ c.0.Rsp = r(0x88);
+ c.0.Rbp = r(0x98);
+ let (rip, rsp) = (c.0.Rip as usize, c.0.Rsp as usize);
+ if rip == 0 || !crate::gpu::shader::readable(rsp, 8) {
+ return None;
+ }
+ let mut scanned = Vec::new();
+ for k in 0..4096usize {
+ let at = rsp + 8 * k;
+ if !crate::gpu::shader::readable(at, 8) {
+ break;
+ }
+ let v = (at as *const usize).read_unaligned();
+ if modules::image_base_for_addr(v).is_some() || modules::describe_address(v).contains('+') {
+ if scanned.last() != Some(&v) {
+ scanned.push(v);
+ }
+ if scanned.len() == n {
+ break;
+ }
+ }
+ }
+ let frames = unwind(&mut c.0, n);
+ Some((rip, rsp, frames, scanned, cpu_ms))
+ }
+}
+
+/// Local diagnostic (stall hunting): every thread's RIP and the module return addresses found
+/// by scanning 16 KiB of its stack, logged one line per thread. Unlike `dump_threads` it takes
+/// no lock a stuck thread may hold: no unwinder (RtlLookupFunctionEntry), no loader
+/// (GetModuleHandleEx) – module ranges come from XCL's mapped modules and the PEB loader list,
+/// read without the loader lock before any thread is suspended.
+pub fn dump_threads_raw(out: &mut std::fs::File) {
+ use std::io::Write;
+ use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
+ use windows_sys::Win32::System::Diagnostics::Debug::{GetThreadContext, CONTEXT, CONTEXT_CONTROL_AMD64, CONTEXT_INTEGER_AMD64};
+ use windows_sys::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, Thread32First, Thread32Next, TH32CS_SNAPTHREAD, THREADENTRY32};
+ use windows_sys::Win32::System::Threading::{GetCurrentProcessId, GetCurrentThreadId, OpenThread, ResumeThread, SuspendThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME};
+ #[link(name = "ntdll")]
+ extern "system" {
+ fn NtQueryInformationThread(h: *mut c_void, class: u32, info: *mut c_void, len: u32, ret: *mut u32) -> i32;
+ }
+ unsafe {
+ let t0 = crate::log::uptime();
+ // module ranges, all lock-free: XCL's title modules (atomic range table) and the PEB list
+ let mut ranges: Vec<(usize, usize, String)> = Vec::new();
+ let peb: usize;
+ core::arch::asm!("mov {}, gs:[0x60]", out(reg) peb, options(nostack, readonly, preserves_flags));
+ let ldr = *((peb + 0x18) as *const usize);
+ if ldr != 0 {
+ let head = ldr + 0x10;
+ let mut e = *(head as *const usize);
+ let mut guard = 0;
+ while e != 0 && e != head && guard < 1024 {
+ guard += 1;
+ let base = *((e + 0x30) as *const usize);
+ let size = *((e + 0x40) as *const u32) as usize;
+ let len = (*((e + 0x58) as *const u16) / 2) as usize;
+ let buf = *((e + 0x60) as *const usize) as *const u16;
+ let name = if !buf.is_null() && len > 0 && len < 260 { String::from_utf16_lossy(std::slice::from_raw_parts(buf, len)).to_ascii_lowercase() } else { format!("{base:#x}") };
+ if base != 0 && size != 0 {
+ ranges.push((base, size, name));
+ }
+ e = *(e as *const usize);
+ }
+ }
+ let classify = |a: usize| -> Option {
+ if let Some(b) = modules::image_base_for_addr(a) {
+ return Some(format!("title@{b:#x}+{:#x}", a - b));
+ }
+ ranges.iter().find(|r| a >= r.0 && a < r.0 + r.1).map(|r| format!("{}+{:#x}", r.2, a - r.0))
+ };
+ let _ = writeln!(out, "=== raw thread dump at {t0:.1} s ({} PEB modules) ===", ranges.len());
+ let (pid, me) = (GetCurrentProcessId(), GetCurrentThreadId());
+ let snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
+ if snap == INVALID_HANDLE_VALUE {
+ let _ = writeln!(out, "no snapshot");
+ return;
+ }
+ let mut te: THREADENTRY32 = std::mem::zeroed();
+ te.dwSize = std::mem::size_of::() as u32;
+ let mut ok = Thread32First(snap, &mut te) != 0;
+ let mut stack = vec![0usize; 4096];
+ while ok {
+ if te.th32OwnerProcessID == pid && te.th32ThreadID != me {
+ let h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, 0, te.th32ThreadID);
+ if !h.is_null() {
+ #[repr(align(16))]
+ struct Aligned(CONTEXT);
+ let mut c: Aligned = std::mem::zeroed();
+ c.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64;
+ let susp = SuspendThread(h);
+ let got = susp != u32::MAX && {
+ let ok = GetThreadContext(h, &mut c.0) != 0;
+ ResumeThread(h);
+ ok
+ };
+ // ThreadBasicInformation: TebBaseAddress at +8; NT_TIB StackBase at TEB+8
+ let mut tbi = [0usize; 6];
+ let teb = if NtQueryInformationThread(h, 0, tbi.as_mut_ptr() as *mut c_void, 48, std::ptr::null_mut()) >= 0 { tbi[1] } else { 0 };
+ let stack_base = if teb != 0 { *((teb + 8) as *const usize) } else { 0 };
+ if got {
+ let rsp = c.0.Rsp as usize;
+ let n = if stack_base > rsp { ((stack_base - rsp) / 8).min(stack.len()) } else { 0 };
+ if n > 0 {
+ std::ptr::copy_nonoverlapping(rsp as *const usize, stack.as_mut_ptr(), n);
+ }
+ let rip = classify(c.0.Rip as usize).unwrap_or_else(|| format!("{:#x}", c.0.Rip));
+ let mut hits: Vec = Vec::new();
+ for &v in &stack[..n] {
+ if let Some(d) = classify(v) {
+ if hits.last() != Some(&d) {
+ hits.push(d);
+ }
+ if hits.len() == 28 {
+ break;
+ }
+ }
+ }
+ let _ = writeln!(out, "thread {} (suspend count {}) rip {} rsp {:#x} [{} qwords] | {}", te.th32ThreadID, susp, rip, rsp, n, hits.join(" < "));
+ } else {
+ let _ = writeln!(out, "thread {}: no context (suspend returned {:#x})", te.th32ThreadID, susp);
+ }
+ let _ = out.flush();
+ CloseHandle(h);
+ }
+ }
+ ok = Thread32Next(snap, &mut te) != 0;
+ }
+ CloseHandle(snap);
+ let _ = writeln!(out, "=== done ===");
+ let _ = out.flush();
+ }
+}
+
/// `XCL_THREAD_DUMP_AT`: every other thread of the process stopped for a moment – where it is
/// (RIP) and the calls on its stack that lead there, in the log.
pub fn dump_threads() {
@@ -1562,6 +2204,115 @@ pub fn start_probes() {
mod tests {
use super::*;
+ /// MONITORX / MWAITX replaced in place: the instruction across an 8-byte boundary (GTA VI's
+ /// MONITORX at +7 of its block) becomes the 3-byte NOP, its neighbours kept; a second try
+ /// finds the new bytes and leaves them; one past its 16-byte block is not touched.
+ /// A crash's memory: the qwords around what a register points at, and one step further,
+ /// labelled from the register (one not 8-aligned too); near the end of what is readable as
+ /// many qwords as are; nothing for what is not readable; a context with registers of every
+ /// kind gone through without a fault.
+ #[test]
+ fn crash_memory_reads_what_registers_point_at_and_one_step_further() {
+ use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE};
+ unsafe {
+ let inner: Box<[u64; 16]> = Box::new(std::array::from_fn(|k| 0x1111_0000 + k as u64));
+ let inner_at = inner.as_ptr() as u64;
+ let mut outer: Box<[u64; 16]> = Box::new([0; 16]);
+ // the qword a register 3 bytes into outer[8] points into, and two further on
+ outer[8] = inner_at;
+ outer[10] = inner_at + 0x40;
+ let p = outer.as_ptr() as usize + 8 * 8 + 3;
+ let (line, after) = crash_memory_line("test", p).expect("readable");
+ assert!(line.contains(&format!("[{inner_at:#018x}]")), "{line}");
+ assert_eq!((after[0], after[2]), (inner_at, inner_at + 0x40));
+ assert!(crash_memory_line("test", 0x10).is_none());
+ assert!(crash_memory_line("test", 0xDEAD_0000_0000).is_none());
+ assert_eq!(step_label("rsi", p, 0), "[rsi-0x3] ->");
+ assert_eq!(step_label("rsi", p, 2), "[rsi+0xd] ->");
+ assert_eq!(step_label("rbx", 0x1000, 1), "[rbx+0x8] ->");
+ // the last 16 bytes of a region whose next page is reserved only: 2 qwords
+ let r = VirtualAlloc(std::ptr::null(), 0x2_0000, MEM_RESERVE, PAGE_READWRITE) as usize;
+ assert!(r != 0 && !VirtualAlloc(r as *const _, 0x1_0000, MEM_COMMIT, PAGE_READWRITE).is_null());
+ *((r + 0x1_0000 - 16) as *mut u64) = 0x5151;
+ let (line, after) = crash_memory_line("end", r + 0x1_0000 - 16).expect("the last qwords are readable");
+ assert_eq!(after, [0x5151, 0], "{line}");
+ let mut c: windows_sys::Win32::System::Diagnostics::Debug::CONTEXT = std::mem::zeroed();
+ c.Rsi = p as u64;
+ c.Rax = 0xDEAD_0000_0000;
+ c.Rbx = 1;
+ c.Rcx = u64::MAX;
+ c.Rdx = (r + 0x1_0000 - 8) as u64;
+ c.Rsp = &c as *const _ as u64;
+ let mut lines = Vec::new();
+ crash_memory(&c, &mut |l| lines.push(l));
+ VirtualFree(r as *mut _, 0, MEM_RELEASE);
+ let has = |s: &str| lines.iter().any(|l| l.contains(s));
+ assert!(has(&format!("crash memory: rsi {p:#x}")), "{lines:#?}");
+ assert!(has(&format!("crash memory: [rsi-0x3] -> {inner_at:#x}")), "{lines:#?}");
+ assert!(has(&format!("crash memory: [rsi+0xd] -> {:#x}", inner_at + 0x40)), "{lines:#?}");
+ assert!(has(&format!("crash memory: rdx {:#x}", r + 0x1_0000 - 8)), "{lines:#?}");
+ assert!(!has("crash memory: rax") && !has("crash memory: rbx") && !has("crash memory: rcx"), "{lines:#?}");
+ }
+ }
+
+ /// A crash report's wait for a lock (`try_lock_within`), on mutexes of the test's own (the
+ /// report's own wait is spent once a process): a free lock is taken with the wait spent – each
+ /// is looked at once; one another thread holds is given up when all of the wait is spent; one
+ /// this thread holds itself (a fault inside the kernel's page map) is given up too, no deadlock.
+ #[test]
+ fn a_lock_is_tried_within_the_wait_left() {
+ let free = Mutex::new(1u32);
+ assert!(try_lock_within(&free, &AtomicU32::new(0)).is_some(), "a spent wait still looks once");
+ let held = std::sync::Arc::new(Mutex::new(2u32));
+ let (taken, is_taken) = std::sync::mpsc::channel();
+ let (go, gone) = std::sync::mpsc::channel::<()>();
+ let helper = {
+ let held = std::sync::Arc::clone(&held);
+ std::thread::spawn(move || {
+ let _g = held.lock().unwrap_or_else(|e| e.into_inner());
+ let _ = taken.send(());
+ let _ = gone.recv_timeout(std::time::Duration::from_secs(2));
+ })
+ };
+ let _ = is_taken.recv();
+ let left = AtomicU32::new(20);
+ let busy = try_lock_within(&held, &left).is_none();
+ // (the helper lets go before anything is asserted)
+ drop(go);
+ let _ = helper.join();
+ assert!(busy, "a lock another thread holds is given up");
+ assert_eq!(left.load(Ordering::Relaxed), 0, "once all of the wait is spent");
+ assert!(try_lock_within(&held, &AtomicU32::new(0)).is_some(), "let go: taken at its one look");
+ let _mine = free.lock().unwrap();
+ assert!(try_lock_within(&free, &AtomicU32::new(5)).is_none(), "held by this thread: given up, no deadlock");
+ }
+
+ #[test]
+ fn monitorx_and_mwaitx_are_replaced_in_place() {
+ use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READ};
+ unsafe {
+ let code = VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, windows_sys::Win32::System::Memory::PAGE_EXECUTE_READWRITE) as usize;
+ assert_ne!(code, 0);
+ std::ptr::write_bytes(code as *mut u8, 0xCC, 0x40);
+ std::ptr::copy_nonoverlapping([0x0F, 0x01, 0xFA].as_ptr(), (code + 7) as *mut u8, 3);
+ std::ptr::copy_nonoverlapping([0x0F, 0x01, 0xFB].as_ptr(), (code + 0x10) as *mut u8, 3);
+ std::ptr::copy_nonoverlapping([0x0F, 0x01, 0xFB].as_ptr(), (code + 0x2E) as *mut u8, 3);
+ let mut old = 0u32;
+ windows_sys::Win32::System::Memory::VirtualProtect(code as *const _, 0x1000, PAGE_EXECUTE_READ, &mut old);
+ assert!(patch_in_place(code + 7, &[0x0F, 0x01, 0xFA], &[0x0F, 0x1F, 0x00]));
+ assert!(patch_in_place(code + 0x10, &[0x0F, 0x01, 0xFB], &[0xF3, 0x90, 0x90]));
+ assert!(!patch_in_place(code + 7, &[0x0F, 0x01, 0xFA], &[0x0F, 0x1F, 0x00]), "already replaced");
+ assert!(!patch_in_place(code + 0x2E, &[0x0F, 0x01, 0xFB], &[0xF3, 0x90, 0x90]), "across its 16-byte block");
+ let b = std::slice::from_raw_parts(code as *const u8, 0x40);
+ assert_eq!(b[..7], [0xCC; 7]);
+ assert_eq!(b[7..10], [0x0F, 0x1F, 0x00]);
+ assert_eq!(b[10..16], [0xCC; 6]);
+ assert_eq!(b[0x10..0x13], [0xF3, 0x90, 0x90]);
+ assert_eq!(b[0x2E..0x31], [0x0F, 0x01, 0xFB]);
+ VirtualFree(code as *mut _, 0, MEM_RELEASE);
+ }
+ }
+
#[test]
fn bounded_cstr_stops_at_nul_limit_and_unreadable_memory() {
unsafe {
@@ -1678,14 +2429,16 @@ mod tests {
assert!(s[0x40..0xC0].iter().all(|&b| b == 0));
assert!(s[0xC0..0x140].iter().all(|&b| b == 0xA5));
- // 3) end <= start: executes the single first clzero line [0x40..0x80) and steps only 3 bytes so add/cmp/jb runs natively
+ // 3) end <= start: the do-while loop zeroes the single first line [0x40..0x80) and
+ // leaves – the whole loop is stepped, RAX one line on, the flags of its compare
for end in [buf + 0x40, buf] {
std::ptr::write_bytes(buf as *mut u8, 0xA5, 0x140);
ctx = std::mem::zeroed();
(ctx.Rip, ctx.Rax, ctx.Rdx, ctx.EFlags) = (code as u64, (buf + 0x53) as u64, end as u64, 0x202);
assert_eq!(emulate_console_only(&mut ctx), -1);
- assert_eq!(ctx.Rip, code as u64 + 3);
- assert_eq!(ctx.Rax, (buf + 0x53) as u64);
+ assert_eq!(ctx.Rip, code as u64 + 12);
+ assert_eq!(ctx.Rax, (buf + 0x93) as u64);
+ assert_eq!(ctx.EFlags, cmp_eflags(0x202, (buf + 0x93) as u64, end as u64));
let s = std::slice::from_raw_parts(buf as *const u8, 0x140);
assert!(s[..0x40].iter().all(|&b| b == 0xA5));
assert!(s[0x40..0x80].iter().all(|&b| b == 0));
@@ -1740,30 +2493,680 @@ mod tests {
}
}
- /// The title's fatal error / GPU hang watchdog at world load (`mov dword ptr [0], 0x4d8bd421`)
- /// is resumed by skipping the crash, allowing long shader compilation to complete.
+ /// The shapes of GTA VI 1.0.2.1's report hooks and stall watchdog where the resume rule looks
+ /// (a scan of the title's code finds seven `mov dword ptr [0], imm32`: these five hooks' and the
+ /// watchdog's two). Synthetic: each sequence holds, at its place, every byte
+ /// `title_watchdog_resume` reads and every instruction the real-fault test runs
+ /// (`title_watchdog_resumes_real_faults_through_the_exception_handler`) as the title has them,
+ /// and `int3` everywhere else. `n` bytes: `parts` at their offsets, `int3` elsewhere.
+ const fn shape(parts: &[(usize, &[u8])]) -> [u8; N] {
+ let mut out = [0xCC; N];
+ let mut i = 0;
+ while i < parts.len() {
+ let (at, bytes) = parts[i];
+ let mut k = 0;
+ while k < bytes.len() {
+ out[at + k] = bytes[k];
+ k += 1;
+ }
+ i += 1;
+ }
+ out
+ }
+ /// The report hook 0x4d8bd421 (render sync), the only one with a frame: `sub rsp, 0x48` … its
+ /// store at +0x63, `add rsp, 0x48; ret`.
+ const HOOK_4D8BD421: [u8; 0x74] = shape(&[
+ (0x00, &[0x48, 0x83, 0xEC, 0x48]), // sub rsp, 0x48
+ (0x63, &[0xC7, 0x04, 0x25, 0, 0, 0, 0, 0x21, 0xD4, 0x8B, 0x4D]), // mov dword ptr [0], 0x4d8bd421
+ (0x6E, &[0x48, 0x83, 0xC4, 0x48, 0xC3]), // add rsp, 0x48; ret
+ ]);
+ /// … the four leaf hooks: the store, `ret`, the padding after it
+ const LEAF_HOOKS: [[u8; 16]; 4] = [
+ [0xC7, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, 0x4B, 0xE9, 0xF1, 0x2E, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC],
+ [0xC7, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, 0xE1, 0x5E, 0x79, 0x4D, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC],
+ [0xC7, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, 0x78, 0xE7, 0x0E, 0xB9, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC],
+ [0xC7, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, 0x88, 0x30, 0x28, 0x18, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC],
+ ];
+ /// … the watchdog's first loop from its heartbeat check (`mov r15, [heartbeat]`) past its own
+ /// store (+0x42, right after the hook's `call rax`) and the `int3` after it
+ const WATCHDOG_1: [u8; 0x4E] = shape(&[
+ (0x00, &[0x4C, 0x8B, 0x3D, 0, 0, 0, 0]), // mov r15, [rip+disp32]: the heartbeat
+ (0x07, &[0x49, 0x89, 0xF6, 0xBD, 0x1E, 0, 0, 0]), // mov r14, rsi; mov ebp, 0x1e
+ (0x0F, &[0x48, 0x8D, 0x74, 0x24, 0x28]), // lea rsi, [rsp+0x28]
+ (0x14, &[0xE9, 0, 0, 0, 0]), // jmp rel32: the loop's top
+ (0x19, &[0x49, 0x89, 0xF6, 0x89, 0xEB]), // mov r14, rsi; mov ebx, ebp
+ (0x40, &[0xFF, 0xD0]), // call rax: the hook
+ (0x42, &[0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0]), // mov dword ptr [0], 0
+ ]);
+ /// … its second loop from its heartbeat check past its own store (+0x49, right after the
+ /// hook's `call rax`) and the `xor eax, eax; int3` after it
+ const WATCHDOG_2: [u8; 0x57] = shape(&[
+ (0x00, &[0x4C, 0x8B, 0x3D, 0, 0, 0, 0]), // mov r15, [rip+disp32]: the heartbeat
+ (0x07, &[0xBD, 0x1E, 0, 0, 0]), // mov ebp, 0x1e
+ (0x0C, &[0xE9, 0, 0, 0, 0]), // jmp rel32: the loop's top
+ (0x47, &[0xFF, 0xD0]), // call rax: the hook
+ (0x49, &[0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0]), // mov dword ptr [0], 0
+ (0x54, &[0x31, 0xC0]), // xor eax, eax
+ ]);
+
+ /// Two pages registered as an image (`modules`) while the value lives – what
+ /// `title_watchdog_resume` takes the title's image to be.
+ struct TestImage {
+ base: usize,
+ }
+
+ impl TestImage {
+ unsafe fn new(name: &str) -> TestImage {
+ use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE};
+ let base = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) as usize;
+ assert_ne!(base, 0);
+ modules::register_mapped(std::sync::Arc::new(modules::MappedModule {
+ name: name.into(), path: name.into(), base, size: 0x2000, entry_rva: 0, is_dll: false,
+ exports: Default::default(), tls_callbacks: Mutex::new(Vec::new()), no_thread_calls: Default::default(),
+ initialized: std::sync::atomic::AtomicBool::new(true), stack_reserve: 0,
+ }));
+ TestImage { base }
+ }
+
+ /// `bytes` at `offset` into the image: their address
+ unsafe fn put(&self, offset: usize, bytes: &[u8]) -> usize {
+ assert!(offset + bytes.len() <= 0x2000);
+ std::ptr::copy_nonoverlapping(bytes.as_ptr(), (self.base + offset) as *mut u8, bytes.len());
+ self.base + offset
+ }
+ }
+
+ impl Drop for TestImage {
+ fn drop(&mut self) {
+ modules::unregister_mapped(self.base);
+ unsafe { windows_sys::Win32::System::Memory::VirtualFree(self.base as *mut _, 0, windows_sys::Win32::System::Memory::MEM_RELEASE) };
+ }
+ }
+
+ /// a context at `rip` with its stack at `rsp`, rsi and r14 told apart, rbx and rdi set – and
+ /// every other byte of it told apart too, so that a resume writing any field shows
+ /// (`ctx_differs`)
+ fn watchdog_ctx(rip: usize, rsp: usize) -> windows_sys::Win32::System::Diagnostics::Debug::CONTEXT {
+ let mut ctx: windows_sys::Win32::System::Diagnostics::Debug::CONTEXT = unsafe { std::mem::zeroed() };
+ let bytes = unsafe { std::slice::from_raw_parts_mut(&mut ctx as *mut _ as *mut u8, std::mem::size_of_val(&ctx)) };
+ for (i, b) in bytes.iter_mut().enumerate() {
+ *b = (i as u8).wrapping_mul(37).wrapping_add(11);
+ }
+ (ctx.Rip, ctx.Rsp, ctx.Rsi, ctx.R14, ctx.Rbx, ctx.Rdi) = (rip as u64, rsp as u64, 0x5151, 0x1414, 0xB0B0, 0xD1D1);
+ ctx
+ }
+
+ /// Where `a` differs from `b`: the offsets in CONTEXT of the 8-byte words not the same (none:
+ /// every byte is) – Rip is at 0xf8, Rsi at 0xa8, Rsp at 0x98.
+ fn ctx_differs(a: &windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, b: &windows_sys::Win32::System::Diagnostics::Debug::CONTEXT) -> Vec {
+ let bytes = |c: &windows_sys::Win32::System::Diagnostics::Debug::CONTEXT| unsafe { std::slice::from_raw_parts(c as *const _ as *const u8, std::mem::size_of_val(c)).to_vec() };
+ let (a, b) = (bytes(a), bytes(b));
+ a.chunks(8).zip(b.chunks(8)).enumerate().filter(|(_, (x, y))| x != y).map(|(i, _)| 8 * i).collect()
+ }
+
+ /// GTA VI's stall watchdog on the shapes its binary has: each of its five report hooks – four
+ /// ending `ret`, 0x4d8bd421 `add rsp, 0x48; ret`, its return address 0x48 bytes up – called by
+ /// either loop's `call rax` is resumed at its epilogue: of its whole context (every byte) only
+ /// Rip changes, to the store + 11, and the resume is counted on this thread
+ /// (`WATCHDOG_RESUMED`). The watchdog's own store that epilogue returns to is resumed at that
+ /// loop's heartbeat check: in the first loop only Rip and Rsi change (rsi = r14, its countdown's
+ /// QPC pointer), in the second only Rip; counted too. (The lines the resumes write:
+ /// `title_watchdog_lines_wait_a_few_ms_for_a_busy_log` – their numbers are shared with the
+ /// other tests' threads.)
#[test]
- fn title_watchdog_resumes_fatal_crash_at_world_load() {
- use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE};
+ fn title_watchdog_resumes_each_report_hook_and_then_the_watchdog_on_the_binarys_shapes() {
unsafe {
- let code = VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) as usize;
- assert!(code != 0);
- // mov dword ptr [0], 0x4d8bd421; ret
- let insn = [0xC7u8, 0x04, 0x25, 0, 0, 0, 0, 0x21, 0xD4, 0x8B, 0x4D, 0xC3];
- std::ptr::copy_nonoverlapping(insn.as_ptr(), code as *mut u8, insn.len());
- let mut ctx: windows_sys::Win32::System::Diagnostics::Debug::CONTEXT = std::mem::zeroed();
- ctx.Rip = code as u64;
- assert!(title_watchdog_resume(&mut ctx));
- assert_eq!(ctx.Rip as usize, code + 11);
- // A readable stack slot does not establish the frame layout at a trap.
- let return_address = code + 0x200;
- let saved_rsp = (&return_address as *const usize) as u64;
- (code as *mut u8).add(11).write(0xCC);
- ctx.Rip = code as u64;
- ctx.Rsp = saved_rsp;
- assert!(!title_watchdog_resume(&mut ctx));
- assert_eq!((ctx.Rip, ctx.Rsp), (code as u64, saved_rsp));
- VirtualFree(code as *mut _, 0, MEM_RELEASE);
+ let image = TestImage::new("watchdog_hooks.exe");
+ // the shapes: the stores at their places
+ assert_eq!(HOOK_4D8BD421[0x63..0x74], [0xC7, 0x04, 0x25, 0, 0, 0, 0, 0x21, 0xD4, 0x8B, 0x4D, 0x48, 0x83, 0xC4, 0x48, 0xC3, 0xCC]);
+ assert_eq!(WATCHDOG_1[0x40..0x4E], [0xFF, 0xD0, 0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0, 0xCC]);
+ assert_eq!(WATCHDOG_2[0x47..0x57], [0xFF, 0xD0, 0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0, 0x31, 0xC0, 0xCC]);
+ // (the loop's heartbeat check, its store's offset from there, the first loop)
+ let loops = [(image.put(0x100, &WATCHDOG_1), 0x42usize, true), (image.put(0x200, &WATCHDOG_2), 0x49usize, false)];
+ // (the hook's store, its frame, its imm32)
+ let mut hooks = vec![(image.put(0x400, &HOOK_4D8BD421) + 0x63, 0x48usize, 0x4d8b_d421u32)];
+ for (k, bytes) in LEAF_HOOKS.iter().enumerate() {
+ hooks.push((image.put(0x500 + 0x20 * k, bytes), 0, u32::from_le_bytes(bytes[7..11].try_into().unwrap())));
+ }
+ assert_eq!(hooks.iter().map(|h| h.2).collect::>(), [0x4d8b_d421, 0x2ef1_e94b, 0x4d79_5ee1, 0xb90e_e778, 0x1828_3088]);
+ for &(store, frame, imm) in &hooks {
+ for &(check, store_at, first) in &loops {
+ let ret = check + store_at;
+ // the return address above the hook's frame; below it, a pointer into the hook
+ // (a resume that read it would not find the watchdog's call there)
+ let mut stack = Box::new([store - 0x20; 32]);
+ stack[frame / 8] = ret;
+ let rsp = stack.as_ptr() as usize;
+ let mut ctx = watchdog_ctx(store, rsp);
+ let mut want = ctx;
+ want.Rip = (store + 11) as u64;
+ let before = WATCHDOG_RESUMED.with(|r| r.get());
+ let loop_k = if first { 1 } else { 2 };
+ assert!(title_watchdog_resume(&mut ctx), "hook {imm:#x} called from loop {loop_k}");
+ assert_eq!(ctx_differs(&ctx, &want), Vec::::new(), "hook {imm:#x}: at its epilogue, nothing else changed");
+ assert_eq!(WATCHDOG_RESUMED.with(|r| r.get())[0], before[0] + 1, "hook {imm:#x}: counted");
+ // its epilogue (`add rsp, frame` and `ret`): into the watchdog's store
+ (ctx.Rip, ctx.Rsp) = (ret as u64, (rsp + frame + 8) as u64);
+ let mut want = ctx;
+ want.Rip = check as u64;
+ if first {
+ want.Rsi = want.R14;
+ }
+ assert!(title_watchdog_resume(&mut ctx), "loop {loop_k}'s store after hook {imm:#x}");
+ assert_eq!(ctx_differs(&ctx, &want), Vec::::new(), "loop {loop_k}: at its heartbeat check{}, nothing else changed", if first { " with rsi = r14" } else { "" });
+ let after = WATCHDOG_RESUMED.with(|r| r.get());
+ assert_eq!((after[0], after[loop_k]), (before[0] + 1, before[loop_k] + 1), "loop {loop_k}'s store counted");
+ }
+ }
+ }
+ }
+
+ /// A store to address 0 the watchdog bypass does not know stays fatal: not resumed, its whole
+ /// context (every byte) as it was, not counted – an epilogue neither `ret` nor `add rsp, imm8;
+ /// ret`; a hook whose return address is not right after a `call rax`, not on the watchdog's own
+ /// store, in another image or none, not readable or null; a hook in no image (its return
+ /// address in none either); a stack slot not readable or past the address space; either loop's
+ /// store with another byte at one of the places the rule looks at, before or after it (the
+ /// first loop's on a stack that holds no watchdog return, so that its store followed by `ret`
+ /// is no hook either). Each differs from a copy that is resumed in that one point.
+ #[test]
+ fn title_watchdog_keeps_stores_to_address_0_it_does_not_know_fatal() {
+ use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT;
+ use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE};
+ unsafe {
+ let image = TestImage::new("watchdog_unknown.exe");
+ let other = TestImage::new("watchdog_other.exe");
+ // not resumed, and nothing changed
+ let refused = |ctx: &mut CONTEXT| {
+ let was = *ctx;
+ let before = WATCHDOG_RESUMED.with(|r| r.get());
+ !title_watchdog_resume(ctx) && ctx_differs(ctx, &was).is_empty() && WATCHDOG_RESUMED.with(|r| r.get()) == before
+ };
+ let ret = image.put(0x100, &WATCHDOG_1) + 0x42;
+ // every slot the watchdog's return address: frames of 0, 0x48 and 0x80 alike
+ let stack = Box::new([ret; 32]);
+ let rsp = stack.as_ptr() as usize;
+ // the 0x4d8bd421 hook's store with another epilogue
+ let store = &HOOK_4D8BD421[0x63..0x6E];
+ let with_epilogue = |at: usize, epilogue: &[u8]| {
+ let s = image.put(at, store);
+ image.put(at + 11, epilogue);
+ s
+ };
+ let real = with_epilogue(0x180, &[0x48, 0x83, 0xC4, 0x48, 0xC3]);
+ assert!(title_watchdog_resume(&mut watchdog_ctx(real, rsp)), "its own epilogue");
+ let others: [[u8; 5]; 6] = [
+ [0x48, 0x83, 0xC4, 0x48, 0xCC], // add rsp, 0x48 – no ret
+ [0x48, 0x83, 0xC4, 0x80, 0xC3], // add rsp, -0x80
+ [0x48, 0x83, 0xC5, 0x48, 0xC3], // add rbp, 0x48
+ [0x48, 0x83, 0xEC, 0x48, 0xC3], // sub rsp, 0x48
+ [0xCC, 0xC3, 0x00, 0x00, 0x00], // int3
+ [0x5B, 0xC3, 0x00, 0x00, 0x00], // pop rbx; ret
+ ];
+ for (k, e) in others.iter().enumerate() {
+ let s = with_epilogue(0x200 + 0x20 * k, e);
+ assert!(refused(&mut watchdog_ctx(s, rsp)), "epilogue {e:02x?}");
+ }
+ // the 0x4d8bd421 hook with its frame past the address space
+ assert!(refused(&mut watchdog_ctx(real, usize::MAX - 0x20)), "its frame past the address space");
+ // a leaf hook whose return address is …
+ let leaf = image.put(0x300, &LEAF_HOOKS[2]);
+ let at_ret = |r: usize| {
+ let st = Box::new([r; 4]);
+ refused(&mut watchdog_ctx(leaf, st.as_ptr() as usize))
+ };
+ assert!(!at_ret(ret), "the watchdog's: resumed");
+ // … right after `call rcx`, not `call rax`
+ let mut call_rcx = WATCHDOG_1.to_vec();
+ call_rcx[0x41] = 0xD1;
+ assert!(at_ret(image.put(0x400, &call_rcx) + 0x42), "after call rcx");
+ // … right after `call rax`, not on the watchdog's store: `mov dword ptr [0], 1`, `ret`
+ let mut store_1 = WATCHDOG_1.to_vec();
+ store_1[0x42 + 7] = 1;
+ assert!(at_ret(image.put(0x480, &store_1) + 0x42), "on mov dword ptr [0], 1");
+ let mut ret_after = WATCHDOG_1.to_vec();
+ ret_after[0x42] = 0xC3;
+ assert!(at_ret(image.put(0x500, &ret_after) + 0x42), "on ret");
+ // … in another image, in none
+ assert!(at_ret(other.put(0x100, &WATCHDOG_1) + 0x42), "in another image");
+ let free = VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize;
+ let reserved = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE, PAGE_READWRITE) as usize;
+ assert!(free != 0 && reserved != 0);
+ std::ptr::copy_nonoverlapping(WATCHDOG_1.as_ptr(), free as *mut u8, WATCHDOG_1.len());
+ assert!(at_ret(free + 0x42), "in no image");
+ // … and a hook in no image either, its return address the watchdog's call there
+ std::ptr::copy_nonoverlapping(LEAF_HOOKS[2].as_ptr(), (free + 0x200) as *mut u8, 16);
+ let st = Box::new([free + 0x42; 4]);
+ assert!(refused(&mut watchdog_ctx(free + 0x200, st.as_ptr() as usize)), "a hook in no image");
+ // … not readable, null
+ assert!(at_ret(reserved + 0x42), "not readable");
+ assert!(at_ret(0) && at_ret(1), "null");
+ // the stack slot not readable
+ assert!(refused(&mut watchdog_ctx(leaf, reserved + 0x100)), "a stack not readable");
+ // the second loop's store with another byte before or after it (offsets from the copy's
+ // start; the store at +0x49)
+ let v2 = image.put(0x600, &WATCHDOG_2) + 0x49;
+ let mut ctx = watchdog_ctx(v2, rsp);
+ let mut want = ctx;
+ want.Rip = (v2 - 0x49) as u64;
+ assert!(title_watchdog_resume(&mut ctx) && ctx_differs(&ctx, &want).is_empty(), "the second loop's own bytes: resumed at its heartbeat check, nothing else changed");
+ for (k, (i, b)) in [(0x0C, 0xEB), (0x08, 0x1F), (0x00, 0x48), (0x48, 0xD1), (0x54, 0x33), (0x56, 0xC3)].into_iter().enumerate() {
+ let mut w = WATCHDOG_2.to_vec();
+ assert_ne!(w[i], b);
+ w[i] = b;
+ let s = image.put(0x680 + 0x60 * k, &w) + 0x49;
+ assert!(refused(&mut watchdog_ctx(s, rsp)), "the second loop with {b:#04x} at +{i:#x}");
+ }
+ // the first loop's store with another byte at each place its rule looks at (offsets from
+ // the copy's start = its heartbeat check; the store at +0x42): `mov r15, [rip+..]` (+0x00),
+ // `mov r14, rsi; mov ebp, 0x1e` (+0x07, 8 bytes), `mov r14, rsi; mov ebx, ebp` (+0x19, 5),
+ // the store's imm32 and the `int3` after it (+0x49, 5) – a `nop` there (+0x4d) refused by
+ // the loop rules themselves; a `ret` there makes the store a leaf hook's bytes, refused by
+ // the hook branch before the loop rules are reached: on a stack with no watchdog return
+ // in it
+ let plain = Box::new([0usize; 32]);
+ let prsp = plain.as_ptr() as usize;
+ let v1 = image.put(0x900, &WATCHDOG_1) + 0x42;
+ let mut ctx = watchdog_ctx(v1, prsp);
+ let mut want = ctx;
+ (want.Rip, want.Rsi) = ((v1 - 0x42) as u64, want.R14);
+ assert!(title_watchdog_resume(&mut ctx) && ctx_differs(&ctx, &want).is_empty(), "the first loop's own bytes: resumed at its heartbeat check with rsi = r14, nothing else changed");
+ for (k, (i, b)) in [(0x00, 0x48), (0x0A, 0xB8), (0x0B, 0x1F), (0x1C, 0x8B), (0x49, 0x01), (0x4D, 0x90), (0x4D, 0xC3)].into_iter().enumerate() {
+ let mut w = WATCHDOG_1.to_vec();
+ assert_ne!(w[i], b);
+ w[i] = b;
+ let s = image.put(0x980 + 0x60 * k, &w) + 0x42;
+ assert!(refused(&mut watchdog_ctx(s, prsp)), "the first loop with {b:#04x} at +{i:#x}");
+ }
+ VirtualFree(free as *mut _, 0, MEM_RELEASE);
+ VirtualFree(reserved as *mut _, 0, MEM_RELEASE);
+ }
+ }
+
+ /// The line each of the three resumes writes (a report hook's, the first loop's, the second's)
+ /// waits for a log file another thread is writing, a few ms at most (`log::try_write_soon`):
+ /// with the file held until this thread tries again, the line is written once it is let go –
+ /// whole, with its number (`#n`, below 4 or a power of two: shared with the other tests'
+ /// threads, so resumes are made until one's line is due); held past those few ms, the line is
+ /// given up – within 100 ms – and the resume is the same. (The test process has no log file:
+ /// what is looked at is the line given to the write itself, `put`, its text, and how often it
+ /// tried.)
+ #[test]
+ fn title_watchdog_lines_wait_a_few_ms_for_a_busy_log() {
+ use std::time::{Duration, Instant};
+ unsafe {
+ let image = TestImage::new("watchdog_log.exe");
+ let first = image.put(0x100, &WATCHDOG_1);
+ let second = image.put(0x200, &WATCHDOG_2);
+ let leaf = image.put(0x400, &LEAF_HOOKS[0]);
+ // the leaf hook's return address: the first loop's call
+ let stack = Box::new([first + 0x42; 4]);
+ let rsp = stack.as_ptr() as usize;
+ let tid = windows_sys::Win32::System::Threading::GetCurrentThreadId();
+ // (the first `readable` of the process sets up the unified-memory windows and logs that,
+ // waiting for the file: done before it is held – in the title long before any fire)
+ let _ = crate::gpu::uma::get();
+ // (kind, where its store is, what it resumes at, its line before and after its number)
+ let cases = [
+ (0, leaf, leaf + 11, "the title's stall watchdog called its report hook (#", format!("): hook 0x2ef1e94b at {leaf:#x} (image+0x400); resuming at the hook's epilogue, which returns into the watchdog's own store")),
+ (1, first + 0x42, first, "the title's stall watchdog fired (#", "); resuming at the recognized heartbeat check".to_string()),
+ (2, second + 0x49, second, "the title's stall watchdog fired in its second loop (#", "); resuming at the recognized heartbeat check".to_string()),
+ ];
+ for (k, store, resumed, head, tail) in &cases {
+ for past in [false, true] {
+ // (a moment: up to 5 tries – a thread put off by the system for 5 ms between
+ // seeing this one try and letting go makes one fail)
+ let mut tried = Vec::new();
+ for _attempt in 0..5 {
+ let (held_tx, held_rx) = std::sync::mpsc::channel::<()>();
+ let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
+ let holder = std::thread::spawn(move || {
+ let file = crate::log::soon_test::hold_file();
+ held_tx.send(()).unwrap();
+ let t = Instant::now();
+ let saw = if past {
+ // held until the resume came back
+ done_rx.recv_timeout(Duration::from_secs(5)).is_ok()
+ } else {
+ // let go as soon as this test's thread tries again
+ loop {
+ if crate::log::soon_test::waiting(tid) {
+ break true;
+ }
+ if t.elapsed() > Duration::from_secs(5) {
+ break false;
+ }
+ std::hint::spin_loop();
+ }
+ };
+ drop(file);
+ saw
+ });
+ held_rx.recv().unwrap();
+ let _ = crate::log::soon_test::take_seen();
+ // resumes of this kind – each with its context as the rule leaves it – until
+ // one's line is due: (not given up, how long that resume took)
+ let mut due = None;
+ for _ in 0..4096 {
+ let mut ctx = watchdog_ctx(*store, rsp);
+ let mut want = ctx;
+ want.Rip = *resumed as u64;
+ if *k == 1 {
+ want.Rsi = want.R14;
+ }
+ let said = WATCHDOG_SAID.with(|s| s.get())[*k];
+ let t = Instant::now();
+ assert!(title_watchdog_resume(&mut ctx), "kind {k}");
+ let took = t.elapsed();
+ assert_eq!(ctx_differs(&ctx, &want), Vec::::new(), "kind {k}: resumed as ever");
+ let now = WATCHDOG_SAID.with(|s| s.get())[*k];
+ if now[0] > said[0] {
+ due = Some((now[1] - said[1], took));
+ break;
+ }
+ }
+ let _ = done_tx.send(());
+ let saw = holder.join().unwrap();
+ let (said, took) = due.expect("a line due within 4096 resumes");
+ let seen = crate::log::soon_test::take_seen();
+ if past {
+ assert!(saw, "kind {k}: the file held until the resume came back");
+ assert_eq!((said, seen.as_ref().map(|s| &s.0)), (0, None), "kind {k}: held past the few ms, the line is given up");
+ // (about 5 ms and a yield: 100 ms leaves room for a loaded machine)
+ assert!(took >= Duration::from_millis(4) && took < Duration::from_millis(100), "kind {k}: given up after a few ms ({took:?})");
+ tried.push(true);
+ break;
+ }
+ let ok = saw && said == 1 && seen.as_ref().is_some_and(|(line, tries)| {
+ let n = line.strip_prefix(head).and_then(|l| l.strip_suffix(tail.as_str())).and_then(|n| n.parse::().ok());
+ assert!(n.is_some_and(|n| n < 4 || n.is_power_of_two()), "kind {k}: the line whole, a number due: {line}");
+ *tries > 0
+ });
+ tried.push(ok);
+ if ok {
+ break;
+ }
+ eprintln!("kind {k}: the line not written after the file was let go (holder saw the try: {saw}, written: {said}, seen: {seen:?}, {took:?}) – again");
+ }
+ assert!(tried.last() == Some(&true), "kind {k} (held past the few ms: {past}): {tried:?}");
+ }
+ }
+ }
+ }
+
+ /// What `xcl_watchdog_e2e_run` is given and what the stubs record (its offsets: the assembly's).
+ #[repr(C)]
+ #[derive(Clone, Copy, Debug, Default)]
+ struct Drive {
+ /// the copy's `call rax` the driver jumps to, and the hook (rax there)
+ call: u64,
+ hook: u64,
+ /// rbx, rbp, rsi, rdi, r12, r13, r14, r15 at that call (r14: the QPC pointer's stand-in)
+ set: [u64; 8],
+ /// xmm6 at that call
+ xmm6: [u64; 2],
+ /// the driver's rsp at its jump: the record's address at [rsp] and [rsp + 8] there
+ rsp: u64,
+ /// 1 or 2: the first or the second loop's stub ran; 0xdead: `e2e_safety_net` ended the run
+ reached: u64,
+ /// at the stub: rbx, rbp, rsi, rdi, r12, r13, r14, r15, rsp
+ got: [u64; 9],
+ got_xmm6: [u64; 2],
+ /// (`e2e_safety_net`) the exception's code, address, first two parameters, rip and rsp
+ fault: [u64; 6],
+ }
+ const _: () = assert!(
+ std::mem::offset_of!(Drive, set) == 0x10
+ && std::mem::offset_of!(Drive, xmm6) == 0x50
+ && std::mem::offset_of!(Drive, rsp) == 0x60
+ && std::mem::offset_of!(Drive, reached) == 0x68
+ && std::mem::offset_of!(Drive, got) == 0x70
+ && std::mem::offset_of!(Drive, got_xmm6) == 0xB8
+ );
+
+ // The driver: saves the registers the Windows x64 ABI has a callee keep (rbx, rbp, rsi, rdi,
+ // r12-r15, xmm6 – the resumed loops write rbp, rsi, r14 and r15), leaves the record's address
+ // twice on its stack with rsp 16-byte aligned as a `call` wants it, sets the registers from
+ // the record and jumps to the copy's `call rax`. The stubs the copies' loops jump to after the
+ // resumes record the registers (rax: the record, from the stack) and – also where
+ // `e2e_safety_net` ends a run – restore the saved ones and return to the test.
+ std::arch::global_asm!(
+ r#"
+ .globl xcl_watchdog_e2e_run
+ xcl_watchdog_e2e_run:
+ push rbx
+ push rbp
+ push rsi
+ push rdi
+ push r12
+ push r13
+ push r14
+ push r15
+ sub rsp, 0x18
+ movdqu xmmword ptr [rsp], xmm6
+ push rcx
+ push rcx
+ mov qword ptr [rcx + 0x60], rsp
+ movdqu xmm6, xmmword ptr [rcx + 0x50]
+ mov rbx, qword ptr [rcx + 0x10]
+ mov rbp, qword ptr [rcx + 0x18]
+ mov rsi, qword ptr [rcx + 0x20]
+ mov rdi, qword ptr [rcx + 0x28]
+ mov r12, qword ptr [rcx + 0x30]
+ mov r13, qword ptr [rcx + 0x38]
+ mov r14, qword ptr [rcx + 0x40]
+ mov r15, qword ptr [rcx + 0x48]
+ mov rax, qword ptr [rcx + 0x08]
+ jmp qword ptr [rcx]
+
+ .globl xcl_watchdog_e2e_stub1
+ xcl_watchdog_e2e_stub1:
+ xchg rax, qword ptr [rsp]
+ mov qword ptr [rax + 0x68], 1
+ jmp 2f
+
+ .globl xcl_watchdog_e2e_stub2
+ xcl_watchdog_e2e_stub2:
+ xchg rax, qword ptr [rsp]
+ mov qword ptr [rax + 0x68], 2
+ 2:
+ mov qword ptr [rax + 0x70], rbx
+ mov qword ptr [rax + 0x78], rbp
+ mov qword ptr [rax + 0x80], rsi
+ mov qword ptr [rax + 0x88], rdi
+ mov qword ptr [rax + 0x90], r12
+ mov qword ptr [rax + 0x98], r13
+ mov qword ptr [rax + 0xA0], r14
+ mov qword ptr [rax + 0xA8], r15
+ mov qword ptr [rax + 0xB0], rsp
+ movdqu xmmword ptr [rax + 0xB8], xmm6
+
+ .globl xcl_watchdog_e2e_restore
+ xcl_watchdog_e2e_restore:
+ add rsp, 0x10
+ movdqu xmm6, xmmword ptr [rsp]
+ add rsp, 0x18
+ pop r15
+ pop r14
+ pop r13
+ pop r12
+ pop rdi
+ pop rsi
+ pop rbp
+ pop rbx
+ ret
+ "#
+ );
+
+ extern "win64" {
+ /// Runs `drive`: back here from one of the stubs (or `e2e_safety_net`).
+ fn xcl_watchdog_e2e_run(drive: *mut Drive);
+ fn xcl_watchdog_e2e_stub1();
+ fn xcl_watchdog_e2e_stub2();
+ fn xcl_watchdog_e2e_restore();
+ }
+
+ /// The run in progress (`title_watchdog_resumes_real_faults_through_the_exception_handler`): its
+ /// record (0: none), its thread, the image its code is in.
+ static DRIVE: AtomicUsize = AtomicUsize::new(0);
+ static DRIVE_TID: AtomicU32 = AtomicU32::new(0);
+ static DRIVE_IMAGE: AtomicUsize = AtomicUsize::new(0);
+
+ /// The last vectored handler while the real faults run: an exception of the run's thread in the
+ /// run's image that no handler before it resumed (`null_call_logger` should have) ends that run
+ /// – the exception noted in its record, the driver's caller returned to with its stack and
+ /// registers – instead of the whole test process.
+ unsafe extern "system" fn e2e_safety_net(info: *mut EXCEPTION_POINTERS) -> i32 {
+ let d = DRIVE.load(Ordering::Acquire) as *mut Drive;
+ if d.is_null()
+ || info.is_null()
+ || (*info).ExceptionRecord.is_null()
+ || (*info).ContextRecord.is_null()
+ || windows_sys::Win32::System::Threading::GetCurrentThreadId() != DRIVE_TID.load(Ordering::Acquire)
+ {
+ return 0;
+ }
+ let (rec, ctx) = (&*(*info).ExceptionRecord, &mut *(*info).ContextRecord);
+ let base = DRIVE_IMAGE.load(Ordering::Acquire);
+ if !(base..base + 0x2000).contains(&(ctx.Rip as usize)) {
+ return 0;
+ }
+ (*d).fault = [rec.ExceptionCode as u32 as u64, rec.ExceptionAddress as u64, rec.ExceptionInformation[0] as u64, rec.ExceptionInformation[1] as u64, ctx.Rip, ctx.Rsp];
+ (*d).reached = 0xDEAD;
+ ctx.Rsp = (*d).rsp;
+ ctx.Rip = xcl_watchdog_e2e_restore as usize as u64;
+ -1 // EXCEPTION_CONTINUE_EXECUTION
+ }
+
+ /// A vectored handler, removed when the guard drops (also when an assertion unwinds).
+ struct Veh(*mut c_void);
+
+ impl Drop for Veh {
+ fn drop(&mut self) {
+ unsafe { windows_sys::Win32::System::Diagnostics::Debug::RemoveVectoredExceptionHandler(self.0) };
+ }
+ }
+
+ /// The resumes on real access violations, through the handler the title's process has
+ /// (`null_call_logger`, registered first for the test's length as `install_crash_handler`
+ /// registers it): in one image, a leaf hook (`mov dword ptr [0], 0x2ef1e94b; ret`) and a hook
+ /// with a frame (`sub rsp, 0x48; mov dword ptr [0], 0x4d8bd421; add rsp, 0x48; ret`), each
+ /// entered through either loop's shape and its `call rax` – each with the disp32 of its `mov
+ /// r15, [rip+..]` (a qword in the image: the heartbeat's stand-in) and the rel32 of its `jmp`
+ /// (a stub's: the loop's top) filled in – with r14 the QPC pointer's
+ /// stand-in and rsi apart from it. The hook's store faults and is resumed at its epilogue,
+ /// which returns into the watchdog's store; that faults and is resumed at the loop's heartbeat
+ /// check, which runs on to the stub: the first loop with r14 = the QPC pointer (the rsi = r14 a
+ /// resume there gives it), rsi = rsp + 0x28 (its `lea`), the second with r14 and rsi as they
+ /// were; both with ebp = 30 and r15 = the heartbeat as their loops set them, rbx, rdi, r12,
+ /// r13, xmm6 and rsp as at the call, and both resumes counted on this thread (the handler runs
+ /// on the faulting one). Under Wine and Rosetta 2 as the title would. No fault is raised that
+ /// the rule would not resume (each context is put to it first), and one the handler does not
+ /// resume ends its run through `e2e_safety_net`, not the process.
+ #[test]
+ fn title_watchdog_resumes_real_faults_through_the_exception_handler() {
+ use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, FlushInstructionCache};
+ use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetCurrentThreadId};
+ unsafe {
+ let image = TestImage::new("watchdog_faults.exe");
+ // (int3 where nothing is put: a wrong jump traps in the image, where the safety net is)
+ std::ptr::write_bytes(image.base as *mut u8, 0xCC, 0x2000);
+ let leaf = image.put(0x000, &LEAF_HOOKS[0]);
+ let mut framed = vec![0x48, 0x83, 0xEC, 0x48];
+ framed.extend_from_slice(&HOOK_4D8BD421[0x63..0x74]);
+ let framed = image.put(0x040, &framed);
+ const HEARTBEAT: u64 = 0x7A1E_E2E0_0000_00B7;
+ let heartbeat = image.put(0x400, &HEARTBEAT.to_le_bytes());
+ let trampoline = |at: usize, to: usize| {
+ let mut t = vec![0xFF, 0x25, 0, 0, 0, 0]; // jmp [rip + 0]
+ t.extend_from_slice(&(to as u64).to_le_bytes());
+ image.put(at, &t)
+ };
+ let stubs = [trampoline(0x300, xcl_watchdog_e2e_stub1 as usize), trampoline(0x320, xcl_watchdog_e2e_stub2 as usize)];
+ let rel32 = |end: usize, to: usize| i32::try_from(to as i64 - end as i64).unwrap().to_le_bytes();
+ // the shapes with the two fields the rule does not look at filled in (it checks the
+ // opcodes before them: `4c 8b 3d`, the first loop nothing of its `jmp`, the second its
+ // `e9`)
+ let (one, two) = (image.base + 0x100, image.base + 0x200);
+ let mut w1 = WATCHDOG_1.to_vec();
+ assert_eq!((&w1[..3], w1[0x14]), (&[0x4C, 0x8B, 0x3D][..], 0xE9), "the first loop: mov r15, [rip+disp32] at +0, jmp rel32 at +0x14");
+ w1[3..7].copy_from_slice(&rel32(one + 7, heartbeat));
+ w1[0x15..0x19].copy_from_slice(&rel32(one + 0x19, stubs[0]));
+ image.put(0x100, &w1);
+ let mut w2 = WATCHDOG_2.to_vec();
+ assert_eq!((&w2[..3], w2[0x0C]), (&[0x4C, 0x8B, 0x3D][..], 0xE9), "the second loop: mov r15, [rip+disp32] at +0, jmp rel32 at +0xc");
+ w2[3..7].copy_from_slice(&rel32(two + 7, heartbeat));
+ w2[0x0D..0x11].copy_from_slice(&rel32(two + 0x11, stubs[1]));
+ image.put(0x200, &w2);
+ assert!(FlushInstructionCache(GetCurrentProcess(), image.base as *const c_void, 0x2000) != 0);
+ // (what, the hook's entry, its store, its frame)
+ let hooks = [("the leaf hook 0x2ef1e94b", leaf, leaf, 0usize), ("the hook 0x4d8bd421 with a frame of 0x48", framed, framed + 4, 0x48usize)];
+ // (the loop, its copy, its `call rax`, its store)
+ let loops = [(1usize, one, one + 0x40, one + 0x42), (2, two, two + 0x47, two + 0x49)];
+ // the rule on the contexts the faults will have first: no fault it would not resume
+ for &(k, copy, _, store) in &loops {
+ for &(what, _, hook_store, frame) in &hooks {
+ let mut st = Box::new([0usize; 32]);
+ st[frame / 8] = store;
+ let mut ctx = watchdog_ctx(hook_store, st.as_ptr() as usize);
+ assert!(title_watchdog_resume(&mut ctx) && ctx.Rip as usize == hook_store + 11, "{what} via loop {k}: the rule resumes its store");
+ let mut ctx = watchdog_ctx(store, st.as_ptr() as usize);
+ assert!(title_watchdog_resume(&mut ctx) && ctx.Rip as usize == copy, "{what} via loop {k}: the rule resumes the loop's store");
+ }
+ }
+ let resume = AddVectoredExceptionHandler(1, Some(null_call_logger));
+ if resume.is_null() {
+ eprintln!("SKIPPED: AddVectoredExceptionHandler(1, null_call_logger) failed (error {})", windows_sys::Win32::Foundation::GetLastError());
+ return;
+ }
+ let resume = Veh(resume);
+ let net = AddVectoredExceptionHandler(0, Some(e2e_safety_net));
+ if net.is_null() {
+ eprintln!("SKIPPED: AddVectoredExceptionHandler(0, the safety net) failed (error {})", windows_sys::Win32::Foundation::GetLastError());
+ return;
+ }
+ let net = Veh(net);
+ DRIVE_IMAGE.store(image.base, Ordering::Release);
+ DRIVE_TID.store(GetCurrentThreadId(), Ordering::Release);
+ let runs = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ const QPC: u64 = 0x7A1E_E2E0_0000_0014;
+ // rbx, rbp, rsi, rdi, r12, r13, r14 (the QPC pointer), r15
+ let set = [0xB0B0_B0B0_B0B0_B0B0, 0xBBBB_0000_BBBB_0000, 0x5151_5151_5151_5151, 0xD1D1_D1D1_D1D1_D1D1, 0x1212_1212_1212_1212, 0x1313_1313_1313_1313, QPC, 0xF15F_15F1_5F15_F15F];
+ for &(k, _, call, _) in &loops {
+ for &(what, entry, _, _) in &hooks {
+ let mut d = Drive { call: call as u64, hook: entry as u64, set, xmm6: [0x0123_4567_89AB_CDEF, 0xFEDC_BA98_7654_3210], ..Default::default() };
+ let before = WATCHDOG_RESUMED.with(|r| r.get());
+ eprintln!("E2E: {what} via loop {k}: its store and the loop's fault now");
+ DRIVE.store(&mut d as *mut Drive as usize, Ordering::Release);
+ xcl_watchdog_e2e_run(&mut d);
+ DRIVE.store(0, Ordering::Release);
+ let after = WATCHDOG_RESUMED.with(|r| r.get());
+ let [rbx, rbp, rsi, rdi, r12, r13, r14, r15, rsp] = d.got;
+ eprintln!(
+ "E2E: {what} via loop {k}: back through stub {:#x} – rsp {rsp:#x} (at the call {:#x}), rbp {rbp}, r15 {r15:#x}, r14 {r14:#x}, rsi {rsi:#x}, rbx {rbx:#x}, rdi {rdi:#x}, r12 {r12:#x}, r13 {r13:#x}, xmm6 {:x?}; resumed here: hooks +{}, loop 1 +{}, loop 2 +{}; safety net: {:x?}",
+ d.reached, d.rsp, d.got_xmm6, after[0] - before[0], after[1] - before[1], after[2] - before[2], d.fault
+ );
+ assert_eq!(d.reached, k as u64, "{what} via loop {k}: back through the loop's stub, not the safety net (exception code, address, parameters, rip, rsp: {:x?})", d.fault);
+ assert_eq!(rsp, d.rsp, "{what} via loop {k}: the stack as at the call");
+ assert_eq!((rbx, rdi, r12, r13), (set[0], set[3], set[4], set[5]), "{what} via loop {k}: rbx, rdi, r12, r13 as at the call");
+ assert_eq!((rbp, r15), (30, HEARTBEAT), "{what} via loop {k}: ebp = 30 and r15 = the heartbeat, as the loop sets them");
+ if k == 1 {
+ assert_eq!((r14, rsi), (QPC, rsp + 0x28), "{what} via loop 1: r14 the QPC pointer (rsi = r14 at the resume), rsi its lea");
+ } else {
+ assert_eq!((r14, rsi), (QPC, set[2]), "{what} via loop 2: r14 and rsi as at the call");
+ }
+ assert_eq!(d.got_xmm6, d.xmm6, "{what} via loop {k}: xmm6 as at the call");
+ assert_eq!((after[0], after[k], after[3 - k]), (before[0] + 1, before[k] + 1, before[3 - k]), "{what} via loop {k}: the two resumes, on this thread");
+ }
+ }
+ }));
+ DRIVE.store(0, Ordering::Release);
+ drop(net);
+ drop(resume);
+ DRIVE_TID.store(0, Ordering::Release);
+ if let Err(e) = runs {
+ std::panic::resume_unwind(e);
+ }
}
}
diff --git a/crates/xcl/src/gpu/fence.rs b/crates/xcl/src/gpu/fence.rs
index 4d70280..b50fd92 100644
--- a/crates/xcl/src/gpu/fence.rs
+++ b/crates/xcl/src/gpu/fence.rs
@@ -73,6 +73,7 @@ pub(crate) unsafe fn wait(
}
let start = Instant::now();
let mut remaining = timeout_ms;
+ let _held = crate::waitwatch::xcl(crate::waitwatch::X_GPU_FENCE, target);
loop {
let status = WaitForSingleObject(event, remaining);
let error = (status == WAIT_FAILED).then(Error::from_thread);
diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs
index 859fbf3..03d5da4 100644
--- a/crates/xcl/src/gpu/recomp/dxc.rs
+++ b/crates/xcl/src/gpu/recomp/dxc.rs
@@ -828,7 +828,10 @@ fn process_cache_lock(file: &Path) -> Result {
if handle.is_null() {
return Err("DXIL cache: cannot create the cross-process mutex".into());
}
- let wait = unsafe { WaitForSingleObject(handle, INFINITE) };
+ let wait = {
+ let _held = crate::waitwatch::xcl(crate::waitwatch::X_DXC_MUTEX, 0);
+ unsafe { WaitForSingleObject(handle, INFINITE) }
+ };
if wait != WAIT_OBJECT_0 && wait != WAIT_ABANDONED {
unsafe { CloseHandle(handle) };
return Err(format!("DXIL cache: waiting for the cross-process mutex failed ({wait:#x})"));
diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs
index 8ea0f96..f646cb3 100644
--- a/crates/xcl/src/gpu/recomp/emit.rs
+++ b/crates/xcl/src/gpu/recomp/emit.rs
@@ -64,6 +64,9 @@ pub(super) struct Em {
/// LDS arrival barrier (`xcl_s_barrier`) so RDNA2 early `s_endpgm`, `LOOP_GUARD` exits,
/// or split-wave64 desyncs cannot permanently hang an NVIDIA SM at `bar.sync`.
safe_barrier: bool,
+ /// a multi-wave Compute/Mesh program whose `s_barrier` stays a group barrier that waits
+ /// for every wave (`XCL_SAFE_BARRIER=0`): no dispatch-wide budget trip (`trip`)
+ real_group_barriers: bool,
}
/// Instructions without an effect in this execution model.
@@ -490,6 +493,7 @@ impl Em {
has_f64_round_op: false,
dynamic_f16_rm: false,
safe_barrier: false,
+ real_group_barriers: false,
}
}
@@ -551,6 +555,19 @@ impl Em {
self.safe_barrier = has_s_barrier
&& self.compute_or_mesh_hw_waves().is_some_and(|w| w > 1)
&& std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0");
+ self.real_group_barriers = has_s_barrier && self.compute_or_mesh_hw_waves().is_some_and(|w| w > 1) && !self.safe_barrier;
+ }
+
+ /// The dispatch-wide trip on the loop budget (`PRELUDE_TRIP`, `TRIP_AT_START`,
+ /// `LOOP_GUARD_TRIP`): a compute program counts its waves whose `xcl_budget` ran out, and
+ /// once a dispatch has `budget_trip_waves` of them its waves that start later skip their
+ /// loops. A lane's budget bounds one wave; a dispatch of thousands of groups whose loops
+ /// all run to it can keep a GPU busy for minutes. Not where a group barrier waits for every
+ /// wave – split wave64 halves meeting at barriers (`XCL_WAVE64_SPIN=0`), group barriers
+ /// without the safe form (`XCL_SAFE_BARRIER=0`): a wave that skipped its loops and one that
+ /// did not would wait there for each other. Off with `XCL_BUDGET_TRIP_WAVES=0`.
+ pub(super) fn trip(&self) -> bool {
+ matches!(self.opt.mode, Mode::Compute(_)) && budget_trip_waves() != 0 && !(self.x64() && !self.x64_spin()) && !self.real_group_barriers
}
pub fn take(&mut self) -> String {
@@ -4405,6 +4422,11 @@ impl Em {
}
}
self.safe_barrier_prelude(&mut h);
+ // (a program without loops has nothing to trip: no atomic for each of its waves)
+ let trip = self.trip() && body.contains("xcl_budget_spent()");
+ if trip {
+ h.push_str(PRELUDE_TRIP);
+ }
let _ = writeln!(
h,
"[WaveSize({hw_lanes})]\n[numthreads({x}, {y}, {z})]\nvoid main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID, uint gi : SV_GroupIndex)\n{{"
@@ -4452,6 +4474,9 @@ impl Em {
};
let _ = writeln!(h, " uint v{v} = {init};");
}
+ if trip {
+ h.push_str(TRIP_AT_START);
+ }
h.push_str(body);
if self.safe_barrier {
h.push_str(" xcl_s_barrier_exit();\n");
@@ -5558,6 +5583,49 @@ void xcl_s_barrier() {
}
"#;
+/// Waves of a dispatch of a compute program whose own loop budget (`xcl_budget`) may run out
+/// before its waves that start later skip their loops (`Em::trip`): `XCL_BUDGET_TRIP_WAVES`,
+/// 64 by default; 0: no trip (the HLSL as before). Counted in hardware waves; XCL writes it
+/// into each dispatch's `res` block (word 2), so it is not part of the translation.
+pub fn budget_trip_waves() -> u32 {
+ static N: std::sync::OnceLock = std::sync::OnceLock::new();
+ *N.get_or_init(|| std::env::var("XCL_BUDGET_TRIP_WAVES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64))
+}
+
+/// The dispatch-wide budget (`Em::trip`): `res` word 0 counts the waves whose budget ran out –
+/// an add from the first lane of the lanes that find it spent together at a guard
+/// (`LOOP_GUARD_TRIP`): one a wave when its lanes loop alike, more when lanes that left earlier
+/// loops apart run out at different guards; word 2 is how many may (XCL writes it, and a
+/// serial of the dispatch into word 1: the window uploads leave a chunk alone whose bytes are
+/// as they were, so a count the GPU left at that address would otherwise carry over to a later
+/// dispatch). Only in programs with loops.
+pub(super) const PRELUDE_TRIP: &str = r#"
+static bool xcl_spent = false;
+void xcl_budget_spent() {
+ if (!xcl_spent) {
+ xcl_spent = true;
+ if (WaveIsFirstLane()) { uint o; res.InterlockedAdd(0u, 1u, o); }
+ }
+}
+"#;
+
+/// At the start of `main` (`Em::trip`): a wave that starts once its dispatch has its count of
+/// spent waves skips its loops – each leaves at its first guard, as a spent one does. A wave
+/// decides as a whole (its first lane reads the count, one atomic); the halves of a split
+/// console wave may decide apart – their exchanges then time out once (`xcl_x_meet`,
+/// bounded) and the wave goes on with its own half's values.
+pub(super) const TRIP_AT_START: &str = " {
+ uint xcl_trip = 0u;
+ if (WaveIsFirstLane()) {
+ uint n = 0u;
+ uint w = res.Load(8u);
+ res.InterlockedAdd(0u, 0u, n);
+ xcl_trip = (w != 0u && n >= w) ? 1u : 0u;
+ }
+ if (WaveReadLaneFirst(xcl_trip) != 0u) { xcl_budget = 0u; xcl_spent = true; }
+ }
+";
+
const PRELUDE: &str = r#"
static uint lane_id;
// loop iterations a lane may run (`LOOP_GUARD`): far above what a working program needs
diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs
index 7a6641b..eababec 100644
--- a/crates/xcl/src/gpu/recomp/mod.rs
+++ b/crates/xcl/src/gpu/recomp/mod.rs
@@ -590,6 +590,20 @@ type MemoKey = (u64, u64, Option, usize, Option, Vec);
/// leaves at its next iteration and the program runs to its end.
const LOOP_GUARD: &str = "if (xcl_budget == 0u) break; xcl_budget--;";
+/// `LOOP_GUARD` of a compute program with the dispatch-wide trip (`emit::Em::trip`): a wave
+/// whose budget is spent counts once for its dispatch (`xcl_budget_spent`), then leaves as
+/// before.
+const LOOP_GUARD_TRIP: &str = "if (xcl_budget == 0u) { xcl_budget_spent(); break; } xcl_budget--;";
+
+/// The loop guard `em`'s program gets.
+fn loop_guard(em: &emit::Em) -> &'static str {
+ if em.trip() {
+ LOOP_GUARD_TRIP
+ } else {
+ LOOP_GUARD
+ }
+}
+
/// The loops the translator emits: ranges spanned by backward jumps (far jumps included),
/// partly overlapping ones merged until they nest, sorted. `x64_masks` uses them for the
/// exits through `LOOP_GUARD`.
@@ -942,7 +956,7 @@ fn emit_structured(
}
let raised: BTreeSet = match it {
Item::Loop { a, b, latch, entry } => {
- body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {LOOP_GUARD}\n"));
+ body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {}\n", loop_guard(em)));
let (lcont, lin) = if entry.is_none() { (Some(a), &inner) } else { (None, &none) };
let mut r = emit_structured(c, em, body, entry.unwrap_or(a), latch, None, nest + 1, lcont, lin, d + 1, blocks, flags);
for &t in &r {
@@ -1047,7 +1061,7 @@ fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, d
let start = c.leaders[i];
let inner = c.loops.iter().filter(|&&(a, b)| a == start && b <= hi && (a, b) != (lo, hi)).max_by_key(|x| x.1).copied();
if let Some((a, b)) = inner {
- body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {LOOP_GUARD}\n"));
+ body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {}\n", loop_guard(em)));
emit_range(c, em, body, a, b, depth + 1, blocks, flags);
body.push_str(&format!("{pad}}}\n"));
i = c.leaders.partition_point(|&l| l < b);
diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs
index b256390..b80bebb 100644
--- a/crates/xcl/src/gpu/recomp/pso.rs
+++ b/crates/xcl/src/gpu/recomp/pso.rs
@@ -106,6 +106,82 @@ pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_w
console_to_dxil_in(blob, stage, sampler_base, split_wave64, mem_windows())
}
+/// The bytes of DXIL the translation cache holds for `blob` – the file `console_to_dxil_for`
+/// loads with these parameters and the title's memory windows – from its header (the DXIL is not
+/// read). None when there is none: not translated yet, the cache off or bypassed by a debug
+/// switch. A size found is kept for the run (a program's clones).
+pub fn translated_dxil_len(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool) -> Option {
+ if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) {
+ return None;
+ }
+ static SIZES: OnceLock>> = OnceLock::new();
+ let sizes = SIZES.get_or_init(Default::default);
+ let windows = mem_windows();
+ let k = (crate::gpu::shader::fnv64(blob), blob.len(), stage, sampler_base, windows, split_wave64);
+ if let Some(&n) = sizes.lock().unwrap().get(&k) {
+ return Some(n as usize);
+ }
+ let n = translated::dxil_len(&dxc::cache_dir(), translated::identity(), blob, stage, sampler_base, windows, split_wave64)?;
+ sizes.lock().unwrap().insert(k, n.min(u32::MAX as usize) as u32);
+ Some(n)
+}
+
+/// The static samplers of the translation the cache holds for a program known by its hash only
+/// (`fnv64` of its bytes) – the file `console_to_dxil_for` loads with these parameters and the
+/// title's memory windows –, None: none. Only the header's magic and identity are checked (the
+/// bytes are not at hand) and that the file is whole: what orders a pipeline in the workers' queue
+/// (`pso_async::tier_of`), never what one is built from. A translation found, and every one this
+/// run's builds stored or loaded (`translated::cached_in`), is kept for the run; none found is not:
+/// the next look reads the disk again, so a translation a build stores meanwhile is found (a pixel
+/// shader has tens of pipelines, and the first one's build translates it for all).
+pub fn translated_by_hash(hash: u64, stage: Stage, sampler_base: u32, split_wave64: bool) -> Option {
+ let (dir, allowed) = translation_lookup();
+ let at = match stage {
+ Stage::Vertex => 0,
+ Stage::Pixel => 1,
+ Stage::Compute => 2,
+ };
+ if !allowed[at] {
+ return None;
+ }
+ translated_by_hash_in(dir, translated::identity(), hash, stage, sampler_base, mem_windows(), split_wave64)
+}
+
+/// Where `translated_by_hash` looks – the cache folder – and for which stages (vertex, pixel, compute)
+/// the cache may be used (`cache_allowed`'s debug switches), read once: `host_main` asks first, before
+/// the title runs, so that no title call (a pipeline's first bind, `pso_async::tier_of`) reads the
+/// environment for it; they do not change while a title runs.
+pub fn translation_lookup() -> &'static (PathBuf, [bool; 3]) {
+ static WHERE: OnceLock<(PathBuf, [bool; 3])> = OnceLock::new();
+ WHERE.get_or_init(|| {
+ let present = |name: &str| std::env::var_os(name).is_some();
+ (dxc::cache_dir(), [Stage::Vertex, Stage::Pixel, Stage::Compute].map(|s| cache_allowed(s, present)))
+ })
+}
+
+/// `translated_by_hash` in the cache folder `dir` of the translator identity `ident` (0: the cache
+/// off – none) with `windows` memory windows.
+pub fn translated_by_hash_in(dir: &Path, ident: u64, hash: u64, stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Option {
+ translated::samplers_by_hash(dir, ident, hash, stage, sampler_base, windows, split_wave64)
+}
+
+/// (tests) `blob`'s translation `compiled` through the translation cache in `dir` (`ident`), as a
+/// build's: stored when not there, else loaded – what `translated_by_hash_in` then finds.
+#[cfg(test)]
+pub(crate) fn translate_for_test(dir: &Path, ident: u64, blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split: bool, compiled: Compiled) -> Compiled {
+ translated::cached_in(dir, ident, blob, stage, sampler_base, windows, split, || Ok(compiled)).unwrap()
+}
+
+/// This build's translator identity – the translation cache's folder (`XCL_TRANSLATED_IDENT`'s
+/// when set), also with the cache off (this binary's own then): what every translation's DXIL
+/// depends on (the built-pipelines ledger's name).
+pub fn translator_identity() -> u64 {
+ match translated::identity() {
+ 0 => translated::identity_for(env!("XCL_TRANSLATOR_SOURCE_ID"), dxc::toolchain_identity()),
+ n => n,
+ }
+}
+
/// `console_to_dxil_for` with the title's memory windows given (`xcl shaders --precompile`
/// fills the caches without a title: the same keys as at its run).
pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result {
@@ -148,11 +224,74 @@ pub fn console_to_dxil_shared(blob: &[u8], stage: Stage, sampler_base: u32, spli
/// `XCL_TRANSLATED_CACHE=0` turns it off; `XCL_TRANSLATED_IDENT=` stands for the hash.
mod translated {
use super::{Compiled, Stage};
+ use std::collections::HashMap;
use std::path::{Path, PathBuf};
- use std::sync::OnceLock;
+ use std::sync::{Mutex, OnceLock, PoisonError};
const MAGIC: &[u8; 8] = b"XCLTRAN2";
+ /// A translation this run found by its program's hash, stored or loaded: its folder (a hash of
+ /// its path), identity, program's hash, stage and parameters – `FOUND`'s key.
+ #[derive(Clone, Copy, PartialEq, Eq, Hash)]
+ struct Found {
+ dir: u64,
+ ident: u64,
+ hash: u64,
+ stage: Stage,
+ sampler_base: u32,
+ windows: u32,
+ split: bool,
+ }
+
+ /// The static samplers of each translation in `Found`: kept for the run (a translation is never
+ /// taken off the disk while a title runs), only those that exist (`samplers_by_hash`).
+ static FOUND: Mutex>> = Mutex::new(None);
+
+ fn found_key(dir: &Path, ident: u64, hash: u64, stage: Stage, sampler_base: u32, windows: u32, split: bool) -> Found {
+ Found { dir: crate::gpu::shader::fnv64(dir.as_os_str().as_encoded_bytes()), ident, hash, stage, sampler_base, windows, split }
+ }
+
+ fn note_found(k: Found, samplers: usize) {
+ FOUND.lock().unwrap_or_else(PoisonError::into_inner).get_or_insert_with(HashMap::new).insert(k, samplers.min(u32::MAX as usize) as u32);
+ }
+
+ /// The static samplers of the translation of the program whose `fnv64` is `hash` in `dir` for
+ /// `ident` (`file_by_hash`), None: none – kept for the run once found (`FOUND`); a look that
+ /// finds none reads the disk again the next time.
+ pub(super) fn samplers_by_hash(dir: &Path, ident: u64, hash: u64, stage: Stage, sampler_base: u32, windows: u32, split: bool) -> Option {
+ if ident == 0 || hash == 0 {
+ return None;
+ }
+ let k = found_key(dir, ident, hash, stage, sampler_base, windows, split);
+ if let Some(&n) = FOUND.lock().unwrap_or_else(PoisonError::into_inner).as_ref().and_then(|m| m.get(&k)) {
+ return Some(n);
+ }
+ let n = samplers_on_disk(&file_by_hash(dir, ident, hash, stage, sampler_base, windows, split), ident)?;
+ note_found(k, n as usize);
+ Some(n)
+ }
+
+ /// The static samplers of the translation at `path` for `ident`, from its header – its magic
+ /// and identity only: the program's bytes are not at hand for the rest – and the file whole, as
+ /// `dxil_len` checks it. None: missing, cut, or another identity's.
+ pub(super) fn samplers_on_disk(path: &Path, ident: u64) -> Option {
+ use std::io::{Read, Seek, SeekFrom};
+ let mut f = std::fs::File::open(path).ok()?;
+ let mut head = [0u8; 36];
+ f.read_exact(&mut head).ok()?;
+ if head[..8] != MAGIC[..] || head[8..16] != ident.to_le_bytes() {
+ return None;
+ }
+ let n = u32::from_le_bytes(head[32..36].try_into().unwrap());
+ // then 4 words and a byte a static sampler, the DXIL's length and the DXIL
+ let at = 36 + 17 * n as u64;
+ f.seek(SeekFrom::Start(at)).ok()?;
+ let mut l = [0u8; 4];
+ f.read_exact(&mut l).ok()?;
+ let len = u32::from_le_bytes(l) as u64;
+ (len > 0 && f.metadata().ok()?.len() == at + 4 + len).then_some(n)
+ }
+
pub(super) fn identity_for(source: &str, toolchain: &str) -> u64 {
let mut h = 0xcbf2_9ce4_8422_2325u64;
for part in ["xcl-translated-cache-v2", source, toolchain] {
@@ -166,7 +305,7 @@ mod translated {
/// Translation semantics and the DXC DLLs, independent of link metadata and build profile.
/// Zero means the disk cache is disabled.
- fn identity() -> u64 {
+ pub(super) fn identity() -> u64 {
static I: OnceLock = OnceLock::new();
*I.get_or_init(|| {
if std::env::var("XCL_TRANSLATED_CACHE").is_ok_and(|v| v == "0") {
@@ -189,10 +328,15 @@ mod translated {
}
pub(super) fn file(dir: &Path, ident: u64, blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split: bool) -> PathBuf {
+ file_by_hash(dir, ident, crate::gpu::shader::fnv64(blob), stage, sampler_base, windows, split)
+ }
+
+ /// `file` of the program whose `fnv64` is `hash`
+ pub(super) fn file_by_hash(dir: &Path, ident: u64, hash: u64, stage: Stage, sampler_base: u32, windows: u32, split: bool) -> PathBuf {
dir.join("translated")
.join("v2")
.join(format!("{ident:016x}"))
- .join(format!("{:016x}_{stage:?}_{sampler_base}_{windows}_{}.bin", crate::gpu::shader::fnv64(blob), split as u8))
+ .join(format!("{hash:016x}_{stage:?}_{sampler_base}_{windows}_{}.bin", split as u8))
}
fn header(ident: u64, blob: &[u8]) -> Vec {
@@ -203,6 +347,29 @@ mod translated {
h
}
+ /// The DXIL length of the translation `file` names, from its header – what `load_in` would
+ /// give, without reading the DXIL: None when the file is missing, cut, or not `blob`'s
+ /// translation for `ident` (magic, identity, length and second hash of the bytes).
+ pub(super) fn dxil_len(dir: &Path, ident: u64, blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split: bool) -> Option {
+ use std::io::{Read, Seek, SeekFrom};
+ if ident == 0 {
+ return None;
+ }
+ let mut f = std::fs::File::open(file(dir, ident, blob, stage, sampler_base, windows, split)).ok()?;
+ let mut head = [0u8; 36];
+ f.read_exact(&mut head).ok()?;
+ if head[..32] != header(ident, blob)[..] {
+ return None;
+ }
+ // then 4 words and a byte a static sampler, the DXIL's length and the DXIL
+ let at = 36 + 17 * u32::from_le_bytes(head[32..36].try_into().unwrap()) as u64;
+ f.seek(SeekFrom::Start(at)).ok()?;
+ let mut l = [0u8; 4];
+ f.read_exact(&mut l).ok()?;
+ let len = u32::from_le_bytes(l) as u64;
+ (len > 0 && f.metadata().ok()?.len() == at + 4 + len).then_some(len as usize)
+ }
+
pub(super) fn load_in(path: &Path, ident: u64, blob: &[u8]) -> Option {
let b = std::fs::read(path).ok()?;
let head = header(ident, blob);
@@ -224,7 +391,8 @@ mod translated {
(r.len() == len && len > 0).then(|| Compiled { dxil: r.to_vec(), samplers })
}
- pub(super) fn store_in(path: &Path, ident: u64, blob: &[u8], c: &Compiled) {
+ /// `c` as `blob`'s translation at `path`; whether it is there now.
+ pub(super) fn store_in(path: &Path, ident: u64, blob: &[u8], c: &Compiled) -> bool {
let mut b = header(ident, blob);
b.extend_from_slice(&(c.samplers.len() as u32).to_le_bytes());
for (s, cmp) in &c.samplers {
@@ -233,12 +401,17 @@ mod translated {
}
b.extend_from_slice(&(c.dxil.len() as u32).to_le_bytes());
b.extend_from_slice(&c.dxil);
- let Some(dir) = path.parent() else { return };
+ let Some(dir) = path.parent() else { return false };
let tmp = dir.join(format!("{}.{}.{:?}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id(), std::thread::current().id()));
// written whole, then renamed: a reader never sees half a file
- if std::fs::create_dir_all(dir).is_ok() && std::fs::write(&tmp, &b).is_ok() && std::fs::rename(&tmp, path).is_err() {
+ if std::fs::create_dir_all(dir).is_err() || std::fs::write(&tmp, &b).is_err() {
+ return false;
+ }
+ if std::fs::rename(&tmp, path).is_err() {
let _ = std::fs::remove_file(&tmp);
+ return false;
}
+ true
}
pub(super) fn cached_in(
@@ -254,13 +427,19 @@ mod translated {
if ident == 0 {
return translate();
}
- let path = file(dir, ident, blob, stage, sampler_base, windows, split);
+ let hash = crate::gpu::shader::fnv64(blob);
+ let path = file_by_hash(dir, ident, hash, stage, sampler_base, windows, split);
+ // (each one there from now on is what `samplers_by_hash` finds: a pipeline sent after
+ // this one with the same shader goes where those that need no DXC go – `pso_async`)
if let Some(c) = load_in(&path, ident, blob) {
super::dxc::note_memory_hit();
+ note_found(found_key(dir, ident, hash, stage, sampler_base, windows, split), c.samplers.len());
return Ok(c);
}
let c = translate()?;
- store_in(&path, ident, blob, &c);
+ if store_in(&path, ident, blob, &c) {
+ note_found(found_key(dir, ident, hash, stage, sampler_base, windows, split), c.samplers.len());
+ }
Ok(c)
}
@@ -523,7 +702,14 @@ fn cached_shader(
}
fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool {
- !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN"]
+ cache_allowed_with(stage, present, super::emit::budget_trip_waves())
+}
+
+/// `cache_allowed` with the dispatch-wide budget's threshold `trip_waves`: it is read at run
+/// time, so only turning it off – 0 – changes a compute program's HLSL.
+fn cache_allowed_with(stage: Stage, present: impl Fn(&str) -> bool, trip_waves: u32) -> bool {
+ !(stage == Stage::Compute && present("XCL_BUDGET_TRIP_WAVES") && trip_waves == 0)
+ && !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN"]
.iter()
.any(|name| present(name))
&& (stage != Stage::Pixel
@@ -541,13 +727,23 @@ fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool {
/// s0…s3 are the driver's, so what is above 4 is the root arguments its compiler passed in
/// registers. None: not a console compute shader.
pub fn compute_user_sgprs(blob: &[u8]) -> Option {
+ compute_interface(blob).map(|cs| cs.user_sgprs)
+}
+
+/// The thread group of a console compute shader (its numthreads). None: not a console
+/// compute shader.
+pub fn compute_threads(blob: &[u8]) -> Option<[u32; 3]> {
+ compute_interface(blob).map(|cs| cs.threads)
+}
+
+fn compute_interface(blob: &[u8]) -> Option {
if let Some(f) = fspx(blob) {
- return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2).user_sgprs);
+ return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2));
}
let sh = xbox::parse(blob)?;
let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?;
match interface(blob, &sh, f)? {
- Mode::Compute(cs) => Some(cs.user_sgprs),
+ Mode::Compute(cs) => Some(cs),
_ => None,
}
}
@@ -817,6 +1013,46 @@ mod shader_cache_tests {
let _ = std::fs::remove_dir_all(&dir);
}
+ /// The DXIL's length comes from a translation's header – what `load_in` would give – for the
+ /// same bytes and identity and a whole file only.
+ #[test]
+ fn the_dxil_size_comes_from_a_translations_header() {
+ let dir = std::env::temp_dir().join(format!("xcl-dxil-len-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let c = Compiled { dxil: vec![1, 2, 3, 4, 5], samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)] };
+ let back = translated::cached_in(&dir, 42, b"console", Stage::Compute, 0, 4, true, || Ok(c.clone())).unwrap();
+ assert_eq!(back.dxil, c.dxil);
+ let len = |ident: u64| translated::dxil_len(&dir, ident, b"console", Stage::Compute, 0, 4, true);
+ assert_eq!(len(42), Some(5));
+ let path = translated::file(&dir, 42, b"console", Stage::Compute, 0, 4, true);
+ let good = std::fs::read(&path).unwrap();
+ translated::store_in(&path, 43, b"console", &c);
+ assert_eq!(len(42), None, "another identity in the header");
+ translated::store_in(&path, 42, b"consolf", &c);
+ assert_eq!(len(42), None, "other bytes of the same length");
+ std::fs::write(&path, &good[..good.len() - 1]).unwrap();
+ assert_eq!(len(42), None, "a cut file");
+ std::fs::write(&path, &good).unwrap();
+ assert_eq!(len(42), Some(5), "the whole file again");
+ assert_eq!(len(44), None, "no file");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// The ledger's identity is the translation cache's folder – also a developer's
+ /// `XCL_TRANSLATED_IDENT` one (run it with that set: an identity that recomputes the binary's
+ /// passes only without it) – and the folder's formula is today's (a change of it would
+ /// translate every program again: an hour of a retail game's start).
+ #[test]
+ fn the_translator_identity_is_the_translation_caches_folder() {
+ if std::env::var_os("XCL_TRANSLATED_CACHE").is_some() {
+ return crate::gpu::recomp::runner::skip_config("XCL_TRANSLATED_CACHE is set");
+ }
+ if std::env::var_os("XCL_TRANSLATED_IDENT").is_none() {
+ assert_eq!(translated::identity(), translated::identity_for(env!("XCL_TRANSLATOR_SOURCE_ID"), dxc::toolchain_identity()));
+ }
+ assert_eq!(translator_identity(), translated::identity());
+ }
+
#[test]
fn translated_v2_ignores_valid_entries_outside_its_namespace() {
let dir = std::env::temp_dir().join(format!("xcl-translated-legacy-{}", std::process::id()));
@@ -845,6 +1081,84 @@ mod shader_cache_tests {
let _ = std::fs::remove_dir_all(&dir);
}
+ /// A translation is found by its program's hash alone – the file `console_to_dxil_for` loads,
+ /// its static samplers from the header – for that hash, stage, sampler base, windows, split and
+ /// identity only, whole, and never for hash 0 or the cache off (identity 0). (PP2's P5; a folder
+ /// of its own: the user's cache is never written.)
+ #[test]
+ fn a_translation_is_found_by_its_programs_hash() {
+ let dir = std::env::temp_dir().join(format!("xcl-by-hash-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let blob = b"a console pixel shader";
+ let h = crate::gpu::shader::fnv64(blob);
+ let c = Compiled { dxil: vec![9; 40], samplers: vec![([1, 2, 3, 4], false), ([5, 6, 7, 8], true)] };
+ let path = translated::file(&dir, 42, blob, Stage::Pixel, 0, 4, true);
+ assert_eq!(path, translated::file_by_hash(&dir, 42, h, Stage::Pixel, 0, 4, true), "the file of its hash");
+ assert!(translated::store_in(&path, 42, blob, &c));
+ let by = |hash: u64, stage: Stage, base: u32, windows: u32, split: bool, ident: u64| translated_by_hash_in(&dir, ident, hash, stage, base, windows, split);
+ assert_eq!(by(h, Stage::Pixel, 0, 4, true, 42), Some(2), "its two static samplers");
+ assert_eq!(by(h, Stage::Pixel, 1, 4, true, 42), None, "another sampler base");
+ assert_eq!(by(h, Stage::Vertex, 0, 4, true, 42), None, "another stage");
+ assert_eq!(by(h, Stage::Pixel, 0, 1, true, 42), None, "other windows");
+ assert_eq!(by(h, Stage::Pixel, 0, 4, false, 42), None, "the other split");
+ assert_eq!(by(h ^ 1, Stage::Pixel, 0, 4, true, 42), None, "another program");
+ assert_eq!(by(0, Stage::Pixel, 0, 4, true, 42), None, "no program");
+ assert_eq!(by(h, Stage::Pixel, 0, 4, true, 0), None, "the cache off");
+ // the header: its magic and identity, the file whole
+ assert_eq!(translated::samplers_on_disk(&path, 42), Some(2));
+ assert_eq!(translated::samplers_on_disk(&path, 43), None, "another identity");
+ let good = std::fs::read(&path).unwrap();
+ std::fs::write(&path, &good[..good.len() - 1]).unwrap();
+ assert_eq!(translated::samplers_on_disk(&path, 42), None, "a cut file");
+ let mut bad = good.clone();
+ bad[0] ^= 1;
+ std::fs::write(&path, &bad).unwrap();
+ assert_eq!(translated::samplers_on_disk(&path, 42), None, "not a translation");
+ assert_eq!(translated::samplers_on_disk(&dir.join("none.bin"), 42), None, "no file");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// A translation a build stores after a look found none is found by the next look – on disk,
+ /// and told by the store itself (its file taken away before the look: still found) –; one a
+ /// build loads is told the same way; what was found is kept for the run: a "none" never outlives
+ /// a store, and nothing not found is kept (PP2's A2).
+ #[test]
+ fn a_translation_stored_after_a_look_found_none_is_found_by_the_next() {
+ let dir = std::env::temp_dir().join(format!("xcl-by-hash-a2-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let (vs, ps, cs) = (b"a console vertex shader".as_slice(), b"a console pixel shader".as_slice(), b"a console compute shader".as_slice());
+ let fnv = crate::gpu::shader::fnv64;
+ let by = |blob: &[u8], stage: Stage| translated_by_hash_in(&dir, 42, fnv(blob), stage, 0, 4, true);
+ assert_eq!(by(vs, Stage::Vertex), None, "not translated yet");
+ assert_eq!(by(ps, Stage::Pixel), None, "not translated yet");
+ // a build translates them: stored
+ let c = Compiled { dxil: vec![3; 24], samplers: vec![([1, 1, 1, 1], false); 3] };
+ let mut translated = 0;
+ for (blob, stage) in [(vs, Stage::Vertex), (ps, Stage::Pixel)] {
+ let back = translated::cached_in(&dir, 42, blob, stage, 0, 4, true, || {
+ translated += 1;
+ Ok(c.clone())
+ })
+ .unwrap();
+ assert_eq!(back.dxil.len(), 24);
+ }
+ assert_eq!(translated, 2);
+ assert_eq!(by(vs, Stage::Vertex), Some(3), "stored since: found");
+ // (the PS's file gone before any look: what the store told)
+ std::fs::remove_file(translated::file(&dir, 42, ps, Stage::Pixel, 0, 4, true)).unwrap();
+ assert_eq!(by(ps, Stage::Pixel), Some(3), "the store told it");
+ // one an earlier run stored, loaded by a build: told by the load (its file gone before any look)
+ let path = translated::file(&dir, 42, cs, Stage::Compute, 0, 4, true);
+ assert!(translated::store_in(&path, 42, cs, &compiled(5)));
+ let loaded = translated::cached_in(&dir, 42, cs, Stage::Compute, 0, 4, true, || panic!("on disk: loaded")).unwrap();
+ assert_eq!(loaded.dxil[0], 5);
+ std::fs::remove_file(&path).unwrap();
+ assert_eq!(by(cs, Stage::Compute), Some(compiled(5).samplers.len() as u32), "the load told it");
+ let _ = std::fs::remove_dir_all(&dir);
+ assert_eq!(by(vs, Stage::Vertex), Some(3), "kept for the run");
+ assert_eq!(translated_by_hash_in(&dir, 42, fnv(cs), Stage::Compute, 0, 4, false), None, "the other split: never stored, none kept");
+ }
+
fn key(hash: u64) -> ShaderKey {
ShaderKey {
hash,
@@ -1043,6 +1357,14 @@ mod shader_cache_tests {
assert!(cache_allowed(Stage::Compute, |v| v == name));
}
assert!(cache_allowed(Stage::Pixel, |_| false));
+ // the dispatch-wide budget's threshold is read at run time: only 0 (no trip) changes a
+ // compute program's HLSL, and never a vertex or pixel program's
+ let set = |v: &str| v == "XCL_BUDGET_TRIP_WAVES";
+ for waves in [0u32, 64, 128] {
+ assert!(cache_allowed_with(Stage::Vertex, set, waves) && cache_allowed_with(Stage::Pixel, set, waves));
+ assert_eq!(cache_allowed_with(Stage::Compute, set, waves), waves != 0, "{waves}");
+ assert!(cache_allowed_with(Stage::Compute, |_| false, waves));
+ }
}
#[test]
diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs
index 76e080e..c3f4c9c 100644
--- a/crates/xcl/src/gpu/recomp/runner.rs
+++ b/crates/xcl/src/gpu/recomp/runner.rs
@@ -441,6 +441,15 @@ pub fn skip_test(reason: &str) {
let _ = writeln!(std::io::stderr(), "SKIPPED {test}: {reason}");
}
+/// A test (or a part of one) this host's configuration leaves out – not a GPU it lacks:
+/// `SKIPPED : ` written to stderr itself as `skip_test` does (libtest captures
+/// `eprintln!`), without its `XCL_REQUIRE_GPU` failure.
+pub fn skip_config(reason: &str) {
+ use std::io::Write;
+ let thread = std::thread::current();
+ let _ = writeln!(std::io::stderr(), "SKIPPED {}: {reason}", thread.name().unwrap_or("?"));
+}
+
/// Run a compiled kernel (DXIL) with `state` and flat memory `mem`.
pub fn run(dxil: &[u8], state: &KernelState, mem: &[u32]) -> Result {
run_with(dxil, state, mem, &[], &[])
diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs
index 48ea3dc..50401e1 100644
--- a/crates/xcl/src/gpu/recomp/tests.rs
+++ b/crates/xcl/src/gpu/recomp/tests.rs
@@ -7631,3 +7631,196 @@ fn fspx_containers_translate_and_compile() {
println!("FSPX: {ok} / {n} translated and compiled");
assert_eq!(ok, n);
}
+
+/// The dispatch-wide budget trip (`emit::Em::trip`) is in compute programs only: one check at
+/// the start of `main`, the counting guard in each of the program's loops (none of the plain
+/// guard), in the native and the split wave64 forms; a kernel's loops keep the plain guard.
+/// Where DXC is there, the compute forms compile.
+#[test]
+fn budget_trip_is_in_compute_loops_only() {
+ if super::emit::budget_trip_waves() == 0 {
+ println!("XCL_BUDGET_TRIP_WAVES=0 – nothing to check");
+ return;
+ }
+ // two loops: s0 counts down to 0, then s1 does
+ let code = prog(&[
+ ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 133)], None),
+ ("S_SUB_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None),
+ ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None),
+ ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None), // back to s_sub
+ ("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 133)], None),
+ ("S_SUB_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None),
+ ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 128)], None),
+ ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None), // back to the second s_sub
+ ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)], None),
+ ]);
+ let cs = super::CsInterface { threads: [64, 1, 1], user_sgprs: 2, ..Default::default() };
+ for (wave64, split) in [(false, false), (true, false), (true, true)] {
+ let t = translate(&code, &Options { mode: Mode::Compute(cs.clone()), wave64, split_wave64: split, ..Default::default() }).unwrap();
+ assert!(t.complete(), "{:?}", t.unsupported);
+ let h = &t.hlsl;
+ assert_eq!(h.matches(super::LOOP_GUARD_TRIP).count(), 2, "wave64 {wave64} split {split}:\n{h}");
+ assert_eq!(h.matches(super::LOOP_GUARD).count(), 0, "wave64 {wave64} split {split}:\n{h}");
+ assert_eq!(h.matches("void xcl_budget_spent()").count(), 1, "{h}");
+ assert_eq!(h.matches("if (WaveReadLaneFirst(xcl_trip) != 0u) { xcl_budget = 0u; xcl_spent = true; }").count(), 1, "{h}");
+ // the check comes before the program's first loop
+ assert!(h.find("xcl_trip").unwrap() < h.find("[loop] for (;;)").unwrap(), "{h}");
+ if super::dxc::location().is_ok() {
+ super::dxc::compile(h, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("wave64 {wave64} split {split}: {e}\n{h}"));
+ }
+ }
+ let t = translate(&code, &Options::default()).unwrap();
+ assert_eq!(t.hlsl.matches(super::LOOP_GUARD).count(), 2, "{}", t.hlsl);
+ assert!(!t.hlsl.contains("xcl_budget_spent") && !t.hlsl.contains("xcl_trip"), "{}", t.hlsl);
+ // a compute program without loops has nothing to trip: no atomic for each of its waves
+ let flat = prog(&[
+ ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 133)], None),
+ ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)], None),
+ ]);
+ let t = translate(&flat, &Options { mode: Mode::Compute(cs.clone()), ..Default::default() }).unwrap();
+ assert!(!t.hlsl.contains("xcl_budget_spent") && !t.hlsl.contains("xcl_trip"), "{}", t.hlsl);
+}
+
+/// The trip on the GPU, with the translator's own pieces (`PRELUDE_TRIP`, `TRIP_AT_START`,
+/// `LOOP_GUARD_TRIP`) around a loop that never ends by itself: 16384 groups of 64 threads; once
+/// 64 waves have spent their budget, the groups that start later skip their loop (those the GPU
+/// holds already run theirs – some hundreds on an M5 Pro, more on bigger GPUs). Without the trip
+/// (word 2 = 0) 1024 groups all run theirs to the budget. Bounded either way: each loop stops at
+/// its own budget (2^16 iterations) – 16384 x 64 x 2^16 trivial iterations at worst, a few
+/// seconds.
+#[test]
+fn budget_trip_stops_a_runaway_dispatch_on_the_gpu() {
+ use windows::core::Interface;
+ use windows::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0};
+ use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
+ use windows::Win32::Graphics::Direct3D12::*;
+ use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
+
+ let hlsl = format!(
+ "RWByteAddressBuffer res : register(u1);\nRWByteAddressBuffer outb : register(u2);\nstatic uint xcl_budget = 1u << 16;\n{}\n[numthreads(64, 1, 1)]\nvoid main(uint3 gid : SV_GroupID, uint gi : SV_GroupIndex)\n{{\n{} uint n = 0u;\n [loop] for (;;) {{\n {}\n n++;\n if (outb.Load(12u) == 0xC0FFEEu) break;\n }}\n if (gi == 0u) {{ uint o; outb.InterlockedAdd(n == 0u ? 0u : 4u, 1u, o); }}\n}}\n",
+ super::emit::PRELUDE_TRIP,
+ super::emit::TRIP_AT_START,
+ super::LOOP_GUARD_TRIP
+ );
+ let dxil = match super::dxc::location() {
+ Ok(_) => super::dxc::compile(&hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{hlsl}")),
+ Err(e) => {
+ runner::skip_test("no DXC");
+ println!("no DXC ({e}) – skipping");
+ return;
+ }
+ };
+ unsafe {
+ let mut dev: Option = None;
+ if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() {
+ runner::skip_test("no GPU");
+ return;
+ }
+ let dev = dev.unwrap();
+ let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap();
+ let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
+ let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap();
+ let buffer = |bytes: u64, heap, state, flags| -> ID3D12Resource {
+ let desc = D3D12_RESOURCE_DESC {
+ Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1,
+ SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+ Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default()
+ };
+ let mut out = None;
+ dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out).unwrap();
+ out.unwrap()
+ };
+ let uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
+ let transition = |r: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES| {
+ let b = 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::ManuallyDrop::new(Some(r.clone())),
+ Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
+ StateBefore: before,
+ StateAfter: after,
+ }) },
+ ..Default::default()
+ };
+ list.ResourceBarrier(std::slice::from_ref(&b));
+ let mut t = std::mem::ManuallyDrop::into_inner(b.Anonymous.Transition);
+ std::mem::ManuallyDrop::drop(&mut t.pResource);
+ };
+ // res blocks: [count, serial, waves] – the trip at 64 waves, then none (0)
+ let upload = buffer(1024, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_FLAG_NONE);
+ let mut mapped: *mut std::ffi::c_void = std::ptr::null_mut();
+ upload.Map(0, None, Some(&mut mapped)).unwrap();
+ std::ptr::write_bytes(mapped.cast::(), 0, 1024);
+ let w = mapped.cast::();
+ *w.add(1) = 1;
+ *w.add(2) = 64;
+ *w.add(64 + 1) = 2;
+ upload.Unmap(0, None);
+ let res: Vec = (0..2).map(|_| buffer(256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, uav)).collect();
+ let outs: Vec = (0..2).map(|_| buffer(256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, uav)).collect();
+ let readback = buffer(512, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE);
+ for k in 0..2 {
+ list.CopyBufferRegion(&res[k], 0, &upload, 256 * k as u64, 256);
+ list.CopyBufferRegion(&outs[k], 0, &upload, 512, 256);
+ transition(&res[k], D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ transition(&outs[k], D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ }
+ let descriptor = |reg| D3D12_ROOT_PARAMETER {
+ ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV,
+ Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: reg, RegisterSpace: 0 } },
+ ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL,
+ };
+ let params = [descriptor(1), descriptor(2)];
+ let desc = D3D12_ROOT_SIGNATURE_DESC { NumParameters: 2, pParameters: params.as_ptr(), ..Default::default() };
+ let mut blob = None;
+ D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &mut blob, None).unwrap();
+ let blob = blob.unwrap();
+ let root: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer().cast(), blob.GetBufferSize())).unwrap();
+ let mut pdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
+ pRootSignature: std::mem::ManuallyDrop::new(Some(root.clone())),
+ CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() },
+ ..Default::default()
+ };
+ let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&pdesc).unwrap();
+ std::mem::ManuallyDrop::drop(&mut pdesc.pRootSignature);
+ list.SetComputeRootSignature(&root);
+ list.SetPipelineState(&pso);
+ for (k, groups) in [(0usize, 16384u32), (1, 1024)] {
+ list.SetComputeRootUnorderedAccessView(0, res[k].GetGPUVirtualAddress());
+ list.SetComputeRootUnorderedAccessView(1, outs[k].GetGPUVirtualAddress());
+ list.Dispatch(groups, 1, 1);
+ }
+ for k in 0..2 {
+ transition(&outs[k], D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
+ transition(&res[k], D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
+ list.CopyBufferRegion(&readback, 128 * k as u64, &outs[k], 0, 16);
+ list.CopyBufferRegion(&readback, 256 + 128 * k as u64, &res[k], 0, 16);
+ }
+ list.Close().unwrap();
+ let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+ let event = CreateEventW(None, false, false, None).unwrap();
+ let t0 = std::time::Instant::now();
+ queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]);
+ queue.Signal(&fence, 1).unwrap();
+ fence.SetEventOnCompletion(1, event).unwrap();
+ let waited = WaitForSingleObject(event, 60_000);
+ CloseHandle(event).unwrap();
+ assert_eq!(waited, WAIT_OBJECT_0, "the dispatches did not finish in 60 s");
+ let took = t0.elapsed();
+ readback.Map(0, None, Some(&mut mapped)).unwrap();
+ let r = |at: usize| mapped.cast::().add(at).cast::().read();
+ let (skipped, ran, spent) = (r(0), r(4), r(256));
+ let (skipped0, ran0, spent0) = (r(128), r(132), r(384));
+ readback.Unmap(0, None);
+ println!("trip at 64 waves: {ran} groups ran their loop, {skipped} skipped it, {spent} waves spent; without: {ran0} ran, {skipped0} skipped, {spent0} spent; {:.2} s", took.as_secs_f64());
+ assert_eq!(ran + skipped, 16384);
+ // the groups that start after 64 waves spent their budget skip their loop
+ assert!(ran >= 1 && skipped >= 1, "the trip did not happen: {ran} ran, {skipped} skipped");
+ // each wave counts once; a group's two waves decide apart only when they start as the
+ // count reaches 64 (a group whose first wave skipped and whose second ran is counted
+ // as skipped above): a few such groups at most
+ assert!(spent >= 64 && spent <= 2 * ran + 64, "{spent} waves spent for {ran} groups");
+ assert_eq!((ran0, skipped0), (1024, 0));
+ assert!(spent0 == 1024 || spent0 == 2048, "every wave of the dispatch without the trip spends its budget once: {spent0}");
+ }
+}
diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs
index c29522a..b86e534 100644
--- a/crates/xcl/src/gpu/texture.rs
+++ b/crates/xcl/src/gpu/texture.rs
@@ -152,6 +152,11 @@ pub unsafe fn create(dev: &ID3D12Device, queue: &ID3D12CommandQueue, t: &Image,
pub const SHADER_READ: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATES(D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE.0);
fn validate_subresources(subs: &[Subresource]) -> Result<(), String> {
+ validate_subresources_masked(subs, None)
+}
+
+/// `validate_subresources`; one `mask` leaves out (not copied) may have no texels.
+fn validate_subresources_masked(subs: &[Subresource], mask: Option<&[bool]>) -> Result<(), String> {
if subs.is_empty() {
return Err("texture upload without subresources".into());
}
@@ -164,7 +169,8 @@ fn validate_subresources(subs: &[Subresource]) -> Result<(), String> {
.checked_mul(s.rows)
.and_then(|n| n.checked_mul(s.row_bytes))
.ok_or_else(|| format!("texture subresource {i} size overflow"))?;
- if s.data.len() < bytes {
+ let copied = mask.is_none_or(|m| m.get(i).copied().unwrap_or(false));
+ if copied && s.data.len() < bytes {
return Err(format!("texture subresource {i} has {} B, needs {bytes} B", s.data.len()));
}
}
@@ -195,7 +201,10 @@ pub unsafe fn upload(dev: &ID3D12Device, queue: &ID3D12CommandQueue, res: &ID3D1
let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?;
let staging = record_upload(dev, &list, res, subs, before, after)?;
list.Close().map_err(err)?;
- queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).map_err(err)?)]);
+ {
+ let _ops = crate::hle::d3d12x::d3d_ops();
+ queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).map_err(err)?)]);
+ }
let r = wait(dev, queue);
drop(staging);
r
@@ -221,17 +230,90 @@ unsafe impl Send for Uploader {}
/// queue (raw pointer) → its uploader, while no batch uses it
static UPLOADERS: std::sync::Mutex>> = std::sync::Mutex::new(None);
+/// bytes of the upload buffers kept (`Uploader::staging`) and of one made for a texture over the
+/// cap while its upload runs (`OwnStaging`); one left behind by a timed-out upload stays counted –
+/// it is never dropped
+static STAGING_BYTES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+/// The upload buffers' bytes (`XCL_ACTIVITY`).
+pub fn staging_bytes() -> u64 {
+ STAGING_BYTES.load(std::sync::atomic::Ordering::Relaxed)
+}
+
/// the smallest upload buffer made, and the placement alignment of texture data in it
const STAGING_MIN: u64 = 4 << 20;
const PLACEMENT: u64 = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT as u64;
-fn staging_capacity(bytes: u64) -> Option {
- const LARGE: u64 = 64 << 20;
- const STEP: u64 = 16 << 20;
- if bytes <= LARGE {
- Some(bytes.max(STAGING_MIN).next_power_of_two())
- } else {
- bytes.checked_next_multiple_of(STEP)
+/// `XCL_UPLOAD_STAGING_MB`'s default: the kept upload buffer's bytes and one run's at most.
+pub const STAGING_CAP: u64 = 128 << 20;
+
+/// The cap on the kept upload buffer (`Uploader::staging`) and on one run of an upload
+/// (`plan_runs`), and the title textures' batch (`batch_bytes`): `XCL_UPLOAD_STAGING_MB`, read once
+/// (`host_main`, before the title runs). Before 0023.2 the kept buffer only grew, to the next power
+/// of two of the largest batch: 4 → 32 → 128 → 256 MiB in run 66, the last at 92.1 s a block of its
+/// own in D3DMetal's count (+256 MB for the rest of the run, wired while the GPU works). Unset or
+/// not a number: 128 MiB. A number of MiB: that, raised to 16 (with 1 – 15 a texture of a few MiB
+/// would go through a buffer of its own) and 4096 at most. `0`: no cap, as before 0023.2 – one run
+/// a batch, the kept buffer grown to the next power of two, the title textures' batches 256 MiB.
+pub fn staging_cap() -> Option {
+ #[cfg(test)]
+ if let Some(c) = TEST_CAP.with(|c| c.get()) {
+ return c;
+ }
+ static CAP: std::sync::OnceLock> = std::sync::OnceLock::new();
+ *CAP.get_or_init(|| staging_cap_for(std::env::var("XCL_UPLOAD_STAGING_MB").ok().as_deref()))
+}
+
+/// `XCL_UPLOAD_STAGING_MB`'s value → the cap (None: none) – `staging_cap`.
+fn staging_cap_for(v: Option<&str>) -> Option {
+ match v.and_then(|v| v.trim().parse::().ok()) {
+ None => Some(STAGING_CAP),
+ Some(0) => None,
+ Some(mb) => Some(mb.clamp(16, 4096) << 20),
+ }
+}
+
+/// The console bytes of one batch of title-texture uploads at most (`title_textures`): the cap – a
+/// batch's PC staging bytes can be more, and `upload_batch_masked_run` cuts it in runs of at most
+/// the cap; 256 MiB with none, as before 0023.2.
+pub fn batch_bytes() -> usize {
+ batch_bytes_for(staging_cap())
+}
+
+fn batch_bytes_for(cap: Option) -> usize {
+ cap.map_or(256 << 20, |c| c as usize)
+}
+
+#[cfg(test)]
+thread_local! {
+ /// (tests) this thread's uploads' cap instead of `XCL_UPLOAD_STAGING_MB`'s (`Some(None)`: none)
+ static TEST_CAP: std::cell::Cell>> = const { std::cell::Cell::new(None) };
+ /// (tests) the runs of this thread's last upload: (items, staging bytes, a buffer of its own)
+ static TEST_RUNS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) };
+ /// (tests) bytes of this thread's buffers of their own alive (`OwnStaging`): made, and not let
+ /// go yet – `STAGING_BYTES` is the process's, which other tests move
+ static TEST_OWN_LIVE: std::cell::Cell = const { std::cell::Cell::new(0) };
+ /// (tests) what this thread added to and took from `STAGING_BYTES` for kept buffers
+ /// (`Uploader::staging`, its Drop), and the most that sum reached: (now, peak)
+ static TEST_KEPT_LIVE: std::cell::Cell<(i64, i64)> = const { std::cell::Cell::new((0, 0)) };
+}
+
+/// (tests) `TEST_KEPT_LIVE` moved by `bytes`, its peak kept
+#[cfg(test)]
+fn test_kept_moved(bytes: i64) {
+ TEST_KEPT_LIVE.with(|l| {
+ let now = l.get().0 + bytes;
+ l.set((now, l.get().1.max(now)));
+ });
+}
+
+impl Drop for Uploader {
+ fn drop(&mut self) {
+ if let Some((_, _, cap)) = &self.staging {
+ STAGING_BYTES.fetch_sub(*cap, std::sync::atomic::Ordering::Relaxed);
+ #[cfg(test)]
+ test_kept_moved(-(*cap as i64));
+ }
}
}
@@ -244,50 +326,238 @@ impl Uploader {
Ok(Uploader { alloc, list, fence, value: 0, staging: None })
}
- /// An upload buffer of at least `bytes`, mapped: the one kept, or a bigger one.
- unsafe fn staging(&mut self, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, *mut u8), String> {
- if let Some((b, p, cap)) = &self.staging {
- if *cap >= bytes {
+ /// An upload buffer of at least `bytes` (one run's: not over the cap), mapped: the one kept, or
+ /// a bigger one that replaces it – never made above the cap (`kept_capacity`).
+ unsafe fn staging(&mut self, dev: &ID3D12Device, bytes: u64, cap: Option) -> Result<(ID3D12Resource, *mut u8), String> {
+ if let Some((b, p, c)) = &self.staging {
+ if *c >= bytes {
return Ok((b.clone(), *p));
}
}
- let cap = staging_capacity(bytes).ok_or("texture upload buffer size overflow")?;
- // A cached uploader has passed its last copy fence. Return this reference before
- // acquiring the replacement so the growth path does not keep two buffers itself.
- drop(self.staging.take());
+ let cap = kept_capacity(bytes, cap).ok_or("texture upload buffer size overflow")?;
+ // The kept buffer has passed its last copy's fence (each run waits for its own, and an
+ // uploader whose wait failed is forgotten, never kept): let it go before the bigger one is
+ // made, so that growing never holds both (upstream 9db0989).
+ if let Some((_, _, old)) = self.staging.take() {
+ STAGING_BYTES.fetch_sub(old, std::sync::atomic::Ordering::Relaxed);
+ #[cfg(test)]
+ test_kept_moved(-(old as i64));
+ }
let b = buffer(dev, cap)?;
let mut p = std::ptr::null_mut();
b.Map(0, None, Some(&mut p)).map_err(err)?;
+ STAGING_BYTES.fetch_add(cap, std::sync::atomic::Ordering::Relaxed);
+ #[cfg(test)]
+ test_kept_moved(cap as i64);
self.staging = Some((b.clone(), p as *mut u8, cap));
Ok((b, p as *mut u8))
}
}
+/// The kept upload buffer's capacity for a run of `bytes` when the one kept is smaller (or there is
+/// none): 4 MiB or the next power of two of `bytes`, as before 0023.2 – but never above the cap,
+/// which a run on the kept buffer is never over (`plan_runs`; with a cap under 4 MiB, the cap).
+/// None when that power of two is past u64 (upstream 9db0989's overflow check).
+fn kept_capacity(bytes: u64, cap: Option) -> Option {
+ let grown = bytes.max(STAGING_MIN).checked_next_power_of_two()?;
+ Some(cap.map_or(grown, |c| grown.min(c.max(bytes))))
+}
+
+/// An upload buffer of its own for one texture whose staging is over the cap (`Run::own`), the
+/// size of its layout: mapped, counted in `STAGING_BYTES` while it lives, dropped once its run's
+/// copies were waited for – never kept (a texture of more than the cap on the PC would otherwise
+/// grow the kept buffer past it for the rest of the run). Forgotten when that wait fails, as the
+/// uploader is: the GPU may still read it.
+struct OwnStaging {
+ buffer: ID3D12Resource,
+ mapped: *mut u8,
+ bytes: u64,
+}
+
+impl OwnStaging {
+ unsafe fn new(dev: &ID3D12Device, bytes: u64) -> Result {
+ let buffer = buffer(dev, bytes)?;
+ let mut p = std::ptr::null_mut();
+ buffer.Map(0, None, Some(&mut p)).map_err(err)?;
+ STAGING_BYTES.fetch_add(bytes, std::sync::atomic::Ordering::Relaxed);
+ #[cfg(test)]
+ TEST_OWN_LIVE.with(|l| l.set(l.get() + bytes));
+ Ok(OwnStaging { buffer, mapped: p as *mut u8, bytes })
+ }
+}
+
+impl Drop for OwnStaging {
+ fn drop(&mut self) {
+ STAGING_BYTES.fetch_sub(self.bytes, std::sync::atomic::Ordering::Relaxed);
+ #[cfg(test)]
+ TEST_OWN_LIVE.with(|l| l.set(l.get() - self.bytes));
+ }
+}
+
+/// A texture over the cap went through an upload buffer of its own (`OwnStaging`): said the first
+/// 4 times, then at powers of two.
+fn note_own_staging(bytes: u64, cap: Option) {
+ 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 <= 4 || n.is_power_of_two() {
+ crate::xlog_info!("{}", own_staging_line(bytes, cap, n));
+ }
+}
+
+fn own_staging_line(bytes: u64, cap: Option, n: u64) -> String {
+ format!(
+ "title textures: an upload of one texture's {} MB went through an upload buffer of its own, past XCL_UPLOAD_STAGING_MB={}: made for it and let go once its copy ran ({n} so far)",
+ bytes >> 20,
+ cap.unwrap_or(0) >> 20
+ )
+}
+
+/// One submit of an upload: planned items `items` (indices into the upload's planned items, in
+/// order), each from its base (multiples of D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT, from 0), the
+/// staging bytes they take, and whether it goes through a buffer of its own (one texture over the
+/// cap) rather than the kept one.
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct Run {
+ items: std::ops::Range,
+ bases: Vec,
+ bytes: u64,
+ own: bool,
+}
+
+/// The runs an upload whose planned items take `totals` staging bytes goes in: whole items in
+/// order, at most `cap` bytes a run (bases from 0 in each), a texture over the cap alone in a run
+/// of its own buffer; with no cap one run of everything (`XCL_UPLOAD_STAGING_MB=0`, as before
+/// 0023.2). The cut is by the PC's staging bytes, not the console's: they are what the buffer
+/// holds, and a texture's PC layout can be larger than its console bytes. (One texture is not cut
+/// by subresource: its copy transitions the whole resource either way, and a second part would need
+/// footprints of its own – for a case not seen.)
+fn plan_runs(totals: &[u64], cap: Option) -> Vec {
+ let mut runs: Vec = Vec::new();
+ for (i, &t) in totals.iter().enumerate() {
+ if cap.is_some_and(|c| t > c) {
+ runs.push(Run { items: i..i + 1, bases: vec![0], bytes: t, own: true });
+ continue;
+ }
+ if let Some(r) = runs.last_mut().filter(|r| !r.own) {
+ let base = r.bytes.div_ceil(PLACEMENT) * PLACEMENT;
+ if cap.is_none_or(|c| base + t <= c) {
+ r.items.end = i + 1;
+ r.bases.push(base);
+ r.bytes = base + t;
+ continue;
+ }
+ }
+ runs.push(Run { items: i..i + 1, bases: vec![0], bytes: t, own: false });
+ }
+ runs
+}
+
+/// What `run_all` appends to the error of an item of a run that was never submitted.
+const NOT_SUBMITTED: &str = " – this part of the batch was not submitted";
+
+/// Whether a failed item's error (`upload_batch_masked_run`'s Ok list) says its run was never
+/// submitted – none of its copies reached the queue, so an upload at a later submit lands what this
+/// one did not; a layout failure would fail again.
+pub fn never_submitted(e: &str) -> bool {
+ e.ends_with(NOT_SUBMITTED)
+}
+
+/// How one run of an upload failed: before its list was submitted (none of its copies reach the
+/// GPU), or after (a Signal or a wait that failed: its copies land on the queue in its order).
+#[derive(Debug)]
+enum RunError {
+ Before(String),
+ After(String),
+}
+
+/// The runs `runs` of an upload one after the other, each through `run` (recorded, submitted and
+/// waited for, as one batch was before 0023.2), and what the caller is told – `planned` is each
+/// planned item's index in the caller's items, `failed` the items whose layout failed:
+/// - every run ran: Ok(failed);
+/// - run r failed before its submit: the first – Err, nothing was submitted (as before 0023.2); a
+/// later one – Ok(failed ∪ the items of r and of every run after it, with the error): the caller
+/// warns of them and tries lazy ones again, as for an item that failed;
+/// - run r failed after its submit (a Signal or a wait): the last – Err with `executed`, as before
+/// 0023.2 (its copies land on the queue in its order, and the caller takes them as done); one with
+/// runs after it – Ok(failed ∪ the items of every run after r, with the error) and `executed`:
+/// runs up to r land in the queue's order, and the textures of the runs never submitted are not
+/// reported uploaded (a lazy one would be taken to hold texels its tiles do not hold).
+///
+/// `executed`: whether any run was submitted.
+fn run_all(runs: &[Run], planned: &[usize], mut failed: Vec<(usize, String)>, executed: &mut bool, mut run: impl FnMut(&Run) -> Result<(), RunError>) -> Result, String> {
+ let not_submitted = |from: &[Run], e: &str| -> Vec<(usize, String)> {
+ from.iter().flat_map(|r| r.items.clone()).filter_map(|i| planned.get(i)).map(|&k| (k, format!("{e}{NOT_SUBMITTED}"))).collect()
+ };
+ for (k, r) in runs.iter().enumerate() {
+ match run(r) {
+ Ok(()) => *executed = true,
+ Err(RunError::Before(e)) if k == 0 => return Err(e),
+ Err(RunError::Before(e)) => {
+ failed.extend(not_submitted(&runs[k..], &e));
+ return Ok(failed);
+ }
+ Err(RunError::After(e)) => {
+ *executed = true;
+ if k + 1 == runs.len() {
+ return Err(e);
+ }
+ failed.extend(not_submitted(&runs[k + 1..], &e));
+ return Ok(failed);
+ }
+ }
+ }
+ Ok(failed)
+}
+
/// Several uploads on one list, one wait: (resource, subresources, states) each – the states
/// the texture is in and is left in: one for every subresource, or one per subresource (D3D12
/// order). A failure of one is returned with its index; the others still run. The texels go
/// through the queue's kept upload buffer (`Uploader`).
pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> {
+ upload_batch_masked(dev, queue, items, &[])
+}
+
+/// `upload_batch` copying only the subresources `masks[i]` says of item i (None, or no mask for
+/// it: all of them) – a reserved texture with tiles for some of its subresources
+/// (`lazy_tex`). The barriers are the same.
+pub unsafe fn upload_batch_masked(
+ dev: &ID3D12Device,
+ queue: &ID3D12CommandQueue,
+ items: &[(ID3D12Resource, Vec, Vec)],
+ masks: &[Option>],
+) -> Result, String> {
+ upload_batch_masked_run(dev, queue, items, masks, &mut false)
+}
+
+/// `upload_batch_masked`; `executed` says, on an error too, whether copies were submitted (then
+/// they land on `queue` in its order – a wait that timed out, a Signal that failed). The texels go
+/// in runs of at most the cap (`staging_cap`, `plan_runs`), each recorded, submitted and waited for
+/// on its own: the kept buffer is never made above the cap, and a texture over it goes through a
+/// buffer of its own (`OwnStaging`). What a run that failed leaves the caller: `run_all`.
+pub unsafe fn upload_batch_masked_run(
+ dev: &ID3D12Device,
+ queue: &ID3D12CommandQueue,
+ items: &[(ID3D12Resource, Vec, Vec)],
+ masks: &[Option>],
+ executed: &mut bool,
+) -> Result, String> {
+ *executed = false;
if items.is_empty() {
return Ok(Vec::new());
}
let key = windows::core::Interface::as_raw(queue) as usize;
let taken = UPLOADERS.lock().unwrap().as_mut().and_then(|m| m.remove(&key));
- let mut up = match taken {
+ let up = match taken {
Some(u) => u,
None => Uploader::new(dev)?,
};
- // where each texture's texels go in the upload buffer
+ // where each texture's texels go in the upload buffer: its layout (the runs place it)
let mut failed = Vec::new();
let mut planned = Vec::with_capacity(items.len());
- let mut total = 0u64;
for (k, (res, subs, states)) in items.iter().enumerate() {
- match layout(dev, res, subs, states, states) {
- Ok(l) => {
- let base = total.div_ceil(PLACEMENT) * PLACEMENT;
- total = base + l.total;
- planned.push((k, l, base));
- }
+ let mask = masks.get(k).and_then(|m| m.as_deref());
+ match layout_masked(dev, res, subs, states, states, mask) {
+ Ok(l) => planned.push((k, l)),
Err(e) => failed.push((k, e)),
}
}
@@ -295,26 +565,82 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items
put_back(key, up);
return Ok(failed);
}
- let (staging, mapped) = up.staging(dev, total)?;
- up.alloc.Reset().map_err(err)?;
- up.list.Reset(&up.alloc, None).map_err(err)?;
- for (k, l, base) in &planned {
- let (res, subs, states) = &items[*k];
- record_into(&up.list, res, subs, l, states, states, &staging, mapped, *base);
+ let cap = staging_cap();
+ let runs = plan_runs(&planned.iter().map(|(_, l)| l.total).collect::>(), cap);
+ #[cfg(test)]
+ TEST_RUNS.with(|t| *t.borrow_mut() = runs.iter().map(|r| (r.items.len(), r.bytes, r.own)).collect());
+ let index: Vec = planned.iter().map(|(k, _)| *k).collect();
+ let mut up = Some(up);
+ let done = run_all(&runs, &index, failed, executed, |run| {
+ let Some(u) = up.as_mut() else { return Err(RunError::Before("texture copy: no uploader".into())) };
+ let r = one_run(dev, queue, u, items, masks, &planned, run, cap);
+ match &r {
+ Ok(()) => {}
+ // (a fresh uploader next time, as after a batch that failed before 0023.2)
+ Err(RunError::Before(_)) => up = None,
+ // the GPU may still read the upload buffer and run the list: they stay alive (a fresh
+ // uploader next time) – freeing them under the GPU removed the device
+ Err(RunError::After(_)) => std::mem::forget(up.take()),
+ }
+ r
+ });
+ if let Some(u) = up {
+ put_back(key, u);
+ }
+ done
+}
+
+/// One run of `upload_batch_masked_run` on `up`: its texels into the kept buffer (or one of its
+/// own), its copies recorded on the uploader's list, submitted, signalled and waited for (10 s).
+#[allow(clippy::too_many_arguments)]
+unsafe fn one_run(
+ dev: &ID3D12Device,
+ queue: &ID3D12CommandQueue,
+ up: &mut Uploader,
+ items: &[(ID3D12Resource, Vec, Vec)],
+ masks: &[Option>],
+ planned: &[(usize, Layout)],
+ run: &Run,
+ cap: Option,
+) -> Result<(), RunError> {
+ use RunError::{After, Before};
+ let own = if run.own {
+ let o = OwnStaging::new(dev, run.bytes).map_err(Before)?;
+ note_own_staging(run.bytes, cap);
+ Some(o)
+ } else {
+ None
+ };
+ let (staging, mapped) = match &own {
+ Some(o) => (o.buffer.clone(), o.mapped),
+ None => up.staging(dev, run.bytes, cap).map_err(Before)?,
+ };
+ up.alloc.Reset().map_err(|e| Before(err(e)))?;
+ up.list.Reset(&up.alloc, None).map_err(|e| Before(err(e)))?;
+ for (i, &base) in run.items.clone().zip(&run.bases) {
+ let Some((k, l)) = planned.get(i) else { continue };
+ let Some((res, subs, states)) = items.get(*k) else { continue };
+ let mask = masks.get(*k).and_then(|m| m.as_deref());
+ record_into(&up.list, res, subs, l, states, states, &staging, mapped, base, mask);
+ }
+ up.list.Close().map_err(|e| Before(err(e)))?;
+ {
+ let _ops = crate::hle::d3d12x::d3d_ops();
+ queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&up.list).map_err(|e| Before(err(e)))?)]);
}
- up.list.Close().map_err(err)?;
- queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&up.list).map_err(err)?)]);
up.value += 1;
let copy_error = |e| format!("texture copy: {e}");
- queue.Signal(&up.fence, up.value).map_err(|e| copy_error(fence::api_error(dev, "Signal", e)))?;
- if let Err(e) = fence::wait(&up.fence, up.value, dev, None, 10_000) {
- // the GPU may still read the upload buffer and run the list: they stay alive (a fresh
- // uploader next time) – freeing them under the GPU removed the device
- std::mem::forget(up);
- return Err(copy_error(e));
- }
- put_back(key, up);
- Ok(failed)
+ let waited = match queue.Signal(&up.fence, up.value) {
+ Err(e) => Err(copy_error(fence::api_error(dev, "Signal", e))),
+ Ok(()) => fence::wait(&up.fence, up.value, dev, None, 10_000).map_err(copy_error),
+ };
+ if let Err(e) = waited {
+ // (the list was submitted: a buffer of its own it reads stays alive, as the uploader does)
+ std::mem::forget(own);
+ return Err(After(e));
+ }
+ drop(own);
+ Ok(())
}
fn put_back(key: usize, up: Uploader) {
@@ -342,7 +668,7 @@ pub unsafe fn record_upload_states(
let up = buffer(dev, l.total)?;
let mut p = std::ptr::null_mut();
up.Map(0, None, Some(&mut p)).map_err(err)?;
- record_into(list, res, subs, &l, before, after, &up, p as *mut u8, 0);
+ record_into(list, res, subs, &l, before, after, &up, p as *mut u8, 0, None);
up.Unmap(0, None);
Ok(up)
}
@@ -357,8 +683,13 @@ struct Layout {
/// The `Layout` of uploading `subs` into `res`, checked against the resource.
unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES]) -> Result {
- validate_subresources(subs)?;
- let rd = res.GetDesc();
+ layout_masked(dev, res, subs, before, after, None)
+}
+
+/// `layout`, the subresources `mask` leaves out (not copied) allowed to have no texels.
+unsafe fn layout_masked(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES], mask: Option<&[bool]>) -> Result {
+ validate_subresources_masked(subs, mask)?;
+ let rd = copyable_desc(res);
let n = subs.len();
validate_subresource_count(&rd, n)?;
for s in [before, after] {
@@ -382,13 +713,38 @@ unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource],
Ok(Layout { fps, rows, total })
}
+/// The description of `res` for GetCopyableFootprints: a reserved texture's 64 KiB tiled
+/// layout as the default one (the footprints of the texels are the same; `lazy_tex`).
+pub unsafe fn copyable_desc(res: &ID3D12Resource) -> D3D12_RESOURCE_DESC {
+ let mut d = res.GetDesc();
+ if d.Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE || d.Layout == D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE {
+ d.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
+ }
+ d
+}
+
/// Write `subs` into the mapped upload buffer `up` (`mapped`) from `base` (a multiple of
/// D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT) as `l` places them, and record their copies into
-/// `res` on `list` (barriers from `before` and back to `after`).
+/// `res` on `list` (barriers from `before` and back to `after`) – those `mask` has (None: all).
#[allow(clippy::too_many_arguments)]
-unsafe fn record_into(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, subs: &[Subresource], l: &Layout, before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES], up: &ID3D12Resource, mapped: *mut u8, base: u64) {
+unsafe fn record_into(
+ list: &ID3D12GraphicsCommandList,
+ res: &ID3D12Resource,
+ subs: &[Subresource],
+ l: &Layout,
+ before: &[D3D12_RESOURCE_STATES],
+ after: &[D3D12_RESOURCE_STATES],
+ up: &ID3D12Resource,
+ mapped: *mut u8,
+ base: u64,
+ mask: Option<&[bool]>,
+) {
let n = subs.len();
- for ((s, fp), &nrows) in subs.iter().zip(&l.fps).zip(&l.rows) {
+ let wanted = |k: usize| mask.is_none_or(|m| m.get(k).copied().unwrap_or(false));
+ for (k, ((s, fp), &nrows)) in subs.iter().zip(&l.fps).zip(&l.rows).enumerate() {
+ if !wanted(k) {
+ continue;
+ }
let pitch = fp.Footprint.RowPitch as usize;
let row = s.row_bytes.min(pitch);
// depth slices are NumRows rows apart (rows of 4×4 blocks for BCn)
@@ -405,6 +761,9 @@ unsafe fn record_into(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, su
list.ResourceBarrier(&to_copy);
}
for (k, fp) in l.fps.iter().enumerate() {
+ if !wanted(k) {
+ continue;
+ }
let dst = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(res),
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
@@ -810,17 +1169,282 @@ mod tests {
}
}
+ /// (tests) This thread's uploads go with cap `cap` until the guard is dropped.
+ fn cap_for_test(cap: Option) -> impl Drop {
+ struct Restore;
+ impl Drop for Restore {
+ fn drop(&mut self) {
+ TEST_CAP.with(|c| c.set(None));
+ }
+ }
+ TEST_CAP.with(|c| c.set(Some(cap)));
+ Restore
+ }
+
+ /// (tests) The runs of this thread's last upload: (textures, staging bytes, a buffer of its own).
+ fn last_runs() -> Vec<(usize, u64, bool)> {
+ TEST_RUNS.with(|t| t.borrow().clone())
+ }
+
+ /// (tests) The upload buffer `queue`'s uploader keeps: (buffer, capacity).
+ fn kept(queue: &ID3D12CommandQueue) -> Option<(usize, u64)> {
+ let key = windows::core::Interface::as_raw(queue) as usize;
+ UPLOADERS.lock().unwrap().as_ref().and_then(|m| m.get(&key)).and_then(|u| u.staging.as_ref()).map(|s| (windows::core::Interface::as_raw(&s.0) as usize, s.2))
+ }
+
+ /// (tests) No uploader kept for `queue`: one an earlier queue left at its address (idle – an
+ /// uploader is kept only after its last wait) is let go.
+ fn forget_uploader(queue: &ID3D12CommandQueue) {
+ let key = windows::core::Interface::as_raw(queue) as usize;
+ let gone = UPLOADERS.lock().unwrap().as_mut().and_then(|m| m.remove(&key));
+ drop(gone);
+ }
+
+ /// (tests) A 2D texture of `w` × `h` with `mips` levels in the shader-read states.
+ unsafe fn texture_2d(dev: &ID3D12Device, w: u64, h: u32, mips: u16, format: DXGI_FORMAT) -> ID3D12Resource {
+ let rd = D3D12_RESOURCE_DESC {
+ Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
+ Width: w,
+ Height: h,
+ DepthOrArraySize: 1,
+ MipLevels: mips,
+ Format: format,
+ SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+ ..Default::default()
+ };
+ let mut r: Option = None;
+ dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rd, SHADER_READ, None, &mut r).unwrap();
+ r.unwrap()
+ }
+
+ /// (tests) Every subresource of `r`, filled with a pattern of `seed`.
+ unsafe fn pattern(dev: &ID3D12Device, r: &ID3D12Resource, seed: u8) -> Vec {
+ let rd = r.GetDesc();
+ let n = rd.MipLevels as usize;
+ let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n];
+ let (mut rows, mut row_bytes) = (vec![0u32; n], vec![0u64; n]);
+ dev.GetCopyableFootprints(&rd, 0, n as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), None);
+ (0..n)
+ .map(|k| {
+ let (r, b, d) = (rows[k] as usize, row_bytes[k] as usize, fps[k].Footprint.Depth as usize);
+ Subresource { rows: r, row_bytes: b, depth: d, data: (0..r * b * d).map(|i| (i as u8).wrapping_mul(31) ^ (i >> 9) as u8 ^ seed ^ k as u8).collect() }
+ })
+ .collect()
+ }
+
+ /// (tests) Every texture of `items` reads back what was uploaded into it.
+ unsafe fn assert_read_back(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)], what: &str) {
+ for (i, (r, want, _)) in items.iter().enumerate() {
+ let got = read_back(dev, queue, r, want);
+ for (k, (g, w)) in got.iter().zip(want).enumerate() {
+ assert!(g == w, "{what}: texture {i}, subresource {k} differs");
+ }
+ }
+ }
+
+ /// GP3 at 1/128 of its scale – this thread's cap 1 MiB for XCL_UPLOAD_STAGING_MB's 128: a batch
+ /// of seven textures of 320 KiB on the PC (2.2 MiB, as a batch of 300 MB is 2.3 caps) goes in 3
+ /// runs of whole textures through the queue's kept buffer, made at the cap and never above it;
+ /// then one texture of 1.6 MiB (as one of 200 MB is 1.6 caps) goes through a buffer of its own
+ /// and leaves the kept one as it was. Every texel reads back as uploaded.
+ #[test]
+ fn gpu_an_upload_over_the_staging_cap_goes_in_runs_and_never_grows_the_kept_buffer_past_it() {
+ let Some((dev, queue)) = device() else {
+ println!("no D3D12 device – skipping");
+ crate::gpu::recomp::runner::skip_test("no GPU");
+ return;
+ };
+ let cap = 1u64 << 20;
+ let _cap = cap_for_test(Some(cap));
+ unsafe {
+ forget_uploader(&queue);
+ let textures: Vec<_> = (0..7).map(|_| texture_2d(&dev, 256, 320, 1, DXGI_FORMAT_R8G8B8A8_UNORM)).collect();
+ let items: Vec<_> = textures.iter().enumerate().map(|(i, r)| (r.clone(), pattern(&dev, r, i as u8 * 16), vec![SHADER_READ])).collect();
+ assert!(upload_batch(&dev, &queue, &items).unwrap().is_empty(), "an upload failed");
+ let runs = last_runs();
+ assert_eq!(runs.iter().map(|r| (r.0, r.2)).collect::>(), [(3, false), (3, false), (1, false)], "runs: {runs:?}");
+ assert!(runs.iter().all(|r| r.1 <= cap), "a run over the cap: {runs:?}");
+ assert_read_back(&dev, &queue, &items, "in runs");
+ let before = kept(&queue).expect("the queue's upload buffer is kept");
+ assert_eq!(before.1, cap, "the kept buffer is made at the cap (4 MiB before 0023.2)");
+ // one texture over the cap: a buffer of its own, the kept one untouched
+ let big = texture_2d(&dev, 512, 800, 1, DXGI_FORMAT_R8G8B8A8_UNORM);
+ let one = vec![(big.clone(), pattern(&dev, &big, 0x5A), vec![SHADER_READ])];
+ assert_eq!(TEST_OWN_LIVE.with(|l| l.get()), 0);
+ assert!(upload_batch(&dev, &queue, &one).unwrap().is_empty(), "the upload over the cap failed");
+ let runs = last_runs();
+ assert!(runs.len() == 1 && runs[0].0 == 1 && runs[0].1 > cap && runs[0].2, "runs: {runs:?}");
+ assert_eq!(TEST_OWN_LIVE.with(|l| l.get()), 0, "the buffer of its own is let go once its copy ran");
+ assert_read_back(&dev, &queue, &one, "through a buffer of its own");
+ assert_eq!(kept(&queue), Some(before), "the kept buffer is the one it was, at the cap");
+ // and a batch under the cap after it: the kept buffer again
+ assert!(upload_batch(&dev, &queue, &items[..2]).unwrap().is_empty());
+ assert_eq!(last_runs().iter().map(|r| (r.0, r.2)).collect::>(), [(2, false)]);
+ assert_read_back(&dev, &queue, &items[..2], "after it");
+ assert_eq!(kept(&queue), Some(before));
+ forget_uploader(&queue);
+ }
+ }
+
+ /// A small batch with the default cap (or XCL_UPLOAD_STAGING_MB=0, or any cap of 16 MiB or
+ /// more) is one run through the queue's kept buffer, made as before 0023.2: 4 MiB, the next
+ /// power of two of 4 MiB or more.
+ #[test]
+ fn gpu_a_small_upload_batch_is_one_run_through_the_kept_buffer_as_before() {
+ let Some((dev, queue)) = device() else {
+ println!("no D3D12 device – skipping");
+ crate::gpu::recomp::runner::skip_test("no GPU");
+ return;
+ };
+ unsafe {
+ forget_uploader(&queue);
+ let textures = [
+ texture_2d(&dev, 64, 64, 7, DXGI_FORMAT_R8G8B8A8_UNORM),
+ texture_2d(&dev, 100, 30, 1, DXGI_FORMAT_R8G8B8A8_UNORM),
+ texture_2d(&dev, 256, 256, 9, DXGI_FORMAT_BC7_UNORM),
+ ];
+ let items: Vec<_> = textures.iter().enumerate().map(|(i, r)| (r.clone(), pattern(&dev, r, 0x40 + i as u8), vec![SHADER_READ])).collect();
+ assert!(upload_batch(&dev, &queue, &items).unwrap().is_empty(), "an upload failed");
+ let runs = last_runs();
+ assert!(runs.len() == 1 && runs[0].0 == 3 && !runs[0].2, "one run: {runs:?}");
+ assert_eq!(kept(&queue).map(|k| k.1), Some(STAGING_MIN), "the kept buffer as before 0023.2");
+ assert_read_back(&dev, &queue, &items, "one run");
+ forget_uploader(&queue);
+ }
+ }
+
+ /// The runs of an upload (`plan_runs`): 300 MiB of 1-MiB textures at the cap of 128 MiB go in 3
+ /// runs of whole textures (128, 128 and 44), each from base 0; a texture of 200 MiB alone in a
+ /// run through a buffer of its own, the ones around it in runs of their own; bases at the
+ /// placement alignment; exactly the cap fits a run; with no cap (`XCL_UPLOAD_STAGING_MB=0`) one
+ /// run of everything, as before 0023.2. The kept buffer for capped runs is never above the cap.
#[test]
- fn large_staging_uses_sixteen_mib_growth_steps() {
- let mib = 1 << 20;
- assert_eq!(staging_capacity(1), Some(4 * mib));
- assert_eq!(staging_capacity(33 * mib), Some(64 * mib));
- assert_eq!(staging_capacity(64 * mib + 1), Some(80 * mib));
- assert_eq!(staging_capacity(138_713_408), Some(144 * mib));
- assert_eq!(staging_capacity(256 * mib + 1), Some(272 * mib));
- assert_eq!(staging_capacity(u64::MAX), None);
+ fn an_upload_plan_goes_in_runs_of_at_most_the_cap() {
+ let mib = 1u64 << 20;
+ let cap = Some(STAGING_CAP);
+ let runs = plan_runs(&[mib; 300], cap);
+ assert_eq!(runs.iter().map(|r| r.items.len()).collect::>(), [128, 128, 44]);
+ assert!(runs.iter().all(|r| !r.own && r.bytes <= STAGING_CAP && r.bases[0] == 0), "{runs:?}");
+ assert_eq!((runs[1].items.clone(), runs[2].items.clone()), (128..256, 256..300));
+ assert_eq!(runs[2].bases, (0..44).map(|k| k * mib).collect::>());
+ assert!(runs.iter().all(|r| kept_capacity(r.bytes, cap).is_some_and(|c| c <= STAGING_CAP)));
+ // a texture of 200 MiB between smaller ones: alone, through a buffer of its own
+ assert_eq!(
+ plan_runs(&[3 * mib, 5 * mib, 200 * mib, 7 * mib], cap),
+ [
+ Run { items: 0..2, bases: vec![0, 3 * mib], bytes: 8 * mib, own: false },
+ Run { items: 2..3, bases: vec![0], bytes: 200 * mib, own: true },
+ Run { items: 3..4, bases: vec![0], bytes: 7 * mib, own: false },
+ ]
+ );
+ // bases at the placement alignment (512 B)
+ assert_eq!(plan_runs(&[1000, 1000, 1000], cap), [Run { items: 0..3, bases: vec![0, 1024, 2048], bytes: 3048, own: false }]);
+ // exactly the cap fits; a byte more starts a run
+ assert_eq!(plan_runs(&[64 * mib, 64 * mib], cap).len(), 1);
+ assert_eq!(plan_runs(&[64 * mib, 64 * mib + 1], cap).len(), 2);
+ assert_eq!(plan_runs(&[STAGING_CAP], cap), [Run { items: 0..1, bases: vec![0], bytes: STAGING_CAP, own: false }]);
+ // no cap: one run of everything, its buffer grown as before 0023.2
+ let runs = plan_runs(&[mib; 300], None);
+ assert_eq!((runs.len(), runs[0].items.clone(), runs[0].bytes, runs[0].own), (1, 0..300, 300 * mib, false));
+ assert_eq!(kept_capacity(runs[0].bytes, None), Some(512 * mib));
+ assert_eq!(plan_runs(&[200 * mib, mib], None).len(), 1);
+ assert!(plan_runs(&[], cap).is_empty());
}
+ /// `XCL_UPLOAD_STAGING_MB`: unset or not a number 128 MiB; a number of MiB raised to 16 and at
+ /// most 4096; `0` no cap. The title textures' batch follows it (256 MiB with none, as before
+ /// 0023.2). The kept buffer is grown as before 0023.2 – the next power of two of 4 MiB or more –
+ /// but never above the cap (one under 4 MiB: the cap). This process's switch as it was read; the
+ /// line of an upload over the cap.
+ #[test]
+ fn the_upload_staging_cap_is_read_in_mib_and_zero_is_as_before() {
+ let mib = 1u64 << 20;
+ assert_eq!(staging_cap_for(None), Some(128 * mib));
+ assert_eq!(staging_cap_for(Some("x")), Some(128 * mib));
+ assert_eq!(staging_cap_for(Some("")), Some(128 * mib));
+ assert_eq!(staging_cap_for(Some(" 64 ")), Some(64 * mib));
+ assert_eq!(staging_cap_for(Some("5")), Some(16 * mib));
+ assert_eq!(staging_cap_for(Some("99999")), Some(4096 * mib));
+ assert_eq!(staging_cap_for(Some("0")), None);
+ assert_eq!(batch_bytes_for(Some(128 * mib)), 128 << 20);
+ assert_eq!(batch_bytes_for(Some(16 * mib)), 16 << 20);
+ assert_eq!(batch_bytes_for(None), 256 << 20);
+ assert_eq!(kept_capacity(mib, Some(128 * mib)), Some(4 * mib));
+ assert_eq!(kept_capacity(33 * mib, Some(128 * mib)), Some(64 * mib));
+ assert_eq!(kept_capacity(100 * mib, Some(128 * mib)), Some(128 * mib));
+ assert_eq!(kept_capacity(128 * mib, Some(128 * mib)), Some(128 * mib));
+ assert_eq!(kept_capacity(129 * mib, None), Some(256 * mib), "no cap: as before 0023.2");
+ assert_eq!(kept_capacity(u64::MAX, None), None, "past u64: an error, not a buffer of 0 bytes");
+ assert_eq!(kept_capacity(700 << 10, Some(mib)), Some(mib), "a cap under 4 MiB: the cap");
+ let env = std::env::var("XCL_UPLOAD_STAGING_MB").ok();
+ assert_eq!(staging_cap(), staging_cap_for(env.as_deref()), "this process's switch");
+ assert_eq!(batch_bytes(), batch_bytes_for(staging_cap()));
+ assert_eq!(
+ own_staging_line(200 << 20, Some(128 << 20), 3),
+ "title textures: an upload of one texture's 200 MB went through an upload buffer of its own, past XCL_UPLOAD_STAGING_MB=128: made for it and let go once its copy ran (3 so far)"
+ );
+ }
+
+ /// What a run that failed leaves the caller (`run_all`; the design check's A4): a failure after
+ /// its submit (a Signal or a wait) in run 1 of 3 gives runs 2-3's textures as failed – never
+ /// submitted – and the copies before as submitted (Ok, `executed`); in the last run Err with
+ /// `executed`, as one batch's failure before 0023.2; one before its submit in run 1 is Err with
+ /// nothing submitted, in run 2 gives runs 2-3's textures as failed. A texture whose layout failed
+ /// stays failed; the texts name the failure.
+ #[test]
+ fn a_failed_run_gives_the_textures_of_the_runs_not_submitted_as_failed() {
+ // ten textures: #4's layout failed; the others in 3 runs of 3 textures of 40 MiB at 128
+ let planned = [0usize, 1, 2, 3, 5, 6, 7, 8, 9];
+ let runs = plan_runs(&[40 << 20; 9], Some(STAGING_CAP));
+ assert_eq!(runs.iter().map(|r| r.items.clone()).collect::>(), [0..3, 3..6, 6..9]);
+ let layout = vec![(4usize, "layout".to_string())];
+ let go = |fail: Option<(usize, bool)>| {
+ let (mut executed, mut called) = (false, 0usize);
+ let r = run_all(&runs, &planned, layout.clone(), &mut executed, |_| {
+ called += 1;
+ match fail {
+ Some((at, true)) if at + 1 == called => Err(RunError::After("texture copy: timed out".into())),
+ Some((at, false)) if at + 1 == called => Err(RunError::Before("Reset".into())),
+ _ => Ok(()),
+ }
+ });
+ (r, executed, called)
+ };
+ let failed = |r: &Result, String>| r.as_ref().map(|f| f.iter().map(|x| x.0).collect::>()).map_err(Clone::clone);
+ let (r, executed, called) = go(None);
+ assert_eq!((failed(&r), executed, called), (Ok(vec![4]), true, 3), "all ran");
+ let (r, executed, called) = go(Some((0, true)));
+ assert_eq!((failed(&r), executed, called), (Ok(vec![4, 3, 5, 6, 7, 8, 9]), true, 1), "a wait in run 1 of 3: runs 2-3 not submitted");
+ assert_eq!(r.as_ref().unwrap()[1].1, "texture copy: timed out – this part of the batch was not submitted");
+ // (what the caller tells them by – C-F3: the textures never submitted, not the layout failure)
+ let unsent: Vec = r.unwrap().into_iter().filter(|(_, e)| never_submitted(e)).map(|(k, _)| k).collect();
+ assert_eq!(unsent, [3, 5, 6, 7, 8, 9], "every texture of the runs not submitted, not #4");
+ let (before, _, _) = go(Some((1, false)));
+ assert!(before.unwrap().iter().filter(|(k, _)| *k != 4).all(|(_, e)| never_submitted(e)), "before run 2's submit: runs 2-3 never submitted");
+ assert!(!never_submitted("layout") && !never_submitted("texture copy: timed out"));
+ let (r, executed, called) = go(Some((1, true)));
+ assert_eq!((failed(&r), executed, called), (Ok(vec![4, 7, 8, 9]), true, 2), "a wait in run 2: run 3 not submitted");
+ let (r, executed, called) = go(Some((2, true)));
+ assert_eq!((failed(&r), executed, called), (Err("texture copy: timed out".to_string()), true, 3), "a wait in the last run: as before 0023.2");
+ let (r, executed, called) = go(Some((0, false)));
+ assert_eq!((failed(&r), executed, called), (Err("Reset".to_string()), false, 1), "before run 1's submit: nothing submitted");
+ let (r, executed, called) = go(Some((1, false)));
+ assert_eq!((failed(&r), executed, called), (Ok(vec![4, 3, 5, 6, 7, 8, 9]), true, 2), "before run 2's submit: runs 2-3 not submitted");
+ // one run (a batch under the cap): as before 0023.2
+ let one = plan_runs(&[1 << 20; 3], Some(STAGING_CAP));
+ let mut executed = false;
+ assert_eq!(run_all(&one, &[0, 1, 2], Vec::new(), &mut executed, |_| Err(RunError::After("lost".into()))), Err("lost".to_string()));
+ assert!(executed);
+ }
+
+ /// (upstream 9db0989) A large mixed batch – a 128 MiB RGBA texture, then it with a 4 MiB BC7
+ /// one – reads back byte for byte and keeps its staging tight: under the cap (`staging_cap`,
+ /// 128 MiB by default) the 132 MiB batch goes in two runs on the kept buffer of 128 MiB, which
+ /// the repeated batch reuses; no D3D12 debug errors with XCL_D3D12_DEBUG. Before that the kept
+ /// buffer grows: the BC7 texture alone keeps one of 4 MiB, and the RGBA one alone then a new
+ /// one of 128 MiB – the 4 MiB one let go, and taken off `STAGING_BYTES`, before the bigger one
+ /// is made, so this thread's kept bytes peak at 128 MiB, never 132 (`TEST_KEPT_LIVE`); both
+ /// read back byte for byte, and the uploader's Drop takes its buffer off again.
#[test]
fn gpu_large_mixed_upload_keeps_tight_staging_and_exact_pixels() {
use windows::core::Interface;
@@ -845,6 +1469,10 @@ mod tests {
};
println!("large upload adapter: {}", String::from_utf16_lossy(&desc.Description).trim_end_matches('\0'));
let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap();
+ // the default cap on this thread whatever XCL_UPLOAD_STAGING_MB says, and no uploader an
+ // earlier queue left at this queue's address
+ let _cap = cap_for_test(Some(STAGING_CAP));
+ forget_uploader(&queue);
let make = |width, height, format| {
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: width, Height: height,
@@ -869,8 +1497,21 @@ mod tests {
(stage.0.as_raw() as usize, stage.2)
};
let batch = [rgba, bc7];
+ // the growth: this thread's kept bytes from here, the peak reset
+ let base = TEST_KEPT_LIVE.with(|l| {
+ let now = l.get().0;
+ l.set((now, now));
+ now
+ });
+ assert!(upload_batch(&dev, &queue, &batch[1..]).unwrap().is_empty());
+ let small = kept();
+ assert_eq!(small.1, 4 << 20, "the BC7 texture alone: a kept buffer of 4 MiB");
+ assert!(read_back(&dev, &queue, &batch[1].0, &batch[1].1) == batch[1].1, "BC7 alone pixel mismatch");
assert!(upload_batch(&dev, &queue, &batch[..1]).unwrap().is_empty());
let first = kept();
+ let (now, peak) = TEST_KEPT_LIVE.with(|l| l.get());
+ assert_eq!((now - base, peak - base), (128 << 20, 128 << 20), "grown to 128 MiB, the 4 MiB buffer let go before");
+ assert!(read_back(&dev, &queue, &batch[0].0, &batch[0].1) == batch[0].1, "RGBA alone pixel mismatch");
let before = std::time::Instant::now();
assert!(upload_batch(&dev, &queue, &batch).unwrap().is_empty());
let growth = before.elapsed();
@@ -888,6 +1529,7 @@ mod tests {
// Drop the test's large uploader after its last copy fence and readbacks have passed.
let uploader = UPLOADERS.lock().unwrap().as_mut().unwrap().remove(&key);
drop(uploader);
+ assert_eq!(TEST_KEPT_LIVE.with(|l| l.get().0) - base, 0, "the kept buffer taken off STAGING_BYTES with its uploader");
if let Ok(info) = dev.cast::() {
let mut errors = 0;
for index in 0..info.GetNumStoredMessagesAllowedByRetrievalFilter() {
@@ -906,8 +1548,8 @@ mod tests {
println!("large upload: request={} B first_capacity={} B grown_capacity={} B growth={growth:?} repeat={repeat:?} byte_exact=true",
(128 + 4) << 20, first.1, grown.1);
assert_eq!(first.1, 128 << 20);
+ assert_eq!(grown, first, "132 MiB at the cap of 128 MiB: two runs on the kept buffer, never a bigger one");
assert_eq!(grown, reused, "the repeated batch must reuse the staging buffer");
- assert_eq!(grown.1, 144 << 20, "staging for 132 MiB must fit the next large size class");
}
}
diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs
index 173e21b..5dd5a4e 100644
--- a/crates/xcl/src/gpu/uma.rs
+++ b/crates/xcl/src/gpu/uma.rs
@@ -13,7 +13,7 @@
//! 4095 MiB works (exactly 4 GiB is rejected), opening 4 GiB takes ~0.5 s.
use std::collections::BTreeMap;
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Mutex, OnceLock};
use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE};
@@ -31,8 +31,39 @@ pub const MAX_WINDOWS: usize = 4;
/// bytes of sparse window 0 only 32-bit descriptor heaps get (`Uma::desc_range`)
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;
+
+/// XCL's own part of the committed coherent window – its floor, and what it is made with beside
+/// the title's need (`coherent_hint`): XCL's per-draw arguments (its pool, `POOL`, and blocks),
+/// readback heaps and buffers, a title's few committed textures (`real.rs`: while 128 MiB stay
+/// free). A Mac's window has a copy in video memory of its whole size (D3DMetal has no
+/// OpenExistingHeapFromAddress), wired while the GPU works: 256 MB there – run 66 used 139 MB of
+/// 512, still rising (120 → 139 MB from 162.7 to 186.0 s), and a full window skips draws, which the
+/// `coherent window:` line counts –, 512 MB elsewhere. GTA VI's four committed textures (run 66:
+/// 8, 16, 16 and 8 MB at 34 s, the use 64 → 112 MB) still fit 256 MB, the last by 16 MB; a texture
+/// past that becomes a plain PC texture, as one that finds the window full. `XCL_COHERENT_OWN_MB`
+/// (read once, with `XCL_COHERENT_MB` – the whole window instead, with this as its floor) sets it:
+/// unset or not a number → the default; a number → that many MiB, raised to 64 (a window that small
+/// gets a pool of a quarter of it, 16 MiB) and 4095 at most; `512` is a Mac's window before 0023.2.
+pub fn own_part() -> usize {
+ static OWN: OnceLock = OnceLock::new();
+ *OWN.get_or_init(|| own_part_for(crate::util::mac_host(), std::env::var("XCL_COHERENT_OWN_MB").ok().as_deref()))
+}
+
+/// `own_part` on a Mac or not, with `XCL_COHERENT_OWN_MB`'s value.
+fn own_part_for(mac: bool, var: Option<&str>) -> usize {
+ match var.and_then(|v| v.trim().parse::().ok()) {
+ Some(mb) => mb.clamp(64, 4095) << 20,
+ None if mac => 256 << 20,
+ None => 512 << 20,
+ }
+}
+
+/// The committed coherent window of a layout of `size` bytes asked for with `coherent` (the title's
+/// need and XCL's part, or `XCL_COHERENT_MB`): never less than XCL's part `own` unless the whole
+/// layout is smaller, whole 64 KiB grains, at most a window.
+fn committed_for(size: usize, coherent: usize, own: usize) -> usize {
+ ((size.min(coherent.max(own)) + GRAIN - 1) & !(GRAIN - 1)).clamp(GRAIN, MAX_SIZE)
+}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum WindowKind {
@@ -55,6 +86,11 @@ pub struct Uma {
pool: Mutex<(usize, usize, Vec)>,
/// the committed windows are not the GPU's memory: it has copies of them (`set_shadowed`)
shadowed: AtomicBool,
+ /// `used` now and at most so far – kept with it under `inner`'s lock (`grew`, `shrank`) – and
+ /// the per-draw blocks `Arena::take` found no room for so far (`usage`)
+ used_now: AtomicUsize,
+ used_most: AtomicUsize,
+ arena_full: AtomicU64,
}
/// bytes of XCL's arena pool (`Uma::new`)
@@ -148,6 +184,7 @@ impl Uma {
g.free.insert(at + bytes, start + len - at - bytes);
}
g.used.insert(at, bytes);
+ self.grew(bytes);
at
};
let p = self.base + at;
@@ -160,17 +197,48 @@ impl Uma {
self.pool.lock().unwrap().2.pop()
}
+ /// `used` grew by `bytes` (under `inner`'s lock): the use now and its high-water.
+ fn grew(&self, bytes: usize) {
+ let now = self.used_now.fetch_add(bytes, Ordering::Relaxed) + bytes;
+ self.used_most.fetch_max(now, Ordering::Relaxed);
+ }
+
+ /// `used` shrank by `bytes` (under `inner`'s lock).
+ fn shrank(&self, bytes: usize) {
+ self.used_now.fetch_sub(bytes, Ordering::Relaxed);
+ }
+
+ /// A per-draw block `Arena::take` found no room for: its draw or dispatch is skipped.
+ fn refused(&self) {
+ self.arena_full.fetch_add(1, Ordering::Relaxed);
+ }
+
+ /// The committed windows' use now and at most so far – as `used`, the blocks handed out: XCL's
+ /// pool counted whole from the start, its 64 MiB of a runtime window – and the per-draw blocks
+ /// refused so far for want of room (their draws and dispatches skipped).
+ pub fn usage(&self) -> (usize, usize, u64) {
+ (self.used_now.load(Ordering::Relaxed), self.used_most.load(Ordering::Relaxed), self.arena_full.load(Ordering::Relaxed))
+ }
+
+ /// XCL's per-draw pool: (its bytes, the bytes of its blocks free now).
+ pub fn pool_usage(&self) -> (usize, usize) {
+ let g = self.pool.lock().unwrap_or_else(|e| e.into_inner());
+ (g.1 - g.0, g.2.len() * ARENA_BLOCK)
+ }
+
/// Runtime layout: windows 0..3 (12 GiB) reserved as write-watched sparse VRAM windows
/// (window 0 holds 32-bit-addressed descriptor heaps + buffers + XMem, windows 1..2 hold
/// large title reservations and overflow), and window 3 as a smaller committed coherent
- /// window (`OpenExistingHeapFromAddress`) for per-draw arguments and CPU readback buffers.
+ /// window (`OpenExistingHeapFromAddress`) for per-draw arguments and CPU readback buffers:
+ /// XCL's own part of it (`own_part`).
pub fn for_runtime(size: usize) -> Option {
- Self::for_runtime_with(size, RUNTIME_COMMITTED_CAP)
+ Self::for_runtime_with(size, own_part())
}
- /// `for_runtime` with a coherent window of up to `coherent` bytes (`coherent_hint`).
+ /// `for_runtime` with a coherent window of up to `coherent` bytes (`coherent_hint`), XCL's
+ /// part at least (`committed_for`).
pub fn for_runtime_with(size: usize, coherent: usize) -> Option {
- let committed = ((size.min(coherent.max(RUNTIME_COMMITTED_CAP)) + GRAIN - 1) & !(GRAIN - 1)).clamp(GRAIN, MAX_SIZE);
+ let committed = committed_for(size, coherent, own_part());
let sparse_len = (MAX_WINDOWS - 1) * WINDOW;
for slot in (4usize..512).step_by(MAX_WINDOWS) {
let base = slot << 32;
@@ -202,6 +270,9 @@ impl Uma {
sparse_free: Mutex::new(sparse_free),
pool: Mutex::new((0, 0, Vec::new())),
shadowed: AtomicBool::new(false),
+ used_now: AtomicUsize::new(0),
+ used_most: AtomicUsize::new(0),
+ arena_full: AtomicU64::new(0),
};
u.reserve_pool(POOL);
return Some(u);
@@ -426,6 +497,9 @@ impl Uma {
sparse_free: Mutex::new(Default::default()),
pool: Mutex::new((0, 0, Vec::new())),
shadowed: AtomicBool::new(false),
+ used_now: AtomicUsize::new(0),
+ used_most: AtomicUsize::new(0),
+ arena_full: AtomicU64::new(0),
});
}
for p in got {
@@ -540,14 +614,15 @@ impl Uma {
self.alloc_where(size, align, Some(k), true)
}
- /// `XCL_TRACE_MEM`: each committed-window allocation of 1 MB or more and each one that
- /// fails, with the XCL code that asked for it (what fills the window).
+ /// `XCL_TRACE_MEM`: each committed-window allocation of 1 MB or more and the failed ones that
+ /// `failure_traced` takes (the failures so far appended), with the XCL code that asked for it
+ /// (what fills the window).
#[track_caller]
- fn trace(&self, size: usize, got: Option, used: usize) {
+ fn trace(&self, size: usize, got: Option, used: usize, failures: u64) {
let at = std::panic::Location::caller();
match got {
Some(p) => crate::xlog_info!("UMA: {} KB at {p:#x} for {}:{} ({} MB used)", size >> 10, at.file(), at.line(), used >> 20),
- None => crate::xlog_info!("UMA: {} KB for {}:{} – no room ({} MB used)", size >> 10, at.file(), at.line(), used >> 20),
+ None => crate::xlog_info!("UMA: {} KB for {}:{} – no room ({} MB used) – {failures} failures so far", size >> 10, at.file(), at.line(), used >> 20),
}
}
@@ -566,10 +641,16 @@ impl Uma {
(at.checked_add(size).is_some_and(|end| end <= o + l)).then_some((o, l, at))
});
let Some((start, len, at)) = found else {
+ // (a full window refuses every per-draw block of every list: the first 16 failures, then
+ // the 32nd, 64th, … – the trace sums the used map under `inner` and writes on the title's
+ // binding threads)
if Self::tracing() {
- let used = g.used.values().sum();
- drop(g);
- self.trace(size, None, used);
+ let k = TRACED_FAILURES.fetch_add(1, Ordering::Relaxed) + 1;
+ if failure_traced(k) {
+ let used = g.used.values().sum();
+ drop(g);
+ self.trace(size, None, used, k);
+ }
}
return None;
};
@@ -581,11 +662,12 @@ impl Uma {
g.free.insert(at + size, start + len - at - size);
}
g.used.insert(at, size);
+ self.grew(size);
let used = if Self::tracing() && size >= 1 << 20 { Some(g.used.values().sum()) } else { None };
drop(g);
let p = (self.base + at) as *mut u8;
if let Some(used) = used {
- self.trace(size, Some(p as usize), used);
+ self.trace(size, Some(p as usize), used, 0);
}
if zero {
unsafe { std::ptr::write_bytes(p, 0, size) };
@@ -609,6 +691,7 @@ impl Uma {
let mut g = self.inner.lock().unwrap();
let off = p - self.base;
let Some(orig) = g.used.remove(&off) else { return false };
+ self.shrank(orig);
let (mut start, mut len) = (off, orig);
// merge with the free neighbours
if let Some((&o, &l)) = g.free.range(..off).next_back() {
@@ -670,14 +753,23 @@ impl Arena {
}
if n > ARENA_BLOCK / 2 {
// a large piece: a block of its own (the current one stays in use)
- let p = u.alloc(n, align)?;
+ let Some(p) = u.alloc(n, align) else {
+ u.refused();
+ return None;
+ };
blocks.push(p as usize);
return Some(p);
}
// XCL's pool first, then any free part of committed unified memory
let p = match u.pool_block() {
Some(p) => p,
- None => u.alloc(ARENA_BLOCK, GRAIN)? as usize,
+ None => match u.alloc(ARENA_BLOCK, GRAIN) {
+ Some(p) => p as usize,
+ None => {
+ u.refused();
+ return None;
+ }
+ },
};
blocks.push(p);
self.at = p + n;
@@ -688,33 +780,55 @@ impl Arena {
static GLOBAL: OnceLock> = OnceLock::new();
+/// `XCL_TRACE_MEM`'s failed window allocations so far (`Uma::alloc_where`)
+static TRACED_FAILURES: AtomicU64 = AtomicU64::new(0);
+
+/// Whether the `k`-th failed window allocation (from 1) is traced: the first 16, then the 32nd, 64th,
+/// … – a full window would otherwise write one line per refused per-draw block (one per draw or
+/// dispatch of every list), at run 66's world rates thousands a second on the title's binding threads.
+fn failure_traced(k: u64) -> bool {
+ k <= 16 || k.is_power_of_two()
+}
+
/// The title's graphics memory XCL places in the coherent window (`note_coherent_need`) is
/// known only once it asks for it, and the window is committed when it is made: its size is
/// what the title asked for in its last run (`/cache/uma_coherent.txt`) and XCL's own
-/// 512 MB, at most a window. `XCL_COHERENT_MB` chooses it.
+/// part (`own_part`: 256 MB on a Mac, 512 elsewhere), at most a window. `XCL_COHERENT_MB` chooses
+/// it.
fn coherent_file() -> std::path::PathBuf {
crate::state::data_dir().join("cache").join("uma_coherent.txt")
}
/// Bytes the coherent window is made with.
pub fn coherent_hint() -> usize {
- if let Some(mb) = std::env::var("XCL_COHERENT_MB").ok().and_then(|v| v.parse::().ok()) {
- return (mb << 20).clamp(GRAIN, MAX_SIZE);
+ let env = std::env::var("XCL_COHERENT_MB").ok().and_then(|v| v.parse::().ok());
+ let title = if env.is_some() { 0 } else { std::fs::read_to_string(coherent_file()).ok().and_then(|s| s.trim().parse::().ok()).unwrap_or(0) };
+ let free = if env.is_none() && title > 0 { free_commit() } else { usize::MAX };
+ let (bytes, short) = coherent_hint_for(env, title, free, own_part());
+ if short {
+ crate::xlog_warn!(
+ "UMA: {} MB of commit free, under {} MB: the title's GPU heaps stay outside unified memory (a larger page file gives them the coherent window)",
+ free >> 20,
+ NEEDS_FOR_COHERENT_HEAPS >> 20
+ );
+ }
+ bytes
+}
+
+/// `coherent_hint` of `XCL_COHERENT_MB` (`env_mb`), the title's need in its last run, the commit
+/// free and XCL's part: (bytes, whether the title's heaps stay out for want of commit).
+fn coherent_hint_for(env_mb: Option, title: usize, free_commit: usize, own: usize) -> (usize, bool) {
+ if let Some(mb) = env_mb {
+ return ((mb << 20).clamp(GRAIN, MAX_SIZE), false);
}
- let title = std::fs::read_to_string(coherent_file()).ok().and_then(|s| s.trim().parse::().ok()).unwrap_or(0);
// only with the commit for all of it: the title's ~13 GB, video memory for its render targets
// and textures (WDDM charges commit for each video-memory allocation too) and the window
// itself – a retail game took ~18 GB; with less free it runs without (its GPU heaps outside
// unified memory: no image) rather than taking the system's commit
- if title > 0 && free_commit() < NEEDS_FOR_COHERENT_HEAPS {
- crate::xlog_warn!(
- "UMA: {} MB of commit free, under {} MB: the title's GPU heaps stay outside unified memory (a larger page file gives them the coherent window)",
- free_commit() >> 20,
- NEEDS_FOR_COHERENT_HEAPS >> 20
- );
- return RUNTIME_COMMITTED_CAP;
+ if title > 0 && free_commit < NEEDS_FOR_COHERENT_HEAPS {
+ return (own, true);
}
- (title + RUNTIME_COMMITTED_CAP).min(MAX_SIZE)
+ ((title + own).min(MAX_SIZE), false)
}
/// Commit free before the title starts for its GPU heaps to go to the coherent window.
@@ -741,7 +855,7 @@ pub fn note_coherent_need(bytes: usize) {
let _ = std::fs::create_dir_all(d);
}
let _ = std::fs::write(&f, bytes.to_string());
- crate::xlog_info!("UMA: the title's graphics memory for the coherent window: {} MB (a window of up to {} MB from the next run)", bytes >> 20, (bytes + RUNTIME_COMMITTED_CAP).min(MAX_SIZE) >> 20);
+ crate::xlog_info!("UMA: the title's graphics memory for the coherent window: {} MB (a window of up to {} MB from the next run)", bytes >> 20, (bytes + own_part()).min(MAX_SIZE) >> 20);
}
}
@@ -752,6 +866,48 @@ impl Uma {
}
}
+/// What the `coherent window:` line said last (`CoherentWatch::look`): the high-water and the
+/// refused per-draw blocks then.
+#[derive(Default)]
+pub struct CoherentWatch {
+ said: Option<(usize, u64)>,
+}
+
+impl CoherentWatch {
+ /// The coherent window's line (xcl-activity, every 2 s), when it is due: at the first look with a
+ /// window, then when its high-water rose 4 MiB or more since it was said, or when a per-draw block
+ /// was refused since – about 10-40 lines a run. `own`: XCL's part (`own_part`).
+ pub fn look(&mut self, u: &Uma, own: usize) -> Option {
+ let (now, most, full) = u.usage();
+ if self.said.is_some_and(|(m, f)| most < m + (4 << 20) && full == f) {
+ return None;
+ }
+ self.said = Some((most, full));
+ let (pool, pool_free) = u.pool_usage();
+ Some(coherent_line(now, most, u.size(), own, pool.saturating_sub(pool_free), pool, full))
+ }
+}
+
+/// The line `CoherentWatch::look` says. The use counts XCL's per-draw pool whole from the start (64
+/// MiB of a runtime window), as `bind`'s "coherent N/M MB" does: run 66's 139 MB is that figure.
+fn coherent_line(now: usize, most: usize, size: usize, own: usize, pool_used: usize, pool: usize, full: u64) -> String {
+ format!(
+ "coherent window: {} MB in use (its per-draw pool counted whole), {} MB at most so far, of {} MB (XCL's own part {} MB, XCL_COHERENT_OWN_MB); XCL's per-draw pool {} of {} MB in use; {full} per-draw blocks found no room so far (each a draw or dispatch skipped, or the title's middleware's upload memory taken from the sparse windows instead)",
+ now >> 20,
+ most >> 20,
+ size >> 20,
+ own >> 20,
+ pool_used >> 20,
+ pool >> 20
+ )
+}
+
+/// The title's graphics memory if it was made already (`get` makes it): for what only looks at it
+/// (xcl-activity), so that the window is never made off the title's own first call.
+pub fn made() -> Option<&'static Uma> {
+ GLOBAL.get().and_then(Option::as_ref)
+}
+
/// The title's graphics memory (created on first use; `XCL_UMA_MB`, default 2048).
pub fn get() -> Option<&'static Uma> {
GLOBAL
@@ -963,4 +1119,190 @@ mod tests {
// Contiguous sparse windows 0..2 are reported as one OS watch region; window 3 as another.
assert_eq!(u.watch_regions(), vec![(u.base(), 3 * WINDOW), (u.base() + 3 * WINDOW, 16 << 20)]);
}
+
+ /// XCL's own part of the coherent window (`own_part_for`): 256 MiB on a Mac (its copy in video
+ /// memory, wired while the GPU works), 512 elsewhere as before 0023.2; `XCL_COHERENT_OWN_MB` a
+ /// number of MiB raised to 64 and at most 4095 (`512`: a Mac's window before 0023.2), not a
+ /// number the default. This process's part as it was read.
+ #[test]
+ fn xcls_part_of_the_coherent_window_is_256_mb_on_a_mac_and_512_elsewhere() {
+ let mib = 1usize << 20;
+ assert_eq!(own_part_for(true, None), 256 * mib);
+ assert_eq!(own_part_for(false, None), 512 * mib, "off a Mac: as before 0023.2");
+ assert_eq!(own_part_for(true, Some("512")), 512 * mib, "the switch: a Mac's window before 0023.2");
+ assert_eq!(own_part_for(true, Some(" 384 ")), 384 * mib);
+ assert_eq!(own_part_for(true, Some("x")), 256 * mib);
+ assert_eq!(own_part_for(false, Some("")), 512 * mib);
+ assert_eq!(own_part_for(true, Some("16")), 64 * mib, "raised to 64");
+ assert_eq!(own_part_for(true, Some("0")), 64 * mib);
+ assert_eq!(own_part_for(false, Some("9000")), 4095 * mib, "at most 4095");
+ let env = std::env::var("XCL_COHERENT_OWN_MB").ok();
+ assert_eq!(own_part(), own_part_for(crate::util::mac_host(), env.as_deref()), "this process's part");
+ }
+
+ /// The window is the title's need and XCL's part (`coherent_hint_for`), never less than XCL's
+ /// part unless the whole layout is (`committed_for`): on a Mac XCL's 256 MB and the title's need
+ /// (run 66's window: 256 MB, none of the title's heaps there), 512 off a Mac; XCL_COHERENT_MB the
+ /// whole window, XCL's part its floor (on a Mac 256-511 now give that size; before 0023.2 512);
+ /// the title's heaps out for want of commit: XCL's part alone, with a warning.
+ #[test]
+ fn the_coherent_window_is_the_titles_need_plus_xcls_part_and_never_less() {
+ let mib = 1usize << 20;
+ let (mac, pc) = (own_part_for(true, None), own_part_for(false, None));
+ let plenty = usize::MAX;
+ assert_eq!(coherent_hint_for(None, 0, plenty, mac), (256 * mib, false));
+ assert_eq!(coherent_hint_for(None, 0, plenty, pc), (512 * mib, false));
+ assert_eq!(coherent_hint_for(None, 100 * mib, plenty, mac), (356 * mib, false), "the title's need and XCL's part");
+ assert_eq!(coherent_hint_for(None, 100 * mib, NEEDS_FOR_COHERENT_HEAPS - 1, mac), (256 * mib, true), "commit short: XCL's part alone");
+ assert_eq!(coherent_hint_for(None, 4 << 30, plenty, mac), (MAX_SIZE, false), "at most a window");
+ assert_eq!(coherent_hint_for(Some(128), 100 * mib, 0, mac), (128 * mib, false), "XCL_COHERENT_MB: its size, the file and the commit not asked");
+ assert_eq!(coherent_hint_for(Some(1024), 0, plenty, mac), (1024 * mib, false));
+ // the committed window of the runtime layout (`get`: XCL_UMA_MB or more, the hint)
+ let uma = 2048 * mib;
+ assert_eq!(committed_for(uma, 256 * mib, mac), 256 * mib, "a Mac: 256 MB (run 66: 512)");
+ assert_eq!(committed_for(uma, 512 * mib, pc), 512 * mib, "off a Mac: as before 0023.2");
+ assert_eq!(committed_for(uma, 128 * mib, mac), 256 * mib, "XCL_COHERENT_MB=128: XCL's part is its floor");
+ assert_eq!(committed_for(uma, 300 * mib, mac), 300 * mib, "XCL_COHERENT_MB=300 on a Mac: 300 (before 0023.2: 512)");
+ assert_eq!(committed_for(uma, 128 * mib, pc), 512 * mib);
+ assert_eq!(committed_for(uma, 1024 * mib, mac), 1024 * mib);
+ assert_eq!(committed_for(16 * mib, 256 * mib, mac), 16 * mib, "a smaller layout: all of it");
+ assert_eq!(committed_for(8 << 30, 8 << 30, mac), MAX_SIZE, "at most a window");
+ assert_eq!(committed_for(uma, 100 * mib + 1, 64 * mib), 100 * mib + GRAIN, "whole grains");
+ // the runtime layout as `get` makes it: XCL's part of this host (256 MiB on a Mac – this test
+ // process under the bottle's Wine –, 512 elsewhere), the title's need on top of it, and an
+ // XCL_COHERENT_MB below it raised to it
+ let own = own_part();
+ for (coherent, want, what) in [(own, own, "XCL's part alone"), (64 * mib, own, "XCL_COHERENT_MB=64: XCL's part is its floor"), (own + 32 * mib, own + 32 * mib, "a title's need of 32 MiB on top")] {
+ let u = Uma::for_runtime_with(uma, coherent).unwrap();
+ assert_eq!((u.size(), u.committed_window()), (want, Some(3)), "{what}");
+ // (XCL's pool: 64 MiB, a quarter of a window under 256 MiB)
+ let pool = POOL.min(want / 4) / ARENA_BLOCK * ARENA_BLOCK;
+ assert_eq!(u.pool_usage(), (pool, pool), "{what}: XCL's pool in it, all free");
+ }
+ }
+
+ /// A window's use now, its high-water and the per-draw blocks refused (`Uma::usage`): a runtime
+ /// window of its own of 4 MiB (pool 1 MiB, counted from the start); allocations and frees move
+ /// the use, the high-water stays; `Arena::take` until it finds no room counts each refusal, for a
+ /// block and for a large piece.
+ #[test]
+ fn the_windows_high_water_and_refused_blocks_are_counted() {
+ let mib = 1usize << 20;
+ let u = Uma::for_runtime(4 * mib).unwrap();
+ assert_eq!((u.size(), u.pool_usage()), (4 * mib, (mib, mib)), "4 MiB, a pool of a quarter of it, all free");
+ assert_eq!(u.usage(), (mib, mib, 0), "the pool counted whole from the start");
+ let a = u.alloc(mib, 0).unwrap() as usize;
+ assert_eq!(u.usage(), (2 * mib, 2 * mib, 0));
+ assert!(u.free(a));
+ assert_eq!(u.usage(), (mib, 2 * mib, 0), "a free lowers the use, the high-water stays");
+ let b = u.alloc(2 * mib, 0).unwrap() as usize;
+ assert_eq!(u.usage(), (3 * mib, 3 * mib, 0));
+ assert_eq!(u.usage().0, u.used(), "the use is `used`");
+ // per-draw blocks: the pool's 4, the window's last 1 MiB in 4 more, then no room
+ let mut blocks = Vec::new();
+ let mut taken = 0;
+ while Arena::default().take(&u, 64, 16, &mut blocks).is_some() {
+ taken += 1;
+ }
+ assert_eq!((taken, u.usage().2), (8, 1), "8 blocks, then one refused");
+ assert_eq!(u.pool_usage(), (mib, 0), "the pool all in use");
+ assert!(Arena::default().take(&u, 64, 16, &mut blocks).is_none());
+ assert!(Arena::default().take(&u, ARENA_BLOCK, 256, &mut blocks).is_none(), "a large piece with no room");
+ assert_eq!(u.usage().2, 3, "each refusal counted");
+ assert_eq!(u.usage().1, 4 * mib, "the high-water: the whole window");
+ for p in blocks {
+ assert!(u.free(p));
+ }
+ assert!(u.free(b));
+ assert_eq!(u.usage(), (mib, 4 * mib, 3), "the pool's blocks back in it, the rest freed");
+ assert_eq!(u.pool_usage(), (mib, mib));
+ }
+
+ /// The `coherent window:` line (`CoherentWatch::look`): said at the first look, then only when
+ /// the high-water rose 4 MiB or more since it was said or a per-draw block was refused since; its
+ /// text with the window's use, high-water, size, XCL's part and the pool.
+ #[test]
+ fn the_coherent_window_line_is_said_when_its_high_water_rose_or_a_block_was_refused() {
+ let mib = 1usize << 20;
+ let u = Uma::with_windows(1, 16 * mib).unwrap();
+ u.reserve_pool(4 * ARENA_BLOCK);
+ let mut w = CoherentWatch::default();
+ assert_eq!(
+ w.look(&u, 256 * mib).as_deref(),
+ Some("coherent window: 1 MB in use (its per-draw pool counted whole), 1 MB at most so far, of 16 MB (XCL's own part 256 MB, XCL_COHERENT_OWN_MB); XCL's per-draw pool 0 of 1 MB in use; 0 per-draw blocks found no room so far (each a draw or dispatch skipped, or the title's middleware's upload memory taken from the sparse windows instead)")
+ );
+ assert_eq!(w.look(&u, 256 * mib), None, "nothing moved");
+ assert_eq!(
+ coherent_line(3 * mib, 5 * mib, 16 * mib, 256 * mib, mib, 2 * mib, 7),
+ "coherent window: 3 MB in use (its per-draw pool counted whole), 5 MB at most so far, of 16 MB (XCL's own part 256 MB, XCL_COHERENT_OWN_MB); XCL's per-draw pool 1 of 2 MB in use; 7 per-draw blocks found no room so far (each a draw or dispatch skipped, or the title's middleware's upload memory taken from the sparse windows instead)",
+ "each field in its place"
+ );
+ let a = u.alloc(3 * mib, 0).unwrap() as usize;
+ assert_eq!(w.look(&u, 256 * mib), None, "3 MiB higher: not yet");
+ let b = u.alloc(mib, 0).unwrap() as usize;
+ assert!(w.look(&u, 256 * mib).is_some_and(|l| l.starts_with("coherent window: 5 MB in use (its per-draw pool counted whole), 5 MB at most so far, of 16 MB")), "4 MiB higher");
+ assert!(u.free(a) && u.free(b));
+ assert_eq!(w.look(&u, 256 * mib), None, "lower: nothing");
+ // the pool used up and the rest of the window taken: a refused block
+ let mut blocks = Vec::new();
+ while let Some(p) = u.alloc(GRAIN, GRAIN) {
+ blocks.push(p as usize);
+ }
+ let mut arena = Vec::new();
+ while Arena::default().take(&u, 64, 16, &mut arena).is_some() {}
+ let l = w.look(&u, 256 * mib).expect("a refused block, and the window full");
+ assert!(l.contains("16 MB at most so far, of 16 MB") && l.contains("XCL's per-draw pool 1 of 1 MB in use; 1 per-draw blocks found no room so far"), "{l}");
+ assert_eq!(w.look(&u, 256 * mib), None);
+ assert!(Arena::default().take(&u, 64, 16, &mut arena).is_none());
+ assert!(w.look(&u, 256 * mib).is_some_and(|l| l.contains("; 2 per-draw blocks found no room so far")), "refused again");
+ for p in blocks.into_iter().chain(arena) {
+ assert!(u.free(p));
+ }
+ }
+
+ /// C-F4: with XCL_TRACE_MEM a failed window allocation is traced for the first 16, then the 32nd,
+ /// 64th, … – not one line per refused per-draw block of a full window.
+ #[test]
+ fn failed_window_allocations_are_traced_at_a_bounded_rate() {
+ let traced: Vec = (1..=600).filter(|&k| failure_traced(k)).collect();
+ assert_eq!(traced, (1..=16).chain([32, 64, 128, 256, 512]).collect::>());
+ assert!(failure_traced(1 << 40) && !failure_traced((1 << 40) + 1));
+ assert!(!failure_traced(17) && !failure_traced(31) && !failure_traced(33));
+ }
+
+ /// C-F4's wiring and text (step Fm's open issue: no test set XCL_TRACE_MEM): with it (a process of
+ /// its own, `EXTRA_ENV=XCL_TRACE_MEM=1`) a window allocation that finds no room is traced at the
+ /// failures `failure_traced` takes – the first 16, then the 32nd, 64th, … –, each line HEAD's
+ /// with " – {k} failures so far" appended; without it none is said and none counted. On a unified
+ /// memory of the test's own (one 16 MiB window, no arena pool): 40 refusals on this thread, its
+ /// lines (`log::kept`), the count from where it stood – the exact lines when no other thread
+ /// counted meanwhile (in a process of its own, always so).
+ #[test]
+ fn failed_window_allocations_are_traced_with_their_count_only_with_xcl_trace_mem() {
+ let u = Uma::with_windows(1, 16 << 20).unwrap();
+ let k0 = TRACED_FAILURES.load(Ordering::Relaxed);
+ let kept = crate::log::kept::keep();
+ for _ in 0..40 {
+ assert!(u.alloc(32 << 20, 0).is_none(), "no room");
+ }
+ let lines: Vec = kept.take().into_iter().filter(|l| l.starts_with("UMA: ")).collect();
+ drop(kept);
+ let k1 = TRACED_FAILURES.load(Ordering::Relaxed);
+ if !Uma::tracing() {
+ assert!(lines.is_empty(), "{lines:#?}");
+ assert_eq!(k1, k0, "not counted without XCL_TRACE_MEM");
+ return;
+ }
+ let ks: Vec = lines
+ .iter()
+ .map(|l| {
+ assert!(l.starts_with("UMA: 32768 KB for ") && l.contains("uma.rs:") && l.contains(" – no room (0 MB used) – "), "HEAD's line, the count after it: {l}");
+ l.strip_suffix(" failures so far").and_then(|s| s.rsplit(' ').next()).and_then(|k| k.parse().ok()).unwrap_or_else(|| panic!("the count at the end: {l}"))
+ })
+ .collect();
+ assert!(ks.iter().all(|&k| k0 < k && k <= k1 && failure_traced(k)), "{ks:?} in {k0}..={k1}");
+ if k1 - k0 == 40 {
+ assert_eq!(ks, (k0 + 1..=k0 + 40).filter(|&k| failure_traced(k)).collect::>(), "each traced failure said once, in order");
+ }
+ }
}
diff --git a/crates/xcl/src/hle/bcpack/tables.rs b/crates/xcl/src/hle/bcpack/tables.rs
index 5b5cd3d..cd1ced8 100644
--- a/crates/xcl/src/hle/bcpack/tables.rs
+++ b/crates/xcl/src/hle/bcpack/tables.rs
@@ -1438,7 +1438,7 @@ pub static BC6: [(Bc6Ep, Bc6Ix); DICTIONARY] = [
(Bc6Ep { e: [[45056, 40960, 38400], [0, 38912, 45056], [29696, 37888, 36864], [12288, 26624, 45056]] }, Bc6Ix { mode: 8, ix: [-4, 3, -2, -3, -2, 0, -3, -3, 1, -2, -4, -3, 2, -3, -3, -3] }),
];
pub static BC7: [(Bc7Ep, Bc7Ix); DICTIONARY] = [
- (Bc7Ep { ctrl: 0, rows: [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] }, Bc7Ix { bits: [4, 0], ix: [[2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] }),
+ (Bc7Ep { ctrl: 0, rows: [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] }, Bc7Ix { bits: [4, 0], ix: [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] }),
(Bc7Ep { ctrl: 1, rows: [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] }, Bc7Ix { bits: [3, 0], ix: [[1, 0, 0, 0, 0, 0, -1, -1, 0, -1, 0, 0, 0, -1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] }),
(Bc7Ep { ctrl: 4, rows: [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] }, Bc7Ix { bits: [4, 0], ix: [[4, 5, 3, 4, 4, 4, 4, 3, 4, 4, 5, 4, 5, 4, 4, 4], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] }),
(Bc7Ep { ctrl: 5, rows: [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] }, Bc7Ix { bits: [4, 0], ix: [[2, -2, -4, -2, 3, -2, -4, -2, -2, 1, -4, -3, -2, -1, -4, -3], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] }),
diff --git a/crates/xcl/src/hle/bcpack/tests.rs b/crates/xcl/src/hle/bcpack/tests.rs
index 70c425a..ccfaf23 100644
--- a/crates/xcl/src/hle/bcpack/tests.rs
+++ b/crates/xcl/src/hle/bcpack/tests.rs
@@ -103,14 +103,17 @@ fn junk_streams_do_not_panic() {
}
/// The BC7 dictionary indices follow VIctory PR #658: 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.
+/// indices, and pixel 0 is the anchor (top bit clear). Entry 0 is read like the other 254:
+/// every BC7 record of `bcpack-tables.bin` is 116 bytes, and the u16 after the two widths is
+/// skipped in all of them (in entry 0 it is 2, not its widths). So entry 0's first indices are
+/// `[1, 0, ...]`, as `scripts/gen_bcpack_victory_tables.py` writes them; reading that u16 as
+/// an index instead would make them `[2, 1, 0, ...]`.
#[test]
fn bc7_dictionary_indices_line_up() {
let (ep0, ix0) = super::tables::BC7[0];
assert_eq!(ep0.ctrl, 0);
assert_eq!(ix0.bits, [4, 0]);
- assert_eq!(ix0.ix[0], [2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+ assert_eq!(ix0.ix[0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
assert_eq!(ix0.ix[1], [0; 16]);
for (k, (_, ix)) in super::tables::BC7.iter().enumerate() {
assert!(ix.bits[0] > 0, "entry {k}: the first index set has no bits");
diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs
index 6fd8cb2..ece2296 100644
--- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs
+++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs
@@ -315,6 +315,12 @@ mod tests {
drop(lists);
drop(list);
drop(alloc);
+ // (where its last Release is held until the queues are past its work, nothing of it
+ // goes before that – `late_release`)
+ let t = std::time::Instant::now();
+ while current(a as usize) != a as usize && t.elapsed().as_secs() < 10 {
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
assert_eq!(current(a as usize), a as usize, "a released allocator leaves nothing behind");
assert!(!STATE.lock().unwrap().as_ref().unwrap().types.contains_key(&(a as usize)));
}
diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs
index 7b997d0..aff8250 100644
--- a/crates/xcl/src/hle/d3d12x/bind.rs
+++ b/crates/xcl/src/hle/d3d12x/bind.rs
@@ -10,7 +10,7 @@
use std::collections::HashMap;
use std::ffi::c_void;
-use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use windows::core::Interface;
@@ -37,6 +37,11 @@ struct State {
arena: crate::gpu::uma::Arena,
res_buf: Option<(ID3D12Resource, u64, usize)>,
res_retired: Vec<(ID3D12Resource, u64, usize)>,
+ /// the `res` blocks (unified memory) of this recording's translated compute dispatches
+ /// (`res_block`): given a new serial and a count of 0 when the recording runs again
+ res_blocks: Vec,
+ /// this recording was submitted (`before_submit`)
+ submitted: bool,
}
static ALLOC_RES: Mutex>>> = Mutex::new(None);
@@ -76,6 +81,12 @@ const DISPATCHES: usize = 3;
const DISPATCHES_SKIPPED: usize = 4;
fn count(k: usize) {
+ #[cfg(test)]
+ MY_COUNTS.with(|c| {
+ let mut v = c.get();
+ v[k] += 1;
+ c.set(v);
+ });
let n = COUNTS[k].fetch_add(1, Ordering::Relaxed) + 1;
if n.is_power_of_two() && n >= 64 {
let c: Vec = COUNTS.iter().map(|c| c.load(Ordering::Relaxed)).collect();
@@ -89,6 +100,155 @@ fn count(k: usize) {
}
}
+/// Why a pipeline must not reach the PC (`unbuilt`).
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+enum Unbuilt {
+ /// a stand-in whose real pipeline was not there when the bind resolved it (a build that ended
+ /// just after, or one no bind waited for)
+ Building,
+ /// … still being built while binds go on without it (`pso_async`: past its wait, the big lane)
+ Late,
+ /// a stand-in whose build failed or was refused (`XCL_PSO_MAX_DXIL_KB`, `XCL_NO_BUILD_CS`)
+ Failed,
+ /// a pipeline of XCL's fallback shaders (`real::fallback_kind`)
+ Fallback,
+}
+
+impl Unbuilt {
+ fn describe(self) -> &'static str {
+ match self {
+ Unbuilt::Building => "its pipeline was still being built when this was recorded",
+ Unbuilt::Late => "its pipeline is late: still being built while binds go on without it",
+ Unbuilt::Failed => "its pipeline's build failed or was refused",
+ Unbuilt::Fallback => "XCL's fallback shaders stand in for shaders without a translation",
+ }
+ }
+}
+
+/// work skipped because its pipeline was not built or is a fallback (`skip_unbuilt`), by where
+/// (`pso_async::note_skip` is told of the same skips less those of fallbacks)
+static UNBUILT: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5];
+const U_DISPATCH: usize = 0;
+const U_INDIRECT_COMPUTE: usize = 1;
+const U_INDIRECT_DRAW: usize = 2;
+const U_DISPATCH_MESH: usize = 3;
+const U_DRAW: usize = 4;
+const U_WHERE: [&str; 5] = ["Dispatch", "ExecuteIndirect (compute)", "ExecuteIndirect (draws)", "DispatchMesh", "draw"];
+
+/// `XCL_STANDIN_SKIP=0`: ExecuteIndirect and DispatchMesh hold back only a stand-in whose build is
+/// not over, as before 0023 – a failed or refused one, and a pipeline of XCL's fallback shaders, go
+/// to the PC with the title's arguments and whatever root signature the list holds (the invalid
+/// pair of `execute_indirect`'s note). For bisecting only: with group A's refusals it is that call.
+fn standin_skip_on() -> bool {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ *ON.get_or_init(|| {
+ let on = std::env::var("XCL_STANDIN_SKIP").map_or(true, |v| v.trim() != "0");
+ if !on {
+ crate::xlog_warn!("XCL_STANDIN_SKIP=0: ExecuteIndirect and DispatchMesh of a stand-in whose build failed or was refused, or of XCL's fallback shaders, go to the PC as before 0023 – a root signature that does not match the pipeline");
+ }
+ on
+ })
+}
+
+/// `XCL_STANDIN_SKIP_DRAWS=0`: a draw with a stand-in whose pipeline is not built, or with XCL's
+/// fallback shaders, is drawn with them and counted with the PC pipelines, as before 0023 (they
+/// draw nothing; a point list one magenta pixel at the centre).
+fn standin_skip_draws_on() -> bool {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var("XCL_STANDIN_SKIP_DRAWS").map_or(true, |v| v.trim() != "0"))
+}
+
+/// Why `raw`, resolved to `resolved` (`pso_async::resolve_wait`), must not go to the PC, and whether
+/// it computes. A stand-in the bind still holds – `resolved == raw`: its real pipeline was not there
+/// when it was resolved; a build that ends between the two looks must not send the stand-in – or a
+/// pipeline of XCL's fallback shaders. None: a real pipeline, or the title's own PC pipeline.
+fn unbuilt(raw: usize, resolved: usize) -> Option<(Unbuilt, bool)> {
+ if resolved == raw {
+ if let Some(s) = super::pso_async::standin_state(raw) {
+ let why = if s.late && !s.done {
+ Unbuilt::Late
+ } else if s.done && !s.built {
+ Unbuilt::Failed
+ } else {
+ Unbuilt::Building
+ };
+ return Some((why, s.compute));
+ }
+ }
+ super::real::fallback_kind(resolved).map(|compute| (Unbuilt::Fallback, compute))
+}
+
+/// The gate of ExecuteIndirect and DispatchMesh (`XCL_STANDIN_SKIP=0`: only a stand-in whose
+/// build is not over, as `is_pending` did).
+fn held_back(raw: usize, resolved: usize) -> Option<(Unbuilt, bool)> {
+ if standin_skip_on() {
+ return unbuilt(raw, resolved);
+ }
+ super::pso_async::standin_state(raw).filter(|s| !s.done).map(|s| (if s.late { Unbuilt::Late } else { Unbuilt::Building }, s.compute))
+}
+
+#[cfg(test)]
+thread_local! {
+ /// (tests) this thread's last skip: (pipeline, where, why)
+ static LAST_UNBUILT: std::cell::Cell> = const { std::cell::Cell::new(None) };
+ /// (tests) `COUNTS` of this thread's binds: the suite runs on 6 threads, and exact deltas of the
+ /// process's counts race
+ static MY_COUNTS: std::cell::Cell<[u64; 5]> = const { std::cell::Cell::new([0; 5]) };
+}
+
+#[cfg(test)]
+fn take_last_unbuilt() -> Option<(usize, usize, Unbuilt)> {
+ LAST_UNBUILT.with(|c| c.take())
+}
+
+/// Work with `raw` (`why`) skipped at `at`: counted (`UNBUILT`, and the dispatches or draws
+/// skipped), a stand-in's skip told to `pso_async` (its program's tally – at every place, never
+/// for a fallback), the first 8 of each place and then every 2^k-th logged.
+fn skip_unbuilt(at: usize, raw: usize, why: Unbuilt) {
+ UNBUILT[at].fetch_add(1, Ordering::Relaxed);
+ count(if matches!(at, U_DISPATCH | U_INDIRECT_COMPUTE) { DISPATCHES_SKIPPED } else { DRAWS_SKIPPED });
+ if why != Unbuilt::Fallback {
+ super::pso_async::note_skip(raw);
+ }
+ #[cfg(test)]
+ LAST_UNBUILT.with(|c| c.set(Some((raw, at, why))));
+ static LOGGED: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5];
+ let n = LOGGED[at].fetch_add(1, Ordering::Relaxed) + 1;
+ if n <= 8 || n.is_power_of_two() {
+ let u: [u64; 5] = std::array::from_fn(|k| UNBUILT[k].load(Ordering::Relaxed));
+ crate::xlog_warn!(
+ "D3D12.X: {} with the pipeline {raw:#x} skipped – {} (#{n} there; so far {} Dispatch, {} compute and {} draw ExecuteIndirect, {} DispatchMesh, {} draws)",
+ U_WHERE[at], why.describe(), u[0], u[1], u[2], u[3], u[4]
+ );
+ }
+}
+
+/// (`XCL_ACTIVITY`) ExecuteIndirect of translated pipelines recorded so far, by where their
+/// arguments were and what became of them (`indirect::census`), and the work skipped for a
+/// pipeline not built (`skip_unbuilt`). None: nothing counted, or nothing new since the last line.
+pub fn indirect_line() -> Option {
+ // (the counts at the last call, the draws checked then: the activity thread calls this every 2 s)
+ static LAST: Mutex<(u64, u64)> = Mutex::new((0, 0));
+ let c = indirect::census_snapshot();
+ let u: [u64; 5] = std::array::from_fn(|k| UNBUILT[k].load(Ordering::Relaxed));
+ let sum = c.sum() + u.iter().sum::();
+ let checked = c.checked_draws();
+ let (last_sum, last_checked) = std::mem::replace(&mut *LAST.lock().unwrap_or_else(|e| e.into_inner()), (sum, checked));
+ if sum == 0 || sum == last_sum {
+ return None;
+ }
+ let census = if indirect::census_on() { c.text(checked.saturating_sub(last_checked)) } else { "not counted (XCL_INDIRECT_CENSUS=0)".to_string() };
+ Some(indirect_line_text(&census, &u))
+}
+
+/// The line itself (what run 65's tools read).
+fn indirect_line_text(census: &str, u: &[u64; 5]) -> String {
+ format!(
+ "ExecuteIndirect recorded so far: {census}; work skipped for a pipeline not built: {} Dispatch, {} compute and {} draw ExecuteIndirect, {} DispatchMesh, {} draws",
+ u[0], u[1], u[2], u[3], u[4]
+ )
+}
+
fn with(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R {
f(STATES.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default())
}
@@ -111,6 +271,8 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) {
s.layout_gfx = None;
s.args_gfx.clear();
s.rs_gfx = 0;
+ s.res_blocks.clear();
+ s.submitted = false;
let mut res_bufs = std::mem::take(&mut s.res_retired);
if let Some(b) = s.res_buf.take() {
res_bufs.push(b);
@@ -119,6 +281,7 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) {
});
console_list::hold_until_reset(old, blocks);
hold_res_until_reset(old, res_bufs);
+ super::stall::list_reset(list);
}
/// `ClearState(pso)`: resets pipeline and root-argument state back to creation defaults
@@ -155,6 +318,8 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u
s.args_gfx = args_gfx;
s.rs_gfx = rs_gfx;
s.pso = pso;
+ s.res_blocks.clear();
+ s.submitted = false;
let mut res_bufs = std::mem::take(&mut s.res_retired);
if let Some(b) = s.res_buf.take() {
res_bufs.push(b);
@@ -163,6 +328,7 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u
});
console_list::hold_until_reset(old, blocks);
hold_res_until_reset(old, res_bufs);
+ super::stall::list_reset(to);
}
/// Kickoff can move a list to another backing without going through the bind Reset hook.
@@ -174,6 +340,8 @@ fn sync_recording_backing(list: *mut c_void) {
}
let old = std::mem::replace(&mut s.allocator, backing);
s.arena = Default::default();
+ s.res_blocks.clear();
+ s.submitted = false;
let mut res = std::mem::take(&mut s.res_retired);
res.extend(s.res_buf.take());
Some((old, std::mem::take(&mut s.uma), res))
@@ -194,6 +362,36 @@ pub(super) fn forget(list: *mut c_void) {
}
hold_res_until_reset(s.allocator, s.res_retired);
}
+ super::stall::list_reset(list);
+}
+
+/// `lists` are about to be submitted – before XCL sends the CPU's writes to video memory
+/// (`title_textures::refresh`). A recording submitted before runs again: its compute `res`
+/// blocks get a count of 0 and a new serial on the CPU, so the upload clears what the GPU
+/// counted in its last run (`res_block`).
+pub(super) fn before_submit(lists: &[*mut c_void]) {
+ let mut g = STATES.lock().unwrap();
+ let Some(m) = g.as_mut() else { return };
+ for &l in lists {
+ let Some(s) = m.get_mut(&(l as usize)) else { continue };
+ if !s.submitted {
+ s.submitted = true;
+ continue;
+ }
+ for &p in &s.res_blocks {
+ // (XCL's own block in unified memory, held until the recording's allocator is reset)
+ unsafe { std::ptr::write_volatile(p as *mut [u32; 2], [0, next_res_serial()]) };
+ }
+ }
+}
+
+/// KickoffX submitted `list` and reset it on the PC: it records anew.
+pub(super) fn kicked_off(list: *mut c_void) {
+ with(list, |s| {
+ s.res_blocks.clear();
+ s.submitted = false;
+ });
+ super::stall::list_reset(list);
}
#[cfg(test)]
@@ -634,8 +832,10 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y:
}
return;
}
- if super::pso_async::is_pending(raw_pso) {
- count(DRAWS_SKIPPED);
+ // a stand-in whose pipeline is not built, or XCL's fallback: its dummy mesh shader draws
+ // nothing, with a root signature the list may not hold (`unbuilt`)
+ if let Some((why, _)) = held_back(raw_pso, pso) {
+ skip_unbuilt(U_DISPATCH_MESH, raw_pso, why);
return;
}
let rs = with(this, |s| s.rs_gfx) as *mut c_void;
@@ -649,12 +849,16 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y:
/// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a
/// translated pipeline, on XCL's ABI with the kept root arguments and any per-command updates.
pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) {
+ let _xcl_api = crate::waitwatch::api("bind::execute_indirect");
type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64);
let pc: F = std::mem::transmute(super::real::orig_fn(this, 59));
let raw_pso = with(this, |s| s.pso);
let pso = super::pso_async::resolve_wait(raw_pso);
let args_pc_off = args_off + super::real::buffer_delta(args);
- let count_off = count_off + super::real::buffer_delta(count_buf);
+ // the count's offset as the title gave it, and as the PC's ExecuteIndirect takes it (`count_off`:
+ // from offset 0 of the buffer's PC resource, `buffer_delta`)
+ let count_title_off = count_off;
+ let count_off = count_title_off + super::real::buffer_delta(count_buf);
let mac = crate::util::mac_host();
if let Some(tp) = mac.then(|| super::real::two_pass_of(pso)).flatten() {
@@ -721,20 +925,30 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us
let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso));
if !gfx && !compute {
- // A pipeline still being built (or whose build failed): its stand-in draws nothing, and
- // the list may hold XCL's ABI root signature from a translated draw before it – the PC
- // call with that pair is invalid (debug layer 953, "the currently set Root Signature
- // doesn't match the currently set Pipeline State Object"; a retail title's world then
- // hung the GPU, 0x887a0006). Skipped, like a draw or dispatch of such a pipeline.
- if super::pso_async::is_pending(raw_pso) {
- count(DRAWS_SKIPPED);
- static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
- if N.fetch_add(1, Ordering::Relaxed) < 4 {
- crate::xlog_warn!("D3D12.X: ExecuteIndirect with a pipeline that is still being built skipped");
+ // A stand-in whose pipeline is not built – still being built, late, failed or refused
+ // (`pso_async`) – or a pipeline of XCL's fallback shaders. It draws and computes nothing,
+ // and the list may hold XCL's ABI root signature from a translated draw or dispatch before
+ // it: the PC call with that pair is invalid (debug layer 953, "the currently set Root
+ // Signature doesn't match the currently set Pipeline State Object"; a retail title's world
+ // then hung the GPU, 0x887a0006), with the title's arguments unchecked. A compute one never
+ // has the title's compute root signature on the PC list at all (it stays here:
+ // `set_compute_root_signature`). Skipped, like a draw or dispatch of such a pipeline.
+ if let Some((why, computes)) = held_back(raw_pso, pso) {
+ let at = if dispatch_mesh_stride(sig).is_some() {
+ U_DISPATCH_MESH
+ } else if computes {
+ U_INDIRECT_COMPUTE
+ } else {
+ U_INDIRECT_DRAW
+ };
+ if at == U_INDIRECT_COMPUTE {
+ let call = super::skip_roots::Call::Indirect { sig, max, args: (args, args_off), count: (count_buf, count_title_off) };
+ skipped_unbuilt_roots(this, raw_pso, why, call);
}
+ skip_unbuilt(at, raw_pso, why);
return;
}
- // a PC pipeline: the title's root signature, as for a draw (`graphics_bound`)
+ // a PC pipeline (the title's own shaders): the title's root signature, as for a draw (`graphics_bound`)
let rs = with(this, |s| s.rs_gfx) as *mut c_void;
if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) {
list.SetGraphicsRootSignature(r);
@@ -750,40 +964,123 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us
return;
}
let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return };
+ let (hash, threads) = if compute { super::real::pso_console_cs(pso).unwrap_or((0, 0)) } else { (0, 0) };
+ // (the title's arguments and count as it gave them: `[indirect]` and XCL_SKIP_CS's root views
+ // name their addresses)
+ let at = ArgsAt { args: (args, args_off), count: (count_buf, count_title_off) };
+ if compute && skip_cs(this, hash, threads, super::skip_roots::Call::Indirect { sig, max, args: at.args, count: at.count }) {
+ return;
+ }
+ // where the arguments are – for every translated ExecuteIndirect while anything counts or checks
+ // them (the census, the draw check, XCL_INDIRECT_OWN, the lists' counts by place –
+ // `stall::indirect_on`); else compute and the draws `[indirect]` still logs, as before 0023
+ let place = if compute || indirect::census_on() || indirect::draw_check_on() || indirect::own_skip() || super::stall::indirect_on() || note_indirect_draws() {
+ indirect::classify(args, args_off)
+ } else {
+ super::stall::Args::Unknown
+ };
+ if count_buf != 0 && indirect::census_on() {
+ indirect::census_count_buffer(gfx, indirect::classify(count_buf, count_title_off));
+ }
+ let key = if compute { hash } else { pso as u64 };
+ // `XCL_INDIRECT_OWN=skip`: arguments in a PC resource of their own – which no translated
+ // program and no CPU write of the title reaches – are not recorded (nor counted for the list)
+ if place == super::stall::Args::Own && indirect::own_skip() {
+ indirect::census(gfx, place, indirect::Fate::SkippedOwn);
+ note_indirect_args(gfx, key, place, at, max, false, Some(&"XCL_INDIRECT_OWN=skip".to_string()));
+ count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED });
+ return;
+ }
+ let mut checked = false;
let result = match mac.then(|| indirect::lookup(sig)).flatten() {
Some(Some(signature)) => {
sync_recording_backing(this);
let allocator = with(this, |s| s.allocator);
if allocator == 0 {
- return;
- }
- let repack = indirect::Repack { signature: &signature, resource: args, offset: args_off, max, gfx };
- bind_abi_before(this, list, pso, gfx, |layout, inline, shadow, io, root| {
- let u = crate::gpu::uma::get().ok_or("no unified memory")?;
- repack.record(list, root, layout.ok_or("no bound console root layout")?, inline, shadow, io, |size| {
- with(this, |s| s.arena.take(u, size, 16, &mut s.uma)).map(|p| p as usize)
+ // (nothing is recorded either way: counted and named like the other refusals)
+ Err("no allocator for the repacked arguments".to_string())
+ } else {
+ let repack = indirect::Repack { signature: &signature, resource: args, offset: args_off, max, gfx };
+ // (the repacker drops a dispatch command with absurd group counts – `groups_ok`)
+ checked = compute && indirect::sanitize_on();
+ bind_abi_before(this, list, pso, gfx, |layout, inline, shadow, io, root| {
+ let u = crate::gpu::uma::get().ok_or("no unified memory")?;
+ repack.record(list, root, layout.ok_or("no bound console root layout")?, inline, shadow, io, |size| {
+ with(this, |s| s.arena.take(u, size, 16, &mut s.uma)).map(|p| p as usize)
+ })
+ }).map(|packed| {
+ let offset = packed.bind_arguments(list);
+ fresh_indirect_arguments(this, || {
+ pc(this, packed.signature.as_raw() as usize, max, packed.arguments.as_raw() as usize, offset, count_buf, count_off);
+ });
+ packed.finish_gpu(list);
+ with(this, |s| {
+ let shadow = if gfx { &mut s.args_gfx } else { &mut s.args };
+ packed.retain_and_clear(s.allocator, shadow);
+ });
+ if offset == 0 { "indirect repacked" } else { "indirect repacked single dispatch" }
})
- }).map(|packed| {
- let offset = packed.bind_arguments(list);
- fresh_indirect_arguments(this, || {
- pc(this, packed.signature.as_raw() as usize, max, packed.arguments.as_raw() as usize, offset, count_buf, count_off);
- });
- packed.finish_gpu(list);
- with(this, |s| {
- let shadow = if gfx { &mut s.args_gfx } else { &mut s.args };
- packed.retain_and_clear(s.allocator, shadow);
- });
- if offset == 0 { "indirect repacked" } else { "indirect repacked single dispatch" }
- })
+ }
}
Some(None) => Err("unsupported root-changing command signature".into()),
- None => bind_abi(this, list, pso, gfx).map(|()| {
- fresh_indirect_arguments(this, || {
- pc(this, sig, max, args, args_pc_off, count_buf, count_off);
- });
- "indirect direct arguments"
- }),
+ None => {
+ let check = if !mac || max == 0 {
+ None
+ } else if compute {
+ // a dispatch signature: the group counts checked on the GPU first (`indirect::Sanitize`)
+ indirect::sanitize_on().then(|| indirect::plain_dispatch(sig)).flatten().map(|stride| (stride, indirect::Command::Dispatch))
+ } else {
+ // a draw signature with its arguments outside unified memory or in a resource XCL does
+ // not know (once work was skipped, or `all`: anywhere): its commands checked on the GPU first
+ indirect::draw_check(place, sig, || bound_indices(this))
+ };
+ // the title's arguments as they are, after the writes before them (`fresh_indirect_arguments`)
+ let direct = || {
+ bind_abi(this, list, pso, gfx).map(|()| {
+ fresh_indirect_arguments(this, || {
+ pc(this, sig, max, args, args_pc_off, count_buf, count_off);
+ });
+ "indirect direct arguments"
+ })
+ };
+ // (not in a bundle: barriers are not allowed there)
+ match check.filter(|_| list.GetType() != D3D12_COMMAND_LIST_TYPE_BUNDLE) {
+ // (XCL's checked copy is a buffer of its own, in INDIRECT_ARGUMENT after the check)
+ Some((stride, cmd)) => match checked_execute_indirect(this, list, pso, gfx, cmd, stride, max, args, args_off, count_buf, count_off, pc) {
+ Ok(()) => {
+ checked = true;
+ if gfx {
+ // (the check's SetPipelineState moved list_x's key off the title's
+ // pipeline: depth bias and splits look it up by that key)
+ super::list_x::on_set_pipeline_state(this, raw_pso);
+ }
+ Ok("indirect checked arguments")
+ }
+ Err(e) => {
+ unchecked_warning(gfx, hash, pso, &e);
+ direct()
+ }
+ },
+ None => direct(),
+ }
+ }
};
+ let checked = checked && result.is_ok();
+ indirect::census(gfx, place, match (&result, checked) {
+ (Err(_), _) => indirect::Fate::Failed,
+ (Ok(_), true) => indirect::Fate::Checked,
+ (Ok(_), false) => indirect::Fate::AsIs,
+ });
+ note_indirect_args(gfx, key, place, at, max, checked, result.as_ref().err());
+ // a draw's: counted for its list as recorded, and as run with each submission of the list
+ // (compute's are counted with their record – `stall::note`)
+ if gfx && result.is_ok() {
+ super::stall::note_indirect_draw(this, place);
+ }
+ if compute && result.is_ok() {
+ super::stall::count_indirect(checked);
+ super::stall::note(this, super::stall::Rec { hash, threads, what: super::stall::What::Indirect { max, args: place, checked, count: count_buf != 0 } });
+ }
match result {
Ok(kind) => {
super::list_x::note_stall_work(this, kind, pso, [args as u64, count_buf as u64, max.into()]);
@@ -799,6 +1096,129 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us
}
}
+/// The PC's ExecuteIndirect (#59).
+type ExecuteIndirectFn = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64);
+
+/// A translated pipeline's per-dispatch block `res` (u1). Compute: word 0 counts the waves whose
+/// loop budget ran out (`xcl_budget_spent` – 0 here), word 1 is a serial of the dispatch (the
+/// windows upload a chunk only when its bytes changed: without it a count the GPU left at this
+/// address would carry over to the next dispatch there; a recording run again gets new ones –
+/// `before_submit`), word 2 how many such waves a dispatch has before its later ones skip their
+/// loops (`emit::budget_trip_waves`). One block serves all the commands of an ExecuteIndirect,
+/// and a bundle's dispatch in all its runs (bundles and lists of console code –
+/// `XCL_CONSOLE_LISTS=1` – get no fresh blocks when they run again). Graphics: zeros, as before.
+pub(super) fn res_block(gfx: bool) -> [u8; 256] {
+ let mut b = [0u8; 256];
+ if !gfx {
+ b[4..8].copy_from_slice(&next_res_serial().to_le_bytes());
+ b[8..12].copy_from_slice(&crate::gpu::recomp::emit::budget_trip_waves().to_le_bytes());
+ }
+ b
+}
+
+/// A serial for a compute `res` block (never 0).
+fn next_res_serial() -> u32 {
+ static SERIAL: AtomicU64 = AtomicU64::new(0);
+ ((SERIAL.fetch_add(1, Ordering::Relaxed) + 1) as u32).max(1)
+}
+
+/// ExecuteIndirect of a translated pipeline with a plain signature of `stride` bytes and one
+/// DISPATCH, DRAW or DRAW_INDEXED argument (`cmd`): XCL's pass copies the commands to a buffer of its
+/// own, the absurd ones made 0 (`indirect::Sanitize`), and the ExecuteIndirect reads them there.
+/// Err: nothing was recorded (the caller passes the title's arguments as they are).
+#[allow(clippy::too_many_arguments)]
+unsafe fn checked_execute_indirect(
+ this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool, cmd: indirect::Command, stride: u32, max: u32,
+ args: usize, args_off: u64, count_buf: usize, count_off: u64, pc: ExecuteIndirectFn,
+) -> Result<(), String> {
+ sync_recording_backing(this);
+ let allocator = with(this, |s| s.allocator);
+ if allocator == 0 {
+ return Err("no allocator for the checked arguments".into());
+ }
+ // (made before anything is recorded: a failure leaves the list as it was)
+ let prepared = indirect::Sanitize::prepare_command(list, allocator, args, args_off, stride, max, cmd)?;
+ // (a draw's check is a compute pass: the draw's own root signature, root UAVs and pipeline are
+ // bound after it, the pipeline last)
+ let checked = bind_abi_before(this, list, pso, gfx, |_, _, _, _, _| Ok(prepared.record(list)))?;
+ pc(this, checked.signature.as_raw() as usize, max, checked.buffer.as_raw() as usize, checked.offset, count_buf, count_off);
+ checked.finish(list);
+ Ok(())
+}
+
+/// A compute or draw ExecuteIndirect whose check could not be made (the first 8 of each).
+fn unchecked_warning(gfx: bool, hash: u64, pso: usize, e: &str) {
+ static N: [std::sync::atomic::AtomicU32; 2] = [const { std::sync::atomic::AtomicU32::new(0) }; 2];
+ if N[gfx as usize].fetch_add(1, Ordering::Relaxed) < 8 {
+ if gfx {
+ crate::xlog_warn!("D3D12.X: ExecuteIndirect of a draw (pipeline {pso:#x}): its arguments are not checked ({e}) – the title's arguments go to the GPU as they are");
+ } else {
+ crate::xlog_warn!("D3D12.X: ExecuteIndirect of {hash:016x}: its group counts are not checked ({e}) – the title's arguments go to the GPU as they are");
+ }
+ }
+}
+
+/// Indices the index buffer bound on `list` holds (u32::MAX: none XCL knows – the check does not
+/// look at the index range then).
+unsafe fn bound_indices(list: *mut c_void) -> u32 {
+ use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R32_UINT};
+ match super::list_x::bound_index_buffer(list) {
+ Some(v) if v.Format == DXGI_FORMAT_R32_UINT => v.SizeInBytes / 4,
+ Some(v) if v.Format == DXGI_FORMAT_R16_UINT => v.SizeInBytes / 2,
+ _ => u32::MAX,
+ }
+}
+
+/// The title's arguments of an ExecuteIndirect and its count: (resource, the title's offset) –
+/// as the title gave them (never XCL's checked copy).
+#[derive(Clone, Copy)]
+struct ArgsAt {
+ args: (usize, u64),
+ count: (usize, u64),
+}
+
+/// `[indirect]`: the first ExecuteIndirect of each console program (compute – `key` its hash)
+/// or pipeline (draws – `key` its address) with its arguments in each kind of place, the first
+/// 128 of compute and 32 of draws, with where they are in title memory (`outside::args_at`) –
+/// translated programs reach title memory through unified memory only, and what a GPU producer
+/// writes outside it never reaches the arguments a PC ExecuteIndirect reads.
+#[allow(clippy::too_many_arguments)]
+fn note_indirect_args(gfx: bool, key: u64, place: super::stall::Args, at: ArgsAt, max: u32, checked: bool, skipped: Option<&String>) {
+ static SEEN: Mutex>> = Mutex::new(None);
+ {
+ let mut g = SEEN.lock().unwrap_or_else(|e| e.into_inner());
+ let s = g.get_or_insert_with(Default::default);
+ let budget = if gfx { &INDIRECT_DRAWS_LOGGED } else { &INDIRECT_COMPUTE_LOGGED };
+ if budget.load(Ordering::Relaxed) >= if gfx { 32 } else { 128 } || !s.insert((gfx, key, place)) {
+ return;
+ }
+ budget.fetch_add(1, Ordering::Relaxed);
+ }
+ let what = if gfx { format!("a draw (pipeline {key:#x})") } else { format!("{key:016x}") };
+ crate::xlog_info!(
+ "[indirect] {what} ExecuteIndirect (up to {max} command(s){}): arguments {}{}{}",
+ if at.count.0 != 0 { ", a count buffer" } else { "" },
+ place.describe(),
+ // (a live resource of the title's: the call it came with is going on)
+ unsafe { super::outside::args_at(at.args.0, at.args.1, at.count) },
+ match (checked, skipped) {
+ (_, Some(e)) => format!("; skipped: {e}"),
+ (true, None) if gfx => "; its arguments checked on the GPU first".to_string(),
+ (true, None) => "; group counts checked on the GPU first".to_string(),
+ (false, None) => String::new(),
+ }
+ );
+}
+
+static INDIRECT_COMPUTE_LOGGED: AtomicU64 = AtomicU64::new(0);
+static INDIRECT_DRAWS_LOGGED: AtomicU64 = AtomicU64::new(0);
+
+/// Whether draws' ExecuteIndirect are still logged (`note_indirect_args`; past its 32 the
+/// arguments of draws are not looked at).
+fn note_indirect_draws() -> bool {
+ INDIRECT_DRAWS_LOGGED.load(Ordering::Relaxed) < 32
+}
+
/// XCL's own buffers for `fresh_indirect_arguments` cached per device (device -> buffer): COMMON between its uses
static ARGUMENT_ORDER: Mutex >> = Mutex::new(None);
@@ -985,15 +1405,14 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option
let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone();
let pso = with(this, |s| s.pso);
// a pipeline still being built in the background is waited for (its stand-in draws nothing)
- if !super::real::is_translated_graphics(super::pso_async::resolve_wait(pso)) {
- count(DRAWS_PC);
+ let real = super::pso_async::resolve_wait(pso);
+ if !super::real::is_translated_graphics(real) {
if super::present::trace_frame() {
// which pipelines draw without a translation (first 12 distinct)
static SEEN: Mutex> = Mutex::new(Vec::new());
let mut g = SEEN.lock().unwrap();
if !g.contains(&pso) && g.len() < 12 {
g.push(pso);
- let real = super::pso_async::resolve_wait(pso);
crate::xlog_info!(
"frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {real:#x}; pending {}, two-pass {}, RT0 {:?})",
super::pso_async::is_pending(pso),
@@ -1002,9 +1421,19 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option
);
}
}
- // a PC pipeline (also a stand-in or fallback: made with the title's root signature):
- // the title's root signature, which nothing else binds on the PC list – a draw without
- // one is invalid (the debug layer reports it on every GPU; WARP faults on it)
+ // a stand-in whose pipeline is not built, or XCL's fallback: its dummy shaders would draw
+ // nothing (a point list one magenta pixel) – skipped (`unbuilt`; XCL_STANDIN_SKIP_DRAWS=0: drawn)
+ if standin_skip_draws_on() {
+ if let Some((why, _)) = unbuilt(pso, real) {
+ skip_unbuilt(U_DRAW, pso, why);
+ return None;
+ }
+ }
+ count(DRAWS_PC);
+ // a PC pipeline (the title's own shaders – with XCL_STANDIN_SKIP_DRAWS=0 also a stand-in or
+ // a fallback, made with the title's root signature): the title's root signature, which
+ // nothing else binds on the PC list – a draw without one is invalid (the debug layer reports
+ // it on every GPU; WARP faults on it)
let rs = with(this, |s| s.rs_gfx) as *mut c_void;
if let Some(r) = ID3D12RootSignature::from_raw_borrowed(&rs) {
list.SetGraphicsRootSignature(r);
@@ -1290,11 +1719,33 @@ pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso:
/// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments
pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) {
- let pso = super::pso_async::resolve_wait(with(this, |s| s.pso));
+ dispatch_call(this, [x, y, z], None)
+}
+
+/// DispatchX (`list_x::dispatch_x`): a Dispatch – its flags are not applied, only named
+/// (`note_dispatch_x_flags`).
+pub(super) unsafe fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) {
+ dispatch_call(this, [x, y, z], Some(flags))
+}
+
+/// A Dispatch of `[x, y, z]` groups – DispatchX's `flags`, None for a Dispatch.
+unsafe fn dispatch_call(this: *mut c_void, [x, y, z]: [u32; 3], flags: Option) {
+ let _xcl_api = crate::waitwatch::api("bind::dispatch");
+ let raw = with(this, |s| s.pso);
+ let pso = super::pso_async::resolve_wait(raw);
+ if let Some(f) = flags {
+ note_dispatch_x_flags(&DISPATCH_X_FLAGS, f, [x, y, z], || program_of(raw, pso));
+ }
let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return };
if !super::real::is_translated_compute(pso) {
- // a console pipeline without a translation (including a background build that
- // failed): nothing to run (its root arguments were not given to the PC list either)
+ // a stand-in not built or XCL's fallback: counted and logged as such (`skip_unbuilt`)
+ if let Some((why, _)) = unbuilt(raw, pso) {
+ skipped_unbuilt_roots(this, raw, why, super::skip_roots::Call::Dispatch { groups: [x, y, z], flags });
+ skip_unbuilt(U_DISPATCH, raw, why);
+ return;
+ }
+ // any other pipeline without a translated console shader: nothing to run (its root
+ // arguments were not given to the PC list either)
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 {
crate::xlog_warn!("D3D12.X: Dispatch with a pipeline that has no translated console shader ({pso:#x}) skipped");
@@ -1302,8 +1753,15 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32,
count(DISPATCHES_SKIPPED);
return;
}
+ let (hash, threads) = super::real::pso_console_cs(pso).unwrap_or((0, 0));
+ if skip_cs(this, hash, threads, super::skip_roots::Call::Dispatch { groups: [x, y, z], flags }) {
+ return;
+ }
match translated_dispatch(this, list, pso, x, y, z) {
- Ok(()) => count(DISPATCHES),
+ Ok(()) => {
+ count(DISPATCHES);
+ super::stall::note(this, super::stall::Rec { hash, threads, what: super::stall::What::Groups([x, y, z]) });
+ }
Err(e) => {
count(DISPATCHES_SKIPPED);
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
@@ -1314,6 +1772,128 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32,
}
}
+/// `XCL_SKIP_CS`: a dispatch of a listed console program is not recorded (counted, noted, the
+/// first 8 logged; at the program's first skips its root views – `skip_roots`). True: skipped.
+/// `call`: the Dispatch, DispatchX or ExecuteIndirect it came with (the title's resources, alive
+/// for the call).
+fn skip_cs(list: *mut c_void, hash: u64, threads: u32, call: super::skip_roots::Call) -> bool {
+ if !super::stall::skipped(hash) {
+ return false;
+ }
+ // (the world's first frame is near: `XCL_FRAME_DUMP_WORLD` – the first one kept)
+ super::present::note_world_mark(hash);
+ count(DISPATCHES_SKIPPED);
+ super::stall::count_skipped();
+ super::stall::note(list, super::stall::Rec { hash, threads, what: super::stall::What::Skipped });
+ static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+ if N.fetch_add(1, Ordering::Relaxed) < 8 {
+ crate::xlog_warn!("D3D12.X: XCL_SKIP_CS: a dispatch of {hash:016x} not recorded");
+ }
+ // (past a program's first skips: one look)
+ unsafe { super::skip_roots::note_skip(list, hash, super::skip_roots::Pipeline::Built { threads }, call, || compute_roots(list)) };
+ true
+}
+
+/// A dispatch of stand-in `raw`, not built (`why`), skipped: a program XCL_SKIP_CS lists has its
+/// root views logged at it all the same – log only, its work stays skipped as unbuilt, within the
+/// same budget as `skip_cs`'s. B-1 skips such a dispatch before `skip_cs` sees it: a listed program
+/// late at its first world frame's bind would have left no root view line, its key data lost if
+/// the title crashed then (run 63) or stalled (run 64). Such a skip marks the world's first frame
+/// too (`XCL_FRAME_DUMP_WORLD`), as `skip_cs`'s does.
+fn skipped_unbuilt_roots(list: *mut c_void, raw: usize, why: Unbuilt, call: super::skip_roots::Call) {
+ // (no root view left to log – none listed, XCL_SKIP_CS_ROOTS=0, the budget spent – and the
+ // world marked or not to be: one look each)
+ let recording = super::skip_roots::recording();
+ let marking = super::present::world_mark_open();
+ if !recording && !marking {
+ return;
+ }
+ let Some(hash) = super::pso_async::program_hash(raw).filter(|&h| super::stall::skipped(h)) else { return };
+ if marking {
+ super::present::note_world_mark(hash);
+ }
+ if recording {
+ unsafe { super::skip_roots::note_skip(list, hash, super::skip_roots::Pipeline::Unbuilt(why.describe()), call, || compute_roots(list)) };
+ }
+}
+
+/// The compute root signature's layout and the arguments `list` keeps (none for a list bind does
+/// not know: nothing is made for it).
+fn compute_roots(list: *mut c_void) -> (Option>, Vec) {
+ let g = STATES.lock().unwrap_or_else(|e| e.into_inner());
+ g.as_ref().and_then(|m| m.get(&(list as usize))).map_or((None, Vec::new()), |s| (s.layout.clone(), s.args.clone()))
+}
+
+/// The console program a Dispatch of `raw`, resolved to `pso`, runs – a look only: a translated
+/// pipeline's (`real::pso_console_cs` of a pipeline already resolved), else its stand-in's
+/// (`pso_async::program_hash`); 0: none known.
+fn program_of(raw: usize, pso: usize) -> u64 {
+ if super::real::is_translated_compute(pso) {
+ super::real::pso_console_cs(pso).map_or(0, |c| c.0)
+ } else {
+ super::pso_async::program_hash(raw).unwrap_or(0)
+ }
+}
+
+/// DispatchX's flags (`dispatch_x`) are not applied: XCL takes its counts as groups. cool_fox's
+/// notes say flag 0x20 makes them threads – taken as groups, such a stage of the title's
+/// structure builder ran up to 64 times its threads. Each distinct value but 0 is named once,
+/// with the program and the counts as given, the first 16 values in the process; after that one
+/// look at the values named, no lock.
+fn note_dispatch_x_flags(seen: &FirstValues, flags: u32, groups: [u32; 3], program: impl FnOnce() -> u64) {
+ if !seen.first(flags) {
+ return;
+ }
+ let line = dispatch_x_flags_line(flags, program(), groups);
+ crate::xlog_info!("{line}");
+ #[cfg(test)]
+ FLAGS_LINES.with(|l| l.borrow_mut().push(line));
+}
+
+fn dispatch_x_flags_line(flags: u32, hash: u64, groups: [u32; 3]) -> String {
+ format!("D3D12.X: DispatchX flags {flags:#x} ({hash:016x}, counts {}×{}×{}): not applied", groups[0], groups[1], groups[2])
+}
+
+/// the DispatchX flags named so far
+static DISPATCH_X_FLAGS: FirstValues = FirstValues::new();
+
+/// Values seen for the first time (`first`): each distinct one but 0 once, the first 16.
+struct FirstValues {
+ seen: [AtomicU32; 16],
+ n: std::sync::atomic::AtomicUsize,
+ lock: Mutex<()>,
+}
+
+impl FirstValues {
+ const fn new() -> FirstValues {
+ FirstValues { seen: [const { AtomicU32::new(0) }; 16], n: std::sync::atomic::AtomicUsize::new(0), lock: Mutex::new(()) }
+ }
+
+ /// `v` is new (not 0, and fewer than 16 kept): kept. A value kept before is found without the
+ /// lock; a new one is taken under it.
+ fn first(&self, v: u32) -> bool {
+ let known = |n: usize| self.seen.iter().take(n).any(|s| s.load(Ordering::Relaxed) == v);
+ if v == 0 || self.n.load(Ordering::Acquire) >= self.seen.len() || known(self.n.load(Ordering::Acquire)) {
+ return false;
+ }
+ let _g = self.lock.lock().unwrap_or_else(|e| e.into_inner());
+ let n = self.n.load(Ordering::Acquire);
+ let Some(slot) = self.seen.get(n) else { return false };
+ if known(n) {
+ return false;
+ }
+ slot.store(v, Ordering::Relaxed);
+ self.n.store(n + 1, Ordering::Release);
+ true
+ }
+}
+
+#[cfg(test)]
+thread_local! {
+ /// (tests) the DispatchX flags lines this thread logged
+ static FLAGS_LINES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) };
+}
+
/// `XCL_TRACE_FRAME`: a full-screen dispatch (enough groups to cover a 4K target in tiles of up
/// to 128 pixels) – what its root arguments say. A bindless title passes the indices of its
/// descriptors in root constants and constant buffers: every small value there is looked up
@@ -1423,8 +2003,12 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis
if super::present::trace_frame() {
trace_fullscreen(this, pso, [x, y, z]);
}
- bind_abi(this, list, pso, false)?;
+ {
+ let _xcl_api = crate::waitwatch::api("bind::translated_dispatch: bind_abi");
+ bind_abi(this, list, pso, false)?;
+ }
super::list_x::note_stall_work(this, "dispatch", pso, [x.into(), y.into(), z.into()]);
+ let _xcl_api = crate::waitwatch::api("bind::translated_dispatch: the PC's Dispatch");
list.Dispatch(x, y, z);
Ok(())
}
@@ -1441,6 +2025,7 @@ unsafe fn bind_abi_before(
before: impl FnOnce(Option<&Layout>, usize, &[u8], &[u32], &ID3D12RootSignature) -> Result,
) -> Result {
if crate::util::mac_host() {
+ let _xcl_api = crate::waitwatch::api("bind::bind_abi: sync_recording_backing");
sync_recording_backing(this);
}
let u = crate::gpu::uma::get().ok_or("no unified memory")?;
@@ -1451,9 +2036,13 @@ unsafe fn bind_abi_before(
if first == 0 && u.shadowed() {
return Err("window 0 of unified memory has no buffer on the GPU".into());
}
- let (layout, args) = with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) });
+ let (layout, args) = {
+ let _xcl_api = crate::waitwatch::api("bind::bind_abi: the list's state (args)");
+ with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) })
+ };
// 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each)
let copy = |bytes: &[u8]| -> Result {
+ let _xcl_api = crate::waitwatch::api("bind::bind_abi: arena.take");
let p = with(this, |s| s.arena.take(u, bytes.len().max(16), 256, &mut s.uma)).ok_or("unified memory is full")?;
std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len());
Ok(p as usize)
@@ -1461,7 +2050,10 @@ unsafe fn bind_abi_before(
// a pipeline still being built in the background is waited for
let real = super::pso_async::resolve_wait(pso);
// a compute shader takes no more arguments from registers than it has (`inline_for`)
- let user_sgprs = if gfx { None } else { super::real::pso_user_sgprs(real) };
+ let user_sgprs = {
+ let _xcl_api = crate::waitwatch::api("bind::bind_abi: pso_user_sgprs");
+ if gfx { None } else { super::real::pso_user_sgprs(real) }
+ };
let inline = layout.as_ref().map_or(0, |l| if gfx { l.inline_gfx } else { console_list::inline_for(l, user_sgprs) } as usize).min(args.len());
let table_at = copy(&args[inline..])?;
let mut io = match layout.as_ref() {
@@ -1472,14 +2064,23 @@ unsafe fn bind_abi_before(
io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0);
io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32;
let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?;
- let res_at = copy(&[0u8; 256])?;
+ let res_at = copy(&res_block(gfx))?;
+ if !gfx {
+ with(this, |s| s.res_blocks.push(res_at));
+ }
let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first);
- let rs = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?;
+ let rs = {
+ let _xcl_api = crate::waitwatch::api("bind::bind_abi: root signature lookup");
+ super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?
+ };
let rs = rs as *mut c_void;
let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?;
let pc = real as *mut c_void;
let pc = ID3D12PipelineState::from_raw_borrowed(&pc).ok_or("pipeline")?;
- let value = before(layout.as_deref(), inline, &args, &io, rs)?;
+ let value = {
+ let _xcl_api = crate::waitwatch::api("bind::bind_abi: before()");
+ before(layout.as_deref(), inline, &args, &io, rs)?
+ };
let views = [va(io_at), va(res_at)].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first)));
if gfx {
list.SetGraphicsRootSignature(rs);
@@ -1487,11 +2088,13 @@ unsafe fn bind_abi_before(
list.SetGraphicsRootUnorderedAccessView(k as u32, v);
}
} else {
+ let _xcl_api = crate::waitwatch::api("bind::bind_abi: the PC's SetComputeRootSignature / root UAVs");
list.SetComputeRootSignature(rs);
for (k, v) in views.enumerate() {
list.SetComputeRootUnorderedAccessView(k as u32, v);
}
}
+ let _xcl_api = crate::waitwatch::api("bind::bind_abi: the PC's SetPipelineState");
list.SetPipelineState(pc);
Ok(value)
}
@@ -1503,7 +2106,8 @@ pub(super) fn last_draw_args() -> (bool, u32, u32, u32, i32) {
#[cfg(test)]
pub(super) fn counts_snapshot() -> [u64; 5] {
- std::array::from_fn(|k| COUNTS[k].load(Ordering::Relaxed))
+ // (this thread's binds: exact deltas of the process's counts race under 6 test threads)
+ MY_COUNTS.with(|c| c.get())
}
#[cfg(test)]
@@ -1522,6 +2126,38 @@ mod tests {
use super::*;
use std::sync::atomic::AtomicUsize;
+ /// A recording submitted again gets its compute `res` blocks back to a count of 0 with a new
+ /// serial (the upload then clears what the GPU counted in its last run); its first submission
+ /// and a new recording (KickoffX) leave them as recorded.
+ #[test]
+ fn a_recording_run_again_gets_fresh_dispatch_blocks() {
+ let list = 0x7a_1000usize as *mut c_void;
+ // (a serial the counter will not reach in a test run)
+ let mut block = [7u32, 0xDEAD_BEEF, 64, 0];
+ let at = block.as_mut_ptr() as usize;
+ with(list, |s| {
+ s.res_blocks = vec![at];
+ s.submitted = false;
+ });
+ let read = |p: usize| unsafe { std::ptr::read_volatile(p as *const [u32; 4]) };
+ before_submit(&[list]);
+ assert_eq!(read(at), [7, 0xDEAD_BEEF, 64, 0], "the first run is as recorded");
+ before_submit(&[list]);
+ let again = read(at);
+ assert_eq!((again[0], again[2], again[3]), (0, 64, 0));
+ assert!(again[1] != 0xDEAD_BEEF && again[1] != 0, "a new serial: {again:?}");
+ before_submit(&[list]);
+ assert_ne!(read(at)[1], again[1], "each run again a new one");
+ // KickoffX: the list records anew – its blocks are not this recording's any more
+ unsafe { std::ptr::write_volatile(at as *mut u32, 5) };
+ kicked_off(list);
+ before_submit(&[list]);
+ before_submit(&[list]);
+ assert_eq!(read(at)[0], 5);
+ remove_state_for_test(list);
+ let _ = &mut block;
+ }
+
/// A pipeline with the rect list GS draws its rect lists whole: draw_rects leaves them alone.
#[test]
fn rect_lists_with_the_rect_list_gs_are_not_expanded_on_the_cpu() {
@@ -1533,26 +2169,35 @@ mod tests {
assert!(cpu_rect_expansion(with_gs));
}
- /// An ExecuteIndirect whose bound pipeline is still being built is skipped (its stand-in
- /// with XCL's ABI root signature on the list is the debug layer's 953 and a hung GPU);
- /// a built or failed one goes to the PC call. The gate `execute_indirect` uses.
+ /// The predicate every bind site skips by (`unbuilt`): a stand-in the bind still holds – its
+ /// build not over, failed, or over only after the bind resolved it – and a pipeline of XCL's
+ /// fallback shaders are held back (its stand-in or fallback with XCL's ABI root signature on
+ /// the list is the debug layer's 953 and a hung GPU); a stand-in resolved to its built
+ /// pipeline, a pipeline with no stand-in (the title's own) and none go on.
#[test]
- fn execute_indirect_with_a_pipeline_still_building_is_skipped() {
- let (building, built, failed) = (0x7E57_6001usize, 0x7E57_6002usize, 0x7E57_6003usize);
+ fn unbuilt_holds_back_stand_ins_not_built_and_fallbacks_only() {
+ let (building, built, failed) = (0x7B00_1001usize, 0x7B00_1002usize, 0x7B00_1003usize);
+ let (pc, fallback) = (0x7B00_1004usize, 0x7B00_1005usize);
// lazy submits: no worker starts them, so the states stay under the test's control
- pso_async::submit_lazy(building, false, Box::new(|| 0x1234), 0);
- pso_async::submit_lazy(built, false, Box::new(|| 0x1235), 0);
+ pso_async::submit_lazy(building, false, Box::new(|| 0x7B00_1234), 0);
+ pso_async::submit_lazy(built, false, Box::new(|| 0x7B00_1235), 0);
pso_async::submit_lazy(failed, false, Box::new(|| 0), 0);
- assert!(pso_async::is_pending(building));
- assert_eq!(pso_async::resolve_wait(built), 0x1235);
+ real::register_fallback_for_test(fallback, true);
+ assert_eq!(pso_async::resolve_wait(built), 0x7B00_1235);
assert_eq!(pso_async::resolve_wait(failed), failed);
- assert!(!pso_async::is_pending(built) && !pso_async::is_pending(failed));
- // never resolved: still pending (the skip case), then forgotten
- assert!(pso_async::is_pending(building));
+ assert_eq!(unbuilt(building, building), Some((Unbuilt::Building, false)), "still being built");
+ assert_eq!(unbuilt(failed, failed), Some((Unbuilt::Failed, false)), "its build failed");
+ assert_eq!(unbuilt(built, 0x7B00_1235), None, "built: its real pipeline goes on");
+ assert_eq!(unbuilt(built, built), Some((Unbuilt::Building, false)), "resolved before it was built: still held back");
+ assert_eq!(unbuilt(pc, pc), None, "the title's own pipeline");
+ assert_eq!(unbuilt(0, 0), None, "no pipeline");
+ assert_eq!(unbuilt(fallback, fallback), Some((Unbuilt::Fallback, true)), "XCL's fallback shaders");
+ real::forget_pso_for_test(fallback);
+ assert_eq!(unbuilt(fallback, fallback), None, "a fallback is forgotten with its pipeline");
pso_async::released(building);
pso_async::released(built);
pso_async::released(failed);
- assert!(!pso_async::is_pending(building));
+ assert_eq!(unbuilt(building, building), None, "a released stand-in is none any more");
}
/// A dispatch writes an ExecuteIndirect's group count through another buffer over the same
@@ -1766,78 +2411,194 @@ void main(uint t : SV_GroupIndex) {
forget(list);
}
+ /// A command list of console code as bind's hooks see it, recording what reaches the PC: its
+ /// table (`real::test_ext_table`) is laid out as an adopted object's, so `real::orig_fn` and
+ /// the PC methods `ID3D12GraphicsCommandList` calls find the slots below. The one fake of the
+ /// tests of the bind paths.
#[repr(C)]
- struct FakeAdoptedList {
+ struct FakeList {
vt: *const usize,
refs: AtomicUsize,
- dispatch_calls: AtomicUsize,
- set_compute_rs_calls: AtomicUsize,
- set_compute_uav_calls: AtomicUsize,
- set_pso_calls: AtomicUsize,
- execute_indirect_calls: AtomicUsize,
+ /// GetType's answer (DIRECT, or BUNDLE)
+ ty: std::sync::atomic::AtomicI32,
+ /// the device GetDevice answers with (0: E_NOINTERFACE)
+ device: usize,
+ /// (slot, a, b) of every call but IUnknown's, in order
+ calls: Mutex>,
+ /// each SetComputeRoot32BitConstants' words
+ constants: Mutex>>,
+ /// each ExecuteIndirect: (signature, max, arguments, offset, count, count offset)
+ indirect: Mutex>,
+ }
+
+ /// A `FakeList` with its 96-slot table: both live until the test ends, and nothing outside
+ /// the test's thread calls into them.
+ struct Fake {
+ list: Box,
+ _tables: (Box<[usize; 96]>, Vec),
+ }
+
+ impl Fake {
+ /// A list whose GetDevice answers with `device` (0: none).
+ fn new(device: usize) -> Fake {
+ let mut orig = Box::new([0usize; 96]);
+ orig[0] = fake_query_interface as usize;
+ orig[1] = fake_add_ref as usize;
+ orig[2] = fake_release as usize;
+ orig[7] = fake_get_device as usize;
+ orig[8] = fake_get_type as usize;
+ orig[12] = fake_draw_instanced as usize;
+ orig[14] = fake_dispatch as usize;
+ orig[25] = fake_set_pipeline_state as usize;
+ orig[26] = fake_resource_barrier as usize;
+ orig[29] = fake_set_compute_root_signature as usize;
+ orig[30] = fake_set_graphics_root_signature as usize;
+ orig[35] = fake_set_compute_root_constants as usize;
+ orig[39] = fake_set_compute_root_srv as usize;
+ orig[41] = fake_set_compute_root_uav as usize;
+ orig[42] = fake_set_graphics_root_uav as usize;
+ orig[43] = fake_ia_set_index_buffer as usize;
+ orig[59] = fake_execute_indirect as usize;
+ orig[79] = fake_dispatch_mesh as usize;
+ let (ext, vt) = real::test_ext_table(&orig[..]);
+ let list = Box::new(FakeList {
+ vt,
+ refs: AtomicUsize::new(1),
+ ty: std::sync::atomic::AtomicI32::new(D3D12_COMMAND_LIST_TYPE_DIRECT.0),
+ device,
+ calls: Mutex::new(Vec::new()),
+ constants: Mutex::new(Vec::new()),
+ indirect: Mutex::new(Vec::new()),
+ });
+ Fake { list, _tables: (orig, ext) }
+ }
+
+ /// The list as the title hands it to bind's hooks.
+ fn ptr(&self) -> *mut c_void {
+ &*self.list as *const FakeList as *mut c_void
+ }
+
+ /// How many calls of PC slot `slot` reached the list so far.
+ fn count(&self, slot: usize) -> usize {
+ self.list.calls.lock().unwrap().iter().filter(|c| c.0 == slot).count()
+ }
+
+ /// (a, b) of the last call of PC slot `slot`.
+ fn last(&self, slot: usize) -> Option<(u64, u64)> {
+ self.list.calls.lock().unwrap().iter().rev().find(|c| c.0 == slot).map(|c| (c.1, c.2))
+ }
+ }
+
+ unsafe fn fake_of<'a>(this: *mut c_void) -> &'a FakeList {
+ &*(this as *const FakeList)
+ }
+
+ unsafe fn fake_call(this: *mut c_void, slot: usize, a: u64, b: u64) {
+ fake_of(this).calls.lock().unwrap().push((slot, a, b));
+ }
+
+ unsafe extern "system" fn fake_query_interface(this: *mut c_void, _riid: *const windows::core::GUID, ppv: *mut *mut c_void) -> windows::core::HRESULT {
+ fake_add_ref(this);
+ *ppv = this;
+ windows::core::HRESULT(0)
}
unsafe extern "system" fn fake_add_ref(this: *mut c_void) -> u32 {
- (*(this as *const FakeAdoptedList)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1
+ fake_of(this).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1
}
unsafe extern "system" fn fake_release(this: *mut c_void) -> u32 {
- (*(this as *const FakeAdoptedList)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1
+ fake_of(this).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1
+ }
+
+ unsafe extern "system" fn fake_get_device(this: *mut c_void, riid: *const windows::core::GUID, ppv: *mut *mut c_void) -> windows::core::HRESULT {
+ fake_call(this, 7, 0, 0);
+ let device = fake_of(this).device as *mut c_void;
+ match ID3D12Device::from_raw_borrowed(&device) {
+ Some(d) => d.query(riid, ppv),
+ None => {
+ *ppv = std::ptr::null_mut();
+ windows::Win32::Foundation::E_NOINTERFACE
+ }
+ }
+ }
+
+ unsafe extern "system" fn fake_get_type(this: *mut c_void) -> D3D12_COMMAND_LIST_TYPE {
+ fake_call(this, 8, 0, 0);
+ D3D12_COMMAND_LIST_TYPE(fake_of(this).ty.load(Ordering::Relaxed))
+ }
+
+ unsafe extern "system" fn fake_draw_instanced(this: *mut c_void, vertices: u32, instances: u32, _first_vertex: u32, _first_instance: u32) {
+ fake_call(this, 12, vertices.into(), instances.into());
+ }
+
+ unsafe extern "system" fn fake_dispatch(this: *mut c_void, x: u32, y: u32, _z: u32) {
+ fake_call(this, 14, x.into(), y.into());
+ }
+
+ unsafe extern "system" fn fake_set_pipeline_state(this: *mut c_void, pso: *mut c_void) {
+ fake_call(this, 25, pso as u64, 0);
+ }
+
+ unsafe extern "system" fn fake_resource_barrier(this: *mut c_void, n: u32, _barriers: *const c_void) {
+ fake_call(this, 26, n.into(), 0);
+ }
+
+ unsafe extern "system" fn fake_set_compute_root_signature(this: *mut c_void, rs: *mut c_void) {
+ fake_call(this, 29, rs as u64, 0);
+ }
+
+ unsafe extern "system" fn fake_set_graphics_root_signature(this: *mut c_void, rs: *mut c_void) {
+ fake_call(this, 30, rs as u64, 0);
}
- unsafe extern "system" fn fake_dispatch(this: *mut c_void, _x: u32, _y: u32, _z: u32) {
- (*(this as *const FakeAdoptedList)).dispatch_calls.fetch_add(1, Ordering::Relaxed);
+ unsafe extern "system" fn fake_set_compute_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) {
+ fake_call(this, 35, i.into(), offset.into());
+ let words = if data.is_null() { Vec::new() } else { std::slice::from_raw_parts(data, n as usize).to_vec() };
+ fake_of(this).constants.lock().unwrap().push(words);
}
- unsafe extern "system" fn fake_set_pso(this: *mut c_void, _pso: *mut c_void) {
- (*(this as *const FakeAdoptedList)).set_pso_calls.fetch_add(1, Ordering::Relaxed);
+ unsafe extern "system" fn fake_set_compute_root_srv(this: *mut c_void, i: u32, va: u64) {
+ fake_call(this, 39, i.into(), va);
}
- unsafe extern "system" fn fake_set_compute_rs(this: *mut c_void, _rs: *mut c_void) {
- (*(this as *const FakeAdoptedList)).set_compute_rs_calls.fetch_add(1, Ordering::Relaxed);
+ unsafe extern "system" fn fake_set_compute_root_uav(this: *mut c_void, i: u32, va: u64) {
+ fake_call(this, 41, i.into(), va);
}
- unsafe extern "system" fn fake_set_compute_uav(this: *mut c_void, _slot: u32, _va: u64) {
- (*(this as *const FakeAdoptedList)).set_compute_uav_calls.fetch_add(1, Ordering::Relaxed);
+ unsafe extern "system" fn fake_set_graphics_root_uav(this: *mut c_void, i: u32, va: u64) {
+ fake_call(this, 42, i.into(), va);
}
- unsafe extern "system" fn fake_execute_indirect(
- this: *mut c_void,
- _sig: usize,
- _max: u32,
- _args: usize,
- _args_off: u64,
- _count_buf: usize,
- _count_off: u64,
- ) {
- (*(this as *const FakeAdoptedList)).execute_indirect_calls.fetch_add(1, Ordering::Relaxed);
+ unsafe extern "system" fn fake_ia_set_index_buffer(this: *mut c_void, view: *const D3D12_INDEX_BUFFER_VIEW) {
+ let (va, bytes) = view.as_ref().map_or((0, 0), |v| (v.BufferLocation, v.SizeInBytes.into()));
+ fake_call(this, 43, va, bytes);
}
+ unsafe extern "system" fn fake_execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count: usize, count_off: u64) {
+ fake_call(this, 59, sig as u64, args as u64);
+ fake_of(this).indirect.lock().unwrap().push((sig, max, args, args_off, count, count_off));
+ }
+
+ unsafe extern "system" fn fake_dispatch_mesh(this: *mut c_void, x: u32, y: u32, _z: u32) {
+ fake_call(this, 79, x.into(), y.into());
+ }
+
+ /// A compute pipeline built in the background takes the translated path once resolved; one
+ /// whose build failed has its Dispatch and its ExecuteIndirect skipped, named and counted at
+ /// their places (XCL_STANDIN_SKIP=0: its ExecuteIndirect goes to the PC, as before 0023); a
+ /// genuine PC pipeline's ExecuteIndirect goes to the PC with the title's root signature.
#[test]
fn async_compute_pso_success_and_failure_in_dispatch_and_execute_indirect() {
- let mut orig_vt = [0usize; 64];
- orig_vt[1] = fake_add_ref as usize;
- orig_vt[2] = fake_release as usize;
- orig_vt[14] = fake_dispatch as usize;
- orig_vt[25] = fake_set_pso as usize;
- orig_vt[29] = fake_set_compute_rs as usize;
- orig_vt[41] = fake_set_compute_uav as usize;
- orig_vt[59] = fake_execute_indirect as usize;
-
- // Extended vtable laid out as `real::orig_fn` reads it, with the COM method pointers used
- // via `ID3D12GraphicsCommandList`.
- let (_ext_vt, ext) = crate::hle::d3d12x::real::test_ext_table(&orig_vt);
-
- let fake = Box::new(FakeAdoptedList {
- vt: ext,
- refs: AtomicUsize::new(1),
- dispatch_calls: AtomicUsize::new(0),
- set_compute_rs_calls: AtomicUsize::new(0),
- set_compute_uav_calls: AtomicUsize::new(0),
- set_pso_calls: AtomicUsize::new(0),
- execute_indirect_calls: AtomicUsize::new(0),
- });
- let list_ptr = &*fake as *const FakeAdoptedList as *mut c_void;
+ let fake = Fake::new(0);
+ let list_ptr = fake.ptr();
+ // the title's graphics root signature (no layout noted: only `rs_gfx` is set), which the
+ // PC path binds
+ let rs_title = 0x7B00_02F5usize;
+ let reset_with_rs = |pso: usize| {
+ reset(list_ptr, 0x7200_0100, pso);
+ unsafe { set_graphics_root_signature(list_ptr, rs_title as *mut c_void) };
+ };
// 1. Background compute build SUCCEEDS: real PSO R is registered in TRANSLATED_COMPUTE,
// stand-in S is NOT. ExecuteIndirect resolves S -> R and treats it as translated.
@@ -1859,50 +2620,74 @@ void main(uint t : SV_GroupIndex) {
assert!(!real::is_translated_compute(standin_ok));
assert!(real::is_translated_compute(real_ok));
- reset(list_ptr, 0x7200_0100, standin_ok);
+ reset_with_rs(standin_ok);
unsafe {
// With `sig_root_changing`, a translated compute PSO rejects this unsupported signature
// instead of falling through to `pc` (which happened when `R` wasn't registered).
execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0);
}
- assert_eq!(
- fake.execute_indirect_calls.load(Ordering::Relaxed),
- 0,
- "ExecuteIndirect must recognize resolved async compute PSO R as translated"
- );
+ assert_eq!(fake.count(59), 0, "ExecuteIndirect must recognize resolved async compute PSO R as translated");
+ assert_eq!(take_last_unbuilt(), None, "a built pipeline is not held back");
+ assert_eq!(super::super::stall::ledger_indirect_for_test(list_ptr), [[0; 4]; 2], "a compute ExecuteIndirect not recorded is not counted");
// 2. Background compute build FAILS (returns 0): stand-in S_fail is NOT in
// TRANSLATED_COMPUTE. Dispatch must skip cleanly without binding XCL's ABI RS/UAVs
- // onto S_fail, and ExecuteIndirect must not enter bind_abi either.
+ // onto S_fail, and its ExecuteIndirect must not reach the PC either.
let standin_fail = 0x7200_0003usize;
pso_async::submit(standin_fail, true, Box::new(|| 0));
assert_eq!(pso_async::resolve_wait(standin_fail), standin_fail);
assert!(!real::is_translated_compute(standin_fail));
- reset(list_ptr, 0x7200_0100, standin_fail);
+ reset_with_rs(standin_fail);
let before = counts_snapshot();
unsafe {
dispatch(list_ptr, 1, 1, 1);
}
let after = counts_snapshot();
assert_eq!(after[DISPATCHES], before[DISPATCHES]);
- assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]);
- assert_eq!(fake.set_compute_rs_calls.load(Ordering::Relaxed), 0);
- assert_eq!(fake.set_compute_uav_calls.load(Ordering::Relaxed), 0);
- assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 0);
- assert_eq!(fake.dispatch_calls.load(Ordering::Relaxed), 0);
+ assert_eq!(after[DISPATCHES_SKIPPED], before[DISPATCHES_SKIPPED] + 1);
+ // no compute root signature, UAV, pipeline or Dispatch of XCL's ABI on the PC list
+ for slot in [29, 41, 25, 14] {
+ assert_eq!(fake.count(slot), 0, "PC slot {slot}");
+ }
+ assert_eq!(take_last_unbuilt(), Some((standin_fail, U_DISPATCH, Unbuilt::Failed)));
+ assert_eq!(pso_async::take_last_skip(), Some(standin_fail), "a stand-in's skip is told to pso_async");
+ let (calls, rs_calls, before) = (fake.count(59), fake.count(30), counts_snapshot());
unsafe {
execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0);
}
- assert_eq!(fake.set_compute_rs_calls.load(Ordering::Relaxed), 0);
- assert_eq!(fake.set_compute_uav_calls.load(Ordering::Relaxed), 0);
- assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 0);
- assert_eq!(
- fake.execute_indirect_calls.load(Ordering::Relaxed),
- 1,
- "failed async compute stand-in must not enter translated ExecuteIndirect path"
- );
+ let after = counts_snapshot();
+ for slot in [29, 41, 25] {
+ assert_eq!(fake.count(slot), 0, "failed async compute stand-in must not enter translated ExecuteIndirect path (PC slot {slot})");
+ }
+ if standin_skip_on() {
+ assert_eq!(
+ (fake.count(59) - calls, fake.count(30) - rs_calls),
+ (0, 0),
+ "a failed async compute stand-in's ExecuteIndirect must not reach the PC"
+ );
+ assert_eq!(take_last_unbuilt(), Some((standin_fail, U_INDIRECT_COMPUTE, Unbuilt::Failed)));
+ assert_eq!(pso_async::take_last_skip(), Some(standin_fail));
+ assert_eq!(after[DISPATCHES_SKIPPED], before[DISPATCHES_SKIPPED] + 1);
+ } else {
+ // XCL_STANDIN_SKIP=0: only a stand-in whose build is not over is held back, as before 0023
+ assert_eq!((fake.count(59) - calls, fake.count(30) - rs_calls), (1, 1), "XCL_STANDIN_SKIP=0: 0022's PC call");
+ assert_eq!(take_last_unbuilt(), None);
+ assert_eq!(pso_async::take_last_skip(), None);
+ }
+
+ // 3. A genuine PC pipeline (no stand-in, no fallback): the PC call, after the title's
+ // root signature
+ reset_with_rs(0x7B00_0205);
+ let (calls, rs_calls) = (fake.count(59), fake.count(30));
+ unsafe {
+ execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0);
+ }
+ assert_eq!((fake.count(59) - calls, fake.count(30) - rs_calls), (1, 1), "the title's own pipeline goes to the PC");
+ assert_eq!(fake.last(30), Some((rs_title as u64, 0)));
+ assert_eq!(take_last_unbuilt(), None);
+ assert_eq!(pso_async::take_last_skip(), None);
forget(list_ptr);
indirect::forget(sig_root_changing);
@@ -1911,6 +2696,656 @@ void main(uint t : SV_GroupIndex) {
real::forget_pso_for_test(real_ok);
}
+ /// DispatchMesh with a stand-in whose build failed, or with a pipeline of XCL's fallback
+ /// shaders, is skipped – named and counted at its place, a stand-in's skip told to pso_async
+ /// (XCL_STANDIN_SKIP=0: both go to the PC, as before 0023); a genuine PC mesh pipeline's goes
+ /// to the PC after the title's root signature.
+ #[test]
+ fn dispatch_mesh_with_a_stand_in_not_built_or_a_fallback_is_skipped() {
+ let fake = Fake::new(0);
+ let list = fake.ptr();
+ let rs_title = 0x7B00_20F5usize;
+ let (failed, fallback, pc) = (0x7B00_2001usize, 0x7B00_2002usize, 0x7B00_20F1usize);
+ pso_async::submit(failed, false, Box::new(|| 0));
+ assert_eq!(pso_async::resolve_wait(failed), failed);
+ real::register_fallback_for_test(fallback, false);
+ // one DispatchMesh with `pso` bound: the DispatchMesh and SetGraphicsRootSignature calls
+ // that reached the PC list, and what it added to this thread's counts
+ let mesh = |pso: usize| -> (usize, usize, [u64; 5]) {
+ reset(list, 0x7B00_2100, pso);
+ unsafe { set_graphics_root_signature(list, rs_title as *mut c_void) };
+ let (calls, rs_calls, before) = (fake.count(79), fake.count(30), counts_snapshot());
+ unsafe { dispatch_mesh(list, 2, 1, 1) };
+ let after = counts_snapshot();
+ (fake.count(79) - calls, fake.count(30) - rs_calls, std::array::from_fn(|k| after[k] - before[k]))
+ };
+ let skip = standin_skip_on();
+ for (pso, why) in [(failed, Unbuilt::Failed), (fallback, Unbuilt::Fallback)] {
+ let (calls, rs_calls, d) = mesh(pso);
+ if skip {
+ assert_eq!((calls, rs_calls), (0, 0), "{why:?}: skipped");
+ assert_eq!(take_last_unbuilt(), Some((pso, U_DISPATCH_MESH, why)));
+ assert_eq!((d[DRAWS_SKIPPED], d[DRAWS_PC]), (1, 0), "{why:?}");
+ } else {
+ assert_eq!((calls, rs_calls), (1, 1), "{why:?}: XCL_STANDIN_SKIP=0: 0022's PC call");
+ assert_eq!(take_last_unbuilt(), None);
+ assert_eq!((d[DRAWS_SKIPPED], d[DRAWS_PC]), (0, 1), "{why:?}");
+ }
+ assert_eq!(
+ pso_async::take_last_skip(),
+ (skip && why != Unbuilt::Fallback).then_some(pso),
+ "{why:?}: a stand-in's skip is told to pso_async, a fallback's is not"
+ );
+ }
+ let (calls, rs_calls, d) = mesh(pc);
+ assert_eq!((calls, rs_calls), (1, 1), "the title's own mesh pipeline goes to the PC");
+ assert_eq!(fake.last(30), Some((rs_title as u64, 0)));
+ assert_eq!(fake.last(79), Some((2, 1)));
+ assert_eq!((d[DRAWS_SKIPPED], d[DRAWS_PC]), (0, 1));
+ assert_eq!(take_last_unbuilt(), None);
+ assert_eq!(pso_async::take_last_skip(), None);
+
+ forget(list);
+ let _ = pso_async::released(failed);
+ real::forget_pso_for_test(fallback);
+ }
+
+ /// A draw with a stand-in whose build failed, or with a pipeline of XCL's fallback shaders, is
+ /// skipped – named and counted at its place, not with the PC pipelines, a stand-in's skip told
+ /// to pso_async (XCL_STANDIN_SKIP_DRAWS=0: drawn, as before 0023); a genuine PC pipeline's draw
+ /// goes to the PC after the title's root signature.
+ #[test]
+ fn draws_with_a_stand_in_not_built_or_a_fallback_are_skipped() {
+ let fake = Fake::new(0);
+ let list = fake.ptr();
+ let rs_title = 0x7B00_60F5usize;
+ let (failed, fallback, pc) = (0x7B00_6001usize, 0x7B00_6002usize, 0x7B00_60F1usize);
+ pso_async::submit(failed, false, Box::new(|| 0));
+ assert_eq!(pso_async::resolve_wait(failed), failed);
+ real::register_fallback_for_test(fallback, false);
+ // one DrawInstanced with `pso` bound: the DrawInstanced and SetGraphicsRootSignature calls
+ // that reached the PC list, and what it added to this thread's counts (`draw_rects` and
+ // `sync_title_buffers` pass over a list list_x does not know)
+ let draw = |pso: usize| -> (usize, usize, [u64; 5]) {
+ reset(list, 0x7B00_6100, pso);
+ unsafe { set_graphics_root_signature(list, rs_title as *mut c_void) };
+ let (calls, rs_calls, before) = (fake.count(12), fake.count(30), counts_snapshot());
+ unsafe { draw_instanced(list, 3, 1, 0, 0) };
+ let after = counts_snapshot();
+ (fake.count(12) - calls, fake.count(30) - rs_calls, std::array::from_fn(|k| after[k] - before[k]))
+ };
+ let skip = standin_skip_draws_on();
+ for (pso, why) in [(failed, Unbuilt::Failed), (fallback, Unbuilt::Fallback)] {
+ let (calls, rs_calls, d) = draw(pso);
+ if skip {
+ assert_eq!((calls, rs_calls), (0, 0), "{why:?}: skipped");
+ assert_eq!(take_last_unbuilt(), Some((pso, U_DRAW, why)));
+ assert_eq!((d[DRAWS_SKIPPED], d[DRAWS_PC]), (1, 0), "{why:?}: counted as skipped, not with the PC pipelines");
+ } else {
+ assert_eq!((calls, rs_calls), (1, 1), "{why:?}: XCL_STANDIN_SKIP_DRAWS=0: drawn, as before 0023");
+ assert_eq!(take_last_unbuilt(), None);
+ assert_eq!((d[DRAWS_SKIPPED], d[DRAWS_PC]), (0, 1), "{why:?}");
+ }
+ assert_eq!(
+ pso_async::take_last_skip(),
+ (skip && why != Unbuilt::Fallback).then_some(pso),
+ "{why:?}: a stand-in's skip is told to pso_async, a fallback's is not"
+ );
+ }
+ let (calls, rs_calls, d) = draw(pc);
+ assert_eq!((calls, rs_calls), (1, 1), "the title's own pipeline draws");
+ assert_eq!(fake.last(30), Some((rs_title as u64, 0)));
+ assert_eq!(fake.last(12), Some((3, 1)));
+ assert_eq!((d[DRAWS_SKIPPED], d[DRAWS_PC]), (0, 1));
+ assert_eq!(take_last_unbuilt(), None);
+ assert_eq!(pso_async::take_last_skip(), None);
+
+ forget(list);
+ let _ = pso_async::released(failed);
+ real::forget_pso_for_test(fallback);
+ }
+
+ /// A big compute pipeline no run built is late at its first bind (group A's big lane builds it,
+ /// binds do not wait): its ExecuteIndirect is skipped at once – named late, nothing on the PC
+ /// list – until it is built; then its real pipeline's goes on.
+ #[test]
+ fn execute_indirect_with_a_late_stand_in_is_skipped_until_it_is_built() {
+ let Some(_lanes) = pso_async::lane_tests::lanes() else { return };
+ let fake = Fake::new(0);
+ let list = fake.ptr();
+ let (s, built, key) = (0x7B00_3001usize, 0x7B00_3011usize, 0x7B00_3AAAu64);
+ // the build waits at a gate, 3 s at most: dropping `open` opens it (also when an assertion
+ // unwinds – the entry is then left: its job's result is no pipeline to release)
+ let (open, gate) = std::sync::mpsc::channel::<()>();
+ let job: pso_async::Job = Box::new(move || {
+ let _ = gate.recv_timeout(std::time::Duration::from_secs(3));
+ built
+ });
+ pso_async::submit_program(s, true, job, true, key, pso_async::Program { hash: 0x7B00_3BBB, kind: b'C', dxil: 1 << 20, key, ..Default::default() });
+ reset(list, 0x7B00_3100, s);
+ let t = std::time::Instant::now();
+ unsafe { execute_indirect(list, 0x7B00_30F0, 1, 0, 0, 0, 0) };
+ let waited = t.elapsed();
+ assert!(waited < std::time::Duration::from_millis(500), "a late pipeline was waited for: {waited:?}");
+ assert_eq!(fake.count(59), 0, "a late stand-in's ExecuteIndirect must not reach the PC");
+ assert_eq!(take_last_unbuilt(), Some((s, U_INDIRECT_COMPUTE, Unbuilt::Late)));
+ assert_eq!(pso_async::take_last_skip(), Some(s), "a stand-in's skip is told to pso_async");
+ assert!(pso_async::is_pending(s), "still being built");
+ drop(open);
+ let t = std::time::Instant::now();
+ while pso_async::is_pending(s) {
+ assert!(t.elapsed() < std::time::Duration::from_secs(10), "its build did not end");
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ unsafe { execute_indirect(list, 0x7B00_30F0, 1, 0, 0, 0, 0) };
+ assert_eq!(fake.count(59), 1, "built: its real pipeline (here not a translated one) goes to the PC");
+ assert_eq!(take_last_unbuilt(), None);
+ forget(list);
+ let _ = pso_async::released(s);
+ }
+
+ /// The adapter's device (None: the test says SKIPPED) and a DEFAULT buffer of `bytes` on it:
+ /// title memory outside unified memory as `indirect::classify` sees it (`Own`).
+ unsafe fn device_and_own_buffer(bytes: u64) -> Option<(ID3D12Device, ID3D12Resource)> {
+ use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
+ let mut dev: Option = None;
+ if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() {
+ crate::gpu::recomp::runner::skip_test("no GPU");
+ return None;
+ }
+ let dev = dev.unwrap();
+ let desc = D3D12_RESOURCE_DESC {
+ Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1,
+ SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+ Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default()
+ };
+ let mut own: Option = None;
+ dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut own)
+ .expect("a DEFAULT buffer");
+ Some((dev, own.unwrap()))
+ }
+
+ /// `XCL_INDIRECT_OWN=skip`: an ExecuteIndirect of a translated pipeline – draws or compute – with
+ /// its arguments outside unified memory is not recorded (nothing on the PC list, counted as
+ /// skipped for the lever); without the lever never so.
+ #[test]
+ fn xcl_indirect_own_skip_keeps_arguments_outside_unified_memory_off_the_gpu() {
+ use super::super::stall::Args;
+ unsafe {
+ let Some((_dev, own)) = device_and_own_buffer(256) else { return };
+ let fake = Fake::new(0);
+ let list = fake.ptr();
+ let (draws, computes) = (0x7B00_4001usize, 0x7B00_4002usize);
+ real::register_translated_graphics_for_test(draws);
+ real::register_translated_compute_for_test(computes);
+ for (pso, gfx) in [(draws, true), (computes, false)] {
+ reset(list, 0x7B00_4100, pso);
+ let (calls, rs_calls, before) = (fake.count(59), fake.count(30), counts_snapshot());
+ // (an unregistered signature: no repacker, no check)
+ execute_indirect(list, 0x7B00_40F0, 1, own.as_raw() as usize, 0, 0, 0);
+ let after = counts_snapshot();
+ let census = indirect::take_last_census();
+ if indirect::own_skip() {
+ assert_eq!(census, indirect::census_on().then_some((gfx, Args::Own, indirect::Fate::SkippedOwn)), "gfx {gfx}");
+ assert_eq!((fake.count(59) - calls, fake.count(30) - rs_calls), (0, 0), "gfx {gfx}: not recorded");
+ let skipped = if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED };
+ assert_eq!(after[skipped] - before[skipped], 1, "gfx {gfx}: counted as skipped");
+ } else if let Some(c) = census {
+ // (`bind_abi` fails in a test process: unified memory is not open on the GPU)
+ assert!(matches!(c, (g, Args::Own, indirect::Fate::AsIs | indirect::Fate::Failed) if g == gfx), "gfx {gfx}: {c:?}");
+ }
+ }
+ forget(list);
+ real::forget_pso_for_test(draws);
+ real::forget_pso_for_test(computes);
+ }
+ }
+
+ /// Indirect draws are counted by where their arguments are past the 32 `[indirect]` lines (the
+ /// census classifies every one), and those whose signature the check does not read are counted
+ /// as such; with XCL_INDIRECT_CENSUS=0 neither count moves.
+ #[test]
+ fn indirect_draws_are_counted_by_place_past_the_log_cap() {
+ use super::super::stall::Args;
+ unsafe {
+ let Some((_dev, own)) = device_and_own_buffer(256) else { return };
+ let fake = Fake::new(0);
+ let list = fake.ptr();
+ let psos: Vec = (0..40).map(|k| 0x7B00_5000 + 0x10 * k).collect();
+ for &p in &psos {
+ real::register_translated_graphics_for_test(p);
+ }
+ let counted = || (indirect::census_of(true, Args::Own), indirect::census_snapshot().unread);
+ let (own_before, unread_before) = counted();
+ for &p in &psos {
+ reset(list, 0x7B00_5F00, p);
+ // (an unregistered signature: one the check does not read)
+ execute_indirect(list, 0x7B00_5FF0, 1, own.as_raw() as usize, 0, 0, 0);
+ }
+ let (own_after, unread_after) = counted();
+ if indirect::census_on() {
+ assert!(own_after - own_before >= 40, "40 draws outside unified memory counted: {}", own_after - own_before);
+ if indirect::draw_check_on() && !indirect::own_skip() {
+ assert!(unread_after - unread_before >= 40, "40 draws with a signature the check does not read: {}", unread_after - unread_before);
+ }
+ } else {
+ assert_eq!((own_after, unread_after), (own_before, unread_before), "XCL_INDIRECT_CENSUS=0: nothing counted");
+ }
+ forget(list);
+ for p in psos {
+ real::forget_pso_for_test(p);
+ }
+ }
+ }
+
+ /// The sequence run 65 records for a translated draw's ExecuteIndirect with its arguments
+ /// outside unified memory: XCL's check (a compute pass) first, then the draw's own root
+ /// signature, root UAVs and pipeline, then the ExecuteIndirect of XCL's checked commands with
+ /// XCL's signature, and list_x's key back on the title's pipeline; an indexed draw's check knows
+ /// the indices bound; a bundle's is not checked (barriers are not allowed there).
+ #[test]
+ fn a_checked_indirect_draw_records_the_check_then_the_draws_own_state() {
+ use super::super::stall::Args;
+ use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16_UINT;
+ if !crate::util::mac_host() {
+ return;
+ }
+ unsafe {
+ let Some((dev, own)) = device_and_own_buffer(256) else { return };
+ if crate::gpu::recomp::dxc::create_instance().is_none() {
+ return crate::gpu::recomp::runner::skip_test("no DXC");
+ }
+ let fake = Fake::new(dev.as_raw() as usize);
+ let list = fake.ptr();
+ let (pso, rs, allocator) = (0x7B00_7001usize, 0x7B00_70F5usize, 0x7B00_7100usize);
+ let (sig, sig_indexed) = (0x7B00_70A0usize, 0x7B00_70A1usize);
+ let own_raw = own.as_raw() as usize;
+ real::register_translated_graphics_for_test(pso);
+ real::set_pso_root_signature_for_test(pso, rs);
+ // (open windows, which only XCL's device creation opens)
+ let _windows = real::window_vas_for_test(vec![0x7B00_7000_0000; 4]);
+ reset(list, allocator, pso);
+ indirect::note_plain_draw(sig, 16, false);
+ indirect::note_plain_draw(sig_indexed, 20, true);
+ // list_x's key moved off the title's pipeline, as XCL's own SetPipelineState calls move it
+ list_x::on_set_pipeline_state(list, 0x7B00_70EE);
+ let checks = indirect::draw_check_on();
+ let census = |fate: indirect::Fate| indirect::census_on().then_some((true, Args::Own, fate));
+
+ // 1. a DRAW
+ execute_indirect(list, sig, 1, own_raw, 0, 0, 0);
+ let calls = std::mem::take(&mut *fake.list.calls.lock().unwrap());
+ let ei = calls.iter().position(|c| c.0 == 59).expect("an ExecuteIndirect");
+ let (got_sig, max, got_args, _, count, _) = *fake.list.indirect.lock().unwrap().last().unwrap();
+ if checks {
+ let dispatch = calls.iter().position(|c| c.0 == 14).expect("the check's Dispatch");
+ assert!(calls[dispatch..ei].iter().any(|c| c.0 == 30 && c.1 == rs as u64), "the draw's root signature after the check: {calls:x?}");
+ let last_pso = calls[..ei].iter().rev().find(|c| c.0 == 25).map(|c| c.1 as usize);
+ assert_eq!(last_pso, Some(pso), "the draw's pipeline the last one set before its ExecuteIndirect");
+ assert!(got_sig != sig && got_args != own_raw, "XCL's signature and checked commands, not the title's");
+ assert_eq!((max, count), (1, 0), "max 1, no count buffer");
+ assert_eq!(indirect::take_last_census(), census(indirect::Fate::Checked));
+ assert_eq!(list_x::bound_pso_for_test(list), pso, "list_x's key back on the title's pipeline");
+ } else {
+ assert!(!calls.iter().any(|c| c.0 == 14), "XCL_INDIRECT_SANITIZE_DRAWS=0: no check");
+ assert_eq!((got_sig, got_args), (sig, own_raw), "the title's signature and arguments");
+ assert_eq!(indirect::take_last_census(), census(indirect::Fate::AsIs));
+ }
+ // counted for its list as recorded: it runs with each submission of the list
+ if super::super::stall::indirect_on() {
+ assert_eq!(super::super::stall::ledger_indirect_for_test(list)[1][Args::Own.index()], 1, "the draw counted for its list, by where its arguments are");
+ }
+
+ // 2. a DRAW_INDEXED with 32 indices bound (an address reserved, never committed: not
+ // readable, so never mirrored into unified memory)
+ let reserved = windows_sys::Win32::System::Memory::VirtualAlloc(std::ptr::null(), 0x1_0000, windows_sys::Win32::System::Memory::MEM_RESERVE, windows_sys::Win32::System::Memory::PAGE_NOACCESS);
+ assert!(!reserved.is_null(), "reserve the index buffer's address");
+ let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: reserved as u64, SizeInBytes: 64, Format: DXGI_FORMAT_R16_UINT };
+ list_x::ia_set_index_buffer_x(list, &view);
+ fake.list.constants.lock().unwrap().clear();
+ execute_indirect(list, sig_indexed, 1, own_raw, 0, 0, 0);
+ if checks {
+ let words = fake.list.constants.lock().unwrap().last().cloned().expect("the check's root constants");
+ assert_eq!(words.len(), 8);
+ assert_eq!(words[6], if indirect::draw_indices_on() { 32 } else { u32::MAX }, "the indices the check bounds the range by");
+ assert_eq!(indirect::take_last_census(), census(indirect::Fate::Checked));
+ }
+
+ // 3. a bundle: no check, the title's signature and arguments
+ fake.list.ty.store(D3D12_COMMAND_LIST_TYPE_BUNDLE.0, Ordering::Relaxed);
+ fake.list.calls.lock().unwrap().clear();
+ execute_indirect(list, sig, 1, own_raw, 0, 0, 0);
+ assert_eq!(fake.count(14), 0, "no check in a bundle");
+ let (got_sig, _, got_args, ..) = *fake.list.indirect.lock().unwrap().last().unwrap();
+ assert_eq!((got_sig, got_args), (sig, own_raw), "a bundle's: the title's signature and arguments");
+ assert_eq!(indirect::take_last_census(), census(indirect::Fate::AsIs));
+
+ real::forget_pso_for_test(pso);
+ indirect::forget(sig);
+ indirect::forget(sig_indexed);
+ // (XCL's checked commands were never run: the chunk is still in its UAV state)
+ indirect::allocator_reset(allocator);
+ forget(list);
+ console_list::allocator_reset(allocator as *mut c_void);
+ list_x::on_release(list as usize);
+ windows_sys::Win32::System::Memory::VirtualFree(reserved, 0, windows_sys::Win32::System::Memory::MEM_RELEASE);
+ }
+ }
+
+ /// A draw ExecuteIndirect that records nothing (here: an unsupported root-changing signature)
+ /// is not counted for its list – only what entered a list runs with its submissions.
+ #[test]
+ fn a_failed_draw_execute_indirect_is_not_counted_for_its_list() {
+ let fake = Fake::new(0);
+ let list = fake.ptr();
+ let (pso, sig) = (0x7D0D_5000usize, 0x7D0D_50F0usize);
+ real::register_translated_graphics_for_test(pso);
+ indirect::register(sig, 0, &[]);
+ note_root_changing_signature(sig);
+ reset(list, 0x7D0D_5100, pso);
+ // (a Mac: an Err in the tail; elsewhere the root-changing skip)
+ unsafe { execute_indirect(list, sig, 1, 0, 0, 0, 0) };
+ assert_eq!(fake.count(59), 0, "nothing reached the PC");
+ assert_eq!(super::super::stall::ledger_indirect_for_test(list), [[0; 4]; 2], "a draw ExecuteIndirect not recorded is not counted for its list");
+ forget(list);
+ indirect::forget(sig);
+ real::forget_pso_for_test(pso);
+ }
+
+ /// A root signature of 3 parameters: 4 constants, a root UAV and a descriptor table (RTS0 v2).
+ fn three_param_blob() -> Vec {
+ let words: [u32; 18] = [
+ 2, 3, 24, 0, 0, 0, // version 2, 3 parameters at 24, no static samplers
+ 1, 0, 60, // constants, their payload at 60
+ 4, 0, 0, // a root UAV
+ 0, 0, 0, // a descriptor table
+ 0, 0, 4, // register 0, space 0, 4 values
+ ];
+ words.iter().flat_map(|w| w.to_le_bytes()).collect()
+ }
+
+ /// A program XCL_SKIP_CS skips has its root views logged at its first 2 skips, as run 65 reads
+ /// them (`skip_roots`): the call (Dispatch, DispatchX with its flags, ExecuteIndirect), the list,
+ /// its threads and root parameters; its constants; its root descriptor and its table's slots,
+ /// each with where its memory is and who wrote it – an empty V# of XCL's with the memory it
+ /// would have named –, the CPU's bytes outside unified memory; every line under 480 bytes
+ /// starting with the program's hash. Nothing reaches the PC. XCL_SKIP_CS_ROOTS=0: no line.
+ #[test]
+ fn a_skipped_program_logs_the_root_views_it_names() {
+ use super::super::{console_heap, skip_roots, stall};
+ use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE};
+ let _census = super::super::outside::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ let Some(u) = crate::gpu::uma::get() else { return };
+ let fake = Fake::new(0);
+ let list = fake.ptr();
+ let (pso, pso2, rs) = (0x7F0F_1001usize, 0x7F0F_1002usize, 0x7F0F_10F5usize);
+ let (hash, hash2) = (0x7F0F_0000_0000_1001u64, 0x7F0F_0000_0000_1002u64);
+ let _skip = stall::skip_for_test(&[hash, hash2]);
+ let _roots = skip_roots::budget_for_test(&[hash, hash2], 2, 16);
+ for (p, h) in [(pso, hash), (pso2, hash2)] {
+ real::register_translated_compute_for_test(p);
+ real::register_console_cs_for_test(p, h, 64);
+ }
+ console_list::note_root_signature(rs, &three_param_blob());
+ // GPU-visible title memory outside unified memory, committed: 0x2a 1 1 0 at +0x100
+ let mem = unsafe { VirtualAlloc(std::ptr::null(), 0x1_0000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) } as usize;
+ assert_ne!(mem, 0);
+ crate::hle::kernelx::note_plain_gpu_for_test(mem, 0x1_0000);
+ for (k, v) in [0x2au32, 1, 1, 0].into_iter().enumerate() {
+ unsafe { ((mem + 0x100) as *mut u32).add(k).write(v) };
+ }
+ // a heap of XCL's: slot 0 XCL's empty V# of that memory, slot 1 the title's own V# of it,
+ // the rest zeros
+ let obj = 0x7F0F_1E00usize;
+ assert!(console_heap::register(obj, 8, 0x7F0F_2000, 0, 32, false, false, true));
+ let v = console_heap::start(obj).unwrap() as usize;
+ unsafe { std::ptr::write_bytes(v as *mut u8, 0, 8 * 32) };
+ console_heap::write_view(&console_heap::slot(v as u64).unwrap(), &[0; 4], "buffer SRV", || Some((mem + 0x100, 4096)));
+ let title_v = crate::gpu::desc::buffer_words((mem + 0x200) as u64, 0, 64, 22);
+ unsafe { std::ptr::copy_nonoverlapping(title_v.as_ptr(), (v + 32) as *mut u32, 4) };
+ let bind_roots = |pso: usize| unsafe {
+ reset(list, 0x7F0F_1100, pso);
+ set_compute_root_signature(list, rs as *mut c_void);
+ let consts = [1u32, 2, 3, 4];
+ set_compute_root_constants(list, 0, 4, consts.as_ptr(), 0);
+ set_compute_root_descriptor(list, 1, (mem + 0x100) as u64);
+ set_compute_root_table(list, 2, v as u64);
+ };
+ bind_roots(pso);
+ let before = counts_snapshot();
+ unsafe { dispatch(list, 3, 2, 1) };
+ let first = skip_roots::take_lines_for_test();
+ unsafe { dispatch_x(list, 4, 1, 1, 0x20) };
+ let second = skip_roots::take_lines_for_test();
+ unsafe { dispatch(list, 1, 1, 1) };
+ let third = skip_roots::take_lines_for_test();
+ bind_roots(pso2);
+ unsafe { execute_indirect(list, 0x7F0F_10A0, 1, 0, 0, 0, 0) };
+ let indirect = skip_roots::take_lines_for_test();
+ let after = counts_snapshot();
+ for slot in [14, 25, 29, 41, 59] {
+ assert_eq!(fake.count(slot), 0, "PC slot {slot}: a skipped program records nothing");
+ }
+ assert_eq!(after[DISPATCHES_SKIPPED] - before[DISPATCHES_SKIPPED], 4);
+ forget(list);
+ console_heap::unregister(obj);
+ crate::hle::kernelx::forget_plain_gpu_for_test(mem);
+ unsafe { VirtualFree(mem as *mut c_void, 0, MEM_RELEASE) };
+ real::forget_pso_for_test(pso);
+ real::forget_pso_for_test(pso2);
+ // (XCL_SKIP_CS_ROOTS as this process was started with: 0 turns the root views off)
+ let roots_off = std::env::var("XCL_SKIP_CS_ROOTS").is_ok_and(|v| v.trim() == "0");
+ assert_eq!(skip_roots::switch_for_test(), !roots_off, "XCL_SKIP_CS_ROOTS=0: off, else on");
+ if !skip_roots::switch_for_test() {
+ assert_eq!((first, second, third, indirect), (vec![], vec![], vec![], vec![]), "XCL_SKIP_CS_ROOTS=0: no line");
+ return;
+ }
+ let prefix = format!("D3D12.X: XCL_SKIP_CS: {hash:016x} ");
+ for l in first.iter().chain(&second).chain(&third) {
+ assert!(l.starts_with(&prefix) && l.len() < 480, "{} bytes: {l}", l.len());
+ }
+ let all = first.join("\n");
+ let plain = format!("outside unified memory: in GPU-visible title memory at {mem:#x} of 64 KB (a test, flags 0x0, protection 0x0)");
+ // (memory below 4 GiB: what translated programs read there – `skip_roots::low_note`)
+ let low = if mem < 1 << 32 { "below 4 GiB: translated programs read window 0's bytes there and write nowhere; " } else { "" };
+ let t = v - u.base();
+ for want in [
+ format!("{prefix}root views at its skip #1 (#1 logged in the process): Dispatch 3×2×1 on list {:#x}, 64 threads; 3 root parameters (1 constants, 1 root descriptors, 1 tables)", list as usize),
+ format!("{prefix}p0: 4 constants [0x1, 0x2, 0x3, 0x4]"),
+ format!("{prefix}p1: root descriptor {:#x}: {plain}; the title's (its root argument); {low}on the CPU: 0000002a 00000001 00000001 00000000 (dwords)", mem + 0x100),
+ format!("{prefix}p2: table {t:#x}: slots of heap {obj:#x} from #0 (XCL's memory, shader visible); empty, no view of XCL's made there (zeros of the title's, or its copy of an empty V#): [2, 3, 4, 5, 6, 7]"),
+ format!(
+ "{prefix}p2[0]: empty V# (XCL's buffer SRV named {:#x}, 4096 bytes, or a copy of an empty V# over it: the same bytes); {plain}; XCL's buffer SRV or a copy of an empty V# over it (the same bytes); {low}on the CPU: 0000002a 00000001 00000001 00000000 (dwords)",
+ mem + 0x100
+ ),
+ format!("{prefix}p2[1]: V# {:#x}, 64 bytes (stride 0, 64 records, format 22); {plain}; the title's bytes (no view of XCL's made in this slot: its own descriptor or a copy); {low}on the CPU: 00000000 00000000 00000000 00000000 (dwords)", mem + 0x200),
+ ] {
+ assert!(first.contains(&want), "missing:\n{want}\nin:\n{all}");
+ }
+ assert_eq!(first.len(), 6, "{all}");
+ assert!(second[0].starts_with(&format!("{prefix}root views at its skip #2 (#2 logged in the process): DispatchX 4×1×1 (flags 0x20) on list ")), "{second:?}");
+ assert_eq!(&second[1..], &first[1..], "the same views at its second skip");
+ assert_eq!(third, Vec::::new(), "a program's third skip: no line");
+ assert!(
+ indirect[0].starts_with(&format!("D3D12.X: XCL_SKIP_CS: {hash2:016x} root views at its skip #1 (#3 logged in the process): ExecuteIndirect of up to 1 command(s) with signature 0x7f0f10a0: arguments unknown on list ")),
+ "{indirect:?}"
+ );
+ assert_eq!(indirect.len(), 6, "{indirect:?}");
+ }
+
+ /// A program XCL_SKIP_CS lists whose stand-in is not built – late at its bind (a Dispatch), or
+ /// failed (an ExecuteIndirect) – has its root views logged at its skip all the same, the head
+ /// saying its work is skipped as unbuilt; the work stays skipped, nothing reaches the PC (F-6).
+ /// Pipelines and hashes 0x7A0C_90xx.
+ #[test]
+ fn a_listed_program_not_built_yet_logs_its_root_views_at_its_skip() {
+ use super::super::{skip_roots, stall};
+ let fake = Fake::new(0);
+ let list = fake.ptr();
+ let (late, failed) = (0x7A0C_9001usize, 0x7A0C_9002usize);
+ let (h_late, h_failed) = (0x7A0C_0000_0000_9001u64, 0x7A0C_0000_0000_9002u64);
+ let _skip = stall::skip_for_test(&[h_late, h_failed]);
+ let _roots = skip_roots::budget_for_test(&[h_late, h_failed], 2, 16);
+ let prog = |h: u64| pso_async::Program { hash: h, kind: b'C', dxil: 16 << 10, ..Default::default() };
+ // late: a lazy one past its wait, never sent (its job never runs); failed: refused when made
+ pso_async::submit_program(late, true, Box::new(|| 0), true, 0, prog(h_late));
+ pso_async::make_late_for_test(late);
+ pso_async::submit_refused(failed, true, 0, prog(h_failed));
+ reset(list, 0x7A0C_9100, late);
+ unsafe { dispatch(list, 3, 2, 1) };
+ let dispatched = skip_roots::take_lines_for_test();
+ let skipped_late = take_last_unbuilt();
+ reset(list, 0x7A0C_9100, failed);
+ unsafe { execute_indirect(list, 0x7A0C_90A0, 1, 0, 0, 0, 0) };
+ let indirect = skip_roots::take_lines_for_test();
+ let skipped_failed = take_last_unbuilt();
+ let pc = (fake.count(14), fake.count(59));
+ forget(list);
+ let _ = pso_async::released(late);
+ let _ = pso_async::released(failed);
+ assert_eq!(pc, (0, 0), "work of a pipeline not built never reaches the PC");
+ assert_eq!(skipped_late, Some((late, U_DISPATCH, Unbuilt::Late)), "the Dispatch skipped as unbuilt");
+ assert_eq!(skipped_failed, Some((failed, U_INDIRECT_COMPUTE, Unbuilt::Failed)), "the ExecuteIndirect skipped as unbuilt");
+ if !skip_roots::switch_for_test() {
+ assert_eq!((dispatched, indirect), (vec![], vec![]), "XCL_SKIP_CS_ROOTS=0: no line");
+ return;
+ }
+ let head = format!(
+ "D3D12.X: XCL_SKIP_CS: {h_late:016x} root views at its skip #1 (#1 logged in the process): Dispatch 3×2×1 on list {:#x}, its pipeline not built yet – its work skipped as unbuilt ({})",
+ list as usize,
+ Unbuilt::Late.describe()
+ );
+ assert!(dispatched.first().is_some_and(|l| l.starts_with(&head)), "missing:\n{head}\nin:\n{dispatched:?}");
+ let head = format!("D3D12.X: XCL_SKIP_CS: {h_failed:016x} root views at its skip #1 (#2 logged in the process): ExecuteIndirect of up to 1 command(s) with signature 0x7a0c90a0: arguments unknown on list {:#x}, its pipeline not built yet", list as usize);
+ assert!(indirect.first().is_some_and(|l| l.starts_with(&head) && l.contains(Unbuilt::Failed.describe())), "missing:\n{head}\nin:\n{indirect:?}");
+ }
+
+ /// The world's first frame (`XCL_FRAME_DUMP_WORLD`) is marked by the first skipped dispatch of a
+ /// program XCL_SKIP_CS lists – one not built yet (`skipped_unbuilt_roots`, with no root views to
+ /// log) or a built one (`skip_cs`) –, the first kept; the title's DeserializePipelineStateX before
+ /// it (GTA VI's first: ~4.6 s into its loading) and the skip of a program not listed are no
+ /// mark. Nothing reaches the PC. On a world mark of this thread's own. Pipelines and hashes
+ /// 0x7A1E_70xx.
+ #[test]
+ fn the_first_skip_of_a_listed_program_marks_the_worlds_first_frame() {
+ use super::super::{device_x, present, stall};
+ let fake = Fake::new(0);
+ let list = fake.ptr();
+ let (late, other, built) = (0x7A1E_7001usize, 0x7A1E_7003usize, 0x7A1E_7002usize);
+ let (h_late, h_other, h_built) = (0x7A1E_0000_0000_7001u64, 0x7A1E_0000_0000_7003u64, 0x7A1E_0000_0000_7002u64);
+ let _skip = stall::skip_for_test(&[h_late, h_built]);
+ let prog = |h: u64| pso_async::Program { hash: h, kind: b'C', dxil: 16 << 10, ..Default::default() };
+ // not built yet: lazy ones past their wait, never sent (their jobs never run)
+ for (p, h) in [(late, h_late), (other, h_other)] {
+ pso_async::submit_program(p, true, Box::new(|| 0), true, 0, prog(h));
+ pso_async::make_late_for_test(p);
+ }
+ real::register_translated_compute_for_test(built);
+ real::register_console_cs_for_test(built, h_built, 64);
+ let dispatch_of = |pso: usize| unsafe {
+ reset(list, 0x7A1E_7100, pso);
+ dispatch(list, 2, 1, 1);
+ };
+ // a Deserialize call and the skip of a program not listed first: no mark; then the one not
+ // built yet, then a built one
+ let world = present::world_mark_for_test();
+ let mut out = std::ptr::null_mut();
+ let _ = unsafe { device_x::deserialize_pso_x(std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), &mut out) };
+ dispatch_of(other);
+ let before_any = (present::test_world_mark(), present::world_mark_open());
+ let p0 = present::presents();
+ dispatch_of(late);
+ let p1 = present::presents();
+ let by_late = present::test_world_mark();
+ dispatch_of(built);
+ let kept = (present::test_world_mark(), present::world_mark_open());
+ drop(world);
+ // a built one's skip first
+ let world = present::world_mark_for_test();
+ dispatch_of(built);
+ dispatch_of(late);
+ let by_built = present::test_world_mark();
+ drop(world);
+ let skipped_late = take_last_unbuilt();
+ let pc = (fake.count(14), fake.count(25));
+ forget(list);
+ let _ = pso_async::released(late);
+ let _ = pso_async::released(other);
+ real::forget_pso_for_test(built);
+ assert_eq!(before_any, (None, true), "a DeserializePipelineStateX call and the skip of a program not listed are no mark");
+ let (at, hash) = by_late.expect("the skip of a listed program not built yet marks the world");
+ assert!(hash == h_late && at >= p0 && at <= p1, "{by_late:?} ({p0}-{p1})");
+ assert_eq!(kept, (by_late, false), "a later skip leaves the first mark");
+ assert_eq!(by_built.map(|m| m.1), Some(h_built), "a built one's skip (skip_cs) marks it");
+ assert_eq!(skipped_late, Some((late, U_DISPATCH, Unbuilt::Late)), "the one not built yet skipped as unbuilt, as before");
+ assert_eq!(pc, (0, 0), "nothing reaches the PC");
+ }
+
+ /// DispatchX's flags are named once per value – never 0, 16 values at most – with the program
+ /// and the counts as given (`D3D12.X: DispatchX flags …: not applied`); the DispatchX goes on as
+ /// a Dispatch of those counts.
+ #[test]
+ fn dispatch_x_flags_are_named_once_per_value_and_never_for_zero() {
+ let seen = FirstValues::new();
+ assert!(!seen.first(0), "0: no flags");
+ assert!(seen.first(0x20));
+ assert!(!seen.first(0x20), "once per value");
+ assert!(seen.first(0x40));
+ for v in 1..=14u32 {
+ assert!(seen.first(0x1000 + v), "{v}");
+ }
+ assert!(!seen.first(0x2000), "16 values at most");
+ assert!(!seen.first(0x40));
+ assert_eq!(dispatch_x_flags_line(0x20, 0x71f4_ac8a_d5eb_a33c, [64, 1, 1]), "D3D12.X: DispatchX flags 0x20 (71f4ac8ad5eba33c, counts 64×1×1): not applied");
+ // through DispatchX (#78): once per value, the counts as given; each DispatchX a Dispatch
+ let fake = Fake::new(0);
+ let list = fake.ptr();
+ let (pso, hash) = (0x7F0F_6001usize, 0x7F0F_0000_0000_6001u64);
+ // (skipped: a test process has no unified memory open on the GPU to bind)
+ let _skip = super::super::stall::skip_for_test(&[hash]);
+ real::register_translated_compute_for_test(pso);
+ real::register_console_cs_for_test(pso, hash, 64);
+ reset(list, 0x7F0F_6100, pso);
+ // (a value no other test gives)
+ let flags = 0x7F0F_0020;
+ let before = counts_snapshot();
+ unsafe {
+ list_x::dispatch_x(list, 5, 6, 7, flags);
+ list_x::dispatch_x(list, 8, 9, 10, flags);
+ list_x::dispatch_x(list, 1, 1, 1, 0);
+ }
+ let lines = FLAGS_LINES.with(|l| std::mem::take(&mut *l.borrow_mut()));
+ let after = counts_snapshot();
+ forget(list);
+ real::forget_pso_for_test(pso);
+ assert_eq!(lines, vec![dispatch_x_flags_line(flags, hash, [5, 6, 7])]);
+ assert_eq!(after[DISPATCHES_SKIPPED] - before[DISPATCHES_SKIPPED], 3, "each DispatchX went on as a Dispatch");
+ assert_eq!(fake.count(14), 0);
+ }
+
+ /// The `ExecuteIndirect recorded so far` line, as run 65's tools read it: each kind, place and
+ /// fate in its place, the draws checked in the last 2 s, the work skipped for pipelines not built.
+ #[test]
+ fn the_indirect_line_names_each_kind_place_and_fate() {
+ use super::super::stall::Args;
+ use indirect::Fate;
+ let (window, own, unknown) = (Args::Window(0).index(), Args::Own.index(), Args::Unknown.index());
+ let mut c = indirect::CensusSnapshot::default();
+ c.n[0][window][Fate::Checked as usize] = 8;
+ c.n[0][own][Fate::Checked as usize] = 113;
+ c.counted[0] = [2, 1];
+ c.n[1][window][Fate::AsIs as usize] = 6;
+ c.n[1][own][Fate::Checked as usize] = 20;
+ c.n[1][own][Fate::AsIs as usize] = 3;
+ c.n[1][own][Fate::Failed as usize] = 3;
+ c.n[1][unknown][Fate::Failed as usize] = 1;
+ c.unread = 4;
+ assert_eq!(
+ indirect_line_text(&c.text(7), &[5, 3, 0, 0, 40]),
+ "ExecuteIndirect recorded so far: compute 121 (unified memory 8, upload 0, outside unified memory 113, unknown 0; checked 121, as they were 0, skipped for XCL_INDIRECT_OWN 0, not recorded 0; 2 with a count buffer, 1 of those outside unified memory), draws 33 (unified memory 6, upload 0, outside unified memory 26, unknown 1; checked 20, as they were 9, skipped for XCL_INDIRECT_OWN 0, not recorded 4; 0 with a count buffer, 0 of those outside unified memory; 4 with a signature the check does not read), 7 draws checked in the last 2 s; work skipped for a pipeline not built: 5 Dispatch, 3 compute and 0 draw ExecuteIndirect, 0 DispatchMesh, 40 draws"
+ );
+ }
+
#[test]
fn create_list_reset_and_clear_state_track_initial_pso_on_d3d12() {
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
diff --git a/crates/xcl/src/hle/d3d12x/compose.rs b/crates/xcl/src/hle/d3d12x/compose.rs
new file mode 100644
index 0000000..f35ad55
--- /dev/null
+++ b/crates/xcl/src/hle/d3d12x/compose.rs
@@ -0,0 +1,278 @@
+//! The console's display planes, composed for the XCL window.
+//!
+//! A title may present more than one plane in a PresentX: GTA VI as a Series S shows its 3D
+//! image at 1920×1080 in plane 0 and its interface at 3840×2160 in plane 1, both over the whole
+//! screen. The console's display composes them – each plane's source rectangle scaled to its
+//! place on the screen, each over the ones before it with its alpha (premultiplied, as the
+//! display planes are). One full-screen triangle does the same into the XCL window's back
+//! buffer: the planes are sampled with a linear filter (a 1080p plane under a 2160p one is
+//! scaled up as the display scaler would), composed over black, and written opaque.
+
+use std::ffi::c_void;
+use std::mem::transmute_copy;
+
+use windows::core::Interface;
+use windows::Win32::Foundation::RECT;
+use windows::Win32::Graphics::Direct3D::*;
+use windows::Win32::Graphics::Direct3D12::*;
+use windows::Win32::Graphics::Dxgi::Common::*;
+
+/// Planes one composition takes (a console shows two title planes; more are not drawn).
+pub const MAX_PLANES: usize = 4;
+
+/// Root constants: four source rects, four destinations (float4 each), the plane count.
+const CONSTANT_WORDS: u32 = 4 * MAX_PLANES as u32 * 2 + 1;
+
+const HLSL: &str = r#"
+Texture2D plane0 : register(t0);
+Texture2D plane1 : register(t1);
+Texture2D plane2 : register(t2);
+Texture2D plane3 : register(t3);
+SamplerState linear_clamp : register(s0);
+
+cbuffer Planes : register(b0) {
+ float4 src[4]; // the part of each plane shown, 0..1 of its texels: left, top, right, bottom
+ float4 dst[4]; // where on the screen, 0..1: left, top, right, bottom
+ uint count;
+};
+
+struct V {
+ float4 pos : SV_Position;
+ float2 uv : TEXCOORD0;
+};
+
+V vs_main(uint id : SV_VertexID) {
+ V o;
+ float2 uv = float2((id << 1) & 2, id & 2);
+ o.pos = float4(uv * float2(2, -2) + float2(-1, 1), 0, 1);
+ o.uv = uv;
+ return o;
+}
+
+float4 layer(Texture2D t, float4 s, float4 d, float2 uv) {
+ if (uv.x < d.x || uv.y < d.y || uv.x >= d.z || uv.y >= d.w) {
+ return 0;
+ }
+ float2 f = (uv - d.xy) / max(d.zw - d.xy, 1e-6);
+ return t.SampleLevel(linear_clamp, lerp(s.xy, s.zw, f), 0);
+}
+
+// premultiplied alpha: the plane over what is under it
+float4 over(float4 top, float4 under) {
+ return top + (1 - top.a) * under;
+}
+
+float4 ps_main(V v) : SV_Target {
+ float4 c = float4(0, 0, 0, 1);
+ c = over(layer(plane0, src[0], dst[0], v.uv), c);
+ if (count > 1) { c = over(layer(plane1, src[1], dst[1], v.uv), c); }
+ if (count > 2) { c = over(layer(plane2, src[2], dst[2], v.uv), c); }
+ if (count > 3) { c = over(layer(plane3, src[3], dst[3], v.uv), c); }
+ return float4(c.rgb, 1);
+}
+"#;
+
+/// One plane of a present: its resource, the part of it shown (texels: left, top, right,
+/// bottom) and where on the screen (0..1: left, top, right, bottom).
+pub struct Plane {
+ pub res: ID3D12Resource,
+ pub src: [f32; 4],
+ pub dst: [f32; 4],
+}
+
+/// The pipeline that composes planes into a back buffer of one format.
+pub struct Composer {
+ dev: usize,
+ fmt: DXGI_FORMAT,
+ root: ID3D12RootSignature,
+ pso: ID3D12PipelineState,
+ /// SRVs of the planes (shader visible; rewritten for each present – the presenter waits for
+ /// the previous one first)
+ srvs: ID3D12DescriptorHeap,
+ rtvs: ID3D12DescriptorHeap,
+ inc: usize,
+}
+
+// D3D12 objects are free-threaded
+unsafe impl Send for Composer {}
+
+/// The format a plane is read with: its typeless and sRGB forms as their UNORM one (the bytes
+/// go to the window as they are, as a copy would take them).
+fn view_format(f: DXGI_FORMAT) -> DXGI_FORMAT {
+ super::present::swap_format(f).unwrap_or(f)
+}
+
+impl Composer {
+ /// The composer for back buffers of format `fmt` on `dev`.
+ pub unsafe fn new(dev: &ID3D12Device, fmt: DXGI_FORMAT) -> Result {
+ let vs = crate::gpu::recomp::dxc::compile(HLSL, "vs_main", "vs_6_0", &[])?;
+ let ps = crate::gpu::recomp::dxc::compile(HLSL, "ps_main", "ps_6_0", &[])?;
+ let range = D3D12_DESCRIPTOR_RANGE {
+ RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
+ NumDescriptors: MAX_PLANES as u32,
+ BaseShaderRegister: 0,
+ RegisterSpace: 0,
+ OffsetInDescriptorsFromTableStart: 0,
+ };
+ let params = [
+ D3D12_ROOT_PARAMETER {
+ ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE,
+ Anonymous: D3D12_ROOT_PARAMETER_0 { DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &range } },
+ ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL,
+ },
+ D3D12_ROOT_PARAMETER {
+ ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS,
+ Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: CONSTANT_WORDS } },
+ ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL,
+ },
+ ];
+ let sampler = D3D12_STATIC_SAMPLER_DESC {
+ Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR,
+ AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
+ AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
+ AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
+ MipLODBias: 0.0,
+ MaxAnisotropy: 1,
+ ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER,
+ BorderColor: D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK,
+ MinLOD: 0.0,
+ MaxLOD: f32::MAX,
+ ShaderRegister: 0,
+ RegisterSpace: 0,
+ ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL,
+ };
+ let desc = D3D12_ROOT_SIGNATURE_DESC {
+ NumParameters: params.len() as u32,
+ pParameters: params.as_ptr(),
+ NumStaticSamplers: 1,
+ pStaticSamplers: &sampler,
+ Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE,
+ };
+ let mut blob = None;
+ D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &mut blob, None).map_err(|e| format!("serialize the plane composer's root signature: {e}"))?;
+ let blob = blob.ok_or("no root signature blob for the plane composer")?;
+ let root: ID3D12RootSignature = dev
+ .CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer().cast(), blob.GetBufferSize()))
+ .map_err(|e| format!("create the plane composer's root signature: {e}"))?;
+ let mut pd = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
+ pRootSignature: transmute_copy(&root),
+ VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as _, BytecodeLength: vs.len() },
+ PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as _, BytecodeLength: ps.len() },
+ SampleMask: u32::MAX,
+ PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
+ NumRenderTargets: 1,
+ SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+ ..Default::default()
+ };
+ pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8;
+ pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
+ pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
+ pd.RasterizerState.DepthClipEnable = true.into();
+ pd.RTVFormats[0] = fmt;
+ let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&pd).map_err(|e| format!("create the plane composer's pipeline: {e}"))?;
+ let srvs: ID3D12DescriptorHeap = dev
+ .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
+ Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
+ NumDescriptors: MAX_PLANES as u32,
+ Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
+ NodeMask: 0,
+ })
+ .map_err(|e| format!("the plane composer's SRV heap: {e}"))?;
+ let rtvs: ID3D12DescriptorHeap = dev
+ .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() })
+ .map_err(|e| format!("the plane composer's RTV heap: {e}"))?;
+ let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize;
+ Ok(Composer { dev: dev.as_raw() as usize, fmt, root, pso, srvs, rtvs, inc })
+ }
+
+ /// Made for back buffers of `fmt` on `dev`.
+ pub fn fits(&self, dev: &ID3D12Device, fmt: DXGI_FORMAT) -> bool {
+ self.dev == dev.as_raw() as usize && self.fmt == fmt
+ }
+
+ /// Records into `list` the composition of `planes` (bottom first) into `target` (`w`×`h`,
+ /// in the RENDER_TARGET state). The planes are read from the COMMON state the console's
+ /// PresentX leaves them in (implicitly promoted, as the single plane's copy is).
+ pub unsafe fn record(&self, dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, target: &ID3D12Resource, w: u32, h: u32, planes: &[Plane]) {
+ let cpu = self.srvs.GetCPUDescriptorHandleForHeapStart();
+ let mut constants = [0u32; CONSTANT_WORDS as usize];
+ for k in 0..MAX_PLANES {
+ let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu.ptr + k * self.inc };
+ let plane = planes.get(k);
+ let format = plane.map_or(DXGI_FORMAT_R8G8B8A8_UNORM, |p| view_format(p.res.GetDesc().Format));
+ let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
+ Format: format,
+ ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
+ Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
+ Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, PlaneSlice: 0, ResourceMinLODClamp: 0.0 } },
+ };
+ dev.CreateShaderResourceView(plane.map(|p| &p.res), Some(&desc), at);
+ if let Some(p) = plane {
+ let d = p.res.GetDesc();
+ let (pw, ph) = ((d.Width as f32).max(1.0), (d.Height as f32).max(1.0));
+ let src = [p.src[0] / pw, p.src[1] / ph, p.src[2] / pw, p.src[3] / ph];
+ for j in 0..4 {
+ constants[4 * k + j] = src[j].to_bits();
+ constants[4 * MAX_PLANES + 4 * k + j] = p.dst[j].to_bits();
+ }
+ }
+ }
+ constants[8 * MAX_PLANES] = planes.len().min(MAX_PLANES) as u32;
+ let rtv = self.rtvs.GetCPUDescriptorHandleForHeapStart();
+ dev.CreateRenderTargetView(target, None, rtv);
+ list.SetGraphicsRootSignature(&self.root);
+ list.SetDescriptorHeaps(&[Some(self.srvs.clone())]);
+ list.SetGraphicsRootDescriptorTable(0, self.srvs.GetGPUDescriptorHandleForHeapStart());
+ list.SetGraphicsRoot32BitConstants(1, CONSTANT_WORDS, constants.as_ptr() as *const c_void, 0);
+ list.SetPipelineState(&self.pso);
+ list.OMSetRenderTargets(1, Some(&rtv), false, None);
+ list.RSSetViewports(&[D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: w as f32, Height: h as f32, MinDepth: 0.0, MaxDepth: 1.0 }]);
+ list.RSSetScissorRects(&[RECT { left: 0, top: 0, right: w as i32, bottom: h as i32 }]);
+ list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ list.DrawInstanced(3, 1, 0, 0);
+ }
+}
+
+/// A plane's source rect from the title's (texels, as i32: left, top, right, bottom) – the
+/// whole resource when there is none or it is empty or outside it.
+pub fn source_rect(rect: Option<[i32; 4]>, w: u64, h: u64) -> [f32; 4] {
+ let full = [0.0, 0.0, w as f32, h as f32];
+ let Some([l, t, r, b]) = rect else { return full };
+ if l < 0 || t < 0 || r <= l || b <= t || r as u64 > w || b as u64 > h {
+ return full;
+ }
+ [l as f32, t as f32, r as f32, b as f32]
+}
+
+/// A plane's place on the screen from the title's (0..1: left, top, right, bottom) – the whole
+/// screen when there is none or it is not a sane rectangle.
+pub fn destination(rect: Option<[f32; 4]>) -> [f32; 4] {
+ let full = [0.0, 0.0, 1.0, 1.0];
+ let Some([l, t, r, b]) = rect else { return full };
+ let sane = [l, t, r, b].iter().all(|v| v.is_finite() && (-1.0..=2.0).contains(v)) && r > l && b > t;
+ if sane {
+ [l, t, r, b]
+ } else {
+ full
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn plane_rects() {
+ assert_eq!(source_rect(Some([0, 0, 1920, 1080]), 1920, 1080), [0.0, 0.0, 1920.0, 1080.0]);
+ assert_eq!(source_rect(Some([0, 0, 1280, 720]), 1920, 1080), [0.0, 0.0, 1280.0, 720.0]); // dynamic resolution
+ assert_eq!(source_rect(Some([0, 0, 4000, 1080]), 1920, 1080), [0.0, 0.0, 1920.0, 1080.0]);
+ assert_eq!(source_rect(Some([10, 10, 5, 20]), 1920, 1080), [0.0, 0.0, 1920.0, 1080.0]);
+ assert_eq!(source_rect(None, 3840, 2160), [0.0, 0.0, 3840.0, 2160.0]);
+ assert_eq!(destination(Some([0.0, 0.0, 1.0, 1.0])), [0.0, 0.0, 1.0, 1.0]);
+ assert_eq!(destination(Some([0.25, 0.25, 0.75, 0.75])), [0.25, 0.25, 0.75, 0.75]);
+ assert_eq!(destination(Some([f32::NAN, 0.0, 1.0, 1.0])), [0.0, 0.0, 1.0, 1.0]);
+ assert_eq!(destination(Some([0.0, 0.0, 0.0, 1.0])), [0.0, 0.0, 1.0, 1.0]);
+ assert_eq!(destination(None), [0.0, 0.0, 1.0, 1.0]);
+ assert_eq!(CONSTANT_WORDS, 33);
+ }
+}
diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs
index efc4d80..94bf74a 100644
--- a/crates/xcl/src/hle/d3d12x/console_heap.rs
+++ b/crates/xcl/src/hle/d3d12x/console_heap.rs
@@ -161,6 +161,8 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool {
next: 0,
free: Vec::new(),
});
+ // (the view census's map of it, while the heap is still held: before any view goes there)
+ super::view_census::make(cap);
}
true
}
@@ -212,6 +214,72 @@ pub fn in_global(obj: usize) -> bool {
HEAPS.lock().unwrap().iter().any(|h| h.obj == obj && !h.pages.is_empty())
}
+/// The shared heap's extent for the view census: (descriptors given out – places `[0, next)` were
+/// all used once –, its size, its released ranges (first, count) sorted by first). None: no shared
+/// heap.
+pub(super) fn global_extent() -> Option<(u32, u32, Vec<(u32, u32)>)> {
+ let (next, cap, mut free) = {
+ let g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+ let s = g.as_ref()?;
+ (s.next, s.cap, s.free.clone())
+ };
+ free.sort_unstable();
+ Some((next, cap, free))
+}
+
+/// `f(place)` for the places in the shared heap of CPU-only heaps' view slots whose words no longer
+/// hold their own image T# – the title wrote them over as memory (a CBV, a buffer V#, zeros, a copy
+/// of another slot), or nothing was ever written: the resync walks shader-visible heaps only, so
+/// the shared heap's descriptors there (the slot's SRV and UAV places, both given) still name what
+/// XCL last put there, reachable through any T# that carries the place (the view census). The words
+/// are read a page at a time under the heaps' lock – a heap's memory goes only once it is out of
+/// `HEAPS` –, so a title's view call waits for one page's look at most.
+pub(super) fn cpu_only_stale(mut f: impl FnMut(u32)) {
+ let pages: Vec<(usize, usize)> = HEAPS
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .iter()
+ .filter(|h| !h.visible && !h.sampler && h.shadow != 0)
+ .flat_map(|h| h.pages.iter().enumerate().filter(|&(_, &first)| first != UNMAPPED).map(move |(p, _)| (h.obj, p)))
+ .collect();
+ let mut words = vec![[0u32; 8]; PAGE_SLOTS as usize];
+ for (obj, p) in pages {
+ let (first, n) = {
+ let heaps = HEAPS.lock().unwrap_or_else(|e| e.into_inner());
+ // (gone since, or its object's address another heap's now: that one's page, if placed)
+ let Some(h) = heaps.iter().find(|h| h.obj == obj && !h.visible && !h.sampler && h.shadow != 0) else { continue };
+ let Some(&first) = h.pages.get(p).filter(|&&first| first != UNMAPPED) else { continue };
+ let k0 = p as u32 * PAGE_SLOTS;
+ let n = (k0 + PAGE_SLOTS).min(h.n).saturating_sub(k0);
+ for (j, w) in words.iter_mut().enumerate().take(n as usize) {
+ unsafe { std::ptr::copy_nonoverlapping((h.shadow + ((k0 + j as u32) * SLOT) as usize) as *const u32, w.as_mut_ptr(), 8) };
+ }
+ (first, n)
+ };
+ for (j, w) in words.iter().enumerate().take(n as usize) {
+ let own = first + 2 * j as u32;
+ if !(w[3] >> 28 >= 8 && w[0] == own) {
+ f(own);
+ f(own + 1);
+ }
+ }
+ }
+}
+
+/// Tests that take places in the shared heap and give them back: one at a time (where the next
+/// place goes depends on what was given back before – `large_heaps_get_shared_pages_as_used`
+/// counts on two small heaps getting places side by side; the view census's tests read what their
+/// heap's places hold).
+#[cfg(test)]
+pub(super) static SHARED_RANGES: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+/// (tests) the shared heap's device – what a test's own descriptor heaps and resources are made
+/// with, so `publish`'s copies stay on one device.
+#[cfg(test)]
+pub(super) fn shared_device_for_test() -> Option {
+ GLOBAL.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|g| g.dev.clone())
+}
+
/// Memory for a heap of `bytes` from the title's allocation hook – where the title expects the
/// heap then. Only what descriptor tables can address (window 0) and is committed; anything else
/// goes back to the title.
@@ -294,8 +362,15 @@ fn unregister_with_resync(obj: usize, track_resync: bool) {
})
};
if let Some(h) = gone {
+ // (the view census: the title heap's descriptors go with it before its places go back;
+ // atomics only – this can run on the ledger's thread)
+ let names = super::view_census::names();
for (p, &f) in h.pages.iter().enumerate().filter(|&(_, &f)| f != UNMAPPED) {
- release_global(f, page_descriptors(h.n, p as u32));
+ let count = page_descriptors(h.n, p as u32);
+ if let Some(m) = names {
+ m.heap_gone(f, count);
+ }
+ release_global(f, count);
}
match h.memory {
Memory::Sparse => {
@@ -308,6 +383,15 @@ fn unregister_with_resync(obj: usize, track_resync: bool) {
}
Memory::Title => unsafe { crate::hle::kernelx::runtime_free(h.shadow, crate::hle::kernelx::D3D_DESCRIPTOR_HEAP) },
}
+ // (XCL's views in its slots: the memory may be another heap's next)
+ let end = h.shadow.saturating_add(h.n as usize * h.slot_bytes() as usize);
+ WROTE.lock().unwrap_or_else(|e| e.into_inner()).forget(h.shadow, end);
+ #[cfg(test)]
+ TEST_RECORD.with(|t| {
+ if let Some(r) = t.borrow_mut().as_mut() {
+ r.forget(h.shadow, end);
+ }
+ });
}
}
@@ -354,6 +438,38 @@ pub fn slot(cpu: u64) -> Option {
Some(Slot { at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k })
}
+/// The PC view just made in slot `s` – its SRV, or with `uav` its UAV, in the title's heap – names
+/// `res` (0: a null view): one store into the view census's map (`view_census`), after the driver's
+/// call. A slot with no place in the shared heap is counted, not mapped.
+#[inline]
+pub fn note_pc_view(s: &Slot, uav: bool, res: usize) {
+ if s.sampler {
+ return;
+ }
+ let Some(m) = super::view_census::names() else { return };
+ if s.shared_srv != 0 {
+ m.title_view(s.index, uav, res);
+ } else {
+ m.note_untracked();
+ }
+}
+
+/// A device copy (`real::copy_console_slots`) wrote both PC descriptors of view slot `d` – in the
+/// title's heap and then the shared heap's – from slot `s` (None: not a console slot): the view
+/// census's map follows (a source with no place in the shared heap: not known).
+#[inline]
+pub fn note_copied_view(d: &Slot, s: Option<&Slot>) {
+ if d.sampler {
+ return;
+ }
+ let Some(m) = super::view_census::names() else { return };
+ match s {
+ _ if d.shared_srv == 0 => m.note_untracked(),
+ Some(s) if s.shared_srv != 0 && !s.sampler => m.copied(d.index, s.index),
+ _ => m.copied_unknown(d.index),
+ }
+}
+
/// The view just made in slot `s` (its SRV, or with `uav` its UAV) goes to the shared heap.
pub unsafe fn publish(s: &Slot, uav: bool) {
if s.shared_srv == 0 {
@@ -362,6 +478,9 @@ pub unsafe fn publish(s: &Slot, uav: bool) {
if let Some(g) = GLOBAL.lock().unwrap().as_ref() {
let (dst, src) = if uav { (s.shared_srv + g.inc as u64, s.pc_uav) } else { (s.shared_srv, s.pc_srv) };
g.dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
+ if let Some(m) = super::view_census::names() {
+ m.published(s.index + uav as u32);
+ }
}
}
@@ -404,29 +523,251 @@ pub fn resource_at(at: usize) -> Option {
RES.lock().unwrap().as_ref()?.get(&at).copied()
}
+/// `words` into slot `s` (`write_view`: a view of XCL's, not named).
pub fn write(s: &Slot, words: &[u32]) {
+ write_view(s, words, "view", || None)
+}
+
+/// XCL's view of `what` ("buffer SRV", "CBV" …) into slot `s`: its words; `at` gives the title
+/// memory the view names – an empty V#'s, the memory it would have named –, asked only while
+/// XCL's views are recorded (`Wrote`).
+pub fn write_view(s: &Slot, words: &[u32], what: &'static str, at: impl FnOnce() -> Option<(usize, u64)>) {
+ write_named(s, words, what, || at().map(|(a, n)| Names::Memory(a, n)))
+}
+
+/// XCL's view of `what` of texture `res` (its T#, or an empty view of a shape XCL cannot describe)
+/// into slot `s`: the texture's title address is looked up only when a line names the slot
+/// (`Names::Texture`), not in the title's view calls.
+pub fn write_texture_view(s: &Slot, words: &[u32], what: &'static str, res: usize) {
+ write_named(s, words, what, || (res != 0).then_some(Names::Texture(res)))
+}
+
+fn write_named(s: &Slot, words: &[u32], what: &'static str, names: impl FnOnce() -> Option) {
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) };
+ if !s.sampler && super::skip_roots::recording() {
+ // (the slot's 8 words as the write left them – a buffer V#'s 4 leave the other 4 as they
+ // were: a later copy that differs in those is the title's)
+ let mut now = [0u32; 8];
+ unsafe { std::ptr::copy_nonoverlapping(s.at as *const u32, now.as_mut_ptr(), 8) };
+ note_wrote(s.at, Wrote { what, tag: tag(&now), names: names() });
+ }
+}
+
+/// The title memory a view of XCL's names (`Wrote`): an address and its bytes – or a texture, its
+/// address looked up when a line names the slot (`now`): `title_textures`' lock stays off the
+/// title's view calls (run 64: some 770 texture views a second while its world loaded). A key
+/// lookup – a texture gone since names nothing, and is never touched.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Names {
+ Memory(usize, u64),
+ Texture(usize),
+}
+
+impl Names {
+ /// (address, bytes) now – a texture's bytes not counted: 0
+ fn now(self) -> Option<(usize, u64)> {
+ match self {
+ Names::Memory(a, n) => Some((a, n)),
+ Names::Texture(res) => super::real::texture_address(res),
+ }
+ }
+}
+
+/// A view XCL wrote into a slot: what it is, a tag of the slot's 8 words as XCL's write left them,
+/// and the title memory it names. Kept while `XCL_SKIP_CS`'s root views are still to be logged
+/// (`skip_roots::recording`: they tell XCL's descriptors from the title's own bytes – its own
+/// descriptors, its copies of slots – by it), for `WROTE_MAX` slots.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct Wrote {
+ what: &'static str,
+ tag: u64,
+ names: Option,
+}
+
+/// XCL's record of the views it wrote: slot address → what XCL last wrote there, `max` slots at
+/// most; `full`: a slot was not recorded for want of room – an unrecorded slot's writer is not
+/// known from then on.
+struct Record {
+ wrote: std::collections::BTreeMap,
+ max: usize,
+ full: bool,
+}
+
+impl Record {
+ const fn new(max: usize) -> Record {
+ Record { wrote: std::collections::BTreeMap::new(), max, full: false }
+ }
+
+ /// `w` is what XCL wrote at `at`; Some(max): that filled the record (its first slot not
+ /// recorded – once).
+ fn note(&mut self, at: usize, w: Wrote) -> Option {
+ if self.wrote.len() >= self.max && !self.wrote.contains_key(&at) {
+ return (!std::mem::replace(&mut self.full, true)).then_some(self.max);
+ }
+ self.wrote.insert(at, w);
+ None
+ }
+
+ /// The records of slots in `[from, end)` dropped (a heap gone: its memory may be another's next).
+ fn forget(&mut self, from: usize, end: usize) {
+ let gone: Vec = self.wrote.range(from..end).map(|(&a, _)| a).collect();
+ for a in gone {
+ self.wrote.remove(&a);
+ }
+ }
+}
+
+/// slot address → what XCL last wrote there
+static WROTE: Mutex = Mutex::new(Record::new(WROTE_MAX));
+/// slots recorded at most (some 10 MB)
+const WROTE_MAX: usize = 1 << 17;
+
+#[cfg(test)]
+thread_local! {
+ /// (tests) this thread's record instead of the process's (`record_for_test`)
+ static TEST_RECORD: std::cell::RefCell> = const { std::cell::RefCell::new(None) };
+}
+
+/// `f` on the record: the process's – (tests) this thread's while it has one
+fn with_record(f: impl FnOnce(&mut Record) -> R) -> R {
+ #[cfg(test)]
+ if TEST_RECORD.with(|t| t.borrow().is_some()) {
+ return TEST_RECORD.with(|t| f(t.borrow_mut().as_mut().expect("this thread's record")));
+ }
+ f(&mut WROTE.lock().unwrap_or_else(|e| e.into_inner()))
+}
+
+/// (tests) XCL's views this thread writes recorded in a record of `max` slots of its own (the
+/// process's record is shared by the suite's threads) until the guard goes.
+#[cfg(test)]
+pub(super) fn record_for_test(max: usize) -> impl Drop {
+ struct Restore;
+ impl Drop for Restore {
+ fn drop(&mut self) {
+ TEST_RECORD.with(|t| *t.borrow_mut() = None);
+ }
+ }
+ TEST_RECORD.with(|t| *t.borrow_mut() = Some(Record::new(max)));
+ Restore
+}
+
+/// FNV-1a of `words`.
+fn tag(words: &[u32]) -> u64 {
+ words.iter().flat_map(|w| w.to_le_bytes()).fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3))
+}
+
+fn note_wrote(at: usize, w: Wrote) {
+ // (the line after the record's lock)
+ if let Some(max) = with_record(|r| r.note(at, w)) {
+ let line = full_line(max);
+ crate::xlog_warn!("{line}");
+ #[cfg(test)]
+ FULL_LINES.with(|l| l.borrow_mut().push(line));
+ }
+}
+
+#[cfg(test)]
+thread_local! {
+ /// (tests) the "record … is full" lines this thread logged
+ static FULL_LINES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) };
+}
+
+/// (tests) the "record … is full" lines this thread logged since the last call
+#[cfg(test)]
+pub(super) fn take_full_lines_for_test() -> Vec {
+ FULL_LINES.with(|l| std::mem::take(&mut *l.borrow_mut()))
+}
+
+/// The line of a record that just filled (`Record::note`) – it holds `XCL_SKIP_CS`: run65_events.sh
+/// shows it.
+fn full_line(max: usize) -> String {
+ format!("D3D12.X: XCL_SKIP_CS: XCL's record of the views it writes is full ({max} slots): later slots' writers are unknown")
+}
+
+fn wrote_at(at: usize) -> Option {
+ with_record(|r| r.wrote.get(&at).copied())
}
/// Copy a console slot's descriptor to another slot of the same kind, the PC heap index
/// in it (T# word 0, S# word 3 [11:0]) renumbered for the destination. Buffer V# carry
-/// their address and stay as they are.
+/// their address and stay as they are. (XCL's write: of the source's view, as recorded – while the
+/// source still holds XCL's bytes; the title's bytes there make it a plain copy.)
pub fn copy_words(src: &Slot, dst: &Slot) {
let n = if src.sampler { 4 } else { 8 };
let mut w = [0u32; 8];
unsafe { std::ptr::copy_nonoverlapping(src.at as *const u32, w.as_mut_ptr(), n) };
+ let source = w;
if src.sampler {
w[3] = (w[3] & !0xFFF) | (dst.index & 0xFFF);
} else if w[3] >> 28 >= 8 {
w[0] = dst.index;
}
- write(dst, &w[..n]);
+ let from = if !src.sampler && super::skip_roots::recording() { wrote_at(src.at).filter(|f| tag(&source) == f.tag) } else { None };
+ write_named(dst, &w[..n], from.map_or("view copied by CopyDescriptors", |f| f.what), || from.and_then(|f| f.names));
if !src.sampler {
note_resource(dst, resource_at(src.at).unwrap_or(0));
}
}
+/// Who wrote what a view slot holds, as far as XCL can tell (`peek`).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Writer {
+ /// XCL: its view of `.0` (as `write_view` names it), naming the title memory `.1`
+ Xcl(&'static str, Option<(usize, u64)>),
+ /// the title, over a view of XCL's (`.0`): its own descriptor or a copy of a slot
+ Over(&'static str),
+ /// the title: XCL wrote nothing there
+ Title,
+ /// not known (why)
+ Unknown(&'static str),
+}
+
+/// What a console slot holds and who wrote it – a look only (`slot` would give a page of the
+/// slot its place in the shared heap).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Peek {
+ pub words: [u32; 8],
+ /// the heap object, the slot's number in it, its first byte
+ pub heap: usize,
+ pub k: u32,
+ pub at: usize,
+ pub sampler: bool,
+ /// the heap's slots are in the title's memory (its allocation hook), not XCL's
+ pub title_memory: bool,
+ pub visible: bool,
+ pub writer: Writer,
+}
+
+/// The console slot at `at` (any byte of it) of XCL's heaps (None: in none of them). Its words are
+/// read under the heaps' lock (a heap's memory goes only once it is out of `HEAPS`).
+pub fn peek(at: usize) -> Option {
+ let (words, heap, k, slot_at, sampler, title_memory, visible) = {
+ let heaps = HEAPS.lock().unwrap_or_else(|e| e.into_inner());
+ let h = heaps.iter().find(|h| at >= h.shadow && at - h.shadow < h.n as usize * h.slot_bytes() as usize)?;
+ let k = (at - h.shadow) / h.slot_bytes() as usize;
+ let slot_at = h.shadow + k * h.slot_bytes() as usize;
+ let mut w = [0u32; 8];
+ unsafe { std::ptr::copy_nonoverlapping(slot_at as *const u32, w.as_mut_ptr(), if h.sampler { 4 } else { 8 }) };
+ (w, h.obj, k as u32, slot_at, h.sampler, h.memory == Memory::Title, h.visible)
+ };
+ let writer = if sampler { Writer::Unknown("a sampler slot") } else { writer_of(slot_at, &words) };
+ Some(Peek { words, heap, k, at: slot_at, sampler, title_memory, visible, writer })
+}
+
+/// (a line names the slot: a texture's address is looked up now – `Names::now`)
+fn writer_of(at: usize, words: &[u32; 8]) -> Writer {
+ if !super::skip_roots::recorded() {
+ return Writer::Unknown("XCL's views are not recorded");
+ }
+ match with_record(|r| (r.wrote.get(&at).copied(), r.full)) {
+ (Some(w), _) if tag(words) == w.tag => Writer::Xcl(w.what, w.names.and_then(Names::now)),
+ (Some(w), _) => Writer::Over(w.what),
+ (None, true) => Writer::Unknown("XCL's record of its views is full"),
+ (None, false) => Writer::Title,
+ }
+}
+
/// `XCL_TRACE_FRAME`: what the slots of each shader-visible view heap hold – images whose
/// PC index is the slot's own (made or copied through the device) or another (copied by the
/// title itself, as memory), buffers, empty.
@@ -501,25 +842,6 @@ pub fn words_at(addr32: u32) -> Option<[u32; 8]> {
static LAST_TAGS: Mutex>> = Mutex::new(None);
-/// Find the CPU-only mirror of a global SRV. D3D12 cannot copy descriptors from
-/// the shader-visible global heap, even if its CPU handle is available.
-fn cpu_mirror_srv(heaps: &[Heap], index: u32) -> Option {
- for h in heaps.iter().filter(|h| h.pc_gpu == 0) {
- for (page, &first) in h.pages.iter().enumerate() {
- let page = page as u32;
- if first == UNMAPPED || index < first {
- continue;
- }
- let offset = index - first;
- if offset % 2 == 0 && offset < page_descriptors(h.n, page) {
- let slot = page * PAGE_SLOTS + offset / 2;
- return Some(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: h.pc_cpu as usize + 2 * slot as usize * h.inc as usize });
- }
- }
- }
- None
-}
-
/// Brings the host descriptor heap (`GLOBAL`) up to date with descriptors the title wrote into
/// heap memory itself (copies of whole slots or converting image slots to buffers/CBVs/zeroes),
/// before a submission runs (`real::q_execute_command_lists`).
@@ -535,20 +857,60 @@ fn cpu_mirror_srv(heaps: &[Heap], index: u32) -> Option, put: impl FnOnce(Mirror)) -> Mirror {
+ let m = if w.iter().all(|&x| x == 0) || w[3] >> 28 < 8 {
+ Mirror::Null
+ } else if w[0] != own && w[0] < cap {
+ Mirror::From(w[0])
+ } else {
+ Mirror::Nothing
+ };
+ put(m);
+ if let Some(n) = names {
+ match m {
+ Mirror::Null => n.shared_cleared(own),
+ Mirror::From(s) => n.shared_copied(own, s),
+ Mirror::Nothing => {}
+ }
+ }
+ m
+}
+
+/// `resync_title_writes` under the heaps' locks (HEAPS, GLOBAL, LAST_TAGS – as before).
+unsafe fn resync_slots(found: &mut super::outside::HeapVs) {
let heaps = HEAPS.lock().unwrap();
let g = GLOBAL.lock().unwrap();
let Some(g) = g.as_ref() else { return };
let mut tags_lock = LAST_TAGS.lock().unwrap();
let tags = tags_lock.get_or_insert_with(HashMap::new);
+ let names = super::view_census::names();
- let process = GetCurrentProcess();
- let mut snapshot = [[0u32; 8]; PAGE_SLOTS as usize];
for h in heaps.iter().filter(|h| h.visible && !h.sampler) {
if h.shadow == 0 {
continue;
@@ -559,55 +921,62 @@ pub unsafe fn resync_title_writes() {
}
let k_start = p as u32 * PAGE_SLOTS;
let k_end = (k_start + PAGE_SLOTS).min(h.n);
- let count = (k_end - k_start) as usize;
- if count == 0 {
- continue;
- }
- let address = h.shadow + k_start as usize * SLOT as usize;
- let bytes = count * SLOT as usize;
- let mut copied = 0;
- // The title owns some heap allocations and can decommit their backing memory.
- if ReadProcessMemory(process, address as *const c_void, snapshot.as_mut_ptr().cast(), bytes, &mut copied) == 0
- || copied != bytes
- {
- continue;
- }
-
- for (offset, w) in snapshot[..count].iter().enumerate() {
- let k = k_start + offset as u32;
+ for k in k_start..k_end {
+ let slot_va = h.shadow + (k * SLOT) as usize;
+ let w = std::slice::from_raw_parts(slot_va as *const u32, 8);
let tag = ((w[3] as u64) << 32) | (w[0] as u64);
- let own_idx = first + 2 * offset as u32;
+ let own_idx = first + 2 * (k - k_start);
if tags.get(&(h.obj, k)) == Some(&tag) {
continue;
}
+ // (a slot whose words changed since the last submit: counted when it is a buffer
+ // V# outside unified memory – `outside`)
+ found.look(w);
+ // (diagnostic `XCL_TRACE_PAGES`) a descriptor the title wrote naming a traced page
+ {
+ let buffer_base = (w[0] as usize) | (((w[1] & 0xFFFF) as usize) << 32);
+ let image_base = ((w[0] as usize) | (((w[1] & 0xFF) as usize) << 32)) << 8;
+ let (kind, base) = if w[3] >> 28 >= 8 { ("image", image_base) } else { ("buffer", buffer_base) };
+ if crate::hle::kernelx::traced_range(base, 16) {
+ static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+ if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 16 {
+ crate::xlog_info!("[trace] the title wrote a {kind} descriptor naming {base:#x} into slot {k} of heap {:#x}: {:08x?}", h.obj, w);
+ }
+ }
+ }
let dst_cpu = g.cpu + (own_idx as u64) * (g.inc as u64);
- if w.iter().all(|&x| x == 0) || (w[3] >> 28 < 8) {
- // Overwritten with buffer / CBV or cleared: install null raw buffer SRV
- // so mesh shader loads past bounds safely return 0 rather than fault at address 0.
- let null_desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
- Format: windows::Win32::Graphics::Dxgi::Common::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: 0,
- StructureByteStride: 0,
- Flags: D3D12_BUFFER_SRV_FLAG_RAW,
+ resync_slot(w, own_idx, g.cap, names, |m| match m {
+ Mirror::Null => {
+ // Overwritten with buffer / CBV or cleared: install null raw buffer SRV
+ // so mesh shader loads past bounds safely return 0 rather than fault at address 0.
+ let null_desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
+ Format: windows::Win32::Graphics::Dxgi::Common::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: 0,
+ StructureByteStride: 0,
+ Flags: D3D12_BUFFER_SRV_FLAG_RAW,
+ },
},
- },
- };
- g.dev.CreateShaderResourceView(None, Some(&null_desc), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst_cpu as usize });
- } else if w[0] != own_idx {
- let Some(src_cpu) = cpu_mirror_srv(&heaps, w[0]) else { continue };
- g.dev.CopyDescriptorsSimple(
- 1,
- D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst_cpu as usize },
- src_cpu,
- D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
- );
- }
+ };
+ g.dev.CreateShaderResourceView(None, Some(&null_desc), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst_cpu as usize });
+ }
+ Mirror::From(src_idx) => {
+ // Copied whole slot from another slot index in GLOBAL: mirror source descriptor
+ let src_cpu = g.cpu + (src_idx as u64) * (g.inc as u64);
+ g.dev.CopyDescriptorsSimple(
+ 1,
+ D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst_cpu as usize },
+ D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src_cpu as usize },
+ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
+ );
+ }
+ Mirror::Nothing => {}
+ });
tags.insert((h.obj, k), tag);
}
}
@@ -618,25 +987,21 @@ pub unsafe fn resync_title_writes() {
mod tests {
use super::*;
+ /// XCL's record of its views says once that it filled – its first slot without room –, not at
+ /// the later ones; a slot it holds is updated all the same (F-1). Its line holds XCL_SKIP_CS.
#[test]
- fn global_srv_resolves_only_to_a_live_cpu_mirror() {
- let heap = Heap {
- obj: 1,
- shadow: 0,
- n: PAGE_SLOTS + 4,
- pc_cpu: 0x1000,
- pc_gpu: 0,
- inc: 32,
- sampler: false,
- pages: vec![UNMAPPED, 64],
- visible: true,
- memory: Memory::Title,
- };
- let heaps = [heap];
- assert_eq!(cpu_mirror_srv(&heaps, 68).unwrap().ptr, 0x1000 + 2 * (PAGE_SLOTS as usize + 2) * 32);
- assert!(cpu_mirror_srv(&heaps, 69).is_none()); // UAV
- assert!(cpu_mirror_srv(&heaps, 72).is_none()); // past the last partial page
- assert!(cpu_mirror_srv(&heaps, 0).is_none()); // no assigned page
+ fn the_record_of_xcl_s_views_says_once_that_it_filled() {
+ let w = Wrote { what: "view", tag: 1, names: None };
+ let mut r = Record::new(1);
+ assert_eq!(r.note(0x100, w), None);
+ assert_eq!(r.note(0x120, w), Some(1), "full: said");
+ assert_eq!(r.note(0x140, w), None, "said once");
+ assert_eq!(r.note(0x100, Wrote { tag: 2, ..w }), None, "a slot it holds is updated");
+ assert_eq!(r.wrote.get(&0x100).map(|w| w.tag), Some(2));
+ assert!(r.full && !r.wrote.contains_key(&0x120));
+ r.forget(0x100, 0x120);
+ assert!(r.wrote.is_empty(), "a heap's slots forgotten when it goes");
+ assert_eq!(full_line(WROTE_MAX), "D3D12.X: XCL_SKIP_CS: XCL's record of the views it writes is full (131072 slots): later slots' writers are unknown");
}
#[test]
@@ -734,6 +1099,7 @@ mod tests {
fn large_heaps_get_shared_pages_as_used() {
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
use windows::Win32::Graphics::Dxgi::*;
+ let _one = SHARED_RANGES.lock().unwrap_or_else(|e| e.into_inner());
if crate::gpu::uma::get().is_none() {
return;
}
@@ -782,4 +1148,197 @@ mod tests {
unregister(0xB100);
unregister(0xB101);
}
+
+ /// A buffer V# outside unified memory found in a slot changed since the last submit is shown
+ /// to `outside::HeapVs` once per change – whichever submit's resync finds it (each holds the
+ /// heaps for its whole loop); an image T# and a buffer V# of unified memory are not.
+ #[test]
+ fn buffer_vsharps_new_outside_unified_memory_are_seen_once_per_change() {
+ use super::super::outside::{forget_heap_seen_for_test, heap_seen_for_test};
+ use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
+ use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS};
+ let _one = SHARED_RANGES.lock().unwrap_or_else(|e| e.into_inner());
+ let Some(u) = crate::gpu::uma::get() else { return };
+ let Some(inside) = (0..u.windows()).map(|k| u.window(k)).find(|w| w.1 > 0x20_0000).map(|w| (w.0 + 0x10_0000) as u64) else { return };
+ let dev = unsafe {
+ let mut dev: Option = None;
+ if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() {
+ return crate::gpu::recomp::runner::skip_test("no GPU");
+ }
+ dev.expect("D3D12 device")
+ };
+ if !unsafe { shared_heap(&dev) } {
+ return crate::gpu::recomp::runner::skip_config("no shared shader-visible heap");
+ }
+ // (8 slots: the place it gives back, 16 descriptors, is two small heaps' side by side)
+ let obj = 0x7D0D_6000usize;
+ assert!(register(obj, 8, 0x30_0000, 0, 32, false, true, true));
+ let v = start(obj).unwrap();
+ let s: Vec = (0..3u64).map(|k| slot(v + k * SLOT as u64).unwrap()).collect();
+ if s.iter().any(|x| x.shared_srv == 0) {
+ unregister(obj);
+ return crate::gpu::recomp::runner::skip_config("the heap's slots have no place in the shared heap");
+ }
+ let out = unsafe { VirtualAlloc(std::ptr::null(), 0x10_0000, MEM_RESERVE, PAGE_NOACCESS) } as u64;
+ assert_ne!(out, 0, "a reservation outside the windows");
+ let (base, base2) = (out + 0x100, out + 0x8000);
+ let vsharp = |b: u64| {
+ let w = crate::gpu::desc::buffer_words(b, 0, 64, 22);
+ [w[0], w[1], w[2], w[3], 0, 0, 0, 0]
+ };
+ write(&s[0], &vsharp(base));
+ // (an image T#: its words, read as a buffer V#'s, would name base2)
+ write(&s[1], &[base2 as u32, (base2 >> 32) as u32, 0, 9 << 28, 0, 0, 0, 0]);
+ write(&s[2], &vsharp(inside));
+ unsafe {
+ resync_title_writes();
+ resync_title_writes();
+ }
+ let seen = (heap_seen_for_test(base), heap_seen_for_test(base2), heap_seen_for_test(inside));
+ write(&s[0], &vsharp(base + 0x40));
+ unsafe { resync_title_writes() };
+ let again = heap_seen_for_test(base + 0x40);
+ unregister(obj);
+ // (before the reservation goes: a later test's may get its address)
+ for b in [base, base + 0x40] {
+ forget_heap_seen_for_test(b);
+ }
+ unsafe { VirtualFree(out as *mut std::ffi::c_void, 0, MEM_RELEASE) };
+ assert_eq!(seen, (1, 0, 0), "the buffer V# outside unified memory once in two submits; not the image, not one of unified memory");
+ assert_eq!(again, 1, "the slot written again: seen again");
+ }
+
+ /// The resync's step for a changed slot (`resync_slot`, the view census's binding amendment A5:
+ /// tested on a map of its own, not through the process's resync, which any test's submit runs):
+ /// a buffer V#, a CBV or zeros get a null SRV at the slot's place – the map's shared descriptor
+ /// there names nothing, the title heap's keeps its texture –; an image T# copied from another
+ /// slot gets that slot's shared descriptor, and the map with it; the slot's own T#, or one whose
+ /// index is past the shared heap, gets nothing. The map follows the heap, never before it.
+ #[test]
+ fn the_resync_s_step_updates_the_view_map_after_the_shared_heap() {
+ let m = super::super::view_census::window(0, 64);
+ let (a, b) = (0x7A1E_2B01usize, 0x7A1E_2B02usize);
+ for (i, r) in [(4, a), (8, b)] {
+ m.title_view(i, false, r);
+ m.published(i);
+ }
+ let buffer = [0x1000, 0, 64, 0x3101_6FAC, 0, 0, 0, 0];
+ let mut seen = None;
+ assert_eq!(resync_slot(&buffer, 4, 64, Some(m), |x| seen = Some((x, m.at(4)))), Mirror::Null);
+ assert_eq!(seen, Some((Mirror::Null, (a, a))), "the heap first, then the map");
+ assert_eq!(m.at(4), (a, 0), "the title heap's descriptor still names it");
+ let cbv = crate::gpu::desc::cbv_words(0x1000, 256);
+ assert_eq!(resync_slot(&[cbv[0], cbv[1], cbv[2], cbv[3], 0, 0, 0, 0], 8, 64, None, |_| {}), Mirror::Null, "a CBV");
+ assert_eq!(resync_slot(&[0; 8], 8, 64, None, |_| {}), Mirror::Null, "zeros");
+ // slot 8's T# copied (as memory) into the slot at place 10
+ let t8 = [8, 0x0470_0000, 0, 9 << 28, 0, 0, 0, 0];
+ assert_eq!(resync_slot(&t8, 10, 64, Some(m), |_| {}), Mirror::From(8));
+ assert_eq!(m.at(10), (0, b));
+ let own = [12, 0x0470_0000, 0, 9 << 28, 0, 0, 0, 0];
+ assert_eq!(resync_slot(&own, 12, 64, Some(m), |_| {}), Mirror::Nothing, "its own T#");
+ let past = [64, 0x0470_0000, 0, 9 << 28, 0, 0, 0, 0];
+ assert_eq!(resync_slot(&past, 12, 64, Some(m), |_| {}), Mirror::Nothing, "an index past the shared heap");
+ assert_eq!((m.at(8), m.at(12)), ((b, b), (0, 0)));
+ }
+
+ /// The view census's map follows the shared heap's places: a view made in a slot names its
+ /// texture in the title heap's descriptor, its publication in the shared heap's (a UAV at the
+ /// place after its slot's SRV); a CPU-only slot the title wrote over as memory is told (its
+ /// shared descriptors still name what XCL put there); the heap's release takes its title heap's
+ /// descriptors and leaves the shared ones; a view into a heap with no place in the shared heap
+ /// is counted, not mapped. (The heap is CPU-only, as the title's are with a shared heap: no
+ /// resync walks it; the map is this thread's – `names_for_test`.)
+ #[test]
+ fn publish_and_unregister_keep_the_view_map_in_step() {
+ use super::super::view_census::names_for_test;
+ use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
+ let _one = SHARED_RANGES.lock().unwrap_or_else(|e| e.into_inner());
+ if crate::gpu::uma::get().is_none() {
+ return;
+ }
+ let dev = unsafe {
+ let mut dev: Option = None;
+ if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() {
+ return crate::gpu::recomp::runner::skip_test("no GPU");
+ }
+ dev.expect("D3D12 device")
+ };
+ if !unsafe { shared_heap(&dev) } {
+ return crate::gpu::recomp::runner::skip_config("no shared shader-visible heap");
+ }
+ let dev = shared_device_for_test().expect("the shared heap's device");
+ // the title's PC heap: CPU-only, 2 descriptors a slot, null SRVs in all (what `publish` copies)
+ let pc: ID3D12DescriptorHeap = unsafe { dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 16, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0 }) }.expect("a CPU-only heap");
+ let cpu = unsafe { pc.GetCPUDescriptorHandleForHeapStart() }.ptr as u64;
+ let inc = unsafe { dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) };
+ let null = D3D12_SHADER_RESOURCE_VIEW_DESC {
+ Format: windows::Win32::Graphics::Dxgi::Common::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: 0, StructureByteStride: 0, Flags: D3D12_BUFFER_SRV_FLAG_RAW } },
+ };
+ for k in 0..16u64 {
+ unsafe { dev.CreateShaderResourceView(None, Some(&null), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + k * inc as u64) as usize }) };
+ }
+ let obj = 0x7A1E_2001usize;
+ assert!(register(obj, 8, cpu, 0, inc, false, true, false));
+ let v = start(obj).unwrap();
+ let s: Vec = (0..4u64).map(|k| slot(v + k * SLOT as u64).unwrap()).collect();
+ if s.iter().any(|x| x.shared_srv == 0) {
+ unregister(obj);
+ return crate::gpu::recomp::runner::skip_config("the heap's slots have no place in the shared heap");
+ }
+ let first = s[0].index;
+ assert!(s.iter().enumerate().all(|(k, x)| x.index == first + 2 * k as u32), "a page's places side by side");
+ let (m, window) = names_for_test(first, 16);
+ let (a, b) = (0x7A1E_2A11usize, 0x7A1E_2A12usize);
+ note_pc_view(&s[0], false, a);
+ assert_eq!(m.at(first), (a, 0), "the title heap's descriptor first");
+ unsafe { publish(&s[0], false) };
+ assert_eq!(m.at(first), (a, a), "then the shared heap's");
+ note_pc_view(&s[1], true, b);
+ unsafe { publish(&s[1], true) };
+ assert_eq!((m.at(s[1].index), m.at(s[1].index + 1)), ((0, 0), (b, b)), "a UAV at the place after its slot's SRV");
+ // the title writes a CBV over slot 0 (as memory); slot 1 holds its own image T#
+ let cbv = crate::gpu::desc::cbv_words(0x1000, 256);
+ unsafe {
+ std::ptr::copy_nonoverlapping([cbv[0], cbv[1], cbv[2], cbv[3], 0, 0, 0, 0].as_ptr(), s[0].at as *mut u32, 8);
+ std::ptr::copy_nonoverlapping([s[1].index, 0x0470_0000, 0, 9 << 28, 0, 0, 0, 0].as_ptr(), s[1].at as *mut u32, 8);
+ }
+ let mut stale = Vec::new();
+ cpu_only_stale(|i| {
+ if (first..first + 16).contains(&i) {
+ stale.push(i);
+ }
+ });
+ assert!(stale.contains(&first) && stale.contains(&(first + 1)), "slot 0's places: written over ({stale:?})");
+ assert!(!stale.contains(&s[1].index) && !stale.contains(&(s[1].index + 1)), "slot 1 holds its own T#");
+ assert_eq!(stale.len(), 14, "every other slot of the heap's page (never written)");
+ unregister(obj);
+ assert!((first..first + 16).all(|i| m.at(i).0 == 0), "the title heap's descriptors went with it");
+ assert_eq!((m.at(first).1, m.at(s[1].index + 1).1), (a, b), "the shared heap's stay, in a released range now");
+ drop(window);
+ // a heap without places in the shared heap: its views are counted
+ let other = 0x7A1E_2002usize;
+ assert!(register(other, 2, 0x10_0000, 0, 32, false, false, true));
+ let (m2, _w2) = names_for_test(0, 16);
+ let x = slot(start(other).unwrap()).unwrap();
+ note_pc_view(&x, false, a);
+ note_copied_view(&x, Some(&s[0]));
+ // a sampler slot's views and copies name no view: neither mapped nor counted
+ let sampler = Slot { at: 0, index: 3, pc_srv: 0, pc_uav: 0, pc_gpu_uav: 0, sampler: true, shared_srv: 0, k: 3 };
+ note_pc_view(&sampler, false, a);
+ note_copied_view(&sampler, Some(&sampler));
+ unregister(other);
+ assert_eq!(m2.counts(), (2, 0), "a view and a copy into it: untracked");
+ assert!((0..16).all(|i| m2.at(i) == (0, 0)));
+ // the census reads the released ranges sorted by first, whatever order they went back in
+ let (y, z) = (0x7A1E_2003usize, 0x7A1E_2004usize);
+ assert!(register(y, 2, cpu, 0, inc, false, true, false) && register(z, 2, cpu, 0, inc, false, true, false));
+ let _ = (slot(start(y).unwrap()), slot(start(z).unwrap()));
+ unregister(z);
+ unregister(y);
+ let (_, _, free) = global_extent().expect("the shared heap");
+ assert!(free.windows(2).all(|w| w[0].0 < w[1].0), "released ranges sorted ({free:?})");
+ }
}
diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs
index e1bdeb9..40e758d 100644
--- a/crates/xcl/src/hle/d3d12x/console_list.rs
+++ b/crates/xcl/src/hle/d3d12x/console_list.rs
@@ -847,7 +847,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result {
io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0);
io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32;
let io_at = uma_copy(st, bytemuck_u32(&io)).ok_or("UMA: io")?;
- let res_at = uma_copy(st, &[0u8; 256]).ok_or("UMA: res")?;
+ let res_at = uma_copy(st, &super::bind::res_block(false)).ok_or("UMA: res")?;
// the pipeline's own root signature when it has static samplers
let own = super::real::pso_root_signature(real).or(((*p).rs != 0).then_some((*p).rs)).map(|r| r as *mut c_void);
match own.as_ref().and_then(|r| ID3D12RootSignature::from_raw_borrowed(r)) {
diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs
index 97d6600..2d9dc8e 100644
--- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs
+++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs
@@ -9,11 +9,10 @@
//! queue signals it, and a worker thread does the writes, in submission order, when the GPU is
//! there – what bottom of pipe means.
-use std::collections::{HashMap, HashSet};
+use std::collections::HashMap;
use std::ffi::c_void;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
-use std::sync::{Mutex, OnceLock};
-use std::time::{Duration, Instant};
+use std::sync::{mpsc, Mutex, OnceLock};
use windows::core::Interface;
use windows::Win32::Foundation::HANDLE;
@@ -34,6 +33,29 @@ pub(super) enum Write {
/// the GPU would see them (`title_textures::read_memory`: a GPU view's pages where the CPU
/// has them), to `dst` in the title's own memory
Copy { dst: usize, src: usize, len: usize },
+ /// Local fix: `len` bytes the GPU copied into a persistently mapped READBACK buffer (`src`:
+ /// its mapped address), written to `dst` in the title's own memory once the queue is past
+ /// the copy – CopyMemoryToMemoryX whose source is a PC resource standing for title memory.
+ /// `_src` (that resource) stays until the copy ran: its last Release is then held against
+ /// a mark taken after the list was submitted (`late_release`).
+ ReadbackCopy { dst: usize, src: usize, len: usize, _buf: ID3D12Resource, _src: ID3D12Resource },
+ /// Local fix: a title texture's subresources the GPU copied into a mapped READBACK buffer
+ /// (`mapped`, one D3D12 footprint each, mip-major within an array slice), laid out again as
+ /// the console has the texture in memory (`tex`), of which `len` bytes from `skip` go to `dst`.
+ TextureReadback {
+ dst: usize,
+ len: usize,
+ skip: usize,
+ mapped: usize,
+ footprints: Vec,
+ mips: u32,
+ array: u32,
+ side: u32,
+ tex: std::sync::Arc,
+ _buf: ID3D12Resource,
+ /// the texture copied out of (kept as `ReadbackCopy` keeps its source)
+ _src: ID3D12Resource,
+ },
}
/// copies done so far, and those whose source had no memory for some of its bytes (zeros)
@@ -44,13 +66,54 @@ pub fn copies() -> (u64, u64) {
(COPIES[0].load(Ordering::Relaxed), COPIES[1].load(Ordering::Relaxed))
}
+/// local diagnostic: where the worker is (0 waiting for a job, 1 waiting for the fence,
+/// 2 immediate/readback writes, 3 copy: writable(), 4 copy: read_memory(), 5 copy: memcpy),
+/// since when (ms of the log clock), and job counters – read by `probe_line`.
+static PHASE: AtomicU32 = AtomicU32::new(0);
+static PHASE_SINCE_MS: AtomicU64 = AtomicU64::new(0);
+static JOBS_IN: AtomicU64 = AtomicU64::new(0);
+static JOBS_DONE: AtomicU64 = AtomicU64::new(0);
+static LAST_WANTED: AtomicU64 = AtomicU64::new(0);
+static LAST_SEEN: AtomicU64 = AtomicU64::new(0);
+static LAST_COPY: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
+
+fn phase(p: u32) {
+ PHASE.store(p, Ordering::Relaxed);
+ PHASE_SINCE_MS.store((crate::log::uptime() * 1000.0) as u64, Ordering::Relaxed);
+}
+
+/// One line for the local probe: the worker's phase and how long it has been in it.
+pub(super) fn probe_line() -> String {
+ let now = (crate::log::uptime() * 1000.0) as u64;
+ let since = PHASE_SINCE_MS.load(Ordering::Relaxed);
+ let names = ["idle", "fence-wait", "writes", "copy:writable", "copy:read_memory", "copy:memcpy"];
+ let p = PHASE.load(Ordering::Relaxed) as usize;
+ format!(
+ "cpu_writes: {} for {:.1}s | jobs in {} done {} | fence wanted {} seen {} | copies {} | last copy {:#x}<-{:#x} ({:#x} B)",
+ names.get(p).copied().unwrap_or("?"),
+ now.saturating_sub(since) as f64 / 1000.0,
+ JOBS_IN.load(Ordering::Relaxed),
+ JOBS_DONE.load(Ordering::Relaxed),
+ LAST_WANTED.load(Ordering::Relaxed),
+ LAST_SEEN.load(Ordering::Relaxed),
+ COPIES[0].load(Ordering::Relaxed),
+ LAST_COPY[0].load(Ordering::Relaxed),
+ LAST_COPY[1].load(Ordering::Relaxed),
+ LAST_COPY[2].load(Ordering::Relaxed),
+ )
+}
+
struct Job {
+ /// the queue the submission went to (its worker's key)
queue: usize,
fence: ID3D12Fence,
value: u64,
writes: Vec,
- submitted: Instant,
- warned: bool,
+ /// signalled to `value` by the worker once the writes are done (jobs with a CPU copy, see
+ /// `copy_ordered`)
+ done: Option,
+ /// the submission's lists and their last work, for a wait past `WAIT_MS` (`XCL_TRACE_GPU_STALL=1`;
+ /// empty without it)
lists: Vec,
}
@@ -61,87 +124,147 @@ unsafe impl Send for Job {}
struct QueueFence {
fence: ID3D12Fence,
value: u64,
+ /// what the queue waits on after a submission with a CPU copy (made on first use)
+ done: Option,
+}
+
+/// Local fix (`XCL_CPU_COPY_ORDERED`, on unless "0"): a submission whose lists carry a
+/// CopyMemoryToMemoryX done by the CPU makes its queue wait – on the GPU timeline, right after
+/// XCL's own signal – until the worker has done the copy. Without it the title saw its own
+/// fence complete (the queue's later Signal) before the worker had written the destination, read
+/// it too early and waited for ever: GTA VI 1.0.2.1 stopped submitting at its first loading
+/// screen, right after "copied by the CPU once the GPU is there".
+fn copy_ordered() -> bool {
+ static ON: OnceLock = OnceLock::new();
+ *ON.get_or_init(|| std::env::var("XCL_CPU_COPY_ORDERED").map_or(true, |v| v.trim() != "0"))
}
unsafe impl Send for QueueFence {}
static FENCES: Mutex>> = Mutex::new(None);
-const STALL_AFTER: Duration = Duration::from_secs(10);
-static INCOMING: Mutex> = Mutex::new(Vec::new());
+/// how long the worker waits for one submission before it says so in the log (it goes on
+/// waiting: writing early made the title see its work done and free what the GPU still used)
+const WAIT_MS: u32 = 10_000;
-fn worker_event() -> usize {
- static EVENT: OnceLock = OnceLock::new();
- *EVENT.get_or_init(|| unsafe {
- let event = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) as usize;
- if event == 0 {
- crate::xlog_error!("D3D12.X: could not create the bottom-of-pipe completion event");
- return 0;
+/// Wait until `fence` reaches `value`. Every wake is checked against the fence: the event is
+/// one per worker, and a completion asked for before (a wait that timed out) can set it late,
+/// which let a later job write before its own submission had run. A removed device (the fence
+/// reads all ones) or an event that cannot be armed ends the wait. Past the first `WAIT_MS`, with
+/// `XCL_TRACE_GPU_STALL=1`, the queue's waits and the submission's lists are logged once (upstream
+/// 9db0989).
+unsafe fn wait_for_fence(fence: &ID3D12Fence, value: u64, event: windows_sys::Win32::Foundation::HANDLE, writes: usize, queue: usize, lists: &[String]) {
+ let mut waited_ms = 0u64;
+ loop {
+ let now = fence.GetCompletedValue();
+ if now >= value {
+ return;
}
- let spawned = std::thread::Builder::new().name("xcl-cpu-writes".into()).spawn(move || complete_jobs(event));
- if let Err(e) = spawned {
- crate::xlog_error!("D3D12.X: no thread for the writes after the GPU: {e}");
- windows_sys::Win32::Foundation::CloseHandle(event as _);
- return 0;
+ if fence.SetEventOnCompletion(value, HANDLE(event as *mut c_void)).is_err() {
+ crate::xlog_warn!("D3D12.X: writes after the GPU: SetEventOnCompletion failed (fence at {now}, wanted {value}) – done now");
+ return;
}
- event
- })
-}
-
-unsafe fn complete_jobs(event: usize) {
- let mut pending: Vec = Vec::new();
- let mut completed = HashMap::new();
- let mut stalled = HashSet::new();
- loop {
- for job in std::mem::take(&mut *INCOMING.lock().unwrap()) {
- if job.fence.GetCompletedValue() < job.value {
- let _ = job.fence.SetEventOnCompletion(job.value, HANDLE(event as _));
+ if th::WaitForSingleObject(event, WAIT_MS) == windows_sys::Win32::Foundation::WAIT_TIMEOUT && fence.GetCompletedValue() < value {
+ waited_ms += WAIT_MS as u64;
+ static LATE: AtomicU64 = AtomicU64::new(0);
+ let k = LATE.fetch_add(1, Ordering::Relaxed) + 1;
+ if k.is_power_of_two() {
+ crate::xlog_warn!(
+ "D3D12.X: writes after the GPU: a queue has not got to its submission after {} s (fence at {}, wanted {value}; {writes} writes) – still waiting ({k} such waits so far)",
+ waited_ms / 1000,
+ fence.GetCompletedValue()
+ );
}
- pending.push(job);
- }
- completed.clear();
- stalled.clear();
- pending.retain_mut(|job| {
- // One sample per queue keeps its writes in order if the fence advances mid-scan.
- let done = *completed.entry(job.queue).or_insert_with(|| job.fence.GetCompletedValue());
- if done == u64::MAX {
- return false; // device removed: its readbacks are invalid
+ if waited_ms == WAIT_MS as u64 && super::list_x::trace_gpu_stall() {
+ super::list_x::log_gpu_stall(queue);
+ for list in lists {
+ crate::xlog_warn!("D3D12.X: submission for fence {value}: {list}");
+ }
}
- if done < job.value {
- if stalled.insert(job.queue) && !job.warned && job.submitted.elapsed() >= STALL_AFTER {
- job.warned = true;
- crate::xlog_warn!("D3D12.X: bottom-of-pipe writes still pending (fence at {done}, wanted {}; {} writes)", job.value, job.writes.len());
- if super::list_x::trace_gpu_stall() {
- super::list_x::log_gpu_stall(job.queue);
- for list in &job.lists {
- crate::xlog_warn!("D3D12.X: submission for fence {}: {list}", job.value);
+ }
+ }
+}
+
+/// The worker of `queue`'s jobs: one per queue, so a queue that waits (on the GPU) for another
+/// queue's copy is never held back by a job of its own queue's – one worker for every queue
+/// made such a wait last until the 10 s timeout wrote early.
+fn worker(queue: usize) -> Option> {
+ static W: Mutex>>> = Mutex::new(None);
+ let mut g = W.lock().unwrap_or_else(|e| e.into_inner());
+ let m = g.get_or_insert_with(HashMap::new);
+ if let Some(tx) = m.get(&queue) {
+ return Some(tx.clone());
+ }
+ let (tx, rx) = mpsc::channel::();
+ let spawned = std::thread::Builder::new().name(format!("xcl-cpu-writes-{queue:x}")).spawn(move || unsafe {
+ let event = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null());
+ for job in rx {
+ phase(1);
+ LAST_WANTED.store(job.value, Ordering::Relaxed);
+ wait_for_fence(&job.fence, job.value, event, job.writes.len(), job.queue, &job.lists);
+ let seen = job.fence.GetCompletedValue();
+ LAST_SEEN.store(seen, Ordering::Relaxed);
+ phase(2);
+ // a removed device (the fence reads all ones): its readbacks are invalid – the writes
+ // are not done (upstream 9db0989) – and the title is stopped here with the report,
+ // as at its next submit or present (`real::stop_if_device_removed`): a title waiting
+ // on a marker of this job would not get there. (A device that still answers: the
+ // writes are left out, as upstream does.)
+ let writes: &[Write] = if seen == u64::MAX {
+ super::real::stop_if_device_removed();
+ static REMOVED: std::sync::Once = std::sync::Once::new();
+ REMOVED.call_once(|| crate::xlog_warn!("D3D12.X: writes after the GPU: the device was removed – the writes of its submissions are not done ({} in the first)", job.writes.len()));
+ &[]
+ } else {
+ &job.writes
+ };
+ for w in writes {
+ match w {
+ Write::Immediate(va, words) => write_now(*va, words),
+ Write::ReadbackU64 { va, src, .. } => {
+ let value = (*(*src as *const AtomicU64)).load(Ordering::Acquire);
+ write_u64_now(*va, value);
+ }
+ Write::Copy { dst, src, len } => copy_now(*dst, *src, *len),
+ Write::TextureReadback { dst, len, skip, mapped, footprints, mips, array, side, tex, .. } => {
+ texture_readback(*dst, *len, *skip, *mapped, footprints, *mips, *array, *side, tex);
+ }
+ Write::ReadbackCopy { dst, src, len, .. } => {
+ if writable(*dst, *len) {
+ std::ptr::copy_nonoverlapping(*src as *const u8, *dst as *mut u8, *len);
+ let n = COPIES[0].fetch_add(1, Ordering::Relaxed);
+ if n < 4 {
+ let data = std::slice::from_raw_parts(*src as *const u8, *len);
+ let nonzero = data.iter().filter(|&&b| b != 0).count();
+ let head: String = data.iter().take(32).map(|b| format!("{b:02x}")).collect();
+ crate::xlog_info!("D3D12.X: GPU copy read back into {:#x} ({:#x} B, {nonzero} non-zero bytes): {head}", *dst, *len);
+ }
+ }
}
}
}
- return true;
- }
- for w in &job.writes {
- match w {
- Write::Immediate(va, words) => write_now(*va, words),
- Write::ReadbackU64 { va, src, .. } => {
- let value = (*(*src as *const AtomicU64)).load(Ordering::Acquire);
- write_u64_now(*va, value);
- }
- Write::Copy { dst, src, len } => copy_now(*dst, *src, *len),
+ if let Some(done) = &job.done {
+ let _ = done.Signal(job.value);
}
+ JOBS_DONE.fetch_add(1, Ordering::Relaxed);
+ phase(0);
}
- false
});
- // Both new jobs and GPU completion wake the worker. Poll if a host drops a fence event.
- th::WaitForSingleObject(event as _, if pending.is_empty() { th::INFINITE } else { 100 });
+ if let Err(e) = spawned {
+ crate::xlog_error!("D3D12.X: no thread for the writes after the GPU: {e}");
+ return None;
}
+ m.insert(queue, tx.clone());
+ Some(tx)
}
-fn enqueue(job: Job) {
- let event = worker_event();
- INCOMING.lock().unwrap().push(job);
- if event != 0 {
- unsafe { th::SetEvent(event as _) };
+/// local diagnostic: bottom-of-pipe writes dropped because their memory was not committed and
+/// writable (the title then never sees its marker), logged for the first few
+static DROPPED: AtomicU64 = AtomicU64::new(0);
+fn note_dropped(kind: &str, va: usize, state: u32, protect: u32) {
+ let k = DROPPED.fetch_add(1, Ordering::Relaxed);
+ if k < 16 || k.is_power_of_two() {
+ crate::xlog_warn!("D3D12.X: [diag] bottom-of-pipe {kind} to {va:#x} dropped (#{k}): state {state:#x} protect {protect:#x}");
}
}
@@ -150,9 +273,11 @@ unsafe fn write_now(va: usize, words: &[u32]) {
use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE};
let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
if VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT {
+ note_dropped("dwords", va, m.State, m.Protect);
return;
}
if m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 || (m.BaseAddress as usize + m.RegionSize) < va + 4 * words.len() {
+ note_dropped("dwords", va, m.State, m.Protect);
return;
}
for (i, &w) in words.iter().enumerate() {
@@ -166,21 +291,87 @@ unsafe fn write_u64_now(va: usize, value: u64) {
let Some(end) = va.checked_add(8) else { return };
let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
if VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT {
+ note_dropped("u64", va, m.State, m.Protect);
return;
}
if m.Protect & PAGE_GUARD != 0 || m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 || (m.BaseAddress as usize).saturating_add(m.RegionSize) < end {
+ note_dropped("u64", va, m.State, m.Protect);
return;
}
(*(va as *const AtomicU64)).store(value, Ordering::Release);
}
+/// The texture the GPU copied out (`TextureReadback`) in the console's layout, then `len` bytes of
+/// it from `skip` to `dst`.
+#[allow(clippy::too_many_arguments)]
+unsafe fn texture_readback(dst: usize, len: usize, skip: usize, mapped: usize, footprints: &[D3D12_PLACED_SUBRESOURCE_FOOTPRINT], mips: u32, array: u32, side: u32, tex: &crate::hle::xg::Texture) {
+ if !writable(dst, len) {
+ return;
+ }
+ let size = tex.size() as usize;
+ let Some(end) = skip.checked_add(len) else { return };
+ if end > size {
+ return;
+ }
+ let mut img = vec![0u8; size];
+ let side = side.max(1) as usize;
+ for slice in 0..array as usize {
+ for mip in 0..mips as usize {
+ let Some(fp) = footprints.get(mip + slice * mips as usize) else { continue };
+ let w = (fp.Footprint.Width as usize).div_ceil(side);
+ let h = (fp.Footprint.Height as usize).div_ceil(side);
+ if w == 0 || h == 0 {
+ continue;
+ }
+ let pitch = fp.Footprint.RowPitch as usize;
+ // bytes per element: what a footprint row holds per element (rows are padded to 256)
+ let e = pitch / w;
+ let e = [16usize, 8, 4, 2, 1].into_iter().find(|&b| b <= e && w * b <= pitch).unwrap_or(1);
+ let base = mapped + fp.Offset as usize;
+ for y in 0..h {
+ let row = (base + y * pitch) as *const u8;
+ for x in 0..w {
+ let o = tex.element_offset(mip, x, y, slice) as usize;
+ if o + e <= size {
+ std::ptr::copy_nonoverlapping(row.add(x * e), img.as_mut_ptr().add(o), e);
+ }
+ }
+ }
+ }
+ }
+ std::ptr::copy_nonoverlapping(img.as_ptr().add(skip), dst as *mut u8, len);
+ let n = COPIES[0].fetch_add(1, Ordering::Relaxed);
+ if n < 4 {
+ let nonzero = img[skip..end].iter().filter(|&&b| b != 0).count();
+ let head: String = img[skip..end].iter().take(32).map(|b| format!("{b:02x}")).collect();
+ crate::xlog_info!("D3D12.X: texture read back into {dst:#x} ({len:#x} B from +{skip:#x} of {size:#x}; {nonzero} non-zero bytes): {head}");
+ }
+}
+
/// `len` bytes from `src` as the GPU would see them to `dst`, if `dst` is still writable.
unsafe fn copy_now(dst: usize, src: usize, len: usize) {
+ LAST_COPY[0].store(dst as u64, Ordering::Relaxed);
+ LAST_COPY[1].store(src as u64, Ordering::Relaxed);
+ LAST_COPY[2].store(len as u64, Ordering::Relaxed);
+ phase(3);
if !writable(dst, len) {
+ phase(2);
return;
}
+ phase(4);
let (data, all) = super::title_textures::read_memory(src, len);
+ phase(5);
+ {
+ static SHOWN: AtomicU64 = AtomicU64::new(0);
+ if SHOWN.fetch_add(1, Ordering::Relaxed) < 8 {
+ let nonzero = data.iter().filter(|&&b| b != 0).count();
+ let head: String = data.iter().take(64).map(|b| format!("{b:02x}")).collect();
+ let before: String = std::slice::from_raw_parts(dst as *const u8, len.min(32)).iter().map(|b| format!("{b:02x}")).collect();
+ crate::xlog_info!("D3D12.X: [diag] CPU copy {src:#x} → {dst:#x} ({len:#x} B): all source present {all}, {nonzero} non-zero bytes; dst before {before}; data {head}");
+ }
+ }
std::ptr::copy_nonoverlapping(data.as_ptr(), dst as *mut u8, len);
+ phase(2);
let n = COPIES[0].fetch_add(1, Ordering::Relaxed);
if !all && COPIES[1].fetch_add(1, Ordering::Relaxed) < 4 {
crate::xlog_warn!("D3D12.X: CopyMemoryToMemoryX {src:#x} → {dst:#x} ({len:#x} bytes), copy #{n} by the CPU: part of the source has no memory (zeros there)");
@@ -199,13 +390,19 @@ pub(super) fn writable(va: usize, bytes: usize) -> bool {
&& m.BaseAddress as usize + m.RegionSize >= va + bytes
}
-/// `writes` of lists just submitted to `queue`: done when the GPU has finished them.
+/// `writes` of lists just submitted to `queue`: done when the GPU has finished them. `lists`: the
+/// submission's lists for a wait that lasts (`XCL_TRACE_GPU_STALL=1`; empty without it).
pub(super) unsafe fn after(queue: *mut c_void, writes: Vec, lists: Vec) {
if writes.is_empty() || queue.is_null() {
return;
}
let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return };
- {
+ let ordered = copy_ordered() && writes.iter().any(|w| matches!(w, Write::Copy { .. } | Write::ReadbackCopy { .. } | Write::TextureReadback { .. }));
+ // (the job goes to its worker under FENCES, right after its value: two threads submitting to
+ // one queue at once sent their jobs the other way round, and the worker waited for the later
+ // value while the queue waited, on the GPU, for the earlier job's copy)
+ let Some(tx) = worker(queue as usize) else { return };
+ let (writes_n, sent) = {
let mut g = FENCES.lock().unwrap();
let m = g.get_or_insert_with(HashMap::new);
let entry = match m.entry(queue as usize) {
@@ -217,17 +414,40 @@ pub(super) unsafe fn after(queue: *mut c_void, writes: Vec, lists: Vec(0, D3D12_FENCE_FLAG_NONE) else { return };
- v.insert(QueueFence { fence, value: 0 })
+ v.insert(QueueFence { fence, value: 0, done: None })
}
};
+ if ordered && entry.done.is_none() {
+ let mut dev: Option = None;
+ if q.GetDevice(&mut dev).is_ok() {
+ if let Some(dev) = dev {
+ entry.done = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok();
+ }
+ }
+ }
entry.value += 1;
if q.Signal(&entry.fence, entry.value).is_err() {
return;
}
- static FIRST: std::sync::Once = std::sync::Once::new();
- FIRST.call_once(|| crate::xlog_info!("D3D12.X: bottom-of-pipe writes outside unified memory are done by the CPU after the GPU ({} in the first submission)", writes.len()));
- // Signal and enqueue under the same lock so concurrent submits cannot reorder the writes.
- enqueue(Job { queue: queue as usize, fence: entry.fence.clone(), value: entry.value, writes, submitted: Instant::now(), warned: false, lists });
+ let done = if ordered { entry.done.clone() } else { None };
+ if let Some(d) = &done {
+ // the queue goes on (and the title's own later signals complete) only once the
+ // worker has done this submission's copy
+ crate::waitwatch::note_gpu_wait("cpu copy landed", queue as usize, d, entry.value);
+ if q.Wait(d, entry.value).is_err() {
+ crate::xlog_warn!("D3D12.X: CPU copy: the queue cannot wait for it (Wait failed) – it may be seen late");
+ } else {
+ static FIRST_ORDERED: std::sync::Once = std::sync::Once::new();
+ FIRST_ORDERED.call_once(|| crate::xlog_info!("D3D12.X: CPU copies are ordered on their queue: its later work waits until the copy has landed (XCL_CPU_COPY_ORDERED=0: not)"));
+ }
+ }
+ let n = writes.len();
+ JOBS_IN.fetch_add(1, Ordering::Relaxed);
+ (n, tx.send(Job { queue: queue as usize, fence: entry.fence.clone(), value: entry.value, writes, done, lists }).is_ok())
+ };
+ static FIRST: std::sync::Once = std::sync::Once::new();
+ if sent {
+ FIRST.call_once(|| crate::xlog_info!("D3D12.X: bottom-of-pipe writes outside unified memory are done by the CPU after the GPU ({writes_n} in the first submission)"));
}
}
@@ -267,8 +487,12 @@ mod tests {
}
}
+ /// (upstream 9db0989) A queue whose fence has not got to its submission keeps that submission's
+ /// writes pending – never written early – while another queue's land: each queue has its own
+ /// worker (`worker`).
#[test]
fn stalled_queue_keeps_writes_pending_without_blocking_other_queues() {
+ use std::time::{Duration, Instant};
unsafe {
let mut dev: Option = None;
if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() {
@@ -281,15 +505,16 @@ mod tests {
let cell = || Box::leak(Box::new(AtomicU32::new(0))) as &AtomicU32;
let first = cell();
let second = cell();
+ // (each fence stands for a queue of its own: the worker's key)
let job = |fence: &ID3D12Fence, at: &AtomicU32| Job {
queue: fence.as_raw() as usize,
fence: fence.clone(),
value: 1,
writes: vec![Write::Immediate(at.as_ptr() as usize, vec![1])],
- submitted: Instant::now() - STALL_AFTER,
- warned: false,
+ done: None,
lists: Vec::new(),
};
+ let enqueue = |j: Job| worker(j.queue).expect("no worker").send(j).unwrap();
enqueue(job(&held, first));
enqueue(job(&done, second));
let wait = |at: &AtomicU32| {
@@ -310,6 +535,92 @@ mod tests {
}
}
+ /// A submission whose fence reads all ones – what a removed device's fences read – while the
+ /// device still answers (`real::stop_if_device_removed` finds nothing to stop): its writes are
+ /// not done (upstream 9db0989), its `done` fence is still signalled, so a queue that waits on
+ /// it goes on, and the queue's next job is done as usual.
+ #[test]
+ fn a_fence_at_all_ones_leaves_the_writes_out_and_still_signals_done() {
+ use std::time::{Duration, Instant};
+ unsafe {
+ let mut dev: Option = None;
+ if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() {
+ crate::gpu::recomp::runner::skip_test("no GPU");
+ return;
+ }
+ let dev = dev.unwrap();
+ let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+ fence.Signal(u64::MAX).unwrap();
+ assert_eq!(fence.GetCompletedValue(), u64::MAX);
+ let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+ let next_fence: ID3D12Fence = dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).unwrap();
+ let marker = Box::leak(Box::new(AtomicU32::new(0))) as &AtomicU32;
+ let next = Box::leak(Box::new(AtomicU32::new(0))) as &AtomicU32;
+ // (the fence stands for a queue of its own: the worker's key)
+ let key = fence.as_raw() as usize;
+ let tx = worker(key).expect("no worker");
+ let job = |fence: &ID3D12Fence, at: &AtomicU32, word: u32, done: Option| Job {
+ queue: key,
+ fence: fence.clone(),
+ value: 1,
+ writes: vec![Write::Immediate(at.as_ptr() as usize, vec![word])],
+ done,
+ lists: Vec::new(),
+ };
+ tx.send(job(&fence, marker, 1, Some(done.clone()))).unwrap();
+ tx.send(job(&next_fence, next, 7, None)).unwrap();
+ let start = Instant::now();
+ while next.load(Ordering::Acquire) == 0 {
+ assert!(start.elapsed() < Duration::from_secs(5), "the queue's next job was never done");
+ std::thread::sleep(Duration::from_millis(1));
+ }
+ assert_eq!(done.GetCompletedValue(), 1, "done signalled for the job at all ones");
+ assert_eq!(marker.load(Ordering::Acquire), 0, "no write for a fence at all ones");
+ assert_eq!(next.load(Ordering::Acquire), 7);
+ }
+ }
+
+ /// The title's own signal on the queue, made right after a submission with a CPU copy,
+ /// completes only once the copy has landed (`copy_ordered`) – what GTA VI 1.0.2.1 relies on
+ /// when it reads the destination as soon as its fence says the work is done.
+ #[test]
+ fn a_titles_later_signal_completes_after_the_copy() {
+ unsafe {
+ let mut dev: Option = None;
+ if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() {
+ let Ok(factory) = CreateDXGIFactory1::() else {
+ crate::gpu::recomp::runner::skip_test("no GPU");
+ return;
+ };
+ let Ok(warp) = factory.EnumWarpAdapter::() else {
+ crate::gpu::recomp::runner::skip_test("no GPU");
+ return;
+ };
+ if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() {
+ crate::gpu::recomp::runner::skip_test("no GPU");
+ return;
+ }
+ }
+ let dev = dev.unwrap();
+ let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap();
+ let title_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+ for round in 1..=32u64 {
+ // a 16 KiB header, as the title copies it, with a pattern that differs per round
+ let from: Vec = (0..0x4000u32).map(|i| (i as u64 * 31 + round * 7) as u8).collect();
+ let to = vec![0u8; 0x4000];
+ let (src, dst) = (from.as_ptr() as usize, to.as_ptr() as usize);
+ after(q.as_raw(), vec![Write::Copy { dst, src, len: from.len() }], Vec::new());
+ q.Signal(&title_fence, round).unwrap();
+ let t = std::time::Instant::now();
+ while title_fence.GetCompletedValue() < round {
+ assert!(t.elapsed().as_secs() < 15, "the title's signal never completed (round {round})");
+ std::thread::yield_now();
+ }
+ assert!(to == from, "round {round}: the title's signal completed before the copy landed");
+ }
+ }
+ }
+
/// A ReadbackU64 write copies the 64-bit value from the mapped readback buffer after the queue finishes.
#[test]
fn readback_u64_lands_after_the_queue() {
diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs
index 621991f..f0e096c 100644
--- a/crates/xcl/src/hle/d3d12x/device_x.rs
+++ b/crates/xcl/src/hle/d3d12x/device_x.rs
@@ -225,6 +225,7 @@ pub(super) unsafe extern "system" fn create_shader_cache_session_x(
/// the desc is a PC D3D12_GRAPHICS_PIPELINE_STATE_DESC with console shaders; the extensions
/// are not modelled
pub(super) unsafe extern "system" fn create_graphics_pso_x(this: *mut c_void, desc: *const c_void, extensions: u32, _ext: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
+ let _xcl_api = crate::waitwatch::api("device_x::create_graphics_pso_x");
static N: AtomicU64 = AtomicU64::new(0);
if extensions != 0 && once(&N, 1) {
crate::xlog_info!("D3D12.X: CreateGraphicsPipelineStateX with {extensions} extension(s) – not modelled");
@@ -489,6 +490,22 @@ pub(super) fn depth_bias_cache_len() -> usize {
DEPTH_BIAS_PSOS.lock().unwrap().as_ref().map_or(0, HashMap::len)
}
+/// (tests) `derived` as the cached depth-bias variant of (`base`, `bias`) – Some – or that entry
+/// taken out again without releasing it – None (a test's fake pipeline is never released).
+#[cfg(test)]
+pub(super) fn set_depth_bias_pso_for_test(base: usize, bias: DepthBias, derived: Option) {
+ let mut g = DEPTH_BIAS_PSOS.lock().unwrap();
+ let m = g.get_or_insert_with(HashMap::new);
+ match derived {
+ Some(d) => {
+ m.insert((base, bias), d);
+ }
+ None => {
+ m.remove(&(base, bias));
+ }
+ }
+}
+
#[cfg(test)]
pub(super) fn register_test_base(pso: usize, dynamic_depth_bias: bool, static_bias: DepthBias) {
let base = Arc::new(Base {
@@ -657,6 +674,7 @@ pub(super) unsafe extern "system" fn create_derived_pso_x(this: *mut c_void, bas
/// device #86 CreatePipelineState(stream desc, riid, pipeline)
pub(super) unsafe extern "system" fn create_pipeline_state_x(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
+ let _xcl_api = crate::waitwatch::api("device_x::create_pipeline_state_x");
real::dev_create_pipeline_state(this, desc, riid, ppv)
}
@@ -1036,6 +1054,7 @@ fn note_alias(va: usize, x: &[u8; 0x38]) {
/// memory (placed in its UMA heap); a texture gets a PC texture kept in step with the memory
/// (`title_textures`: detiled as the console lays it out, uploaded again after CPU writes).
pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, va: u64, desc: *const u8, state: u32, clear: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
+ let _xcl_api = crate::waitwatch::api("device_x::create_placed_resource_x");
static N: AtomicU64 = AtomicU64::new(0);
if desc.is_null() || ppv.is_null() || !crate::gpu::shader::readable(desc as usize, 0x38) {
return E_INVALIDARG;
@@ -1043,6 +1062,16 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void,
let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned();
let d = pc_resource_desc(&x);
let buffer = u32::from_le_bytes(d[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32;
+ if crate::hle::kernelx::traced_range(va as usize, 1) {
+ let u64at = |o: usize| u64::from_le_bytes(d[o..o + 8].try_into().unwrap());
+ crate::xlog_info!(
+ "[trace] CreatePlacedResourceX at {va:#x}: dimension {}, width {}, state {state:#x}; console desc {:02x?}; from {}",
+ u32::from_le_bytes(d[0..4].try_into().unwrap()),
+ u64at(0x10),
+ &x[..0x38],
+ crate::hle::kernelx::callers(1)
+ );
+ }
note_alias(va as usize, &x);
// console-only state bits (Unicorn Overlord's 4K display target: 0x100000) are not the
// PC's: the PC refused the resource (E_INVALIDARG) and the title threw
@@ -1059,12 +1088,15 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void,
}
}
// render targets, depth buffers, UAV textures: in video memory, aliased by address (`vram`);
- // sampled textures: on the same shared 64 KiB pages when tiled resources allow, else committed
+ // sampled textures: on the same shared 64 KiB pages when tiled resources allow, else – in a
+ // GPU view, `lazy_tex` – reserved with tiles where the title's memory is, else committed
let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap());
let mut placed_hr = None;
+ let mut made = Made::Committed;
+ let mut pc_bytes = 0u64;
+ let console_bytes = if buffer { None } else { crate::hle::xg::Texture::new(&x).ok().map(|t| t.size()).filter(|&s| s != u64::MAX && s != 0) };
if !buffer {
let pc = std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC);
- let console_bytes = crate::hle::xg::Texture::new(&x).ok().map(|t| t.size()).filter(|&s| s != u64::MAX && s != 0);
if super::vram::gpu_owned(flags) {
if let Some(hr) = super::vram::place(this, va as usize, &pc, state, clear, console_bytes, riid, ppv) {
if hr >= 0 && !(*ppv).is_null() {
@@ -1072,11 +1104,29 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void,
super::title_textures::retire_overlapping(va as usize, bytes as usize);
}
real::note_title_address(*ppv as usize, va as usize);
+ note_made(Made::Arena, console_bytes.unwrap_or(0), 0);
+ made_as(MadeAs { how: Made::Arena, pc: 0, kept: false });
}
return hr;
}
+ made = Made::OwnedCommitted;
+ if super::title_textures::census_on() {
+ pc_bytes = real::pc_size(this, &d);
+ }
} else {
placed_hr = super::vram::place_pages(this, va as usize, &pc, state, clear, console_bytes, riid, ppv);
+ if placed_hr.is_some() {
+ made = Made::Pages;
+ } else {
+ // (the PC's size: what a lazy texture's tiles are weighed against, and the census)
+ if super::lazy_tex::enabled() || super::title_textures::census_on() {
+ pc_bytes = real::pc_size(this, &d);
+ }
+ placed_hr = super::lazy_tex::create(this, va as usize, &pc, &x, pc_bytes, state, clear, riid, ppv, &|a, n| super::title_textures::pages_present(a, n));
+ if placed_hr.is_some() {
+ made = Made::Lazy;
+ }
+ }
}
}
let hr = match placed_hr {
@@ -1088,24 +1138,34 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void,
};
if hr >= 0 && !buffer && !(*ppv).is_null() {
static M: AtomicU64 = AtomicU64::new(0);
- match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)) {
+ note_made(made, console_bytes.unwrap_or(0), pc_bytes);
+ match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32), pc_bytes) {
Ok(()) => {
real::note_title_address(*ppv as usize, va as usize);
+ note_source(console_bytes.unwrap_or(0));
+ made_as(MadeAs { how: made, pc: pc_bytes, kept: true });
return hr;
}
- Err(e) if once(&M, 4) => {
- let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap());
- crate::xlog_warn!(
- "D3D12.X: CreatePlacedResourceX texture at {va:#x} (dimension {} {}x{}x{}, {} mips, format {}, {} samples, layout {:#x}, flags {:#x}): not kept in step with the memory ({e})",
- u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u16::from_le_bytes(x[0x1C..0x1E].try_into().unwrap()),
- u16::from_le_bytes(x[0x1E..0x20].try_into().unwrap()), u(0x20), u(0x24), u(0x2C), u(0x30)
- )
+ Err(e) => {
+ note_made(Made::NotKept, console_bytes.unwrap_or(0), pc_bytes);
+ made_as(MadeAs { how: made, pc: pc_bytes, kept: false });
+ if once(&M, 4) {
+ let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap());
+ crate::xlog_warn!(
+ "D3D12.X: CreatePlacedResourceX texture at {va:#x} (dimension {} {}x{}x{}, {} mips, format {}, {} samples, layout {:#x}, flags {:#x}): not kept in step with the memory ({e})",
+ u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u16::from_le_bytes(x[0x1C..0x1E].try_into().unwrap()),
+ u16::from_le_bytes(x[0x1E..0x20].try_into().unwrap()), u(0x20), u(0x24), u(0x2C), u(0x30)
+ )
+ }
}
- Err(_) => {}
}
}
if hr >= 0 && !(*ppv).is_null() {
real::note_title_address(*ppv as usize, va as usize);
+ // (a buffer reaches this point only with a PC resource of its own: the census, `outside`)
+ if buffer {
+ super::outside::note_placed(*ppv as usize, va as usize, &d);
+ }
}
if hr < 0 || once(&N, 4) {
let w = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap());
@@ -1124,8 +1184,126 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void,
/// device #133 (a retail game): CreatePlacedResourceX with a barrier layout (D3D12_BARRIER_LAYOUT, seen:
/// 0xFFFFFFFF = undefined for a buffer) in the initial state's place.
pub(super) unsafe extern "system" fn create_placed_resource_layout_x(this: *mut c_void, va: u64, desc: *const u8, layout: u32, clear: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
+ let _xcl_api = crate::waitwatch::api("device_x::create_placed_resource_layout_x");
real::note_newer_device_method(133);
- create_placed_resource_x(this, va, desc, layout_state(layout), clear, riid, ppv)
+ with_source(Source::Layout, || create_placed_resource_x(this, va, desc, layout_state(layout), clear, riid, ppv))
+}
+
+/// How a title texture placed in its memory was made (`creation_stats`; the view census).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) enum Made {
+ /// sampled: committed
+ Committed,
+ /// sampled: reserved with tiles where the title's memory is (`lazy_tex`)
+ Lazy,
+ /// sampled: on shared pages (`vram::place_pages`)
+ Pages,
+ /// GPU-owned: in an arena (`vram::place`)
+ Arena,
+ /// GPU-owned: committed (no arena for it)
+ OwnedCommitted,
+ /// of those above, not kept in step with the memory (`title_textures::register` refused it:
+ /// render targets, depth buffers, the console's 116 / 117 floats)
+ NotKept,
+}
+
+/// Which method of the title's made a resource (`with_source`).
+#[derive(Clone, Copy, PartialEq)]
+pub(super) enum Source {
+ /// device #44 CreatePlacedResourceX
+ Placed,
+ /// device #133, the same with a barrier layout
+ Layout,
+ /// a view by address (device #70 / #71, `real::resource_at`)
+ ViewAt,
+ /// CreateCommittedResource of a texture in console memory (`real::place_console_texture`)
+ Committed,
+}
+
+thread_local! {
+ static SOURCE: std::cell::Cell = const { std::cell::Cell::new(Source::Placed) };
+ /// how the last texture `create_placed_resource_x` made on this thread was made, while the view
+ /// census is on (`made_as`): `real::resource_at` takes it after its call (beside `SOURCE`, on
+ /// the same path)
+ static LAST_MADE: std::cell::Cell> = const { std::cell::Cell::new(None) };
+}
+
+/// `f` making resources for the title's method `s`.
+pub(super) fn with_source(s: Source, f: impl FnOnce() -> R) -> R {
+ let was = SOURCE.with(|c| c.replace(s));
+ let r = f();
+ SOURCE.with(|c| c.set(was));
+ r
+}
+
+/// How `create_placed_resource_x` made a texture (the view census: what a views-by-address one
+/// is, `real::ViewTexture`).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct MadeAs {
+ pub how: Made,
+ /// the PC's committed size of it (0: not known – arenas, pages)
+ pub pc: u64,
+ /// kept in step with the memory (`title_textures::register` took it)
+ pub kept: bool,
+}
+
+/// The texture just made was made as `m`: kept for this thread's caller while the view census is
+/// on – nothing otherwise (no thread-local on the title's creation path then).
+fn made_as(m: MadeAs) {
+ if super::view_census::on() {
+ LAST_MADE.with(|c| c.set(Some(m)));
+ }
+}
+
+/// How the texture `create_placed_resource_x` last made on this thread was made – taken: the next
+/// take gives None until another is made (None: none since, or the view census is off).
+pub(super) fn take_last_made() -> Option {
+ LAST_MADE.with(|c| c.take())
+}
+
+/// (count, console bytes, PC bytes) by `Made`
+static MADE: [[AtomicU64; 3]; 6] = [const { [const { AtomicU64::new(0) }; 3] }; 6];
+/// (count, console bytes) of the textures kept in step by `Source`
+static SOURCES: [[AtomicU64; 2]; 4] = [const { [const { AtomicU64::new(0) }; 2] }; 4];
+
+fn note_made(m: Made, console: u64, pc: u64) {
+ let k = &MADE[m as usize];
+ k[0].fetch_add(1, Ordering::Relaxed);
+ k[1].fetch_add(console, Ordering::Relaxed);
+ k[2].fetch_add(pc, Ordering::Relaxed);
+}
+
+fn note_source(console: u64) {
+ let k = &SOURCES[SOURCE.with(|c| c.get()) as usize];
+ k[0].fetch_add(1, Ordering::Relaxed);
+ k[1].fetch_add(console, Ordering::Relaxed);
+}
+
+/// The title textures placed in its memory so far by how they were made and by the method that
+/// made them, as text (`XCL_ACTIVITY`).
+pub fn creation_stats() -> String {
+ let l = |a: &AtomicU64| a.load(Ordering::Relaxed);
+ let m = |k: Made| {
+ let x = &MADE[k as usize];
+ format!("{} ({} MB, {} MB on the PC)", l(&x[0]), l(&x[1]) >> 20, l(&x[2]) >> 20)
+ };
+ let s = |k: Source| {
+ let x = &SOURCES[k as usize];
+ format!("{} ({} MB)", l(&x[0]), l(&x[1]) >> 20)
+ };
+ format!(
+ "title textures made: sampled committed {}, lazy {}, on pages {}; GPU-owned in arenas {}, committed {}; of those not kept in step {}; kept in step from #44 {}, #133 {}, views by address {}, committed by the title {}",
+ m(Made::Committed),
+ m(Made::Lazy),
+ m(Made::Pages),
+ m(Made::Arena),
+ m(Made::OwnedCommitted),
+ m(Made::NotKept),
+ s(Source::Placed),
+ s(Source::Layout),
+ s(Source::ViewAt),
+ s(Source::Committed)
+ )
}
/// The resource state (D3D12_RESOURCE_STATES) of a D3D12_BARRIER_LAYOUT (undefined: COMMON).
@@ -1201,6 +1379,27 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi
super::indirect::register(sig, stride, &list);
} else if matches!(list.as_slice(), [a] if a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH.0 as u32) {
super::bind::note_dispatch_mesh_signature(sig, stride);
+ } else if matches!(list.as_slice(), [a] if a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32) {
+ // (its group counts are checked before the GPU runs them: `indirect::sanitize`)
+ super::indirect::note_plain_dispatch(sig, stride);
+ super::indirect::warm_up(this as usize);
+ } else if let [a] = list.as_slice() {
+ // (a translated draw's arguments outside unified memory are checked before the GPU
+ // runs them: `indirect::draw_check`)
+ let indexed = a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED.0 as u32;
+ if indexed || a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW.0 as u32 {
+ super::indirect::note_plain_draw(sig, stride, indexed);
+ super::indirect::warm_up(this as usize);
+ }
+ } else if list.iter().any(|a| a[0] <= D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED.0 as u32) {
+ // a draw with vertex or index buffer views among its arguments: not checked (the first 8 told)
+ static N: AtomicU64 = AtomicU64::new(0);
+ if N.fetch_add(1, Ordering::Relaxed) < 8 {
+ crate::xlog_info!(
+ "D3D12.X: a draw command signature with other arguments (stride {stride}, argument types {:?}): its ExecuteIndirect are not checked",
+ list.iter().map(|a| a[0]).collect::>()
+ );
+ }
}
} else if needs_root {
super::bind::note_root_changing_signature(sig);
@@ -1213,6 +1412,26 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi
mod tests {
use super::*;
+ /// How a texture was made goes to this thread's caller once (`take_last_made`: a second take
+ /// gives none – a later creation that says nothing never hands over an older one), and only
+ /// while the view census is on (`made_as`; the census-on case in a process of its own with
+ /// `EXTRA_ENV=XCL_ACTIVITY=1`) (M17).
+ #[test]
+ fn a_creations_made_record_is_handed_to_its_caller_once() {
+ let m = MadeAs { how: Made::Lazy, pc: 0x7A1E_4000, kept: true };
+ let _ = take_last_made();
+ LAST_MADE.with(|c| c.set(Some(m)));
+ assert_eq!(take_last_made(), Some(m));
+ assert_eq!(take_last_made(), None, "taken: none left");
+ made_as(MadeAs { kept: false, ..m });
+ assert_eq!(take_last_made(), super::super::view_census::on().then_some(MadeAs { kept: false, ..m }), "kept only with the census on");
+ assert_eq!(take_last_made(), None);
+ // (another thread's is its own)
+ LAST_MADE.with(|c| c.set(Some(m)));
+ assert_eq!(std::thread::spawn(take_last_made).join().unwrap(), None);
+ assert_eq!(take_last_made(), Some(m));
+ }
+
#[test]
fn slot_73_preserves_a_null_initial_pipeline_for_command_lists() {
let params = [2, 0, 1];
@@ -1431,4 +1650,60 @@ mod tests {
assert!(!is_shader_cache_session_guid(&IID_XBOX_DMA_COMMAND_LIST));
assert!(!is_shader_cache_session_guid(&IID_GRAPHICS_COMMAND_LIST));
}
+
+ /// The title's plain draw signatures (one DRAW, or one DRAW_INDEXED) are noted when it makes
+ /// them – the draw check reads their commands – and forgotten with them (`gone`); a draw
+ /// signature with a vertex buffer view among its arguments is none.
+ #[test]
+ fn plain_draw_signatures_are_noted_when_made() {
+ use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
+ if !crate::util::mac_host() {
+ return;
+ }
+ unsafe {
+ let mut dev: Option = 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();
+ // (XCL's device: `real::dev_create_command_signature` calls the driver through its table)
+ real::adopt(dev.as_raw(), real::Kind::Device);
+ let iid = GUID::from_u128(ID3D12CommandSignature::IID.to_u128());
+ // a console desc (stride, count, the arguments, node mask); null: refused
+ let make = |stride: u32, args: &[[u32; 4]]| -> *mut c_void {
+ let mut desc = [0u8; 24];
+ desc[0..4].copy_from_slice(&stride.to_le_bytes());
+ desc[4..8].copy_from_slice(&(args.len() as u32).to_le_bytes());
+ desc[8..16].copy_from_slice(&(args.as_ptr() as u64).to_le_bytes());
+ let mut out: *mut c_void = std::ptr::null_mut();
+ if create_command_signature_x(dev.as_raw(), desc.as_ptr(), 0, &iid, &mut out) < 0 {
+ return std::ptr::null_mut();
+ }
+ out
+ };
+ let (draw, indexed) = (D3D12_INDIRECT_ARGUMENT_TYPE_DRAW.0 as u32, D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED.0 as u32);
+ let vertex_buffer = D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW.0 as u32;
+ let sigs = [
+ (make(16, &[[draw, 0, 0, 0]]), Some((16, false))),
+ (make(20, &[[indexed, 0, 0, 0]]), Some((20, true))),
+ (make(32, &[[indexed, 0, 0, 0]]), Some((32, true))),
+ (make(32, &[[vertex_buffer, 0, 0, 0], [draw, 0, 0, 0]]), None),
+ ];
+ for (k, &(sig, want)) in sigs.iter().enumerate() {
+ if sig.is_null() {
+ // (the driver may refuse the last one: its branch only logs)
+ assert_eq!(k, 3, "signature {k} was not made");
+ crate::gpu::recomp::runner::skip_config("its last case only: the driver refused a draw signature with a vertex buffer view");
+ continue;
+ }
+ assert_eq!(super::super::indirect::plain_draw(sig as usize), want, "signature {k}");
+ }
+ for (sig, _) in sigs.into_iter().filter(|s| !s.0.is_null()) {
+ // (what `gone` calls when the title releases it)
+ super::super::bind::forget_mac_signatures(sig as usize);
+ assert_eq!(super::super::indirect::plain_draw(sig as usize), None, "forgotten with it");
+ drop(ID3D12CommandSignature::from_raw(sig));
+ }
+ }
+ }
}
diff --git a/crates/xcl/src/hle/d3d12x/fence_x.rs b/crates/xcl/src/hle/d3d12x/fence_x.rs
index 6915c08..c0a0206 100644
--- a/crates/xcl/src/hle/d3d12x/fence_x.rs
+++ b/crates/xcl/src/hle/d3d12x/fence_x.rs
@@ -25,9 +25,24 @@ struct Fence {
waited: u64,
}
-/// (fences are never freed: XCL holds a reference to each)
+/// the fences queues were told to signal or wait for – never freed while their values are asked
+/// from other threads (`refresh`, `snapshot`): a reference to each is held for good (`entry`)
static FENCES: Mutex>> = Mutex::new(None);
+/// `fence`'s entry. One seen for the first time is held for good: the title's from their
+/// creation (`real::dev_create_fence`), any other – one of XCL's that a hooked queue was told
+/// to signal – by a reference taken here (D3DMetal's objects are outside the memory
+/// `VirtualQuery` reports, so a pointer is not checked: every caller passes a fence a queue
+/// was just given).
+fn entry(g: &mut Option>, fence: usize) -> &mut Fence {
+ g.get_or_insert_with(HashMap::new).entry(fence).or_insert_with(|| {
+ if !super::real::is_title_fence(fence) {
+ unsafe { borrowed(fence, |f| std::mem::forget(f.clone())) };
+ }
+ Fence::default()
+ })
+}
+
/// the event a completion sets (auto-reset); the first use starts the thread that follows it
fn event() -> usize {
static E: OnceLock = OnceLock::new();
@@ -65,11 +80,8 @@ fn refresh() {
for (&p, f) in g.iter().flatten() {
if let Some(c) = f.cell {
if let Some(v) = unsafe { borrowed(p, |f| f.GetCompletedValue()) } {
- // If the device has been removed, GetCompletedValue returns UINT64_MAX.
- // Do not update the cell or treat this as a completed fence value.
- if v == u64::MAX {
- continue;
- }
+ // (a removed device's all-ones goes to the cell too: the title's wait on it ends,
+ // and its next call reaches `real::stop_if_device_removed`)
let was = c.0.swap(v, Ordering::AcqRel);
if was != v {
unsafe {
@@ -94,7 +106,7 @@ unsafe fn arm(fence: usize, value: u64) {
pub(super) unsafe fn note_queue_signal(fence: usize, value: u64) {
let cell = {
let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner());
- let f = g.get_or_insert_with(HashMap::new).entry(fence).or_default();
+ let f = entry(&mut g, fence);
f.signalled = f.signalled.max(value);
f.cell.is_some()
};
@@ -109,18 +121,52 @@ pub(super) unsafe fn note_queue_signal(fence: usize, value: u64) {
/// A queue was told to wait for `fence` (one of the title's) to reach `value`.
pub(super) fn note_queue_wait(fence: usize, value: u64) {
let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner());
- let f = g.get_or_insert_with(HashMap::new).entry(fence).or_default();
+ let f = entry(&mut g, fence);
f.waited = f.waited.max(value);
}
-/// The CPU signalled `fence`.
-pub(super) fn note_cpu_signal(fence: usize) {
- let known = FENCES.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.get(&fence).is_some_and(|f| f.cell.is_some()));
+/// The CPU signalled `fence` with `value`; its completed value was `before`. Signal sets the
+/// value: one below `before` rewinds the fence (used again from 0), and the values queues were
+/// told of before are behind it then. A Signal forward (a CPU job done – DirectStorage's –
+/// while queues still wait for later values, or signal them) changes nothing of theirs.
+pub(super) fn note_cpu_signal(fence: usize, value: u64, before: u64) {
+ let known = {
+ let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner());
+ match g.as_mut().and_then(|m| m.get_mut(&fence)) {
+ Some(f) => {
+ if value < before {
+ f.signalled = f.signalled.min(value);
+ f.waited = f.waited.min(value);
+ }
+ f.cell.is_some()
+ }
+ None => false,
+ }
+ };
if known {
refresh();
}
}
+/// (tests) A fence a test named with a stand-in pointer is forgotten.
+#[cfg(test)]
+pub(super) fn forget_for_test(fence: usize) {
+ if let Some(m) = FENCES.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
+ m.remove(&fence);
+ }
+}
+
+/// Every title fence a queue was told to signal or wait for: (fence, completed value, highest
+/// value a queue was told to signal, highest value a queue was told to wait for) – `stall`.
+pub(super) fn snapshot() -> Vec<(usize, u64, u64, u64)> {
+ let fences: Vec<(usize, u64, u64)> = {
+ let g = FENCES.lock().unwrap_or_else(|e| e.into_inner());
+ g.iter().flatten().map(|(&p, f)| (p, f.signalled, f.waited)).collect()
+ };
+ // (the completed values outside the lock: a queue's Signal takes it)
+ fences.into_iter().map(|(p, sig, wait)| (p, unsafe { borrowed(p, |f| f.GetCompletedValue()) }.unwrap_or(u64::MAX), sig, wait)).collect()
+}
+
/// Diagnostic summary of title fences whose completed value lags their signalled or waited value.
pub(super) fn pending_summary() -> String {
let g = FENCES.lock().unwrap_or_else(|e| e.into_inner());
@@ -142,7 +188,7 @@ pub(super) fn pending_summary() -> String {
pub(super) unsafe extern "system" fn completed_value_address(this: *mut c_void) -> *const u64 {
let (cell, pending) = {
let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner());
- let f = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default();
+ let f = entry(&mut g, this as usize);
match f.cell {
Some(c) => return c.0.as_ptr(),
None => {
@@ -170,30 +216,6 @@ mod tests {
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::*;
- #[test]
- fn fence_cell_updates_on_advance_and_rewind_excluding_device_removal() {
- let cell = Cell(AtomicU64::new(100));
-
- // 1. Advance: 100 -> 101
- let v1 = 101;
- let was1 = cell.0.swap(v1, Ordering::AcqRel);
- assert_eq!(was1, 100);
- assert_eq!(cell.0.load(Ordering::Acquire), 101);
-
- // 2. Legitimate rewind / reset: 101 -> 50
- let v2 = 50;
- let was2 = cell.0.swap(v2, Ordering::AcqRel);
- assert_eq!(was2, 101);
- assert_eq!(cell.0.load(Ordering::Acquire), 50);
-
- // 3. Device removal sentinel (u64::MAX) must be excluded
- let v_removed = u64::MAX;
- if v_removed != u64::MAX {
- cell.0.swap(v_removed, Ordering::AcqRel);
- }
- assert_eq!(cell.0.load(Ordering::Acquire), 50);
- }
-
/// The cell follows the fence: CPU signals at once, queue signals when the GPU is there –
/// also one queued before the address was asked for.
#[test]
@@ -225,8 +247,51 @@ mod tests {
note_queue_signal(p as usize, 7);
wait(cell, 7);
fence.Signal(9).unwrap();
- note_cpu_signal(p as usize);
+ note_cpu_signal(p as usize, 9, 7);
assert_eq!(*cell, 9);
+ // a real fence is held (`entry`): its value can be asked from any thread
+ let mine = |p: usize| {
+ let g = FENCES.lock().unwrap_or_else(|e| e.into_inner());
+ let f = &g.as_ref().unwrap()[&p];
+ (unsafe { borrowed(p, |f| f.GetCompletedValue()) }, f.signalled, f.waited)
+ };
+ assert_eq!(mine(p as usize), (Some(9), 7, 0));
+ // a CPU Signal forward, below what a queue waits for or was told to signal: theirs stay
+ note_queue_wait(p as usize, 20);
+ note_queue_signal(p as usize, 15);
+ fence.Signal(12).unwrap();
+ note_cpu_signal(p as usize, 12, 9);
+ assert_eq!(mine(p as usize), (Some(12), 15, 20));
+ // a rewind (below the value it had): what queues were told is behind it
+ fence.Signal(2).unwrap();
+ note_cpu_signal(p as usize, 2, 12);
+ assert_eq!(mine(p as usize), (Some(2), 2, 2));
+ assert_eq!(*cell, 2);
+ std::mem::forget(fence); // the map keeps its address
+ }
+ }
+
+ /// The all-ones a removed device's fences read reaches the cell too (here a CPU Signal of
+ /// u64::MAX stands for it): the title's wait on the cell ends, and its next call reaches
+ /// `real::stop_if_device_removed` – the cell is not left at the last value it had.
+ #[test]
+ fn the_cell_takes_all_ones_too() {
+ unsafe {
+ let mut dev: Option = None;
+ if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() {
+ let factory: IDXGIFactory4 = CreateDXGIFactory1().unwrap();
+ let warp: IDXGIAdapter = factory.EnumWarpAdapter().unwrap();
+ D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device");
+ }
+ let dev = dev.unwrap();
+ let fence: ID3D12Fence = dev.CreateFence(3, D3D12_FENCE_FLAG_NONE).unwrap();
+ let p = fence.as_raw();
+ let cell = completed_value_address(p);
+ assert_eq!(*cell, 3);
+ fence.Signal(u64::MAX).unwrap();
+ assert_eq!(fence.GetCompletedValue(), u64::MAX);
+ note_cpu_signal(p as usize, u64::MAX, 3);
+ assert_eq!(*cell, u64::MAX, "the cell reads all ones after refresh");
std::mem::forget(fence); // the map keeps its address
}
}
diff --git a/crates/xcl/src/hle/d3d12x/frame.rs b/crates/xcl/src/hle/d3d12x/frame.rs
index 1a78f0c..5c693e7 100644
--- a/crates/xcl/src/hle/d3d12x/frame.rs
+++ b/crates/xcl/src/hle/d3d12x/frame.rs
@@ -333,7 +333,10 @@ pub unsafe extern "system" fn wait_frame_event_x(_this: *mut std::ffi::c_void, t
};
let mut hs = vec![internal as HANDLE];
hs.extend(extra);
- let r = WaitForMultipleObjects(hs.len() as u32, hs.as_ptr(), (flags & WAIT_ALL != 0) as i32, timeout_ms);
+ let r = {
+ let _held = crate::waitwatch::xcl(crate::waitwatch::X_FRAME_EVENT, ty as u64);
+ WaitForMultipleObjects(hs.len() as u32, hs.as_ptr(), (flags & WAIT_ALL != 0) as i32, timeout_ms)
+ };
ACTIVITY[0].fetch_add(1, Ordering::Relaxed);
if r == WAIT_TIMEOUT {
ACTIVITY[1].fetch_add(1, Ordering::Relaxed);
diff --git a/crates/xcl/src/hle/d3d12x/gpu_views.rs b/crates/xcl/src/hle/d3d12x/gpu_views.rs
index dbabc38..08e7d63 100644
--- a/crates/xcl/src/hle/d3d12x/gpu_views.rs
+++ b/crates/xcl/src/hle/d3d12x/gpu_views.rs
@@ -157,6 +157,7 @@ const MAX_BATCHES: usize = 1 << 16;
/// XMemMapPhysicalPagesScatter got in the CPU range in the call before. The result is not
/// looked at.
pub(super) unsafe fn update(n: u32, batches: *const u8, pool: usize, arg: u32) {
+ let _xcl_api = crate::waitwatch::api("gpu_views::update");
let call = CALLS.fetch_add(1, Ordering::Relaxed);
// `XCL_GPU_PAGE_MAPPINGS=0`: the calls are not kept – a GPU view is read by the pairing of
// the two reservations alone (`kernelx::mirrors`), to compare the two
@@ -202,6 +203,23 @@ pub(super) unsafe fn update(n: u32, batches: *const u8, pool: usize, arg: u32) {
.collect();
// (the trace's distances: asked of the kernel before the table is locked)
let places: Vec> = if trace() { resolved.iter().map(|&(_, page)| page.and_then(crate::hle::kernelx::page_address)).collect() } else { Vec::new() };
+ // (diagnostic `kernelx::traced`: asked of the kernel before the table is locked)
+ for (&(view, page), &(_, pool_page)) in resolved.iter().zip(&asked) {
+ if crate::hle::kernelx::traced(view) || page.is_some_and(crate::hle::kernelx::traced) {
+ let place = page.and_then(crate::hle::kernelx::page_address);
+ crate::xlog_info!(
+ "[trace] queue #31 call #{call}: GPU view {view:#x} → pool page {pool_page:x?} (pool address {:x?}) → physical page {page:x?}, which is at {place:x?} ({:?} non-zero bytes there)",
+ pool_page.map(|p| pool + p as usize * PAGE),
+ place.and_then(crate::hle::kernelx::page_nonzero)
+ );
+ if let Some(p) = page {
+ crate::hle::kernelx::trace_add(p);
+ }
+ if let Some(a) = place {
+ crate::hle::kernelx::trace_add(a);
+ }
+ }
+ }
let (mut mapped, mut unmapped, mut lost) = (0usize, 0usize, 0usize);
{
let mut g = VIEWS.lock().unwrap();
@@ -280,6 +298,11 @@ fn page_at(addr: usize) -> Option {
VIEWS.lock().unwrap().as_ref()?.at.get(&(addr & !(PAGE - 1))).copied()
}
+/// (diagnostic) The physical page the queue's mappings show at the GPU-view page of `addr`.
+pub fn physical_page_at(addr: usize) -> Option {
+ page_at(addr)
+}
+
/// What the queue's page mappings say of `addr`: None – no page is mapped at its GPU-view page
/// (or it is no GPU-view address); Some(place) – one is, and `place` is where the CPU has the
/// memory the GPU sees at `addr` (None: a page with no memory yet).
@@ -329,6 +352,15 @@ pub fn counts() -> (usize, u64) {
(MAPPED.load(Ordering::Relaxed), CALLS.load(Ordering::Relaxed))
}
+/// (diagnostic) Whether the queue's mappings show each of `pages` in a GPU view now.
+pub fn pages_in_views(pages: &[usize]) -> Vec {
+ if !any() {
+ return vec![false; pages.len()];
+ }
+ let g = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
+ pages.iter().map(|p| g.as_ref().is_some_and(|v| v.of.contains_key(p))).collect()
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -400,6 +432,7 @@ mod tests {
let ranges = [[1u32, 2, 1]];
let batch: [usize; 3] = [gpu + 5 * PAGE, 1, ranges.as_ptr() as usize];
update(1, batch.as_ptr() as *const u8, pool, 4);
+ assert_eq!(pages_in_views(&[pages[2], pages[1]]), [true, false], "the page shown in the view, not its neighbour");
// (a texture over virtual pages 4..7 of the GPU's range, as the content comparison sees it)
let hash = || crate::hle::d3d12x::title_textures::memory_hash_for_tests(gpu + 4 * PAGE + 0x30, 3 * PAGE - 0x50);
let before = hash();
@@ -418,6 +451,7 @@ mod tests {
update(1, batch.as_ptr() as *const u8, pool, 4);
assert_eq!(memory_at(gpu + 5 * PAGE + 0x40), None);
assert!(views_of(cpu + 5 * PAGE, PAGE).is_empty());
+ assert_eq!(pages_in_views(&[pages[2], pages[1]]), [false, false]);
assert_ne!(written, hash(), "a page unmapped from the view shows too");
assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 4, pages.as_mut_ptr()), 1);
for r in [pool, cpu, gpu] {
diff --git a/crates/xcl/src/hle/d3d12x/indirect.rs b/crates/xcl/src/hle/d3d12x/indirect.rs
index 5374918..9f40768 100644
--- a/crates/xcl/src/hle/d3d12x/indirect.rs
+++ b/crates/xcl/src/hle/d3d12x/indirect.rs
@@ -1,19 +1,284 @@
//! Repack root-changing indirect draws and dispatches on the GPU. The native signature
//! consumes an ABI io UAV address followed by the draw or dispatch arguments for each item.
+//!
+//! On a Mac the group counts of a translated compute ExecuteIndirect are checked on the GPU
+//! before it runs (`Sanitize`). GPU-driven work computes them on the GPU (GTA VI's VFX heap
+//! defragmentation: one program writes (count, 1, 1) for the next, which indexes its records by
+//! group), and a producer whose writes do not reach the PC arguments – title memory outside
+//! unified memory – leaves whatever that memory held. The likely cause of GTA VI's first world
+//! frame keeping a Mac's GPU busy for minutes with no Metal error (run 61): such a count, which
+//! D3DMetal ran as it was.
+//!
+//! A translated draw's ExecuteIndirect with its arguments outside unified memory or in a resource
+//! XCL does not know (once work of a pipeline not built was skipped, or with
+//! `XCL_INDIRECT_SANITIZE_DRAWS=all`: anywhere) is checked as well (`draw_check`; plain DRAW and
+//! DRAW_INDEXED signatures): a vertex or index count, an instance count, a first vertex, index or
+//! instance, or an index range that could hang or fault the GPU makes the command draw nothing. Every
+//! ExecuteIndirect of a translated pipeline is counted when recorded, by where its arguments are
+//! and what became of it (`census`).
use std::collections::HashMap;
use std::ffi::c_void;
use std::mem::ManuallyDrop;
-use std::sync::{Arc, Mutex};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
use windows::core::Interface;
use windows::Win32::Graphics::Direct3D12::*;
-use super::{console_list::{Layout, Param}, real};
+use super::{console_list::{Layout, Param}, real, stall::Args};
use crate::gpu::recomp::{self, KERNEL_SGPRS};
const IO_BYTES: u32 = 4 * KERNEL_SGPRS as u32;
const THREADS: u32 = 64;
-const CONFIG_WORDS: u32 = 13;
+const CONFIG_WORDS: u32 = 14;
+
+/// `XCL_INDIRECT_SANITIZE=0`: a translated compute ExecuteIndirect on a Mac gets the title's
+/// arguments as they are (no check of its group counts).
+pub(super) fn sanitize_on() -> bool {
+ static ON: OnceLock = OnceLock::new();
+ *ON.get_or_init(|| std::env::var("XCL_INDIRECT_SANITIZE").map_or(true, |v| v.trim() != "0"))
+}
+
+/// Groups a checked dispatch command may have (`XCL_INDIRECT_MAX_GROUPS`, default 2^22 – some
+/// 30 times a full-screen pass of 8 x 8 tiles at 4K); more, or Y or Z above D3D12's 65 535,
+/// and the command runs no group.
+pub(super) fn max_groups() -> u32 {
+ static N: OnceLock = OnceLock::new();
+ *N.get_or_init(|| std::env::var("XCL_INDIRECT_MAX_GROUPS").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(1 << 22))
+}
+
+/// What the check lets through – `SANITIZE_HLSL` and the repacker test the same on the GPU
+/// (this copy is the tests' reference: keep them equal).
+#[cfg_attr(not(test), allow(dead_code))]
+pub(super) fn groups_ok(g: [u32; 3], cap: u32) -> bool {
+ if g[0] > cap || g[1] > 65_535 || g[2] > 65_535 {
+ return false;
+ }
+ g.contains(&0) || (g[1] <= cap / g[0] && g[2] <= cap / (g[0] * g[1]))
+}
+
+/// How translated draws' ExecuteIndirect arguments are checked (`XCL_INDIRECT_SANITIZE_DRAWS`).
+/// The check reads plain signatures only – one DRAW or DRAW_INDEXED argument –, never in a bundle
+/// (barriers are not allowed there); a root-changing signature (the repacker copies its draws as
+/// they are) and one with vertex or index buffer views go as the title gave them in every mode
+/// (the census: "as they were", "with a signature the check does not read").
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub(super) enum DrawCheck {
+ /// `0`, or `XCL_INDIRECT_SANITIZE=0`: as the title gave them (0022)
+ Off,
+ /// unset (the default) or `own`: those outside unified memory or in a resource XCL does not
+ /// know – unset, those in unified memory and upload buffers too once work of a pipeline not
+ /// built was skipped (`effective_mode`); `own` keeps to the first
+ Own,
+ /// `all`: wherever they are – unified memory and upload buffers too
+ All,
+}
+
+/// The mode `XCL_INDIRECT_SANITIZE_DRAWS` says (`value`; None: unset), and whether it becomes `All`
+/// once a pipeline's work was skipped (`effective_mode`): the default does, an explicit `own`
+/// never – the mode before work could be skipped (0023's first runs) – nor `0` or `all`. Any other
+/// value is the default, as before.
+fn draw_check_of(value: Option<&str>) -> (DrawCheck, bool) {
+ match value.map(str::trim) {
+ Some("0") => (DrawCheck::Off, false),
+ Some(v) if v.eq_ignore_ascii_case("all") => (DrawCheck::All, false),
+ Some(v) if v.eq_ignore_ascii_case("own") => (DrawCheck::Own, false),
+ _ => (DrawCheck::Own, true),
+ }
+}
+
+/// (`XCL_INDIRECT_SANITIZE_DRAWS`, read once) the mode, and whether the default's upgrade applies
+fn draw_check_setting() -> (DrawCheck, bool) {
+ static M: OnceLock<(DrawCheck, bool)> = OnceLock::new();
+ *M.get_or_init(|| {
+ if !sanitize_on() {
+ return (DrawCheck::Off, false);
+ }
+ let v = std::env::var("XCL_INDIRECT_SANITIZE_DRAWS").ok();
+ let setting = draw_check_of(v.as_deref());
+ match setting {
+ (DrawCheck::All, _) => crate::xlog_info!(
+ "XCL_INDIRECT_SANITIZE_DRAWS=all: translated draws' ExecuteIndirect whose signature is one DRAW or DRAW_INDEXED argument (not in bundles) are checked on the GPU first, in unified memory and upload buffers too; root-changing (repacked) signatures and ones with vertex or index buffer views go as they are (the census: as they were / with a signature the check does not read)"
+ ),
+ (DrawCheck::Own, false) => crate::xlog_info!(
+ "XCL_INDIRECT_SANITIZE_DRAWS=own: translated draws' ExecuteIndirect of one DRAW or DRAW_INDEXED argument (not in bundles) are checked on the GPU only with their arguments outside unified memory or in a resource XCL does not know – also once work of a pipeline not built was skipped"
+ ),
+ _ => {}
+ }
+ setting
+ })
+}
+
+/// The mode `XCL_INDIRECT_SANITIZE_DRAWS` sets (before `effective_mode`).
+pub(super) fn draw_check_mode() -> DrawCheck {
+ draw_check_setting().0
+}
+
+pub(super) fn draw_check_on() -> bool {
+ draw_check_mode() != DrawCheck::Off
+}
+
+/// The mode a draw is checked in: `Own` – the default – becomes `All` once work of a pipeline not
+/// built was skipped (`skipped`: `pso_async::work_skipped`). 0023 skips the work of late, refused,
+/// failed and big-lane pipelines as a matter of course, GPU producers among them; a draw whose
+/// arguments such a producer writes into unified memory reads what was there before – in a first
+/// world frame stale or aliased bytes, an unbounded draw (the hang class before this Mac's kernel
+/// panics). `Off` and `All` stay.
+pub(super) fn effective_mode(mode: DrawCheck, skipped: bool) -> DrawCheck {
+ match (mode, skipped) {
+ (DrawCheck::Own, true) => DrawCheck::All,
+ (m, _) => m,
+ }
+}
+
+/// `XCL_INDIRECT_DRAW_INDICES=0`: the check of a DRAW_INDEXED does not compare its index range with
+/// the bound index buffer (D3D12 reads an index past it as 0; Metal need not). The caps and the
+/// wrap rules stay.
+pub(super) fn draw_indices_on() -> bool {
+ static ON: OnceLock = OnceLock::new();
+ *ON.get_or_init(|| std::env::var("XCL_INDIRECT_DRAW_INDICES").map_or(true, |v| v.trim() != "0"))
+}
+
+/// `XCL_INDIRECT_MAX_DRAW_COUNT` (default 2^23 − 1, `MAX_DRAW_COUNT`): vertices or indices a checked
+/// draw command may draw per instance – a command of 2^23 or more an instance draws nothing.
+pub(super) fn max_draw_count() -> u32 {
+ static N: OnceLock = OnceLock::new();
+ *N.get_or_init(|| std::env::var("XCL_INDIRECT_MAX_DRAW_COUNT").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(MAX_DRAW_COUNT))
+}
+
+/// The default of `max_draw_count`: 2^23 − 1, cool_fox's empirical cut (a command of 2^23 vertices
+/// or indices an instance or more draws nothing) after a window checker found 90 records of 2^24
+/// vertices in one list of GTA VI's GPU-written ones – kept by a cap of 2^24, they ask D3DMetal for
+/// 1.5 G vertex invocations a list (that checker may have reported larger counts clamped to 2^24;
+/// the cut drops both).
+pub(super) const MAX_DRAW_COUNT: u32 = (1 << 23) - 1;
+
+/// `XCL_INDIRECT_MAX_DRAW_WORK` (default 2^26, a 4K screen's pixels eight times over): those times
+/// its instances. (The check divides, so products of 2^32 or more are dropped whatever this is.)
+pub(super) fn max_draw_work() -> u32 {
+ static N: OnceLock = OnceLock::new();
+ *N.get_or_init(|| std::env::var("XCL_INDIRECT_MAX_DRAW_WORK").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(1 << 26))
+}
+
+/// What the draw check lets through – `SANITIZE_DRAW_HLSL` tests the same on the GPU (this copy is
+/// the tests' reference: keep them equal). `n` vertices or indices an instance, `instances`, `first`
+/// the first vertex or index, `first_instance`; `bound` the indices the bound index buffer holds
+/// (u32::MAX: not looked at – a DRAW, no index buffer XCL knows, or `XCL_INDIRECT_DRAW_INDICES=0`).
+/// A DRAW_INDEXED's base vertex is not looked at.
+#[cfg_attr(not(test), allow(dead_code))]
+pub(super) fn draw_ok(n: u32, instances: u32, first: u32, first_instance: u32, cap: u32, work: u32, bound: u32) -> bool {
+ n <= cap && instances <= work / n.max(1) && first <= u32::MAX - n && first_instance <= u32::MAX - instances && first + n <= bound
+}
+
+/// `XCL_INDIRECT_OWN=skip` (a lever for a test run; default off): an ExecuteIndirect of a translated
+/// pipeline whose arguments are in a PC resource of their own – title memory outside unified memory,
+/// which neither translated programs nor the title's CPU writes reach – is not recorded. Counted
+/// (`census`), and `[indirect]` names the first of each program.
+pub(super) fn own_skip() -> bool {
+ static ON: OnceLock = OnceLock::new();
+ *ON.get_or_init(|| {
+ let on = std::env::var("XCL_INDIRECT_OWN").is_ok_and(|v| v.trim().eq_ignore_ascii_case("skip"));
+ if on {
+ crate::xlog_warn!("XCL_INDIRECT_OWN=skip: ExecuteIndirect of translated pipelines with their arguments outside unified memory (a PC resource of their own) are not recorded");
+ }
+ on
+ })
+}
+
+/// `XCL_INDIRECT_CENSUS=0`: no census (its counts, the `ExecuteIndirect recorded so far` line); a
+/// draw's arguments are then looked at only when the draw check or `XCL_INDIRECT_OWN` needs them,
+/// or while `[indirect]` still logs draws (0022).
+pub(super) fn census_on() -> bool {
+ static ON: OnceLock = OnceLock::new();
+ *ON.get_or_init(|| std::env::var("XCL_INDIRECT_CENSUS").map_or(true, |v| v.trim() != "0"))
+}
+
+/// Plain dispatch signatures (one DISPATCH argument, no root arguments): signature → stride.
+static PLAIN: Mutex>> = Mutex::new(None);
+
+pub(super) fn note_plain_dispatch(sig: usize, stride: u32) {
+ if stride >= 12 && stride % 4 == 0 {
+ PLAIN.lock().unwrap().get_or_insert_with(HashMap::new).insert(sig, stride);
+ }
+}
+
+/// The stride of a plain dispatch signature.
+pub(super) fn plain_dispatch(sig: usize) -> Option {
+ PLAIN.lock().unwrap().as_ref()?.get(&sig).copied()
+}
+
+/// Plain draw signatures (one DRAW or DRAW_INDEXED argument, no root arguments): signature →
+/// (stride, indexed).
+static PLAIN_DRAW: Mutex>> = Mutex::new(None);
+
+pub(super) fn note_plain_draw(sig: usize, stride: u32, indexed: bool) {
+ if stride >= if indexed { 20 } else { 16 } && stride % 4 == 0 {
+ PLAIN_DRAW.lock().unwrap().get_or_insert_with(HashMap::new).insert(sig, (stride, indexed));
+ }
+}
+
+/// The stride of a plain draw signature, and whether it draws indexed.
+pub(super) fn plain_draw(sig: usize) -> Option<(u32, bool)> {
+ PLAIN_DRAW.lock().unwrap().as_ref()?.get(&sig).copied()
+}
+
+/// The check of a translated draw's ExecuteIndirect: (stride, command), or None – the check is off,
+/// the arguments are where the mode does not look (`Own` before any work was skipped: unified
+/// memory, an upload buffer – what the title's GPU work or CPU wrote), or the signature is not one
+/// DRAW or DRAW_INDEXED (counted; a root-changing one does not come here: the repacker's). The
+/// caller leaves a bundle's unchecked. `indices`: what the bound index buffer holds (asked only for
+/// an indexed draw). The mode is the effective one (`effective_mode`); the first draw its upgrade
+/// checks is logged.
+pub(super) fn draw_check(place: Args, sig: usize, indices: impl FnOnce() -> u32) -> Option<(u32, Command)> {
+ let (mode, upgrades) = draw_check_setting();
+ let now = if upgrades { effective_mode(mode, super::pso_async::work_skipped()) } else { mode };
+ let check = draw_check_in(now, place, sig, indices);
+ // (`Own` would have let it go as it was)
+ if now != mode && check.is_some() && !matches!(place, Args::Own | Args::Unknown) {
+ static ONCE: std::sync::Once = std::sync::Once::new();
+ ONCE.call_once(|| {
+ crate::xlog_info!(
+ "D3D12.X: work of a pipeline not built was skipped – from now on translated draws' ExecuteIndirect of one DRAW or DRAW_INDEXED argument (not in bundles) are checked on the GPU in unified memory and upload buffers too, as with XCL_INDIRECT_SANITIZE_DRAWS=all (this first one's arguments: {}); XCL_INDIRECT_SANITIZE_DRAWS=own keeps to those outside unified memory or in a resource XCL does not know",
+ place.short()
+ )
+ });
+ }
+ check
+}
+
+fn draw_check_in(mode: DrawCheck, place: Args, sig: usize, indices: impl FnOnce() -> u32) -> Option<(u32, Command)> {
+ match mode {
+ DrawCheck::Off => return None,
+ DrawCheck::Own if !matches!(place, Args::Own | Args::Unknown) => return None,
+ _ => {}
+ }
+ let Some((stride, indexed)) = plain_draw(sig) else {
+ note_unread_draw();
+ return None;
+ };
+ Some((stride, if indexed { Command::DrawIndexed { indices: if draw_indices_on() { indices() } else { u32::MAX } } } else { Command::Draw }))
+}
+
+/// Where ExecuteIndirect's arguments at console offset `offset` of `resource` are.
+pub(super) unsafe fn classify(resource: usize, offset: u64) -> Args {
+ if resource == 0 {
+ return Args::Unknown;
+ }
+ if let Some((p, _)) = real::console_buffer(resource) {
+ let k = crate::gpu::uma::get().and_then(|u| u.window_of(p.saturating_add(offset as usize)));
+ return k.map_or(Args::Unknown, |k| Args::Window(k as u8));
+ }
+ let raw = resource as *mut c_void;
+ let Some(r) = ID3D12Resource::from_raw_borrowed(&raw) else { return Args::Unknown };
+ if r.GetDesc().Dimension != D3D12_RESOURCE_DIMENSION_BUFFER {
+ return Args::Unknown;
+ }
+ let mut props = D3D12_HEAP_PROPERTIES::default();
+ if r.GetHeapProperties(Some(&mut props), None).is_ok() && matches!(props.Type, D3D12_HEAP_TYPE_UPLOAD | D3D12_HEAP_TYPE_GPU_UPLOAD) {
+ return Args::Upload;
+ }
+ Args::Own
+}
#[derive(Clone, Copy)]
enum RootArg {
@@ -46,6 +311,12 @@ pub(super) fn forget(sig: usize) {
if let Some(sigs) = SIGNATURES.lock().unwrap().as_mut() {
sigs.remove(&sig);
}
+ if let Some(sigs) = PLAIN.lock().unwrap().as_mut() {
+ sigs.remove(&sig);
+ }
+ if let Some(sigs) = PLAIN_DRAW.lock().unwrap().as_mut() {
+ sigs.remove(&sig);
+ }
}
impl Signature {
@@ -132,6 +403,513 @@ pub(super) fn retain_resource(allocator: usize, resource: ID3D12Resource) {
pub(super) fn allocator_reset(allocator: usize) {
let buffers = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator));
drop(buffers);
+ // the checked arguments' buffers serve the next recordings (dropped outside the locks:
+ // a Release may call back into D3D12)
+ let chunks = CHUNKS.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)).unwrap_or_default();
+ let mut extra = Vec::new();
+ {
+ let mut free = FREE_CHUNKS.lock().unwrap();
+ for mut c in chunks {
+ c.used = 0;
+ if free.len() < 16 && c.cap == CHUNK_BYTES {
+ free.push(c);
+ } else {
+ extra.push(c);
+ }
+ }
+ }
+ drop(extra);
+}
+
+// --- the check of a translated compute ExecuteIndirect's group counts (a Mac) ---
+
+/// A buffer the checked arguments of one recording go into, piece by piece (`take_chunk`).
+struct Chunk {
+ buf: ID3D12Resource,
+ cap: u64,
+ used: u64,
+ dev: usize,
+}
+
+/// allocator → its chunks (the last one is filled); released when the allocator is reset
+static CHUNKS: Mutex >>> = Mutex::new(None);
+/// chunks of reset allocators, for the next recordings
+static FREE_CHUNKS: Mutex> = Mutex::new(Vec::new());
+const CHUNK_BYTES: u64 = 64 << 10;
+
+/// `bytes` of a buffer (UNORDERED_ACCESS, the state it is left in) for the recording on
+/// `allocator`: (the buffer, the offset).
+unsafe fn take_chunk(dev: &ID3D12Device, allocator: usize, bytes: u64) -> Result<(ID3D12Resource, u64), String> {
+ let bytes = bytes.max(1).next_multiple_of(256);
+ let key = dev.as_raw() as usize;
+ {
+ let mut g = CHUNKS.lock().unwrap();
+ let v = g.get_or_insert_with(HashMap::new).entry(allocator).or_default();
+ if let Some(c) = v.last_mut().filter(|c| c.dev == key && c.cap - c.used >= bytes) {
+ let at = c.used;
+ c.used += bytes;
+ return Ok((c.buf.clone(), at));
+ }
+ }
+ let cap = bytes.max(CHUNK_BYTES);
+ let picked = {
+ let mut free = FREE_CHUNKS.lock().unwrap();
+ free.iter().position(|c| c.dev == key && c.cap >= cap).map(|i| free.swap_remove(i))
+ };
+ let mut c = match picked {
+ Some(c) => c,
+ None => {
+ let mut buf = None;
+ dev.CreateCommittedResource(
+ &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
+ D3D12_HEAP_FLAG_NONE,
+ &D3D12_RESOURCE_DESC {
+ Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: cap, Height: 1, DepthOrArraySize: 1, MipLevels: 1,
+ SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+ Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default()
+ },
+ D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
+ None,
+ &mut buf,
+ )
+ .map_err(|e| format!("a buffer for checked indirect arguments ({cap} B): {e}"))?;
+ Chunk { buf: buf.ok_or("no buffer for checked indirect arguments")?, cap, used: 0, dev: key }
+ }
+ };
+ c.used = bytes;
+ let buf = c.buf.clone();
+ CHUNKS.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().push(c);
+ Ok((buf, 0))
+}
+
+/// The check (one thread a command): a command's group counts are copied to XCL's buffer as
+/// they are when `groups_ok`, else as 0 x 0 x 0 – the command runs nothing.
+const SANITIZE_HLSL: &str = r#"
+cbuffer Config : register(b0) { uint count; uint src_at; uint stride; uint cap; uint dst_at; }
+#ifdef SRC_UAV
+RWByteAddressBuffer src : register(u1);
+#else
+ByteAddressBuffer src : register(t0);
+#endif
+RWByteAddressBuffer dst : register(u0);
+[numthreads(64, 1, 1)]
+void main(uint3 id : SV_DispatchThreadID) {
+ if (id.x >= count)
+ return;
+ uint3 g = src.Load3(src_at + id.x * stride);
+ bool ok = g.x <= cap && g.y <= 65535u && g.z <= 65535u
+ && (g.x == 0u || g.y == 0u || g.z == 0u || (g.y <= cap / g.x && g.z <= cap / (g.x * g.y)));
+ dst.Store3(dst_at + id.x * 12u, ok ? g : uint3(0u, 0u, 0u));
+}
+"#;
+
+#[derive(Clone)]
+struct SanitizePipeline {
+ root: ID3D12RootSignature,
+ pso: ID3D12PipelineState,
+}
+
+/// The check's root signature: `constants` root constants (b0), XCL's buffer (u0), the source as a
+/// UAV (u1, unified memory) or an SRV (t0).
+unsafe fn check_root(dev: &ID3D12Device, src_uav: bool, constants: u32) -> Result {
+ let descriptor = |kind, reg| D3D12_ROOT_PARAMETER {
+ ParameterType: kind,
+ Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: reg, RegisterSpace: 0 } },
+ ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL,
+ };
+ let params = [
+ D3D12_ROOT_PARAMETER {
+ ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS,
+ Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: constants } },
+ ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL,
+ },
+ descriptor(D3D12_ROOT_PARAMETER_TYPE_UAV, 0),
+ if src_uav { descriptor(D3D12_ROOT_PARAMETER_TYPE_UAV, 1) } else { descriptor(D3D12_ROOT_PARAMETER_TYPE_SRV, 0) },
+ ];
+ let desc = D3D12_ROOT_SIGNATURE_DESC { NumParameters: params.len() as u32, pParameters: params.as_ptr(), ..Default::default() };
+ let mut blob = None;
+ D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &mut blob, None).map_err(|e| format!("serialize the indirect check's root signature: {e}"))?;
+ let blob = blob.ok_or("no indirect check root signature blob")?;
+ dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer().cast(), blob.GetBufferSize()))
+ .map_err(|e| format!("create the indirect check's root signature: {e}"))
+}
+
+/// The check's pipeline for `dev`, reading its source as a UAV (unified memory) or an SRV.
+unsafe fn sanitize_pipeline(dev: &ID3D12Device, src_uav: bool) -> Result {
+ static CACHE: Mutex>> = Mutex::new(None);
+ let key = (dev.as_raw() as usize, src_uav);
+ if let Some(p) = CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) {
+ return Ok(p);
+ }
+ let hlsl = if src_uav { format!("#define SRC_UAV 1\n{SANITIZE_HLSL}") } else { SANITIZE_HLSL.to_string() };
+ let dxil = recomp::dxc::compile_cached(&hlsl, "main", "cs_6_6")?.0;
+ let root = check_root(dev, src_uav, 5)?;
+ let pso = compute_pso(dev, &root, &dxil).map_err(|e| format!("create the indirect check's pipeline: {e}"))?;
+ let made = SanitizePipeline { root, pso };
+ // (another thread may have made one meanwhile: the first stays – lists may have recorded it –
+ // and this one, never used, goes after the lock: its Release comes back into XCL, `gone`)
+ let (p, spare) = {
+ let mut g = CACHE.lock().unwrap();
+ let m = g.get_or_insert_with(HashMap::new);
+ match m.get(&key) {
+ Some(p) => (p.clone(), Some(made)),
+ None => {
+ m.insert(key, made.clone());
+ (made, None)
+ }
+ }
+ };
+ drop(spare);
+ Ok(p)
+}
+
+/// A plain dispatch signature of 12 bytes for `dev` (what the checked arguments are read with).
+unsafe fn dispatch_signature(dev: &ID3D12Device) -> Result