diff --git a/Cargo.lock b/Cargo.lock index 324bc0bdf4..cb2a50ac1e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -560,6 +560,7 @@ dependencies = [ "serde_json", "toml", "windows", + "windows-core", "windows-sys 0.61.2", ] diff --git a/README.md b/README.md index b21e067f0b..83a6798152 100644 --- a/README.md +++ b/README.md @@ -149,10 +149,10 @@ A gamepad is recommended ([Controls](#controls)). The game folder is never modif |---|---|---|---| | **Shader recompiler** | ✅ | RDNA2 → HLSL → DXIL: VS, PS, CS, mesh (NGG), GS; atomics, LDS, scratch, images, samplers incl. static ones, wave ops, ray-tracing instructions; structured control flow; parallel DXC, disk cache | 26 698 / 26 698 programs of the retail pack; 0 DXC errors on random samples; per-instruction GPU tests | | **Pipelines** | ✅ | PSOs from console shaders: VS+PS, CS, MS+PS, VS+GS+PS; root signature with the shaders' static samplers; non-blocking creation – a pipeline whose shaders are not compiled yet gets a stand-in at once and is built in the background | GPU tests drawing the game's own VS / PS pairs, also built in the background | -| **D3D12.X compute** | ✅ | console device slots, console descriptor heaps (T# / V# / S#), buffers at their console addresses, compute command lists recorded in the console format and replayed (tables, barriers, clears, copies) | the game's BVH builder and FSR 4 record and run through XCL | +| **D3D12.X compute** | ✅ | console device slots, console descriptor heaps (T# / V# / S#), buffers at their console addresses, compute command lists recorded in the console format and replayed (tables, barriers with console flag translation, clears, copies) | the game's BVH builder and FSR 4 record and run through XCL | | **D3D12.X graphics** | ✅ | device, resources and heaps (also placed in title memory), pipelines; the title's graphics command lists – draws, indirect draws, graphics root arguments, barriers, copies, clears – and command lists recorded by console code, replayed; `PresentX` and frame pacing into an XCL window | Minecraft Preview plays its worlds (millions of draws, none skipped); Fortnite and XDefiant draw their screens | | **Textures** | ✅ | GFX10 tiling (all 14 2D swizzle modes, the 6 3D thick modes, linear), mip chains with mip tail, arrays, cubes and 3D textures → PC textures; supported GPU-written title subresources copy back before their writer queue's title fence becomes visible | 912 / 912 entries detiled in the tested retail archive; GPU upload bit exact in test fixtures | -| **Ray tracing** | ✅ | BLAS / TLAS built on the GPU by the game's own XboxBvhBuilder; RDNA2 BVH node format; BVH intersection instructions emulated in shaders | GPU traversal = brute force reference; the game's builder output checked on the GPU | +| **Ray tracing** | ✅ | BLAS / TLAS built on the GPU by the game's own XboxBvhBuilder; RDNA2 BVH node format; BVH intersection instructions emulated in shaders, with misses for nodes outside mapped memory windows | GPU traversal = brute force reference; the game's builder output checked on the GPU | | **Upscaling** | ✅ | the game's AMD FSR 4 console DLL (`amd_fidelityfx_upscaler_xbox.dll`): context, the 29 pipelines in the console driver's own container (FSPX) translated, a frame's 20 passes recorded and run on the GPU | end-to-end with the real DLL: a 1280×720 → 1920×1080 frame on an RX 9070, the input's gradient in the output | Far-jump address calculations are resolved to fixed targets only when branches enter at the start of the calculation. @@ -263,6 +263,14 @@ xcl shaders D:\data\shaders.rpf --measure-pso HEX --repeat 3 # cold driv xcl rpf D:\data\shaders.rpf --extract NAME --out folder ``` +Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. Add +`-Pipelines` to warm the GPU driver's compute-pipeline cache too (slower and GPU/driver-specific): + +```powershell +.\scripts\precompile-shaders.ps1 -Package 'D:\data\shaders.rpf' +.\scripts\precompile-shaders.ps1 -Package 'D:\data\shaders.rpf' -Pipelines +``` +
Switches, caches, logs and the files XCL writes @@ -272,6 +280,7 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder With presentation disabled, preparation runs without a window. A staged corpus still gates launch when the null renderer is selected. For an unstaged title set `XCL_PREPARE=0` to skip startup preparation, or `XCL_PREPARE_GRAPHICS=0` to skip optional graphics history. + Under Series S (`lockhart`) the usage manifests and graphics history use `-lockhart` file names. `XCL_PREPARE_HISTORY_PRESENT=N` instead prepares at most 500 compute and exact graphics/mesh pipelines used through present `N` in the previous `XCL_PSO_MANIFEST=1` recording. Graphics recipes need a recording made by a build that writes their exact identity; older recordings @@ -337,6 +346,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder watchdog for a GPU queue wait (5000 ms). A value that is not a number above 0 keeps the default. Expiry stops the title before later GPU work is submitted; it never treats elapsed time as proof that the waited-for work completed. +- Retired two-pass mesh buffers from tracked command lists can be reused once all GPU + submissions that used them complete, even while the title still holds the command allocator. +- Direct two-pass mesh draws can reuse one smaller record buffer across several slices when + the memory cap is tight. Each slice keeps the draw's original mesh group IDs. - Translated shaders are reused across XCL rebuilds when the translator sources and DXC toolchain are unchanged; `XCL_TRANSLATED_CACHE=0` disables that disk cache. Loading a cached shader without split pieces reuses the file buffer, avoiding a second @@ -349,7 +362,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder `XCL_DIRECT_SPLIT_INSTRUCTIONS` sets the target instructions per piece (default 12500, zero disables splitting). Loops stay in one piece. A strongly connected component over the target gets its own piece, up to four times the target. Larger components and indirect - dispatches use the whole pipeline. + dispatches use the whole pipeline. A chained dispatch runs in slabs of groups that share one + scratch buffer of at most `XCL_SPLIT_SCRATCH_MB` (default 256); the chains of one recording + share it, and `XCL_SPLIT_SCRATCH_TOTAL_MB` (default 384) bounds what all recordings not yet + reset hold together (past it a dispatch runs in smaller slabs). - Huge pipelines (translated DXIL of `XCL_HUGE_PSO_BYTES` or more, default 262144) built on the background `xcl-pso*` workers take turns in the driver's compiler: `XCL_HUGE_PSO_CONCURRENCY` at once (default 1, maximum 64). Pipelines of 4 MiB or more use a separate one-wide lane so @@ -365,6 +381,13 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder On AMD, cold 128–256 KiB compute pipelines use a separate lane (three background / four wanted at once on hosts with at least 32 GiB RAM, two / three below that), configurable with `XCL_MEDIUM_PSO_CONCURRENCY` and `XCL_MEDIUM_PSO_WANTED_CONCURRENCY`. +- A loop in a translated compute program run by a Dispatch (not ExecuteIndirect) is ended + after its dispatch's share of passes for each entry (between 1024 and 65 536 a thread, fewer the + more threads the dispatch has; the direct DXIL translator ends the thread's program there), so + one that runs away does not hold the GPU past the time Windows gives it. The direct + translator's compact form (programs of 20 000 instructions and more) and `XCL_PER_LANE` keep + only the thread's 65 536 passes in all. `XCL_DISPATCH_LOOP_BUDGET=0` leaves every loop the + thread's 65 536 passes, as before (to compare). - With `XCL_DRED=1`, a D3D12 device removal logs GPU breadcrumbs in `xcl.log`. XCL examines up to 4,096 command lists and reports up to 64 unfinished lists, starting with those on which the GPU completed at least one operation. For each, it names the translated @@ -375,6 +398,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder - `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib requests with virtual destinations. Defaults: four workers and a shared 32 MiB staging budget (`XCL_DSTORAGE_WORKERS`, `XCL_DSTORAGE_MEMORY_BUDGET_MIB`). Requests retire in queue order. +- The queue's page mappings (`CopyPageMappingsBatchX`: a title maps the pages its texture streaming + fills into its GPU views) are applied: a GPU-view page shows the physical page mapped into it. + `XCL_PAGE_MAPPINGS=0` turns them off (the call is ignored and a GPU-view page shows its CPU view at + the same offset, as before). - Every run writes `report.json` (called stubs, unknown D3D12.X slots and interfaces, XGameRuntime classes asked for, shader statistics, audio formats, crash). `d3d12.presents` counts presentations, not visible content. With `XCL_FRAME_DUMP=N` (`N > 1`), @@ -383,6 +410,17 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder (decoded 8-bit R+G+B > 30). The field is `null` until a frame is sampled; `non_dark_samples` is `null` if its format cannot be decoded. Intermediate render-target dumps do not update it. Sampling uses every fourth pixel in each direction (`XCL_FRAME_DUMP_FULL=1`: every pixel). + `XCL_DUMP_TARGETS=[,]` logs, for the first frames with that many draws and dispatches, + each render target and the depth buffer drawn into (draws ran / stand-in / PC / skipped) and dumps + the eight drawn into most (`target_.bmp`); `XCL_DUMP_AFTER_S=` waits `s` seconds first. + `XCL_CAPTURE_FRAME=[,]` writes the command stream of the first frame with that many draws + and dispatches (`s` seconds after the first present at the earliest) to `capture_/` next to + the log: `frame.jsonl` (every submit, barrier, copy, clear, draw and dispatch in the order the GPU got + them, with render targets and root arguments), `resources.jsonl`, `pipelines.jsonl`, the pipelines' + shaders translated again and `summary.txt`. Every frame is recorded until then, which costs time. + `XCL_GPU_TIMES=[,]` times every draw and dispatch of the next `frames` busy frames (from + `s` seconds after the first present) with GPU timestamps and logs the 60 programs that took the + most GPU time per frame (`D3D12.X: GPU times:` lines); the times are coarse, fine for ranking. A coarse sample can miss detail; a non-dark sample does not establish correct rendering or gameplay. With `XCL_STALL_TRACE=1`, `report.json` also contains versioned aggregate counts, total/max time and log2-nanosecond histograms for coarse runtime stalls, plus a bounded list of the newest spans of at diff --git a/crates/xcl/Cargo.toml b/crates/xcl/Cargo.toml index a333bed0ea..83cc661b3e 100644 --- a/crates/xcl/Cargo.toml +++ b/crates/xcl/Cargo.toml @@ -27,6 +27,7 @@ retour = "0.3" serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "1" +windows-core = "0.62" [dependencies.windows] version = "0.62" diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index 0386f7b26a..7b975f3744 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -4,7 +4,7 @@ use std::process::Command; // `pso.rs` also contains cache storage and pipeline setup. Keep it out of the source hash so // those changes do not discard translations; bump this only when its container parsing, // translation options, profiles, or post-translation HLSL changes. -const TRANSLATION_GLUE_REVISION: &str = "pso-glue-v4"; +const TRANSLATION_GLUE_REVISION: &str = "pso-glue-v5"; const TRANSLATOR_SOURCES: &[&str] = &[ "src/gpu/dxbc.rs", diff --git a/crates/xcl/src/config.rs b/crates/xcl/src/config.rs index e262e5bf45..acd0e76f2d 100644 --- a/crates/xcl/src/config.rs +++ b/crates/xcl/src/config.rs @@ -419,6 +419,24 @@ mod tests { } } + /// The Series S profile changes the title memory budget only: unified memory (`uma_mb`, the + /// window plan's size) is the memory mode's, the same as a Series X run's in that mode. + #[test] + fn the_series_s_budget_leaves_unified_memory_as_it_is() { + let manifest = crate::manifest::Manifest { + anaconda_memory: Some("Advanced".into()), + lockhart_memory: Some("Advanced".into()), + ..Default::default() + }; + let resolved = |device: &str| { + let mut c = Config { device_type: device.into(), ..Config::default() }; + c.resolve(Some(&manifest)); + (c.title_memory_mb, c.uma_mb) + }; + assert_eq!(resolved("anaconda"), (13_824, 4095)); + assert_eq!(resolved("lockhart"), (8_192, 4095)); + } + #[test] fn raytracing_tier_parsing() { assert_eq!(parse_raytracing_tier("auto"), None); diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 2a94cd36e0..849be55398 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -109,6 +109,23 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i modules::describe_address(addr) ); crate::xlog_error!("{msg}"); + // what happened lately at the title pages the registers point into + if !ctx.is_null() { + let c = &*ctx; + let mut seen: Vec = Vec::new(); + for (n, v) in [("rax", c.Rax), ("rbx", c.Rbx), ("rcx", c.Rcx), ("rdx", c.Rdx), ("rsi", c.Rsi), ("rdi", c.Rdi), ("rbp", c.Rbp), ("r8", c.R8), ("r9", c.R9), ("r10", c.R10), ("r11", c.R11), ("r12", c.R12), ("r13", c.R13), ("r14", c.R14), ("r15", c.R15)] { + let p = v as usize; + if p < 0x1_0000 || seen.contains(&(p & !0xFFFF)) { + continue; + } + seen.push(p & !0xFFFF); + let d = crate::hle::kernelx::pagelog::describe(p); + if !d.is_empty() { + crate::xlog_error!("page of {n}={p:#x}: {d}"); + } + } + crate::xlog_error!("page events so far: {}", crate::hle::kernelx::pagelog::counts()); + } crate::report::write_final(Some(msg)); crate::log::flush(); } @@ -180,6 +197,116 @@ pub fn find_gs_check(code: &[u8]) -> Option { None } +/// The CPU has CLZERO (CPUID 8000_0008h, EBX bit 0): AMD's since Zen, no Intel CPU. +pub fn cpu_has_clzero() -> bool { + static HAS: std::sync::OnceLock = std::sync::OnceLock::new(); + *HAS.get_or_init(|| unsafe { + std::arch::x86_64::__cpuid(0x8000_0000).eax >= 0x8000_0008 && std::arch::x86_64::__cpuid(0x8000_0008).ebx & 1 != 0 + }) +} + +/// The code of a CLZERO loop's stand-in for a CPU without CLZERO, entered by a `call` in the +/// loop's place: `[rax & !63 .. )` zeroed in whole lines up to `end_reg`, at least one line, rax +/// and the flags left as the loop's last `add rax, 0x40; cmp rax, ` leaves them. No +/// other register changes. +fn clzero_loop_thunk(end_reg: u8) -> Vec { + let r = end_reg & 15; + let mut c: Vec = vec![0x57, 0x51, 0x50]; // push rdi; push rcx; push rax + c.extend_from_slice(&[0x48 | (r >> 3), 0x8B, 0xC8 | (r & 7)]); // mov rcx, + c.extend_from_slice(&[0x48, 0x89, 0xC7]); // mov rdi, rax + c.extend_from_slice(&[0x48, 0x83, 0xE7, 0xC0]); // and rdi, -64 + c.extend_from_slice(&[0x48, 0x29, 0xC1]); // sub rcx, rax + c.extend_from_slice(&[0x76, 0x0A]); // jbe one + c.extend_from_slice(&[0x48, 0x83, 0xC1, 0x3F]); // add rcx, 63 + c.extend_from_slice(&[0x48, 0xC1, 0xE9, 0x06]); // shr rcx, 6 + c.extend_from_slice(&[0xEB, 0x05]); // jmp go + c.extend_from_slice(&[0xB9, 0x01, 0x00, 0x00, 0x00]); // one: mov ecx, 1 + c.extend_from_slice(&[0x48, 0xC1, 0xE1, 0x06]); // go: shl rcx, 6 + c.extend_from_slice(&[0x48, 0x01, 0x0C, 0x24]); // add [rsp], rcx (the rax to leave) + c.extend_from_slice(&[0x31, 0xC0]); // xor eax, eax + c.extend_from_slice(&[0xF3, 0xAA]); // rep stosb + c.extend_from_slice(&[0x58, 0x59, 0x5F]); // pop rax; pop rcx; pop rdi + c.extend_from_slice(&[0x48 | ((r >> 3) << 2), 0x39, 0xC0 | ((r & 7) << 3)]); // cmp rax, + c.push(0xC3); // ret + c +} + +/// Executable memory a `call rel32` at `site` reaches (64 KiB, committed), made in the first free +/// place above it. None: none within 1 GiB. +unsafe fn code_near(site: usize) -> Option { + use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE}; + let mut at = (site + 0x1_0000) & !0xFFFF; + while at - site < 0x4000_0000 { + let p = VirtualAlloc(at as *const std::ffi::c_void, 0x1_0000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize; + if p != 0 { + return Some(p); + } + at += 0x1_0000; + } + None +} + +/// Executable memory `[at, at + len)` of a title image on a CPU without CLZERO: each +/// `clzero; add rax, 0x40; cmp rax, ; jb` loop (`insn::ConsoleOnly::ClzeroLoop`, 12 bytes) +/// becomes a call of a stand-in that zeroes the same lines (`clzero_loop_thunk`). +/// `XCL_CLZERO_PATCH=0` leaves the loops as they are. The patched loops. +/// +/// Left alone, every run of such a loop is an illegal-instruction exception that +/// `emulate_console_only` answers: a retail title's memset is such a loop, and while its world +/// loaded one of its threads was in that exception at every look (thread dumps at 300, 360 and +/// 400 s of several runs on an Intel CPU), with the GPU measured at 0.2 to 0.5 s of work in world +/// frames of 17 to 43 s. +pub unsafe fn patch_clzero_loops(at: usize, len: usize, image: &str) -> usize { + use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; + if len < 12 || std::env::var("XCL_CLZERO_PATCH").is_ok_and(|v| v.trim() == "0") { + return 0; + } + let code = std::slice::from_raw_parts(at as *const u8, len); + let sites: Vec<(usize, u8)> = (0..len - 11) + .filter(|&i| code[i] == 0x0F && code[i + 1] == 0x01 && code[i + 2] == 0xFC && (i == 0 || code[i - 1] != 0x67)) + .filter_map(|i| match crate::insn::decode(&code[i..i + 12]) { + // (rsp is no end of a loop: the stand-in's pushes move it) + Some((crate::insn::ConsoleOnly::ClzeroLoop { end_reg }, 12)) if end_reg != 4 => Some((i, end_reg)), + _ => None, + }) + .collect(); + if sites.is_empty() { + return 0; + } + let Some(arena) = code_near(at + len) else { + crate::xlog_warn!("{image}: {} CLZERO loops stay emulated (no executable memory near the image)", sites.len()); + return 0; + }; + // one stand-in for each end register + let mut thunks = [0usize; 16]; + let mut next = arena; + let mut done = 0; + for &(i, reg) in &sites { + if thunks[reg as usize] == 0 { + let t = clzero_loop_thunk(reg); + std::ptr::copy_nonoverlapping(t.as_ptr(), next as *mut u8, t.len()); + thunks[reg as usize] = next; + next += (t.len() + 15) & !15; + } + let site = at + i; + let Ok(rel) = i32::try_from(thunks[reg as usize] as i64 - (site as i64 + 5)) else { continue }; + let mut patch = [0xE8u8, 0, 0, 0, 0, 0x0F, 0x1F, 0x80, 0, 0, 0, 0]; // call thunk; nop (7 bytes) + patch[1..5].copy_from_slice(&rel.to_le_bytes()); + let mut old = 0u32; + if VirtualProtect(site as *const std::ffi::c_void, 12, PAGE_EXECUTE_READWRITE, &mut old) == 0 { + continue; + } + std::ptr::copy_nonoverlapping(patch.as_ptr(), site as *mut u8, 12); + VirtualProtect(site as *const std::ffi::c_void, 12, old, &mut old); + done += 1; + } + if done != 0 { + windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache(windows_sys::Win32::System::Threading::GetCurrentProcess(), at as *const std::ffi::c_void, len); + crate::xlog_info!("{image}: {done} CLZERO loops run as native code on this CPU, which has no CLZERO (XCL_CLZERO_PATCH=0: emulated, one exception a loop)"); + } + done +} + /// Executable memory `[at, at + len)` of a title image: its `__report_gsfailure` (the target of /// `__security_check_cookie`'s failure jump) is redirected to a report that names the /// function whose stack cookie did not match (the return address on the stack), then ends @@ -1260,6 +1387,41 @@ mod tests { assert_eq!(cmp_eflags(0x202, 0x8000_0000_0000_0000, 1), 0x202 | 0x004 | 0x010 | 0x800); } + /// A CLZERO loop patched for a CPU without CLZERO (`patch_clzero_loops`) zeroes the same + /// lines and leaves rax, the flags and every other register as the loop does. + #[test] + fn a_patched_clzero_loop_zeroes_whole_lines_and_keeps_registers() { + unsafe { + // clzero; add rax, 0x40; cmp rax, r10; jb -12; setb cl (the flags, seen); ret + let code = crate::stubs::alloc_code(64); + let bytes = [0x0Fu8, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x4C, 0x39, 0xD0, 0x72, 0xF4, 0x0F, 0x92, 0xC1, 0xC3]; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), code, bytes.len()); + assert_eq!(patch_clzero_loops(code as usize, bytes.len(), "test"), 1); + assert_eq!(*code, 0xE8, "a call in the loop's place"); + let run = |start: usize, end: usize| -> (usize, usize, usize, usize) { + let (rax, rcx, rdi, rdx): (usize, usize, usize, usize); + std::arch::asm!("call {f}", f = in(reg) code, inout("rax") start => rax, in("r10") end, inout("rcx") 0xAA00usize => rcx, inout("rdi") 0x1111usize => rdi, inout("rdx") 0x2222usize => rdx); + (rax, rcx, rdi, rdx) + }; + #[repr(align(64))] + struct Lines([u8; 64 * 6]); + let mut m = Lines([0xEE; 64 * 6]); + let base = m.0.as_mut_ptr() as usize; + // from the middle of line 1 to the middle of line 3: two passes (rax reaches the end + // after the second), the lines 1 and 2 whole + let (rax, rcx, rdi, rdx) = run(base + 64 + 8, base + 64 * 3 + 8); + assert_eq!(rax, base + 64 * 3 + 8); + assert_eq!(rcx, 0xAA00, "rcx is the caller's but for cl: rax is not below the end"); + assert_eq!((rdi, rdx), (0x1111, 0x2222), "no other register changes"); + assert!(m.0[..64].iter().all(|&b| b == 0xEE) && m.0[64..64 * 3].iter().all(|&b| b == 0) && m.0[64 * 3..].iter().all(|&b| b == 0xEE)); + // end at or before the start: one line, as the loop's first pass + m.0.fill(0xEE); + let (rax, _, _, _) = run(base + 64 * 2, base + 64); + assert_eq!(rax, base + 64 * 3); + assert!(m.0[..64 * 2].iter().all(|&b| b == 0xEE) && m.0[64 * 2..64 * 3].iter().all(|&b| b == 0) && m.0[64 * 3..].iter().all(|&b| b == 0xEE)); + } + } + #[test] fn clzero_loop_aligns_updates_flags_and_falls_back_when_end_le_start() { use std::sync::{atomic::AtomicBool, Arc}; diff --git a/crates/xcl/src/gpu/agility.rs b/crates/xcl/src/gpu/agility.rs index 795dfddd11..82d229e48f 100644 --- a/crates/xcl/src/gpu/agility.rs +++ b/crates/xcl/src/gpu/agility.rs @@ -46,6 +46,10 @@ pub enum State { static STATE: OnceLock = OnceLock::new(); static DEBUG_LAYER: OnceLock> = OnceLock::new(); +static DRED: OnceLock>> = OnceLock::new(); +/// Tests: set when any `create_device` started while the DRED step had not run yet. +#[cfg(test)] +pub(crate) static DRED_LATE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// Candidate directories in search order. pub(crate) fn candidates(env_override: Option, exe_dir: Option, local_app_data: Option) -> Vec { @@ -321,7 +325,13 @@ pub fn create_device

(adapter: P, feature_level: D3D_FEATURE_LEVEL) -> windows where P: Param, { + // DRED only applies to devices created after it is set: before the process's first one + enable_dred_once(); let mut device: Option = None; + #[cfg(test)] + if DRED.get().is_none() { + DRED_LATE.store(true, std::sync::atomic::Ordering::SeqCst); + } match state() { State::Loaded { factory, .. } => { // SAFETY: `factory` is a valid `ID3D12DeviceFactory` kept alive for `'static`, @@ -357,6 +367,41 @@ pub fn configuration_interface(clsid: &GUID) -> windows::core::Res } } +/// What `XCL_DRED` asks for: `None` when it is unset, else whether the breadcrumbs are on too +/// (`XCL_DRED=pagefault`: the faulting address and what was there only; the breadcrumbs put a +/// marker around every operation of every list, which is what made a title stall). +pub(crate) fn dred_request(var: Option) -> Option { + var.map(|v| v != "pagefault") +} + +/// `XCL_DRED=1`: on a device removal the faulting address and the last GPU operations (logged +/// by `log_device_removed`); no debug layer needed. Opt-in: with it XDefiant stalled in its +/// first seconds twice. The settings apply only to devices created after them, so this runs +/// from `create_device`, before the first device of the process (the launch preparation's +/// runner makes one before the title's); once per process. +pub fn enable_dred_once() -> &'static Option> { + DRED.get_or_init(|| { + let breadcrumbs = dred_request(std::env::var_os("XCL_DRED"))?; + Some(match configuration_interface::(&CLSID_D3D12DeviceRemovedExtendedData) { + Ok(d) => { + // SAFETY: `d` is a valid settings interface; the calls only record the setting. + unsafe { + if breadcrumbs { + d.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + } + d.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + } + crate::xlog_info!("D3D12: DRED on ({})", if breadcrumbs { "page faults and the lists' last operations" } else { "page faults" }); + Ok(()) + } + Err(e) => { + crate::xlog_warn!("D3D12: DRED requested but unavailable: {e}"); + Err(e.to_string()) + } + }) + }) +} + /// Enable the debug layer at most once per process. The GPU test runner may create a /// device before D3D12.X starts; enabling it again after that removes the device. pub fn enable_debug_layer() -> &'static Result<(), String> { diff --git a/crates/xcl/src/gpu/agility_tests.rs b/crates/xcl/src/gpu/agility_tests.rs index 234c6a6031..5317a3e3ac 100644 --- a/crates/xcl/src/gpu/agility_tests.rs +++ b/crates/xcl/src/gpu/agility_tests.rs @@ -183,6 +183,31 @@ fn rejects_malformed_export_rvas_and_cross_section_reads() { assert!(read_sdk_version_from_bytes(&x86).is_err()); } +#[test] +fn dred_request_reads_the_variable() { + use std::ffi::OsString; + + assert_eq!(dred_request(None), None); + assert_eq!(dred_request(Some(OsString::from("1"))), Some(true)); + assert_eq!(dred_request(Some(OsString::from("pagefault"))), Some(false)); +} + +/// The DRED settings apply only to devices created after them: `create_device` (the runner's +/// and the title's) has to have set them by the time it returns the process's first device. +#[test] +fn create_device_sets_dred_first() { + // Needs no device: the record is made before the creation call, whether or not it succeeds. + let dev = create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0); + assert!( + !DRED_LATE.load(std::sync::atomic::Ordering::SeqCst), + "a create_device call started before the DRED step had run" + ); + assert!(DRED.get().is_some(), "create_device did not run the DRED step"); + if dev.is_err() { + crate::gpu::recomp::runner::skip_test("no D3D12 device (the ordering was checked)"); + } +} + #[test] fn env_trimming_trailing_slash_and_no_sm66_messages() { use std::ffi::OsString; diff --git a/crates/xcl/src/gpu/bvh.rs b/crates/xcl/src/gpu/bvh.rs index a1b0a36c3c..17393bac7e 100644 --- a/crates/xcl/src/gpu/bvh.rs +++ b/crates/xcl/src/gpu/bvh.rs @@ -22,8 +22,9 @@ //! 3×4 as in D3D12_RAYTRACING_INSTANCE_DESC; @112..127 zero. //! //! The console builder reports sizes for exactly these node sizes plus 4 bytes of parent -//! pointers per 64 bytes of nodes (`tests/console_dlls_e2e.rs`); where those pointers live is -//! unknown and no shader seen reads them, so they are not written. +//! pointers per 64 bytes of nodes (`tests/console_dlls_e2e.rs`). A title's traversal loop reads +//! the parent of node `n` (when its short stack runs out) at the dword +//! `base + 4·((n >> 3) − (header@52 >> 6 − header@56 >> 2))`; the builder here does not write them. //! //! Top-down build: median split of the leaf box centroids on the longest axis, twice per box //! node (4 children), one triangle / instance per leaf. @@ -120,6 +121,15 @@ pub fn build_top(instances: &[Instance]) -> Bvh { Builder { data: Vec::new(), bounds, leaf_bytes: INSTANCE_BYTES, leaf: &leaf }.finish() } +/// A structure no ray hits: its root a box32 node with no child (a top or bottom level alike). +pub fn empty() -> Bvh { + let mut data = vec![0; HEADER_BYTES + BOX_BYTES]; + let root = (HEADER_BYTES / 8) as u32 | BOX32; + put(&mut data, ROOT_AT, &[root]); + put(&mut data, HEADER_BYTES, &[INVALID; 4]); + Bvh { data, root } +} + fn put(out: &mut [u8], at: usize, words: &[u32]) { for (k, w) in words.iter().enumerate() { out[at + 4 * k..at + 4 * k + 4].copy_from_slice(&w.to_le_bytes()); @@ -419,6 +429,250 @@ impl Bvh { } } +/// The tiles a walk reports what it reached in (`Reach::tiles`): a GPU view's (64 KiB) +pub const WALK_TILE: u64 = 0x1_0000; +/// node offsets and parent pointers further than this from a structure's base are not followed +const WALK_SPAN: u64 = 2 << 30; +/// tiles a walk keeps read (64 MiB): more and they are read again +const WALK_CACHE: usize = 1024; +/// root ids followed into one bottom level (besides its header's) +const WALK_ROOTS: usize = 8; + +/// How far a walk of the title's structures goes: it reads memory the title may be writing. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + /// nodes of one structure + pub nodes: u64, + /// nodes of a top level and its bottom levels + pub scene_nodes: u64, + /// bytes read in a walk (whole tiles) + pub bytes: u64, + /// distinct bottom levels of a top level + pub bottoms: usize, +} + +impl Default for Limits { + fn default() -> Self { + Limits { nodes: 4 << 20, scene_nodes: 32 << 20, bytes: 2 << 30, bottoms: 1 << 16 } + } +} + +/// What a traversal can read of one structure, found by walking it from its root(s). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Reach { + pub base: u64, + /// nodes reached (box, triangle, instance) + pub nodes: u64, + /// [first, end) byte of the header and the nodes reached (whole nodes) + pub span: (u64, u64), + /// [first, end) byte of the parent pointers of the nodes reached; None: header @52 and @56 + /// are 0, no parent array + pub parents: Option<(u64, u64)>, + /// the `WALK_TILE` tiles of all of it, as (address, bytes) runs + pub tiles: Vec<(u64, u64)>, + /// why the walk left something out + pub cut: Option<&'static str>, +} + +/// A top level and the bottom levels its instance nodes reach (`walk_scene`). +#[derive(Debug, Default)] +pub struct Scene { + pub top: Reach, + /// the bottom levels walked (those `walk_scene`'s `walk` asked for), by address + pub bottoms: Vec, + /// every distinct bottom-level address of an instance node reached, ascending + pub referenced: Vec, + /// the first thing any walk left out + pub cut: Option<&'static str>, +} + +/// The title's memory as a walk reads it: whole tiles, a few kept; a tile that cannot be read +/// whole is read for the bytes asked only. +struct Mem<'r> { + read: &'r mut dyn FnMut(u64, &mut [u8]) -> bool, + tiles: std::collections::HashMap>>, + bytes: u64, + nodes: u64, + lim: Limits, +} + +/// a read refused: `Err(true)` the byte cap, `Err(false)` memory that cannot be read +type Got = Result<(), bool>; + +impl Mem<'_> { + fn get(&mut self, at: u64, out: &mut [u8]) -> Got { + let end = at.checked_add(out.len() as u64).ok_or(false)?; + let mut p = at; + while p < end { + let t = p & !(WALK_TILE - 1); + let n = (end.min(t.saturating_add(WALK_TILE)) - p) as usize; + let dst = &mut out[(p - at) as usize..][..n]; + if !self.tiles.contains_key(&t) { + if self.bytes >= self.lim.bytes { + return Err(true); + } + if self.tiles.len() >= WALK_CACHE { + self.tiles.clear(); + } + self.bytes += WALK_TILE; + let mut b = vec![0u8; WALK_TILE as usize].into_boxed_slice(); + let whole = t.checked_add(WALK_TILE).is_some() && (self.read)(t, &mut b); + self.tiles.insert(t, whole.then_some(b)); + } + match &self.tiles[&t] { + Some(b) => dst.copy_from_slice(&b[(p - t) as usize..][..n]), + None => { + self.bytes += n as u64; + if !(self.read)(p, dst) { + return Err(false); + } + } + } + p += n as u64; + } + Ok(()) + } +} + +/// `[at, at + len)`'s tiles onto `tiles` (indices) +fn touch(tiles: &mut Vec, at: u64, len: u64) { + for t in at / WALK_TILE..=(at + len - 1) / WALK_TILE { + if tiles.last() != Some(&t) { + tiles.push(t); + } + } +} + +/// Every node the traversal can reach from the header's root and `roots`, once each (a visited +/// set: no loop, whatever the bytes say). `top`: box and instance nodes (whose (bottom-level +/// address, root) go to `found`); else box and triangle nodes. +fn walk(mem: &mut Mem, base: u64, roots: &[u32], top: bool, found: &mut Vec<(u64, u32)>) -> Reach { + let mut r = Reach { base, span: (base, base), ..Default::default() }; + let mut hdr = [0u8; HEADER_BYTES]; + if base.checked_add(WALK_SPAN).is_none() || mem.get(base, &mut hdr).is_err() { + r.cut = Some("header unreadable"); + return r; + } + let mut tiles = Vec::new(); + touch(&mut tiles, base, HEADER_BYTES as u64); + r.span.1 = base + HEADER_BYTES as u64; + // the parent of node n at base + 4·(n / 64 − shift) + let (h52, h56) = (word(&hdr, 52), word(&hdr, 56)); + let shift = (h52 != 0 || h56 != 0).then(|| (h52 >> 6) as i64 - (h56 >> 2) as i64); + let mut parents: Option<(u64, u64)> = None; + let mut seen: Vec = Vec::new(); + let mut stack = vec![word(&hdr, ROOT_AT)]; + stack.extend(roots.iter().rev()); + let mut node = [0u8; 128]; + while let Some(n) = stack.pop() { + if n == INVALID { + continue; + } + let ty = n & 7; + let (size, kind) = match ty { + BOX32 => (128, true), + 4 => (64, true), + INSTANCE => (128, top), + 0..=3 => (64, !top), + _ => (0, false), + }; + let off = node_at(n) as u64; + if !kind || off < HEADER_BYTES as u64 || off + size > WALK_SPAN { + r.cut = r.cut.or(Some("bad node id")); + continue; + } + let k = (off / 64) as usize; + if seen.len() <= k / 64 { + seen.resize(k / 64 + 1, 0); + } + if seen[k / 64] & 1 << (k % 64) != 0 { + continue; + } + if r.nodes >= mem.lim.nodes || mem.nodes >= mem.lim.scene_nodes { + r.cut = Some("node cap"); + break; + } + seen[k / 64] |= 1 << (k % 64); + let at = base + off; + let b = &mut node[..size as usize]; + match mem.get(at, b) { + Ok(()) => {} + Err(true) => { + r.cut = Some("byte cap"); + break; + } + Err(false) => { + r.cut = r.cut.or(Some("node unreadable")); + continue; + } + } + let b: &[u8] = b; + r.nodes += 1; + mem.nodes += 1; + r.span = (r.span.0.min(at), r.span.1.max(at + size)); + touch(&mut tiles, at, size); + if let Some(s) = shift { + let d = 4 * ((off / 64) as i64 - s); + match base.checked_add_signed(d).filter(|_| d.unsigned_abs() <= WALK_SPAN) { + Some(p) => { + parents = Some(parents.map_or((p, p + 4), |(lo, hi)| (lo.min(p), hi.max(p + 4)))); + touch(&mut tiles, p, 4); + } + None => r.cut = r.cut.or(Some("parent pointer out of range")), + } + } + match ty { + BOX32 | 4 => stack.extend((0..4).rev().map(|c| word(b, 4 * c)).filter(|&c| c != INVALID)), + INSTANCE => { + let (root, addr) = (word(b, 56) & 0x3FFF_FFFF, (word(b, 60) as u64) << 8); + if addr != 0 && root != 0x3FFF_FFFF { + found.push((addr, root)); + } + } + _ => {} + } + } + r.parents = parents; + tiles.sort_unstable(); + tiles.dedup(); + for t in tiles { + match r.tiles.last_mut() { + Some((a, n)) if *a + *n == t * WALK_TILE => *n += WALK_TILE, + _ => r.tiles.push((t * WALK_TILE, WALK_TILE)), + } + } + r +} + +/// What a ray traversal can read of the top level at `base` and of the bottom levels its +/// instance nodes reach, through `read` (copies `out.len()` bytes at an address; false when any +/// of them cannot be read). A bottom level is walked when `walk(address)` says so (one known +/// already need not be). Never more than `lim`; what was left out is in the `cut`s. +pub fn walk_scene(read: &mut dyn FnMut(u64, &mut [u8]) -> bool, base: u64, lim: &Limits, walk_bottom: &mut dyn FnMut(u64) -> bool) -> Scene { + let mut mem = Mem { read, tiles: Default::default(), bytes: 0, nodes: 0, lim: *lim }; + let mut found = Vec::new(); + let top = walk(&mut mem, base, &[], true, &mut found); + let mut s = Scene { cut: top.cut, top, ..Default::default() }; + found.sort_unstable(); + found.dedup(); + for g in found.chunk_by(|a, b| a.0 == b.0) { + if s.referenced.len() >= lim.bottoms { + s.cut = s.cut.or(Some("bottom-level cap")); + break; + } + let addr = g[0].0; + s.referenced.push(addr); + if !walk_bottom(addr) { + continue; + } + let roots: Vec = g.iter().take(WALK_ROOTS).map(|x| x.1).collect(); + let b = walk(&mut mem, addr, &roots, false, &mut Vec::new()); + s.cut = s.cut.or(b.cut); + s.bottoms.push(b); + } + s +} + #[cfg(test)] pub(crate) mod tests { use super::*; @@ -594,6 +848,194 @@ pub(crate) mod tests { assert!(!is_compressed_header(&[])); } + /// The empty structure: a ray right through its (zero) bounds reaches no child, as a top or + /// a bottom level. + #[test] + fn the_empty_structure_has_nothing_to_hit() { + let e = empty(); + assert_eq!(word(&e.data, ROOT_AT), e.root); + let (o, d) = ([-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]); + assert_eq!(intersect_node(&e.data, e.root, 100.0, o, d, d.map(|x| 1.0 / x), true), [INVALID; 4]); + assert_eq!(e.trace(o, d, 100.0), None); + assert_eq!(e.trace_scene(&|_| None, o, d, 100.0), None); + let s = walk_scene(&mut space(&[(TOP_AT, e.data.clone())]), TOP_AT, &Limits::default(), &mut |_| true); + assert_eq!((s.top.nodes, s.referenced.len(), s.cut), (1, 0, None)); + } + + /// An address space of `regions` (address, bytes): a read inside one of them only. + fn space(regions: &[(u64, Vec)]) -> impl FnMut(u64, &mut [u8]) -> bool + '_ { + move |a, out| { + let r = regions.iter().find(|(at, d)| a >= *at && a + out.len() as u64 <= at + d.len() as u64); + r.map(|(at, d)| out.copy_from_slice(&d[(a - at) as usize..][..out.len()])).is_some() + } + } + + /// whole tiles over `[at, at + len)` + fn tiles_of(at: u64, len: u64) -> Vec<(u64, u64)> { + let lo = at & !(WALK_TILE - 1); + vec![(lo, (at + len).next_multiple_of(WALK_TILE) - lo)] + } + + /// `n` instances spread over bottom levels at `blas` + fn top_over(blas: &[(u64, Bvh)], n: usize) -> Bvh { + let mut r = rng(5); + let instances: Vec = (0..n) + .map(|i| { + let (addr, b) = &blas[i % blas.len()]; + let t = [r(-50.0, 50.0), r(-50.0, 50.0), r(-50.0, 50.0)]; + let m = [0, 1, 2].map(|row| [(row == 0) as u32 as f32, (row == 1) as u32 as f32, (row == 2) as u32 as f32, t[row]]); + Instance { transform: m, id: i as u32, mask: 0xFF, contribution: 0, flags: 0, blas_address: *addr, blas_root: b.root, blas_bounds: b.bounds() } + }) + .collect(); + build_top(&instances) + } + + const TOP_AT: u64 = 0x20_0000_0000; + + fn walk_all(regions: &[(u64, Vec)], lim: &Limits) -> Scene { + walk_scene(&mut space(regions), TOP_AT, lim, &mut |_| true) + } + + /// box + leaf nodes of a structure from the builder here (every node reachable) + fn node_count(b: &Bvh, leaf: usize, leaves: usize) -> u64 { + (leaves + (b.data.len() - HEADER_BYTES - leaf * leaves) / BOX_BYTES) as u64 + } + + /// A top level of 600 instances (over 64 KiB) over 3 bottom levels, one of them neither at + /// nor a whole number of tiles: the walk reaches exactly each structure's bytes and tiles. + #[test] + fn walk_reaches_exactly_the_top_level_and_each_bottom_level() { + let sizes = [30, 200, 1500]; + let addrs = [0x10_0000_0000u64, 0x10_0040_0000, 0x10_0081_2300]; + let blas: Vec<(u64, Bvh)> = (0..3).map(|k| (addrs[k], build(&random_tris(sizes[k], 40 + k as u64), 0))).collect(); + let top = top_over(&blas, 600); + assert!(top.data.len() > 0x1_0000, "{} bytes", top.data.len()); + let mut regions: Vec<(u64, Vec)> = blas.iter().map(|(a, b)| (*a, b.data.clone())).collect(); + regions[0].1.resize(0x1_0000, 0); // a whole tile: read whole + regions.push((TOP_AT, top.data.clone())); + let s = walk_all(®ions, &Limits::default()); + assert_eq!(s.cut, None); + let len = top.data.len() as u64; + assert_eq!(s.top.span, (TOP_AT, TOP_AT + len)); + assert_eq!(s.top.nodes, node_count(&top, INSTANCE_BYTES, 600)); + assert_eq!(s.top.tiles, tiles_of(TOP_AT, len)); + assert_eq!(s.top.parents, None, "header @52 / @56 0: no parent array"); + assert_eq!(s.referenced, addrs); + for (k, b) in s.bottoms.iter().enumerate() { + let (a, built) = &blas[k]; + let len = built.data.len() as u64; + assert_eq!((b.base, b.span, b.cut), (*a, (*a, *a + len), None), "bottom level {k}"); + assert_eq!(b.nodes, node_count(built, TRI_BYTES, sizes[k]), "bottom level {k}"); + assert_eq!(b.tiles, tiles_of(*a, len), "bottom level {k}"); + } + // a bottom level known already is not walked again, still referenced + let s2 = walk_scene(&mut space(®ions), TOP_AT, &Limits::default(), &mut |a| a != addrs[1]); + assert_eq!((s2.referenced.len(), s2.bottoms.len()), (3, 2)); + } + + /// An instance's bottom level that cannot be read is left out and said so; the others are not. + #[test] + fn walk_leaves_out_an_unreadable_bottom_level() { + let good = build(&random_tris(50, 3), 0); + let blas = [(0x10_0000_0000u64, good), (0x30_0000_0000, build(&random_tris(5, 4), 0))]; + let top = top_over(&blas, 8); + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, top.data.clone())]; + let s = walk_all(®ions, &Limits::default()); + assert_eq!(s.referenced, [0x10_0000_0000, 0x30_0000_0000]); + assert_eq!(s.cut, Some("header unreadable")); + assert_eq!((s.bottoms[0].nodes, s.bottoms[0].cut), (node_count(&blas[0].1, TRI_BYTES, 50), None)); + assert_eq!((s.bottoms[1].nodes, s.bottoms[1].tiles.len(), s.bottoms[1].cut), (0, 0, Some("header unreadable"))); + assert_eq!(s.top.nodes, node_count(&top, INSTANCE_BYTES, 8)); + } + + /// A box pointing back at the root (or twice at one child) is walked once. + #[test] + fn walk_visits_a_node_once_in_a_cycle() { + let blas = [(0x10_0000_0000u64, build(&random_tris(5, 4), 0))]; + let mut top = top_over(&blas, 3); + assert_eq!(word(&top.data, HEADER_BYTES + 12), INVALID); + put(&mut top.data, HEADER_BYTES + 12, &[top.root]); + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, top.data.clone())]; + let s = walk_all(®ions, &Limits::default()); + assert_eq!((s.top.nodes, s.top.cut), (4, None)); + let first = word(&top.data, HEADER_BYTES); + put(&mut top.data, HEADER_BYTES + 12, &[first]); + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, top.data.clone())]; + assert_eq!(walk_all(®ions, &Limits::default()).top.nodes, 4); + } + + /// A root that is no node of a top level (a triangle, an unknown type, inside the header, + /// too far, not there) gives no node, and says why. + #[test] + fn walk_refuses_a_garbage_root() { + let blas = [(0x10_0000_0000u64, build(&random_tris(5, 4), 0))]; + let top = top_over(&blas, 3); + let cases = [(0x7u32 | (HEADER_BYTES as u32 / 8), "bad node id"), (HEADER_BYTES as u32 / 8, "bad node id"), (0x10 | BOX32, "bad node id"), (0x4000_0000 | BOX32, "bad node id"), (0x10_0000 | BOX32, "node unreadable")]; + for (root, why) in cases { + let mut data = top.data.clone(); + put(&mut data, ROOT_AT, &[root]); + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, data)]; + let s = walk_all(®ions, &Limits::default()); + assert_eq!((s.top.nodes, s.top.cut, s.referenced.len()), (0, Some(why), 0), "root {root:#x}"); + assert_eq!(s.top.tiles, tiles_of(TOP_AT, HEADER_BYTES as u64), "the header only"); + } + } + + /// Memory that ends inside the structure: the nodes before it, and said so. + #[test] + fn walk_stops_at_truncated_memory() { + let blas = [(0x10_0000_0000u64, build(&random_tris(5, 4), 0))]; + let top = top_over(&blas, 600); + let half = top.data.len() / 2 + 0x40; + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, top.data[..half].to_vec())]; + let s = walk_all(®ions, &Limits::default()); + assert_eq!(s.top.cut, Some("node unreadable")); + assert!(s.top.nodes > 100 && s.top.nodes < node_count(&top, INSTANCE_BYTES, 600), "{} nodes", s.top.nodes); + assert!(s.top.span.1 <= TOP_AT + half as u64); + assert_eq!(s.referenced, [blas[0].0]); + } + + /// The node, scene and byte caps end a walk with what it found. + #[test] + fn walk_stops_at_its_caps() { + let blas = [(0x10_0000_0000u64, build(&random_tris(300, 4), 0))]; + let top = top_over(&blas, 600); + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, top.data.clone())]; + let s = walk_all(®ions, &Limits { nodes: 10, ..Default::default() }); + assert_eq!((s.top.nodes, s.top.cut), (10, Some("node cap"))); + let all = node_count(&top, INSTANCE_BYTES, 600); + let s = walk_all(®ions, &Limits { scene_nodes: all + 7, ..Default::default() }); + assert_eq!((s.top.nodes, s.bottoms[0].nodes, s.cut), (all, 7, Some("node cap"))); + let s = walk_all(®ions, &Limits { bytes: WALK_TILE, ..Default::default() }); + assert_eq!(s.top.cut, Some("byte cap")); + assert!(s.top.span.1 <= TOP_AT + WALK_TILE); + let s = walk_all(®ions, &Limits { bottoms: 0, ..Default::default() }); + assert_eq!((s.referenced.len(), s.cut), (0, Some("bottom-level cap"))); + } + + /// The parent pointer of every node reached, at header@52 / @56's place: before the nodes + /// here (in the tile before the structure's); one too far is left out, without overflow. + #[test] + fn walk_reaches_the_parent_pointers() { + let blas = [(0x10_0000_0000u64, build(&random_tris(5, 4), 0))]; + let mut top = top_over(&blas, 600); + let last = (top.data.len() - INSTANCE_BYTES) as u64 / 64; + // shift = 0x40_0000 >> 6 − 0x40 >> 2 = 65520: the pointers from 4·(4 − 65520) on + put(&mut top.data, 52, &[0x40_0000, 0x40]); + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, top.data.clone())]; + let s = walk_all(®ions, &Limits::default()); + let p = |k: u64| TOP_AT - 4 * (65520 - k); + assert_eq!(s.top.parents, Some((p(4), p(last) + 4))); + assert_eq!(s.top.cut, None); + let len = top.data.len() as u64; + assert_eq!(s.top.tiles, [tiles_of(p(4), p(last) + 4 - p(4)), tiles_of(TOP_AT, len)].concat()); + put(&mut top.data, 52, &[0, 0xFFFF_FFFC]); + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, top.data.clone())]; + let s = walk_all(®ions, &Limits::default()); + assert_eq!((s.top.parents, s.top.cut), (None, Some("parent pointer out of range"))); + assert_eq!(s.top.tiles, tiles_of(TOP_AT, len)); + } + #[test] fn grazing_axis_aligned_ray_and_nan_box() { let mut data = vec![0u8; 256]; diff --git a/crates/xcl/src/gpu/dxil/cfg.rs b/crates/xcl/src/gpu/dxil/cfg.rs index 4f114cb15e..3e3ee17075 100644 --- a/crates/xcl/src/gpu/dxil/cfg.rs +++ b/crates/xcl/src/gpu/dxil/cfg.rs @@ -1,7 +1,7 @@ //! Basic blocks of a decoded RDNA2 program, their edges and a reverse //! post-order (the emission order: every block after its dominators). -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use crate::gpu::rdna2::{self, Decoded}; @@ -244,6 +244,39 @@ fn make_reducible_inner(blocks: &mut Vec) -> Result<(Vec, BTree } } +/// The loop directly around each loop header of a reducible `cfg` (None: an outermost loop). +/// A header's loop is its header and every block that reaches one of its back edges (an edge +/// into it from a block at or after it in `rpo`) without passing the header; the loop around +/// it is the smallest other loop that holds its header. +pub fn loop_parents(cfg: &Cfg) -> BTreeMap> { + let n = cfg.blocks.len(); + let mut pos = vec![usize::MAX; n]; + for (i, &b) in cfg.rpo.iter().enumerate() { + pos[b] = i; + } + let body = |h: usize| { + let mut inside = vec![false; n]; + inside[h] = true; + let mut stack: Vec = cfg.blocks[h].preds.iter().copied().filter(|&p| pos[p] != usize::MAX && pos[p] >= pos[h]).collect(); + while let Some(x) = stack.pop() { + if !inside[x] { + inside[x] = true; + stack.extend(cfg.blocks[x].preds.iter().copied()); + } + } + inside + }; + let loops: Vec<(usize, Vec)> = cfg.headers.iter().map(|&h| (h, body(h))).collect(); + let size = |b: &[bool]| b.iter().filter(|&&x| x).count(); + loops + .iter() + .map(|&(h, _)| { + let around = loops.iter().filter(|(g, b)| *g != h && b[h]).min_by_key(|(g, b)| (size(b), pos[*g])).map(|&(g, _)| g); + (h, around) + }) + .collect() +} + #[derive(Clone, Copy)] struct Succs { buf: [usize; 2], @@ -388,6 +421,72 @@ mod tests { assert_eq!(headers2.len(), 1); } + /// A reducible `Cfg` of `blocks` (no instructions), as `Cfg::build` finishes one. + fn cfg_of(mut blocks: Vec) -> Cfg { + let (rpo, headers) = make_reducible(&mut blocks).unwrap(); + for &b in &rpo { + for t in succ_of(&blocks[b]) { + if !blocks[t].preds.contains(&b) { + blocks[t].preds.push(b); + } + } + } + Cfg { insts: Vec::new(), blocks, rpo, headers } + } + + fn parents(blocks: Vec) -> Vec<(usize, Option)> { + loop_parents(&cfg_of(blocks)).into_iter().collect() + } + + use Term::{Cond, End, Jump}; + + #[test] + fn loop_parents_of_one_loop_and_of_loops_one_after_the_other() { + // 0 → 1 → 2 → {1 | 3} + assert_eq!(parents(vec![blk(Jump(1)), blk(Jump(2)), blk(Cond(0, 1, 3)), blk(End)]), [(1, None)]); + // 0 → 1 ⟲, 1 → 2 → 3 ⟲, 3 → 4 + assert_eq!(parents(vec![blk(Jump(1)), blk(Cond(0, 1, 2)), blk(Jump(3)), blk(Cond(0, 3, 4)), blk(End)]), [(1, None), (3, None)]); + } + + #[test] + fn loop_parents_of_loops_inside_one_another() { + // 1 → 2 ⟲, 2 → 3 → {1 | 4} + assert_eq!(parents(vec![blk(Jump(1)), blk(Jump(2)), blk(Cond(0, 2, 3)), blk(Cond(0, 1, 4)), blk(End)]), [(1, None), (2, Some(1))]); + // three deep: 3 ⟲ inside 2 … 4 inside 1 … 5 + let deep = vec![blk(Jump(1)), blk(Jump(2)), blk(Jump(3)), blk(Cond(0, 3, 4)), blk(Cond(0, 2, 5)), blk(Cond(0, 1, 6)), blk(End)]; + assert_eq!(parents(deep), [(1, None), (2, Some(1)), (3, Some(2))]); + } + + /// Both back edges make the loop: each of 3 → 1 and 5 → 1 has an inner loop (2 ⟲, 4 ⟲) only + /// on its own path, so a body of either back edge alone leaves one of them outermost. + #[test] + fn loop_parents_of_a_loop_with_two_back_edges() { + let b = vec![blk(Jump(1)), blk(Cond(0, 2, 4)), blk(Cond(0, 2, 3)), blk(Jump(1)), blk(Cond(0, 4, 5)), blk(Cond(0, 1, 6)), blk(End)]; + assert_eq!(parents(b), [(1, None), (2, Some(1)), (4, Some(1))]); + } + + /// A loop entered in the middle, after `make_reducible` split it (0 → {3 | 1}, 1 → 2's copy, + /// cycle 2 → 3 → {2 | 4}): one loop, at 3. + #[test] + fn loop_parents_of_a_split_loop() { + let b = vec![blk(Cond(0, 3, 1)), blk(Jump(2)), blk(Jump(3)), blk(Cond(0, 2, 4)), blk(End)]; + assert_eq!(parents(b), [(3, None)]); + } + + /// The outer body enters the inner loop 4 from two blocks (2 and 3). + #[test] + fn loop_parents_of_a_loop_entered_from_two_blocks() { + let b = vec![blk(Jump(1)), blk(Cond(0, 2, 3)), blk(Jump(4)), blk(Jump(4)), blk(Cond(0, 4, 5)), blk(Cond(0, 1, 6)), blk(End)]; + assert_eq!(parents(b), [(1, None), (4, Some(1))]); + } + + /// The program's first block is the outer loop's header. + #[test] + fn loop_parents_of_a_loop_at_the_entry() { + let b = vec![blk(Jump(1)), blk(Cond(0, 1, 2)), blk(Cond(0, 0, 3)), blk(End)]; + assert_eq!(parents(b), [(0, None), (1, Some(0))]); + } + #[test] fn acyclic_cfg_skips_dominator_pass_and_matches_rpo_and_preds() { let mut code = Vec::new(); diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 5621972b77..3b9095b3a3 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -14,6 +14,155 @@ fn prog(list: &[(&str, &str, &[(&str, u64)], Option)]) -> Vec { v } +/// One console wave in two hardware halves (33 to 64 threads a group): the halves of a compute +/// or mesh group exchange through the bounded counters, as those of larger groups do, and meet +/// at no group barrier after the one at the program's start. A barrier at every exchange hung NVIDIA +/// GPUs when several such programs ran at once (#1727; the change is #1741's). +#[test] +fn a_single_split_wave_of_a_compute_group_exchanges_without_a_group_barrier() { + use crate::gpu::recomp::CsInterface; + // v1 = lane 32's v0: the lower half needs the upper half's value + let code = prog(&[("V_READLANE_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 256), ("SRC1", 160)], None)]); + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let dis = |threads: u32, code: &[u8]| { + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 }; + super::validate::disassemble(&super::kernel::translate_compute(code, o, &cs).unwrap_or_else(|e| panic!("{threads} threads: {e}")).dxil) + }; + // (barrier mode 9: the thread group's sync with its memory fence, `ops::barrier::GROUP_SYNC`) + let syncs = |d: &str| d.matches("@dx.op.barrier(i32 80, i32 9)").count(); + let Ok(alone) = dis(32, &code) else { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + }; + assert_eq!(syncs(&alone), 1, "the start's barrier: +{alone}"); + assert!(alone.matches("atomicrmw").count() < 3, "a half without a partner does not wait for one: +{alone}"); + for threads in [33, 64, 128] { + let d = dis(threads, &code).unwrap(); + assert_eq!(syncs(&d), 1, "{threads} threads: a group barrier at the exchange: +{d}"); + assert!(d.matches("atomicrmw").count() >= 3, "{threads} threads: the exchange's counters: +{d}"); + } + // the text before the start's barrier, and after it + let at_start = |d: &str| d.split_at(d.find("@dx.op.barrier(i32 80, i32 9)").expect("the start's barrier")).0.to_string(); + // the value (`%N`) the first line of `pre` that `hit` accepts defines + fn def(pre: &str, hit: impl Fn(&str) -> bool) -> Option { + pre.lines().find(|l| hit(l)).and_then(|l| l.trim().split_once(" = ")).map(|(n, _)| n.to_string()) + } + // a zero stored through that address in `pre` + fn zeroed(pre: &str, at: Option) -> bool { + at.is_some_and(|p| pre.contains(&format!("store i32 0, i32 addrspace(3)* {p},"))) + } + // without LDS: slots and counters of their own (one console wave: 4 slot words, 2 counters), + // the counters zeroed before the start's barrier + let d = dis(64, &code).unwrap(); + assert!(d.contains("@xcl_xs = external addrspace(3) global [4 x i32]") && d.contains("@xcl_xc = external addrspace(3) global [2 x i32]"), "the spin storage: +{d}"); + let pre = at_start(&d); + assert!(zeroed(&pre, def(&pre, |l| l.contains("addrspace(3)* @xcl_xc, i32 0, i32 %"))), "the counters zeroed before the start's barrier: +{d}"); + // a mesh program's compute pass of one console wave (48 or 64 threads) exchanges the same way + for threads in [48, 64] { + let ms = crate::gpu::recomp::MsInterface { outputs: vec![], threads, max_vertices: 64, max_primitives: 64 }; + let d = super::validate::disassemble(&super::kernel::translate_mesh(&code, o, &ms).unwrap_or_else(|e| panic!("mesh, {threads} threads: {e}")).dxil).unwrap(); + assert_eq!(syncs(&d), 1, "mesh, {threads} threads: a group barrier at the exchange: +{d}"); + assert!(d.contains("@xcl_xc = external addrspace(3) global [2 x i32]") && d.matches("atomicrmw").count() >= 3, "mesh, {threads} threads: the exchange's counters: +{d}"); + let pre = at_start(&d); + assert!(zeroed(&pre, def(&pre, |l| l.contains("addrspace(3)* @xcl_xc, i32 0, i32 %"))), "mesh, {threads} threads: the counters zeroed before the start's barrier: +{d}"); + } + // with the program's LDS the counters live in its top words (the address a thread's own, + // v0 << 10: a constant one's clamp folds away, `module::opt`) + let with_lds = prog(&[ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 138), ("VSRC1", 0)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 0)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 256), ("SRC1", 160)], None), + ]); + let d = dis(64, &with_lds).unwrap(); + assert_eq!(syncs(&d), 1, "a group barrier at the exchange (LDS): +{d}"); + assert!(d.matches("atomicrmw").count() >= 3, "the exchange's counters (LDS): +{d}"); + // the HLSL layout: the thread counter in the top word (8191), the two counters below it + // (8189, 8190: zeroed before the start's barrier), the 4 slot words below them (from + // 8192 - 4 - 2 - 1 = 8185), and the program's LDS clamped below the slots (8184) + let pre = at_start(&d); + let rest = &d[pre.len()..]; + let index = def(&pre, |l| l.ends_with(", 8189")); + let counter = index.and_then(|i| def(&pre, |l| l.contains("@xcl_lds, i32 0, i32 ") && l.ends_with(&format!(" {i}")))); + assert!(pre.contains("@xcl_lds, i32 0, i32 8191") && zeroed(&pre, counter), "the top word and the counters zeroed before the start's barrier: +{d}"); + assert!(rest.contains(", 8185"), "the slots from word 8185: +{d}"); + assert_eq!(rest.matches(", 8189").count(), 2, "this half's and the partner's counter: +{d}"); + assert!(rest.contains("i32 8184)"), "the program's LDS below the exchange: +{d}"); +} + +/// The split form keeps the console wave's order of LDS accesses (`Lw::lds_in_order`): an LDS +/// read after a write, and a write after a read, meet the other half first (the kernel form's +/// group barrier, a compute group's counters); a read with no write since the last meet does +/// not, and a half without a partner and the native form never do. In a loop the meet is +/// conditional on the bits, and still validates. +#[test] +fn split_lds_reads_meet_after_writes() { + use crate::gpu::recomp::CsInterface; + type Inst<'a> = (&'a str, &'a str, &'a [(&'a str, u64)], Option); + let write: Inst = ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 0)], None); + let read: Inst = ("DS_READ_B32", "ENC_DS", &[("VDST", 2), ("ADDR", 1)], None); + let syncs = |d: &str| d.matches("@dx.op.barrier(i32 80, i32 9)").count(); + let kernel = |list: &[Inst], split: bool| { + let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }; + super::validate::disassemble(&translate(&prog(list), o).unwrap_or_else(|e| panic!("{e}"))) + }; + let Ok(rw) = kernel(&[write, read], true) else { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + }; + let w = syncs(&kernel(&[write], true).unwrap()); + assert_eq!(syncs(&rw), w + 1, "the read meets after the write:\n{rw}"); + assert_eq!(syncs(&kernel(&[write, write], true).unwrap()), w, "a write after a write"); + assert_eq!(syncs(&kernel(&[read, write], true).unwrap()), w + 1, "the write meets after the read"); + assert_eq!(syncs(&kernel(&[write, read, read], true).unwrap()), w + 1, "the second read: the halves met since the write"); + assert_eq!(syncs(&kernel(&[write, read, write], true).unwrap()), w + 2, "a meet before the read and before the second write"); + let native = |list: &[Inst]| syncs(&kernel(list, false).unwrap()); + assert_eq!(native(&[write, read]), native(&[write]), "the native form"); + // a loop: read, write, three times – each waits for the other from the second pass on + let looped = |body: &[Inst]| { + let mut l: Vec = vec![("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 131)], None)]; + l.extend_from_slice(body); + // back to the loop's first instruction: the DS instructions are 2 words each + let back = 0x1_0000 - (2 * body.len() as u64 + 3); + l.extend_from_slice(&[ + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None), + ]); + let mut code = prog(&l); + code.truncate(code.len() - 4); + code.extend(encode("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", back)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + syncs(&super::validate::disassemble(&translate(&code, o).unwrap_or_else(|e| panic!("{e}"))).unwrap()) + }; + assert!(looped(&[read, write]) >= looped(&[read]) + 2, "the loop's read and write meet when the bits are set"); + // compute groups: the counters' meet (two more atomics), none without a partner half + let atomics = |threads: u32, list: &[Inst]| { + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let d = super::validate::disassemble(&super::kernel::translate_compute(&prog(list), o, &cs).unwrap_or_else(|e| panic!("{threads} threads: {e}")).dxil).unwrap(); + d.matches("atomicrmw").count() + }; + for threads in [64, 128] { + assert_eq!(atomics(threads, &[write, read]), atomics(threads, &[write]) + 2, "{threads} threads"); + } + assert_eq!(atomics(32, &[write, read]), atomics(32, &[write]), "32 threads: no partner half"); +} + #[test] fn straight_line_and_loop_kernels_validate() { let code = prog(&[ @@ -223,8 +372,8 @@ fn wave64_graphics_with_upper_lane_reads_refused_in_32_lane_mode() { ] { assert!(e.contains("lanes 32–63"), "{e}"); } - assert!(super::coverage::translate_mode(&vs_upper, &Mode::Vertex(vsi.clone()), split, false).is_err()); - assert!(super::coverage::translate_mode(&ps_upper, &Mode::Pixel(psi.clone()), split, false).is_err()); + assert!(super::coverage::translate_mode(&vs_upper, &Mode::Vertex(vsi.clone()), split, false, &[]).is_err()); + assert!(super::coverage::translate_mode(&ps_upper, &Mode::Pixel(psi.clone()), split, false, &[]).is_err()); super::kernel::translate_vertex(&vs_upper, native, &vsi).expect("native wave64 VS"); super::kernel::translate_pixel(&ps_upper, native, &psi).expect("native wave64 PS"); @@ -374,7 +523,19 @@ fn geometry_mode_validates() { for (name, code, g) in cases { for split in [true, false] { let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }; - super::kernel::translate_geometry(&code, o, &g).unwrap_or_else(|e| panic!("{name} split {split}: {}", &e[..e.len().min(3000)])); + match super::kernel::translate_geometry(&code, o, &g) { + Ok(_) => {} + // a split pass with an ES phase is left to the HLSL path (the safe barrier): + // complete there, and DXC compiles it + Err(e) if e.contains("split wave64 geometry: the ES phase exchanges at group barriers") => { + let t = crate::gpu::recomp::translate_geometry(&code, g.clone(), true, 1).unwrap_or_else(|e| panic!("{name} HLSL: {e}")); + assert!(t.complete(), "{name}: {:?}", t.unsupported_why); + if crate::gpu::recomp::dxc::location().is_ok() { + crate::gpu::recomp::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{name} HLSL: {e}")); + } + } + Err(e) => panic!("{name} split {split}: {}", &e[..e.len().min(3000)]), + } } } } @@ -479,7 +640,7 @@ fn ps_get_lod_with_a_static_sampler() { let k = super::kernel::translate_pixel(&code, ko, &psi).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); assert_eq!(k.static_samplers, vec![(linear, false)], "one static sampler, shared by get_lod and sample"); if crate::gpu::recomp::dxc::location().is_ok() { - super::coverage::translate_mode(&code, &Mode::Pixel(psi), ko, true).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); + super::coverage::translate_mode(&code, &Mode::Pixel(psi), ko, true, &[]).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); } } @@ -658,6 +819,365 @@ fn window_at_lowers_to_32bit_carry_without_int64() { } } +/// A loop that only ends when its counter wraps to 0, then global_store_dword [v0 * 4], the +/// counter (the recompiler tests' `endless_loop_program`). +fn endless_loop() -> Vec { + prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 128)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 10), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 10)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 0)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 4), ("SADDR", 0x7D)], None), + ]) +} + +/// The same loop inside one of three passes (`endless_loop_entered_three_times`). +fn endless_loop_entered_three_times() -> Vec { + prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 128)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 128)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 128)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 10), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 12), ("SSRC1", 10)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 11), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 11), ("SSRC1", 131)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF8)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 12)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 0)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 4), ("SADDR", 0x7D)], None), + ]) +} + +/// The blocks of the emitted `main`: (label, predecessors, text); the entry block is `%0`. +fn main_blocks(dis: &str) -> Vec<(String, Vec, String)> { + let body = dis.split("define void @main()").nth(1).and_then(|s| s.split("\n}\n").next()).expect("main body"); + let mut out = vec![("%0".to_string(), Vec::new(), String::new())]; + for line in body.lines() { + if let Some(rest) = line.strip_prefix(";

= vec![ + ("HLSL wave32", false, |l, cs| super::dxc::compile(&translate(&code_of(l), &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap().hlsl, "main", "cs_6_6", &[]).unwrap()), + ("HLSL split wave64", true, |l, cs| super::dxc::compile(&translate(&code_of(l), &Options { mode: Mode::Compute(cs.clone()), wave64: true, split_wave64: true, ..Default::default() }).unwrap().hlsl, "main", "cs_6_6", &[]).unwrap()), + ("direct wave32", false, |l, cs| translate_compute(&code_of(l), KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, cs).unwrap().dxil), + ("direct split wave64", true, |l, cs| translate_compute(&code_of(l), KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }, cs).unwrap().dxil), + ("per-lane wave32", false, |l, cs| super::lower_dxil::compute_code(&code_of(l), cs, false).unwrap()), + ("per-lane split wave64", true, |l, cs| super::lower_dxil::compute_split(&decode(l), cs).unwrap()), + ]; + if w64 { + forms.push(("HLSL wave64", true, |l, cs| super::dxc::compile(&translate(&code_of(l), &Options { mode: Mode::Compute(cs.clone()), wave64: true, ..Default::default() }).unwrap().hlsl, "main", "cs_6_6", &[]).unwrap())); + forms.push(("direct wave64", true, |l, cs| translate_compute(&code_of(l), KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }, cs).unwrap().dxil)); + forms.push(("per-lane wave64", true, |l, cs| super::lower_dxil::compute_code(&code_of(l), cs, true).unwrap())); + } + let cs = |threads: [u32; 3], y: bool| CsInterface { threads, user_sgprs: 2, tgid: [true, y, false], tg_size: false, tid_components: if y { 2 } else { 1 } }; + let io = |x: u32, y: u32, folded: u32| { + let mut io = vec![0u32; 128]; + (io[IO_THREAD_LIMIT[0]], io[IO_THREAD_LIMIT[1]], io[IO_GROUP_LIMIT]) = (x, y, folded); + io + }; + for (name, wave64, build) in forms { + let lanes = if wave64 { 64 } else { 32 }; + // 64 threads a group, 4 groups: thread indices, then EXEC's count + let index = build(&thread_index_program(6, None, None), &cs([64, 1, 1], false)); + let count = build(&thread_index_program(6, None, Some(wave64)), &cs([64, 1, 1], false)); + for l in [3 * 64 + 40, 3 * 64 + 20, 0] { + let mem = runner::dispatch(&index, [4, 1, 1], &io(l, 0, 0), &[NONE; 256]).unwrap_or_else(|e| panic!("{name}: {e}")); + for (k, &got) in mem.iter().enumerate() { + assert_eq!(got, if l == 0 || (k as u32) < l { k as u32 } else { NONE }, "{name}, limit {l}: thread {k}"); + } + let mem = runner::dispatch(&count, [4, 1, 1], &io(l, 0, 0), &[NONE; 256]).unwrap_or_else(|e| panic!("{name}: {e}")); + for (k, &got) in mem.iter().enumerate() { + let first = k as u32 / lanes * lanes; + let n = if l == 0 { lanes } else { l.saturating_sub(first).min(lanes) }; + assert_eq!(got, if l == 0 || (k as u32) < l { n } else { NONE }, "{name}, limit {l}: thread {k}'s EXEC"); + } + } + // 65 537 console groups of 4 threads folded into 65 535 x 2, the last one ending at its + // fourth thread + let folded = build(&thread_index_program(2, None, None), &cs([4, 1, 1], false)); + let (n, l) = (FOLD_X + 2, 4 * (FOLD_X + 1) + 3); + let mem = runner::dispatch(&folded, [FOLD_X, 2, 1], &io(l, 0, n), &vec![NONE; 4 * 2 * FOLD_X as usize]).unwrap_or_else(|e| panic!("{name}: {e}")); + for (k, &got) in mem.iter().enumerate() { + assert_eq!(got, if (k as u32) < l { k as u32 } else { NONE }, "{name}, folded: thread {k}"); + } + // 2 x 2 groups of 8 x 8, limits in Y and in X and Y + let rows = build(&thread_index_program(3, Some(2), None), &cs([8, 8, 1], true)); + for (lx, ly) in [(0, 13), (11, 13), (0, 0)] { + let mem = runner::dispatch(&rows, [2, 2, 1], &io(lx, ly, 0), &[NONE; 256]).unwrap_or_else(|e| panic!("{name}: {e}")); + for (k, &got) in mem.iter().enumerate() { + let (x, y) = (k as u32 % 16, k as u32 / 16); + let ran = (lx == 0 || x < lx) && (ly == 0 || y < ly); + assert_eq!(got, if ran { k as u32 } else { NONE }, "{name}, limit {lx} x {ly}: thread ({x}, {y})"); + } + } + } +} + +/// v_fract_f32 at the edges, as RDNA computes it (x - floor(x) kept below 1.0): ±inf gives +/// NaN and a NaN stays NaN – a `min()` clamp returned 0.99999994 there on NVIDIA (HLSL min +/// returns its non-NaN operand); a tiny negative value rounds to the largest float below 1. +#[test] +fn gpu_fract_f32_edges() { + if !gpu_ready() { + return; + } + let code = prog(&[("V_FRACT_F32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 1)], None)]); + let inputs = [f32::INFINITY, f32::NEG_INFINITY, f32::NAN, -0.0, 1.5, -0.25, -(2f32.powi(-25)), 7.0]; + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[1] = inputs[l % inputs.len()].to_bits(); + } + let r = runner::run_code(&code, &st, &[]).unwrap(); + for l in 0..64 { + let (x, got) = (inputs[l % inputs.len()], f32::from_bits(r.vgpr[l][2])); + if x.is_infinite() || x.is_nan() { + assert!(got.is_nan(), "lane {l}: fract({x}) = {got}, want NaN"); + } else if x == -(2f32.powi(-25)) { + assert_eq!(r.vgpr[l][2], 0x3F7F_FFFF, "lane {l}: fract({x}) below 1.0"); + } else { + assert_eq!(got.to_bits(), (x - x.floor()).to_bits(), "lane {l}: fract({x})"); + } + } +} + +/// f64 compares with NaN operands, both the ordered ones and the negated ones that are true +/// when unordered, bit for bit against IEEE. +#[test] +fn gpu_f64_compares_with_nan() { + for wave64 in gpu_waves() { + f64_compares_with_nan(wave64); + } +} + +fn f64_compares_with_nan(wave64: bool) { + const OPS: [&str; 8] = ["O", "U", "NEQ", "NLT", "NGE", "EQ", "LT", "LG"]; + let insts: Vec<(String, u64)> = OPS.iter().enumerate().map(|(i, op)| (format!("V_CMP_{op}_F64"), 20 + 2 * i as u64)).collect(); + let fields: Vec<[(&str, u64); 3]> = insts.iter().map(|(_, d)| [("VDST", *d), ("SRC0", V), ("SRC1", V + 2)]).collect(); + let list: Vec<(&str, &str, &[(&str, u64)], Option)> = + insts.iter().zip(&fields).map(|((n, _), f)| (n.as_str(), "ENC_VOP3", &f[..], None)).collect(); + let p = prog(&list); + let nan = f64::from_bits(0x7FF8_0000_0000_1234); + let pairs = [(1.0, 1.0), (nan, 1.0), (2.0, nan), (-0.0, 0.0), (f64::INFINITY, f64::INFINITY), (nan, nan), (1.0, 2.0)]; + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let (a, b): (f64, f64) = pairs[l % pairs.len()]; + (r[0], r[1], r[2], r[3]) = (a.to_bits() as u32, (a.to_bits() >> 32) as u32, b.to_bits() as u32, (b.to_bits() >> 32) as u32); } let (r, lanes) = run_wave(&p, &st, wave64); let mut bad = Vec::new(); @@ -9551,6 +10470,118 @@ fn gpu_safe_s_barrier_multi_warp_and_early_endpgm() { } } +/// `XCL_SAMPLE_BARRIER=` (a title's dumped shaders, `\shaders`, or a part of them; +/// `XCL_DIRECT_DXIL=1` as its runs have it): every compute and mesh program there with +/// `s_barrier` in a thread group of several 32-lane hardware waves is refused by the direct +/// translator for that reason, and translates completely on the HLSL path with 16 memory windows +/// from the descriptor heap in the split form, which DXC compiles. The direct translator leaves +/// those programs to the HLSL path's bounded barrier (`dxil::lower`'s s_barrier): one the HLSL +/// path could not translate would lose its draws or dispatches altogether. +#[test] +#[ignore] +fn programs_left_to_the_hlsl_path_for_their_barrier_translate_and_compile() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Mutex; + let Some(dir) = std::env::var_os("XCL_SAMPLE_BARRIER") else { return }; + let mut files: Vec = Vec::new(); + let mut todo = vec![std::path::PathBuf::from(dir)]; + while let Some(d) = todo.pop() { + for e in std::fs::read_dir(&d).unwrap().flatten() { + let p = e.path(); + if p.is_dir() { + todo.push(p); + } else if p.extension().is_some_and(|x| x == "bin") && !p.to_string_lossy().contains(".fssm") { + files.push(p); + } + } + } + files.sort(); + const REFUSAL: &str = "s_barrier in a group of several hardware waves"; + let windows = super::HEAP_WINDOWS | 16; + let next = AtomicUsize::new(0); + // programs with the barrier in a group of several waves, of them refused by the direct + // translator for it, complete on the HLSL path, compiled by DXC + let (n, refused, complete, compiled) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); + let failures: Mutex> = Mutex::new(Vec::new()); + std::thread::scope(|s| { + for _ in 0..super::dxc::compile_threads() { + s.spawn(|| loop { + let Some(path) = files.get(next.fetch_add(1, Ordering::Relaxed)) else { break }; + let blob = std::fs::read(path).unwrap(); + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + let Some(sh) = crate::gpu::xbox::parse(&blob) else { continue }; + for f in &sh.fssm { + let Some(mode) = super::interface(&blob, &sh, f) else { continue }; + let threads = match &mode { + Mode::Compute(cs) => cs.threads.iter().product::(), + Mode::Mesh(ms) => ms.threads, + _ => continue, + }; + let Some(p) = f.programs.first() else { continue }; + let code = &f.data[p.offset..p.offset + p.len]; + let has_barrier = { + let mut off = 0; + let mut found = false; + while off + 4 <= code.len() { + let Ok(d) = crate::gpu::rdna2::decode(&code[off..], off as u64) else { break }; + found |= d.inst.name == "S_BARRIER"; + off += d.len; + } + found + }; + if !has_barrier || threads <= 32 { + continue; + } + n.fetch_add(1, Ordering::Relaxed); + let wave64 = super::fssm_wave64(f, code); + let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64, mem_windows: windows, sampler_base: 0 }; + let direct = match &mode { + Mode::Compute(cs) => crate::gpu::dxil::kernel::translate_compute(code, o, cs).map(|_| ()), + Mode::Mesh(ms) => crate::gpu::dxil::kernel::translate_mesh(code, o, ms).map(|_| ()), + _ => unreachable!(), + }; + match direct { + Err(e) if e.contains(REFUSAL) => { + refused.fetch_add(1, Ordering::Relaxed); + } + Err(e) => failures.lock().unwrap().push(format!("{name}: the direct translator fails otherwise: {}", e.lines().next().unwrap_or(""))), + Ok(()) => failures.lock().unwrap().push(format!("{name}: the direct translator took it ({threads} threads)")), + } + let opt = Options { mode: mode.clone(), wave64, split_wave64: true, mem_windows: windows, ..Default::default() }; + let t = match translate(code, &opt) { + Ok(t) => t, + Err(e) => { + failures.lock().unwrap().push(format!("{name}: HLSL path: {e}")); + continue; + } + }; + if !t.complete() { + failures.lock().unwrap().push(format!("{name}: HLSL path incomplete: {:?} {:?}", t.unsupported, t.unsupported_why)); + continue; + } + complete.fetch_add(1, Ordering::Relaxed); + if !t.hlsl.contains("xcl_s_barrier();") { + failures.lock().unwrap().push(format!("{name}: the HLSL has no bounded barrier")); + } + match super::dxc::compile_cached(&t.hlsl, "main", "cs_6_6") { + Ok(_) => { + compiled.fetch_add(1, Ordering::Relaxed); + } + Err(e) => failures.lock().unwrap().push(format!("{name}: DXC: {}", e.lines().find(|l| l.contains("error")).unwrap_or(e.lines().next().unwrap_or("")))), + } + } + }); + } + }); + let (n, refused, complete, compiled) = (n.into_inner(), refused.into_inner(), complete.into_inner(), compiled.into_inner()); + let failures = failures.into_inner().unwrap(); + println!("barrier programs in groups of several waves: {n}; refused by the direct translator for the barrier: {refused}; complete on the HLSL path: {complete}; compiled: {compiled}"); + for f in failures.iter().take(40) { + println!(" {f}"); + } + assert!(failures.is_empty(), "{} of {n} programs", failures.len()); +} + #[test] fn qsad_and_mqsad_operand_forms_and_validation() { let vop3 = |name: &str, f: &[(&str, u64)]| encode(name, "ENC_VOP3", f, None).unwrap(); @@ -9914,6 +10945,151 @@ fn jumps_to_outer_loop_heads_are_structured() { assert!(structured >= 100 && entered > 20, "{structured} structured, {entered} jumps into loops"); } +/// Compute shaders only declare `globallycoherent` on their flat memory windows (`mem`, `mem1`… +/// and `XCL_HEAP_WINDOWS` heap views) when the program uses cross-workgroup coherence: memory +/// atomics, `GLC`/`DLC`/`SLC` memory ops, or cache invalidations. Both the HLSL and direct DXIL +/// backends follow the same predicate. +#[test] +fn compute_globallycoherent_only_when_needed() { + let cs = super::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let enc = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + let prog = |insts: &[(&str, &str, &[(&str, u64)])]| { + let mut c = Vec::new(); + for &(n, e, f) in insts { + c.extend(enc(n, e, f)); + } + c.extend(enc("S_ENDPGM", "ENC_SOPP", &[])); + c + }; + + // Plain compute: SMEM + MUBUF load/store + LDS + s_barrier, no GLC/DLC/SLC/atomics/inv. + let plain = prog(&[ + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125)]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("SADDR", 0)]), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)]), + ("S_BARRIER", "ENC_SOPP", &[]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 1), ("SADDR", 0)]), + ]); + + let coherent_cases: Vec<(&str, Vec)> = vec![ + ("smem glc", prog(&[("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125), ("GLC", 1)])])), + ("smem dlc", prog(&[("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125), ("DLC", 1)])])), + ("mubuf glc", prog(&[("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("GLC", 1)])])), + ("global dlc", prog(&[("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("SADDR", 0), ("DLC", 1)])])), + ("mubuf slc", prog(&[("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("SLC", 1)])])), + ("buffer_atomic", prog(&[("BUFFER_ATOMIC_ADD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128)])])), + ("global_atomic", prog(&[("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("DATA", 2), ("SADDR", 0)])])), + ("flat_atomic", prog(&[("FLAT_ATOMIC_ADD", "ENC_FLAT", &[("VDST", 1), ("ADDR", 2), ("DATA", 4)])])), + ("s_dcache_inv", prog(&[("S_DCACHE_INV", "ENC_SMEM", &[])])), + ("s_gl1_inv", prog(&[("S_GL1_INV", "ENC_SMEM", &[])])), + ("buffer_gl0_inv", prog(&[("BUFFER_GL0_INV", "ENC_MUBUF", &[])])), + ("buffer_gl1_inv", prog(&[("BUFFER_GL1_INV", "ENC_MUBUF", &[])])), + ]; + + for (windows, heap) in [(1u32, false), (2, false), (2, true)] { + let opt = Options { mode: Mode::Compute(cs.clone()), wave64: false, mem_windows: windows, heap_windows: heap, ..Default::default() }; + let t = translate(&plain, &opt).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + assert!(!t.hlsl.contains("globallycoherent"), "plain CS (windows={windows}, heap={heap}) must not emit globallycoherent:\n{}", t.hlsl); + + for (label, code) in &coherent_cases { + let t = translate(code, &opt).unwrap(); + assert!(t.complete(), "{label}: {:?}", t.unsupported_why); + assert!(t.hlsl.contains("globallycoherent"), "{label} (windows={windows}, heap={heap}) must emit globallycoherent"); + if heap { + assert!(t.hlsl.contains("#define XCL_MW globallycoherent RWByteAddressBuffer"), "{label}: heap window accessor must be globallycoherent"); + } + } + } + + // Kernel mode stays non-coherent even with atomics. + let k = translate(&coherent_cases[6].1, &Options { mode: Mode::Kernel, wave64: false, ..Default::default() }).unwrap(); + assert!(!k.hlsl.contains("globallycoherent"), "kernel mode must not emit globallycoherent"); + + // Direct DXIL backend: check the IsGloballyCoherent bit (0x4000) in annotateHandle properties + // (RAW_BUFFER=11 | IsUAV=0x1000 = 4107 vs RAW_BUFFER=11 | IsUAV=0x1000 | IsGloballyCoherent=0x4000 = 20491). + // (the plain program in a group of one 32-lane wave: its s_barrier in a group of several + // hardware waves is left to the HLSL path) + let one_wave = super::CsInterface { threads: [32, 1, 1], ..cs.clone() }; + for mw in [1u32, super::HEAP_WINDOWS | 2] { + let o = crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: mw, sampler_base: 0 }; + let plain_k = crate::gpu::dxil::kernel::translate_compute(&plain, o, &one_wave).unwrap(); + let coh_k = crate::gpu::dxil::kernel::translate_compute(&coherent_cases[6].1, o, &cs).unwrap(); + if super::dxc::location().is_ok() { + let plain_dis = crate::gpu::dxil::validate::disassemble(&plain_k.dxil).unwrap(); + let coh_dis = crate::gpu::dxil::validate::disassemble(&coh_k.dxil).unwrap(); + assert!(!plain_dis.contains("i32 20491"), "direct DXIL plain CS (mw={mw:#x}) must not set IsGloballyCoherent:\n{plain_dis}"); + assert!(coh_dis.contains("i32 20491"), "direct DXIL atomic CS (mw={mw:#x}) must set IsGloballyCoherent:\n{coh_dis}"); + } + } +} + +/// Real GPU check of both non-coherent (cached) and coherent (cross-workgroup atomic + GLC) +/// compute shaders across HLSL and direct DXIL. +#[test] +fn gpu_compute_coherent_and_cached_loads() { + if !gpu_ready() { + return; + } + let cs = super::CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let enc = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + + // 1. Plain cached compute: each thread reads a uniform dword via SMEM (s[0:1] = 0x100) and + // writes (val + group_id * 32 + tid) to mem[0x200 + (group_id * 32 + tid) * 4]. + let mut plain = Vec::new(); + plain.extend(enc("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125)])); + plain.extend(enc("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 133)])); // s3 = tgid * 32 + plain.extend(enc("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 3), ("VSRC1", 0)])); // v1 = tgid * 32 + v0 + plain.extend(enc("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 1)])); // v2 = mem[0x100] + idx + plain.extend(enc("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 1)])); // v3 = idx * 4 + plain.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 128)])); + plain.extend(enc("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 2), ("SADDR", 0x7D), ("OFFSET", 0x200)])); + plain.extend(enc("S_ENDPGM", "ENC_SOPP", &[])); + + let t_plain = translate(&plain, &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap(); + assert!(t_plain.complete(), "{:?}", t_plain.unsupported_why); + assert!(!t_plain.hlsl.contains("globallycoherent")); + let dxil_plain_hlsl = super::dxc::compile(&t_plain.hlsl, "main", "cs_6_6", &[]).unwrap(); + let dxil_plain_direct = crate::gpu::dxil::kernel::translate_compute(&plain, crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, &cs).unwrap().dxil; + + let mut io = vec![0u32; super::KERNEL_SGPRS]; + io[0] = 0x100; + let mut mem = vec![0u32; 0x400 / 4]; + mem[0x100 / 4] = 0x1234_0000; + for (tag, dxil) in [("hlsl", &dxil_plain_hlsl), ("direct", &dxil_plain_direct)] { + let out = runner::dispatch(dxil, [4, 1, 1], &io, &mem).unwrap(); + for idx in 0..128usize { + assert_eq!(out[(0x200 + idx * 4) / 4], 0x1234_0000 + idx as u32, "{tag} plain cached idx={idx}"); + } + } + + // 2. Cross-workgroup coherent compute: 16 groups of 32 threads atomically increment a shared + // counter at mem[0x100] and record their returned ticket at mem[0x200 + ticket * 4]. + let mut coh = Vec::new(); + coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)])); // v1 = 0 + coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)])); // v2 = 1 + coh.extend(enc("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 3), ("ADDR", 1), ("DATA", 2), ("SADDR", 0), ("GLC", 1)])); + coh.extend(enc("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 130), ("VSRC1", 3)])); // v4 = ticket * 4 + coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 128)])); + coh.extend(enc("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 3), ("SADDR", 0x7D), ("OFFSET", 0x200), ("GLC", 1)])); + coh.extend(enc("S_ENDPGM", "ENC_SOPP", &[])); + + let t_coh = translate(&coh, &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap(); + assert!(t_coh.complete(), "{:?}", t_coh.unsupported_why); + assert!(t_coh.hlsl.contains("globallycoherent")); + let dxil_coh_hlsl = super::dxc::compile(&t_coh.hlsl, "main", "cs_6_6", &[]).unwrap(); + let dxil_coh_direct = crate::gpu::dxil::kernel::translate_compute(&coh, crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, &cs).unwrap().dxil; + + let mem2 = vec![0u32; (0x200 + 512 * 4) / 4]; + for (tag, dxil) in [("hlsl", &dxil_coh_hlsl), ("direct", &dxil_coh_direct)] { + let out = runner::dispatch(dxil, [16, 1, 1], &io, &mem2).unwrap(); + assert_eq!(out[0x100 / 4], 512, "{tag} coherent cross-group counter"); + for ticket in 0..512usize { + assert_eq!(out[(0x200 + ticket * 4) / 4], ticket as u32, "{tag} coherent ticket={ticket}"); + } + } +} + #[test] fn gpu_bvh_triangle_types_2_and_3() { if !gpu_ready() { @@ -10409,151 +11585,6 @@ fn gpu_ps_mask_loop_on_a_primitive_edge_ends() { assert!(bad.is_empty(), "{} pixels wrong (passes, steps, 1, lane count), first {:?}", bad.len(), &bad[..bad.len().min(8)]); } -/// Compute shaders only declare `globallycoherent` on their flat memory windows (`mem`, `mem1`… -/// and `XCL_HEAP_WINDOWS` heap views) when the program uses cross-workgroup coherence: memory -/// atomics, `GLC`/`DLC`/`SLC` memory ops, or cache invalidations. Both the HLSL and direct DXIL -/// backends follow the same predicate. -#[test] -fn compute_globallycoherent_only_when_needed() { - let cs = super::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; - let enc = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); - let prog = |insts: &[(&str, &str, &[(&str, u64)])]| { - let mut c = Vec::new(); - for &(n, e, f) in insts { - c.extend(enc(n, e, f)); - } - c.extend(enc("S_ENDPGM", "ENC_SOPP", &[])); - c - }; - - // Plain compute: SMEM + MUBUF load/store + LDS + s_barrier, no GLC/DLC/SLC/atomics/inv. - let plain = prog(&[ - ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125)]), - ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("SADDR", 0)]), - ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)]), - ("S_BARRIER", "ENC_SOPP", &[]), - ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 1), ("SADDR", 0)]), - ]); - - let coherent_cases: Vec<(&str, Vec)> = vec![ - ("smem glc", prog(&[("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125), ("GLC", 1)])])), - ("smem dlc", prog(&[("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125), ("DLC", 1)])])), - ("mubuf glc", prog(&[("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("GLC", 1)])])), - ("global dlc", prog(&[("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("SADDR", 0), ("DLC", 1)])])), - ("mubuf slc", prog(&[("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("SLC", 1)])])), - ("buffer_atomic", prog(&[("BUFFER_ATOMIC_ADD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128)])])), - ("global_atomic", prog(&[("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("DATA", 2), ("SADDR", 0)])])), - ("flat_atomic", prog(&[("FLAT_ATOMIC_ADD", "ENC_FLAT", &[("VDST", 1), ("ADDR", 2), ("DATA", 4)])])), - ("s_dcache_inv", prog(&[("S_DCACHE_INV", "ENC_SMEM", &[])])), - ("s_gl1_inv", prog(&[("S_GL1_INV", "ENC_SMEM", &[])])), - ("buffer_gl0_inv", prog(&[("BUFFER_GL0_INV", "ENC_MUBUF", &[])])), - ("buffer_gl1_inv", prog(&[("BUFFER_GL1_INV", "ENC_MUBUF", &[])])), - ]; - - for (windows, heap) in [(1u32, false), (2, false), (2, true)] { - let opt = Options { mode: Mode::Compute(cs.clone()), wave64: false, mem_windows: windows, heap_windows: heap, ..Default::default() }; - let t = translate(&plain, &opt).unwrap(); - assert!(t.complete(), "{:?}", t.unsupported_why); - assert!(!t.hlsl.contains("globallycoherent"), "plain CS (windows={windows}, heap={heap}) must not emit globallycoherent:\n{}", t.hlsl); - - for (label, code) in &coherent_cases { - let t = translate(code, &opt).unwrap(); - assert!(t.complete(), "{label}: {:?}", t.unsupported_why); - assert!(t.hlsl.contains("globallycoherent"), "{label} (windows={windows}, heap={heap}) must emit globallycoherent"); - if heap { - assert!(t.hlsl.contains("#define XCL_MW globallycoherent RWByteAddressBuffer"), "{label}: heap window accessor must be globallycoherent"); - } - } - } - - // Kernel mode stays non-coherent even with atomics. - let k = translate(&coherent_cases[6].1, &Options { mode: Mode::Kernel, wave64: false, ..Default::default() }).unwrap(); - assert!(!k.hlsl.contains("globallycoherent"), "kernel mode must not emit globallycoherent"); - - // Direct DXIL backend: check the IsGloballyCoherent bit (0x4000) in annotateHandle properties - // (RAW_BUFFER=11 | IsUAV=0x1000 = 4107 vs RAW_BUFFER=11 | IsUAV=0x1000 | IsGloballyCoherent=0x4000 = 20491). - // (the plain program in a group of one 32-lane wave: its s_barrier in a group of several - // hardware waves is left to the HLSL path) - let one_wave = super::CsInterface { threads: [32, 1, 1], ..cs.clone() }; - for mw in [1u32, super::HEAP_WINDOWS | 2] { - let o = crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: mw, sampler_base: 0 }; - let plain_k = crate::gpu::dxil::kernel::translate_compute(&plain, o, &one_wave).unwrap(); - let coh_k = crate::gpu::dxil::kernel::translate_compute(&coherent_cases[6].1, o, &cs).unwrap(); - if super::dxc::location().is_ok() { - let plain_dis = crate::gpu::dxil::validate::disassemble(&plain_k.dxil).unwrap(); - let coh_dis = crate::gpu::dxil::validate::disassemble(&coh_k.dxil).unwrap(); - assert!(!plain_dis.contains("i32 20491"), "direct DXIL plain CS (mw={mw:#x}) must not set IsGloballyCoherent:\n{plain_dis}"); - assert!(coh_dis.contains("i32 20491"), "direct DXIL atomic CS (mw={mw:#x}) must set IsGloballyCoherent:\n{coh_dis}"); - } - } -} - -/// Real GPU check of both non-coherent (cached) and coherent (cross-workgroup atomic + GLC) -/// compute shaders across HLSL and direct DXIL. -#[test] -fn gpu_compute_coherent_and_cached_loads() { - if !gpu_ready() { - return; - } - let cs = super::CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; - let enc = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); - - // 1. Plain cached compute: each thread reads a uniform dword via SMEM (s[0:1] = 0x100) and - // writes (val + group_id * 32 + tid) to mem[0x200 + (group_id * 32 + tid) * 4]. - let mut plain = Vec::new(); - plain.extend(enc("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125)])); - plain.extend(enc("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 133)])); // s3 = tgid * 32 - plain.extend(enc("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 3), ("VSRC1", 0)])); // v1 = tgid * 32 + v0 - plain.extend(enc("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 1)])); // v2 = mem[0x100] + idx - plain.extend(enc("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 1)])); // v3 = idx * 4 - plain.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 128)])); - plain.extend(enc("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 2), ("SADDR", 0x7D), ("OFFSET", 0x200)])); - plain.extend(enc("S_ENDPGM", "ENC_SOPP", &[])); - - let t_plain = translate(&plain, &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap(); - assert!(t_plain.complete(), "{:?}", t_plain.unsupported_why); - assert!(!t_plain.hlsl.contains("globallycoherent")); - let dxil_plain_hlsl = super::dxc::compile(&t_plain.hlsl, "main", "cs_6_6", &[]).unwrap(); - let dxil_plain_direct = crate::gpu::dxil::kernel::translate_compute(&plain, crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, &cs).unwrap().dxil; - - let mut io = vec![0u32; super::KERNEL_SGPRS]; - io[0] = 0x100; - let mut mem = vec![0u32; 0x400 / 4]; - mem[0x100 / 4] = 0x1234_0000; - for (tag, dxil) in [("hlsl", &dxil_plain_hlsl), ("direct", &dxil_plain_direct)] { - let out = runner::dispatch(dxil, [4, 1, 1], &io, &mem).unwrap(); - for idx in 0..128usize { - assert_eq!(out[(0x200 + idx * 4) / 4], 0x1234_0000 + idx as u32, "{tag} plain cached idx={idx}"); - } - } - - // 2. Cross-workgroup coherent compute: 16 groups of 32 threads atomically increment a shared - // counter at mem[0x100] and record their returned ticket at mem[0x200 + ticket * 4]. - let mut coh = Vec::new(); - coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)])); // v1 = 0 - coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)])); // v2 = 1 - coh.extend(enc("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 3), ("ADDR", 1), ("DATA", 2), ("SADDR", 0), ("GLC", 1)])); - coh.extend(enc("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 130), ("VSRC1", 3)])); // v4 = ticket * 4 - coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 128)])); - coh.extend(enc("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 3), ("SADDR", 0x7D), ("OFFSET", 0x200), ("GLC", 1)])); - coh.extend(enc("S_ENDPGM", "ENC_SOPP", &[])); - - let t_coh = translate(&coh, &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap(); - assert!(t_coh.complete(), "{:?}", t_coh.unsupported_why); - assert!(t_coh.hlsl.contains("globallycoherent")); - let dxil_coh_hlsl = super::dxc::compile(&t_coh.hlsl, "main", "cs_6_6", &[]).unwrap(); - let dxil_coh_direct = crate::gpu::dxil::kernel::translate_compute(&coh, crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, &cs).unwrap().dxil; - - let mem2 = vec![0u32; (0x200 + 512 * 4) / 4]; - for (tag, dxil) in [("hlsl", &dxil_coh_hlsl), ("direct", &dxil_coh_direct)] { - let out = runner::dispatch(dxil, [16, 1, 1], &io, &mem2).unwrap(); - assert_eq!(out[0x100 / 4], 512, "{tag} coherent cross-group counter"); - for ticket in 0..512usize { - assert_eq!(out[(0x200 + ticket * 4) / 4], ticket as u32, "{tag} coherent ticket={ticket}"); - } - } -} - #[test] fn gpu_v_dot8_u32_u4_edge_cases() { const CASES: [(u32, u32, u32); 16] = [ diff --git a/crates/xcl/src/gpu/shader.rs b/crates/xcl/src/gpu/shader.rs index 8cf87f4276..006ced121d 100644 --- a/crates/xcl/src/gpu/shader.rs +++ b/crates/xcl/src/gpu/shader.rs @@ -215,8 +215,8 @@ pub fn readable(p: usize, len: usize) -> bool { if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(p, len)) { return true; } - if resident_and_readable(p, end) { - return true; + if let Some(answer) = pages_readable(p, end) { + return answer; } let mut cur = p; while cur < end { @@ -230,36 +230,59 @@ pub fn readable(p: usize, len: usize) -> bool { true } -/// Whether each page of `[p, end)` (up to 16 pages) is in the working set with a readable -/// protection, asked of the kernel for all the pages in one call that touches none of them. -/// `readable` asks this first because `VirtualQuery` sizes the whole region around an address by -/// walking it: in a title's 2 GB block of committed memory that took 20–25 ms a call, and a retail game's -/// streaming thread, which has the page arrays of its DirectStorage requests checked, spent most -/// of the world load there. `false` for a page that is not resident (never touched, paged out, -/// guard, reserved, no access): the `VirtualQuery` walk answers for those. -fn resident_and_readable(p: usize, end: usize) -> bool { +/// Whether each page of `[p, end)` is readable, asked of the working set – the kernel answers for +/// up to 512 pages in one call that touches none of them. `readable` asks this first because +/// `VirtualQuery` sizes the whole region around an address by walking it: in a title's 2 GB block +/// of committed memory that took 20–30 ms a call. A retail game's streaming thread, which has +/// the page arrays of its DirectStorage requests checked, spent most of the world load there; +/// so did the submits, which check each texture of more than 64 KiB that was written (30–50 ms +/// of a frame). +/// +/// None: ask `VirtualQuery` – the working set cannot be asked, or a range of up to 16 pages (a +/// title's pointer that may be garbage) has a page that is not resident (never touched, paged +/// out, guard, reserved, no access). In a longer range such a page is read by the kernel (a +/// byte of it): a committed one is then resident, as the caller's reads would make it, any other +/// is not readable. +fn pages_readable(p: usize, end: usize) -> Option { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Memory::{PAGE_GUARD, PAGE_NOACCESS}; use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; - const MAX_PAGES: usize = 16; - let first = p >> 12; - let pages = ((end - 1) >> 12) - first + 1; - if pages > MAX_PAGES { - return false; - } - let mut ws: [PSAPI_WORKING_SET_EX_INFORMATION; MAX_PAGES] = unsafe { std::mem::zeroed() }; - for (k, e) in ws[..pages].iter_mut().enumerate() { - e.VirtualAddress = ((first + k) << 12) as *mut std::ffi::c_void; - } - let size = (pages * std::mem::size_of::()) as u32; - if unsafe { K32QueryWorkingSetEx(windows_sys::Win32::System::Threading::GetCurrentProcess(), ws.as_mut_ptr() as *mut std::ffi::c_void, size) } == 0 { - return false; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + const SMALL: usize = 16; + const BATCH: usize = 512; + let (first, last) = (p >> 12, (end - 1) >> 12); + let small = last - first < SMALL; + let mut ws: [PSAPI_WORKING_SET_EX_INFORMATION; BATCH] = unsafe { std::mem::zeroed() }; + let mut at = first; + while at <= last { + let n = (last - at + 1).min(BATCH); + for (k, e) in ws[..n].iter_mut().enumerate() { + e.VirtualAddress = ((at + k) << 12) as *mut std::ffi::c_void; + e.VirtualAttributes.Flags = 0; + } + let size = (n * std::mem::size_of::()) as u32; + if unsafe { K32QueryWorkingSetEx(GetCurrentProcess(), ws.as_mut_ptr() as *mut std::ffi::c_void, size) } == 0 { + return None; + } + for e in &ws[..n] { + // PSAPI_WORKING_SET_EX_BLOCK: bit 0 Valid, bits 4-14 Win32Protection + let flags = unsafe { e.VirtualAttributes.Flags }; + let protect = ((flags >> 4) & 0x7FF) as u32; + if flags & 1 != 0 && protect != 0 && protect & (PAGE_NOACCESS | PAGE_GUARD) == 0 { + continue; + } + if small { + return None; + } + let (mut byte, mut got) = (0u8, 0usize); + let ok = unsafe { ReadProcessMemory(GetCurrentProcess(), e.VirtualAddress as *const std::ffi::c_void, &mut byte as *mut u8 as *mut std::ffi::c_void, 1, &mut got) }; + if ok == 0 || got != 1 { + return Some(false); + } + } + at += n; } - // PSAPI_WORKING_SET_EX_BLOCK: bit 0 Valid, bits 4-14 Win32Protection - ws[..pages].iter().all(|e| { - let flags = unsafe { e.VirtualAttributes.Flags }; - let protect = ((flags >> 4) & 0x7FF) as u32; - flags & 1 != 0 && protect != 0 && protect & (PAGE_NOACCESS | PAGE_GUARD) == 0 - }) + Some(true) } /// Record a shader blob submitted by the title. Safe on garbage pointers. @@ -290,7 +313,7 @@ pub fn capture(stage: &str, ptr: usize, len: usize) { *st.stats.unknown_parts.entry(p.fourcc.clone()).or_default() += 1; } drop(g); - if !dumps_enabled() { + if !dumps_enabled(stage, h) { let names: Vec<&str> = parts.iter().map(|p| p.fourcc.as_str()).collect(); crate::xlog_info!("[SHADER] {stage} {h:016x}: {} B, format {}, parts [{}]", blob.len(), kind.label(), names.join(",")); if kind == Kind::XboxNative { @@ -320,9 +343,21 @@ pub fn capture(stage: &str, ptr: usize, len: usize) { /// more for that: the report's `recomp_*` counts come from it). Off by default: a retail game's /// ~17 000 dumps took 4.8 GB, and translating each again took its loading threads ~0.1 s a /// program at every start. -fn dumps_enabled() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_DUMP_SHADERS").is_ok_and(|v| v == "1")) +/// `XCL_DUMP_SHADERS=ps,0123456789abcdef`: only the shaders of those stages (as the log names +/// them: `vs`, `ps`, `cs` …) and the ones with those dump hashes (16 hex digits). +fn dumps_enabled(stage: &str, h: u64) -> bool { + static WANTED: std::sync::OnceLock> = std::sync::OnceLock::new(); + dump_wanted(WANTED.get_or_init(|| dump_list(&std::env::var("XCL_DUMP_SHADERS").unwrap_or_default())), stage, h) +} + +/// The items of an `XCL_DUMP_SHADERS` value. +fn dump_list(v: &str) -> Vec { + v.split(',').map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()).collect() +} + +/// Whether a list of `XCL_DUMP_SHADERS` items asks for the shader of `stage` with dump hash `h`. +fn dump_wanted(list: &[String], stage: &str, h: u64) -> bool { + list.iter().any(|s| s == "1" || s.eq_ignore_ascii_case(stage) || (s.len() == 16 && u64::from_str_radix(s, 16) == Ok(h))) } /// Console container without dumps: its FSSM variants and instructions accounted. @@ -432,6 +467,38 @@ pub fn stats() -> ShaderStats { #[cfg(test)] mod tests { + /// Ranges of any size are answered page by page: committed pages (touched or not) are + /// readable, a reserved or no-access page anywhere in the range is not. + #[test] + fn readable_answers_for_long_ranges_page_by_page() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, VirtualProtect, MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + const PAGES: usize = 1200; + unsafe { + // (reserved pages of its own behind the committed ones) + let base = VirtualAlloc(std::ptr::null(), (PAGES + 16) << 12, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + assert!(!VirtualAlloc(base as *const _, PAGES << 12, MEM_COMMIT, PAGE_READWRITE).is_null()); + assert!(super::readable(base, PAGES << 12), "committed, none touched"); + for k in (0..PAGES).step_by(3) { + *((base + (k << 12)) as *mut u8) = 1; + } + assert!(super::readable(base, PAGES << 12), "committed, some touched"); + assert!(super::readable(base + 100, (PAGES << 12) - 100), "not from a page's start"); + assert!(!super::readable(base, (PAGES << 12) + 1), "past the end"); + let hole = base + (700 << 12); + VirtualFree(hole as *mut _, 1 << 12, MEM_DECOMMIT); + assert!(!super::readable(base, PAGES << 12), "a reserved page inside"); + assert!(super::readable(base, 700 << 12), "up to the hole"); + assert!(super::readable(hole + (1 << 12), 499 << 12), "behind the hole"); + assert!(!super::readable(hole, 16), "the hole itself"); + let mut old = 0; + assert_ne!(VirtualProtect((base + (40 << 12)) as *const _, 1 << 12, PAGE_NOACCESS, &mut old), 0); + assert!(!super::readable(base, 100 << 12), "a no-access page inside"); + assert!(super::readable(base, 40 << 12)); + VirtualFree(base as *mut _, 0, MEM_RELEASE); + } + } + use super::*; fn container(parts: &[(&[u8; 4], &[u8])]) -> Vec { @@ -481,6 +548,23 @@ mod tests { assert!(l.contains("FSSM #0 [PS]") && l.contains("v_add_f32"), "{l}"); } + /// `XCL_DUMP_SHADERS`: `1` is every shader, a stage name that stage, 16 hex digits one + /// shader – and a hash is not taken for a stage, nor "1" for a hash. + #[test] + fn a_dump_list_names_stages_and_hashes() { + let h = 0x0942_b913_6a89_143du64; + assert!(dump_wanted(&dump_list("1"), "cs", h)); + assert!(!dump_wanted(&dump_list(""), "ps", h)); + assert!(!dump_wanted(&dump_list("0"), "ps", 0)); + let ps = dump_list(" PS , 0942b9136a89143d "); + assert!(dump_wanted(&ps, "ps", 7), "a stage"); + assert!(dump_wanted(&ps, "vs", h), "a hash, whatever its stage"); + assert!(!dump_wanted(&ps, "vs", h + 1)); + assert!(!dump_wanted(&dump_list("0000000000000001"), "vs", 7)); + assert!(dump_wanted(&dump_list("0000000000000001"), "vs", 1)); + assert!(!dump_wanted(&dump_list("1x"), "vs", 1), "not every shader"); + } + #[test] fn readable_rejects_garbage() { assert!(!readable(0, 10)); @@ -503,14 +587,15 @@ mod tests { std::ptr::write_volatile(page(0) as *mut u8, 1); std::ptr::write_volatile(page(1) as *mut u8, 1); // written pages: answered from the working set - assert!(resident_and_readable(page(0), page(2))); + assert_eq!(pages_readable(page(0), page(2)), Some(true)); assert!(readable(page(0), 2 << 12)); assert!(readable(page(0) + 100, 8)); // untouched pages: the region walk answers, and they stay untouched - assert!(!resident_and_readable(page(5), page(5) + 8)); + assert_eq!(pages_readable(page(5), page(5) + 8), None); assert!(readable(page(5), 8)); assert!(readable(page(6), 1 << 12)); - assert!(!resident_and_readable(page(5), page(7))); + assert_eq!(pages_readable(page(5), page(7)), None); + assert_eq!(pages_readable(page(3), page(3) + 8), None, "a guard page is not touched to answer"); assert!(!readable(page(2), 8)); assert!(!readable(page(3), 8)); assert!(!readable(page(4), 8)); @@ -524,9 +609,9 @@ mod tests { assert!(!readable(page(0), 20 << 12)); VirtualFree(base as *mut _, 0, MEM_RELEASE); } - // more pages than one working-set query takes: the region walk + // a range of many pages: the working set too let v = vec![1u8; 32 << 12]; - assert!(!resident_and_readable(v.as_ptr() as usize, v.as_ptr() as usize + v.len())); + assert_eq!(pages_readable(v.as_ptr() as usize, v.as_ptr() as usize + v.len()), Some(true)); assert!(readable(v.as_ptr() as usize, v.len())); } } diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index 62f7e11bca..0371295e6e 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -1008,226 +1008,6 @@ mod tests { } } - /// Batches through one queue share its upload buffer (`Uploader`): two batches of three - /// textures (mips, an odd size, BC7) each read back what was uploaded, and the second batch - /// made no new upload buffer. - #[test] - fn gpu_upload_batches_reuse_the_queues_upload_buffer() { - let Some((dev, queue)) = device() else { - println!("no D3D12 device – skipping"); - crate::gpu::recomp::runner::skip_test("no GPU"); - return; - }; - unsafe { - let make = |w: u64, h: u32, mips: u16, 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() - }; - // every subresource of `r`, filled with a pattern of `seed` - let subs = |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) ^ seed ^ k as u8).collect() } - }) - .collect() - }; - let textures = [make(64, 64, 7, DXGI_FORMAT_R8G8B8A8_UNORM), make(100, 30, 1, DXGI_FORMAT_R8G8B8A8_UNORM), make(256, 256, 9, DXGI_FORMAT_BC7_UNORM)]; - let key = windows::core::Interface::as_raw(&queue) as usize; - let kept = || 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)); - let mut buffers = Vec::new(); - for round in 0..2u8 { - let items: Vec<_> = textures.iter().enumerate().map(|(i, r)| (r.clone(), subs(r, round * 16 + i as u8), vec![SHADER_READ])).collect(); - assert!(upload_batch(&dev, &queue, &items).unwrap().is_empty(), "round {round}: an upload failed"); - 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, "round {round}, texture {i}, subresource {k} differs"); - } - } - buffers.push(kept().expect("the queue's upload buffer is kept")); - } - assert_eq!(buffers[0], buffers[1], "the second batch made a new upload buffer"); - } - } - - #[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 select_large_upload_device_with( - selector: &crate::gpu::adapter::Selector, - make_factory: impl FnOnce() -> Result, - warp_device: impl FnOnce(&F) -> Result, - hardware_device: impl FnOnce(&F, &crate::gpu::adapter::Selector) -> Option<(D, String)>, - default_device: impl FnOnce() -> Result, - ) -> Result<(D, String), String> { - match make_factory() { - Ok(factory) if *selector == crate::gpu::adapter::Selector::Warp => { - warp_device(&factory).map(|dev| (dev, "WARP (software renderer)".to_string())) - } - Ok(factory) => hardware_device(&factory, selector).ok_or_else(|| "no GPU".to_string()), - Err(err) if *selector == crate::gpu::adapter::Selector::Auto => default_device() - .map(|dev| (dev, "default D3D12 adapter".to_string())) - .map_err(|dev_err| format!("DXGI factory unavailable ({err}); default D3D12 device unavailable ({dev_err})")), - Err(err) => Err(format!("DXGI factory unavailable for {selector}: {err}")), - } - } - - unsafe fn large_upload_device(selector: &crate::gpu::adapter::Selector) -> Result<(ID3D12Device, String), String> { - use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; - use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIAdapter1, IDXGIFactory6}; - select_large_upload_device_with( - selector, - || CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| e.to_string()), - |factory| { - let warp: IDXGIAdapter1 = factory.EnumWarpAdapter().map_err(|e| format!("WARP adapter unavailable: {e}"))?; - crate::gpu::agility::create_device(&warp, D3D_FEATURE_LEVEL_11_0).map_err(|e| format!("WARP device unavailable: {e}")) - }, - |factory, sel| { - crate::gpu::adapter::candidates(factory, sel).into_iter().find_map(|(a, desc)| { - crate::gpu::agility::create_device(&a, D3D_FEATURE_LEVEL_11_0).ok().map(|dev| (dev, crate::gpu::adapter::name(&desc))) - }) - }, - || crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0).map_err(|e| e.to_string()), - ) - } - - #[test] - fn large_upload_device_selection_handles_factory_fallback_and_selectors() { - use crate::gpu::adapter::Selector; - // 1. Auto + DXGI_ERROR_UNSUPPORTED falls back to default device. - let mut used_default = false; - let ok = select_large_upload_device_with(&Selector::Auto, || Err::<(), _>("DXGI_ERROR_UNSUPPORTED (0x887A0004)".into()), |_| unreachable!(), |_, _| unreachable!(), || { used_default = true; Ok(42u32) }); - assert!(used_default && ok == Ok((42, "default D3D12 adapter".to_string()))); - // 2. Auto + double failure returns Err without panicking. - let err = select_large_upload_device_with(&Selector::Auto, || Err::<(), _>("E_FAIL".into()), |_| unreachable!(), |_, _| unreachable!(), || Err::("no D3D12 device".into())); - assert!(err.as_ref().is_err_and(|e| e.contains("E_FAIL") && e.contains("no D3D12 device"))); - // 3. Explicit XCL_ADAPTER filter + factory error must not ignore filter via default fallback. - for sel in [Selector::Name("rtx".into()), Selector::Index(1), Selector::Warp] { - let mut fallback = false; - let res = select_large_upload_device_with(&sel, || Err::<(), _>("DXGI_ERROR_UNSUPPORTED".into()), |_| unreachable!(), |_, _| unreachable!(), || { fallback = true; Ok(99u32) }); - assert!(!fallback && res.is_err()); - } - // 4. Headless CI: Auto + factory ok with 0 hardware adapters skips cleanly without fallback. - let mut fallback = false; - let none = select_large_upload_device_with(&Selector::Auto, || Ok(()), |_| unreachable!(), |_, _| None::<(u32, String)>, || { fallback = true; Ok(7u32) }); - assert!(!fallback && none == Err("no GPU".to_string())); - // 5. Selector::Warp + factory ok uses EnumWarpAdapter path. - let warp = select_large_upload_device_with(&Selector::Warp, || Ok(()), |_| Ok(11u32), |_, _| unreachable!(), || unreachable!()); - assert_eq!(warp, Ok((11, "WARP (software renderer)".to_string()))); - } - - #[test] - fn gpu_large_mixed_upload_keeps_tight_staging_and_exact_pixels() { - use windows::core::Interface; - - unsafe { - if std::env::var_os("XCL_D3D12_DEBUG").is_some() { - match crate::gpu::agility::configuration_interface::(&CLSID_D3D12Debug) { - Ok(debug) => debug.EnableDebugLayer(), - Err(error) => println!("D3D12 debug layer unavailable: {error}"), - } - } - let selector = crate::gpu::adapter::Selector::from_env_or("auto"); - let (dev, adapter_name) = match large_upload_device(&selector) { - Ok(selected) => selected, - Err(reason) => { - crate::gpu::recomp::runner::skip_test(&reason); - return; - } - }; - println!("large upload adapter: {adapter_name}"); - let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); - let make = |width, height, format| { - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: width, Height: height, - DepthOrArraySize: 1, MipLevels: 1, Format: format, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() - }; - let mut out = None::; - let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; - dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, SHADER_READ, None, &mut out).unwrap(); - out.unwrap() - }; - let pixels = |rows: usize, row_bytes: usize, seed: u8| { - let data = (0..rows * row_bytes).map(|i| (i as u8).wrapping_mul(31) ^ (i >> 13) as u8 ^ seed).collect(); - vec![Subresource { depth: 1, rows, row_bytes, data }] - }; - let rgba = (make(8192, 4096, DXGI_FORMAT_R8G8B8A8_UNORM), pixels(4096, 32768, 27), vec![SHADER_READ]); - let bc7 = (make(2048, 2048, DXGI_FORMAT_BC7_UNORM), pixels(512, 8192, 91), vec![SHADER_READ]); - let key = queue.as_raw() as usize; - let kept = || { - let guard = UPLOADERS.lock().unwrap(); - let stage = guard.as_ref().unwrap()[&key].staging.as_ref().unwrap(); - (stage.0.as_raw() as usize, stage.2) - }; - let batch = [rgba, bc7]; - assert!(upload_batch(&dev, &queue, &batch[..1]).unwrap().is_empty()); - let first = kept(); - let before = std::time::Instant::now(); - assert!(upload_batch(&dev, &queue, &batch).unwrap().is_empty()); - let growth = before.elapsed(); - let grown = kept(); - for (resource, bytes, _) in &batch { - assert!(read_back(&dev, &queue, resource, bytes) == *bytes, "mixed batch pixel mismatch"); - } - let before = std::time::Instant::now(); - assert!(upload_batch(&dev, &queue, &batch).unwrap().is_empty()); - let repeat = before.elapsed(); - let reused = kept(); - for (resource, bytes, _) in &batch { - assert!(read_back(&dev, &queue, resource, bytes) == *bytes, "repeat pixel mismatch"); - } - // 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); - if let Ok(info) = dev.cast::() { - let mut errors = 0; - for index in 0..info.GetNumStoredMessagesAllowedByRetrievalFilter() { - let mut size = 0; - info.GetMessage(index, None, &mut size).unwrap(); - let mut buffer = vec![0usize; size.div_ceil(std::mem::size_of::())]; - let msg = buffer.as_mut_ptr().cast::(); - info.GetMessage(index, Some(msg), &mut size).unwrap(); - if matches!((*msg).Severity, D3D12_MESSAGE_SEVERITY_ERROR | D3D12_MESSAGE_SEVERITY_CORRUPTION) { - errors += 1; - } - } - println!("D3D12 debug errors or corruption messages: {errors}"); - assert_eq!(errors, 0); - } - 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, 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"); - } - } - /// Mean |level `k` - level `k - 1` scaled down 2×| per channel (0..255 scale) of a texture /// with `ch` channels of `cb` bytes (unorm); None when the sizes do not halve. fn mip_error(big: &Subresource, small: &Subresource, ch: usize, cb: usize) -> Option { diff --git a/crates/xcl/src/gpu/tiling.rs b/crates/xcl/src/gpu/tiling.rs index 9515bd44c2..de370cc695 100644 --- a/crates/xcl/src/gpu/tiling.rs +++ b/crates/xcl/src/gpu/tiling.rs @@ -205,6 +205,26 @@ impl Layout { } } + /// How many elements of a row lie together in memory, at any multiple of that many: up to 16 + /// bytes of them. + fn run(&self) -> usize { + let e = 1u32 << self.elem_log2; + let mut run = 16 / e as usize; + while run > 1 { + let low = run as u32 * e - 1; + let clear = |t: &[u32]| t.iter().all(|o| o & low == 0); + let together = self.block_w.is_multiple_of(run) + && self.ox.chunks_exact(run).all(|c| c[0] & low == 0 && c.iter().enumerate().all(|(k, &o)| o == c[0] + k as u32 * e)) + && [&self.oy, &self.oz, &self.hx, &self.hy, &self.hz].iter().all(|t| clear(t)) + && self.base_xor as u32 & low == 0; + if together { + break; + } + run /= 2; + } + run + } + /// surface `w` × `h` elements: (blocks per row, blocks per column) pub fn blocks(&self, w: usize, h: usize) -> (usize, usize) { (w.div_ceil(self.block_w), h.div_ceil(self.block_h)) @@ -468,6 +488,25 @@ pub fn image_layout(t: &super::desc::Image, cfg: PipeConfig) -> Option<(Layout, Some((l, t.width.div_ceil(side) as usize, t.height.div_ceil(side) as usize)) } +/// Part of a level: the elements `x0..x1` of its rows `y0..y1`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Rect { + pub x0: usize, + pub y0: usize, + pub x1: usize, + pub y1: usize, +} + +/// `N` bytes from each of `runs` (XOR `at`) of a block, one after another to `to`. +#[inline(always)] +unsafe fn copy_runs<'a, const N: usize>(block: *const u8, runs: impl Iterator, at: u32, to: *mut u8) { + let mut to = to as *mut [u8; N]; + for x in runs { + to.write_unaligned((block.add((x ^ at) as usize) as *const [u8; N]).read_unaligned()); + to = to.add(1); + } +} + /// One mip level of a tiled surface, in elements. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct MipLevel { @@ -651,6 +690,152 @@ impl Chain { out } + /// The first level in the mip tail (the number of levels when there is none). + pub fn first_tail(&self) -> usize { + self.levels.iter().position(|l| l.tail.is_some()).unwrap_or(self.levels.len()) + } + + /// The bytes of a slice level `i` takes (the levels in the mip tail share its block). + pub fn level_bytes(&self, i: usize) -> std::ops::Range { + if self.levels[i].tail.is_some() { + return 0..self.layout.block_bytes; + } + // (from the smallest level to mip 0, see `new_3d`) + self.levels[i].offset..if i == 0 { self.slice_bytes } else { self.levels[i - 1].offset } + } + + /// The parts of a slice's levels (level, elements of it) the bytes `ranges` of the slice hold: + /// whole blocks of a level, as few rectangles as rows of them give, and the level as a whole + /// when most of its blocks are among them. `ranges` (from, to) are sorted and disjoint. (2D: a + /// 3D texture's slices are layers.) + pub fn parts(&self, ranges: &[(usize, usize)]) -> Vec<(usize, Rect)> { + let t = &self.layout; + let mut out = Vec::new(); + let first_tail = self.first_tail(); + for i in first_tail..self.levels.len() { + if ranges.first().is_some_and(|r| r.0 < t.block_bytes) { + out.push((i, Rect { x0: 0, y0: 0, x1: self.levels[i].width, y1: self.levels[i].height })); + } + } + // (row of blocks, first block, past the last one) of a level, in their order in memory + let mut spans: Vec<(usize, usize, usize)> = Vec::new(); + for i in 0..first_tail { + let l = &self.levels[i]; + let whole = self.level_bytes(i); + let row = l.pitch.div_ceil(t.block_w).max(1); + spans.clear(); + let mut blocks = 0; + for &(from, to) in &ranges[ranges.partition_point(|r| r.1 <= whole.start)..] { + if from >= whole.end { + break; + } + let (from, to) = (from.max(whole.start) - whole.start, to.min(whole.end) - whole.start); + let (mut k, end) = (from / t.block_bytes, to.div_ceil(t.block_bytes)); + while k < end { + let (y, x) = (k / row, k % row); + let n = (row - x).min(end - k); + k += n; + // (a linear surface's "blocks" are 256 bytes of a row: whole rows of those) + let (x, n) = if t.block_h == 1 { (0, row) } else { (x, n) }; + match spans.last_mut() { + Some(s) if s.0 == y && x <= s.2 => { + blocks += (x + n).saturating_sub(s.2); + s.2 = s.2.max(x + n); + } + _ => { + spans.push((y, x, x + n)); + blocks += n; + } + } + } + } + if spans.is_empty() { + continue; + } + if blocks * 4 >= (whole.len() / t.block_bytes) * 3 { + out.push((i, Rect { x0: 0, y0: 0, x1: l.width, y1: l.height })); + continue; + } + let from = out.len(); + for &(y, x0, x1) in &spans { + let r = Rect { x0: x0 * t.block_w, y0: y * t.block_h, x1: (x1 * t.block_w).min(l.width), y1: ((y + 1) * t.block_h).min(l.height) }; + // (padding blocks beyond the level) + if r.x0 >= r.x1 || r.y0 >= r.y1 { + continue; + } + match out[from..].last_mut() { + Some((_, p)) if p.x0 == r.x0 && p.x1 == r.x1 && p.y1 == r.y0 => p.y1 = r.y1, + _ => out.push((i, r)), + } + } + } + out + } + + /// The rows of blocks of level `i` that hold the rows of `r` (0..1 for a level in the tail), + /// and in each the blocks that hold its columns. + pub fn blocks_of(&self, i: usize, r: Rect) -> (std::ops::Range, std::ops::Range) { + let (t, l) = (&self.layout, &self.levels[i]); + ((r.y0 + l.origin.1) / t.block_h..(r.y1 + l.origin.1).div_ceil(t.block_h), (r.x0 + l.origin.0) / t.block_w..(r.x1 + l.origin.0).div_ceil(t.block_w)) + } + + /// Where block (`bx`, `by`) of level `i` begins in its slice. + pub fn block_at(&self, i: usize, bx: usize, by: usize) -> usize { + let l = &self.levels[i]; + l.offset + (by * l.pitch.div_ceil(self.layout.block_w).max(1) + bx) * self.layout.block_bytes + } + + /// The elements of `r` that are in blocks `blocks` of block row `by` of level `i` in array + /// slice `slice` → linear rows, `pitch` bytes apart; `dst` is where `r`'s first element goes. + /// `src` holds those blocks' bytes, one after another. + /// + /// # Safety + /// `dst` takes `r`'s rows `pitch` bytes apart; `src` is the length of the blocks. + pub unsafe fn detile_blocks(&self, src: &[u8], i: usize, slice: usize, by: usize, blocks: std::ops::Range, r: Rect, dst: *mut u8, pitch: usize) { + let (t, l) = (&self.layout, &self.levels[i]); + assert!(src.len() >= blocks.len() * t.block_bytes); + // in the coordinates of the blocks (a level in the tail lies somewhere in its block) + let (x0, x1) = (r.x0 + l.origin.0, r.x1 + l.origin.0); + let (y0, y1) = ((r.y0 + l.origin.1).max(by * t.block_h), (r.y1 + l.origin.1).min((by + 1) * t.block_h)); + let e = t.elem_log2; + let hi = |tab: &[u32], c: usize| tab[c % tab.len()]; + let z = t.oz[slice % t.block_d] ^ hi(&t.hz, slice / t.block_d); + let run = t.run(); + for (n, bx) in blocks.enumerate() { + let (from, to) = (x0.max(bx * t.block_w), x1.min((bx + 1) * t.block_w)); + if from >= to { + continue; + } + let block = src[n * t.block_bytes..][..t.block_bytes].as_ptr(); + let fixed = hi(&t.hx, bx) ^ hi(&t.hy, by) ^ z ^ t.base_xor as u32; + // whole runs of elements that lie together, then the rest one by one + let (a, b) = (from - bx * t.block_w, to - bx * t.block_w); + let (ra, rb) = (a.next_multiple_of(run), b / run * run); + let columns = &t.ox[..t.block_w]; + for y in y0..y1 { + let at = t.oy[y - by * t.block_h] ^ fixed; + let row = dst.add((y - l.origin.1 - r.y0) * pitch + ((from - x0) << e)); + // SAFETY: an offset is inside the block (`every_pattern_is_a_permutation_of_its_block`) + let one = |x: usize| std::ptr::copy_nonoverlapping(block.add((columns[x] ^ at) as usize), row.add((x - a) << e), 1 << e); + if ra >= rb { + (a..b).for_each(one); + continue; + } + (a..ra).for_each(one); + let runs = columns[ra..rb].iter().step_by(run); + let to = row.add((ra - a) << e); + match run << e { + 16 => copy_runs::<16>(block, runs, at, to), + 8 => copy_runs::<8>(block, runs, at, to), + 4 => copy_runs::<4>(block, runs, at, to), + 2 => copy_runs::<2>(block, runs, at, to), + _ => copy_runs::<1>(block, runs, at, to), + } + (rb..b).for_each(one); + } + } + } + /// linear rows of level `i` → its place in array slice `slice` (`dst`, `slice_bytes` long) pub fn tile_level(&self, dst: &mut [u8], i: usize, slice: usize, linear: &[u8]) { let l = self.levels[i]; @@ -760,6 +945,130 @@ mod tests { } } + /// A level detiled block by block, in rectangles of it, is the level `detile_level` gives: + /// every mode (linear too), element size and level (mip tails too), a base swizzle, slices. + #[test] + fn blocks_of_a_level_detile_as_the_level_does() { + let mut seed = 0x9E37_79B9u32; + let mut random = |n: usize| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed as usize % n + }; + for mode in MODES.into_iter().chain([0]) { + for e in 0..5u32 { + for (k, cfg) in configs().into_iter().enumerate() { + let mut lay = Layout::new(mode, e, cfg).unwrap(); + if mode != 0 && k % 2 == 1 { + lay.base_xor = (lay.block_bytes / 2) & !((1 << e) - 1); + } + let es = 1usize << e; + let (w, h) = [(77, 45), (300, 130), (64, 64)][random(3)]; + let c = Chain::new(lay, w, h, 1, 9); + for slice in [0usize, 3] { + let mem: Vec = (0..c.slice_bytes).map(|i| ((i + slice * 7) * 131 % 251) as u8).collect(); + for (i, l) in c.levels.iter().enumerate() { + let want = c.detile_level(&mem, i, slice); + // the level cut into rectangles at block borders, each with its own pitch + let mut got = vec![0xEEu8; l.width * l.height * es]; + let (bw, bh) = if l.tail.is_some() { (l.width, l.height) } else { (c.layout.block_w, c.layout.block_h) }; + let mut y0 = 0; + while y0 < l.height { + let y1 = (y0 + bh * (1 + random(3))).min(l.height); + let mut x0 = 0; + while x0 < l.width { + let r = Rect { x0, y0, x1: (x0 + bw * (1 + random(3))).min(l.width), y1 }; + let pitch = (r.x1 - r.x0) * es + random(3) * 64; + let mut out = vec![0xEEu8; pitch * (r.y1 - r.y0) + 64]; + let (rows, columns) = c.blocks_of(i, r); + for by in rows { + let (from, n) = (c.block_at(i, columns.start, by), columns.len() * c.layout.block_bytes); + unsafe { c.detile_blocks(&mem[from..from + n], i, slice, by, columns.clone(), r, out.as_mut_ptr(), pitch) }; + } + for y in r.y0..r.y1 { + let row = (r.x1 - r.x0) * es; + got[(y * l.width + r.x0) * es..][..row].copy_from_slice(&out[(y - r.y0) * pitch..][..row]); + assert!(out[(y - r.y0) * pitch + row..(y - r.y0 + 1) * pitch].iter().all(|&b| b == 0xEE), "mode {mode} e{e} level {i}: bytes past a row written"); + } + x0 = r.x1; + } + y0 = y1; + } + assert!(got == want, "mode {mode} e{e} {cfg:?} {w}x{h} level {i} slice {slice}"); + } + } + } + } + } + } + + /// `parts` of some bytes: the rectangles hold every element those bytes are part of, and none + /// that lies in no block of theirs (unless the level goes as a whole). + #[test] + fn parts_of_some_bytes_are_the_blocks_they_are_in() { + let cfg = PipeConfig { pipes_log2: 5, pkrs_log2: 3 }; + let mut seed = 0x1234_5679u32; + let mut random = |n: usize| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed as usize % n + }; + for mode in [0u32, 1, 5, 9, 21, 25, 27] { + for e in [0u32, 2, 3, 4] { + for (w, h, mips) in [(700u32, 300u32, 1u32), (1030, 260, 11), (64, 64, 7), (33, 900, 4)] { + let c = Chain::new(Layout::new(mode, e, cfg).unwrap(), w, h, 1, mips); + for round in 0..6 { + // a few sorted ranges of whole 4 KiB pages (the last one may be a part) + let mut ranges: Vec<(usize, usize)> = Vec::new(); + let mut at = random(c.slice_bytes.div_ceil(0x1000)) * 0x1000; + for _ in 0..1 + round { + let to = (at + 0x1000 * (1 + random(5))).min(c.slice_bytes); + if at >= to { + break; + } + ranges.push((at, to)); + at = to + 0x1000 * (1 + random(60)); + } + if ranges.is_empty() { + continue; + } + let parts = c.parts(&ranges); + let in_ranges = |a: usize, b: usize| ranges.iter().any(|r| a < r.1 && r.0 < b); + for (i, l) in c.levels.iter().enumerate() { + let mine: Vec = parts.iter().filter(|p| p.0 == i).map(|p| p.1).collect(); + assert!(mine.iter().all(|r| r.x0 < r.x1 && r.y0 < r.y1 && r.x1 <= l.width && r.y1 <= l.height), "{mine:?} of {l:?}"); + let whole = mine.len() == 1 && mine[0] == (Rect { x0: 0, y0: 0, x1: l.width, y1: l.height }); + for y in 0..l.height { + for x in 0..l.width { + let n = mine.iter().filter(|r| (r.x0..r.x1).contains(&x) && (r.y0..r.y1).contains(&y)).count(); + let o = c.element_at(l, x, y, 0); + if in_ranges(o, o + (1 << e)) { + assert_eq!(n, 1, "mode {mode} e{e} {w}x{h} level {i}: element ({x}, {y}) is in {n} parts of {mine:?}, {ranges:x?}"); + } else if n > 0 && !whole { + let block = l.offset + (o - l.offset) / c.layout.block_bytes * c.layout.block_bytes; + // (linear: a row of 256-byte pieces goes as a whole) + let row = if mode == 0 { l.pitch << e } else { c.layout.block_bytes }; + let block = if mode == 0 { l.offset + (o - l.offset) / row * row } else { block }; + assert!(in_ranges(block, block + row), "mode {mode} e{e} {w}x{h} level {i}: element ({x}, {y}) of no written block"); + } + assert!(n <= 1); + } + } + } + } + } + } + } + // all of a slice's bytes: every level as a whole + let c = Chain::new(Layout::new(27, 2, cfg).unwrap(), 1030, 260, 1, 11); + let parts = c.parts(&[(0, c.slice_bytes)]); + assert_eq!(parts.len(), 11); + assert!(parts.iter().all(|&(i, r)| r == Rect { x0: 0, y0: 0, x1: c.levels[i].width, y1: c.levels[i].height })); + assert!(c.parts(&[]).is_empty()); + } + /// every mode, element size and pipe configuration: the in-block mapping is a permutation /// of the block's elements (catches a mis-parsed table or a wrong block shape) #[test] diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 11089de9e5..e4e34f0166 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -7,16 +7,18 @@ //! The aperture has 4 windows by default and can grow to 8 or 16 with heap-backed shaders //! (`XCL_HEAP_WINDOWS=1` + `XCL_UMA_WINDOWS=8|16`). The base is aligned to the aperture size, //! so shaders compute the window index from `(address >> 32) - (base >> 32)` and the byte -//! offset from the low 32 bits. Allocations never straddle windows. +//! offset from the low 32 bits. Allocations never straddle windows. With 16 windows, 6 of them +//! hold GPU views of the title's CPU memory (`Uma::view_reserve`), memory only the GPU reaches. //! //! Measured on Windows 11 + RX 9070 (2026-11-20): the heap must cover a fully committed //! `VirtualAlloc` allocation (a reservation with partial commit is rejected); up to //! 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::{Mutex, OnceLock}; -use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; +use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; /// VirtualAlloc: track CPU writes (GetWriteWatch) const MEM_WRITE_WATCH: u32 = 0x20_0000; @@ -38,11 +40,23 @@ pub const MAX_HEAP_WINDOWS: usize = 16; /// sparse pool bloat), while still giving expanded 8/16-window layouts extra coherent windows. const MAX_RUNTIME_SPARSE_WINDOWS: usize = 3; +/// View windows of the 16-window layout (`WindowKind::View`, 24 GiB): GPU views of the title's +/// CPU memory go there (`Uma::view_reserve`). A retail title reserves 24 GiB of 64 KiB pages as +/// a CPU view and the same again as a GPU-only view of it, and gives the GPU only addresses of +/// the second; outside the windows every shader read of it is 0. +pub const VIEW_WINDOWS: usize = 6; + +/// View windows of a runtime layout of `windows` windows (none below 16: no room for them). +fn view_windows(windows: usize) -> usize { + if windows == MAX_HEAP_WINDOWS { VIEW_WINDOWS } else { 0 } +} + /// Maximum number of committed coherent windows in an expanded runtime layout. -/// Always leaves 3 sparse VRAM windows (12 GiB): 1 coherent for 4-window, 5 for 8-window, 13 for 16-window. +/// Always leaves 3 sparse VRAM windows (12 GiB) and the view windows: 1 coherent for 4-window, +/// 5 for 8-window, 7 for 16-window. fn max_coherent_windows(windows: usize) -> usize { if windows > MAX_WINDOWS { - windows.saturating_sub(MAX_RUNTIME_SPARSE_WINDOWS).max(1) + windows.saturating_sub(MAX_RUNTIME_SPARSE_WINDOWS + view_windows(windows)).max(1) } else { 1 } @@ -102,6 +116,10 @@ enum WindowKind { None, Committed(usize), Sparse, + /// GPU views of the title's CPU memory (`view_reserve`): reserved PAGE_NOACCESS, never + /// committed nor write-watched – the CPU never touches them. The GPU reaches them through + /// the window's tiled buffer (`d3d12x::sparse`), whose tiles get video memory on demand. + View, } pub struct Uma { @@ -112,6 +130,10 @@ pub struct Uma { inner: Mutex, /// free ranges of the sparse windows (address → length) and the reservations in them sparse_free: Mutex<(BTreeMap, BTreeMap)>, + /// the same for the view windows (`view_reserve`) + views: Mutex<(BTreeMap, BTreeMap)>, + /// the committed windows are not the GPU's memory: it has copies of them (`set_shadowed`) + shadowed: AtomicBool, /// XCL's own pool in window 0 for `Arena` blocks: (start, end, free blocks). The title /// cannot take it – a title that commits all of unified memory at start (Unicorn /// Overlord: 2046 of 2048 MB) left no room for draw arguments, and draws were skipped. @@ -180,6 +202,43 @@ fn take_sparse_in( Some(at) } +/// The reservation of `take_sparse_in` at `p` goes back to the free ranges (merged with its +/// neighbours): its bytes. +fn give_back(g: &mut (BTreeMap, BTreeMap), p: usize) -> Option { + let size = g.1.remove(&p)?; + let (mut start, mut len) = (p, size); + if let Some((&o, &l)) = g.0.range(..p).next_back() { + if o + l == p { + g.0.remove(&o); + start = o; + len += l; + } + } + if let Some(l) = g.0.remove(&(p + size)) { + len += l; + } + g.0.insert(start, len); + Some(size) +} + +/// The reservation of `take_sparse_in` holding `p`: (start, bytes). +fn reservation_at(g: &(BTreeMap, BTreeMap), p: usize) -> Option<(usize, usize)> { + g.1.range(..=p).next_back().map(|(&a, &l)| (a, l)).filter(|&(a, l)| p < a + l) +} + +/// `VirtualAlloc` of `len` bytes exactly at `at` (false: Windows has something there, or put +/// it elsewhere – then nothing stays reserved). +fn reserve_exactly(at: usize, len: usize, flags: u32, protect: u32) -> bool { + let p = unsafe { VirtualAlloc(at as *const std::ffi::c_void, len, flags, protect) }; + if p as usize != at { + if !p.is_null() { + unsafe { VirtualFree(p, 0, MEM_RELEASE) }; + } + return false; + } + true +} + impl Uma { /// Commit `size` bytes (split into as few equal windows as fit, at most 4) at the first /// free 16 GiB-aligned address from 16 GiB up, with remaining windows reserved as sparse. @@ -225,6 +284,22 @@ impl Uma { *self.pool.lock().unwrap() = (p, p + bytes, (p..p + bytes).step_by(ARENA_BLOCK).rev().collect()); } + /// Diagnostic: how the committed window stands: free bytes in it in total, the largest free + /// run, the bytes in use, and XCL's pool blocks left. + pub fn committed_state(&self) -> (usize, usize, usize, usize) { + let Some(win) = self.kinds.iter().position(|w| matches!(w, WindowKind::Committed(_))) else { return (0, 0, 0, 0) }; + let g = self.inner.lock().unwrap(); + let mine = |o: usize| o / WINDOW == win; + let (mut free, mut largest) = (0usize, 0usize); + for (_, &l) in g.free.iter().filter(|(&o, _)| mine(o)) { + free += l; + largest = largest.max(l); + } + let used = g.used.iter().filter(|(&o, _)| mine(o)).map(|(_, &l)| l).sum(); + drop(g); + (free, largest, used, self.pool.lock().unwrap().2.len()) + } + /// A block of `ARENA_BLOCK` bytes from XCL's pool (None: the pool is used up or absent). fn pool_block(&self) -> Option { self.pool.lock().unwrap().2.pop() @@ -243,42 +318,65 @@ impl Uma { Self::reserve_runtime(size, coherent, MAX_WINDOWS).or_else(|| Self::new(size)) } - /// `for_runtime_with` using `windows` total shader-visible windows: `windows - coh_wins` - /// sparse VRAM windows followed by `coh_wins` committed coherent windows sized to hold - /// `coherent` bytes (up to `max_coherent_windows(windows)`). + /// `for_runtime_with` using `windows` total shader-visible windows: up to 3 sparse VRAM + /// windows followed by `coh_wins` committed coherent windows sized to hold `coherent` bytes + /// (up to `max_coherent_windows(windows)`), then, with 16, `VIEW_WINDOWS` view windows. pub fn for_runtime_windows(size: usize, coherent: usize, windows: usize) -> Option { let windows = if matches!(windows, MAX_WINDOWS | 8 | MAX_HEAP_WINDOWS) { windows } else { MAX_WINDOWS }; Self::reserve_runtime(size, coherent, windows) } + /// The layout: sparse windows (at most `MAX_RUNTIME_SPARSE_WINDOWS`), then the coherent + /// windows, then (16 windows only) the view windows. With view windows the whole aperture + /// is reserved – the coherent windows' uncommitted tails and the windows after the views + /// too, PAGE_NOACCESS – so Windows never places anything at an address shaders read as a + /// window (it read the memory of whatever was there, or of window 0). fn reserve_runtime(size: usize, coherent: usize, windows: usize) -> Option { let coh_sizes = coherent_window_sizes(size, coherent, windows); let coh_wins = coh_sizes.len(); let sparse_wins = (windows - coh_wins).min(MAX_RUNTIME_SPARSE_WINDOWS); let sparse_len = sparse_wins * WINDOW; + let view_wins = view_windows(windows); + let views_at = sparse_wins + coh_wins; + let whole = view_wins > 0; + if views_at + view_wins > windows { + return None; + } for slot in (windows..slot_limit(windows)).step_by(windows) { let base = slot << 32; - let sp = unsafe { VirtualAlloc(base as *const std::ffi::c_void, sparse_len, MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) }; - if sp as usize != base { - if !sp.is_null() { - unsafe { VirtualFree(sp, 0, MEM_RELEASE) }; - } + if !reserve_exactly(base, sparse_len, MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) { continue; } - let mut win_allocs = Vec::with_capacity(1 + coh_wins); + let mut win_allocs = Vec::with_capacity(4 + 2 * coh_wins); win_allocs.push(base); let mut ok = true; for (c, &c_size) in coh_sizes.iter().enumerate() { let c_base = base + (sparse_wins + c) * WINDOW; - let cp = unsafe { VirtualAlloc(c_base as *const std::ffi::c_void, c_size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }; - if cp as usize != c_base { - if !cp.is_null() { - unsafe { VirtualFree(cp, 0, MEM_RELEASE) }; - } + if !reserve_exactly(c_base, c_size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) { ok = false; break; } win_allocs.push(c_base); + if whole && c_size < WINDOW { + if !reserve_exactly(c_base + c_size, WINDOW - c_size, MEM_RESERVE, PAGE_NOACCESS) { + ok = false; + break; + } + win_allocs.push(c_base + c_size); + } + } + if ok && whole { + // the view windows, then the rest of the aperture: one reservation each + for (lo, hi) in [(views_at, views_at + view_wins), (views_at + view_wins, windows)] { + if lo == hi { + continue; + } + if !reserve_exactly(base + lo * WINDOW, (hi - lo) * WINDOW, MEM_RESERVE, PAGE_NOACCESS) { + ok = false; + break; + } + win_allocs.push(base + lo * WINDOW); + } } if !ok { for p in win_allocs { @@ -294,14 +392,21 @@ impl Uma { inner.free.insert(k * WINDOW, c_size); kinds[k] = WindowKind::Committed(c_size); } + kinds[views_at..views_at + view_wins].fill(WindowKind::View); let mut sparse_free: (BTreeMap, BTreeMap) = Default::default(); sparse_free.0.insert(base, sparse_len); + let mut views: (BTreeMap, BTreeMap) = Default::default(); + if view_wins > 0 { + views.0.insert(base + views_at * WINDOW, view_wins * WINDOW); + } let u = Uma { base, kinds, win_allocs, inner: Mutex::new(inner), sparse_free: Mutex::new(sparse_free), + views: Mutex::new(views), + shadowed: AtomicBool::new(false), pool: Mutex::new((0, 0, Vec::new())), driver: Default::default(), }; @@ -344,6 +449,13 @@ impl Uma { self.desc_range().map_or(self.base, |(_, end)| end) } + /// The end of the last sparse window: reservations and allocations in the sparse windows + /// stay below it, never in the view windows (a CPU view of 24 GiB there would be tiled + /// video memory again). + fn sparse_end(&self) -> usize { + self.base + self.kinds.iter().rposition(|w| matches!(w, WindowKind::Sparse)).map_or(0, |k| k + 1) * WINDOW + } + /// Whether window `k` is a sparse VRAM window. pub fn is_sparse_window(&self, k: usize) -> bool { self.kinds.get(k).is_some_and(|w| matches!(w, WindowKind::Sparse)) @@ -354,6 +466,37 @@ impl Uma { self.kinds.get(k).is_some_and(|w| matches!(w, WindowKind::Committed(_))) } + /// Whether window `k` is a view window (GPU views of the title's CPU memory, `view_reserve`). + pub fn is_view_window(&self, k: usize) -> bool { + self.kinds.get(k).is_some_and(|w| matches!(w, WindowKind::View)) + } + + /// Whether `p` is in a view window, reserved for a GPU view or not. Not memory the CPU can + /// touch: `contains`, `is_sparse` and `is_committed` are false there. + pub fn is_view(&self, p: usize) -> bool { + self.window_of(p).is_some_and(|k| self.is_view_window(k)) + } + + /// Address space for a GPU view of `size` bytes in the view windows, starting at a window's + /// start (so a view of 24 GiB fits the 6 windows whole). None: no view windows (layouts + /// below 16 windows), or no room left. + pub fn view_reserve(&self, size: usize) -> Option { + let lo = self.kinds.iter().position(|w| matches!(w, WindowKind::View))?; + let hi = self.kinds.iter().rposition(|w| matches!(w, WindowKind::View))? + 1; + let size = size.max(1).checked_next_multiple_of(GRAIN)?; + take_sparse_in(&mut self.views.lock().unwrap(), self.base + lo * WINDOW, self.base + hi * WINDOW, size, WINDOW, false) + } + + /// The bytes of the view reservation starting at `p` (it is gone after this). + pub fn view_release(&self, p: usize) -> Option { + give_back(&mut self.views.lock().unwrap(), p) + } + + /// The view reservation holding `p`: (start, bytes). + pub fn view_reservation(&self, p: usize) -> Option<(usize, usize)> { + reservation_at(&self.views.lock().unwrap(), p) + } + /// Whether this Uma has any sparse VRAM windows. pub fn has_sparse(&self) -> bool { self.kinds.iter().any(|w| matches!(w, WindowKind::Sparse)) @@ -397,21 +540,41 @@ impl Uma { len > 0 && self.is_committed(p) && p.checked_add(len - 1).is_some_and(|e| self.window_of(e) == self.window_of(p)) } + /// The GPU could not open the committed windows as heaps (`OpenExistingHeapFromAddress` + /// not implemented: D3DMetal): each has a buffer in video memory instead, a copy that + /// `d3d12x::sparse` keeps in step like a sparse window's tiles. + pub fn set_shadowed(&self) { + self.shadowed.store(true, Ordering::Release); + } + + pub fn shadowed(&self) -> bool { + self.shadowed.load(Ordering::Acquire) + } + + /// Whether the GPU works on a copy of the memory at `p` (a sparse window, or a committed + /// one that is shadowed): what the GPU writes there the CPU sees only after a readback. + pub fn is_gpu_copy(&self, p: usize) -> bool { + self.is_sparse(p) || (self.shadowed() && self.is_committed(p)) + } + /// Address space for a title reservation of `size` bytes in the sparse windows (64 KiB /// aligned, first fit; not committed). Prefers windows 1+ so window 0 stays uncluttered for - /// small allocations, falling back to all of the title's sparse space (never `desc_range`). + /// small allocations, keeping reservations of at most one window (`size <= WINDOW`) inside a + /// single window when one has room before falling back to cross-window placement or all of the + /// title's sparse space (never `desc_range`). pub fn sparse_reserve(&self, size: usize) -> Option { if !self.has_sparse() { return None; } - let size = (size.max(1) + GRAIN - 1) & !(GRAIN - 1); + let size = size.max(1).checked_next_multiple_of(GRAIN)?; let mut g = self.sparse_free.lock().unwrap(); - let end = self.base + self.kinds.len() * WINDOW; + let end = self.sparse_end(); let lo = self.title_sparse_start(); - if let Some(at) = take_sparse_in(&mut g, (self.base + WINDOW).max(lo), end, size, GRAIN, false) { - return Some(at); - } - take_sparse_in(&mut g, lo, end, size, GRAIN, false) + let above_0 = (self.base + WINDOW).max(lo); + let single = if size <= WINDOW { take_sparse_in(&mut g, above_0, end, size, GRAIN, true) } else { None }; + single + .or_else(|| take_sparse_in(&mut g, above_0, end, size, GRAIN, false)) + .or_else(|| take_sparse_in(&mut g, lo, end, size, GRAIN, false)) } /// Reserve an aligned range strictly inside sparse window `k` (window 0: 32-bit descriptor @@ -445,7 +608,7 @@ impl Uma { let size = size.max(1).checked_next_multiple_of(GRAIN)?; let align = align.max(GRAIN).checked_next_power_of_two()?; let mut g = self.sparse_free.lock().unwrap(); - let end = self.base + self.kinds.len() * WINDOW; + let end = self.sparse_end(); let lo = self.title_sparse_start(); let above_0 = (self.base + WINDOW).max(lo); if size <= WINDOW { @@ -462,29 +625,40 @@ impl Uma { } } - /// The bytes of the sparse reservation starting at `p` (it is gone after this). - pub fn sparse_release(&self, p: usize) -> Option { - let mut g = self.sparse_free.lock().unwrap(); - let size = g.1.remove(&p)?; - let (mut start, mut len) = (p, size); - if let Some((&o, &l)) = g.0.range(..p).next_back() { - if o + l == p { - g.0.remove(&o); - start = o; - len += l; + /// `sparse_alloc` for memory shaders never address with 32 bits: windows 1+ first (as + /// `sparse_reserve`), window 0 only when they have no room – it stands for the console's low + /// 4 GiB, where a title's own descriptor heaps must lie (`console_heap::title_memory`). + /// Above a window the same as `sparse_alloc`. + pub fn sparse_alloc_above(&self, size: usize, align: usize) -> Option<(usize, usize)> { + if size <= WINDOW && self.has_sparse() { + let size = size.max(1).checked_next_multiple_of(GRAIN)?; + let align = align.max(GRAIN).checked_next_power_of_two()?; + let above_0 = (self.base + WINDOW).max(self.title_sparse_start()); + if let Some(at) = take_sparse_in(&mut self.sparse_free.lock().unwrap(), above_0, self.sparse_end(), size, align, true) { + return Some((at, size)); } } - if let Some(l) = g.0.remove(&(p + size)) { - len += l; - } - g.0.insert(start, len); - Some(size) + self.sparse_alloc(size, align) + } + + /// Diagnostic: the free bytes of sparse window `k` the title may take (not `desc_range`), in + /// all and the largest run. + pub fn sparse_free_in(&self, k: usize) -> (usize, usize) { + let (lo, hi) = (self.base + k * WINDOW, self.base + (k + 1) * WINDOW); + let lo = if k == 0 { lo.max(self.title_sparse_start()) } else { lo }; + let g = self.sparse_free.lock().unwrap(); + let runs = g.0.iter().map(|(&o, &l)| (o.max(lo), (o + l).min(hi))).filter(|&(a, e)| a < e).map(|(a, e)| e - a); + runs.fold((0, 0), |(all, big), n| (all + n, big.max(n))) + } + + /// The bytes of the sparse reservation starting at `p` (it is gone after this). + pub fn sparse_release(&self, p: usize) -> Option { + give_back(&mut self.sparse_free.lock().unwrap(), p) } /// The sparse reservation holding `p`: (start, bytes). pub fn sparse_reservation(&self, p: usize) -> Option<(usize, usize)> { - let g = self.sparse_free.lock().unwrap(); - g.1.range(..=p).next_back().map(|(&a, &l)| (a, l)).filter(|&(a, l)| p < a + l) + reservation_at(&self.sparse_free.lock().unwrap(), p) } /// Bytes currently reserved/allocated in sparse windows. @@ -524,6 +698,8 @@ impl Uma { win_allocs, inner: Mutex::new(inner), sparse_free: Mutex::new(Default::default()), + views: Mutex::new(Default::default()), + shadowed: AtomicBool::new(false), pool: Mutex::new((0, 0, Vec::new())), driver: Default::default(), }); @@ -555,11 +731,11 @@ impl Uma { self.kinds.iter().filter(|w| matches!(w, WindowKind::Committed(_))).count() } - /// (address, bytes) of window `k` (a sparse window: all 4 GiB) + /// (address, bytes) of window `k` (a sparse or view window: all 4 GiB) pub fn window(&self, k: usize) -> (usize, usize) { let len = match self.kinds.get(k).copied().unwrap_or(WindowKind::None) { WindowKind::Committed(s) => s, - WindowKind::Sparse => WINDOW, + WindowKind::Sparse | WindowKind::View => WINDOW, WindowKind::None => 0, }; (self.base + k * WINDOW, len) @@ -567,15 +743,19 @@ impl Uma { /// Underlying write-watched `VirtualAlloc` regions `(base, size)` for `GetWriteWatch`: /// contiguous sparse windows belong to a single reservation, while each committed window - /// is its own allocation. + /// is its own allocation (view windows are not write-watched: the CPU never writes there). pub fn watch_regions(&self) -> Vec<(usize, usize)> { let mut out: Vec<(usize, usize)> = Vec::with_capacity(self.kinds.len()); let mut k = 0; while k < self.kinds.len() { match self.kinds[k] { - WindowKind::None => k += 1, + WindowKind::None | WindowKind::View => k += 1, WindowKind::Committed(s) => { - out.push((self.base + k * WINDOW, s)); + if let Some(segs) = driver_watch_segments(k) { + out.extend(segs); + } else { + out.push((self.base + k * WINDOW, s)); + } k += 1; } WindowKind::Sparse => { @@ -598,19 +778,24 @@ impl Uma { (k < self.kinds.len() && len > 0 && p - start < len).then_some(k) } + /// Whether `p` is unified memory the CPU can address (a committed or sparse window; never + /// a view window, which only the GPU reaches). pub fn contains(&self, p: usize) -> bool { - self.window_of(p).is_some() + self.window_of(p).is_some_and(|k| !self.is_view_window(k)) } /// Whether `p` is memory the title has here: a block handed out in a committed window, or - /// one of its reservations in a sparse window. The windows' ranges are wide (4 GiB each) and - /// a PC resource's GPU address can fall in one by number – that address is not the - /// window's memory (Minecraft's dynamic vertex buffer, a PC upload buffer, was read from an - /// empty sparse window: nothing drew). + /// one of its reservations in a sparse or view window. The windows' ranges are wide (4 GiB + /// each) and a PC resource's GPU address can fall in one by number – that address is not + /// the window's memory (a title's dynamic vertex buffer, a PC upload buffer, was read from + /// an empty sparse window: nothing drew). pub fn is_title_address(&self, p: usize) -> bool { if self.is_sparse(p) { return self.sparse_reservation(p).is_some(); } + if self.is_view(p) { + return self.view_reservation(p).is_some(); + } if !self.is_committed(p) { return false; } @@ -693,6 +878,20 @@ impl Uma { Some(p) } + /// The bytes of the block from `alloc` at `p` (None: not one of ours). + pub fn block_len(&self, p: usize) -> Option { + if !self.is_committed(p) { + return None; + } + { + let g = self.pool.lock().unwrap(); + if p >= g.0 && p < g.1 { + return Some(ARENA_BLOCK); + } + } + self.inner.lock().unwrap().used.get(&(p - self.base)).copied() + } + /// Release a block from `alloc` (false: not one of ours). pub fn free(&self, p: usize) -> bool { if !self.is_committed(p) { @@ -797,10 +996,42 @@ pub fn leave_out() { /// 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 +/// what the title put in it in its last run (`/cache/uma_coherent*.txt`) and XCL's own /// 512 MB, 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") +/// +/// Which of the title's GPU heaps go there is `XCL_COHERENT_HEAPS`'s +/// (`kernelx::coherent_heaps_route`), so a size is kept for each setting, in a file of its own +/// (`coherent_file_name`, and per console): a size measured with every heap in the window does not apply to a +/// run that sends them to the sparse windows. A retail title's 4582 MB of heaps, stored once, +/// made windows of 4095 + 998 MB in runs that put at most 105 MB in them, each shadowed by as +/// much video memory with `XCL_UMA_SHADOW=1`. +fn coherent_file(route: &str) -> std::path::PathBuf { + crate::state::data_dir().join("cache").join(coherent_file_name(route, crate::state::config().is_series_s())) +} + +/// The file in `/cache` that keeps the coherent window's size for `route`, one number: +/// `uma_coherent.txt` for every heap in the window, the file and format builds before the +/// per-setting sizes read and write in the same data folder (a text they cannot parse gave them +/// a 512 MB window, too small for a retail title's heaps), and `uma_coherent_.txt` +/// (`:` as `_`) for the other settings, which those builds never read. +/// The Series S profile has files of its own (`_lockhart` before `.txt`, as xcl-dev/xcl#1110): +/// a title makes smaller heaps there (a retail game 2.9 GB for 4.5), and the Series X size kept +/// in the same data folder committed a window it never filled. +fn coherent_file_name(route: &str, series_s: bool) -> String { + let device = if series_s { "_lockhart" } else { "" }; + if route == ALL_HEAPS { + return format!("uma_coherent{device}.txt"); + } + format!("uma_coherent_{}{device}.txt", route.replace(':', "_")) +} + +/// The setting of `XCL_COHERENT_HEAPS` that puts every GPU heap in the coherent window (none), +/// as `kernelx::coherent_heaps_route` names it. +pub const ALL_HEAPS: &str = "all"; + +/// The bytes a `coherent_file` keeps (0: none), read as builds before read `uma_coherent.txt`. +fn stored_need(text: &str) -> usize { + text.trim().parse::().unwrap_or(0) } /// Machines with less RAM than this get an automatic coherent-window cap. @@ -835,7 +1066,8 @@ pub fn coherent_hint_for(windows: usize) -> usize { return (mb << 20).clamp(GRAIN, cap); } let cap = auto_coherent_cap(total_physical()).map_or(cap, |c| c.clamp(GRAIN, cap)); - let title = std::fs::read_to_string(coherent_file()).ok().and_then(|s| s.trim().parse::().ok()).unwrap_or(0); + let route = crate::hle::kernelx::coherent_heaps_route(); + let title = std::fs::read_to_string(coherent_file(&route)).map_or(0, |s| stored_need(&s)); // 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 @@ -869,13 +1101,46 @@ fn free_commit() -> usize { m.ullAvailPageFile as usize } -/// The title has asked for `bytes` of graphics memory XCL places in the coherent window: the -/// next run makes the window that large (this one has the size it was made with). +/// bytes of graphics memory the title asked the coherent window for in this run +static NOTED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// `coherent_file` is read and written under it +static COHERENT_FILE: Mutex<()> = Mutex::new(()); +/// A run this long has made its GPU heaps (a retail title made all of them in its first 7 s): +/// what it put in the coherent window by then may lower the stored size (`settled_need`). A run +/// that ends sooner only ever grows it: one cut short before its heaps would leave the next +/// run's window too small for them. +const SETTLED: std::time::Duration = std::time::Duration::from_secs(60); + +/// The size to store for `route` when `before` is stored and the run put `run` in the coherent +/// window by `SETTLED` (None: `before` stays). Only a setting that sends heaps to the sparse +/// windows lowers it, where a size measured with more in the window cost video memory for +/// nothing, and by half at most per run. With every heap in the window it only grows: a run that +/// stays in the menu has asked for a part of the heaps a level makes by then, and from a size +/// lowered to it the heaps of the next run that loads one would not fit and go to plain memory +/// (no image). +fn settled_need(route: &str, before: usize, run: usize) -> Option { + (route.starts_with("sparse") && run < before).then(|| run.max(before / 2)) +} + +/// The title has asked for `bytes` of graphics memory XCL places in the coherent window so far +/// in this run (0: its GPU heaps all went to the sparse windows): the next run makes the window +/// that large (this one has the size it was made with). pub fn note_coherent_need(bytes: usize) { - static NOTED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - let before = std::fs::read_to_string(coherent_file()).ok().and_then(|s| s.trim().parse::().ok()).unwrap_or(0); - if bytes > before && NOTED.fetch_max(bytes, std::sync::atomic::Ordering::Relaxed) < bytes { - let f = coherent_file(); + let prev = NOTED.fetch_max(bytes, std::sync::atomic::Ordering::Relaxed); + static SETTLE: std::sync::Once = std::sync::Once::new(); + SETTLE.call_once(|| { + let _ = std::thread::Builder::new().name("xcl-uma-coherent".into()).spawn(|| { + std::thread::sleep(SETTLED); + settle_coherent_need(); + }); + }); + if bytes <= prev { + return; + } + let _g = COHERENT_FILE.lock().unwrap(); + let route = crate::hle::kernelx::coherent_heaps_route(); + let f = coherent_file(&route); + if bytes > std::fs::read_to_string(&f).map_or(0, |s| stored_need(&s)) { if let Some(d) = f.parent() { let _ = std::fs::create_dir_all(d); } @@ -885,6 +1150,25 @@ pub fn note_coherent_need(bytes: usize) { } } +/// `SETTLED` into the run: the size stored for this run's `XCL_COHERENT_HEAPS` comes down +/// towards what the run put in the coherent window (`settled_need`). +fn settle_coherent_need() { + let _g = COHERENT_FILE.lock().unwrap(); + let run = NOTED.load(std::sync::atomic::Ordering::Relaxed); + let route = crate::hle::kernelx::coherent_heaps_route(); + let f = coherent_file(&route); + let before = std::fs::read_to_string(&f).map_or(0, |s| stored_need(&s)); + if let Some(next) = settled_need(&route, before, run) { + let _ = std::fs::write(&f, next.to_string()); + crate::xlog_info!( + "UMA: this run put {} MB of the title's graphics memory in the coherent window, {} MB were stored for '{route}' (XCL_COHERENT_HEAPS): the next run makes it {} MB", + run >> 20, + before >> 20, + (next + RUNTIME_COMMITTED_CAP).min(max_coherent_bytes(configured_runtime_windows())) >> 20 + ); + } +} + impl Uma { /// The first committed coherent window (None: none). pub fn committed_window(&self) -> Option { @@ -894,6 +1178,25 @@ impl Uma { /// The title's graphics memory (created on first use; `XCL_UMA_MB`, default 2048; /// `XCL_UMA_WINDOWS=4|8|16`, default 4, with 8/16 requiring `XCL_HEAP_WINDOWS=1`). +/// Per-window write-watched sub-ranges of mixed driver windows (`XCL_UMA_DRIVER=mixed:...`): only +/// their CUSTOM segments are write-watched, not the GPU_UPLOAD one. +static DRIVER_WATCH_SEGMENTS: Mutex)>> = Mutex::new(Vec::new()); + +/// Window `k` was remade as several driver-heap segments; only `segs` are write-watched. +pub fn set_driver_watch_segments(k: usize, segs: Vec<(usize, usize)>) { + let mut g = DRIVER_WATCH_SEGMENTS.lock().unwrap(); + if let Some(entry) = g.iter_mut().find(|(wk, _)| *wk == k) { + entry.1 = segs; + } else { + g.push((k, segs)); + } +} + +fn driver_watch_segments(k: usize) -> Option> { + let g = DRIVER_WATCH_SEGMENTS.lock().unwrap(); + g.iter().find(|(wk, _)| *wk == k).map(|(_, segs)| segs.clone()) +} + pub fn get() -> Option<&'static Uma> { GLOBAL .get_or_init(|| { @@ -902,7 +1205,15 @@ pub fn get() -> Option<&'static Uma> { let coherent = coherent_hint_for(req); let u = if req > MAX_WINDOWS { Uma::for_runtime_windows((mb << 20).max(coherent), coherent, req).or_else(|| { - crate::xlog_warn!("UMA: could not reserve {req} aligned windows below 1 TiB – falling back to {MAX_WINDOWS}"); + crate::xlog_error!( + "UMA: XCL_UMA_WINDOWS={req} asked for, but {req} aligned windows ({} GiB) could not be reserved below 1 TiB – falling back to {MAX_WINDOWS}: {}", + req * 4, + if view_windows(req) > 0 { + "GPU views of the title's memory stay outside the windows and shaders read 0 there (an empty 3D world)" + } else { + "the extra windows are not there" + } + ); let fallback = coherent_hint_for(MAX_WINDOWS); Uma::for_runtime_with((mb << 20).max(fallback), fallback) }) @@ -913,12 +1224,14 @@ pub fn get() -> Option<&'static Uma> { Some(u) => { let sparse_n = (0..u.shader_windows()).filter(|&k| u.is_sparse_window(k)).count(); let coh_n = u.windows(); + let view_n = (0..u.shader_windows()).filter(|&k| u.is_view_window(k)).count(); crate::xlog_info!( - "UMA: {} sparse VRAM window(s) ({} GiB VA) + {} coherent window(s) ({} MB) at {:#x}", + "UMA: {} sparse VRAM window(s) ({} GiB VA) + {} coherent window(s) ({} MB) + {} view window(s) for GPU views at {:#x}", sparse_n, sparse_n * 4, coh_n, u.size() >> 20, + view_n, u.base() ); } @@ -1152,6 +1465,14 @@ mod tests { assert_eq!(u.watch_regions(), vec![(u.base(), 3 * WINDOW), (u.base() + 3 * WINDOW, 16 << 20)]); } + /// Whether Windows has nothing at `p` (MEM_FREE: it may place an allocation there). + fn free_at(p: usize) -> bool { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_FREE}; + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + let n = unsafe { VirtualQuery(p as *const std::ffi::c_void, &mut m, std::mem::size_of::()) }; + n != 0 && m.State == MEM_FREE + } + #[test] fn runtime_layout_supports_eight_and_sixteen_heap_windows() { for windows in [8usize, MAX_HEAP_WINDOWS] { @@ -1166,8 +1487,12 @@ mod tests { assert!(u.is_sparse_window(k), "window {k} should be sparse"); } assert_eq!(u.committed_window(), Some(MAX_RUNTIME_SPARSE_WINDOWS)); + // 8 windows: the trailing windows stay unreserved; 16: views right after the coherent + // window, the rest kept empty (and reserved: `sixteen_windows_reserve_the_whole_aperture`) + let views = MAX_RUNTIME_SPARSE_WINDOWS + 1..MAX_RUNTIME_SPARSE_WINDOWS + 1 + view_windows(windows); for k in (MAX_RUNTIME_SPARSE_WINDOWS + 1)..windows { - assert!(!u.is_sparse_window(k) && !u.is_committed_window(k), "unused trailing window {k} stays unreserved"); + assert!(!u.is_sparse_window(k) && !u.is_committed_window(k), "window {k} holds no CPU memory"); + assert_eq!(u.is_view_window(k), views.contains(&k), "window {k}: a view window in 16 only"); } let c = u.alloc(0x2_0000, 0).unwrap() as usize; assert_eq!(u.window_of(c), Some(MAX_RUNTIME_SPARSE_WINDOWS)); @@ -1192,6 +1517,169 @@ mod tests { } } + /// The Series X run's plan (`XCL_UMA_WINDOWS=16`, 4095 MB, a 512 MB coherent window) and where + /// its first graphics memory goes: 3 sparse windows, the coherent one, 6 view windows, 6 + /// empty, and its GPU heaps of 1172 / 2199 / 563 / 596 MB and its 38 MB view heap at the + /// addresses that run logged (0xf2e00000 into window 0). Nothing of the title memory size + /// goes into the plan: the Series S profile gets the same one. + #[test] + fn the_series_x_plan_is_pinned() { + let u = Uma::for_runtime_windows(4095 << 20, RUNTIME_COMMITTED_CAP, MAX_HEAP_WINDOWS).expect("16-window aperture"); + let b = u.base(); + assert_eq!(b % (MAX_HEAP_WINDOWS * WINDOW), 0); + use WindowKind::*; + let mut kinds = vec![Sparse, Sparse, Sparse, Committed(512 << 20)]; + kinds.extend([View; VIEW_WINDOWS]); + kinds.extend([None; 6]); + assert_eq!(u.kinds, kinds); + assert_eq!((u.shader_windows(), u.windows(), u.size()), (16, 1, 512 << 20)); + assert_eq!(u.desc_range(), Some((b + GRAIN, b + GRAIN + DESC_HEADROOM))); + assert_eq!((u.title_sparse_start(), u.sparse_end()), (b + 0x2001_0000, b + 3 * WINDOW)); + for (p, k) in [(0xf2e0_0000, Some(0)), (WINDOW + 0x140_0000, Some(1)), (3 * WINDOW, Some(3)), (3 * WINDOW + (512 << 20), Option::None), (4 * WINDOW, Some(4)), (10 * WINDOW, Option::None)] { + assert_eq!(u.window_of(b + p), k, "{p:#x}"); + } + // the GPU heaps (2 MB pages, rounded as `kernelx::VirtualAlloc` does), then the view heap + let at: Vec = [1172usize, 2199, 563, 596].iter().map(|&mb| u.sparse_alloc((mb << 20).next_multiple_of(2 << 20), 2 << 20).unwrap().0 - b).collect(); + assert_eq!(at, [0x2020_0000, 0x6960_0000, WINDOW, WINDOW + (564 << 20)]); + assert_eq!(u.sparse_alloc(0x260_0000, GRAIN).map(|(a, _)| a - b), Some(0xf2e0_0000)); + // the home of the Series X run's page pool (99776 pages: more than a window) goes where it went + let pool = 99776 * GRAIN; + let above = u.sparse_alloc_above(pool, GRAIN); + assert_eq!(above.map(|(a, n)| (a - b, n)), Some((WINDOW + (1160 << 20), pool))); + assert_eq!(u.sparse_release(above.unwrap().0), Some(pool)); + assert_eq!(u.sparse_alloc(pool, GRAIN), above); + } + + /// Memory no shader addresses with 32 bits keeps out of window 0 while windows 1+ have room, + /// and gets window 0 when they have none; above a window it goes as `sparse_alloc`'s. + #[test] + fn sparse_alloc_above_keeps_window_0_for_the_title() { + let u = Uma::for_runtime_windows(16 << 20, RUNTIME_COMMITTED_CAP, MAX_HEAP_WINDOWS).expect("16-window aperture"); + let b = u.base(); + let (h, n) = u.sparse_alloc_above(664 << 20, GRAIN).unwrap(); + assert_eq!((h, n), (b + WINDOW, 664 << 20)); + // window 0 still has the room a 38 MB view heap needs after 2.9 GB of GPU heaps + let heaps = u.sparse_alloc(2892 << 20, 2 << 20).unwrap(); + assert_eq!(u.window_of(heaps.0), Some(0)); + assert_eq!(u.sparse_alloc(0x260_0000, GRAIN).map(|(a, _)| u.window_of(a)), Some(Some(0))); + let used = (2892 << 20) + 0x260_0000; + assert_eq!(u.sparse_free_in(0), (WINDOW - 0x2001_0000 - used, WINDOW - 0x2020_0000 - used)); + assert_eq!(u.sparse_free_in(1), (WINDOW - (664 << 20), WINDOW - (664 << 20))); + // windows 1..2 full: window 0 + let rest = u.sparse_reserve(2 * WINDOW - (664 << 20)).unwrap(); + assert_eq!(u.window_of(rest), Some(1)); + let (w0, _) = u.sparse_alloc_above(GRAIN, GRAIN).unwrap(); + assert_eq!(u.window_of(w0), Some(0)); + assert!(w0 >= u.title_sparse_start(), "never the descriptor headroom"); + assert!(u.sparse_alloc_above(WINDOW + GRAIN, GRAIN).is_none(), "no room above a window"); + } + + /// After physical page homes (`sparse_alloc_above`) take the start of window 1, a title + /// `sparse_reserve` of at most one window that no longer fits in window 1 lands wholly in + /// window 2 instead of straddling the window 1 / window 2 boundary; smaller reservations + /// still fit in window 1, fragmented windows 1+ still fall back to cross-window placement + /// without cluttering window 0, and overflow sizes return `None`. + #[test] + fn sparse_reserve_keeps_single_window_reservations_inside_one_window() { + let u = Uma::for_runtime_windows(16 << 20, RUNTIME_COMMITTED_CAP, MAX_HEAP_WINDOWS).expect("16-window aperture"); + let b = u.base(); + // Series S layout: 2892 MiB GPU heaps + 38 MiB view heap in window 0, 664 MiB homes in window 1. + let (heaps, _) = u.sparse_alloc(2892 << 20, 2 << 20).unwrap(); + let (homes, _) = u.sparse_alloc_above(664 << 20, GRAIN).unwrap(); + let (view_heap, _) = u.sparse_alloc(0x260_0000, GRAIN).unwrap(); + assert_eq!((u.window_of(heaps), u.window_of(homes), u.window_of(view_heap)), (Some(0), Some(1), Some(0))); + + // A ~3.42 GiB reservation exceeds window 1's remaining 3432 MiB and lands wholly in window 2. + let arena = 3500 << 20; + let r = u.sparse_reserve(arena).expect("single-window reservation in window 2"); + assert_eq!(r, b + 2 * WINDOW); + assert_eq!((u.window_of(r), u.window_of(r + arena - 1)), (Some(2), Some(2))); + + // Smaller reservations still fit in window 1's remaining tail without touching window 0. + let small = 256 << 20; + let s = u.sparse_reserve(small).expect("fits in window 1 tail"); + assert_eq!((u.window_of(s), u.window_of(s + small - 1)), (Some(1), Some(1))); + + for p in [s, r, homes] { + assert!(u.sparse_release(p).is_some()); + } + + // Fragmented windows 1+ (2 GiB free at end of window 1 + 2 GiB free at start of window 2): + // a 3 GiB reservation still succeeds via cross-window fallback in windows 1+ without touching window 0. + let (w1_head, _) = u.sparse_alloc_above(2 << 30, GRAIN).unwrap(); + let (w2_head, _) = u.sparse_alloc_in(2, 2 << 30, GRAIN).unwrap(); + let (w2_tail, _) = u.sparse_alloc_in(2, 2 << 30, GRAIN).unwrap(); + assert_eq!(u.sparse_release(w2_head), Some(2 << 30)); + let cross = 3 << 30; + let c = u.sparse_reserve(cross).expect("cross-window fallback in windows 1+"); + assert_eq!((u.window_of(c), u.window_of(c + cross - 1)), (Some(1), Some(2))); + + assert_eq!(u.sparse_reserve(usize::MAX), None); + + for p in [c, w2_tail, w1_head, view_heap, heaps] { + assert!(u.sparse_release(p).is_some()); + } + assert_eq!(u.sparse_used(), 0); + } + + /// With 16 windows nothing of Windows' lands in the aperture: shaders read every window of + /// it, and a window without memory of its own once read whatever Windows had put there. + #[test] + fn sixteen_windows_reserve_the_whole_aperture() { + let u = Uma::for_runtime_windows(16 << 20, RUNTIME_COMMITTED_CAP, MAX_HEAP_WINDOWS).expect("16-window aperture"); + let base = u.base(); + let coh = u.committed_window().unwrap(); + let (c, c_len) = u.window(coh); + // each window's start and end, the coherent window's uncommitted tail + let mut probes: Vec = (0..MAX_HEAP_WINDOWS).flat_map(|k| [base + k * WINDOW, base + (k + 1) * WINDOW - 1]).collect(); + probes.push(c + c_len); + for &p in &probes { + assert!(!free_at(p), "{:#x} (window {}) is free: Windows may place memory there", p, (p - base) / WINDOW); + } + // the view windows and the empty ones are no CPU memory and nobody's write-watched region + for k in coh + 1..MAX_HEAP_WINDOWS { + let p = base + k * WINDOW + 0x1234; + assert!(!u.contains(p) && !u.is_sparse(p) && !u.is_committed(p) && !u.is_gpu_copy(p) && !u.is_title_address(p), "window {k}"); + assert!(!u.is_sparse_window(k) && !u.is_committed_window(k)); + assert_eq!(u.window_of(p).is_some(), u.is_view_window(k), "window {k}: only view windows are windows of their own"); + } + assert!(u.watch_regions().iter().all(|&(a, n)| a + n <= c + c_len), "{:x?}", u.watch_regions()); + } + + /// GPU views go to the view windows, window-aligned: one of 24 GiB fills them, and its + /// release gives the range back whole. The CPU view never goes there. + #[test] + fn view_windows_hold_gpu_views() { + let u = Uma::for_runtime_windows(16 << 20, RUNTIME_COMMITTED_CAP, MAX_HEAP_WINDOWS).expect("16-window aperture"); + let first = (0..MAX_HEAP_WINDOWS).find(|&k| u.is_view_window(k)).expect("view windows"); + assert_eq!((first..MAX_HEAP_WINDOWS).filter(|&k| u.is_view_window(k)).count(), VIEW_WINDOWS); + let g = u.view_reserve(VIEW_WINDOWS * WINDOW).expect("24 GiB in the view windows"); + assert_eq!(g, u.base() + first * WINDOW); + assert!(u.view_reserve(GRAIN).is_none(), "the views are full"); + for x in [0, 0x1234, 5 * WINDOW + 0x10_0000, VIEW_WINDOWS * WINDOW - 1] { + assert!(u.is_view(g + x) && u.is_title_address(g + x), "{x:#x}"); + assert_eq!(u.window_of(g + x), Some(first + x / WINDOW)); + assert!(!u.contains(g + x) && !u.is_sparse(g + x), "{x:#x}: the CPU cannot touch a GPU view"); + assert_eq!(u.view_reservation(g + x), Some((g, VIEW_WINDOWS * WINDOW))); + } + // a CPU view of the same size does not fit the sparse windows and never takes the views + assert!(u.sparse_reserve(VIEW_WINDOWS * WINDOW).is_none()); + assert!(u.sparse_alloc(2 * WINDOW, GRAIN).is_some_and(|(a, n)| a + n <= u.base() + MAX_RUNTIME_SPARSE_WINDOWS * WINDOW)); + assert_eq!(u.view_release(g), Some(VIEW_WINDOWS * WINDOW)); + assert_eq!(u.view_release(g), None); + assert!(!u.is_title_address(g) && u.is_view(g)); + // smaller views start at a window each, and their room comes back merged + let a = u.view_reserve(GRAIN).unwrap(); + let b = u.view_reserve(WINDOW + GRAIN).unwrap(); + assert_eq!((a, b), (g, g + WINDOW)); + assert_eq!(u.view_release(a), Some(GRAIN)); + assert_eq!(u.view_release(b), Some(WINDOW + GRAIN)); + assert_eq!(u.view_reserve(VIEW_WINDOWS * WINDOW), Some(g)); + // no view windows below 16 + let four = Uma::for_runtime(16 << 20).unwrap(); + assert!(four.view_reserve(GRAIN).is_none() && (0..MAX_WINDOWS).all(|k| !four.is_view_window(k))); + } + #[test] fn expanded_heap_window_shaders_translate_and_validate() { use crate::gpu::dxil::kernel::{translate, KernelOptions}; @@ -1215,8 +1703,9 @@ mod tests { fn expanded_runtime_layout_splits_large_coherent_heaps_across_multiple_windows() { // Legacy 4-window layout stays capped at 1 coherent window (4095 MiB). assert_eq!(coherent_window_sizes(6 << 30, 6 << 30, MAX_WINDOWS), vec![MAX_SIZE]); - // 8- and 16-window layouts split >4 GiB coherent heaps across up to 5 / 13 committed windows - // with exact remainder sizing while keeping sparse windows capped at 3 (12 GiB). + // 8- and 16-window layouts split >4 GiB coherent heaps across up to 5 / 7 committed windows + // with exact remainder sizing while keeping sparse windows capped at 3 (12 GiB) and, with + // 16, the 6 view windows free. let want = MAX_SIZE + (512 << 20); for w in [8usize, MAX_HEAP_WINDOWS] { assert_eq!(coherent_window_sizes(want, want, w), vec![MAX_SIZE, 512 << 20]); @@ -1224,9 +1713,13 @@ mod tests { } assert_eq!(coherent_window_sizes(20 << 30, 20 << 30, 8).len(), 5); assert_eq!(coherent_window_sizes(20 << 30, 20 << 30, MAX_HEAP_WINDOWS).len(), 6); + // a coherent need past 7 windows (as a `coherent_file` may keep) stops at 7: windows + // 10..15 stay the views' + assert_eq!(coherent_window_sizes(40 << 30, 40 << 30, MAX_HEAP_WINDOWS), vec![MAX_SIZE; 7]); assert_eq!(max_coherent_windows(MAX_WINDOWS), 1); assert_eq!(max_coherent_windows(8), 5); - assert_eq!(max_coherent_windows(MAX_HEAP_WINDOWS), 13); + assert_eq!(max_coherent_windows(MAX_HEAP_WINDOWS), MAX_HEAP_WINDOWS - MAX_RUNTIME_SPARSE_WINDOWS - VIEW_WINDOWS); + assert_eq!(max_coherent_bytes(MAX_HEAP_WINDOWS), 7 * MAX_SIZE); // Multi-window Uma::alloc seamlessly spills into the 2nd committed window. let u = Uma::with_windows(2, 8 << 20).unwrap(); let a = u.alloc(6 << 20, GRAIN).unwrap() as usize; @@ -1235,6 +1728,51 @@ mod tests { assert_eq!(u.window_of(b), Some(1)); assert!(u.free(a) && u.free(b)); } + + /// The coherent window's size is kept per `XCL_COHERENT_HEAPS` setting: the 4582 MB a run + /// with every GPU heap in the window stored in `uma_coherent.txt` does not size the window of + /// a run that sends them to the sparse windows, which has a file of its own. The file of every + /// heap stays one number, the only text builds before this one read in the same data folder. + #[test] + fn the_stored_coherent_need_is_the_one_of_the_heaps_setting() { + let x = |route| coherent_file_name(route, false); + assert_eq!(x(ALL_HEAPS), "uma_coherent.txt", "the file builds before read and write"); + assert_eq!(x("sparse:16"), "uma_coherent_sparse_16.txt", "no ':' in a Windows file name"); + assert_eq!(x("sparse"), "uma_coherent_sparse.txt"); + assert_eq!(x("off"), "uma_coherent_off.txt"); + // the Series S profile's own files, beside the Series X ones + assert_eq!(coherent_file_name(ALL_HEAPS, true), "uma_coherent_lockhart.txt"); + assert_eq!(coherent_file_name("sparse:16", true), "uma_coherent_sparse_16_lockhart.txt"); + let names: Vec = [false, true].iter().flat_map(|&s| [ALL_HEAPS, "off", "sparse", "sparse:16", "sparse:64"].map(|r| coherent_file_name(r, s))).collect(); + assert!(names.iter().enumerate().all(|(i, n)| !names[..i].contains(n)), "one file per setting and console: {names:?}"); + // what is written is what builds before wrote (`bytes.to_string()`) and parse + // (`s.trim().parse::()`) + let stored = (4582usize << 20).to_string(); + assert_eq!(stored.trim().parse::(), Ok(4582 << 20)); + assert_eq!(stored_need(&stored), 4582 << 20); + assert_eq!(stored_need(&format!("{stored}\r\n")), 4582 << 20); + assert_eq!(stored_need(""), 0); + // a text that is no number reads as none, as builds before read it: it is written over + // with a number at the run's first GPU heap + assert_eq!(stored_need("4804575232 all\n105000000 sparse:16\n"), 0); + } + + /// A run lowers the stored coherent size only with a setting that sends GPU heaps to the + /// sparse windows, and by half at most: with every heap in the window, a run that stayed in + /// the menu (1 GB asked of a full run's 4582 MB) leaves it as it is. + #[test] + fn only_the_sparse_heaps_settings_lower_the_stored_coherent_need() { + let full = 4582usize << 20; + assert_eq!(settled_need(ALL_HEAPS, full, 1 << 30), None, "the next run that loads a level needs all of it"); + assert_eq!(settled_need(ALL_HEAPS, full, 0), None); + assert_eq!(settled_need("off", full, 0), None); + assert_eq!(settled_need("sparse:16", full, 105 << 20), Some(full / 2), "half at most per run"); + assert_eq!(settled_need("sparse:16", full / 2, 105 << 20), Some(full / 4)); + assert_eq!(settled_need("sparse:16", 200 << 20, 105 << 20), Some(105 << 20)); + assert_eq!(settled_need("sparse", 64 << 20, 0), Some(32 << 20)); + assert_eq!(settled_need("sparse:16", 105 << 20, 105 << 20), None, "nothing to lower"); + assert_eq!(settled_need("sparse:16", 105 << 20, 200 << 20), None, "growing is note_coherent_need's"); + } } #[cfg(test)] diff --git a/crates/xcl/src/gpu/xbox.rs b/crates/xcl/src/gpu/xbox.rs index c268bf9bbf..68cd51cd71 100644 --- a/crates/xcl/src/gpu/xbox.rs +++ b/crates/xcl/src/gpu/xbox.rs @@ -144,6 +144,19 @@ impl Fssm { } } + /// The constant data blocks that follow program `p` in the code region, as the program + /// addresses them (`s_getpc_b64`: from its own start): (address, dwords of the block). + pub fn rodata(&self, p: &Program) -> Vec<(u32, Vec)> { + self.data_blocks + .iter() + .filter(|b| b.offset >= p.offset + p.len) + .filter_map(|b| { + let bytes = self.data.get(b.offset..b.offset + b.len)?; + Some(((b.offset - p.offset) as u32, bytes.chunks_exact(4).map(|w| u32::from_le_bytes(w.try_into().unwrap())).collect())) + }) + .collect() + } + /// The header says the code is for 32-lane waves: bit 5 of the flags word at +0xD4 /// (measured on a retail pack: set for every program with 32-bit EXEC writes, clear for /// every one with 64-bit ones). An unused field (0xDEADBEEF) says nothing. diff --git a/crates/xcl/src/hle/api_cost.rs b/crates/xcl/src/hle/api_cost.rs new file mode 100644 index 0000000000..dc7bf549ba --- /dev/null +++ b/crates/xcl/src/hle/api_cost.rs @@ -0,0 +1,392 @@ +//! Diagnostic (`XCL_ACTIVITY`, and `pso_async`'s pipeline line): the time the title's threads +//! spend in some of XCL's calls while it loads, summed over the threads. +//! +//! With `XCL_LOOK_STATS=2` also the calls a frame is made of on the thread that makes the title's +//! submits (its submits, presents and waits), and every call counted on that thread apart: what +//! it does in a frame besides submitting, added up. + +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +#[derive(Clone, Copy)] +pub enum Call { + PlacedTexture, + PlacedBuffer, + PhysicalPages, + Memory, + Pipeline, + /// a bind's wait for a pipeline still being built (`pso_async::resolve_wait`) + PipelineWait, + /// the title's ExecuteCommandLists, whole (`submit_cost::done`; `XCL_LOOK_STATS=2` only, as + /// the ones below) + Submit, + /// PresentX, or a present of the fallback's at a console method + Present, + /// a present's wait for the copy of the frame before + PresentCopyWait, + WaitFrameEvent, + /// the title's blocking waits for a fence (SetEventOnCompletion without an event) + FenceWait, + /// copies back landed for the title's look at a fence (`sparse::settle_readbacks_within`) + FenceSettle, + /// draw recording on command lists (`DrawInstanced`, `DrawIndexedInstanced`, `DrawIndexedX`, + /// `DispatchMesh`, non-dispatch `ExecuteIndirect`) + DrawRecord, + /// compute dispatch recording (`Dispatch`, `DispatchX`, dispatch `ExecuteIndirect`) + DispatchRecord, + /// root signatures/arguments, pipeline state, descriptor heaps, IA buffers, render targets + BindState, + /// device view creation and descriptor copies + ViewDescriptor, + /// GPU-view tile asks (`view_want::want`; sub-timer, may nest inside draw/dispatch/bind/view/copy) + ViewWant, + /// resource barriers, UAV barriers, and console cache/pipeline flushes + ListBarrier, + /// copies, fills, clears, resolves, and bottom-of-pipe writes + ListCopy, + /// command list Close/Reset and command allocator Reset + ListLifecycle, +} + +pub const CALLS: [(Call, &str); 20] = [ + (Call::PlacedTexture, "placed textures"), + (Call::PlacedBuffer, "placed buffers"), + (Call::PhysicalPages, "physical page calls"), + (Call::Memory, "memory calls"), + (Call::Pipeline, "pipelines"), + (Call::PipelineWait, "waits for pipelines being built"), + (Call::Submit, "ExecuteCommandLists"), + (Call::Present, "presents"), + (Call::PresentCopyWait, "waits of a present for the last frame's copy"), + (Call::WaitFrameEvent, "WaitFrameEventX"), + (Call::FenceWait, "blocking fence waits"), + (Call::FenceSettle, "copies back settled at fence looks"), + (Call::DrawRecord, "draw recording"), + (Call::DispatchRecord, "dispatch recording"), + (Call::BindState, "state and root bindings"), + (Call::ViewDescriptor, "view and descriptor calls"), + (Call::ViewWant, "GPU-view tile asks"), + (Call::ListBarrier, "barriers and flushes"), + (Call::ListCopy, "copies, clears, and memory ops"), + (Call::ListLifecycle, "list close and reset"), +]; + +/// Calls that nest inside another timed call and must not be added into the submitting thread's +/// non-overlapping completed-call total. +pub const fn is_sub_call(call: Call) -> bool { + matches!(call, Call::PresentCopyWait | Call::PipelineWait | Call::ViewWant) +} + +/// Coherent single-writer `(count, ns)` counter pair protected by a seqlock generation +/// (odd while updating, even when quiescent). Safe for `ON_SUBMITTER` because `SUBMITTER` +/// latches at most one thread ID via `compare_exchange(0, tid)` for the process lifetime. +struct CounterPair { + seq: AtomicU64, + count: AtomicU64, + ns: AtomicU64, +} + +impl CounterPair { + const fn new() -> Self { + Self { + seq: AtomicU64::new(0), + count: AtomicU64::new(0), + ns: AtomicU64::new(0), + } + } + + fn add_single_writer(&self, ns: u64) { + let g = self.seq.load(Ordering::Relaxed); + self.seq.store(g.wrapping_add(1), Ordering::Relaxed); + std::sync::atomic::fence(Ordering::Release); + self.count.store(self.count.load(Ordering::Relaxed).wrapping_add(1), Ordering::Relaxed); + self.ns.store(self.ns.load(Ordering::Relaxed).saturating_add(ns), Ordering::Relaxed); + self.seq.store(g.wrapping_add(2), Ordering::Release); + } + + fn load_coherent(&self) -> (u64, u64) { + loop { + let g1 = self.seq.load(Ordering::Acquire); + if g1 & 1 != 0 { + std::hint::spin_loop(); + continue; + } + let count = self.count.load(Ordering::Relaxed); + let ns = self.ns.load(Ordering::Relaxed); + std::sync::atomic::fence(Ordering::Acquire); + let g2 = self.seq.load(Ordering::Relaxed); + if g1 == g2 { + return (count, ns / 1000); + } + std::hint::spin_loop(); + } + } +} + +/// calls, nanoseconds (sub-µs calls accumulate without per-call truncation; exposed as µs) +static COST: [[AtomicU64; 2]; CALLS.len()] = [const { [AtomicU64::new(0), AtomicU64::new(0)] }; CALLS.len()]; +/// the same on the submitting thread (`SUBMITTER`), read coherently via `CounterPair`'s seqlock +static ON_SUBMITTER: [CounterPair; CALLS.len()] = [const { CounterPair::new() }; CALLS.len()]; +/// the thread that makes the title's submits (0: none seen, or `XCL_LOOK_STATS` is not 2) +static SUBMITTER: AtomicU32 = AtomicU32::new(0); + +/// Counts the call it stands in when it goes. +pub struct Timer { + pub call: Call, + start: Instant, +} + +pub fn time(call: Call) -> Timer { + Timer { call, start: Instant::now() } +} + +/// Times `call` only when `on` is true (zero clock, TLS, or atomic overhead when false). +#[inline] +pub fn time_if(on: bool, call: Call) -> Option { + on.then(|| time(call)) +} + +impl Drop for Timer { + fn drop(&mut self) { + add(self.call, self.start.elapsed()); + } +} + +fn this_thread() -> u32 { + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() } +} + +/// A call that took `d`. +pub fn add(call: Call, d: Duration) { + let ns = d.as_nanos().min(u64::MAX as u128) as u64; + let idx = call as usize; + let c = &COST[idx]; + c[0].fetch_add(1, Ordering::Relaxed); + c[1].fetch_add(ns, Ordering::Relaxed); + let s = SUBMITTER.load(Ordering::Acquire); + if s != 0 && s == this_thread() { + ON_SUBMITTER[idx].add_single_writer(ns); + } +} + +/// The calling thread made one of the title's submits: the first thread to is the submitting +/// thread from then on (a retail title's world made every submit and present on one thread). +/// Called with `XCL_LOOK_STATS=2` only. +pub fn note_submitter() { + let _ = SUBMITTER.compare_exchange(0, this_thread(), Ordering::AcqRel, Ordering::Acquire); +} + +/// (calls, microseconds) so far, in the order of `CALLS`. +pub fn totals() -> [(u64, u64); CALLS.len()] { + std::array::from_fn(|k| (COST[k][0].load(Ordering::Relaxed), COST[k][1].load(Ordering::Relaxed) / 1000)) +} + +/// Coherent `(calls, microseconds)` snapshot of the submitting thread, in the order of `CALLS`. +pub fn submitter_totals() -> [(u64, u64); CALLS.len()] { + std::array::from_fn(|k| ON_SUBMITTER[k].load_coherent()) +} + +/// Formats per-category `(calls, ms)` deltas across all threads since `before`, retaining any +/// category with a nonzero count **or** duration delta so multi-writer snapshots never drop +/// completed duration when count and duration are observed on separate ticks. +pub fn all_threads_summary_parts(now: &[(u64, u64)], before: &[(u64, u64)]) -> Vec { + CALLS + .iter() + .zip(now.iter().zip(before)) + .filter_map(|(c, (n, o))| { + let dc = n.0.saturating_sub(o.0); + let dus = n.1.saturating_sub(o.1); + if dc == 0 && dus == 0 { + return None; + } + Some(format!("{dc} {} in {} ms", c.1, dus / 1000)) + }) + .collect() +} + +/// Formats durations of submitting-thread calls **completed** since `before` alongside the +/// sample's elapsed `window_ms`. Summing only top-level calls avoids double-counting nested +/// sub-timers (`is_sub_call`). Because a call's full duration is published when it completes, a +/// call that started before the window and finished inside it can make the completed total exceed +/// `window_ms`; accordingly no in-window "untimed" remainder is claimed. Any nonzero duration +/// delta is accounted even if its count delta is zero. +pub fn submitter_summary_line(now: &[(u64, u64)], before: &[(u64, u64)], window_ms: u64) -> Option { + let mut parts = Vec::new(); + let mut completed_us = 0u64; + for (c, (n, o)) in CALLS.iter().zip(now.iter().zip(before)) { + let dc = n.0.saturating_sub(o.0); + let dus = n.1.saturating_sub(o.1); + if dc == 0 && dus == 0 { + continue; + } + if !is_sub_call(c.0) { + completed_us = completed_us.saturating_add(dus); + } + parts.push(format!("{dc} {} in {} ms", c.1, dus / 1000)); + } + if parts.is_empty() { + return None; + } + let completed_ms = completed_us / 1000; + Some(format!("{}; completed {completed_ms} ms (window {window_ms} ms)", parts.join(", "))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_call_is_counted_with_its_time() { + // (in the order of the enum: a name stands for its own count) + assert!(CALLS.iter().enumerate().all(|(k, c)| c.0 as usize == k)); + let before = totals()[Call::Memory as usize]; + { + let mut t = time(Call::Pipeline); + t.call = Call::Memory; + std::thread::sleep(std::time::Duration::from_millis(2)); + } + let after = totals()[Call::Memory as usize]; + assert!(after.0 > before.0 && after.1 >= before.1 + 2000); + } + + #[test] + fn the_submitting_thread_has_its_own_count() { + // (no other test makes a submitter: this thread is it) + note_submitter(); + let me = this_thread(); + assert_eq!(SUBMITTER.load(Ordering::Relaxed), me); + std::thread::spawn(note_submitter).join().unwrap(); + assert_eq!(SUBMITTER.load(Ordering::Relaxed), me, "the first thread stays the submitting one"); + let k = Call::FenceSettle as usize; + let (all, mine) = (totals()[k], submitter_totals()[k]); + add(Call::FenceSettle, Duration::from_micros(300)); + std::thread::spawn(|| add(Call::FenceSettle, Duration::from_micros(50))).join().unwrap(); + let (all2, mine2) = (totals()[k], submitter_totals()[k]); + assert_eq!((all2.0 - all.0, all2.1 - all.1), (2, 350)); + assert_eq!((mine2.0 - mine.0, mine2.1 - mine.1), (1, 300)); + } + + #[test] + fn sub_microsecond_calls_accumulate_without_truncation() { + let k = Call::ListBarrier as usize; + let before = totals()[k]; + for _ in 0..1000 { + add(Call::ListBarrier, Duration::from_nanos(500)); + } + let after = totals()[k]; + assert_eq!(after.0 - before.0, 1000); + assert_eq!(after.1 - before.1, 500); + } + + #[test] + fn time_if_disabled_adds_zero_counts_and_zero_time() { + let k = Call::ListLifecycle as usize; + let before_all = totals()[k]; + let before_sub = submitter_totals()[k]; + { + let guard = time_if(false, Call::ListLifecycle); + assert!(guard.is_none()); + } + assert_eq!(totals()[k], before_all); + assert_eq!(submitter_totals()[k], before_sub); + } + + #[test] + fn submitter_summary_excludes_sub_calls_and_reports_completed_window() { + let before = [(0u64, 0u64); CALLS.len()]; + assert_eq!(submitter_summary_line(&before, &before, 2000), None); + + let mut now = before; + // Top-level calls: 100 + 250 + 50 = 400 ms completed + now[Call::Submit as usize] = (10, 100_000); + now[Call::DrawRecord as usize] = (500, 250_000); + now[Call::BindState as usize] = (2000, 50_000); + // Nested sub-calls: displayed, but excluded from `completed` + now[Call::PipelineWait as usize] = (3, 40_000); + now[Call::PresentCopyWait as usize] = (2, 30_000); + now[Call::ViewWant as usize] = (400, 90_000); + + let line = submitter_summary_line(&now, &before, 2000).unwrap(); + assert!(line.contains("10 ExecuteCommandLists in 100 ms"), "{line}"); + assert!(line.contains("500 draw recording in 250 ms"), "{line}"); + assert!(line.contains("2000 state and root bindings in 50 ms"), "{line}"); + assert!(line.contains("3 waits for pipelines being built in 40 ms"), "{line}"); + assert!(line.contains("2 waits of a present for the last frame's copy in 30 ms"), "{line}"); + assert!(line.contains("400 GPU-view tile asks in 90 ms"), "{line}"); + assert!(line.ends_with("; completed 400 ms (window 2000 ms)"), "{line}"); + assert!(!line.contains("untimed"), "{line}"); + assert!(is_sub_call(Call::PresentCopyWait) && is_sub_call(Call::PipelineWait) && is_sub_call(Call::ViewWant)); + assert!(!is_sub_call(Call::Submit) && !is_sub_call(Call::DrawRecord) && !is_sub_call(Call::FenceWait)); + } + + #[test] + fn summary_retains_nonzero_duration_delta_when_count_delta_is_zero() { + // Deterministic torn-snapshot sequence `(0,0) -> (1,0) -> (1,400_000)` on a top-level + // call and `(0,0) -> (1,0) -> (1,50_000)` on a nested sub-call: the second tick must + // retain the 400 ms duration in both `all_threads_summary_parts` and `submitter_summary_line`, + // without double-counting the nested sub-call into `completed`. + let snap0 = [(0u64, 0u64); CALLS.len()]; + let mut snap1 = snap0; + snap1[Call::FenceWait as usize] = (1, 0); + snap1[Call::ViewWant as usize] = (1, 0); + let mut snap2 = snap1; + snap2[Call::FenceWait as usize] = (1, 400_000); + snap2[Call::ViewWant as usize] = (1, 50_000); + + let sub1 = submitter_summary_line(&snap1, &snap0, 2000).unwrap(); + assert!(sub1.contains("1 blocking fence waits in 0 ms"), "{sub1}"); + assert!(sub1.contains("1 GPU-view tile asks in 0 ms"), "{sub1}"); + assert!(sub1.ends_with("; completed 0 ms (window 2000 ms)"), "{sub1}"); + + let sub2 = submitter_summary_line(&snap2, &snap1, 2000).unwrap(); + assert!(sub2.contains("0 blocking fence waits in 400 ms"), "{sub2}"); + assert!(sub2.contains("0 GPU-view tile asks in 50 ms"), "{sub2}"); + assert!(sub2.ends_with("; completed 400 ms (window 2000 ms)"), "{sub2}"); + + let all2 = all_threads_summary_parts(&snap2, &snap1); + assert!(all2.iter().any(|s| s == "0 blocking fence waits in 400 ms"), "{all2:?}"); + assert!(all2.iter().any(|s| s == "0 GPU-view tile asks in 50 ms"), "{all2:?}"); + } + + #[test] + fn submitter_counter_pair_snapshots_are_coherent_under_concurrent_writes() { + use std::sync::Arc; + const N: u64 = 50_000; + const STEP_NS: u64 = 10_000_000; // 10_000 us per call + let pair = Arc::new(CounterPair::new()); + let writer_pair = Arc::clone(&pair); + let writer = std::thread::spawn(move || { + for _ in 0..N { + writer_pair.add_single_writer(STEP_NS); + } + }); + let mut samples = 0u64; + loop { + let (count, us) = pair.load_coherent(); + assert_eq!(us, count * (STEP_NS / 1000), "torn snapshot observed: count={count}, us={us}"); + samples += 1; + if count == N { + break; + } + } + writer.join().unwrap(); + assert!(samples >= 1); + assert_eq!(pair.load_coherent(), (N, N * (STEP_NS / 1000))); + } + + #[test] + fn submitter_summary_describes_straddling_completed_call_without_untimed_claim() { + // Synthetic 2.5 s blocking fence wait starting at t=0.0 s and completing at t=2.5 s + // across two 2.0 s activity ticks: tick 1 sees no completed calls; tick 2 reports the + // completed 2500 ms call alongside the 2000 ms window without claiming "0 ms untimed". + let snap0 = [(0u64, 0u64); CALLS.len()]; + let tick1_snap = snap0; + assert_eq!(submitter_summary_line(&tick1_snap, &snap0, 2000), None); + + let mut tick2_snap = tick1_snap; + tick2_snap[Call::FenceWait as usize] = (1, 2_500_000); + let tick2 = submitter_summary_line(&tick2_snap, &tick1_snap, 2000).unwrap(); + assert_eq!(tick2, "1 blocking fence waits in 2500 ms; completed 2500 ms (window 2000 ms)"); + assert!(!tick2.contains("untimed"), "{tick2}"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 7804053720..b115958321 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -150,11 +150,11 @@ impl BackingProbe { } unsafe fn free(&self) -> bool { - self.users.is_empty() && self.submit_pins == 0 && self.marks.iter().all(|(_, fence, value)| fence.GetCompletedValue() >= *value) + self.users.is_empty() && self.submit_pins == 0 && self.marks.iter().all(|(_, fence, value)| super::real::fence_completed(fence) >= *value) } unsafe fn in_flight(&self) -> bool { - self.submit_pins != 0 || self.marks.iter().any(|(_, fence, value)| fence.GetCompletedValue() < *value) + self.submit_pins != 0 || self.marks.iter().any(|(_, fence, value)| super::real::fence_completed(fence) < *value) } fn matches(&self, backing: &Backing) -> bool { @@ -459,7 +459,7 @@ impl SubmissionReceipt { } pub(super) fn completed_value(&self) -> u64 { - unsafe { self.marker.fence.GetCompletedValue() } + unsafe { super::real::fence_completed(&self.marker.fence) } } pub(super) fn target_value(&self) -> u64 { @@ -636,15 +636,23 @@ impl Drop for BeginSubmit { } impl PendingSubmit { - /// Associate the captured submit with the queue's existing retirement fence. `false` leaves - /// all reservations permanently pinned: execution may have happened but cannot be retired. + /// `finish_marked` without the mark (`false`: all reservations stay pinned). + #[cfg(test)] pub(super) unsafe fn finish(self, queue: *mut c_void) -> bool { + self.finish_marked(queue).is_ok() + } + + /// Associate the captured submit with the queue's existing retirement fence (`Err`: all + /// reservations stay pinned, execution may have happened but cannot be retired), with the + /// queue fence/value the submit was marked with (`Ok(None)`: nothing to + /// mark, allocator swapping is off) for the two-pass buffers of the lists (`bind`). + unsafe fn finish_marked(self, queue: *mut c_void) -> Result, ()> { if self.entries.is_empty() { - return true; + return Ok(None); } - let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return false }; + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return Err(()) }; let key = queue as usize; - super::queue_submit::with(key, || self.finish_with_queue_ops( + super::queue_submit::with(key, || self.finish_with_queue_ops_marked( key, || { let mut dev: Option = None; @@ -675,16 +683,26 @@ impl PendingSubmit { /// The queue turn excludes another thread while the state lock is released around driver /// calls. An `Arc` keeps the exact marker alive; replacement means the queue generation was /// invalidated, so the submitted work deliberately remains pinned. + #[cfg(test)] fn finish_with_queue_ops( self, key: usize, create: impl FnOnce() -> Option, signal: impl FnOnce(&ID3D12Fence, u64) -> bool, ) -> bool { + self.finish_with_queue_ops_marked(key, create, signal).is_ok() + } + + fn finish_with_queue_ops_marked( + self, + key: usize, + create: impl FnOnce() -> Option, + signal: impl FnOnce(&ID3D12Fence, u64) -> bool, + ) -> Result, ()> { if self.entries.is_empty() { - return true; + return Ok(None); } - self.finish_with_queue_ops_inner(key, create, signal).is_some() + self.finish_with_queue_ops_inner(key, create, signal).map(Some).ok_or(()) } #[allow(dead_code)] // production consumer lands with the generation-pin stage @@ -793,6 +811,19 @@ fn reserve_and_execute_with( true } +/// `lists` were just submitted to `queue` (outside `STATE`): the two-pass buffers their recordings +/// hold go with the queue mark (`None`: unmarked – they fall back to allocator/age holding), and +/// the queue's finished indirect feedback is read (#2815, #2816). +unsafe fn two_pass_after_submit(queue: *mut c_void, lists: &[*mut c_void], mark: Option<&SubmissionReceipt>) { + if queue.is_null() { + return; + } + if !lists.is_empty() { + super::bind::two_pass_submitted(queue, mark.map(|r| &r.marker.fence), mark.map_or(0, |r| r.value), lists); + } + super::bind::poll_two_pass_feedback(queue); +} + #[derive(Default)] pub(super) struct SubmissionGate { failed: bool, @@ -807,14 +838,25 @@ impl SubmissionGate { prepare: impl FnOnce(), execute: impl FnOnce(), ) -> bool { - reserve_and_execute_with( + let mut mark = None; + let ran = reserve_and_execute_with( &mut self.failed, || begin_submit(lists), prepare, BeginSubmit::execution_possible, execute, - |pending| pending.finish(queue), - ) + |pending| match pending.finish_marked(queue) { + Ok(m) => { + mark = m; + true + } + Err(()) => false, + }, + ); + if ran { + two_pass_after_submit(queue, lists, mark.as_ref()); + } + ran } /// Submit and request an exact retirement receipt. The existing `submit` path remains the @@ -838,9 +880,13 @@ impl SubmissionGate { let pending = begin.execution_possible(); execute(); match pending.finish_receipted(queue) { - Some(receipt) => ReceiptedSubmission::Executed(receipt), + Some(receipt) => { + two_pass_after_submit(queue, lists, Some(&receipt)); + ReceiptedSubmission::Executed(receipt) + } None => { self.failed = true; + two_pass_after_submit(queue, lists, None); ReceiptedSubmission::ExecutedUntracked } } @@ -933,6 +979,13 @@ pub(super) fn recording_backing(list: usize) -> Option { STATE.lock().unwrap().as_ref()?.of_list.get(&list).copied() } +/// The title's allocator `alloc` stands for the PC allocator `pc` (as after a Reset put its own +/// aside); `pc == alloc` ends that. +#[cfg(test)] +pub(super) fn stand_in_for_test(alloc: usize, pc: usize) { + STATE.lock().unwrap().get_or_insert_with(State::default).cur.insert(alloc, pc); +} + /// The PC allocator the title's allocator `alloc` stands for now. pub fn current(alloc: usize) -> usize { if !enabled() { @@ -978,7 +1031,7 @@ pub unsafe fn note_resubmits(queue: *mut c_void, lists: &[*mut c_void]) -> usize } let incomplete: Vec<_> = probes .into_iter() - .filter(|(_, _, last)| last.fence.GetCompletedValue() < last.value) + .filter(|(_, _, last)| super::real::fence_completed(&last.fence) < last.value) .collect(); if incomplete.is_empty() { return 0; @@ -1015,8 +1068,81 @@ pub unsafe fn note_resubmits(queue: *mut c_void, lists: &[*mut c_void]) -> usize found } +/// How long a submit waits for the previous submits of its lists (`XCL_RESUBMIT_WAIT_MS`, 2 000; +/// 0: not at all, as before). +fn resubmit_wait() -> std::time::Duration { + static MS: std::sync::OnceLock = std::sync::OnceLock::new(); + std::time::Duration::from_millis(*MS.get_or_init(|| std::env::var("XCL_RESUBMIT_WAIT_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2000))) +} + +/// `lists` are about to be submitted: the ones whose previous submit the GPU has not finished +/// (`note_resubmits`) wait for it first, `limit` at most for all of them; then they go as they +/// are. On the PC a list must not be executed again before its previous execution is done (debug +/// layer id 553); a console lets a title do it, and a retail title did it about once a second in +/// its world – 128 times before its device was removed with shader memory faults, and not once in +/// a run that ended well. Returns (lists waited for, of them not done in time). +pub unsafe fn wait_for_previous_submits(lists: &[*mut c_void]) -> (usize, usize) { + wait_for_previous_submits_within(lists, resubmit_wait()) +} + +unsafe fn wait_for_previous_submits_within(lists: &[*mut c_void], limit: std::time::Duration) -> (usize, usize) { + if !enabled() || limit.is_zero() { + return (0, 0); + } + // (the fences are taken out: nothing is waited for with STATE held) + let pending: Vec<(ID3D12Fence, u64)> = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return (0, 0) }; + lists + .iter() + .filter_map(|&l| s.last_submit.get(&(l as usize))) + .filter(|l| super::real::fence_completed(&l.fence) < l.value) + .map(|l| (l.fence.clone(), l.value)) + .collect() + }; + if pending.is_empty() { + return (0, 0); + } + let start = std::time::Instant::now(); + let mut late = 0; + for (fence, value) in &pending { + // (XCL's own fence, read without the title's hook; a removed device reads as the largest + // value: no wait then. Such a submit is milliseconds from done: a short poll) + let mut polls = 0u32; + while super::real::fence_completed(fence) < *value { + if start.elapsed() >= limit { + late += 1; + break; + } + if polls < 64 { + std::thread::yield_now(); + } else { + std::thread::sleep(std::time::Duration::from_micros(200)); + } + polls += 1; + } + } + static WAITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = WAITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if late > 0 { + crate::xlog_warn!( + "D3D12.X: {late} of {} previous submits of lists submitted again were not done after {} ms – they go as they are (#{n} such submits)", + pending.len(), + limit.as_millis() + ); + } else if n <= 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: a submit waited {:.1} ms for the previous submits of {} of its lists (#{n} such submits)", + start.elapsed().as_secs_f64() * 1e3, + pending.len() + ); + } + (pending.len(), late) +} + /// Whether the GPU has not finished the last submit of the PC list `list` (#1452: it must not be /// submitted again before that; `title_list` records the title's next recording elsewhere). +/// (`fence_completed`: XCL's own fence, without the title's hook, STATE held) pub fn in_flight(list: usize) -> bool { let (lifetime, last) = { let g = STATE.lock().unwrap(); @@ -1028,7 +1154,7 @@ pub fn in_flight(list: usize) -> bool { let Some(last) = s.last_submit.get(&list).cloned() else { return false }; (lifetime, last) }; - if unsafe { last.fence.GetCompletedValue() } < last.value { + if unsafe { super::real::fence_completed(&last.fence) } < last.value { return true; } // If the address changed generation, or another submit was reserved/published while the @@ -1048,6 +1174,28 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { let _ = begin.execution_possible().finish(queue); } +/// The lists recording on the PC allocators of `alloc` hold them no more: the allocator a title +/// list keeps for its put-off dispatches goes with the list, before the list's segments that +/// recorded on it are released (`list_x::on_release`), and `forget` gives back only what nothing +/// holds. +pub(super) fn unpin_users(alloc: usize) { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + unpin_users_in(s, alloc); + } +} + +fn unpin_users_in(s: &mut State, alloc: usize) { + let mine: Vec = s.cur.get(&alloc).copied().into_iter().chain(s.aside.get(&alloc).into_iter().flatten().copied()).chain([alloc]).collect(); + for b in mine { + if let Some(b) = s.backings.get_mut(&b) { + for l in std::mem::take(&mut b.users) { + s.of_list.remove(&l); + } + } + } +} + /// Whether the GPU may still run a recording made on the title's allocator `alloc`. pub(super) unsafe fn allocator_in_flight(alloc: usize) -> bool { let (mine, probes) = { @@ -1255,6 +1403,11 @@ fn take_shared_aside( /// The title resets its allocator `alloc`. `None`: reset it as it is (nothing holds a /// recording on it, or this is off). `Some(hr)`: done here – the PC allocator in use was put /// aside with its recordings and another one took its place. +/// +/// What ended recordings left in unified memory is held per PC allocator +/// (`console_list::hold_until_reset`). It goes back here for the PC allocators of `alloc` whose +/// submits the GPU has passed – not for one put aside because the GPU still runs what was +/// recorded on it (#1358). pub unsafe fn title_reset(alloc: *mut c_void) -> Option { if !enabled() { return None; @@ -1432,6 +1585,27 @@ fn commit_reset( mod tests { use super::*; + /// When a title list goes, the segments that recorded its put-off dispatches on its own + /// allocator hold neither the PC allocator it stands for now nor the ones put aside: `forget` + /// then releases those the GPU is done with (they were left behind, with what was held on them). + #[test] + fn the_own_allocator_of_a_list_that_goes_is_held_by_none_of_its_segments() { + let (own, now, aside, other) = (0x1000usize, 0x2000usize, 0x3000usize, 0x4000usize); + let (seg, old_seg, elsewhere) = (0x5000usize, 0x6000usize, 0x7000usize); + let mut s = State::default(); + s.cur.insert(own, now); + s.aside.insert(own, vec![aside]); + move_list(&mut s, seg, now); + move_list(&mut s, old_seg, aside); + move_list(&mut s, elsewhere, other); + assert!(!unsafe { backing_free_for_test(&s.backings[&now]) }); + unpin_users_in(&mut s, own); + assert!(unsafe { backing_free_for_test(&s.backings[&now]) && backing_free_for_test(&s.backings[&aside]) }, "nothing holds them"); + assert!(!s.of_list.contains_key(&seg) && !s.of_list.contains_key(&old_seg)); + assert_eq!(s.of_list.get(&elsewhere), Some(&other), "a list on another allocator keeps its hold"); + assert!(s.backings[&other].users.contains(&elsewhere)); + } + #[test] fn release_probe_transfers_only_the_logical_final_reference() { use std::cell::Cell; @@ -2476,6 +2650,60 @@ mod tests { ); } + /// The title's Reset (through `real::alloc_reset`) while the GPU has not run a submit of a + /// recording on its allocator: the allocator is put aside, and what the recording left in + /// unified memory stays until the GPU has passed it (#1358). + #[test] + fn a_reset_that_puts_the_allocator_aside_keeps_what_the_gpu_still_reads() { + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let a = alloc.as_raw(); + if !super::super::real::is_adopted(a) { + super::super::real::adopt(a, super::super::real::Kind::CommandAllocator); + } + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let l = list.as_raw() as usize; + created_on(l, a as usize, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + list.Close().unwrap(); + // the queue runs the list only once `gate` is signalled + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + executed(queue.as_raw(), &[l as *mut c_void]); + // the list's recording ends; what it put in unified memory is held for the allocator + forget_list(l); + let block = l + 1; + super::super::console_list::hold_until_reset(a as usize, vec![block]); + + alloc.Reset().unwrap(); + let stand_in = current(a as usize); + let held = super::super::console_list::take_pending_for_test(a as usize); + super::super::console_list::hold_until_reset(a as usize, held.clone()); + + gate.Signal(1).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&done, 1).unwrap(); + let start = std::time::Instant::now(); + while done.GetCompletedValue() < 1 && start.elapsed().as_secs() < 10 { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let ran = done.GetCompletedValue() >= 1; + alloc.Reset().unwrap(); + let after = super::super::console_list::take_pending_for_test(a as usize); + drop(list); + drop(alloc); + + assert_ne!(stand_in, a as usize, "the GPU had not run the submit: another PC allocator took the place"); + assert_eq!(held, vec![block], "the memory of a recording the GPU had not run is held over the Reset"); + assert!(ran, "the queue finishes"); + assert!(after.is_empty(), "the GPU passed the submit: the next Reset gives the memory back"); + } + } + /// A list recorded once and submitted again after the title reset its allocator: the /// recording is still there (the device is not removed), the title's allocator goes on with /// another PC allocator, and the first one is used again once the list has moved on. @@ -2592,4 +2820,47 @@ mod tests { assert_eq!(after_forget, 0, "a forgotten list has no previous submit"); } } + + /// A list whose previous submit still runs is waited for before it is submitted again: until + /// that submit is done, or the limit; a list with nothing running is not waited for. + #[test] + fn a_resubmit_waits_for_the_previous_submit() { + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + // a fence the GPU has not reached stands for a submit still running + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut ids = Box::new([0u8; 2]); + let (alloc, list) = (ids.as_mut_ptr() as usize, ids.as_mut_ptr() as usize + 1); + created_on(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + let recording = s.recordings[&list]; + s.last_submit.insert(list, LastSubmit { queue: 0x10, fence: fence.clone(), value: 1, recording }); + } + let lists = [list as *mut c_void]; + // it never finishes: the limit ends the wait, and says so + let t = std::time::Instant::now(); + assert_eq!(wait_for_previous_submits_within(&lists, std::time::Duration::from_millis(30)), (1, 1)); + assert!(t.elapsed() >= std::time::Duration::from_millis(30)); + // no limit: no wait + assert_eq!(wait_for_previous_submits_within(&lists, std::time::Duration::ZERO), (0, 0)); + // it finishes meanwhile: the wait ends then, far before the limit + let signal = fence.clone(); + let done = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(20)); + signal.Signal(1).unwrap(); + }); + let t = std::time::Instant::now(); + assert_eq!(wait_for_previous_submits_within(&lists, std::time::Duration::from_secs(20)), (1, 0)); + assert!(t.elapsed() < std::time::Duration::from_secs(10), "the wait ends when the submit is done"); + done.join().unwrap(); + // nothing runs now: nothing to wait for + assert_eq!(wait_for_previous_submits_within(&lists, std::time::Duration::from_secs(20)), (0, 0)); + forget_list(list); + forget(alloc); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 9e42d83069..b50b835091 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -9,7 +9,7 @@ //! unified memory and dispatches. That memory stays until the list's allocator is reset. use std::cell::RefCell; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet, VecDeque}; use std::ffi::c_void; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, Weak}; @@ -32,11 +32,782 @@ struct State { pso: usize, /// Retained nonblocking decision for `pso`. resolution: Option, + /// 32-bit addresses of the view heap and the sampler heap set (0: none) + heaps: [u32; 2], + /// the PC allocator (native backing, `native_backing`) this recording is on (`alloc_pool`: + /// not always the title's allocator) allocator: usize, /// unified memory of this recording (io, argument tables) uma: Vec, /// where the next draw's io and argument table go (blocks in `uma`) arena: crate::gpu::uma::Arena, + /// a heap of views is bound (`list_x::ensure_view_heap`), and what that call said (the shared + /// view heap is bound: `list_x::note_shared_view_heap_use`) + heap_bound: bool, + shared_view_bound: bool, + res_buf: Option, + res_retired: Vec, + res_marks: Vec<(usize, ID3D12Fence, u64)>, + res_untracked: bool, + fb_uses: Vec<(usize, u32, u32)>, + /// rewritten indirect arguments (`scratch_args`): the block (and its bytes), its bytes in + /// use, and the bytes of blocks this recording took + scratch: Option<(ID3D12Resource, u64)>, + scratch_used: u64, + scratch_taken: u64, + /// `scratch` was left in INDIRECT_ARGUMENT by the last two-pass ExecuteIndirect (only with + /// `two_pass_batch`; otherwise it goes back to COMMON after each) + scratch_in_args: bool, + /// the record regions a mesh pass may still be reading, with no UAV barrier on the records + /// since (`two_pass_plan`; only with `two_pass_batch`) + record_open: Option, + /// two-pass draws deferred to `flush_two_pass` (`two_pass_defer`) and the title's pipeline + /// sets between them, in the title's order + deferred: Vec, + /// the records of deferred draws: a region each from the start (`batch_region`), and whether + /// the mesh passes of the last run may still read them (no barrier after them) + batch_buf: Option, + batch_used: u64, + batch_open: bool, +} + +/// A recording's blocks of rewritten indirect arguments, and most bytes of them (past it, its +/// two-pass ExecuteIndirects are skipped) +const SCRATCH_BLOCK: u64 = 256 << 10; +const SCRATCH_CAP: u64 = 16 << 20; +/// Most bytes of buffers kept for reuse (`FREE_RES`) +const FREE_RES_CAP: u64 = 1 << 30; +/// How long a buffer no recording took again stays in `FREE_RES`. Recordings take them again +/// within a frame or so, and the GPU is done with one there already (its allocator was reset): +/// only video memory waits on this. +const FREE_RES_IDLE: std::time::Duration = std::time::Duration::from_secs(2); + +static ALLOC_RES: Mutex>>> = Mutex::new(None); +static FREE_RES: Mutex> = Mutex::new(FreePool::new(FREE_RES_CAP)); +static TWO_PASS_LIST_COUNT: AtomicU64 = AtomicU64::new(0); +static TWO_PASS_LISTS: Mutex>> = Mutex::new(None); +static FENCED_RES: Mutex> = Mutex::new(VecDeque::new()); +static FENCED_BYTES: AtomicU64 = AtomicU64::new(0); + +/// Two-pass buffers left by a retired recording, waiting on the GPU fence mark(s) from the +/// submit(s) of that command list before returning to `FREE_RES`. +struct FencedBatch { + marks: Vec<(ID3D12Fence, u64)>, + bytes: u64, + bufs: Vec, +} + +/// Record that `list` holds two-pass buffers in this recording so `two_pass_submitted` only +/// inspects submits touching two-pass command lists. +fn track_two_pass_list(list: usize) { + let mut g = TWO_PASS_LISTS.lock().unwrap(); + let set = g.get_or_insert_with(HashSet::new); + if set.insert(list) { + TWO_PASS_LIST_COUNT.store(set.len() as u64, Ordering::Release); + } +} + +/// Drop `list` from `TWO_PASS_LISTS` when its recording ends or is destroyed. +fn untrack_two_pass_list(list: usize) { + if TWO_PASS_LIST_COUNT.load(Ordering::Acquire) == 0 { + return; + } + let mut g = TWO_PASS_LISTS.lock().unwrap(); + if let Some(set) = g.as_mut() { + if set.remove(&list) { + TWO_PASS_LIST_COUNT.store(set.len() as u64, Ordering::Release); + } + } +} + +/// Mark whether `this` can track two-pass lifetimes via queue submit fences. +fn mark_two_pass_tracking(this: *mut c_void, untracked_out: &mut bool) { + if !super::alloc_pool::enabled() || super::list_x::tracked_list_type(this) == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) { + *untracked_out = true; + } +} + +fn record_queue_fence(marks: &mut Vec<(usize, ID3D12Fence, u64)>, queue: usize, fence: &ID3D12Fence, value: u64) { + if let Some((_, _, recorded)) = marks.iter_mut().find(|(q, f, _)| *q == queue && f.as_raw() == fence.as_raw()) { + // Concurrent submit callbacks can arrive out of Signal order. + *recorded = (*recorded).max(value); + } else { + marks.push((queue, fence.clone(), value)); + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum FenceState { + Pending, + Completed, + Removed, +} + +/// D3D12 returns `u64::MAX` from `GetCompletedValue()` on device removal; treat that sentinel +/// as `Removed` so outstanding work cannot look complete and re-enter the free pool. +unsafe fn fence_state(fence: &ID3D12Fence, target: u64) -> FenceState { + let value = super::real::fence_completed(fence); + if value == u64::MAX { + FenceState::Removed + } else if value >= target { + FenceState::Completed + } else { + FenceState::Pending + } +} + +/// `lists` were just submitted on `queue` (`alloc_pool::executed` outside `alloc_pool::STATE`). +/// Attach the queue fence mark to any recording holding two-pass buffers; when `fence` is `None`, +/// mark those recordings untracked so they fall back to allocator/age holding. +pub(super) unsafe fn two_pass_submitted(queue: *mut c_void, fence: Option<&ID3D12Fence>, value: u64, lists: &[*mut c_void]) { + if TWO_PASS_LIST_COUNT.load(Ordering::Acquire) == 0 || lists.is_empty() { + return; + } + let tracked: Vec<*mut c_void> = { + let g = TWO_PASS_LISTS.lock().unwrap(); + let Some(set) = g.as_ref() else { return }; + lists.iter().copied().filter(|&l| set.contains(&(l as usize))).collect() + }; + if tracked.is_empty() { + return; + } + let q = queue as usize; + let mut fb_pending: Vec<(usize, u32, u32)> = Vec::new(); + for l in tracked { + with(l, |s| { + if !s.fb_uses.is_empty() { + fb_pending.extend_from_slice(&s.fb_uses); + } + if s.res_buf.is_none() && s.batch_buf.is_none() && s.res_retired.is_empty() { + return; + } + match fence { + Some(f) => record_queue_fence(&mut s.res_marks, q, f, value), + None => s.res_untracked = true, + } + }); + } + if !fb_pending.is_empty() { + let fb_fence = fence.map(|f| (f, value)); + for (dev_key, fb_slot, cap) in fb_pending { + mark_indirect_feedback_used(dev_key, fb_slot, cap, q, fb_fence); + } + } +} + +/// A two-pass buffer (records or argument scratch), its bytes and its device: counted from when +/// it is made until it is let go (`TWO_PASS`). +struct TwoPassBuf { + res: ID3D12Resource, + bytes: u64, + dev: usize, +} + +impl TwoPassBuf { + /// A new buffer of `bytes`, if the two-pass buffers alive stay within `two_pass_cap` with it + /// (the free ones in `FREE_RES` go first to make room, when they are enough). Past it: an + /// error, and the draw that asked is skipped. + #[cfg(test)] + unsafe fn make(dev: &ID3D12Device, bytes: u64, what: &str) -> Result { + let cap = two_pass_cap(); + match Self::try_make_with_cap(dev, bytes, what, cap)? { + Some(b) => Ok(b), + None => Err(refuse_two_pass(what, bytes, cap)), + } + } + + unsafe fn try_make_with_cap(dev: &ID3D12Device, bytes: u64, what: &str, cap: u64) -> Result, String> { + if !reserve(&TWO_PASS[TP_ALIVE], bytes, cap) { + reclaim_fenced(); + if !reserve(&TWO_PASS[TP_ALIVE], bytes, cap) { + // (counted with `FREE_RES` locked, so its bytes are in the load; none go when they + // cannot make the room: the draw is skipped either way, and the recordings after it + // can still take them) + let gone = { + let mut free = FREE_RES.lock().unwrap(); + let over = TWO_PASS[TP_ALIVE].load(Ordering::Relaxed).saturating_add(bytes).saturating_sub(cap); + free.take_room(over) + }; + // (the GPU is done with those: let go outside the lock) + let made_room = gone.is_some(); + drop(gone); + if !made_room || !reserve(&TWO_PASS[TP_ALIVE], bytes, cap) { + return Ok(None); + } + } + } + let res = match default_uav_buffer(dev, bytes, what) { + Ok(r) => r, + Err(e) => { + TWO_PASS[TP_ALIVE].fetch_sub(bytes, Ordering::Relaxed); + return Err(e); + } + }; + note_two_pass(TP_MADE); + Ok(Some(TwoPassBuf { res, bytes, dev: dev.as_raw() as usize })) + } +} + +fn refuse_two_pass(what: &str, bytes: u64, cap: u64) -> String { + note_two_pass(TP_REFUSED); + 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: a {what} of {} KiB would take the two-pass buffers alive past {} MiB (XCL_TWO_PASS_MB): its draw is skipped", + bytes >> 10, + cap >> 20 + ); + } + format!("the two-pass buffers alive are at {} MiB (XCL_TWO_PASS_MB)", cap >> 20) +} + +/// Cap two-pass buffers dynamically to 25% of remaining local VRAM headroom, with a card-scaled +/// floor `(local_budget / 32).clamp(256 MiB, 512 MiB)` and a `min(local_budget / 4, 2048 MiB)` +/// ceiling. Falls back to 1024 MiB when DXGI budget is unknown. +fn budget_two_pass_cap(non_two_pass_used: u64, local_budget: u64) -> u64 { + if local_budget == 0 { + return 1024 << 20; + } + let ceiling = (local_budget / 4).min(2048 << 20); + let floor = (local_budget / 32).clamp(256 << 20, 512 << 20).min(ceiling); + (local_budget.saturating_sub(non_two_pass_used) / 4).clamp(floor, ceiling) +} + +/// Most bytes of two-pass buffers alive at once (`XCL_TWO_PASS_MB`, else DXGI budget headroom +/// via `budget_two_pass_cap` cached for 250 ms). +fn two_pass_cap() -> u64 { + static ENV_CAP: std::sync::OnceLock> = std::sync::OnceLock::new(); + if let Some(cap) = *ENV_CAP.get_or_init(|| { + std::env::var("XCL_TWO_PASS_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map(|mb| mb.saturating_mul(1 << 20)) + }) { + return cap; + } + static CACHED: Mutex> = Mutex::new(None); + let now = std::time::Instant::now(); + if let Ok(g) = CACHED.try_lock() { + if let Some((at, cap)) = *g { + if now.saturating_duration_since(at) < std::time::Duration::from_millis(250) { + return cap; + } + } + } + let cap = super::real::video_memory().map_or(1024 << 20, |(used, _, budget)| { + let non_tp = used.saturating_sub(TWO_PASS[TP_ALIVE].load(Ordering::Relaxed)); + budget_two_pass_cap(non_tp, budget) + }); + if let Ok(mut g) = CACHED.try_lock() { + *g = Some((now, cap)); + } + cap +} + +/// `bytes` more counted in `alive` if it stays within `cap` (whether it did). +fn reserve(alive: &AtomicU64, bytes: u64, cap: u64) -> bool { + let mut a = alive.load(Ordering::Relaxed); + loop { + let Some(n) = a.checked_add(bytes).filter(|&n| n <= cap) else { return false }; + match alive.compare_exchange_weak(a, n, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => return true, + Err(now) => a = now, + } + } +} + +impl Drop for TwoPassBuf { + fn drop(&mut self) { + TWO_PASS[TP_ALIVE].fetch_sub(self.bytes, Ordering::Relaxed); + note_two_pass(TP_GONE); + } +} + +/// Two-pass buffers made, taken again from `FREE_RES`, let go, alive bytes, refused past cap, +/// indirect clamp / direct cut counts and dropped groups, fence waits / timeouts, and shrunk +/// record buffers. +static TWO_PASS: [AtomicU64; 12] = [const { AtomicU64::new(0) }; 12]; +const TP_MADE: usize = 0; +const TP_REUSED: usize = 1; +const TP_GONE: usize = 2; +const TP_ALIVE: usize = 3; +const TP_REFUSED: usize = 4; +const TP_INDIRECT_CLAMPED: usize = 5; +const TP_INDIRECT_GROUPS_DROPPED: usize = 6; +const TP_WAITED: usize = 7; +const TP_WAIT_TIMEOUTS: usize = 8; +const TP_SHRUNK: usize = 9; +const TP_DIRECT_CUT: usize = 10; +const TP_DIRECT_GROUPS_DROPPED: usize = 11; + +/// One more of `TWO_PASS[k]`. +fn note_two_pass(k: usize) { + note_two_pass_add(k, 1); +} + +/// Add `delta` to `TWO_PASS[k]`. Logged at most every 2 s while they change (always: each buffer +/// made or let go is the driver's memory manager at work, in video memory that may be short). +fn note_two_pass_add(k: usize, delta: u64) { + use std::sync::atomic::AtomicI64; + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + static LAST: AtomicI64 = AtomicI64::new(i64::MIN); + TWO_PASS[k].fetch_add(delta, Ordering::Relaxed); + let now = START.get_or_init(std::time::Instant::now).elapsed().as_millis() as i64; + let last = LAST.load(Ordering::Relaxed); + if now < last.saturating_add(2000) { + return; + } + // (a buffer is let go while `FREE_RES` is locked on this thread too: no line then, the next + // change logs) + let Ok(free) = FREE_RES.try_lock() else { return }; + let (kept, kept_bytes) = (free.free.len(), free.bytes); + drop(free); + // (what waits for allocator resets, and for time: bytes that stay there hold the cap; tried + // only, as `FREE_RES`) + let Ok(held) = ALLOC_RES.try_lock() else { return }; + let held_bytes: u64 = held.as_ref().map_or(0, |m| m.values().flatten().map(|b| b.bytes).sum()); + drop(held); + let Ok(unknown) = UNKNOWN_RES.try_lock() else { return }; + let unknown_bytes = unknown.bytes; + drop(unknown); + let fenced_bytes = FENCED_BYTES.load(Ordering::Relaxed); + if LAST.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; + } + let [made, reused, gone, alive, refused, clamped, clamped_groups, waited, wait_timeouts, shrunk, direct_cut, direct_dropped] = + std::array::from_fn(|i| TWO_PASS[i].load(Ordering::Relaxed)); + crate::xlog_info!( + "D3D12.X: two-pass buffers: {made} made, {reused} taken again, {gone} let go; {} alive ({} MiB), {kept} of them kept for reuse ({} MiB), {} MiB waiting for GPU fences, {} MiB waiting for allocator resets, {} MiB for no known allocator; {refused} not made past {} MiB (XCL_TWO_PASS_MB); {clamped} indirect cmds clamped ({clamped_groups} groups dropped), {direct_cut} direct cut ({direct_dropped} groups dropped), {waited} waited ({wait_timeouts} timed out), {shrunk} shrunk", + made.saturating_sub(gone), + alive >> 20, + kept_bytes >> 20, + fenced_bytes >> 20, + held_bytes >> 20, + unknown_bytes >> 20, + two_pass_cap() >> 20 + ); +} + +fn hold_res_until_reset(allocator: usize, mut bufs: Vec) { + if bufs.is_empty() { + return; + } + if allocator == 0 { + let over = UNKNOWN_RES.lock().unwrap().hold(std::time::Instant::now(), bufs.into_iter().map(|b| (b.bytes, b)).collect()); + if over > 0 { + 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: two-pass buffers of recordings with no known allocator past {} MiB: {over} of the oldest let go early", UNKNOWN_RES_CAP >> 20); + } + } + return; + } + ALLOC_RES.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().append(&mut bufs); +} + +fn put_free_bufs(bufs: Vec) { + if bufs.is_empty() { + return; + } + let free_cap = two_pass_cap().min(FREE_RES_CAP); + let gone = { + let mut free = FREE_RES.lock().unwrap(); + free.cap = free_cap; + let now = std::time::Instant::now(); + let mut gone = free.take_idle(now, FREE_RES_IDLE); + for b in bufs { + gone.extend(free.put(now, b.bytes, b.dev, b)); + } + gone + }; + drop(gone); +} + +const FENCE_WAIT_LIMIT: std::time::Duration = std::time::Duration::from_millis(10); +const FENCE_WAIT_RESCAN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(1); +const FENCE_WAIT_YIELD_POLLS: u32 = 64; +const FENCE_WAIT_SLEEP: std::time::Duration = std::time::Duration::from_micros(200); +const FENCE_WAIT_BACKOFF_MS: u64 = 250; +static WAIT_BACKOFF_UNTIL_MS: AtomicU64 = AtomicU64::new(0); + +fn epoch_ms() -> u64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 + 1 +} + +fn active_wait_limit(limit: std::time::Duration) -> std::time::Duration { + let until = WAIT_BACKOFF_UNTIL_MS.load(Ordering::Acquire); + if until != 0 && epoch_ms() < until { + std::time::Duration::ZERO + } else { + limit + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum WaitStep { + Progressed, + Stopped, +} + +/// Poll the oldest healthy submitted `FencedBatch` up to `deadline` when cap pressure prevents +/// allocation, skipping or stopping on removed-device batches. Reclaim completed batches +/// on other queues periodically during the wait and again when it ends. +fn wait_oldest_fenced_until(deadline: std::time::Instant) -> WaitStep { + #[cfg(not(test))] + let now = std::time::Instant::now; + #[cfg(test)] + let now = tests::fence_wait_now; + if FENCED_BYTES.load(Ordering::Acquire) == 0 || now() >= deadline { + return WaitStep::Stopped; + } + let marks = { + let fenced = FENCED_RES.lock().unwrap(); + let Some(oldest) = fenced.iter().find(|b| !b.marks.iter().any(|(f, v)| unsafe { fence_state(f, *v) == FenceState::Removed })) else { + return WaitStep::Stopped; + }; + oldest.marks.clone() + }; + let mut next_reclaim = now() + FENCE_WAIT_RESCAN_INTERVAL; + let mut polls = 0u32; + let mut timed_out = false; + 'wait: for (fence, value) in &marks { + loop { + match unsafe { fence_state(fence, *value) } { + FenceState::Completed => break, + FenceState::Removed => return WaitStep::Stopped, + FenceState::Pending => { + #[cfg(test)] + tests::signal_fence_on_wait(fence, polls); + if matches!(unsafe { fence_state(fence, *value) }, FenceState::Completed) { + break; + } + if matches!(unsafe { fence_state(fence, *value) }, FenceState::Removed) { + return WaitStep::Stopped; + } + let polled_at = now(); + if polled_at >= deadline { + timed_out = true; + break 'wait; + } + if polled_at >= next_reclaim { + if reclaim_fenced() > 0 { + note_two_pass(TP_WAITED); + return WaitStep::Progressed; + } + next_reclaim = now() + FENCE_WAIT_RESCAN_INTERVAL; + } + if polls < FENCE_WAIT_YIELD_POLLS { + std::thread::yield_now(); + } else { + std::thread::sleep(FENCE_WAIT_SLEEP); + } + polls += 1; + } + } + } + } + if reclaim_fenced() > 0 { + note_two_pass(TP_WAITED); + return WaitStep::Progressed; + } + if timed_out { + WAIT_BACKOFF_UNTIL_MS.store(epoch_ms().saturating_add(FENCE_WAIT_BACKOFF_MS), Ordering::Release); + note_two_pass(TP_WAIT_TIMEOUTS); + return WaitStep::Stopped; + } + WaitStep::Progressed +} + +unsafe fn acquire_two_pass_buf_with_cap( + dev: &ID3D12Device, + min: u64, + preferred_max: u64, + hard_max: u64, + what: &str, + cap: u64, + wait_limit: std::time::Duration, +) -> Result, String> { + let dev_key = dev.as_raw() as usize; + let try_acquire = || -> Result, String> { + if let Some(b) = take_free(dev_key, min, preferred_max) { + return Ok(Some(b)); + } + if let Some(b) = TwoPassBuf::try_make_with_cap(dev, min, what, cap)? { + return Ok(Some(b)); + } + if hard_max > preferred_max { + if let Some(b) = take_free(dev_key, min, hard_max) { + return Ok(Some(b)); + } + } + Ok(None) + }; + if let Some(b) = try_acquire()? { + return Ok(Some(b)); + } + let effective_wait = active_wait_limit(wait_limit); + if !effective_wait.is_zero() { + let deadline = std::time::Instant::now() + effective_wait; + while std::time::Instant::now() < deadline { + if wait_oldest_fenced_until(deadline) == WaitStep::Stopped { + break; + } + if let Some(b) = try_acquire()? { + return Ok(Some(b)); + } + } + } + Ok(None) +} + +unsafe fn acquire_res_buf_with_cap( + dev: &ID3D12Device, + need: u64, + min_fit: u64, + existing_cap: u64, + cap: u64, + wait_limit: std::time::Duration, +) -> Result, String> { + if let Some(b) = acquire_two_pass_buf_with_cap(dev, need, need.saturating_mul(2), u64::MAX, "two-pass res buffer", cap, wait_limit)? { + return Ok(Some(b)); + } + let floor = record_buffer_bytes(min_fit).min(need); + let dev_key = dev.as_raw() as usize; + let mut cand = need; + while cand > floor { + // Walk every half-step bucket (`record_buffer_bytes` alternates 2^k and 1.5 * 2^(k-1)) + // so shrinking from e.g. 64 MiB tries 48 MiB before 32 MiB and keeps more mesh groups. + let next = if cand.is_power_of_two() { + cand - (cand >> 2) + } else { + cand.next_power_of_two() >> 1 + } + .max(floor); + if next >= cand || (existing_cap >= floor && next <= existing_cap) { + break; + } + cand = next; + if let Some(b) = take_free(dev_key, cand, u64::MAX) { + note_two_pass(TP_SHRUNK); + return Ok(Some(b)); + } + if let Some(b) = TwoPassBuf::try_make_with_cap(dev, cand, "two-pass res buffer", cap)? { + note_two_pass(TP_SHRUNK); + return Ok(Some(b)); + } + } + Ok(None) +} + +fn retire_recording_res(allocator: usize, bufs: Vec, marks: Vec<(usize, ID3D12Fence, u64)>, untracked: bool) { + if bufs.is_empty() { + return; + } + if !untracked && !marks.is_empty() { + let marks: Vec<(ID3D12Fence, u64)> = marks.into_iter().map(|(_, f, v)| (f, v)).collect(); + if marks.iter().all(|(f, v)| unsafe { fence_state(f, *v) == FenceState::Completed }) { + put_free_bufs(bufs); + return; + } + let bytes: u64 = bufs.iter().map(|b| b.bytes).sum(); + let mut fenced = FENCED_RES.lock().unwrap(); + fenced.push_back(FencedBatch { marks, bytes, bufs }); + #[cfg(test)] + tests::observe_fenced_batch_publication(); + FENCED_BYTES.fetch_add(bytes, Ordering::Release); + return; + } + hold_res_until_reset(allocator, bufs); +} + +fn reclaim_fenced() -> u64 { + if FENCED_BYTES.load(Ordering::Acquire) == 0 { + return 0; + } + let mut reclaimed_bufs = Vec::new(); + let mut reclaimed = 0u64; + { + let mut fenced = FENCED_RES.lock().unwrap(); + let mut i = 0; + while i < fenced.len() { + let done = fenced[i].marks.iter().all(|(f, v)| unsafe { fence_state(f, *v) == FenceState::Completed }); + if done { + let batch = fenced.remove(i).unwrap(); + reclaimed += batch.bytes; + reclaimed_bufs.extend(batch.bufs); + } else { + i += 1; + } + } + if reclaimed > 0 { + FENCED_BYTES.fetch_sub(reclaimed, Ordering::Release); + WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); + } + } + put_free_bufs(reclaimed_bufs); + reclaimed +} + +pub(super) fn release_allocator_res(allocator: usize) { + reclaim_fenced(); + let aged = UNKNOWN_RES.lock().unwrap().take_older(std::time::Instant::now(), UNKNOWN_RES_AGE); + let bufs = ALLOC_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)); + let bufs: Vec<_> = bufs.into_iter().flatten().chain(aged).collect(); + if bufs.is_empty() { + let gone = FREE_RES.lock().unwrap().take_idle(std::time::Instant::now(), FREE_RES_IDLE); + drop(gone); + } else { + put_free_bufs(bufs); + } +} + +/// A buffer of `FREE_RES` on the device `dev` of `min..=max` bytes, for a recording to take. +fn take_free(dev: usize, min: u64, max: u64) -> Option { + reclaim_fenced(); + let (gone, picked) = { + let mut free = FREE_RES.lock().unwrap(); + (free.take_idle(std::time::Instant::now(), FREE_RES_IDLE), free.take(dev, min, max)) + }; + // (let go outside the lock) + drop(gone); + if picked.is_some() { + note_two_pass(TP_REUSED); + } + picked +} + +/// How long the two-pass buffers of a recording with no known allocator are kept: no fence or +/// allocator says when the GPU is done with them (a list XCL never saw reset, a segment reset +/// onto none), so time does – far past any frame in flight. +const UNKNOWN_RES_AGE: std::time::Duration = std::time::Duration::from_secs(10); +/// Most bytes of them kept; past it the oldest go early (logged). +const UNKNOWN_RES_CAP: u64 = 1 << 30; + +/// Things of `bytes` each kept from when they were handed over until they are old enough. +struct Aging { + held: std::collections::VecDeque<(std::time::Instant, u64, T)>, + bytes: u64, + cap: u64, +} + +impl Aging { + const fn new(cap: u64) -> Self { + Aging { held: std::collections::VecDeque::new(), bytes: 0, cap } + } + + /// Keep `items` (bytes, item) from `now`. Past the cap the oldest go (dropped here): how many. + fn hold(&mut self, now: std::time::Instant, items: Vec<(u64, T)>) -> usize { + for (b, t) in items { + self.bytes += b; + self.held.push_back((now, b, t)); + } + let mut over = 0; + while self.bytes > self.cap && self.held.len() > 1 { + let (_, b, _) = self.held.pop_front().unwrap(); + self.bytes -= b; + over += 1; + } + over + } + + /// What has been kept `age` or longer at `now`. + fn take_older(&mut self, now: std::time::Instant, age: std::time::Duration) -> Vec { + let mut out = Vec::new(); + while self.held.front().is_some_and(|&(at, _, _)| now.saturating_duration_since(at) >= age) { + let (_, b, t) = self.held.pop_front().unwrap(); + self.bytes -= b; + out.push(t); + } + out + } +} + +/// the two-pass buffers of recordings with no known allocator (`hold_res_until_reset`) +static UNKNOWN_RES: Mutex> = Mutex::new(Aging::new(UNKNOWN_RES_CAP)); + +/// Buffers the GPU is done with, kept for the recordings that need one next (`FREE_RES`): each +/// with when it was handed back, its bytes and its device, oldest first. What it keeps is what +/// recordings took again in the last `FREE_RES_IDLE`, and at most `cap` bytes, so a steady frame +/// takes back what the one before it handed back and makes none. +struct FreePool { + free: Vec<(std::time::Instant, u64, usize, T)>, + bytes: u64, + cap: u64, +} + +impl FreePool { + const fn new(cap: u64) -> Self { + FreePool { free: Vec::new(), bytes: 0, cap } + } + + /// Keep `item` of `bytes` on the device `dev` from `now`. Past the cap the oldest go (what + /// is returned). + fn put(&mut self, now: std::time::Instant, bytes: u64, dev: usize, item: T) -> Vec { + self.bytes += bytes; + self.free.push((now, bytes, dev, item)); + let mut over = Vec::new(); + while self.bytes > self.cap && !self.free.is_empty() { + let (_, b, _, t) = self.free.remove(0); + self.bytes -= b; + over.push(t); + } + over + } + + /// The smallest kept on `dev` of `min..=max` bytes, of those the last handed back (so the + /// ones no recording needs grow old and go). + fn take(&mut self, dev: usize, min: u64, max: u64) -> Option { + let i = self + .free + .iter() + .enumerate() + .filter(|(_, &(_, b, d, _))| d == dev && b >= min && b <= max) + .min_by_key(|&(i, &(_, b, _, _))| (b, std::cmp::Reverse(i)))? + .0; + let (_, b, _, t) = self.free.remove(i); + self.bytes -= b; + Some(t) + } + + /// The oldest kept, of any size and device, until they come to `bytes`. None when all of + /// them come to less: then all stay. + fn take_room(&mut self, bytes: u64) -> Option> { + if self.bytes < bytes { + return None; + } + let mut freed = 0; + let n = self + .free + .iter() + .take_while(|&&(_, b, ..)| { + let more = freed < bytes; + freed += b; + more + }) + .count(); + Some( + self.free + .drain(..n) + .map(|(_, b, _, t)| { + self.bytes -= b; + t + }) + .collect(), + ) + } + + /// What was kept `age` or longer at `now`, no recording having taken it. + fn take_idle(&mut self, now: std::time::Instant, age: std::time::Duration) -> Vec { + let n = self.free.iter().take_while(|&&(at, ..)| now.saturating_duration_since(at) >= age).count(); + self.free + .drain(..n) + .map(|(_, b, _, t)| { + self.bytes -= b; + t + }) + .collect() + } } const STATE_SHARDS: usize = 64; @@ -172,6 +943,12 @@ const DISPATCHES: usize = 3; const DISPATCHES_SKIPPED: usize = 4; fn count(k: usize) { + use super::capture::Outcome; + super::capture::outcome(match k { + DRAWS | DISPATCHES => Outcome::Ran, + DRAWS_PC => Outcome::Pc, + _ => Outcome::Skipped, + }); 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(); @@ -292,9 +1069,10 @@ fn install_reset( resolution: Option, ) { let backing = native_backing(list, allocator); - let (old, blocks, old_resolution) = with(list, |s| { + let (old, blocks, res_bufs, res_marks, res_untracked, had_fb, old_resolution) = with(list, |s| { let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); + s.heap_bound = false; s.pso = initial_pso; let old_resolution = std::mem::replace(&mut s.resolution, resolution); s.layout = None; @@ -302,12 +1080,39 @@ fn install_reset( s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; - (old, std::mem::take(&mut s.uma), old_resolution) + s.heaps = [0; 2]; + // (the scratch blocks are in `res_retired` already) + (s.scratch, s.scratch_used, s.scratch_taken, s.scratch_in_args, s.record_open) = (None, 0, 0, false, None); + let mut res_bufs = std::mem::take(&mut s.res_retired); + if let Some(b) = s.res_buf.take() { + res_bufs.push(b); + } + res_bufs.extend(s.end_batch()); + let res_marks = std::mem::take(&mut s.res_marks); + let res_untracked = std::mem::take(&mut s.res_untracked); + let had_fb = !s.fb_uses.is_empty(); + s.fb_uses.clear(); + (old, std::mem::take(&mut s.uma), res_bufs, res_marks, res_untracked, had_fb, old_resolution) }); + if !res_bufs.is_empty() || !res_marks.is_empty() || res_untracked || had_fb { + untrack_two_pass_list(list as usize); + } + unmark_deferring(list); console_list::hold_until_reset(old, blocks); + retire_recording_res(old, res_bufs, res_marks, res_untracked); drop(old_resolution); } +impl State { + /// The deferred draws of a recording that ends without them (a Reset without a Close, a + /// list let go): dropped, and the buffer of their records for the caller to hold. + fn end_batch(&mut self) -> Option { + self.deferred.clear(); + (self.batch_used, self.batch_open) = (0, false); + self.batch_buf.take() + } +} + pub(super) struct PreparedNativePipeline { original: usize, raw: usize, @@ -370,6 +1175,7 @@ fn install_clear_state( resolution: Option, ) { let old_resolution = with(list, |s| { + s.heap_bound = false; s.pso = pso; let old_resolution = std::mem::replace(&mut s.resolution, resolution); s.layout = None; @@ -377,13 +1183,15 @@ fn install_clear_state( s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; + s.heaps = [0; 2]; old_resolution }); drop(old_resolution); } /// Allocation-bearing root state captured before a mid-list split commits. Preparation also -/// transfers the reserved destination's old UMA ownership, so installation cannot allocate. +/// transfers the reserved destination's old UMA ownership (and retires its previous recording's +/// two-pass buffers and deferred run), so installation cannot allocate. pub(super) struct PreparedSplit { to: usize, allocator: usize, @@ -394,6 +1202,7 @@ pub(super) struct PreparedSplit { rs_gfx: usize, pso: usize, resolution: Option, + heaps: [u32; 2], } impl PreparedSplit { @@ -421,24 +1230,46 @@ pub(super) fn initial_pipeline(list: *mut c_void) -> (usize, Option PreparedSplit { let backing = native_backing(to, allocator); - let (layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution) = with(from, |s| { + let (layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution, heaps) = with(from, |s| { (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso, - s.resolution.clone()) + s.resolution.clone(), s.heaps) }); - let (old, blocks) = with(to, |s| { + let (old, blocks, res_bufs, res_marks, res_untracked, had_fb) = with(to, |s| { let old = std::mem::replace(&mut s.allocator, 0); s.arena = Default::default(); - (old, std::mem::take(&mut s.uma)) + s.heap_bound = false; + // the two-pass record buffers and argument scratch of `to`'s previous recording, as in + // `reset`: the GPU may still read them, so the new one takes fresh ones + (s.scratch, s.scratch_used, s.scratch_taken, s.scratch_in_args, s.record_open) = (None, 0, 0, false, None); + let mut res_bufs = std::mem::take(&mut s.res_retired); + if let Some(b) = s.res_buf.take() { + res_bufs.push(b); + } + res_bufs.extend(s.end_batch()); + let res_marks = std::mem::take(&mut s.res_marks); + let res_untracked = std::mem::take(&mut s.res_untracked); + let had_fb = !s.fb_uses.is_empty(); + s.fb_uses.clear(); + (old, std::mem::take(&mut s.uma), res_bufs, res_marks, res_untracked, had_fb) }); + if !res_bufs.is_empty() || !res_marks.is_empty() || res_untracked || had_fb { + untrack_two_pass_list(to as usize); + } + unmark_deferring(to); console_list::hold_until_reset(old, blocks); - PreparedSplit { to: to as usize, allocator: backing, layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution } + retire_recording_res(old, res_bufs, res_marks, res_untracked); + PreparedSplit { to: to as usize, allocator: backing, layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution, heaps } } /// Install a preflighted split state without cloning or growing the state map. pub(super) fn install_prepared_split(prepared: PreparedSplit) { - let PreparedSplit { to, allocator, layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution } = prepared; + let PreparedSplit { to, allocator, layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution, heaps } = prepared; let entry = STATES.get(to).expect("prepared split destination state"); let old_resolution = { let mut s = entry.state.lock().unwrap(); @@ -451,15 +1282,81 @@ pub(super) fn install_prepared_split(prepared: PreparedSplit) { s.args_gfx = args_gfx; s.rs_gfx = rs_gfx; s.pso = pso; + s.heaps = heaps; std::mem::replace(&mut s.resolution, resolution) }; drop(old_resolution); } +/// The title changed what descriptor heaps the list has: they are looked at again. +pub(super) fn heaps_changed(list: *mut c_void) { + with(list, |s| s.heap_bound = false); +} + pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: usize) { install_prepared_split(prepare_split(from, to, allocator)); } +/// The pipeline the title has bound on `this` (a stand-in while its build goes on). +pub(super) fn bound_pso(this: *mut c_void) -> usize { + with(this, |s| s.pso) +} + +/// `XCL_DUMP_TARGETS`: the resources the first 16 slots of each descriptor table of `this`'s +/// graphics arguments name, each once (as `trace_reads_of_watched` reads them). +pub(super) fn table_resources(this: *mut c_void) -> Vec { + table_resources_of(this, true, 16) +} + +/// The resources the first `slots` slots of each descriptor table of `this`'s graphics (`gfx`) +/// or compute arguments name, each once. +fn table_resources_of(this: *mut c_void, gfx: bool, slots: usize) -> Vec { + let Some(u) = crate::gpu::uma::get() else { return Vec::new() }; + let (layout, args) = with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) }); + let Some(layout) = layout else { return Vec::new() }; + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); + let mut out = Vec::new(); + for p in layout.params.iter() { + let Param::Table { at } = *p else { continue }; + let t = word(at as usize) as usize; + for k in 0..slots { + if let Some(r) = super::console_heap::resource_at(u.base() + t + 32 * k).filter(|r| !out.contains(r)) { + out.push(r); + } + } + } + out +} + +/// `XCL_CAPTURE_FRAME`: a draw or dispatch of the title's on `this` (`gfx`: with the graphics +/// root arguments), with the root arguments, heaps and pipeline it has, until the call returns. +pub(super) unsafe fn capture_work(this: *mut c_void, kind: impl FnOnce() -> super::capture::WorkKind, gfx: bool) -> super::capture::Guard { + use super::capture::{RootArg, RootVal}; + super::capture::op(this, || { + let (root, heaps, pso) = with(this, |s| { + let (layout, args) = if gfx { (&s.layout_gfx, &s.args_gfx) } else { (&s.layout, &s.args) }; + let word = |at: usize| args.get(at..at + 4).map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap())); + let root: Vec = layout.as_ref().map_or(Vec::new(), |l| { + l.params + .iter() + .enumerate() + .map(|(i, p)| RootArg { + i: i as u32, + v: match *p { + Param::Constants { at, count } => RootVal::Constants((0..count as usize).map(|k| word(at as usize + 4 * k)).collect()), + Param::Descriptor { at } => RootVal::View(word(at as usize) as u64 | (word(at as usize + 4) as u64) << 32), + Param::Table { at } => RootVal::Table(word(at as usize)), + }, + }) + .collect() + }); + (root, s.heaps, s.pso) + }); + let views = table_resources_of(this, gfx, super::capture::TABLE_SLOTS); + Some(super::capture::work(this, kind(), pso, gfx, root, heaps, views)) + }) +} + /// A put-off dispatch that could not be recorded. pub(super) fn dispatch_dropped() { count(DISPATCHES_SKIPPED); @@ -473,8 +1370,18 @@ pub(super) fn pass_arena(from: *mut c_void, to: *mut c_void) { /// The list is gone. pub(super) fn forget(list: *mut c_void) { - if let Some(s) = take_state(list as usize) { + unmark_deferring(list); + if let Some(mut s) = take_state(list as usize) { + let batch = s.end_batch(); + if !s.res_retired.is_empty() || s.res_buf.is_some() || batch.is_some() || !s.res_marks.is_empty() || s.res_untracked || !s.fb_uses.is_empty() { + untrack_two_pass_list(list as usize); + } console_list::hold_until_reset(s.allocator, s.uma); + if let Some(b) = s.res_buf.take() { + s.res_retired.push(b); + } + s.res_retired.extend(batch); + retire_recording_res(s.allocator, s.res_retired, s.res_marks, s.res_untracked); } } @@ -507,6 +1414,16 @@ pub(crate) fn remove_state_for_test(list: *mut c_void) { drop(take_state(list as usize)); } +/// SetDescriptorHeaps: the console addresses of `heaps`, for shaders that index them themselves +/// (`Layout::heaps`). +pub(super) fn set_heaps(list: *mut c_void, heaps: &[usize]) { + let mut bases = [0u32; 2]; + for (sampler, base) in heaps.iter().filter_map(|&h| super::console_heap::base(h)) { + bases[sampler as usize] = base; + } + with(list, |s| s.heaps = bases); +} + /// bytes of parameter `i` at constant `offset` (of the compute or the graphics arguments) fn put_in(list: *mut c_void, gfx: bool, i: u32, offset: u32, bytes: &[u8]) { with(list, |s| { @@ -530,6 +1447,8 @@ fn put(list: *mut c_void, i: u32, offset: u32, bytes: &[u8]) { /// #34 SetGraphicsRootSignature (PC #30) pub(super) unsafe extern "system" fn set_graphics_root_signature(this: *mut c_void, rs: *mut c_void) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::BindState); + let _c = super::capture::op(this, || Some(super::capture::Op::RootSig { gfx: true, rs: rs as usize })); let layout = console_list::layout_of(rs as usize); with(this, |s| { s.args_gfx = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; @@ -541,18 +1460,21 @@ pub(super) unsafe extern "system" fn set_graphics_root_signature(this: *mut c_vo /// #36 SetGraphicsRootDescriptorTable (PC #32) pub(super) unsafe extern "system" fn set_graphics_root_table(this: *mut c_void, i: u32, handle: u64) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::BindState); put_in(this, true, i, 0, &(handle as u32).to_le_bytes()); } /// #38 SetGraphicsRoot32BitConstant (PC #34) pub(super) unsafe extern "system" fn set_graphics_root_constant(this: *mut c_void, i: u32, value: u32, offset: u32) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::BindState); put_in(this, true, i, offset, &value.to_le_bytes()); } /// #40 SetGraphicsRoot32BitConstants (PC #36) pub(super) unsafe extern "system" fn set_graphics_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::BindState); if !data.is_null() { let bytes: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); put_in(this, true, i, offset, &bytes); @@ -563,6 +1485,7 @@ pub(super) unsafe extern "system" fn set_graphics_root_constants(this: *mut c_vo /// #40 / #42) pub(super) unsafe extern "system" fn set_graphics_root_descriptor(this: *mut c_void, i: u32, va: u64) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::BindState); note_address(va); put_in(this, true, i, 0, &va.to_le_bytes()); } @@ -583,27 +1506,91 @@ fn note_address(va: u64) { } } -/// Immutable classification of one successfully created command signature. Replacing this value -/// in one map operation prevents address reuse or concurrent execution from mixing generations. -#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] -pub(super) struct IndirectSignatureInfo { - dispatch_only_stride: u32, - flags: u8, +/// Bytes asked for at a root view's address in a GPU view (`view_want`). A root view names an +/// address and no size, and no lookup by address says which of the title's buffers it lies in. +const ROOT_VIEW_BYTES: u64 = 64 << 10; + +/// The view windows of unified memory as one range (start, bytes; 0 bytes: none, as in every +/// layout below 16 windows). The layout is fixed when unified memory is made, so an address the +/// title gives costs one compare to be told apart from a GPU view. +pub(super) fn view_span() -> (u64, u64) { + static SPAN: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); + *SPAN.get_or_init(|| crate::gpu::uma::get().map_or((0, 0), view_span_of)) } -impl IndirectSignatureInfo { - const DISPATCHES: u8 = 1; - const ROOT_CHANGES: u8 = 2; +/// `view_span` of `u` (its view windows follow each other). +pub(super) fn view_span_of(u: &crate::gpu::uma::Uma) -> (u64, u64) { + let mut views = (0..u.shader_windows()).filter(|&k| u.is_view_window(k)).map(|k| u.window(k)); + let Some((start, bytes)) = views.next() else { return (0, 0) }; + let end = views.last().map_or(start + bytes, |(at, bytes)| at + bytes); + (start as u64, (end - start) as u64) +} - pub(super) fn new(dispatches: bool, root_changes: bool, dispatch_only_stride: Option) -> Self { - Self { - dispatch_only_stride: dispatch_only_stride.unwrap_or(0), - flags: (dispatches as u8) * Self::DISPATCHES | (root_changes as u8) * Self::ROOT_CHANGES, - } - } +/// Whether `va` lies in `span` (a `view_span`). +pub(super) fn in_span((start, bytes): (u64, u64), va: u64) -> bool { + va.wrapping_sub(start) < bytes +} - fn dispatches(self) -> bool { self.flags & Self::DISPATCHES != 0 } - fn root_changes(self) -> bool { self.flags & Self::ROOT_CHANGES != 0 } +/// Whether `va` lies in a view window. +pub(super) fn in_views(va: u64) -> bool { + in_span(view_span(), va) +} + +/// `view_want::want` for an address the title gave the GPU: one compare for any other address. +pub(super) fn want_view(path: super::view_want::Path, va: u64, len: u64) -> bool { + in_views(va) && super::view_want::want(path, va, len) +} + +/// The root views of `args` (packed by `layout`) in the view windows `span`, and the bytes asked +/// for at each. +fn root_views_wanted<'a>(layout: &'a Layout, args: &'a [u8], span: (u64, u64)) -> impl Iterator + 'a { + console_list::root_views(layout, args).filter(move |&va| in_span(span, va)).map(|va| (va, ROOT_VIEW_BYTES)) +} + +/// A bind of the root arguments `args`: the tiles of the root views among them that lie in a GPU +/// view are asked for (on `path`), before the list that reads them is submitted. Without view +/// windows one compare a bind. +pub(super) fn want_root_views(layout: Option<&Layout>, args: &[u8], path: super::view_want::Path) { + let span = view_span(); + if span.1 == 0 { + return; + } + let Some(l) = layout else { return }; + for (va, len) in root_views_wanted(l, args, span) { + super::view_want::want(path, va, len); + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct DispatchMeshSig { + companion_dispatch: usize, + byte_stride: u32, + mesh_offset: u32, +} + +static DISPATCH_MESH_SIGS: Mutex>> = Mutex::new(None); + +/// Immutable classification of one successfully created command signature. Replacing this value +/// in one map operation prevents address reuse or concurrent execution from mixing generations. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(super) struct IndirectSignatureInfo { + dispatch_only_stride: u32, + flags: u8, +} + +impl IndirectSignatureInfo { + const DISPATCHES: u8 = 1; + const ROOT_CHANGES: u8 = 2; + + pub(super) fn new(dispatches: bool, root_changes: bool, dispatch_only_stride: Option) -> Self { + Self { + dispatch_only_stride: dispatch_only_stride.unwrap_or(0), + flags: (dispatches as u8) * Self::DISPATCHES | (root_changes as u8) * Self::ROOT_CHANGES, + } + } + + fn dispatches(self) -> bool { self.flags & Self::DISPATCHES != 0 } + fn root_changes(self) -> bool { self.flags & Self::ROOT_CHANGES != 0 } fn dispatch_only(self) -> Option { (self.dispatch_only_stride != 0).then_some(self.dispatch_only_stride) } } @@ -618,1882 +1605,5055 @@ fn indirect_signature(sig: usize) -> IndirectSignatureInfo { .and_then(|signatures| signatures.get(&sig).copied()).unwrap_or_default() } -/// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a -/// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root -/// arguments themselves cannot be – skipped, logged) -pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { - execute_indirect_classified(this, sig, max, args, args_off, count_buf, count_off, indirect_signature(sig)) +pub(super) fn note_dispatch_mesh_signature(sig: usize, companion_dispatch: usize, byte_stride: u32, mesh_offset: u32) { + DISPATCH_MESH_SIGS + .lock() + .unwrap() + .get_or_insert_with(HashMap::new) + .insert(sig, DispatchMeshSig { companion_dispatch, byte_stride, mesh_offset }); } -pub(super) unsafe fn execute_indirect_classified( - this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, - count_buf: usize, count_off: u64, signature: IndirectSignatureInfo, -) { - let (pso, resolution) = with(this, |state| (state.pso, state.resolution.clone())); - execute_indirect_snapshot( - this, sig, max, args, args_off, count_buf, count_off, signature, pso, resolution, true, - ) +/// A command signature was made at `sig`: what a freed one there was noted as goes (a mesh +/// dispatch signature is noted again after this). +pub(super) fn forget_dispatch_mesh_signature(sig: usize) { + if let Some(m) = DISPATCH_MESH_SIGS.lock().unwrap().as_mut() { + m.remove(&sig); + } } -pub(super) unsafe fn execute_indirect_retained( - this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, - count_buf: usize, count_off: u64, signature: IndirectSignatureInfo, -) { - let (pso, resolution) = with(this, |state| (state.pso, state.resolution.clone())); - execute_indirect_snapshot( - this, sig, max, args, args_off, count_buf, count_off, signature, pso, resolution, false, - ) +fn dispatch_mesh_sig_of(sig: usize) -> Option { + DISPATCH_MESH_SIGS.lock().unwrap().as_ref()?.get(&sig).copied() } -unsafe fn execute_indirect_snapshot( - this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, - count_buf: usize, count_off: u64, signature: IndirectSignatureInfo, raw_pso: usize, - resolution: Option, allow_defer: bool, -) { - 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 dispatches = signature.dispatches(); - let _detail = crate::stall::detail_span(if dispatches { crate::stall::StallKind::DetailDispatch } else { crate::stall::StallKind::DetailDraw }); - let retained_compute = resolution.as_ref().map(|resolution| resolution.is_compute()); - if allow_defer && dispatches && retained_compute == Some(true) { - let resolution = resolution.as_ref().unwrap(); - if super::list_x::defer_retained(this, resolution, super::list_x::Deferred::Indirect { - sig, max, args, args_off, count_buf, count_off, signature, - }) { return } - } - let (pso, bound_unbuilt) = match resolution { - Some(resolution) => match resolution.resolve_for_indirect() { - super::pso_async::IndirectPipelineChoice::Exact { raw, generation } => { - super::list_x::record_native_generation(this as usize, Some(generation)); - (raw, false) - } - super::pso_async::IndirectPipelineChoice::InitialFallback { raw, bound_unbuilt } => { - (raw, bound_unbuilt) - } - super::pso_async::IndirectPipelineChoice::Unavailable => { - count_indirect_skip(dispatches); - return; - } +unsafe fn emit_uav_barrier(list: &ID3D12GraphicsCommandList, res: Option<&ID3D12Resource>) { + let mut b = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(res.cloned()), + }), }, - None => (raw_pso, false), }; - let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); - let args_off_title = args_off; - let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); - if !gfx && !compute { - // A pipeline still being built (or whose build failed): its stand-in draws nothing, and - // the list may hold XCL's ABI root signature from a translated draw before it – the PC - // call with that pair is invalid (debug layer 953, "the currently set Root Signature - // doesn't match the currently set Pipeline State Object"; a retail title's world then - // hung the GPU, 0x887a0006). Skipped, like a draw or dispatch of such a pipeline. - if bound_unbuilt { - count_indirect_skip(dispatches); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: ExecuteIndirect with a pipeline that is still being built skipped"); - } - return; - } - // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in - // TWO_PASS rather than TRANSLATED_GRAPHICS. Falling through to raw PC ExecuteIndirect - // with the title's graphics root signature (e.g. a non-DispatchMesh indirect draw or a - // root-changing signature) invalidates the command list (Close → E_INVALIDARG). - if let Some(tp) = super::real::two_pass_of_exact(pso) { - count(DRAWS_SKIPPED); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!( - "D3D12.X: ExecuteIndirect with two-pass {} pipeline ({pso:#x}) skipped – PC pipeline is a mesh shader", - tp.kind - ); - } - return; - } - // a console compute program without a translation (its build failed): nothing to run, - // as for Dispatch. The PC call would run it with the list's compute root signature, which - // can still be XCL's ABI one from a translated dispatch before it (debug layer 953). - // A native PC compute pipeline is not one of these and still goes to the PC call. - // (`CONSOLE_COMPUTE` holds the title's object, which for a shared stand-in differs from - // the driver pipeline `resolve_wait` returned.) - if dispatches && retained_compute.unwrap_or_else(|| super::real::is_console_compute(raw_pso)) { - count(DISPATCHES_SKIPPED); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: ExecuteIndirect dispatch with a pipeline that has no translated console shader ({raw_pso:#x}) skipped"); - } - return; - } - // a PC pipeline: the title's root signature, as for a draw (`graphics_bound`) - let rs = with(this, |s| s.rs_gfx) as *mut c_void; - if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { - list.SetGraphicsRootSignature(r); + list.ResourceBarrier(&[std::ptr::read(&b)]); + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.UAV).pResource); +} + +unsafe fn emit_transition(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + let mut b = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(res.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + }; + list.ResourceBarrier(&[std::ptr::read(&b)]); + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); +} + +/// A UAV barrier on `res` (None: on all resources) and a transition of `res` from `before` to +/// `after`, in one ResourceBarrier call. +unsafe fn emit_uav_and_transition(list: &ID3D12GraphicsCommandList, uav: Option<&ID3D12Resource>, res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + let mut b = [ + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(uav.cloned()) }) }, + }, + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(res.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + }, + ]; + list.ResourceBarrier(&b); + std::mem::ManuallyDrop::drop(&mut (*b[0].Anonymous.UAV).pResource); + std::mem::ManuallyDrop::drop(&mut (*b[1].Anonymous.Transition).pResource); +} + +unsafe fn default_uav_buffer(dev: &ID3D12Device, bytes: u64, what: &str) -> Result { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + }; + let mut res: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut res, + ) + .map_err(|e| format!("{what} ({bytes:#x} B): {e}"))?; + // (a name for what a device removal reports about an address, `real::log_device_removed`; + // and where the first ones lie: an address just past one's end has no allocation to name) + if let Some(r) = &res { + let _ = r.SetName(&windows::core::HSTRING::from(format!("xcl {what}"))); + static MADE: AtomicU64 = AtomicU64::new(0); + let n = MADE.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 48 || n.is_power_of_two() { + let va = r.GetGPUVirtualAddress(); + crate::xlog_info!("D3D12.X: {what} #{n}: GPU addresses {va:#x} .. {:#x}", va + bytes); } - return fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)); } - if signature.root_changes() { - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: ExecuteIndirect that changes root arguments with a translated pipeline skipped"); + res.ok_or_else(|| format!("null {what}")) +} + +/// Groups of a two-pass dispatch that have a record: one record a group in `cap_bytes` of +/// records of `record_bytes`, and every group in X, the mesh pass's `split` times as many (at most +/// 65 535 a dimension). The compute pass writes record `gid.x` with no bound of its own. +fn record_groups(cap_bytes: u64, record_bytes: u64, split: u32) -> u32 { + (cap_bytes / record_bytes.max(1)).min(65_535 / split.max(1) as u64) as u32 +} + +/// The ExecuteIndirects of a two-pass ExecuteIndirect of `max` commands, each of one command and +/// followed by a UAV barrier on the records: (command, compute pass). Each command's compute pass +/// writes its records from record 0, so the next one goes only after the mesh pass drew them. +fn two_pass_steps(max: u32) -> impl Iterator { + (0..max).flat_map(|k| [(k, true), (k, false)]) +} + +/// `XCL_TWO_PASS_BATCH=1`: two-pass draws record fewer barriers (read once). Their records go +/// in the two halves of the record buffer in turn (`Records::Halves`), so a draw's mesh pass +/// needs no UAV barrier after it: the next compute pass writes the other half, and the barrier +/// after that one orders the mesh pass before the half is written again. An ExecuteIndirect's +/// rewritten arguments stay in INDIRECT_ARGUMENT until the next one rewrites into the block, with +/// the UAV barrier before the rewrite in the same ResourceBarrier call as that transition. +/// `XCL_TWO_PASS_BATCH=2` also defers runs of two-pass draws (`flush_two_pass`); the draws it +/// does not defer go as with 1. +fn two_pass_batch() -> bool { + two_pass_mode() >= 1 +} + +/// `XCL_TWO_PASS_BATCH=2`: runs of two-pass draws are deferred (`flush_two_pass`). +pub(super) fn two_pass_defer() -> bool { + two_pass_mode() == 2 +} + +/// `XCL_TWO_PASS_BATCH`: 0 (unset or anything else), 1 or 2 (read once). +fn two_pass_mode() -> u8 { + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("XCL_TWO_PASS_BATCH").as_deref().map(str::trim) { + Ok("1") => 1, + Ok("2") => 2, + _ => 0, + }) +} + +/// Record regions of a two-pass pass (`TwoPassStep::Pass`): the first half, the second half, or +/// the whole buffer (both). +const HALF_0: u8 = 0b01; +const HALF_1: u8 = 0b10; +const WHOLE: u8 = HALF_0 | HALF_1; + +/// How a two-pass draw lays out its records. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Records { + /// every command from the start of the buffer, a UAV barrier after each pass + Whole, + /// commands in the buffer's two halves in turn, no UAV barrier after a mesh pass + Halves, +} + +/// A step of a two-pass draw on the PC list (`two_pass_plan`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum TwoPassStep { + /// the compute pass (writes the records of `region`) or the mesh pass (reads them) of command `k` + Pass { k: u32, compute: bool, region: u8 }, + /// a UAV barrier on the records + Barrier, +} + +/// The steps of a two-pass draw with `commands` indirect commands or direct mesh slices, +/// after draws that left a mesh pass reading `open` with no barrier since. `Whole` is the order +/// the draws had before `Halves`: `two_pass_steps`, a barrier after each. +fn two_pass_plan(commands: u32, records: Records, open: Option) -> Vec { + let mut v = Vec::with_capacity(commands as usize * 4 + 1); + let first = match (records, open) { + (_, None) => HALF_0, + (Records::Halves, Some(HALF_0)) => HALF_1, + (Records::Halves, Some(HALF_1)) => HALF_0, + _ => { + v.push(TwoPassStep::Barrier); + HALF_0 } - return; - } - let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; - if compute && max == 1 && count_buf == 0 && signature.dispatch_only().is_some() { - let chained = indirect_address(args, args_off_title, args_off).map_or(Ok(false), |address| { - super::real::dispatch_chain::execute_indirect(list, raw_pso, pso, with(this, |s| s.allocator), address, - |root| bind_abi_with_root_resolved(this, list, raw_pso, pso, false, root, [0; 3]).map(|_| ())) - }); - match chained { - Ok(true) => { - count(DISPATCHES); - return; + }; + for (k, compute) in two_pass_steps(commands) { + match records { + Records::Whole => { + v.push(TwoPassStep::Pass { k, compute, region: WHOLE }); + v.push(TwoPassStep::Barrier); } - Ok(false) => {} - Err(e) => { - count(DISPATCHES_SKIPPED); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: split ExecuteIndirect skipped: {e}"); + Records::Halves => { + let region = if k % 2 == 0 { first } else { first ^ WHOLE }; + v.push(TwoPassStep::Pass { k, compute, region }); + if compute { + v.push(TwoPassStep::Barrier); } - return; } } } - match bind_abi_resolved(this, list, raw_pso, pso, gfx) { - Ok(()) => { - if compute { - if super::real::pso_dispatch_remap_exact(pso).is_some() { - match super::real::remap_fallback::whole_exact(pso) { - Ok(fallback) => super::real::bind_pipeline_exact( - this, raw_pso, fallback.as_raw() as usize, - ), - Err(e) => { - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: ExecuteIndirect remap fallback skipped: {e}"); - } - count(DISPATCHES_SKIPPED); - return; - } - } - } - match super::real::dispatch_chain::whole(pso) { - Ok(Some(whole)) => super::real::bind_pipeline_exact( - this, raw_pso, whole.as_raw() as usize, - ), - Ok(None) => {} - Err(e) => { - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO: {e}"); - } - count(DISPATCHES_SKIPPED); - return; - } - } - } - count(if gfx { DRAWS } else { DISPATCHES }); - fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)) + v +} + +/// What a mesh pass may still be reading after `step`, with `open` before it. +fn open_after(open: Option, step: TwoPassStep) -> Option { + match step { + TwoPassStep::Barrier => None, + TwoPassStep::Pass { compute: false, region, .. } => Some(open.unwrap_or(0) | region), + TwoPassStep::Pass { compute: true, .. } => open, + } +} + +/// `plan` on `list` with the records in `res` at `res_va`: `pass(k, compute, records)` records a +/// pass with its region at GPU address `records` (the second half `half` bytes in). What each +/// step leaves a mesh pass reading is kept for the next draw's plan (`State::record_open`). +unsafe fn run_two_pass_plan( + this: *mut c_void, + list: &ID3D12GraphicsCommandList, + plan: &[TwoPassStep], + res: &ID3D12Resource, + res_va: u64, + half: u64, + mut pass: impl FnMut(u32, bool, u64) -> Result<(), String>, +) -> Result<(), String> { + for &step in plan { + match step { + TwoPassStep::Barrier => emit_uav_barrier(list, Some(res)), + TwoPassStep::Pass { k, compute, region } => pass(k, compute, res_va + if region == HALF_1 { half } else { 0 })?, } - Err(e) => { - count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: ExecuteIndirect with a translated pipeline skipped: {e}"); - } + with(this, |s| s.record_open = open_after(s.record_open, step)); + } + Ok(()) +} + +/// The record buffer of a two-pass draw that needs `need` bytes of records (shrinking down to +/// `min_fit` when cap-constrained): buffer, address, the bytes of a region and the layout. +/// `Halves` (with `two_pass_batch`) when twice the buffer the draw would have had whole fits +/// `RECORD_MAX` and the two-pass buffers without waiting, shrinking, or refusing: each half +/// holds what the whole one would. +unsafe fn records_for(this: *mut c_void, need: u64, min_fit: u64, batch: bool) -> Result<(ID3D12Resource, u64, u64, Records), String> { + records_for_with_cap(this, need, min_fit, batch, two_pass_cap()) +} + +unsafe fn records_for_with_cap(this: *mut c_void, need: u64, min_fit: u64, batch: bool, budget_cap: u64) -> Result<(ID3D12Resource, u64, u64, Records), String> { + if let Some(both) = halves_bytes(need, batch) { + if let Some((buf, va, cap)) = try_ensure_res_buffer_exact_with_cap(this, both, budget_cap)? { + return Ok((buf, va, cap / 2, Records::Halves)); } } + let (buf, va, cap) = ensure_res_buffer_with_cap(this, need, min_fit, budget_cap)?; + Ok((buf, va, cap, Records::Whole)) } -fn count_indirect_skip(dispatches: bool) { - count(if dispatches { DISPATCHES_SKIPPED } else { DRAWS_SKIPPED }); - #[cfg(test)] - INDIRECT_SKIP_COUNTS.with(|counts| { - let mut next = counts.get(); - next[dispatches as usize] += 1; - counts.set(next); - }); +/// The bytes of a record buffer in halves for `need` (`records_for`), if it can have them. +fn halves_bytes(need: u64, batch: bool) -> Option { + let both = record_buffer_bytes(need) * 2; + (batch && both <= RECORD_MAX).then_some(both) } -#[cfg(test)] -thread_local! { - static INDIRECT_SKIP_COUNTS: std::cell::Cell<[u32; 2]> = const { std::cell::Cell::new([0; 2]) }; +// --------------------------------------------------------------------------------------- +// deferred two-pass draws (`XCL_TWO_PASS_BATCH=2`) +// +// A two-pass draw on a direct list is not recorded at once: what both of its passes read is +// written to unified memory as the unbatched draw would write it (its io blocks with the title's +// root arguments of that moment, the argument rewrite's constants), and the draw waits in the +// list's `State::deferred` with a region of its own in the list's batch record buffer. The run +// goes out (`flush_two_pass`) before any title call on the list that is not a root-argument set +// or another such draw (`before_list_call`, in front of every slot of the list's vtable), at the +// list's Close, at `XCL_TWO_PASS_BATCH_MOST` draws and when the next draw's records do not fit: +// the argument rewrites, all compute passes, one barrier, the mesh passes in the title's order. +// Between the draws of a run nothing reaches the PC list, so each mesh pass draws with the PC +// state (render targets, viewports, …) its draw had. +// --------------------------------------------------------------------------------------- + +/// Most draws in a run (`XCL_TWO_PASS_BATCH_MOST`, 64 by default; read once). +fn batch_most() -> usize { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| std::env::var("XCL_TWO_PASS_BATCH_MOST").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(64).max(1)) } -#[cfg(test)] -fn take_indirect_skip_counts() -> [u32; 2] { - INDIRECT_SKIP_COUNTS.with(|counts| counts.replace([0; 2])) +/// Bytes of a list's batch record buffer (`XCL_TWO_PASS_BATCH_MB`, 128 MiB by default; read +/// once). An ExecuteIndirect's region is what its draw would have had alone, up to 32 MiB. +fn batch_records_bytes() -> u64 { + static BYTES: std::sync::OnceLock = std::sync::OnceLock::new(); + *BYTES.get_or_init(|| std::env::var("XCL_TWO_PASS_BATCH_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(128).clamp(1, 1024) << 20) } -unsafe fn indirect_address(resource: usize, title_offset: u64, pc_offset: u64) -> Option { - match super::real::console_buffer(resource) { - Some((base, size)) if title_offset.checked_add(12).is_some_and(|end| end <= size as u64) => { - super::real::uma_va_of(base + title_offset as usize) - } - Some(_) => None, - None => Some(ID3D12Resource::from_raw_borrowed(&(resource as *mut c_void))?.GetGPUVirtualAddress()) - .filter(|&address| address != 0).and_then(|address| address.checked_add(pc_offset)), +/// Lists with deferred draws, and how many (the hook in front of every list call looks at the +/// count first). +static DEFERRING: super::sharded::Sharded = super::sharded::Sharded::new(); +static DEFERRING_LISTS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +fn mark_deferring(list: *mut c_void) { + if DEFERRING.insert(list as usize, 1).is_none() { + DEFERRING_LISTS.fetch_add(1, Ordering::Relaxed); } } -/// XCL's own buffer for `fresh_indirect_arguments` (device, buffer): COMMON between its uses -static ARGUMENT_ORDER: Mutex> = Mutex::new(None); +fn unmark_deferring(list: *mut c_void) { + if DEFERRING.remove(list as usize).is_some() { + DEFERRING_LISTS.fetch_sub(1, Ordering::Relaxed); + } +} -/// `op` (an ExecuteIndirect on `list`) reading the arguments and count the list wrote before it. -/// -/// The console orders a dispatch that writes indirect arguments before the ExecuteIndirect that -/// reads them with a barrier that reaches the PC as a UAV barrier (`list_x::resource_barrier_x`). -/// NVIDIA's driver (RTX 5090) fetches an ExecuteIndirect's arguments without waiting for that -/// barrier: it ran the count that was there before the list in all but a few of 100 tries, also -/// when the dispatch wrote them through another resource over the same memory, as translated -/// shaders do through the memory window buffers (`execute_indirect_reads_the_arguments_written_before_it`). -/// A retail title's ExecuteIndirect after the dispatch that writes its group count then runs -/// whatever count the memory held before. A transition to INDIRECT_ARGUMENT makes the driver -/// wait for the writes – of any buffer, as measured there. The title's buffer is in the title's -/// state (its transitions reach the PC list), so a buffer of XCL's own takes it, COMMON -> -/// INDIRECT_ARGUMENT before and back after. Only on a list XCL made (`list_x::on_create`) and -/// not a bundle, which cannot hold barriers; its type comes from XCL's state, not a call to it. -unsafe fn fresh_indirect_arguments(list: *mut c_void, op: impl FnOnce()) { - let tracked = super::list_x::tracked_list_type(list).is_some_and(|t| t != D3D12_COMMAND_LIST_TYPE_BUNDLE); - let buffer = if tracked { ID3D12GraphicsCommandList::from_raw_borrowed(&list).and_then(|l| argument_order_buffer(l)) } else { None }; - let Some(buffer) = buffer else { return op() }; - let b = buffer.as_raw() as usize; - super::list_x::transition(list, b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); - op(); - super::list_x::transition(list, b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); +/// What a deferred draw runs besides its two stages. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum DeferredWork { + /// DispatchMesh: the compute pass's groups, the mesh pass's + Mesh { groups: u32, mesh_groups: u32 }, + /// ExecuteIndirect of one command: its argument rewrite into `block` (in `before` until the + /// run), the companion Dispatch signature and the DispatchMesh one, where each pass's command is + Indirect { rewrite: Rewrite, block: usize, before: D3D12_RESOURCE_STATES, companion: usize, sig: usize, compute_at: u64, mesh_at: u64 }, } -/// The device's buffer for `fresh_indirect_arguments` (made on first use) -unsafe fn argument_order_buffer(list: &ID3D12GraphicsCommandList) -> Option { - let mut dev: Option = None; - list.GetDevice(&mut dev).ok()?; - let dev = dev?; - let mut g = ARGUMENT_ORDER.lock().unwrap(); - if let Some((_, b)) = g.as_ref().filter(|(d, _)| *d == dev.as_raw() as usize) { - return Some(b.clone()); - } - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: 256, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - ..Default::default() - }; - let mut b: Option = None; - if let Err(e) = dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut b) { - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: ExecuteIndirect: no buffer to order its arguments after the writes before it ({e}) – it may read old ones"); +/// What a deferred draw records: everything it reads was fixed when the title made it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct DrawSnap { + compute: StageBind, + mesh: StageBind, + work: DeferredWork, +} + +/// What a run holds (`State::deferred`): a deferred draw, or a SetPipelineState of the title to a +/// two-pass pipeline between them, recorded (`replay_pipeline_bind`: the PC pipeline its retained +/// bind selects and what `list_x::on_set_pipeline_state` sets with it, such as the depth bias) +/// where it came among the mesh passes. The reference keeps the pipeline until then. +enum RunItem { + Draw(DeferredDraw), + Bind { pso: usize, resolution: Option, _held: Option }, + StencilRef(u32), + Topology(u32), + Scissors(Vec<[i32; 4]>), +} + +/// A run item as `batch_commands` takes it. +#[derive(Clone, Debug, PartialEq, Eq)] +enum Step { + Draw(DrawSnap), + Bind(usize), + StencilRef(u32), + Topology(u32), + Scissors(Vec<[i32; 4]>), +} + +impl RunItem { + fn step(&self) -> Step { + match self { + RunItem::Draw(d) => Step::Draw(d.snap), + RunItem::Bind { pso, .. } => Step::Bind(*pso), + RunItem::StencilRef(r) => Step::StencilRef(*r), + RunItem::Topology(t) => Step::Topology(*t), + RunItem::Scissors(r) => Step::Scissors(r.clone()), } - return None; } - let b = b?; - *g = Some((dev.as_raw() as usize, b.clone())); - Some(b) } -/// A DrawInstanced of the console's rect list (three corners of each rectangle, the fourth -/// implied) as two triangles a rectangle; false: not a rect list, or one this cannot expand -/// (the caller draws the three vertices as a triangle – half of each rectangle). -/// -/// The PC has no rect lists. The fourth corner is made here, on the CPU, from the title's -/// vertex data: v3 = v0 + v2 − v1 (seen in a retail title's full-screen passes: (−1,1) (−1,−1) -/// (1,−1) with texture coordinates (0,0) (0,1) (1,1) – the missing corner is (1,1), (1,0)). -/// The vertex layout is not looked at: each 4-byte word that is the same in all three vertices -/// is kept (a packed colour), any other is taken as a float. Vertices a shader makes from the -/// vertex index alone (no vertex buffer) are not expanded. -unsafe fn draw_rects(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) -> bool { - if !cpu_rect_expansion(pso) { - return false; - } - let Some(vbs) = super::list_x::rect_list_state(this) else { return false }; - let rects = (vertices / 3) as usize; - if vbs.is_empty() || rects == 0 || rects > 4096 { - return false; +/// A deferred two-pass draw (`RunItem::Draw`). +struct DeferredDraw { + snap: DrawSnap, + /// (what the snapshot names stays alive until the run is recorded) + _tp: Arc, + _mesh_pso: Option, + _block: Option, + /// the pipeline the title bound, for the counts; the kind and size for `XCL_GPU_TIMES` + raw_pso: usize, + kind: &'static str, + size: [u32; 3], +} + +/// Why a two-pass draw is recorded at once rather than deferred. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum NoDefer { + /// `XCL_TWO_PASS_BATCH` is not 2 + Off, + /// not a direct list (a bundle cannot hold the barriers; a compute list draws nothing) + NotDirect, + /// `XCL_CAPTURE_FRAME` records each call where it is made + Capture, + /// an ExecuteIndirect of more than one command (each runs its passes in turn) + Commands, + /// its records are more than a batch record buffer + TooBig, +} + +/// Whether a two-pass draw of `commands` commands whose records take `region` bytes is deferred. +fn defer_check(on: bool, ty: Option, capture: bool, commands: u32, region: u64, batch_bytes: u64) -> Result<(), NoDefer> { + if !on { + return Err(NoDefer::Off); } - let mut views = Vec::new(); - for &(slot, (va, bytes, stride), _) in &vbs { - let (s, at) = (stride as usize, va as usize + first_vertex as usize * stride as usize); - let len = rects * 3 * s; - if va == 0 || s == 0 || s % 4 != 0 || first_vertex as usize * s + len > bytes as usize || !crate::gpu::shader::readable(at, len) { - return false; - } - let p = allocate_upload_memory(this, rects * 6 * s, 16); - if p.is_null() { - return false; - } - let word = |v: usize, w: usize| (at as *const u8).add(v * s + w * 4).cast::().read_unaligned(); - for r in 0..rects { - let out = p.add(r * 6 * s); - let src = (at as *const u8).add(r * 3 * s); - // v0 v1 v2, then v0 v2 v3 - std::ptr::copy_nonoverlapping(src, out, 3 * s); - std::ptr::copy_nonoverlapping(src, out.add(3 * s), s); - std::ptr::copy_nonoverlapping(src.add(2 * s), out.add(4 * s), s); - for w in 0..s / 4 { - let (a, b, c) = (word(r * 3, w), word(r * 3 + 1, w), word(r * 3 + 2, w)); - let d = if a == b && b == c { a } else { (f32::from_bits(a) + f32::from_bits(c) - f32::from_bits(b)).to_bits() }; - out.add(5 * s + w * 4).cast::().write_unaligned(d); - } - } - views.push((slot, D3D12_VERTEX_BUFFER_VIEW { BufferLocation: super::list_x::pc_va_of(p as u64), SizeInBytes: (rects * 6 * s) as u32, StrideInBytes: stride })); + if ty != Some(D3D12_COMMAND_LIST_TYPE_DIRECT) { + return Err(NoDefer::NotDirect); } - for (slot, v) in &views { - list.IASetVertexBuffers(*slot, Some(&[*v])); + if capture { + return Err(NoDefer::Capture); } - list.DrawInstanced(rects as u32 * 6, instances, 0, first_instance); - for &(slot, _, pc) in &vbs { - if let Some(v) = pc { - list.IASetVertexBuffers(slot, Some(&[v])); - } + if commands != 1 { + return Err(NoDefer::Commands); } - static N: AtomicU64 = AtomicU64::new(0); - if N.fetch_add(1, Ordering::Relaxed) == 0 { - crate::xlog_info!("D3D12.X: rect lists are drawn as two triangles a rectangle, the fourth corner made on the CPU"); + if region > batch_bytes { + return Err(NoDefer::TooBig); } - true + Ok(()) } -/// Whether a rect list drawn with the bound pipeline `pso` is expanded on the CPU (`draw_rects`): -/// not with the rect list GS (`real::has_rect_list_gs`), which completes each rect itself – both -/// would draw every rect twice (each CPU half is three corners of the rect). -fn cpu_rect_expansion(pso: usize) -> bool { - !super::real::has_rect_list_gs(pso) +/// Where in a batch record buffer of `bytes` with `used` taken a draw's `region` goes: None, the +/// run so far is recorded first and it goes at the start. +fn batch_place(used: u64, region: u64, bytes: u64) -> Option { + (used.saturating_add(region) <= bytes).then_some(used) } -/// #12 DrawInstanced -pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) { - let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDraw); - DRAW_ARGS.with(|d| d.set((false, vertices, instances, first_vertex, 0))); - if let Some((list, pso)) = graphics_bound(this) { - if draw_rects(this, &list, pso, vertices, instances, first_vertex, first_instance) { - return; - } - super::list_x::sync_title_buffers(this, None, first_vertex, vertices, if first_instance != 0 { instances.max(2) } else { instances }); - list.DrawInstanced(vertices, instances, first_vertex, first_instance); - } +/// Bytes of a draw's region: its records, 256-aligned. +fn batch_region_bytes(need: u64) -> u64 { + need.max(1).next_multiple_of(256) } -thread_local! { - /// the draw being bound: (indexed, count, instances, first index / vertex, base vertex) – for the frame trace - static DRAW_ARGS: std::cell::Cell<(bool, u32, u32, u32, i32)> = const { std::cell::Cell::new((false, 0, 0, 0, 0)) }; +/// Console list slots a run of deferred draws goes on across (`before_list_call`): QueryInterface, +/// AddRef, Release and the private data / name / device / type ones (they record nothing), the +/// compute and graphics root signature and root argument sets (kept by XCL, `put_in`: nothing +/// reaches the PC list), SetPipelineState, ExecuteIndirect and DispatchMesh (at their slots of +/// the title's layout, `real::NEWER_LIST_SLOTS`; they go into the run or record it first +/// themselves: `set_pipeline_state`). Everything else – barriers, copies, clears, other draws, +/// dispatches, render targets, viewports, heaps, queries, predication, bundles, Close, Reset, +/// the console's own methods – records the run first. +fn keeps_two_pass_batch(slot: usize, newer_layout: bool) -> bool { + let (ei, dm) = if newer_layout { (61, 129) } else { (59, 127) }; + matches!(slot, 0..=8 | 20 | 22 | 24 | 25 | 33..=46) || slot == ei || slot == dm || (newer_layout && slot == 142) } -#[cfg(test)] -static LAST_ABI_PSO: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -#[cfg(test)] -static STOP_ABI_LIST: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -#[cfg(test)] -static STOP_ABI_AFTER_BIND_LIST: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -#[cfg(test)] -static STOP_ABI_TEST: Mutex<()> = Mutex::new(()); +/// Whether a list call through `slot` records the list's deferred draws first. +fn flush_wanted(slot: usize, newer_layout: bool, from_title: bool, deferring: bool) -> bool { + deferring && from_title && !keeps_two_pass_batch(slot, newer_layout) +} -/// #13 DrawIndexedInstanced -pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) { - let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDraw); - if let Some(list) = prepare_indexed_draw(this, indices, instances, first_index, base_vertex) { - super::list_x::sync_title_buffers(this, Some((first_index, indices, base_vertex)), 0, 0, if first_instance != 0 { instances.max(2) } else { instances }); - emit_prepared_indexed_draw(&list, indices, instances, first_index, base_vertex, first_instance); +/// What ended a run (`flush_two_pass`), for the log: a title call through a console list slot +/// (`before_list_call`), or one of these. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum RunEnd { + Call(usize), + /// the list's Close + Close, + /// a PC Close of a segment of the list (`list_x`) + Segment, + /// `XCL_TWO_PASS_BATCH_MOST` draws + Most, + /// the next draw's records did not fit + Full, + /// a DispatchMesh / ExecuteIndirect not deferred + Draw, + /// a SetPipelineState to a pipeline that is not two-pass + Pipeline, +} + +/// Console slots counted apart in `RUN_ENDS`; the other ends after them. +const RUN_END_SLOTS: usize = 640; +static RUN_ENDS: [AtomicU64; RUN_END_SLOTS + 6] = [const { AtomicU64::new(0) }; RUN_END_SLOTS + 6]; + +fn run_end_index(e: RunEnd) -> usize { + match e { + RunEnd::Call(s) => s.min(RUN_END_SLOTS - 1), + RunEnd::Close => RUN_END_SLOTS, + RunEnd::Segment => RUN_END_SLOTS + 1, + RunEnd::Most => RUN_END_SLOTS + 2, + RunEnd::Full => RUN_END_SLOTS + 3, + RunEnd::Draw => RUN_END_SLOTS + 4, + RunEnd::Pipeline => RUN_END_SLOTS + 5, } } -/// Prepare an indexed draw once, before callers make temporary native state changes. -pub(super) unsafe fn prepare_indexed_draw( - this: *mut c_void, - indices: u32, - instances: u32, - first_index: u32, - base_vertex: i32, -) -> Option { - DRAW_ARGS.with(|d| d.set((true, indices, instances, first_index, base_vertex))); - graphics_bound(this).map(|(list, _)| list) +/// The name of `RUN_ENDS[i]` (a slot by the PC method the title's layout has there). +fn run_end_name(i: usize, newer_layout: bool) -> String { + match i.checked_sub(RUN_END_SLOTS) { + None if newer_layout && i >= 59 => format!("console list slot #{i} (newer layout)"), + None => super::real::list_slot_name(i), + Some(0) => "Close".into(), + Some(1) => "a Close of XCL's (list segment, KickoffX)".into(), + Some(2) => "XCL_TWO_PASS_BATCH_MOST draws".into(), + Some(3) => "the batch record buffer full".into(), + Some(4) => "a DispatchMesh / ExecuteIndirect not deferred".into(), + _ => "SetPipelineState to a pipeline that is not two-pass".into(), + } } -/// Submit an indexed draw whose translated graphics state has already been prepared. -pub(super) unsafe fn emit_prepared_indexed_draw( - list: &ID3D12GraphicsCommandList, - indices: u32, - instances: u32, - first_index: u32, - base_vertex: i32, - first_instance: u32, -) { - list.DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance); +/// The run ends counted so far, most first: "name count, …" (the first `n`). +fn run_ends_text(n: usize) -> String { + let mut v: Vec<(u64, usize)> = RUN_ENDS.iter().enumerate().map(|(i, c)| (c.load(Ordering::Relaxed), i)).filter(|e| e.0 > 0).collect(); + v.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); + let newer = super::real::QUEUE_SHIFTED.load(Ordering::Acquire); + v.iter().take(n).map(|&(c, i)| format!("{} {c}", run_end_name(i, newer))).collect::>().join(", ") } -/// Resolve one retained bind for correctness-critical draw or dispatch emission and record its -/// exact generation before native commands can consume it. None is fail-closed. -fn resolve_pipeline( - list: usize, - pso: usize, - resolution: Option, -) -> Option { - match resolution.map(|resolution| resolution.resolve_for_emission()) { - Some(super::pso_async::PipelineChoice::Available { raw, generation }) => { - super::list_x::record_native_generation(list, Some(generation)); - Some(raw) +/// In front of every command list slot with `XCL_TWO_PASS_BATCH=2` (`real::class_for`): a title +/// call on a list with deferred draws records them first, unless the slot keeps the run +/// (`keeps_two_pass_batch`). Calls from XCL and the runtime go on as they are. +pub(super) unsafe extern "system" fn before_list_call(caller: usize, slot: u64, frame: *const u64) -> usize { + if DEFERRING_LISTS.load(Ordering::Relaxed) == 0 { + return 0; + } + let this = *frame.add(0x80 / 8) as *mut c_void; + let deferring = DEFERRING.contains(this as usize); + let newer = super::real::QUEUE_SHIFTED.load(Ordering::Acquire); + if flush_wanted(slot as usize, newer, deferring && crate::modules::image_base_for_addr(caller).is_some(), deferring) { + flush_two_pass(this, RunEnd::Call(slot as usize)); + } + 0 +} + +/// A UAV barrier on all resources or on `uav`, and transitions, in one ResourceBarrier call +/// (`Cmd::Barriers`). +unsafe fn emit_barrier_set(list: &ID3D12GraphicsCommandList, all: bool, uav: Option<&ID3D12Resource>, transitions: &[(&ID3D12Resource, D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES)]) { + let mut b: Vec = Vec::with_capacity(transitions.len() + 2); + for r in [all.then_some(None), uav.map(Some)].into_iter().flatten() { + b.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(r.cloned()) }) }, + }); + } + for &(r, before, after) in transitions { + b.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(r.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + }); + } + if b.is_empty() { + return; + } + list.ResourceBarrier(&b); + for x in &mut b { + if x.Type == D3D12_RESOURCE_BARRIER_TYPE_UAV { + std::mem::ManuallyDrop::drop(&mut (*x.Anonymous.UAV).pResource); + } else { + std::mem::ManuallyDrop::drop(&mut (*x.Anonymous.Transition).pResource); } - Some(super::pso_async::PipelineChoice::Unavailable) => None, - None => Some(pso), } } -fn resolve_bound_graphics_pipeline(this: *mut c_void, list: usize) -> Option<(usize, usize)> { - let (pso, resolution) = with(this, |s| (s.pso, s.resolution.clone())); - resolve_pipeline(list, pso, resolution).map(|real| (pso, real)) +/// A command of a run of deferred draws (`batch_commands`); objects by address. +#[derive(Clone, Debug, PartialEq, Eq)] +enum Cmd { + /// one ResourceBarrier call: a UAV barrier on all resources (`all`), one on `uav`, transitions + Barriers { all: bool, uav: Option, transitions: Vec<(usize, D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES)> }, + ComputeRs(usize), + GraphicsRs(usize), + Pso(usize), + ComputeView(u32, u64), + GraphicsView(u32, u64), + Dispatch(u32), + DispatchMesh(u32), + /// ExecuteIndirect of one command: signature, argument buffer, offset + Indirect(usize, usize, u64), + /// the title's SetPipelineState to the pipeline `p`, as without a run (`replay_pipeline_bind`) + Bind(usize), + /// the title's OMSetStencilRef between deferred draws, replayed before subsequent mesh passes + StencilRef(u32), + /// the title's IASetPrimitiveTopology between deferred draws, replayed before subsequent mesh passes + Topology(u32), + /// the title's RSSetScissorRects between deferred draws, replayed before subsequent mesh passes + Scissors(Vec<[i32; 4]>), + /// an `XCL_GPU_TIMES` span: the rewrites and compute passes (None), the mesh pass of draw `d` + TimesBegin(Option), + TimesEnd, } -unsafe fn graphics_bound(this: *mut c_void) -> Option<(ID3D12GraphicsCommandList, usize)> { - let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); - let Some((pso, real)) = resolve_bound_graphics_pipeline(this, list.as_raw() as usize) else { - super::list_x::note_dropped_draw(this); - count(DRAWS_SKIPPED); - return None; - }; - if !super::real::is_translated_graphics(real) { - // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in - // TWO_PASS rather than TRANSLATED_GRAPHICS. Binding the title's graphics RS and issuing - // DrawInstanced / DrawIndexedInstanced against a mesh PSO invalidates the command list - // (Close → E_INVALIDARG). - if let Some(tp) = super::real::two_pass_of_exact(real) { - count(DRAWS_SKIPPED); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!( - "D3D12.X: draw with two-pass {} pipeline ({real:#x}) skipped – PC pipeline is a mesh shader", - tp.kind - ); - } - return None; - } - count(DRAWS_PC); - if super::present::trace_frame() { - // which pipelines draw without a translation (first 12 distinct) - static SEEN: Mutex> = Mutex::new(Vec::new()); - let mut g = SEEN.lock().unwrap(); - if !g.contains(&pso) && g.len() < 12 { - g.push(pso); - crate::xlog_info!( - "frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {real:#x}; pending {}, two-pass {}, RT0 {:?})", - super::pso_async::is_pending(pso), - super::real::two_pass_of_exact(real).is_some(), - super::present::rt0_resource(this as usize).map(|r| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0) })) - ); +/// The commands of a run of `steps` with their records in `records`, after a run whose mesh +/// passes may still read them (`open`): the argument rewrites (after a UAV barrier on all +/// resources – the title's writes of the arguments, `fresh_indirect_arguments` – and the +/// argument blocks to UNORDERED_ACCESS in the same call), the blocks to INDIRECT_ARGUMENT, every +/// compute pass, one UAV barrier on the records, every mesh pass in the title's order with the +/// title's pipeline sets between them where they came. A root signature or pipeline is set where +/// it changes (and a pipeline after each of the title's); every pass sets all its root views. +fn batch_commands(steps: &[Step], records: usize, open: bool) -> Vec { + use D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT as ARGS; + use D3D12_RESOURCE_STATE_UNORDERED_ACCESS as UAV; + let draws: Vec = steps.iter().filter_map(|s| if let Step::Draw(d) = s { Some(*d) } else { None }).collect(); + let mut v = Vec::with_capacity(steps.len() * 20 + 8); + let mut blocks: Vec<(usize, D3D12_RESOURCE_STATES)> = Vec::new(); + for d in &draws { + if let DeferredWork::Indirect { block, before, .. } = d.work { + if !blocks.iter().any(|b| b.0 == block) { + blocks.push((block, before)); } } - // a PC pipeline (also a stand-in or fallback: made with the title's root signature): - // the title's root signature, which nothing else binds on the PC list – a draw without - // one is invalid (the debug layer reports it on every GPU; WARP faults on it) - if super::pso_async::is_pending(pso) { - super::list_x::note_dropped_draw(this); + } + if !blocks.is_empty() { + v.push(Cmd::Barriers { all: true, uav: None, transitions: blocks.iter().map(|&(b, s)| (b, s, UAV)).collect() }); + } else if open { + v.push(Cmd::Barriers { all: false, uav: Some(records), transitions: Vec::new() }); + } + v.push(Cmd::TimesBegin(None)); + let (mut crs, mut grs, mut pso) = (0usize, 0usize, 0usize); + let set = |v: &mut Vec, now: &mut usize, to: usize, cmd: fn(usize) -> Cmd| { + if *now != to { + v.push(cmd(to)); + *now = to; } - let rs = with(this, |s| s.rs_gfx) as *mut c_void; - if let Some(r) = ID3D12RootSignature::from_raw_borrowed(&rs) { - list.SetGraphicsRootSignature(r); + }; + for d in &draws { + if let DeferredWork::Indirect { rewrite, .. } = d.work { + set(&mut v, &mut crs, rewrite.rs, Cmd::ComputeRs); + set(&mut v, &mut pso, rewrite.pso, Cmd::Pso); + v.extend(rewrite.views.iter().map(|&(slot, va)| Cmd::ComputeView(slot, va))); + v.push(Cmd::Dispatch(rewrite.groups)); } - return Some((list, real)); } - if super::present::trace_frame() { - trace_ui_draw(this, pso, real); + if !blocks.is_empty() { + v.push(Cmd::Barriers { all: false, uav: None, transitions: blocks.iter().map(|&(b, _)| (b, UAV, ARGS)).collect() }); } - match bind_abi_resolved(this, &list, pso, real, true) { - Ok(()) => { - count(DRAWS); - Some((list, real)) - } - Err(e) => { - super::list_x::note_dropped_draw(this); - count(DRAWS_SKIPPED); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: draw with a translated pipeline skipped: {e}"); + for d in &draws { + set(&mut v, &mut crs, d.compute.rs, Cmd::ComputeRs); + set(&mut v, &mut pso, d.compute.pso, Cmd::Pso); + v.extend(d.compute.views.iter().enumerate().map(|(k, &va)| Cmd::ComputeView(k as u32, va))); + v.push(match d.work { + DeferredWork::Mesh { groups, .. } => Cmd::Dispatch(groups), + DeferredWork::Indirect { block, companion, compute_at, .. } => Cmd::Indirect(companion, block, compute_at), + }); + } + v.push(Cmd::TimesEnd); + v.push(Cmd::Barriers { all: false, uav: Some(records), transitions: Vec::new() }); + let mut i = 0; + for s in steps { + let d = match s { + Step::Bind(p) => { + v.push(Cmd::Bind(*p)); + // (it set the PC pipeline) + pso = 0; + continue; } - None - } + Step::StencilRef(r) => { + v.push(Cmd::StencilRef(*r)); + continue; + } + Step::Topology(t) => { + v.push(Cmd::Topology(*t)); + continue; + } + Step::Scissors(r) => { + v.push(Cmd::Scissors(r.clone())); + continue; + } + Step::Draw(d) => d, + }; + v.push(Cmd::TimesBegin(Some(i))); + i += 1; + set(&mut v, &mut grs, d.mesh.rs, Cmd::GraphicsRs); + set(&mut v, &mut pso, d.mesh.pso, Cmd::Pso); + v.extend(d.mesh.views.iter().enumerate().map(|(k, &va)| Cmd::GraphicsView(k as u32, va))); + v.push(match d.work { + DeferredWork::Mesh { mesh_groups, .. } => Cmd::DispatchMesh(mesh_groups), + DeferredWork::Indirect { block, sig, mesh_at, .. } => Cmd::Indirect(sig, block, mesh_at), + }); + v.push(Cmd::TimesEnd); } + v } -/// `XCL_TRACE_FRAME`: draws into a presented buffer (the UI) once the title has presented for a -/// while – their pipeline, root arguments and the resources their descriptor tables start with -/// (format, size, kept in step with title memory or not). The first 24. -/// `XCL_TRACE_FRAME`, after 300 presents: one line per distinct (VS, PS, render target) drawn – -/// the shaders' dump hashes, the target and the textures of the first descriptor table. -unsafe fn trace_draw_kinds(this: *mut c_void, pso: usize) { - // keyed by the target's shape, not the object: a UI library's transient targets (Renoir's - // layers) are new objects every frame and would fill the list at once - static SEEN: Mutex)>> = Mutex::new(Vec::new()); - if super::present::activity().0 < 300 { - return; - } - let Some((vs, ps)) = super::real::pso_shaders(pso) else { return }; - let rt = super::present::rt0_resource(this as usize).unwrap_or(0); - let desc = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0, d.SampleDesc.Count) }); - { - let mut g = SEEN.lock().unwrap(); - let key = (vs, ps, desc(rt)); - if g.len() >= 160 || g.contains(&key) { - return; - } - g.push(key); - } - let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); - let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); - let mut tex = Vec::new(); - if let (Some(layout), Some(u)) = (layout, crate::gpu::uma::get()) { - for p in layout.params.iter() { - if let Param::Table { at } = *p { - let t = word(at as usize) as usize; - for k in 0..4usize { - if let Some(r) = super::console_heap::resource_at(u.base() + t + 32 * k) { - tex.push(format!("{:?}{}", desc(r), super::title_textures::address(r).map_or(String::new(), |a| format!(" at {a:#x}")))); - } - } +/// `cmds` (`batch_commands` of `draws`) on the list `this`. +/// `binds`: the run's pipeline sets (`RunItem::Bind`), in the order of their `Cmd::Bind`s. +unsafe fn emit_commands(this: *mut c_void, list: &ID3D12GraphicsCommandList, cmds: &[Cmd], draws: &[&DeferredDraw], binds: &[(usize, Option<&super::pso_async::PipelineResolution>)]) { + let mut next_bind = binds.iter(); + type Ei = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); + type Dm = unsafe extern "system" fn(*mut c_void, u32, u32, u32); + let pc_ei: Ei = std::mem::transmute(super::real::orig_fn(this, 59)); + let pc_dm: Dm = std::mem::transmute(super::real::orig_fn(this, 79)); + // (every object here is held by `draws` or the list's state until this returns) + let res = |raw: usize| { + let p = raw as *mut c_void; + ID3D12Resource::from_raw_borrowed(&p).cloned() + }; + let rs = |raw: usize| { + let p = raw as *mut c_void; + ID3D12RootSignature::from_raw_borrowed(&p).cloned() + }; + for c in cmds { + match c { + Cmd::Barriers { all, uav, transitions } => { + let uav = uav.and_then(res); + let held: Vec<(ID3D12Resource, D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES)> = transitions.iter().filter_map(|&(r, a, b)| Some((res(r)?, a, b))).collect(); + let t: Vec<_> = held.iter().map(|(r, a, b)| (r, *a, *b)).collect(); + emit_barrier_set(list, *all, uav.as_ref(), &t); } - if tex.len() >= 4 { - break; + Cmd::ComputeRs(r) => list.SetComputeRootSignature(rs(*r).as_ref()), + Cmd::GraphicsRs(r) => list.SetGraphicsRootSignature(rs(*r).as_ref()), + Cmd::Pso(p) => { + let p = *p as *mut c_void; + list.SetPipelineState(ID3D12PipelineState::from_raw_borrowed(&p)); } - } - } - crate::xlog_info!( - "frame trace: draws vs {vs:016x} ps {ps:016x} into {:?}{} – textures {}; {}", - desc(rt), - if super::present::is_presented(rt) { " (presented)" } else { "" }, - tex.join(", "), - super::list_x::state_summary(this) - ); -} - -/// `XCL_TRACE_SHADERS=hash,…` (dump hashes, hex): the draws traced with their root arguments -/// are those whose vertex or pixel shader is listed – into any target, at any time (the first -/// 24); without it, draws into a presented target (or any – `XCL_TRACE_UI_ANY`) after 300 -/// presents. -fn traced_shaders() -> &'static [u64] { - static S: std::sync::OnceLock> = std::sync::OnceLock::new(); - S.get_or_init(|| std::env::var("XCL_TRACE_SHADERS").unwrap_or_default().split(',').filter_map(|h| u64::from_str_radix(h.trim(), 16).ok()).collect()) -} - -/// `XCL_TRACE_FRAME` with a watched target (`present::watch_rt`): draws whose descriptor -/// tables name it – that object, or another at its title address (the first 16). -unsafe fn trace_reads_of_watched(this: *mut c_void, pso: usize) { - let Some(w) = super::present::watched_rt() else { return }; - let w_addr = super::real::title_address(w).or_else(|| super::title_textures::address(w)); - let Some(u) = crate::gpu::uma::get() else { return }; - let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); - let Some(layout) = layout else { return }; - let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); - for p in layout.params.iter() { - let Param::Table { at } = *p else { continue }; - let t = word(at as usize) as usize; - for k in 0..16usize { - let Some(r) = super::console_heap::resource_at(u.base() + t + 32 * k) else { continue }; - let addr = super::real::title_address(r).or_else(|| super::title_textures::address(r)); - if super::present::is_watched(r) || (addr.is_some() && addr == w_addr) { - let rt = super::present::rt0_resource(this as usize).unwrap_or(0); - // each (source, target, shaders) once - static SEEN: Mutex> = Mutex::new(Vec::new()); - { - let mut g = SEEN.lock().unwrap(); - if g.len() >= 32 || g.contains(&(r, rt, pso)) { - return; - } - g.push((r, rt, pso)); - } - if !super::present::is_presented(rt) { - super::present::follow(rt); - } - if let Some(dsv) = super::list_x::bound_dsv(this) { - super::list_x::watch_dsv(dsv); - } - let d = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0, d.Flags.0) }); - crate::xlog_info!( - "frame trace: a draw (shaders {:x?}, {}) reads a watched target {r:#x} {:?} at {addr:x?} (slot {k}), drawing into {rt:#x} {:?}{} – {}", - super::real::pso_shaders(pso), - super::list_x::state_summary(this), - d(r), - d(rt), - if super::present::is_presented(rt) { " (presented)" } else { "" }, - root_args_summary(this, 32) - ); - let args = DRAW_ARGS.with(|d| d.get()); - crate::xlog_info!( - "frame trace: … that draw: {args:?} (indexed, count, instances, first, base vertex); input layout [{}]; {}", - super::real::pso_layout(pso).unwrap_or_default(), - super::list_x::geometry_summary(this, args) - ); - return; + Cmd::ComputeView(slot, va) => list.SetComputeRootUnorderedAccessView(*slot, *va), + Cmd::GraphicsView(slot, va) => list.SetGraphicsRootUnorderedAccessView(*slot, *va), + Cmd::Dispatch(n) => list.Dispatch(*n, 1, 1), + Cmd::DispatchMesh(n) => pc_dm(this, *n, 1, 1), + Cmd::Indirect(sig, buf, at) => pc_ei(this, *sig, 1, *buf, *at, 0, 0), + Cmd::Bind(p) => { + let (pso, resolution) = next_bind.next().copied().unwrap_or((*p, None)); + debug_assert_eq!(pso, *p); + replay_pipeline_bind(this, pso, resolution); + } + Cmd::StencilRef(r) => super::list_x::apply_stencil_ref(this, *r), + Cmd::Topology(t) => super::list_x::apply_topology(this, *t), + Cmd::Scissors(r) => super::list_x::apply_scissors(this, r), + Cmd::TimesBegin(None) => super::gpu_times::before(this, 0, super::gpu_times::Kind::MeshBatch, [draws.len() as u32, 0, 0], false), + Cmd::TimesBegin(Some(d)) => { + let d = &draws[*d]; + let indirect = matches!(d.snap.work, DeferredWork::Indirect { .. }); + super::gpu_times::before(this, d.snap.mesh.pso, super::gpu_times::Kind::Mesh(d.kind), d.size, indirect); } + Cmd::TimesEnd => super::gpu_times::after(this), } } } -/// `XCL_TRACE_FRAME`: render targets a draw into the watched target samples (a UI library's -/// layers) are dumped with it (`present::follow`). -unsafe fn follow_layer_sources(this: *mut c_void) { - let (Some(w), Some(rt)) = (super::present::watched_rt(), super::present::rt0_resource(this as usize)) else { return }; - if rt != w { +/// The deferred draws of the list `this`, recorded now (`batch_commands`), for `why`; nothing +/// when it has none. +pub(super) unsafe fn flush_two_pass(this: *mut c_void, why: RunEnd) { + if DEFERRING_LISTS.load(Ordering::Relaxed) == 0 || !DEFERRING.contains(this as usize) { return; } - let Some(u) = crate::gpu::uma::get() else { return }; - let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); - let Some(layout) = layout else { return }; - let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); - for p in layout.params.iter() { - let Param::Table { at } = *p else { continue }; - let t = word(at as usize) as usize; - for k in 0..4usize { - let Some(r) = super::console_heap::resource_at(u.base() + t + 32 * k) else { continue }; - let layer = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).is_some_and(|x| { - let d = x.GetDesc(); - d.Flags.0 & 1 != 0 && d.Width >= 64 && d.Height >= 32 && d.SampleDesc.Count == 1 - }); - if layer && r != w { - super::present::follow(r); + unmark_deferring(this); + let (items, records, open) = with(this, |s| (std::mem::take(&mut s.deferred), s.batch_buf.as_ref().map(|b| b.res.clone()), s.batch_open)); + let draws: Vec<&DeferredDraw> = items.iter().filter_map(|i| if let RunItem::Draw(d) = i { Some(d) } else { None }).collect(); + if draws.is_empty() { + // (queued state sets only: as they would have gone) + for i in &items { + match i { + RunItem::Bind { pso, resolution, .. } => replay_pipeline_bind(this, *pso, resolution.as_ref()), + RunItem::StencilRef(r) => super::list_x::apply_stencil_ref(this, *r), + RunItem::Topology(t) => super::list_x::apply_topology(this, *t), + RunItem::Scissors(r) => super::list_x::apply_scissors(this, r), + RunItem::Draw(_) => {} } } + return; + } + let (Some(list), Some(records)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), records) else { return }; + RUN_ENDS[run_end_index(why)].fetch_add(1, Ordering::Relaxed); + let steps: Vec = items.iter().map(RunItem::step).collect(); + let cmds = batch_commands(&steps, records.as_raw() as usize, open); + let binds: Vec<(usize, Option<&super::pso_async::PipelineResolution>)> = + items.iter().filter_map(|i| if let RunItem::Bind { pso, resolution, .. } = i { Some((*pso, resolution.as_ref())) } else { None }).collect(); + emit_commands(this, list, &cmds, &draws, &binds); + with(this, |s| (s.batch_used, s.batch_open) = (0, true)); + for d in &draws { + mesh_work(this, super::targets::RAN); + let (what, size) = match d.snap.work { + DeferredWork::Mesh { .. } => (super::watch::MESH, [d.size[0].saturating_mul(d.size[1]).saturating_mul(d.size[2]), 0, 0]), + DeferredWork::Indirect { .. } => (super::watch::INDIRECT_MESH, [1, 0, 0]), + }; + super::watch::note(d.raw_pso, what, size); + count(DRAWS); + } + static RUNS: AtomicU64 = AtomicU64::new(0); + static DRAWN: AtomicU64 = AtomicU64::new(0); + let n = RUNS.fetch_add(1, Ordering::Relaxed) + 1; + let drawn = DRAWN.fetch_add(draws.len() as u64, Ordering::Relaxed) + draws.len() as u64; + if n <= 8 || n.is_power_of_two() { + let binds = items.len() - draws.len(); + crate::xlog_info!("D3D12.X: deferred two-pass draws: run #{n} of {} with {binds} pipeline sets ({drawn} in all, {:.1} a run); runs ended by: {}", draws.len(), drawn as f64 / n as f64, run_ends_text(8)); } } -unsafe fn trace_ui_draw(this: *mut c_void, original: usize, pso: usize) { - trace_draw_kinds(this, pso); - trace_reads_of_watched(this, pso); - follow_layer_sources(this); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - // `XCL_TRACE_MANY=n`: n draws instead of 24 (a whole frame of a UI) - static CAP: std::sync::OnceLock = std::sync::OnceLock::new(); - let cap = *CAP.get_or_init(|| std::env::var("XCL_TRACE_MANY").ok().and_then(|v| v.parse().ok()).unwrap_or(24)); - if N.load(std::sync::atomic::Ordering::Relaxed) >= cap { - return; - } - let Some(rt) = super::present::rt0_resource(this as usize) else { return }; - let wanted = traced_shaders(); - if wanted.is_empty() { - // draws into a presented target, or – `XCL_TRACE_UI_ANY` – into any target - if super::present::activity().0 < 300 || (!super::present::is_presented(rt) && std::env::var_os("XCL_TRACE_UI_ANY").is_none()) { - return; +/// A region of `region` bytes in the batch record buffer of `this` for the next deferred draw +/// (the run so far is recorded first when it does not fit): its GPU address. +unsafe fn batch_region(this: *mut c_void, region: u64) -> Result { + let bytes = batch_records_bytes(); + if with(this, |s| s.batch_buf.is_none()) { + let dev = super::real::list_device(this).ok_or("no device for two-pass buffer")?; + let buf = match take_free(dev.as_raw() as usize, bytes, bytes) { + Some(b) => b, + // (a new one only while the two-pass buffers alive leave half the budget: past it the + // draws go at once, and the records they need alone are still made) + None if TWO_PASS[TP_ALIVE].load(Ordering::Relaxed).saturating_add(bytes) > two_pass_cap() / 2 => return Err("the two-pass buffers alive are at half their budget".into()), + None => TwoPassBuf::try_make_with_cap(&dev, bytes, "two-pass batch records", two_pass_cap())? + .ok_or_else(|| "the two-pass buffers alive are at their budget".to_string())?, + }; + with(this, |s| { + mark_two_pass_tracking(this, &mut s.res_untracked); + (s.batch_buf, s.batch_used, s.batch_open) = (Some(buf), 0, false); + }); + track_two_pass_list(this as usize); + } + let (used, cap) = with(this, |s| (s.batch_used, s.batch_buf.as_ref().map_or(0, |b| b.bytes))); + let at = match batch_place(used, region, cap) { + Some(at) => at, + None => { + flush_two_pass(this, RunEnd::Full); + 0 } - } else if !super::real::pso_shaders(pso).is_some_and(|(v, p)| wanted.contains(&v) || wanted.contains(&p)) { - return; - } else { - super::present::watch_rt(rt); + }; + if at + region > cap { + return Err("its records are more than the batch record buffer".into()); } - N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let sh = super::real::pso_shaders(pso).map(|(v, p)| format!("vs {v:016x} ps {p:016x}")); - crate::xlog_info!("frame trace: UI draw (pipeline {original:#x}, {}): {}", sh.unwrap_or_default(), root_args_summary(this, 16)); - if !wanted.is_empty() { - // the picked shaders' geometry too (vertices dumped at the next present) - let args = DRAW_ARGS.with(|d| d.get()); - crate::xlog_info!( - "frame trace: … that draw: {args:?} (indexed, count, instances, first, base vertex); input layout [{}]; {}", - super::real::pso_layout(pso).unwrap_or_default(), - super::list_x::geometry_summary(this, args) - ); + let va = with(this, |s| { + s.batch_used = at + region; + s.batch_buf.as_ref().map(|b| b.res.GetGPUVirtualAddress()) + }); + va.map(|va| va + at).ok_or_else(|| "no batch record buffer".into()) +} + +/// Queue `OMSetStencilRef` into the list's deferred two-pass run when deferring, so it replays +/// in title order between mesh passes instead of flushing the batch. +pub(super) unsafe fn queue_stencil_ref(this: *mut c_void, r: u32) -> bool { + if DEFERRING_LISTS.load(Ordering::Relaxed) == 0 || !DEFERRING.contains(this as usize) { + return false; } + with(this, |s| s.deferred.push(RunItem::StencilRef(r))); + true } -/// A draw's root arguments for the frame trace: constants, root buffers (their first words, as -/// the CPU sees them), the first slots of descriptor tables (the PC resources they name). -unsafe fn root_args_summary(this: *mut c_void, buffer_words: usize) -> String { - let Some(u) = crate::gpu::uma::get() else { return String::new() }; - let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); - let Some(layout) = layout else { return String::new() }; - let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); - let mut what = Vec::new(); - for (i, p) in layout.params.iter().enumerate() { - match *p { - Param::Constants { at, count } => what.push(format!("p{i} constants {:x?}", (0..count.min(8) as usize).map(|k| word(at as usize + 4 * k)).collect::>())), - Param::Descriptor { at } => { - let va = (word(at as usize) as u64 | (word(at as usize + 4) as u64) << 32) as usize; - let w: Vec = if va != 0 && crate::gpu::shader::readable(va, 4 * buffer_words) { (0..buffer_words).map(|k| ((va + 4 * k) as *const u32).read_unaligned()).collect() } else { Vec::new() }; - what.push(format!("p{i} buffer {va:#x} {w:x?}")); - } - Param::Table { at } => { - let t = word(at as usize) as usize; - let slots: Vec = (0..4usize) - .map(|k| { - let at = u.base() + t + 32 * k; - let w = super::console_heap::words_at((t + 32 * k) as u32); - match super::console_heap::resource_at(at) { - Some(r) => { - if super::title_textures::address(r).is_some() { - super::title_textures::probe_gpu_content(r); - } - let d = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| x.GetDesc()); - format!("[{k}] {r:#x} {:?} title {:?} T# {:x?}", d.map(|d| (d.Dimension.0, d.Width, d.Height, d.Format.0)), super::title_textures::address(r).map(|a| format!("{a:#x}")), w.map(|w| w[..4].to_vec())) - } - None => format!("[{k}] - T# {:x?}", w.map(|w| w[..4].to_vec())), - } - }) - .collect(); - what.push(format!("p{i} table {t:#x}: {}", slots.join(", "))); - } - } +/// Queue `IASetPrimitiveTopology` into the list's deferred two-pass run when deferring, so it +/// replays in title order between mesh passes instead of flushing the batch. +pub(super) unsafe fn queue_topology(this: *mut c_void, t: u32) -> bool { + if DEFERRING_LISTS.load(Ordering::Relaxed) == 0 || !DEFERRING.contains(this as usize) { + return false; } - what.join("; ") + with(this, |s| s.deferred.push(RunItem::Topology(t))); + true } -/// #33 SetComputeRootSignature (PC #29) -pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_void, rs: *mut c_void) { - let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); - let layout = console_list::layout_of(rs as usize); - with(this, |s| { - s.args = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; - s.layout = layout; +/// Queue `RSSetScissorRects` into the list's deferred two-pass run when deferring, so it +/// replays in title order between mesh passes instead of flushing the batch. +pub(super) unsafe fn queue_scissors(this: *mut c_void, rects: Vec<[i32; 4]>) -> bool { + if DEFERRING_LISTS.load(Ordering::Relaxed) == 0 || !DEFERRING.contains(this as usize) { + return false; + } + with(this, |s| s.deferred.push(RunItem::Scissors(rects))); + true +} + +/// `draw` deferred on `this`; the run is recorded when it has `batch_most` draws. +unsafe fn push_deferred(this: *mut c_void, draw: DeferredDraw) { + let n = with(this, |s| { + s.deferred.push(RunItem::Draw(draw)); + s.deferred.iter().filter(|i| matches!(i, RunItem::Draw(_))).count() }); + mark_deferring(this); + if n >= batch_most() { + flush_two_pass(this, RunEnd::Most); + } } -/// #35 SetComputeRootDescriptorTable (PC #31): the table's console address, 32 bits -pub(super) unsafe extern "system" fn set_compute_root_table(this: *mut c_void, i: u32, handle: u64) { - let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); - put(this, i, 0, &(handle as u32).to_le_bytes()); +/// What SetPipelineState does on a list: with no deferred draws, what it always did; with them, +/// a two-pass pipeline goes into the run (`RunItem::Bind`) and any other records the run first. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum OnPipeline { + Bind, + Queue, + FlushThenBind, } -/// #37 SetComputeRoot32BitConstant (PC #33) -pub(super) unsafe extern "system" fn set_compute_root_constant(this: *mut c_void, i: u32, value: u32, offset: u32) { - let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); - put(this, i, offset, &value.to_le_bytes()); +fn on_pipeline(deferring: bool, two_pass: bool) -> OnPipeline { + match (deferring, two_pass) { + (false, _) => OnPipeline::Bind, + (true, true) => OnPipeline::Queue, + (true, false) => OnPipeline::FlushThenBind, + } } -/// #39 SetComputeRoot32BitConstants (PC #35) -pub(super) unsafe extern "system" fn set_compute_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { - let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); - if !data.is_null() { - let bytes: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); - put(this, i, offset, &bytes); +/// A two-pass DispatchMesh of `dims` groups with `tp` (`pso`: its mesh pass's pipeline) deferred +/// on `this` (`XCL_TWO_PASS_BATCH=2`). False: not deferred – the caller records the run so far +/// and this draw at once, as without. +unsafe fn defer_dispatch_mesh(this: *mut c_void, tp: &Arc, pso: usize, raw_pso: usize, dims: [u32; 3]) -> bool { + let groups = dims[0].saturating_mul(dims[1]).saturating_mul(dims[2]); + let record_bytes = tp.record.record_dwords() as u64 * 4; + let region = batch_region_bytes((groups as u64).saturating_mul(record_bytes)); + let ty = super::list_x::tracked_list_type(this); + if groups == 0 || defer_check(true, ty, super::capture::on(), 1, region, batch_records_bytes()).is_err() { + return false; + } + // (as many groups as the draw alone would have: its region holds them all) + let n = groups.min(record_groups(region, record_bytes, tp.mesh_groups_per_record)); + if n == 0 { + return false; } + let Ok(records) = batch_region(this, region) else { return false }; + super::list_x::ensure_view_heap(this); + let (Ok(compute), Ok(mesh)) = (prepare_two_pass_stage(this, pso, tp, records, true, 0), prepare_two_pass_stage(this, pso, tp, records, false, 0)) else { return false }; + let work = DeferredWork::Mesh { groups: n, mesh_groups: n * tp.mesh_groups_per_record }; + push_deferred(this, DeferredDraw { snap: DrawSnap { compute, mesh, work }, _tp: tp.clone(), _mesh_pso: held_pso(pso), _block: None, raw_pso, kind: tp.kind, size: dims }); + true } -/// #41 / #43 / #45 SetComputeRoot{ConstantBuffer,ShaderResource,UnorderedAccess}View (PC #37 / -/// #39 / #41): the 64-bit GPU address -pub(super) unsafe extern "system" fn set_compute_root_descriptor(this: *mut c_void, i: u32, va: u64) { - let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); - note_address(va); - put(this, i, 0, &va.to_le_bytes()); +/// A two-pass ExecuteIndirect of one command deferred (`defer_dispatch_mesh`): `sig` with the +/// DispatchMesh signature `msig`, its command at UMA address `src`, its count at `count`. +#[allow(clippy::too_many_arguments)] +unsafe fn defer_execute_indirect(this: *mut c_void, tp: &Arc, pso: usize, raw_pso: usize, sig: usize, msig: DispatchMeshSig, max: u32, src: usize, count: Option) -> bool { + let record_bytes = tp.record.record_dwords() as u64 * 4; + let fb_dev = super::real::list_device(this); + let (fb_va, fb_slot, hint) = match fb_dev.as_ref().and_then(|d| prepare_indirect_feedback(d, pso)) { + Some((va, slot, h)) => (Some(va), slot, h), + None => (None, 0, None), + }; + let region = batch_region_bytes(indirect_record_need_hint(record_bytes, tp.mesh_groups_per_record, hint)); + let ty = super::list_x::tracked_list_type(this); + if defer_check(true, ty, super::capture::on(), max, region, batch_records_bytes()).is_err() { + return false; + } + // (the groups a command keeps: as the draw alone, `two_pass_record_buffers_fit_what_their_draws_need`) + let cap = record_groups(region, record_bytes, tp.mesh_groups_per_record); + if cap == 0 { + return false; + } + let Ok(records) = batch_region(this, region) else { return false }; + super::list_x::ensure_view_heap(this); + let (Ok(compute), Ok(mesh)) = (prepare_two_pass_stage(this, pso, tp, records, true, 0), prepare_two_pass_stage(this, pso, tp, records, false, 0)) else { return false }; + let Ok((rewrite, block, at)) = prepare_scaled_args(this, src, count, 1, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record, cap, fb_va, fb_slot) else { return false }; + if let Some(d) = &fb_dev { + if fb_slot != 0 { + let dk = d.as_raw() as usize; + with(this, |s| s.fb_uses.push((dk, fb_slot, cap))); + track_two_pass_list(this as usize); + } + } + // (the block is in INDIRECT_ARGUMENT after the run, `scratch_in_args`) + let before = scratch_state(with(this, |s| std::mem::replace(&mut s.scratch_in_args, true))); + let work = DeferredWork::Indirect { rewrite, block: block.as_raw() as usize, before, companion: msig.companion_dispatch, sig, compute_at: at, mesh_at: at + msig.byte_stride as u64 }; + push_deferred(this, DeferredDraw { snap: DrawSnap { compute, mesh, work }, _tp: tp.clone(), _mesh_pso: held_pso(pso), _block: Some(block), raw_pso, kind: tp.kind, size: [max, 0, 0] }); + true } -/// #25 SetPipelineState: retain one title identity for the native bind and later emission. -pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: *mut c_void) { - let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); - let pso = pso as usize; - let resolution = super::pso_async::begin_pipeline_resolution(pso); - if resolution.is_none() { - super::pso_manifest::note_ready_compute(pso); +/// A reference to the pipeline `pso` for as long as a deferred draw names it. +unsafe fn held_pso(pso: usize) -> Option { + let p = pso as *mut c_void; + if !super::real::is_adopted(p) { + return None; } - set_pipeline_state_retained(this, pso, resolution); + ID3D12PipelineState::from_raw_borrowed(&p).cloned() } -#[cfg(test)] -fn set_tracked_pipeline_state(this: *mut c_void, pso: usize) { - let resolution = super::pso_async::begin_pipeline_resolution(pso); - install_tracked_pipeline_state(this, pso, resolution); +/// Smallest and largest record buffer. The smallest is an argument scratch block's size +/// (`SCRATCH_BLOCK`), so a freed one of either serves both. +const RECORD_MIN: u64 = 256 << 10; +const RECORD_MAX: u64 = 128 << 20; +/// Record bytes an ExecuteIndirect of two-pass commands asks for when cold (no GPU feedback yet): +/// a command's groups are known on the GPU only (`SCALE_ARGS_HLSL` keeps them to what fits). +const INDIRECT_RECORDS: u64 = 32 << 20; + +/// Bytes of a record buffer for `need` bytes of records: power-of-two / 1.5× half-step buckets +/// from `RECORD_MIN` (256 KiB) to `RECORD_MAX` (128 MiB). Cuts worst-case rounding waste from 2× +/// to 1.5× while keeping a small set of sizes for `FREE_RES` reuse. +fn record_buffer_bytes(need: u64) -> u64 { + let n = need.clamp(RECORD_MIN, RECORD_MAX); + let p = n.next_power_of_two(); + let half = p >> 1; + let mid = half + (half >> 1); + if n <= mid && mid >= RECORD_MIN { mid } else { p } } -fn install_tracked_pipeline_state( - this: *mut c_void, - pso: usize, - resolution: Option, -) { - let old_resolution = with(this, |s| { - s.pso = pso; - std::mem::replace(&mut s.resolution, resolution) - }); - drop(old_resolution); +/// Record bytes a two-pass ExecuteIndirect asks for: `INDIRECT_RECORDS`, or less when a command's +/// groups (at most 65 535 / `split` in X, `record_groups`) need less – the same groups fit. +fn indirect_record_need(record_bytes: u64, split: u32) -> u64 { + INDIRECT_RECORDS.min(record_bytes.saturating_mul(65_535 / split.max(1) as u64)) } -unsafe fn set_pipeline_state_retained( - this: *mut c_void, - pso: usize, - resolution: Option, -) { - use super::pso_async::{NativePipelineBindMode, NativePipelineChoice}; - let choice = resolution.as_ref().map(|r| r.select_for_native_bind(NativePipelineBindMode::Lazy)); - let (raw, generation) = match choice { - Some(NativePipelineChoice::Exact { raw, generation }) => (Some(raw), Some(generation)), - Some(NativePipelineChoice::InitialFallback { raw, .. }) => (Some(raw), None), - Some(NativePipelineChoice::Unavailable) if resolution.as_ref().unwrap().unavailable_is_emission_guarded() => { - (None, None) +/// Record bytes sized from async GPU `SCALE_ARGS_HLSL` feedback (`hint_groups`): `None` (cold) +/// keeps the full `indirect_record_need` (no cold-start clamping); `Some(0)` takes +/// `RECORD_MIN.min(max_need)`; `Some(g)` reserves `2 × g` records up to `max_need`. +fn indirect_record_need_hint(record_bytes: u64, split: u32, hint_groups: Option) -> u64 { + let max_need = indirect_record_need(record_bytes, split); + match hint_groups { + None => max_need, + Some(0) => RECORD_MIN.min(max_need), + Some(g) => max_need.min(record_bytes.saturating_mul((g as u64).saturating_mul(2))), + } +} + +const FEEDBACK_HEADER_U32S: usize = 2; +const FEEDBACK_SLOTS: usize = 4096; +const FEEDBACK_BYTES: u64 = ((FEEDBACK_HEADER_U32S + FEEDBACK_SLOTS) as u64) * 4; +const FEEDBACK_WINDOW_MS: u128 = 250; +const FEEDBACK_HISTORY: usize = 16; + +static FEEDBACK_ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static FEEDBACK: Mutex>> = Mutex::new(None); + +struct IndirectFeedbackSlot { + history: [u32; FEEDBACK_HISTORY], + hist_valid: u8, + hist_idx: usize, + last_cap: u32, + in_flight_cap: u32, + dirty: bool, + ever_nonzero: bool, +} + +impl IndirectFeedbackSlot { + fn new() -> Self { + Self { history: [0; FEEDBACK_HISTORY], hist_valid: 0, hist_idx: 0, last_cap: u32::MAX, in_flight_cap: u32::MAX, dirty: false, ever_nonzero: false } + } + + fn hint(&self) -> Option { + (self.hist_valid > 0).then(|| self.history[..self.hist_valid as usize].iter().copied().max().unwrap_or(0)) + } + + fn apply_window(&mut self, encoded: u32) { + let cap = std::mem::replace(&mut self.in_flight_cap, u32::MAX); + if encoded == 0 { + return; } - Some(NativePipelineChoice::Unavailable) => { - // Mesh/raw native consumers can bypass retained draw resolution. Preserve root and - // dynamic state, but make Close/submission reject this whole physical recording. - super::list_x::poison_recording(this as usize); - (None, None) + let raw = encoded - 1; + if raw == 0 { + if self.ever_nonzero { + return; + } + self.history[self.hist_idx] = 0; + self.hist_idx = (self.hist_idx + 1) % FEEDBACK_HISTORY; + self.hist_valid = (self.hist_valid + 1).min(FEEDBACK_HISTORY as u8); + return; + } + self.ever_nonzero = true; + if cap != u32::MAX && raw > cap { + self.history = [raw; FEEDBACK_HISTORY]; + self.hist_valid = FEEDBACK_HISTORY as u8; + self.hist_idx = 0; + } else { + self.history[self.hist_idx] = raw; + self.hist_idx = (self.hist_idx + 1) % FEEDBACK_HISTORY; + self.hist_valid = (self.hist_valid + 1).min(FEEDBACK_HISTORY as u8); } - None => (Some(pso), None), - }; - super::list_x::record_native_generation(this as usize, generation); - install_tracked_pipeline_state(this, pso, resolution); - if let Some(raw) = raw { - super::real::bind_pipeline_exact(this, pso, raw); } - super::list_x::on_set_pipeline_state(this, pso); } -pub(super) unsafe fn clear_pipeline_state(this: *mut c_void, pso: usize) { - let resolution = super::pso_async::begin_pipeline_resolution(pso); - clear_pipeline_state_retained(this, pso, resolution); +struct IndirectFeedback { + _gpu: ID3D12Resource, + gpu_va: u64, + readback: ID3D12Resource, + _zero_upload: ID3D12Resource, + _copy_alloc: ID3D12CommandAllocator, + copy_list: ID3D12GraphicsCommandList, + copy_fence: ID3D12Fence, + copy_val: u64, + copy_in_flight: bool, + removed: bool, + dirty: bool, + last_copy: std::time::Instant, + pending_fences: Vec<(usize, ID3D12Fence, u64)>, + slots: Vec, + by_pso: HashMap, } -unsafe fn clear_pipeline_state_retained( - this: *mut c_void, - pso: usize, - resolution: Option, -) { - use super::pso_async::{NativePipelineBindMode, NativePipelineChoice}; - let choice = resolution.as_ref().map(|r| r.select_for_native_bind(NativePipelineBindMode::ForBind)); - let (raw, generation) = match choice { - Some(NativePipelineChoice::Exact { raw, generation }) => (raw, Some(generation)), - Some(NativePipelineChoice::InitialFallback { raw, .. }) => (raw, None), - Some(NativePipelineChoice::Unavailable) => (0, None), - None => (pso, None), +unsafe fn feedback_buffer( + dev: &ID3D12Device, + heap: D3D12_HEAP_TYPE, + state: D3D12_RESOURCE_STATES, + flags: D3D12_RESOURCE_FLAGS, +) -> Result { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: FEEDBACK_BYTES, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, }; - super::list_x::record_native_generation(this as usize, generation); - super::real::clear_pipeline_exact(this, pso, raw); - super::list_x::on_clear_state(this, pso); - install_clear_state(this, pso, resolution); -} - -/// #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 _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDispatch); - dispatch_flags(this, x, y, z, 0); + let mut res: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + state, + None, + &mut res, + ) + .map_err(|e| format!("two-pass feedback ({heap:?}): {e}"))?; + res.ok_or_else(|| "null two-pass feedback buffer".into()) } -/// `DispatchX` flag: x, y, z are thread counts, not group counts; the console launches whole -/// groups and leaves the lanes past the count out of EXEC (0x8000, wave32, needs nothing here) -const DISPATCH_THREAD_DIMENSIONS: u32 = 0x20; -const MAX_DISPATCH_GROUPS: u32 = 65_535; +impl IndirectFeedback { + unsafe fn new(dev: &ID3D12Device) -> Result { + let gpu = feedback_buffer(dev, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)?; + let gpu_va = gpu.GetGPUVirtualAddress(); + let readback = feedback_buffer(dev, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE)?; + let zero_upload = feedback_buffer(dev, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_FLAG_NONE)?; + let mut p = std::ptr::null_mut(); + let empty = D3D12_RANGE { Begin: 0, End: 0 }; + zero_upload.Map(0, Some(&empty), Some(&mut p)).map_err(|e| format!("two-pass feedback zero Map: {e}"))?; + std::ptr::write_bytes(p, 0, FEEDBACK_BYTES as usize); + zero_upload.Unmap(0, None); + let copy_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(|e| format!("two-pass feedback alloc: {e}"))?; + let copy_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, ©_alloc, None).map_err(|e| format!("two-pass feedback list: {e}"))?; + // `gpu` stays in COMMON across concurrent recording lists (implicit COMMON->UAV promotion and + // execute-boundary decay); the copy list reads from COMMON and restores COMMON after clearing. + copy_list.CopyResource(&readback, &gpu); + emit_transition(©_list, &gpu, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST); + copy_list.CopyResource(&gpu, &zero_upload); + emit_transition(©_list, &gpu, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); + copy_list.Close().map_err(|e| format!("two-pass feedback Close: {e}"))?; + let copy_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(|e| format!("two-pass feedback fence: {e}"))?; + Ok(Self { + _gpu: gpu, + gpu_va, + readback, + _zero_upload: zero_upload, + _copy_alloc: copy_alloc, + copy_list, + copy_fence, + copy_val: 0, + copy_in_flight: false, + removed: false, + dirty: false, + last_copy: std::time::Instant::now(), + pending_fences: Vec::new(), + slots: Vec::new(), + by_pso: HashMap::new(), + }) + } -fn valid_dispatch_grid(groups: [u32; 3]) -> bool { - groups.into_iter().all(|n| n <= MAX_DISPATCH_GROUPS) -} + unsafe fn consume_completed(&mut self) -> bool { + if !self.copy_in_flight || self.removed { + return false; + } + match fence_state(&self.copy_fence, self.copy_val) { + FenceState::Pending => return false, + FenceState::Removed => { + self.removed = true; + return false; + } + FenceState::Completed => {} + } + self.copy_in_flight = false; + let len = self.slots.len(); + if len == 0 { + return true; + } + let total = FEEDBACK_HEADER_U32S + len; + let range = D3D12_RANGE { Begin: 0, End: total * 4 }; + let mut ptr = std::ptr::null_mut(); + if self.readback.Map(0, Some(&range), Some(&mut ptr)).is_ok() { + let vals = std::slice::from_raw_parts(ptr.cast::(), total); + let (clamped_cmds, clamped_groups) = (vals[0] as u64, vals[1] as u64); + if clamped_cmds > 0 { + note_two_pass_add(TP_INDIRECT_CLAMPED, clamped_cmds); + } + if clamped_groups > 0 { + note_two_pass_add(TP_INDIRECT_GROUPS_DROPPED, clamped_groups); + } + for (slot, &encoded) in self.slots.iter_mut().zip(&vals[FEEDBACK_HEADER_U32S..]) { + slot.apply_window(encoded); + } + let empty = D3D12_RANGE { Begin: 0, End: 0 }; + self.readback.Unmap(0, Some(&empty)); + } + true + } -/// What a dispatch of `dims` with `flags` launches on pipeline `pso`: its groups and the thread -/// limits for `IO_THREAD_LIMIT` (0: that axis ends on a whole group). None: it cannot be run -/// as the console would (thread dimensions with a group shape not known). -fn dispatch_groups(pso: usize, dims: [u32; 3], flags: u32) -> Option<([u32; 3], [u32; 3])> { - if flags & DISPATCH_THREAD_DIMENSIONS == 0 { - return Some((dims, [0; 3])); + unsafe fn schedule_copy(&mut self, queue: usize) -> Option<(ID3D12CommandList, ID3D12Fence, u64, Vec<(ID3D12Fence, u64)>)> { + if self.removed || self.copy_in_flight || !self.dirty { + return None; + } + if super::real::fence_completed(&self.copy_fence) == u64::MAX + || self.pending_fences.iter().any(|(_, f, _)| super::real::fence_completed(f) == u64::MAX) + { + self.removed = true; + return None; + } + let cold_dirty = self.slots.iter().any(|s| s.dirty && s.hist_valid == 0); + if !cold_dirty && self.last_copy.elapsed().as_millis() < FEEDBACK_WINDOW_MS { + return None; + } + for s in &mut self.slots { + if s.dirty { + s.in_flight_cap = s.last_cap; + s.last_cap = u32::MAX; + s.dirty = false; + } + } + self.dirty = false; + let waits: Vec<(ID3D12Fence, u64)> = std::mem::take(&mut self.pending_fences) + .into_iter() + .filter_map(|(q, f, v)| (q != queue).then_some((f, v))) + .collect(); + self.copy_in_flight = true; + self.copy_val += 1; + self.last_copy = std::time::Instant::now(); + let cl: ID3D12CommandList = self.copy_list.cast().ok()?; + Some((cl, self.copy_fence.clone(), self.copy_val, waits)) + } + + fn slot_for(&mut self, pso: usize) -> Option<(u64, u32, Option)> { + if self.removed { + return None; + } + let idx = if let Some(&i) = self.by_pso.get(&pso) { + i + } else if self.slots.len() < FEEDBACK_SLOTS { + let i = self.slots.len(); + self.slots.push(IndirectFeedbackSlot::new()); + self.by_pso.insert(pso, i); + i + } else { + return None; + }; + Some((self.gpu_va, idx as u32 + 1, self.slots[idx].hint())) } - let threads = super::real::pso_threads_exact(pso)?.map(|t| t.max(1)); - let groups = std::array::from_fn(|k| dims[k].div_ceil(threads[k])); - let limits = std::array::from_fn(|k| if dims[k] % threads[k] != 0 { dims[k] } else { 0 }); - Some((groups, limits)) } -fn skip_untranslated_dispatch(pso: usize) { - 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"); +unsafe fn prepare_indirect_feedback(dev: &ID3D12Device, pso: usize) -> Option<(u64, u32, Option)> { + let dev_key = dev.as_raw() as usize; + { + let mut g = FEEDBACK.lock().unwrap(); + if let Some(fb) = g.as_mut().and_then(|m| m.get_mut(&dev_key)) { + return fb.slot_for(pso); + } } - count(DISPATCHES_SKIPPED); + let created = match IndirectFeedback::new(dev) { + Ok(fb) => fb, + Err(e) => { + static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !WARNED.swap(true, Ordering::Relaxed) { + crate::xlog_warn!("D3D12.X: two-pass indirect feedback disabled: {e}"); + } + return None; + } + }; + FEEDBACK_ACTIVE.store(true, Ordering::Release); + let mut g = FEEDBACK.lock().unwrap(); + g.get_or_insert_with(HashMap::new).entry(dev_key).or_insert(created).slot_for(pso) } -/// `Dispatch` / `DispatchX(x, y, z, flags)`. -pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { - let (bound_pso, resolution) = with(this, |s| (s.pso, s.resolution.clone())); - if let Some(resolution) = &resolution { - if super::list_x::defer_retained(this, resolution, super::list_x::Deferred::Dispatch(x, y, z, flags)) { - return; +fn mark_indirect_feedback_used(dev_key: usize, fb_slot: u32, cap: u32, queue: usize, fence: Option<(&ID3D12Fence, u64)>) { + if fb_slot == 0 { + return; + } + let mut g = FEEDBACK.lock().unwrap(); + if let Some(fb) = g.as_mut().and_then(|m| m.get_mut(&dev_key)) { + if let Some(slot) = fb.slots.get_mut((fb_slot - 1) as usize) { + slot.last_cap = slot.last_cap.min(cap); + slot.dirty = true; + fb.dirty = true; + if let Some((f, v)) = fence { + record_queue_fence(&mut fb.pending_fences, queue, f, v); + } } } - let Some(pso) = resolve_pipeline(this as usize, bound_pso, resolution) else { - skip_untranslated_dispatch(bound_pso); +} + +/// Consume completed async `IndirectFeedback` copies and trigger the next pre-recorded +/// readback+clear on `queue` when a cold slot finished or 250 ms passed. +pub(super) unsafe fn poll_two_pass_feedback(queue: *mut c_void) { + if !FEEDBACK_ACTIVE.load(Ordering::Acquire) || queue.is_null() { return; - }; - 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) - skip_untranslated_dispatch(pso); + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + if q.GetDesc().Type != D3D12_COMMAND_LIST_TYPE_DIRECT { return; } - let Some((groups, limits)) = dispatch_groups(pso, [x, y, z], flags) else { - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: DispatchX of {x}x{y}x{z} threads (flags {flags:#x}) with a pipeline whose group shape is not known ({pso:#x}) skipped"); - } - count(DISPATCHES_SKIPPED); + let mut dev: Option = None; + if q.GetDevice(&mut dev).is_err() { return; + } + let Some(dev_key) = dev.as_ref().map(|d| d.as_raw() as usize) else { return }; + let to_submit = { + let mut g = FEEDBACK.lock().unwrap(); + let Some(fb) = g.as_mut().and_then(|m| m.get_mut(&dev_key)) else { return }; + fb.consume_completed(); + fb.schedule_copy(queue as usize) }; - if !valid_dispatch_grid(groups) { - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: Dispatch of {}x{}x{} groups exceeds the PC limit of {MAX_DISPATCH_GROUPS} on one axis and was skipped", groups[0], groups[1], groups[2]); + if let Some((cl, fence, val, waits)) = to_submit { + for (wf, wv) in waits { + let _ = q.Wait(&wf, wv); } - count(DISPATCHES_SKIPPED); - return; - } - if flags != 0 { - // each kind of flags once: what titles pass, and what it launches - static SEEN: Mutex> = Mutex::new(Vec::new()); - let first = { let mut g = SEEN.lock().unwrap(); !g.contains(&flags) && { g.push(flags); true } }; - if first { - crate::xlog_info!("D3D12.X: DispatchX with flags {flags:#x}: {x}x{y}x{z} launched as {}x{}x{} groups (thread limits {limits:?})", groups[0], groups[1], groups[2]); + if super::real::is_adopted(queue) { + let mut raw = [cl.as_raw()]; + type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + let exec: ExecFn = std::mem::transmute(super::real::orig_fn(queue, 10)); + exec(queue, 1, raw.as_mut_ptr()); + } else { + q.ExecuteCommandLists(&[Some(cl)]); } - } - let done = translated_dispatch(this, list, bound_pso, pso, groups[0], groups[1], groups[2], limits); - match done { - Ok(()) => count(DISPATCHES), - Err(e) => { - count(DISPATCHES_SKIPPED); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: Dispatch with a translated pipeline skipped: {e}"); + if q.Signal(&fence, val).is_err() { + let mut g = FEEDBACK.lock().unwrap(); + if let Some(fb) = g.as_mut().and_then(|m| m.get_mut(&dev_key)) { + fb.removed = true; } } } } -/// `XCL_TRACE_FRAME`: a full-screen dispatch (enough groups to cover a 4K target in tiles of up -/// to 128 pixels) – what its root arguments say. A bindless title passes the indices of its -/// descriptors in root constants and constant buffers: every small value there is looked up -/// in the dispatch's descriptor tables, and the resources found (the pass's inputs and -/// outputs) are logged. -unsafe fn trace_fullscreen(this: *mut c_void, pso: usize, groups: [u32; 3]) { - if groups[0] < 30 || groups[1] < 17 { - return; - } - let Some(u) = crate::gpu::uma::get() else { return }; - let (layout, args) = with(this, |s| (s.layout.clone(), s.args.clone())); - let Some(layout) = layout else { return }; - static SEEN: Mutex> = Mutex::new(Vec::new()); - { - let mut g = SEEN.lock().unwrap(); - if g.contains(&pso) || g.len() >= 12 { - return; +unsafe fn install_res_buffer(this: *mut c_void, entry: TwoPassBuf) -> (ID3D12Resource, u64, u64) { + let (buf, cap) = (entry.res.clone(), entry.bytes); + let va = buf.GetGPUVirtualAddress(); + with(this, |s| { + mark_two_pass_tracking(this, &mut s.res_untracked); + if let Some(old) = s.res_buf.replace(entry) { + s.res_retired.push(old); } - g.push(pso); + }); + track_two_pass_list(this as usize); + (buf, va, cap) +} + +unsafe fn try_ensure_res_buffer_exact_with_cap(this: *mut c_void, need_bytes: u64, budget_cap: u64) -> Result, String> { + let need = record_buffer_bytes(need_bytes); + if let Some((buf, cap)) = with(this, |s| s.res_buf.as_ref().filter(|b| b.bytes >= need).map(|b| (b.res.clone(), b.bytes))) { + let va = buf.GetGPUVirtualAddress(); + return Ok(Some((buf, va, cap))); } - let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); - let mut tables: Vec = Vec::new(); - let mut values: Vec = Vec::new(); - let mut what: Vec = Vec::new(); - for (i, p) in layout.params.iter().enumerate() { - match *p { - Param::Constants { at, count } => { - let w: Vec = (0..count as usize).filter_map(|k| word(at as usize + 4 * k)).collect(); - what.push(format!("p{i} constants {w:x?}")); - values.extend(&w); - } - Param::Descriptor { at } => { - let lo = word(at as usize).unwrap_or(0) as u64; - let hi = word(at as usize + 4).unwrap_or(0) as u64; - let va = (lo | hi << 32) as usize; - let n = 64usize; - if va != 0 && crate::gpu::shader::readable(va, 4 * n) { - let w: Vec = (0..n).map(|k| ((va + 4 * k) as *const u32).read_unaligned()).collect(); - what.push(format!("p{i} buffer {va:#x}: {w:x?}")); - values.extend(&w); - } else { - what.push(format!("p{i} buffer {va:#x} (not readable)")); - } - } - Param::Table { at } => { - let v = word(at as usize).unwrap_or(0); - what.push(format!("p{i} table {v:#x}")); - tables.push(v); - } + let dev = super::real::list_device(this).ok_or("no device for two-pass buffer")?; + let Some(entry) = acquire_two_pass_buf_with_cap(&dev, need, need.saturating_mul(2), u64::MAX, "two-pass res buffer", budget_cap, std::time::Duration::ZERO)? else { + return Ok(None); + }; + Ok(Some(install_res_buffer(this, entry))) +} + +/// The record buffer of this list for `need_bytes` (shrinking to `min_fit_bytes` if the cap is +/// full after waiting on in-flight fences): buffer, address, bytes. +unsafe fn ensure_res_buffer_with_cap(this: *mut c_void, need_bytes: u64, min_fit_bytes: u64, budget_cap: u64) -> Result<(ID3D12Resource, u64, u64), String> { + let need = record_buffer_bytes(need_bytes); + let existing = with(this, |s| s.res_buf.as_ref().map(|b| (b.res.clone(), b.bytes))); + let existing_cap = existing.as_ref().map_or(0, |(_, c)| *c); + if let Some((buf, cap)) = &existing { + if *cap >= need { + let va = buf.GetGPUVirtualAddress(); + return Ok((buf.clone(), va, *cap)); } } - let mut found: Vec<(u32, usize)> = Vec::new(); - for &v in &values { - if v >= 1 << 20 { - continue; - } - for &t in &tables { - let slot = u.base() + t as usize + 32 * v as usize; - if let Some(r) = super::console_heap::resource_at(slot) { - if !found.iter().any(|x| x.1 == r) { - found.push((v, r)); + let dev = super::real::list_device(this).ok_or("no device for two-pass buffer")?; + let entry = match acquire_res_buf_with_cap(&dev, need, min_fit_bytes, existing_cap, budget_cap, FENCE_WAIT_LIMIT)? { + Some(e) => e, + None => { + if let Some((buf, cur_cap)) = existing { + if cur_cap >= record_buffer_bytes(min_fit_bytes) { + note_two_pass(TP_SHRUNK); + let va = buf.GetGPUVirtualAddress(); + return Ok((buf, va, cur_cap)); } } + return Err(refuse_two_pass("two-pass res buffer", need, budget_cap)); } - } - let res: Vec = found - .iter() - .map(|&(v, r)| { - let d = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| x.GetDesc()); - format!("[{v}] {r:#x} {:?}{}", d.map(|d| (d.Dimension.0, d.Width, d.Height, d.Format.0)), if super::present::is_presented(r) { " PRESENTED" } else { "" }) - }) - .collect(); - crate::xlog_info!("frame trace: full-screen dispatch {groups:?}, pipeline {pso:#x}: {}", what.join("; ")); - crate::xlog_info!("frame trace: … its indices name: {}", if res.is_empty() { "nothing".to_string() } else { res.join("; ") }); + }; + Ok(install_res_buffer(this, entry)) } -/// #148 AllocateUploadMemory(size, alignment) → CPU/GPU pointer in unified memory (used by -/// `XboxBvhBuilder.dll` and other console middleware on default title command lists). -/// Freed automatically when the list's command allocator is reset. -pub(super) unsafe extern "system" fn allocate_upload_memory(this: *mut c_void, size: usize, align: usize) -> *mut u8 { - let Some(u) = crate::gpu::uma::get() else { - return std::ptr::null_mut(); - }; - let size = size.max(16); - let align = align.max(16); - if size <= crate::gpu::uma::ARENA_BLOCK / 2 { - if let Some(p) = with(this, |s| s.arena.take(u, size, align, &mut s.uma)) { - return p; - } - } - if u.has_sparse() { - if let Some((p, _)) = super::sparse::alloc(size, align) { - with(this, |s| s.uma.push(p)); - return p as *mut u8; - } - } - match u.alloc(size, align) { - Some(p) => { - with(this, |s| s.uma.push(p as usize)); - p +/// The `io` block of a two-pass stage: its user SGPRs (`compute_pass`: the MS layout) with the +/// argument table at `table_at`, and the high dword of unified memory's base, as the other binds +/// write it (the translated pair picks each access's memory window from it). After the +/// arguments, the addresses of the view heap and the sampler heap set (`heaps`) when the root +/// signature has its shaders index them (`console_list::with_heaps`): the console's mesh +/// stages take them there as its compute and graphics stages do (s23 / s24 for a mesh stage +/// with three tables, a root view and two constants). +fn two_pass_io(layout: Option<&Layout>, args: &[u8], table_at: u64, compute_pass: bool, uma_base: usize, heaps: [u32; 2]) -> Vec { + let mut io = match layout { + Some(l) if compute_pass => console_list::with_heaps(l, None, console_list::user_data_ms(l, args, table_at), heaps), + Some(l) => console_list::with_heaps(l, None, console_list::user_data_gfx(l, args, table_at), heaps), + None if compute_pass => { + let mut v = vec![0u32; 16]; + v[8] = table_at as u32; + v[9] = (table_at >> 32) as u32; + v } - None => std::ptr::null_mut(), - } + None => vec![table_at as u32, (table_at >> 32) as u32], + }; + io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + io[crate::gpu::recomp::IO_UMA_BASE_HI] = (uma_base as u64 >> 32) as u32; + io } -unsafe fn translated_dispatch( +unsafe fn bind_two_pass_stage( this: *mut c_void, list: &ID3D12GraphicsCommandList, - original: usize, - pso: usize, - x: u32, - y: u32, - z: u32, - limits: [u32; 3], + real_mesh_pso: usize, + tp: &super::real::TwoPassPso, + res_va: u64, + compute_pass: bool, ) -> Result<(), String> { - if super::present::trace_frame() { - trace_fullscreen(this, pso, [x, y, z]); - } - let allocator = bind_compute_abi_resolved(this, list, original, pso, limits)?; - super::real::dispatch_chain::dispatch(list, original, pso, allocator, [x, y, z]) + // the pair is translated with heap windows when they are on (`pso::mem_windows`): as `bind_abi` + super::list_x::ensure_view_heap(this); + let stage = prepare_two_pass_stage(this, real_mesh_pso, tp, res_va, compute_pass, 0)?; + emit_two_pass_stage(list, &stage, compute_pass); + Ok(()) } -/// XCL's ABI for a translated pipeline: its root signature, the user SGPRs (`io`, the kept -/// arguments the console's way – compute or graphics) and the argument table in unified -/// memory, u1 res, u2… the memory windows; then the pipeline. -struct PreparedAbiState { - layout: Option>, - args: Vec, - inline: usize, - table_at: usize, - io_at: usize, - res_at: usize, - allocator: usize, +/// What a two-pass stage binds: its root signature, pipeline and root views – the io block made +/// from the title's root arguments as they are when it is prepared, the records, the memory +/// windows (`prepare_two_pass_stage`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct StageBind { + rs: usize, + pso: usize, + views: [u64; 6], } -fn prepare_abi_state( - this: *mut c_void, - u: &crate::gpu::uma::Uma, - gfx: bool, - user_sgprs: Option, -) -> Result { - with(this, |state| { - let (layout, args) = if gfx { - (state.layout_gfx.clone(), state.args_gfx.clone()) - } else { - (state.layout.clone(), state.args.clone()) - }; - let inline = layout - .as_ref() - .map_or(0, |layout| if gfx { layout.inline_gfx } else { console_list::inline_for(layout, user_sgprs) } as usize) - .min(args.len()); - let table_at = state.arena.take(u, (args.len() - inline).max(16), 256, &mut state.uma) - .ok_or("unified memory is full")? as usize; - let io_at = state.arena.take( - u, - crate::gpu::recomp::KERNEL_SGPRS * std::mem::size_of::(), - 256, - &mut state.uma, - ).ok_or("unified memory is full")? as usize; - let res_at = state.arena.take(u, 256, 256, &mut state.uma).ok_or("unified memory is full")? as usize; - Ok(PreparedAbiState { layout, args, inline, table_at, io_at, res_at, allocator: state.allocator }) - }) +/// `stage` on `list`: root signature, root views, pipeline. +unsafe fn emit_two_pass_stage(list: &ID3D12GraphicsCommandList, stage: &StageBind, compute_pass: bool) { + let (rs_raw, pso_raw) = (stage.rs as *mut c_void, stage.pso as *mut c_void); + let (Some(rs), Some(pc)) = (ID3D12RootSignature::from_raw_borrowed(&rs_raw), ID3D12PipelineState::from_raw_borrowed(&pso_raw)) else { return }; + if compute_pass { + list.SetComputeRootSignature(rs); + for (k, &v) in stage.views.iter().enumerate() { + list.SetComputeRootUnorderedAccessView(k as u32, v); + } + } else { + list.SetGraphicsRootSignature(rs); + for (k, &v) in stage.views.iter().enumerate() { + list.SetGraphicsRootUnorderedAccessView(k as u32, v); + } + } + list.SetPipelineState(pc); } -fn prepared_abi_io( - layout: Option<&Layout>, args: &[u8], table_at: usize, gfx: bool, - user_sgprs: Option, uma_base: usize, limits: [u32; 3], -) -> Vec { - let mut io = match layout { - Some(layout) if gfx => console_list::user_data_gfx(layout, args, table_at as u64), - Some(layout) => console_list::user_data_for(layout, user_sgprs, args, table_at as u64), - None => vec![table_at as u32, (table_at >> 32) as u32], +/// The binding of a two-pass stage with the title's root arguments as they are now, written to +/// unified memory (its io block and argument table): nothing is recorded on the list. +unsafe fn prepare_two_pass_stage( + this: *mut c_void, real_mesh_pso: usize, tp: &super::real::TwoPassPso, + res_va: u64, compute_pass: bool, group_base: u32, +) -> Result { + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let first = first_window(super::real::uma_window_va(0), u.shadowed())?; + let (layout, args, heaps) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone(), s.heaps)); + want_root_views(layout.as_deref(), &args, super::view_want::Path::MeshStage); + let copy = |bytes: &[u8]| -> Result { + let p = with(this, |s| s.arena.take(u, bytes.len().max(16), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); + Ok(p as usize) }; - io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); - io[crate::gpu::recomp::IO_UMA_BASE_HI] = (uma_base >> 32) as u32; - if !gfx { - for (k, limit) in limits.into_iter().enumerate() { - io[crate::gpu::recomp::IO_THREAD_LIMIT[k]] = limit; + let inline = layout + .as_ref() + .map_or(0, |l| if compute_pass { l.inline_ms } else { l.inline_gfx } as usize) + .min(args.len()); + let table_at = copy(&args[inline..])?; + let mut io = two_pass_io(layout.as_deref(), &args, table_at as u64, compute_pass, u.base(), heaps); + io[crate::gpu::recomp::IO_MESH_GROUP_BASE] = group_base; + let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; + let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); + let rs = if compute_pass { tp.compute_rs } else { tp.mesh_rs }; + if rs == 0 { + return Err("two-pass root signature".into()); + } + let pso = if compute_pass { tp.compute } else { real_mesh_pso }; + if pso == 0 { + return Err(if compute_pass { "two-pass compute pipeline" } else { "two-pass mesh pipeline" }.into()); + } + let w = |k: usize| super::real::uma_window_va(k).unwrap_or(first); + Ok(StageBind { rs, pso, views: [va(io_at), res_va, w(0), w(1), w(2), w(3)] }) +} + +/// The pass that rewrites a two-pass ExecuteIndirect's arguments, on XCL's ABI: u0 = `count`, +/// `stride`, `offset` (of the DispatchMesh argument), `split`, `cap` (groups with a record), and +/// where the commands are (u2) and go (u3), in bytes. Each command goes out twice, for the compute +/// pass and then (at `count · stride`) for the mesh pass, with at most `cap` groups, all in X: +/// both passes find a group's record by `gid.x` alone. With a count buffer (u0 dword 7 set: the +/// count at dword 8's byte offset in u4), the commands past its count get no groups: they are run +/// one by one (`two_pass_steps`), so without one. +pub(super) const SCALE_ARGS_HLSL: &str = r#"RWByteAddressBuffer io : register(u0); +RWByteAddressBuffer fb : register(u1); +RWByteAddressBuffer src : register(u2); +RWByteAddressBuffer dst : register(u3); +RWByteAddressBuffer cnt : register(u4); +[numthreads(64, 1, 1)] +void main(uint tid : SV_DispatchThreadID) { + uint count = io.Load(0), stride = io.Load(4), offset = io.Load(8), split = io.Load(12), cap = io.Load(16); + if (tid >= count) return; + uint live = io.Load(28) != 0u ? min(count, cnt.Load(io.Load(32))) : count; + uint s = io.Load(20) + tid * stride, d = io.Load(24) + tid * stride, m = d + count * stride; + for (uint i = 0u; i < stride; i += 4u) { + uint w = src.Load(s + i); + dst.Store(d + i, w); + dst.Store(m + i, w); + } + uint3 g = src.Load3(s + offset); + uint raw_n = 0u; + uint n = 0u; + if (tid < live && g.x != 0u && g.y != 0u && g.z != 0u) { + uint lim = 0xFFFFFFFDu; + raw_n = min(g.x, lim); + raw_n = g.y > lim / raw_n ? lim : raw_n * g.y; + raw_n = g.z > lim / raw_n ? lim : raw_n * g.z; + n = min(raw_n, cap); + } + uint fb_slot = io.Load(36); + if (fb_slot != 0u) { + uint prev; + if (raw_n > cap) { + fb.InterlockedAdd(0u, 1u); + fb.InterlockedAdd(4u, raw_n - cap); } + fb.InterlockedMax((fb_slot + 1u) * 4u, raw_n + 1u, prev); } - io + dst.Store3(d + offset, uint3(n, 1u, 1u)); + dst.Store3(m + offset, uint3(n * split, 1u, 1u)); } +"#; -unsafe fn bind_abi_resolved( - this: *mut c_void, list: &ID3D12GraphicsCommandList, original: usize, pso: usize, gfx: bool, -) -> Result<(), String> { - bind_abi_with_root_resolved(this, list, original, pso, gfx, 0, [0; 3]).map(|_| ()) +unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: Mutex>> = Mutex::new(None); + let key = dev.as_raw() as usize; + if let Some(pair) = CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(pair); + } + let dxil = crate::gpu::recomp::dxc::compile_cached(SCALE_ARGS_HLSL, "main", "cs_6_6")?.0; + let rs = crate::gpu::recomp::pso::abi_root_signature(dev, false)?; + let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const c_void, BytecodeLength: dxil.len() }, + ..Default::default() + }; + let res_pso: Result = dev.CreateComputePipelineState(&cdesc); + std::mem::ManuallyDrop::drop(&mut cdesc.pRootSignature); + let pso = res_pso.map_err(|e| format!("scale pso create: {e}"))?; + CACHE.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); + Ok((rs, pso)) +} + +/// `bytes` of this recording's scratch blocks (COMMON between uses): the block and the offset. +/// Past `SCRATCH_CAP` a recording gets no more. +unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, u64), String> { + let bytes = bytes.next_multiple_of(256); + if let Some(r) = with(this, |s| { + let (b, cap) = s.scratch.as_ref()?; + (s.scratch_used + bytes <= *cap).then(|| { + s.scratch_used += bytes; + (b.clone(), s.scratch_used - bytes) + }) + }) { + return Ok(r); + } + let size = bytes.max(SCRATCH_BLOCK); + let remaining = SCRATCH_CAP.saturating_sub(with(this, |s| s.scratch_taken)); + if size > remaining { + return Err(format!("its rewritten arguments are past {} MiB this recording", SCRATCH_CAP >> 20)); + } + let cap = two_pass_cap(); + let block = acquire_two_pass_buf_with_cap(dev, size, remaining, remaining, "two-pass argument scratch", cap, FENCE_WAIT_LIMIT)? + .ok_or_else(|| refuse_two_pass("two-pass argument scratch", size, cap))?; + let b = block.res.clone(); + with(this, |s| { + mark_two_pass_tracking(this, &mut s.res_untracked); + s.scratch_taken += block.bytes; + s.scratch_used = bytes; + s.scratch = Some((block.res.clone(), block.bytes)); + s.scratch_in_args = false; + s.res_retired.push(block); + }); + track_two_pass_list(this as usize); + Ok((b, 0)) } -unsafe fn bind_compute_abi_resolved( +/// The root UAVs of the pass that rewrites a two-pass ExecuteIndirect's arguments +/// (`SCALE_ARGS_HLSL`), as (root slot, GPU address): every view its program declares gets one. +/// +/// u1 holds feedback (`IndirectFeedback::gpu`) and u4 holds the count (`SCALE_ARGS_HLSL` reads +/// them conditionally) – but the root signature was just set, so any left-out slot holds nothing +/// and a driver prefetch from GPU address 0 removes the device on NVIDIA (0x887A0006). When +/// absent, both name `consts`, which are always valid. +fn scale_views(consts: u64, fb: Option, src: u64, dst: u64, count: Option) -> [(u32, u64); 5] { + [(0, consts), (1, fb.unwrap_or(consts)), (2, src), (3, dst), (4, count.unwrap_or(consts))] +} + +/// The arguments of `max` commands at UMA address `src`, rewritten for the two passes +/// (`SCALE_ARGS_HLSL`) into a scratch block: the block (INDIRECT_ARGUMENT until the caller puts +/// it back to COMMON; with `batch` it stays there until the next rewrite into it, +/// `State::scratch_in_args`) and where the compute pass's commands are; the mesh pass's follow them. +/// +/// They are read through the memory window over them, as translated shaders read memory, not +/// through the title's buffer: its state on the PC is the title's and not known here. So is the +/// count (`count`: its UMA address, when the title gave a count buffer). +#[allow(clippy::too_many_arguments)] +unsafe fn make_scaled_args_buffer( this: *mut c_void, list: &ID3D12GraphicsCommandList, - original: usize, + src: usize, + count: Option, + max: u32, + stride: u32, + mesh_offset: u32, + split: u32, + cap: u32, + batch: bool, + fb_va: Option, + fb_slot: u32, +) -> Result<(ID3D12Resource, u64), String> { + let (rewrite, dst, dst_off) = prepare_scaled_args(this, src, count, max, stride, mesh_offset, split, cap, fb_va, fb_slot)?; + // the title's writes of the arguments before this (`fresh_indirect_arguments`) + if batch { + let before = scratch_state(with(this, |s| s.scratch_in_args)); + emit_uav_and_transition(list, None, &dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } else { + emit_uav_barrier(list, None); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + let (rs_raw, pso_raw) = (rewrite.rs as *mut c_void, rewrite.pso as *mut c_void); + list.SetComputeRootSignature(ID3D12RootSignature::from_raw_borrowed(&rs_raw)); + list.SetPipelineState(ID3D12PipelineState::from_raw_borrowed(&pso_raw)); + for (slot, va) in rewrite.views { + list.SetComputeRootUnorderedAccessView(slot, va); + } + list.Dispatch(rewrite.groups, 1, 1); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + if batch { + with(this, |s| s.scratch_in_args = true); + } + Ok((dst, dst_off)) +} + +/// The pass that rewrites an ExecuteIndirect's arguments as bound (`SCALE_ARGS_HLSL`): its root +/// signature and pipeline (made once a device, kept), root views and groups. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Rewrite { + rs: usize, pso: usize, - limits: [u32; 3], -) -> Result { - bind_abi_with_root_resolved(this, list, original, pso, false, 0, limits) + views: [(u32, u64); 5], + groups: u32, } -unsafe fn bind_abi_with_root_resolved( - this: *mut c_void, list: &ID3D12GraphicsCommandList, original: usize, pso: usize, gfx: bool, - root: usize, limits: [u32; 3], -) -> Result { - #[cfg(test)] - { - if STOP_ABI_LIST.load(Ordering::Acquire) == this as usize { - LAST_ABI_PSO.store(pso, Ordering::Release); - return Err("stopped after resolved PSO for test".into()); - } - } - #[cfg(test)] - if STOP_ABI_AFTER_BIND_LIST.load(Ordering::Acquire) == this as usize && root == 0 { - super::real::bind_pipeline_exact(this, original, pso); - LAST_ABI_PSO.store(pso, Ordering::Release); - return Err("stopped after exact native bind for test".into()); - } - let shared_view_bound = super::list_x::ensure_view_heap(this); +/// `make_scaled_args_buffer` up to what it records: the rewrite's constants in unified memory, +/// its place in a scratch block, the block and the offset. +#[allow(clippy::too_many_arguments)] +unsafe fn prepare_scaled_args( + this: *mut c_void, + src: usize, + count: Option, + max: u32, + stride: u32, + mesh_offset: u32, + split: u32, + cap: u32, + fb_va: Option, + fb_slot: u32, +) -> Result<(Rewrite, ID3D12Resource, u64), String> { + let dev = super::real::list_device(this).ok_or("no device")?; + let (rs, pso) = scale_indirect_pipeline(&dev)?; let u = crate::gpu::uma::get().ok_or("no unified memory")?; - let windows = super::real::uma_window_vas(); - let first = *windows.first().ok_or("unified memory is not open on the GPU")?; - // 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_exact(pso) }; - let prepared = prepare_abi_state(this, u, gfx, user_sgprs)?; - let PreparedAbiState { layout, args, inline, table_at, io_at, res_at, allocator } = prepared; - std::ptr::copy_nonoverlapping(args[inline..].as_ptr(), table_at as *mut u8, args.len() - inline); - let io = prepared_abi_io(layout.as_deref(), &args, table_at, gfx, user_sgprs, u.base(), limits); - let io_bytes = io.iter().flat_map(|word| word.to_le_bytes()).collect::>(); - std::ptr::copy_nonoverlapping(io_bytes.as_ptr(), io_at as *mut u8, io_bytes.len()); - std::ptr::write_bytes(res_at as *mut u8, 0, 256); - let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); - let rs = (root != 0).then_some(root) - .or_else(|| super::real::pso_root_signature_exact(pso)) - .or_else(|| super::real::abi_rs_cached().map(|p| p as usize)) - .ok_or("no XCL ABI root signature")?; - let rs = rs as *mut c_void; - let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?; - let views = [va(io_at), va(res_at)].into_iter().chain((0..4).map(|k| windows.get(k).copied().filter(|&v| v != 0).unwrap_or(first))); - if gfx { - list.SetGraphicsRootSignature(rs); - for (k, v) in views.enumerate() { - list.SetGraphicsRootUnorderedAccessView(k as u32, v); + let commands = (max as u64).saturating_mul(stride as u64); + // only the GPU reads them: in a GPU view too, once its tiles are asked for + want_view(super::view_want::Path::MemoryOp, src as u64, commands); + super::real::uma_window_buffer_gpu(src, commands as usize).ok_or("the indirect arguments are not in one memory window")?; + let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; + let count_va = match count { + Some(p) => { + want_view(super::view_want::Path::MemoryOp, p as u64, 4); + super::real::uma_window_buffer_gpu(p, 4).ok_or("the indirect count is not in a memory window")?; + Some(super::real::uma_va_of(p).ok_or("unified memory is not open on the GPU")?) } + None => None, + }; + let (dst, dst_off) = scratch_args(this, &dev, commands.saturating_mul(2))?; + let consts: Vec = [max, stride, mesh_offset, split, cap, 0, 0, count_va.is_some() as u32, 0, fb_slot].iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = with(this, |s| s.arena.take(u, consts.len(), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(consts.as_ptr(), p, consts.len()); + let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; + let views = scale_views(consts_va, fb_va, src_va, dst.GetGPUVirtualAddress() + dst_off, count_va); + // (the pair is the device's for good: `scale_indirect_pipeline` keeps it) + Ok((Rewrite { rs: rs.as_raw() as usize, pso: pso.as_raw() as usize, views, groups: max.div_ceil(64) }, dst, dst_off)) +} + +/// The state the scratch block of a recording is in before a rewrite: INDIRECT_ARGUMENT when the +/// last two-pass ExecuteIndirect left it there (`two_pass_batch`), else COMMON. A block left in +/// INDIRECT_ARGUMENT when the recording moves on to another, or closes, is a buffer: it decays to +/// COMMON when its ExecuteCommandLists is done, before another recording can take it (`FREE_RES` +/// takes back a recording's blocks at its allocator's reset). +fn scratch_state(in_args: bool) -> D3D12_RESOURCE_STATES { + if in_args { + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT } else { - list.SetComputeRootSignature(rs); - for (k, v) in views.enumerate() { - list.SetComputeRootUnorderedAccessView(k as u32, v); - } + D3D12_RESOURCE_STATE_COMMON } - if root == 0 { - super::real::bind_pipeline_exact(this, original, pso); +} + +/// What a DispatchMesh or ExecuteIndirect draws with, decided once from `resolved`, what the +/// retained bind of the title's pipeline resolved to (`resolve_indirect_pipeline`). +enum DrawPipeline { + /// a pipeline XCL built from console MS / GS code: its two passes, with `resolved` as the + /// mesh pass's pipeline + TwoPass(Arc), + /// the stand-in of a pipeline being built (or built since the resolve: the draw still has + /// the stand-in, which was made with the title's root signature, not the two passes') + StandIn, + /// anything else: a PC pipeline, a translated one, a failed build's stand-in + Other, +} + +fn draw_pipeline(resolved: usize, bound_unbuilt: bool) -> DrawPipeline { + if let Some(tp) = super::real::two_pass_of_exact(resolved) { + return DrawPipeline::TwoPass(tp); } - if shared_view_bound && super::vram::srv_tracking_enabled() { - super::list_x::note_shared_view_heap_use(this); + if bound_unbuilt { + return DrawPipeline::StandIn; } - Ok(allocator) + DrawPipeline::Other } -#[cfg(test)] -pub(super) fn last_draw_args() -> (bool, u32, u32, u32, i32) { - DRAW_ARGS.with(|d| d.get()) +/// Before a draw with a PC pipeline (also a stand-in or fallback, made with the title's root +/// signature): the title's graphics 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). +/// False: the list has none (the draw is skipped – it would run under whatever root signature a +/// translated draw left, XCL's ABI or a two-pass one), except on a bundle, which takes its +/// caller's. +unsafe fn bind_title_root_signature(this: *mut c_void, list: &ID3D12GraphicsCommandList) -> bool { + let rs = with(this, |s| s.rs_gfx) as *mut c_void; + if let Some(r) = ID3D12RootSignature::from_raw_borrowed(&rs) { + list.SetGraphicsRootSignature(r); + return true; + } + super::list_x::tracked_list_type(this) == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) } -#[cfg(test)] -pub(super) fn counts_snapshot() -> [u64; 5] { - std::array::from_fn(|k| COUNTS[k].load(Ordering::Relaxed)) +/// A draw skipped by `bind_title_root_signature` (logged the first 4 times). +fn note_no_root_signature() { + 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: a draw with a PC pipeline on a list with no graphics root signature set skipped"); + } } -#[cfg(test)] -pub(super) fn tracked_pso(list: *mut c_void) -> usize { - let Some(entry) = STATES.get(list as usize) else { return 0 }; - let pso = entry.state.lock().unwrap().pso; - pso +pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: u32, z: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDraw); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::DrawRecord); + let _c = capture_work(this, || super::capture::WorkKind::DispatchMesh([x, y, z]), true); + type PcDm = unsafe extern "system" fn(*mut c_void, u32, u32, u32); + let pc_dm: PcDm = std::mem::transmute(super::real::orig_fn(this, 79)); + let (raw_pso, resolution) = with(this, |s| (s.pso, s.resolution.clone())); + let Some((pso, bound_unbuilt)) = resolve_indirect_pipeline(this as usize, raw_pso, resolution) else { + super::list_x::note_dropped_draw(this); + mesh_work(this, super::targets::SKIPPED); + count(DRAWS_SKIPPED); + return; + }; + let tp = match draw_pipeline(pso, bound_unbuilt) { + DrawPipeline::TwoPass(tp) => Some(tp), + DrawPipeline::StandIn => { + mesh_work(this, super::targets::STANDIN); + count(DRAWS_SKIPPED); + return; + } + DrawPipeline::Other => None, + }; + // (XCL_TWO_PASS_BATCH=2: deferred, or the deferred ones recorded before this one) + if let Some(tp) = &tp { + if two_pass_defer() && defer_dispatch_mesh(this, tp, pso, raw_pso, [x, y, z]) { + return; + } + } + flush_two_pass(this, RunEnd::Draw); + if let Some(tp) = tp { + let groups = x.saturating_mul(y).saturating_mul(z); + if groups == 0 { + return; + } + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + let record_bytes = tp.record.record_dwords() as u64 * 4; + let need = (groups as u64).saturating_mul(record_bytes); + super::gpu_times::before(this, pso, super::gpu_times::Kind::Mesh(tp.kind), [x, y, z], false); + let run = (|| -> Result<(), String> { + let (res_buf, res_va, cap, records) = records_for(this, need, record_bytes, two_pass_batch())?; + let n = groups.min(record_groups(cap, record_bytes, tp.mesh_groups_per_record)); + if n == 0 { + return Err(format!("a record of {record_bytes} B does not fit the record buffer")); + } + // Slice ordinary mesh draws that would fit a full-sized record buffer. The + // compute shader gets the original group ID while each slice reuses record 0. + let draw_groups = if tp.kind == "MS" && groups <= record_groups(RECORD_MAX, record_bytes, tp.mesh_groups_per_record) { + groups + } else { + n + }; + let slices = draw_groups.div_ceil(n); + let staged = if slices > 1 { + // A half-buffer layout is selected only when the requested group count fits. + debug_assert_eq!(records, Records::Whole); + super::list_x::ensure_view_heap(this); + let mesh = prepare_two_pass_stage(this, pso, &tp, res_va, false, 0)?; + let compute = (0..slices) + .map(|slice| prepare_two_pass_stage(this, pso, &tp, res_va, true, slice * n)) + .collect::, _>>()?; + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_info!("D3D12.X: two-pass DispatchMesh of {groups} groups in {slices} slices ({n} groups fit the record buffer)"); + } + Some((mesh, compute)) + } else { + None + }; + if draw_groups < groups { + note_two_pass(TP_DIRECT_CUT); + note_two_pass_add(TP_DIRECT_GROUPS_DROPPED, (groups - draw_groups) as u64); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: two-pass DispatchMesh of {groups} groups: {} past the record buffer dropped", groups - draw_groups); + } + } + let plan = two_pass_plan(slices, records, with(this, |s| s.record_open)); + run_two_pass_plan(this, list, &plan, &res_buf, res_va, cap, |slice, compute, va| { + let first = slice * n; + let count = n.min(draw_groups - first); + if let Some((mesh, stages)) = &staged { + let stage = if compute { &stages[slice as usize] } else { mesh }; + emit_two_pass_stage(list, stage, compute); + } else { + bind_two_pass_stage(this, list, pso, &tp, va, compute)?; + } + if compute { + list.Dispatch(count, 1, 1); + } else { + pc_dm(this, count * tp.mesh_groups_per_record, 1, 1); + } + Ok(()) + }) + })(); + super::gpu_times::after(this); + match run { + Ok(()) => { + mesh_work(this, super::targets::RAN); + super::watch::note(raw_pso, super::watch::MESH, [groups, 0, 0]); + count(DRAWS); + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: two-pass DispatchMesh #{n} ({groups} groups, split {}, kind {})", tp.mesh_groups_per_record, tp.kind); + } + } + Err(e) => { + mesh_work(this, super::targets::SKIPPED); + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: two-pass DispatchMesh skipped: {e}"); + } + } + } + return; + } + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + if !bind_title_root_signature(this, list) { + note_no_root_signature(); + mesh_work(this, super::targets::SKIPPED); + count(DRAWS_SKIPPED); + return; + } + mesh_work(this, super::targets::PC); + count(DRAWS_PC); + super::watch::note(raw_pso, super::watch::PC_MESH, [x, y, z]); + pc_dm(this, x, y, z); } -#[cfg(test)] -fn state_locks_available_for_test(list: usize) -> bool { - let shard = match STATES.shards[state_shard_index(list)].try_lock() { - Ok(shard) => shard, - Err(_) => return false, - }; - let entry = shard.as_ref().and_then(|states| states.get(&list)).cloned(); - drop(shard); - let Some(entry) = entry else { return true }; - let available = entry.state.try_lock().is_ok(); - available +/// `XCL_DUMP_TARGETS`: a DispatchMesh (the two passes of a translated mesh pipeline count as the +/// one draw they stand for) with `outcome` +unsafe fn mesh_work(this: *mut c_void, outcome: usize) { + if super::targets::enabled() { + super::targets::note_draw(this, outcome); + } } -#[cfg(test)] -mod tests { - use super::super::{device_x, list_x, pso_async, real, title_list}; - use super::*; - use std::collections::HashSet; - use std::sync::atomic::{AtomicBool, AtomicUsize}; - use std::sync::mpsc; - use std::time::Duration; +/// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a +/// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root +/// arguments themselves cannot be – skipped, logged) +pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { + execute_indirect_classified(this, sig, max, args, args_off, count_buf, count_off, indirect_signature(sig)) +} - #[test] - fn aligned_list_addresses_reach_many_bind_shards() { - let shards = (0..256).map(|index| state_shard_index(0x7100_0000 + index * 16)).collect::>(); - assert!(shards.len() >= STATE_SHARDS / 2, "aligned list addresses reached only {} shards", shards.len()); - } +pub(super) unsafe fn execute_indirect_classified( + this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, + count_buf: usize, count_off: u64, signature: IndirectSignatureInfo, +) { + let (pso, resolution) = with(this, |state| (state.pso, state.resolution.clone())); + execute_indirect_snapshot( + this, sig, max, args, args_off, count_buf, count_off, signature, pso, resolution, true, + ) +} - #[test] - fn busy_bind_shard_does_not_block_an_unrelated_shard() { - let first = 0x7E57_BA00usize; - let second = (1..STATE_SHARDS) - .map(|index| first + index * 16) - .find(|&key| state_shard_index(key) != state_shard_index(first)) - .expect("shard mixer did not distribute aligned keys"); - let shard = STATES.shards[state_shard_index(first)].lock().unwrap(); - let (sent, received) = mpsc::channel(); - let worker = std::thread::spawn(move || { - drop(STATES.get_or_insert(second)); - sent.send(()).unwrap(); - }); - received.recv_timeout(Duration::from_secs(1)).expect("unrelated bind shard blocked"); - worker.join().unwrap(); - drop(shard); - drop(STATES.remove(second)); - } +/// A put-off dispatching ExecuteIndirect recorded at the submit (`list_x`): as the title's call, +/// never put off again. +pub(super) unsafe fn execute_indirect_retained( + this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, + count_buf: usize, count_off: u64, signature: IndirectSignatureInfo, +) { + let (pso, resolution) = with(this, |state| (state.pso, state.resolution.clone())); + execute_indirect_snapshot( + this, sig, max, args, args_off, count_buf, count_off, signature, pso, resolution, false, + ) +} - #[test] - fn busy_list_state_does_not_block_another_list_in_the_same_shard() { - let keys = (0..256).map(|index| Box::new(index as u8)).collect::>(); - let mut seen = HashMap::new(); - let (first, second) = keys - .iter() - .map(|key| (&**key as *const u8) as usize) - .find_map(|key| seen.insert(state_shard_index(key), key).map(|first| (first, key))) - .expect("allocator did not provide two keys in one shard"); - let first_entry = STATES.get_or_insert(first); - drop(STATES.get_or_insert(second)); - let state = first_entry.state.lock().unwrap(); - let (sent, received) = mpsc::channel(); - let worker = std::thread::spawn(move || { - with(second as *mut c_void, |state| state.pso = 0x7E57_D201); - sent.send(()).unwrap(); - }); - received.recv_timeout(Duration::from_secs(1)).expect("unrelated list state blocked"); - worker.join().unwrap(); - drop(state); - drop(STATES.remove(first)); - drop(STATES.remove(second)); +/// The pipeline a DispatchMesh or ExecuteIndirect of the bound `pso` draws or dispatches with: its +/// retained bind resolved once (waited for within `XCL_PSO_WAIT_MS`), and whether that is still the +/// stand-in of a pipeline being built. None: the retained identity is unavailable (fail-closed). +fn resolve_indirect_pipeline( + list: usize, + pso: usize, + resolution: Option, +) -> Option<(usize, bool)> { + match resolution { + Some(resolution) => match resolution.resolve_for_indirect() { + super::pso_async::IndirectPipelineChoice::Exact { raw, generation } => { + super::list_x::record_native_generation(list, Some(generation)); + Some((raw, false)) + } + super::pso_async::IndirectPipelineChoice::InitialFallback { raw, bound_unbuilt } => { + Some((raw, bound_unbuilt)) + } + super::pso_async::IndirectPipelineChoice::Unavailable => None, + }, + None => Some((pso, false)), } +} - #[test] - fn forget_then_same_address_create_uses_a_fresh_entry() { - let key = Box::new(0u8); - let list = (&*key as *const u8) as *mut c_void; - reset(list, 0, 0x7E57_D211); - let old = STATES.get(list as usize).unwrap(); - forget(list); - reset(list, 0, 0x7E57_D212); - let new = STATES.get(list as usize).unwrap(); - assert!(!Arc::ptr_eq(&old, &new)); - old.state.lock().unwrap().pso = 0x7E57_D213; - assert_eq!(tracked_pso(list), 0x7E57_D212, "orphaned state changed the replacement"); - forget(list); +unsafe fn execute_indirect_snapshot( + this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, + count_buf: usize, count_off: u64, signature: IndirectSignatureInfo, raw_pso: usize, + resolution: Option, allow_defer: bool, +) { + 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 dispatches = signature.dispatches(); + let _detail = crate::stall::detail_span(if dispatches { crate::stall::StallKind::DetailDispatch } else { crate::stall::StallKind::DetailDraw }); + let _t = super::look_stats::deep().then(|| { + crate::hle::api_cost::time(if dispatches { + crate::hle::api_cost::Call::DispatchRecord + } else { + crate::hle::api_cost::Call::DrawRecord + }) + }); + let captured = super::capture::on() && dispatches; + let _c = capture_work(this, || super::capture::indirect(sig, captured, max, args, args_off, count_buf, count_off), !captured); + let retained_compute = resolution.as_ref().map(|resolution| resolution.is_compute()); + // (a dispatching one whose pipeline would be waited for here: at the submit, `list_x`; + // recorded there through `execute_indirect_retained`, with everything below. The deferred + // two-pass draws before it are recorded first) + if allow_defer && dispatches && retained_compute == Some(true) { + let resolution = resolution.as_ref().unwrap(); + if resolution.submit_demand_pending() { + flush_two_pass(this, RunEnd::Draw); + } + if super::list_x::defer_retained(this, resolution, super::list_x::Deferred::Indirect { + sig, max, args, args_off, count_buf, count_off, signature, + }) { + super::capture::outcome(super::capture::Outcome::Deferred); + return; + } } - - #[test] - fn warm_bind_cache_does_not_take_the_registry_shard() { - let key = Box::new(0u8); - let list = (&*key as *const u8) as usize; - reset(list as *mut c_void, 0, 0x7E57_D221); - let (ready_tx, ready_rx) = mpsc::channel(); - let (continue_tx, continue_rx) = mpsc::channel(); - let (done_tx, done_rx) = mpsc::channel(); - let worker = std::thread::spawn(move || { - assert_eq!(with(list as *mut c_void, |state| state.pso), 0x7E57_D221); - ready_tx.send(()).unwrap(); - continue_rx.recv().unwrap(); - done_tx.send(with(list as *mut c_void, |state| state.pso)).unwrap(); - }); - ready_rx.recv_timeout(Duration::from_secs(1)).expect("cache worker did not warm its entry"); - let shard = STATES.shards[state_shard_index(list)].lock().unwrap(); - continue_tx.send(()).unwrap(); - assert_eq!(done_rx.recv_timeout(Duration::from_secs(1)).expect("warm cache took its registry shard"), 0x7E57_D221); - drop(shard); - worker.join().unwrap(); - forget(list as *mut c_void); + let Some((pso, bound_unbuilt)) = resolve_indirect_pipeline(this as usize, raw_pso, resolution) else { + ei_work(this, dispatches, super::targets::SKIPPED); + count_indirect_skip(dispatches); + return; + }; + // where the commands are in unified memory (a console buffer's offsets are the title's) + let commands_at = super::real::console_buffer(args).map(|(p, n)| (p + args_off as usize, n.saturating_sub(args_off as usize))); + let count_at = super::real::console_buffer(count_buf).filter(|&(_, n)| count_off as usize + 4 <= n).map(|(p, _)| p + count_off as usize); + if super::targets::enabled() && dispatches { + super::targets::note_indirect_compute(raw_pso, commands_at, count_at, count_buf != 0, max, super::indirect_guard::plain_dispatch(sig)); } - - #[test] - fn tls_cache_keeps_four_entries() { - let mut cache = BindStateCache { entries: [const { None }; STATE_CACHE_ENTRIES], next: 0 }; - let entries = (0..=STATE_CACHE_ENTRIES).map(|_| Arc::new(BindEntry::default())).collect::>(); - for (key, entry) in entries.iter().take(STATE_CACHE_ENTRIES).enumerate() { - cache.insert(key, entry); + let args_off_title = args_off; + let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); + let tp = match draw_pipeline(pso, bound_unbuilt) { + DrawPipeline::TwoPass(tp) => Some(tp), + // A pipeline still being built (or whose build finished after the resolve): 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. + DrawPipeline::StandIn => { + ei_work(this, dispatches, super::targets::STANDIN); + count_indirect_skip(dispatches); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect with a pipeline that is still being built skipped"); + } + return; } - for key in 0..STATE_CACHE_ENTRIES { - assert!(Arc::ptr_eq(&cache.get(key).unwrap(), &entries[key])); + DrawPipeline::Other => None, + }; + if let Some(tp) = tp { + // Only a noted DispatchMesh signature runs the two passes. Any other (one that changes + // root arguments, or whose companion Dispatch signature could not be made) would reach + // the PC call under the title's root signature with the pass-through mesh pipeline on + // the list, whose shaders read their memory through root views the title's root + // signature does not have. + let Some(msig) = dispatch_mesh_sig_of(sig) else { + ei_work(this, dispatches, super::targets::SKIPPED); + 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 two-pass pipeline and a signature that is not a plain DispatchMesh one (root arguments, or no companion Dispatch) skipped"); + } + return; + }; + // (XCL_TWO_PASS_BATCH=2: one command whose arguments and count are in unified memory + // deferred; anything else as without, after the deferred draws before it) + if two_pass_defer() && max == 1 && args != 0 { + let src = commands_at.filter(|&(_, n)| msig.byte_stride as usize <= n).map(|(p, _)| p); + let count = match (count_buf, count_at) { + (0, _) => Some(None), + (_, Some(p)) => Some(Some(p)), + _ => None, + }; + if let (Some(src), Some(count)) = (src, count) { + if defer_execute_indirect(this, &tp, pso, raw_pso, sig, msig, max, src, count) { + return; + } + } } - cache.insert(STATE_CACHE_ENTRIES, &entries[STATE_CACHE_ENTRIES]); - assert!(cache.get(0).is_none(), "FIFO cache did not evict its oldest entry"); - for key in 1..=STATE_CACHE_ENTRIES { - assert!(Arc::ptr_eq(&cache.get(key).unwrap(), &entries[key])); + flush_two_pass(this, RunEnd::Draw); + { + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + super::gpu_times::before(this, pso, super::gpu_times::Kind::Mesh(tp.kind), [max, 0, 0], true); + let run = (|| -> Result<(), String> { + if max == 0 || args == 0 { + return Ok(()); + } + let commands = max as usize * msig.byte_stride as usize; + let src = match commands_at { + Some((p, n)) if commands <= n => p, + _ => return Err("its arguments are not in a console buffer in unified memory".into()), + }; + let record_bytes = tp.record.record_dwords() as u64 * 4; + let batch = two_pass_batch(); + let fb_dev = super::real::list_device(this); + let (fb_va, fb_slot, hint) = match fb_dev.as_ref().and_then(|d| prepare_indirect_feedback(d, pso)) { + Some((va, slot, h)) => (Some(va), slot, h), + None => (None, 0, None), + }; + let (res_buf, res_va, region, records) = records_for(this, indirect_record_need_hint(record_bytes, tp.mesh_groups_per_record, hint), record_bytes, batch)?; + let cap = record_groups(region, record_bytes, tp.mesh_groups_per_record); + if cap == 0 { + return Err(format!("a record of {record_bytes} B does not fit the record buffer")); + } + let count = match (count_buf, count_at) { + (0, _) => None, + (_, Some(p)) => Some(p), + _ => return Err("its count is not in a console buffer in unified memory".into()), + }; + // the groups past the record buffer, and the commands past the count, are dropped + // on the GPU (`SCALE_ARGS_HLSL`) + let (scaled, at) = make_scaled_args_buffer(this, list, src, count, max, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record, cap, batch, fb_va, fb_slot)?; + if let Some(d) = &fb_dev { + if fb_slot != 0 { + let dk = d.as_raw() as usize; + with(this, |s| s.fb_uses.push((dk, fb_slot, cap))); + track_two_pass_list(this as usize); + } + } + let plan = two_pass_plan(max, records, with(this, |s| s.record_open)); + let passes = run_two_pass_plan(this, list, &plan, &res_buf, res_va, region, |k, compute, va| { + bind_two_pass_stage(this, list, pso, &tp, va, compute)?; + let (s, first) = if compute { (msig.companion_dispatch, at) } else { (sig, at + commands as u64) }; + pc(this, s, 1, scaled.as_raw() as usize, first + k as u64 * msig.byte_stride as u64, 0, 0); + Ok(()) + }); + // (with `batch` the block stays in INDIRECT_ARGUMENT for the next rewrite) + if !batch { + emit_transition(list, &scaled, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + } + passes + })(); + super::gpu_times::after(this); + match run { + Ok(()) => { + mesh_work(this, super::targets::RAN); + super::watch::note(raw_pso, super::watch::INDIRECT_MESH, [max, 0, 0]); + count(DRAWS); + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: two-pass ExecuteIndirect(DispatchMesh) #{n} (max {max}, split {}, kind {})", tp.mesh_groups_per_record, tp.kind); + } + } + Err(e) => { + mesh_work(this, super::targets::SKIPPED); + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: two-pass ExecuteIndirect skipped: {e}"); + } + } + } + return; } } - - #[test] - fn cross_thread_cache_rejects_a_reused_address() { - let key = Box::new(0u8); - let list = (&*key as *const u8) as usize; - reset(list as *mut c_void, 0, 0x7E57_D231); - let old = STATES.get(list).unwrap(); - let (ready_tx, ready_rx) = mpsc::channel(); - let (continue_tx, continue_rx) = mpsc::channel(); - let worker = std::thread::spawn(move || { - assert_eq!(with(list as *mut c_void, |state| state.pso), 0x7E57_D231); - ready_tx.send(()).unwrap(); - continue_rx.recv().unwrap(); - with(list as *mut c_void, |state| state.pso) - }); - ready_rx.recv_timeout(Duration::from_secs(1)).expect("cache worker did not warm its entry"); - forget(list as *mut c_void); - reset(list as *mut c_void, 0, 0x7E57_D232); - continue_tx.send(()).unwrap(); - assert_eq!(worker.join().unwrap(), 0x7E57_D232, "worker reused its orphaned cache entry"); - assert!(!old.live.load(Ordering::Acquire)); - forget(list as *mut c_void); + flush_two_pass(this, RunEnd::Draw); + let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); + if !gfx && !compute { + // (a pipeline still being built: skipped above, `DrawPipeline::StandIn`) + // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in + // TWO_PASS rather than TRANSLATED_GRAPHICS. Falling through to raw PC ExecuteIndirect + // with the title's graphics root signature (e.g. a non-DispatchMesh indirect draw or a + // root-changing signature) invalidates the command list (Close → E_INVALIDARG). + // (`DrawPipeline::TwoPass` above takes these; this catches one `draw_pipeline` did not + // see as two-pass.) + if let Some(tp) = super::real::two_pass_of_exact(pso) { + ei_work(this, dispatches, super::targets::SKIPPED); + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!( + "D3D12.X: ExecuteIndirect with two-pass {} pipeline ({pso:#x}) skipped – PC pipeline is a mesh shader", + tp.kind + ); + } + return; + } + // a console compute program without a translation (its build failed): nothing to run, + // as for Dispatch. The PC call would run it with the list's compute root signature, which + // can still be XCL's ABI one from a translated dispatch before it (debug layer 953). + // A native PC compute pipeline is not one of these and still goes to the PC call. + // (The retained bind says whether the title's object is console compute; without one, + // `CONSOLE_COMPUTE` holds the title's object, which for a shared stand-in differs from + // the driver pipeline the resolve returned.) + if dispatches && (retained_compute.unwrap_or_else(|| super::real::is_console_compute(raw_pso)) || super::real::is_console_compute(pso)) { + super::targets::note_dispatch(); + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect dispatch with a pipeline that has no translated console shader ({raw_pso:#x}) skipped"); + } + return; + } + // a PC pipeline: the title's root signature, as for a draw (`graphics_bound`) + // (a dispatch does not use it: it goes on without one) + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + if !bind_title_root_signature(this, list) && !dispatches { + note_no_root_signature(); + ei_work(this, dispatches, super::targets::SKIPPED); + count(DRAWS_SKIPPED); + return; + } + ei_work(this, dispatches, super::targets::PC); + let t = super::gpu_profile::begin(this, pso, super::gpu_profile::Kind::PcIndirect, [max, 0, 0]); + fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)); + super::gpu_profile::end(this, t); + return; } - - #[test] - fn cross_thread_cache_observes_reset_on_the_live_entry() { - let key = Box::new(0u8); - let list = (&*key as *const u8) as usize; - reset(list as *mut c_void, 0, 0x7E57_D241); - let (ready_tx, ready_rx) = mpsc::channel(); - let (continue_tx, continue_rx) = mpsc::channel(); - let worker = std::thread::spawn(move || { - assert_eq!(with(list as *mut c_void, |state| state.pso), 0x7E57_D241); - ready_tx.send(()).unwrap(); - continue_rx.recv().unwrap(); - with(list as *mut c_void, |state| state.pso) - }); - ready_rx.recv_timeout(Duration::from_secs(1)).expect("cache worker did not warm its entry"); - reset(list as *mut c_void, 0, 0x7E57_D242); - continue_tx.send(()).unwrap(); - assert_eq!(worker.join().unwrap(), 0x7E57_D242); - forget(list as *mut c_void); + if signature.root_changes() { + ei_work(this, dispatches, super::targets::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 that changes root arguments with a translated pipeline skipped"); + } + return; } - - /// A pipeline with the rect list GS draws its rect lists whole: draw_rects leaves them alone. - #[test] - fn rect_lists_with_the_rect_list_gs_are_not_expanded_on_the_cpu() { - let (with_gs, without) = (0x7E57_4000usize, 0x7E57_5000usize); - real::register_rect_list_gs_for_test(with_gs); - assert!(!cpu_rect_expansion(with_gs)); - assert!(cpu_rect_expansion(without) && cpu_rect_expansion(0)); - real::forget_pso_for_test(with_gs); - assert!(cpu_rect_expansion(with_gs)); + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + if !gfx && super::real::skip_named_cs(pso) { + return; } - - /// An ExecuteIndirect whose bound pipeline is still being built is skipped (its stand-in - /// with XCL's ABI root signature on the list is the debug layer's 953 and a hung GPU); - /// a built or failed one goes to the PC call. The gate `execute_indirect` uses. - #[test] - fn execute_indirect_with_a_pipeline_still_building_is_skipped() { - let (building, built, failed) = (0x7E57_6001usize, 0x7E57_6002usize, 0x7E57_6003usize); - // 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(failed, false, Box::new(|| 0), 0); - assert!(pso_async::is_pending(building)); - assert_eq!(pso_async::resolve_wait(built), 0x1235); - 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)); - pso_async::released(building); - pso_async::released(built); - pso_async::released(failed); - assert!(!pso_async::is_pending(building)); + // an indirect draw gets its frame trace line as a direct one (`graphics_bound`), marked + if gfx && super::present::trace_frame() { + trace_ui_draw(this, raw_pso, pso, true); } - - /// A dispatch writes an ExecuteIndirect's group count through another buffer over the same - /// memory (as translated shaders write through the memory windows), a UAV barrier (what a - /// console barrier becomes), then the ExecuteIndirect: it runs the count just written, not - /// the one the memory held before the list (`fresh_indirect_arguments`; without it an RTX - /// 5090 ran the old count in nearly every try). - #[test] - fn execute_indirect_reads_the_arguments_written_before_it() { - use crate::gpu::{fence, recomp::runner::skip_test}; - use std::mem::{transmute_copy, ManuallyDrop}; - use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; - use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; - use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, IDXGIAdapter1, IDXGIFactory6, DXGI_CREATE_FACTORY_FLAGS}; - - const TRIES: u32 = 40; - // mode 0: write (x, 1, 1) at a[0..12]; mode 1: count the groups - let src = r#" -#define RS "RootConstants(num32BitConstants=2, b0), UAV(u0), UAV(u1)" -cbuffer C : register(b0) { uint mode; uint x; }; -RWByteAddressBuffer a : register(u0); -RWByteAddressBuffer c : register(u1); -[RootSignature(RS)] -[numthreads(64, 1, 1)] -void main(uint t : SV_GroupIndex) { - if (t != 0u) return; - if (mode == 0u) a.Store3(0, uint3(x, 1u, 1u)); else c.InterlockedAdd(0, 1u); -} -"#; - if crate::gpu::recomp::dxc::location().is_err() { - skip_test("no DXC"); - return; + // a split compute program's one Dispatch-only command runs its chain (`dispatch_chain`) + if compute && max == 1 && count_buf == 0 && signature.dispatch_only().is_some() { + let chained = indirect_address(args, args_off_title, args_off).map_or(Ok(false), |address| { + super::real::dispatch_chain::execute_indirect(list, raw_pso, pso, with(this, |s| s.allocator), address, + |root| bind_abi_with_root_resolved(this, list, raw_pso, pso, false, root, [0; 3], None, 0).map(|_| ())) + }); + match chained { + Ok(true) => { + ei_work(this, dispatches, super::targets::RAN); + count(DISPATCHES); + return; + } + Ok(false) => {} + Err(e) => { + ei_work(this, dispatches, super::targets::SKIPPED); + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: split ExecuteIndirect skipped: {e}"); + } + return; + } } - unsafe { - let setup = || -> Result<(ID3D12Device, String), String> { - let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| format!("DXGI factory unavailable: {e}"))?; - let sel = crate::gpu::adapter::Selector::from_env_or("auto"); - let (adapter, name): (IDXGIAdapter1, String) = if sel == crate::gpu::adapter::Selector::Warp { - (factory.EnumWarpAdapter().map_err(|e| format!("WARP unavailable: {e}"))?, "WARP (software renderer)".into()) - } else { - let (adapter, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next() - .ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; - (adapter, crate::gpu::adapter::name(&desc)) - }; - let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_11_0).map_err(|e| format!("{name}: D3D12 device unavailable ({e})"))?; - let mut sm = D3D12_FEATURE_DATA_SHADER_MODEL { HighestShaderModel: D3D_SHADER_MODEL_6_6 }; - dev.CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &mut sm as *mut _ as _, std::mem::size_of_val(&sm) as u32) - .map_err(|e| format!("{name}: cannot query SM 6.6 ({e})"))?; - if sm.HighestShaderModel.0 < D3D_SHADER_MODEL_6_6.0 { - return Err(crate::gpu::agility::format_no_sm66_message(&name, crate::gpu::agility::state())); + } + // (binds a compute root signature and a pipeline: before the dispatch's or draw's own) + let checked = super::indirect_guard::check(this, pso, sig, max, args, args_off, count_buf); + match bind_abi_resolved(this, list, raw_pso, pso, gfx) { + Ok(b) => { + let mut whole = None; + if compute { + // a wave-local remapped program runs its whole form: the GPU's group counts + // cannot be scaled + if super::real::pso_dispatch_remap_exact(pso).is_some() { + match super::real::remap_fallback::whole_exact(pso) { + Ok(fallback) => whole = Some(fallback), + Err(e) => { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect remap fallback skipped: {e}"); + } + ei_work(this, dispatches, super::targets::SKIPPED); + count(DISPATCHES_SKIPPED); + return; + } + } } - Ok((dev, name)) - }; - let (dev, name) = match setup() { - Ok(selected) => selected, - Err(reason) => { skip_test(&reason); return; } - }; - println!("ExecuteIndirect adapter: {name}"); - let dxil = crate::gpu::recomp::dxc::compile(src, "main", "cs_6_6", &[]).unwrap(); - let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap(); - let cs = D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }; - let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: cs, ..Default::default() }).unwrap(); - let arg = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }; - let mut sig: Option = None; - dev.CreateCommandSignature(&D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 12, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 }, None, &mut sig).unwrap(); - let sig = sig.unwrap(); - let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; - let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); - let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); - let desc = |width| D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: width, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, - ..Default::default() - }; - // the arguments and the buffer the dispatch writes them through: one memory - let mut heap: Option = None; - let heap_desc = D3D12_HEAP_DESC { SizeInBytes: 1 << 16, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }; - dev.CreateHeap(&heap_desc, &mut heap).unwrap(); - let heap = heap.unwrap(); - let placed = || { - let mut r: Option = None; - dev.CreatePlacedResource(&heap, 0, &desc(1 << 16), D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); - r.unwrap() - }; - let (args, written) = (placed(), placed()); - // the group count, read on the CPU - let cpu_heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; - let mut groups: Option = None; - dev.CreateCommittedResource(&cpu_heap, D3D12_HEAP_FLAG_NONE, &desc(256), D3D12_RESOURCE_STATE_COMMON, None, &mut groups).unwrap(); - let groups = groups.unwrap(); - let mut count = std::ptr::null_mut(); - groups.Map(0, None, Some(&mut count)).unwrap(); - let count = count as *mut u32; - let uav_barrier = D3D12_RESOURCE_BARRIER { - Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, - Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, - Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: ManuallyDrop::new(None) }) }, - }; - let run = |list: &ID3D12GraphicsCommandList, close: &dyn Fn()| { - close(); - queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); - let v = done.GetCompletedValue() + 1; - queue.Signal(&done, v).unwrap(); - fence::wait(&done, v, &dev, None, 10_000).unwrap(); - }; - let (mut old, mut wrong) = (0u32, Vec::new()); - for k in 0..TRIES { - // each try writes a count the memory does not hold yet - let new = if k % 2 == 0 { 4096 } else { 0 }; - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); - let record = |x: u32| -> ID3D12GraphicsCommandList { - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, &pso).unwrap(); - list.SetComputeRootSignature(&rs); - list.SetComputeRootUnorderedAccessView(1, written.GetGPUVirtualAddress()); - list.SetComputeRootUnorderedAccessView(2, groups.GetGPUVirtualAddress()); - list.SetComputeRoot32BitConstants(0, 2, [0u32, x].as_ptr() as _, 0); - list.Dispatch(1, 1, 1); - list - }; - let before = record(old); - run(&before, &|| before.Close().unwrap()); - alloc.Reset().unwrap(); - *count = 0; - let list = record(new); - list.ResourceBarrier(&[uav_barrier.clone()]); - list.SetComputeRoot32BitConstants(0, 2, [1u32, 0].as_ptr() as _, 0); - // from here as XCL records a title's ExecuteIndirect: on the adopted list - let raw = list.as_raw(); - real::adopt(raw, real::Kind::CommandList); - list_x::on_create(raw, alloc.as_raw() as usize, 0, ty); - type Ei = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); - type Close = unsafe extern "system" fn(*mut c_void) -> windows::core::HRESULT; - let ei: Ei = std::mem::transmute(real::orig_fn(raw, 59)); - fresh_indirect_arguments(raw, || ei(raw, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0, 0)); - let close: Close = std::mem::transmute(real::orig_fn(raw, 9)); - run(&list, &|| close(raw).unwrap()); - let ran = std::ptr::read_volatile(count); - if ran != new { - wrong.push((k, ran)); + match super::real::dispatch_chain::whole_ready(pso) { + Ok(super::real::dispatch_chain::Whole::Plain) => {} + Ok(super::real::dispatch_chain::Whole::Ready(w)) => whole = Some(w), + Ok(super::real::dispatch_chain::Whole::Late) => { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_warn!("D3D12.X: ExecuteIndirect of a split compute program whose whole form is still being built skipped ({n} so far)"); + } + ei_work(this, dispatches, super::targets::SKIPPED); + count(DISPATCHES_SKIPPED); + return; + } + Err(e) => { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO: {e}"); + } + ei_work(this, dispatches, super::targets::SKIPPED); + count(DISPATCHES_SKIPPED); + return; + } } - old = new; } - groups.Unmap(0, None); - assert!(wrong.is_empty(), "{} of {TRIES} ExecuteIndirects ran another group count than the one written before them (try, groups): {wrong:?}", wrong.len()); + // one dispatch: its group counts (as the guard let them through) folded or clamped on + // the GPU (`clamp`, which writes a folded count into this dispatch's io), then the + // binding set again. Only on a direct or compute list XCL keeps state for, as + // `indirect_guard`: the pass records barriers, which a bundle cannot hold + let mut clamped = None; + let barriers = matches!(super::list_x::tracked_list_type(this), Some(t) if t == D3D12_COMMAND_LIST_TYPE_DIRECT || t == D3D12_COMMAND_LIST_TYPE_COMPUTE); + if compute && max == 1 && dispatches && barriers { + let (from, at) = checked.as_ref().map_or((args, args_off), |c| c.arguments()); + clamped = super::clamp::before(list, from, at, b.io + 4 * crate::gpu::recomp::IO_GROUP_LIMIT as u64); + if clamped.is_some() { + rebind(this, list, &b, false); + } + } + if let Some(whole) = &whole { + super::real::bind_pipeline_exact(this, raw_pso, whole.as_raw() as usize); + } + ei_work(this, dispatches, super::targets::RAN); + count(if gfx { DRAWS } else { DISPATCHES }); + let t = super::gpu_profile::begin(this, pso, if gfx { super::gpu_profile::Kind::IndirectDraw } else { super::gpu_profile::Kind::IndirectDispatch }, [max, 0, 0]); + match (&checked, clamped) { + (_, Some((from, at))) => { + if let Some(c) = &checked { + super::gpu_profile::note_counts(&t, c.slot); + // (`clamp` read the checked counts there) + c.read(this); + } + fresh_indirect_arguments(this, || pc(this, sig, max, from, at, count_buf, count_off)); + super::clamp::done(list); + } + (Some(c), None) => { + super::gpu_profile::note_counts(&t, c.slot); + c.run(this, |buffer, off| pc(this, sig, 1, buffer, off, 0, 0)); + } + (None, None) => fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)), + } + super::gpu_profile::end(this, t); } + Err(e) => { + ei_work(this, dispatches, super::targets::SKIPPED); + count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect with a translated pipeline skipped: {e}"); + } + } + } +} + +/// `XCL_DUMP_TARGETS`: an ExecuteIndirect with `outcome` (a dispatch signature's: a dispatch) +unsafe fn ei_work(this: *mut c_void, dispatches: bool, outcome: usize) { + if !super::targets::enabled() { + return; + } + if dispatches { + super::targets::note_dispatch(); + } else { + super::targets::note_draw(this, outcome); } +} - /// Minimal RTS0 v2 root signature blob with one 4-constant parameter. - fn test_rts0_blob() -> Vec { - let words: [u32; 12] = [ - 2, 1, 24, 0, 0, 0, // version=2, num_params=1, params_offset=24 - 1, 0, 36, // param 0: type=Constants(1), visibility=0, payload_offset=36 - 0, 0, 4, // shader_reg=0, reg_space=0, num_32bit_values=4 - ]; - words.iter().flat_map(|w| w.to_le_bytes()).collect() +fn count_indirect_skip(dispatches: bool) { + count(if dispatches { DISPATCHES_SKIPPED } else { DRAWS_SKIPPED }); + #[cfg(test)] + INDIRECT_SKIP_COUNTS.with(|counts| { + let mut next = counts.get(); + next[dispatches as usize] += 1; + counts.set(next); + }); +} + +#[cfg(test)] +thread_local! { + static INDIRECT_SKIP_COUNTS: std::cell::Cell<[u32; 2]> = const { std::cell::Cell::new([0; 2]) }; +} + +#[cfg(test)] +fn take_indirect_skip_counts() -> [u32; 2] { + INDIRECT_SKIP_COUNTS.with(|counts| counts.replace([0; 2])) +} + +unsafe fn indirect_address(resource: usize, title_offset: u64, pc_offset: u64) -> Option { + match super::real::console_buffer(resource) { + Some((base, size)) if title_offset.checked_add(12).is_some_and(|end| end <= size as u64) => { + super::real::uma_va_of(base + title_offset as usize) + } + Some(_) => None, + None => Some(ID3D12Resource::from_raw_borrowed(&(resource as *mut c_void))?.GetGPUVirtualAddress()) + .filter(|&address| address != 0).and_then(|address| address.checked_add(pc_offset)), + } +} + +/// XCL's own buffer for `fresh_indirect_arguments` (device, buffer): COMMON between its uses +static ARGUMENT_ORDER: Mutex> = Mutex::new(None); + +/// `op` (an ExecuteIndirect on `list`) reading the arguments and count the list wrote before it. +/// +/// The console orders a dispatch that writes indirect arguments before the ExecuteIndirect that +/// reads them with a barrier that reaches the PC as a UAV barrier (`list_x::resource_barrier_x`). +/// NVIDIA's driver (RTX 5090) fetches an ExecuteIndirect's arguments without waiting for that +/// barrier: it ran the count that was there before the list in all but a few of 100 tries, also +/// when the dispatch wrote them through another resource over the same memory, as translated +/// shaders do through the memory window buffers (`execute_indirect_reads_the_arguments_written_before_it`). +/// A retail title's ExecuteIndirect after the dispatch that writes its group count then runs +/// whatever count the memory held before. A transition to INDIRECT_ARGUMENT makes the driver +/// wait for the writes – of any buffer, as measured there. The title's buffer is in the title's +/// state (its transitions reach the PC list), so a buffer of XCL's own takes it, COMMON -> +/// INDIRECT_ARGUMENT before and back after. Only on a list XCL made (`list_x::on_create`) and +/// not a bundle, which cannot hold barriers; its type comes from XCL's state, not a call to it. +unsafe fn fresh_indirect_arguments(list: *mut c_void, op: impl FnOnce()) { + let tracked = super::list_x::tracked_list_type(list).is_some_and(|t| t != D3D12_COMMAND_LIST_TYPE_BUNDLE); + let buffer = if tracked { ID3D12GraphicsCommandList::from_raw_borrowed(&list).and_then(|l| argument_order_buffer(l)) } else { None }; + let Some(buffer) = buffer else { return op() }; + let b = buffer.as_raw() as usize; + super::list_x::transition(list, b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + op(); + super::list_x::transition(list, b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); +} + +/// The device's buffer for `fresh_indirect_arguments` (made on first use) +unsafe fn argument_order_buffer(list: &ID3D12GraphicsCommandList) -> Option { + let mut dev: Option = None; + list.GetDevice(&mut dev).ok()?; + let dev = dev?; + let mut g = ARGUMENT_ORDER.lock().unwrap(); + if let Some((_, b)) = g.as_ref().filter(|(d, _)| *d == dev.as_raw() as usize) { + return Some(b.clone()); + } + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut b: Option = None; + if let Err(e) = dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut b) { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect: no buffer to order its arguments after the writes before it ({e}) – it may read old ones"); + } + return None; + } + let b = b?; + *g = Some((dev.as_raw() as usize, b.clone())); + Some(b) +} + +/// A DrawInstanced of the console's rect list (three corners of each rectangle, the fourth +/// implied) as two triangles a rectangle; false: not a rect list, or one this cannot expand +/// (the caller draws the three vertices as a triangle – half of each rectangle). +/// +/// The PC has no rect lists. The fourth corner is made here, on the CPU, from the title's +/// vertex data: v3 = v0 + v2 − v1 (seen in a retail title's full-screen passes: (−1,1) (−1,−1) +/// (1,−1) with texture coordinates (0,0) (0,1) (1,1) – the missing corner is (1,1), (1,0)). +/// The vertex layout is not looked at: each 4-byte word that is the same in all three vertices +/// is kept (a packed colour), any other is taken as a float. Vertices a shader makes from the +/// vertex index alone (no vertex buffer) are not expanded. +unsafe fn draw_rects(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) -> bool { + if !cpu_rect_expansion(pso) { + return false; + } + let Some(vbs) = super::list_x::rect_list_state(this) else { return false }; + let rects = (vertices / 3) as usize; + if vbs.is_empty() || rects == 0 || rects > 4096 { + return false; + } + let mut views = Vec::new(); + for &(slot, (va, bytes, stride), _) in &vbs { + let (s, start) = (stride as usize, va as usize + first_vertex as usize * stride as usize); + let len = rects * 3 * s; + // (a buffer in a GPU view is read where the CPU has it, its CPU view: the range of the + // vertices, which must be one piece there) + let at = if in_views(va) { + let Some(c) = super::view_want::cpu_run(start as u64, len as u64) else { return false }; + c as usize + } else { + start + }; + if va == 0 || s == 0 || s % 4 != 0 || first_vertex as usize * s + len > bytes as usize || !crate::gpu::shader::readable(at, len) { + return false; + } + let p = allocate_upload_memory(this, rects * 6 * s, 16); + if p.is_null() { + return false; + } + let word = |v: usize, w: usize| (at as *const u8).add(v * s + w * 4).cast::().read_unaligned(); + for r in 0..rects { + let out = p.add(r * 6 * s); + let src = (at as *const u8).add(r * 3 * s); + // v0 v1 v2, then v0 v2 v3 + std::ptr::copy_nonoverlapping(src, out, 3 * s); + std::ptr::copy_nonoverlapping(src, out.add(3 * s), s); + std::ptr::copy_nonoverlapping(src.add(2 * s), out.add(4 * s), s); + for w in 0..s / 4 { + let (a, b, c) = (word(r * 3, w), word(r * 3 + 1, w), word(r * 3 + 2, w)); + let d = if a == b && b == c { a } else { (f32::from_bits(a) + f32::from_bits(c) - f32::from_bits(b)).to_bits() }; + out.add(5 * s + w * 4).cast::().write_unaligned(d); + } + } + views.push((slot, D3D12_VERTEX_BUFFER_VIEW { BufferLocation: super::list_x::pc_va_of(p as u64), SizeInBytes: (rects * 6 * s) as u32, StrideInBytes: stride })); + } + for (slot, v) in &views { + list.IASetVertexBuffers(*slot, Some(&[*v])); + } + list.DrawInstanced(rects as u32 * 6, instances, 0, first_instance); + for &(slot, _, pc) in &vbs { + if let Some(v) = pc { + list.IASetVertexBuffers(slot, Some(&[v])); + } + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_info!("D3D12.X: rect lists are drawn as two triangles a rectangle, the fourth corner made on the CPU"); + } + true +} + +/// Whether a rect list drawn with the bound pipeline `pso` is expanded on the CPU (`draw_rects`): +/// not with the rect list GS (`real::has_rect_list_gs`), which completes each rect itself – both +/// would draw every rect twice (each CPU half is three corners of the rect). +fn cpu_rect_expansion(pso: usize) -> bool { + !super::real::has_rect_list_gs(pso) +} + +/// #12 DrawInstanced +pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDraw); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::DrawRecord); + let _c = capture_work(this, || super::capture::WorkKind::Draw { vertices, instances, first_vertex, first_instance }, true); + DRAW_ARGS.with(|d| d.set((false, vertices, instances, first_vertex, 0))); + if let Some((list, pso)) = graphics_bound(this) { + let t = super::gpu_profile::begin(this, with(this, |s| s.pso), super::gpu_profile::Kind::Draw, [vertices, instances, 0]); + if !draw_rects(this, &list, pso, vertices, instances, first_vertex, first_instance) { + super::list_x::sync_title_buffers(this, None, first_vertex, vertices, if first_instance != 0 { instances.max(2) } else { instances }); + list.DrawInstanced(vertices, instances, first_vertex, first_instance); + } + super::gpu_profile::end(this, t); + } +} + +thread_local! { + /// the draw being bound: (indexed, count, instances, first index / vertex, base vertex) – for the frame trace + static DRAW_ARGS: std::cell::Cell<(bool, u32, u32, u32, i32)> = const { std::cell::Cell::new((false, 0, 0, 0, 0)) }; +} + +#[cfg(test)] +static LAST_ABI_PSO: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +#[cfg(test)] +static STOP_ABI_LIST: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +#[cfg(test)] +static STOP_ABI_AFTER_BIND_LIST: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +#[cfg(test)] +static STOP_ABI_TEST: Mutex<()> = Mutex::new(()); + +/// #13 DrawIndexedInstanced +pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDraw); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::DrawRecord); + let _c = capture_work(this, || super::capture::WorkKind::DrawIndexed { indices, instances, first_index, base_vertex, first_instance }, true); + if let Some(list) = prepare_indexed_draw(this, indices, instances, first_index, base_vertex) { + super::list_x::sync_title_buffers(this, Some((first_index, indices, base_vertex)), 0, 0, if first_instance != 0 { instances.max(2) } else { instances }); + emit_prepared_indexed_draw(&list, indices, instances, first_index, base_vertex, first_instance); + } +} + +/// Prepare an indexed draw once, before callers make temporary native state changes. +pub(super) unsafe fn prepare_indexed_draw( + this: *mut c_void, + indices: u32, + instances: u32, + first_index: u32, + base_vertex: i32, +) -> Option { + DRAW_ARGS.with(|d| d.set((true, indices, instances, first_index, base_vertex))); + graphics_bound(this).map(|(list, _)| list) +} + +/// Submit an indexed draw whose translated graphics state has already been prepared. +pub(super) unsafe fn emit_prepared_indexed_draw( + list: &ID3D12GraphicsCommandList, + indices: u32, + instances: u32, + first_index: u32, + base_vertex: i32, + first_instance: u32, +) { + let this = list.as_raw(); + let t = super::gpu_profile::begin(this, with(this, |s| s.pso), super::gpu_profile::Kind::Draw, [indices, instances, 0]); + list.DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance); + super::gpu_profile::end(this, t); +} + +/// Resolve one retained bind for correctness-critical draw or dispatch emission and record its +/// exact generation before native commands can consume it. None is fail-closed. +fn resolve_pipeline( + list: usize, + pso: usize, + resolution: Option, +) -> Option { + match resolution.map(|resolution| resolution.resolve_for_emission()) { + Some(super::pso_async::PipelineChoice::Available { raw, generation }) => { + super::list_x::record_native_generation(list, Some(generation)); + Some(raw) + } + Some(super::pso_async::PipelineChoice::Unavailable) => None, + None => Some(pso), + } +} + +fn resolve_bound_graphics_pipeline(this: *mut c_void, list: usize) -> Option<(usize, usize)> { + let (pso, resolution) = with(this, |s| (s.pso, s.resolution.clone())); + resolve_pipeline(list, pso, resolution).map(|real| (pso, real)) +} + +unsafe fn graphics_bound(this: *mut c_void) -> Option<(ID3D12GraphicsCommandList, usize)> { + let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); + let Some((pso, real)) = resolve_bound_graphics_pipeline(this, list.as_raw() as usize) else { + super::list_x::note_dropped_draw(this); + count(DRAWS_SKIPPED); + return None; + }; + if !super::real::is_translated_graphics(real) { + // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in + // TWO_PASS rather than TRANSLATED_GRAPHICS. Binding the title's graphics RS and issuing + // DrawInstanced / DrawIndexedInstanced against a mesh PSO invalidates the command list + // (Close → E_INVALIDARG). It draws only through DispatchMesh. + if let Some(tp) = super::real::two_pass_of_exact(real) { + super::targets::note_draw(this, super::targets::SKIPPED); + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!( + "D3D12.X: draw with two-pass {} pipeline ({real:#x}) skipped – PC pipeline is a mesh shader", + tp.kind + ); + } + return None; + } + if super::targets::enabled() { + super::targets::note_draw(this, if super::pso_async::is_pending(pso) { super::targets::STANDIN } else { super::targets::PC }); + } + count(DRAWS_PC); + if super::present::trace_frame() { + // which pipelines draw without a translation (first 12 distinct) + static SEEN: Mutex> = Mutex::new(Vec::new()); + let mut g = SEEN.lock().unwrap(); + if !g.contains(&pso) && g.len() < 12 { + g.push(pso); + crate::xlog_info!( + "frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {real:#x}; pending {}, two-pass {}, RT0 {:?})", + super::pso_async::is_pending(pso), + super::real::two_pass_of_exact(real).is_some(), + super::present::rt0_resource(this as usize).map(|r| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0) })) + ); + } + } + // a pending stand-in draws nothing: an occlusion query around it resolves as visible + if super::pso_async::is_pending(pso) { + super::list_x::note_dropped_draw(this); + } + // a PC pipeline (also a stand-in or fallback): the title's root signature + if !bind_title_root_signature(this, &list) { + note_no_root_signature(); + return None; + } + return Some((list, real)); + } + if super::present::trace_frame() { + trace_ui_draw(this, pso, real, false); + } + match bind_abi_resolved(this, &list, pso, real, true) { + Ok(_) => { + super::targets::note_draw(this, super::targets::RAN); + count(DRAWS); + Some((list, real)) + } + Err(e) => { + super::targets::note_draw(this, super::targets::SKIPPED); + super::list_x::note_dropped_draw(this); + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: draw with a translated pipeline skipped: {e}"); + } + None + } + } +} + +/// `XCL_TRACE_FRAME`: draws into a presented buffer (the UI) once the title has presented for a +/// while – their pipeline, root arguments and the resources their descriptor tables start with +/// (format, size, kept in step with title memory or not). The first 24. +/// `XCL_TRACE_FRAME`, after 300 presents: one line per distinct (VS, PS, render target) drawn – +/// the shaders' dump hashes, the target and the textures of the first descriptor table. +/// ExecuteIndirect draws (`indirect`) are kinds of their own, marked. +unsafe fn trace_draw_kinds(this: *mut c_void, pso: usize, indirect: bool) { + // keyed by the target's shape, not the object: a UI library's transient targets (Renoir's + // layers) are new objects every frame and would fill the list at once + static SEEN: Mutex, bool)>> = Mutex::new(Vec::new()); + if super::present::activity().0 < 300 { + return; + } + let Some((vs, ps)) = super::real::pso_shaders(pso) else { return }; + let rt = super::present::rt0_resource(this as usize).unwrap_or(0); + let desc = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0, d.SampleDesc.Count) }); + // `XCL_TRACE_FORMATS=26,29` (DXGI format numbers): only draws into targets of those formats – + // the first 160 kinds of a busy frame are its first passes, and the ones looked for (a + // lighting target's) never got a line + let formats = trace_formats(); + // (`XCL_TRACE_DSV_FORMATS`: or draws whose depth buffer, at least 2560 wide, has one of those + // PC formats – the passes that write or test a depth buffer and draw into no target of the + // formats above; known while `XCL_DUMP_TARGETS` keeps what a DSV names) + let depth_wanted = || { + let dsv = trace_dsv_formats(); + !dsv.is_empty() + && super::list_x::bound_dsv(this).and_then(super::present::rtv_resource).and_then(desc).is_some_and(|d| d.0 >= 2560 && dsv.contains(&d.2)) + }; + if !formats.is_empty() && !desc(rt).is_some_and(|d| formats.contains(&d.2)) && !depth_wanted() { + return; + } + // `XCL_TRACE_AFTER_S=110`: no kind is listed before that many seconds of the run (a title's + // menus fill the list long before its world draws), and each kind listed then also gets its + // root arguments: constants, the first words of root buffers, the first slots of its tables + // with what the GPU holds of the title textures there (`root_args_summary`) + static AFTER: std::sync::OnceLock> = std::sync::OnceLock::new(); + let after = *AFTER.get_or_init(|| std::env::var("XCL_TRACE_AFTER_S").ok().and_then(|v| v.trim().parse().ok())); + if after.is_some_and(|s| crate::log::uptime() < s) { + return; + } + { + let mut g = SEEN.lock().unwrap(); + let key = (vs, ps, desc(rt), indirect); + if g.len() >= 160 || g.contains(&key) { + return; + } + g.push(key); + } + let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); + let mut tex = Vec::new(); + if let (Some(layout), Some(u)) = (layout, crate::gpu::uma::get()) { + for p in layout.params.iter() { + if let Param::Table { at } = *p { + let t = word(at as usize) as usize; + for k in 0..4usize { + if let Some(r) = super::console_heap::resource_at(u.base() + t + 32 * k) { + tex.push(format!("{:?}{}", desc(r), super::title_textures::address(r).map_or(String::new(), |a| format!(" at {a:#x}")))); + } + } + } + if tex.len() >= 4 { + break; + } + } + } + crate::xlog_info!( + "frame trace: draws vs {vs:016x} ps {ps:016x} into {:?}{}{} – textures {}; {}", + desc(rt), + if super::present::is_presented(rt) { " (presented)" } else { "" }, + if indirect { " (ExecuteIndirect)" } else { "" }, + tex.join(", "), + super::list_x::state_summary(this) + ); + if after.is_some() { + crate::xlog_info!("frame trace: … its root arguments: {}", root_args_summary(this, 8)); + // and, once, what the view heaps hold at that point of the run + static CENSUS: std::sync::Once = std::sync::Once::new(); + CENSUS.call_once(super::console_heap::census); + } +} + +/// `XCL_TRACE_FORMATS=26,29` (DXGI format numbers): the render target formats the frame trace +/// keeps to – the kinds of draws it lists, and the pipelines whose state it logs. Empty: all. +pub(super) fn trace_formats() -> &'static [i32] { + static FORMATS: std::sync::OnceLock> = std::sync::OnceLock::new(); + FORMATS.get_or_init(|| std::env::var("XCL_TRACE_FORMATS").unwrap_or_default().split(',').filter_map(|f| f.trim().parse().ok()).collect()) +} + +/// `XCL_TRACE_DSV_FORMATS=53,55` (DXGI format numbers): depth buffer formats the frame trace +/// also keeps to – draws whose bound depth buffer has one of them as its PC format (53: a D16 +/// buffer), and pipelines whose DSV format is one of them (55). Empty: none. +pub(super) fn trace_dsv_formats() -> &'static [i32] { + static FORMATS: std::sync::OnceLock> = std::sync::OnceLock::new(); + FORMATS.get_or_init(|| std::env::var("XCL_TRACE_DSV_FORMATS").unwrap_or_default().split(',').filter_map(|f| f.trim().parse().ok()).collect()) +} + +/// `XCL_TRACE_SHADERS=hash,…` (dump hashes, hex): the draws traced with their root arguments +/// are those whose vertex or pixel shader is listed – into any target, at any time (the first +/// 24); without it, draws into a presented target (or any – `XCL_TRACE_UI_ANY`) after 300 +/// presents. +fn traced_shaders() -> &'static [u64] { + static S: std::sync::OnceLock> = std::sync::OnceLock::new(); + S.get_or_init(|| std::env::var("XCL_TRACE_SHADERS").unwrap_or_default().split(',').filter_map(|h| u64::from_str_radix(h.trim(), 16).ok()).collect()) +} + +/// `XCL_TRACE_FRAME` with a watched target (`present::watch_rt`): draws whose descriptor +/// tables name it – that object, or another at its title address (the first 16). An +/// ExecuteIndirect draw (`indirect`) has no arguments XCL reads: no line of them. +unsafe fn trace_reads_of_watched(this: *mut c_void, pso: usize, indirect: bool) { + let Some(w) = super::present::watched_rt() else { return }; + let w_addr = super::real::title_address(w).or_else(|| super::title_textures::address(w)); + let Some(u) = crate::gpu::uma::get() else { return }; + let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); + let Some(layout) = layout else { return }; + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); + for p in layout.params.iter() { + let Param::Table { at } = *p else { continue }; + let t = word(at as usize) as usize; + for k in 0..16usize { + let Some(r) = super::console_heap::resource_at(u.base() + t + 32 * k) else { continue }; + let addr = super::real::title_address(r).or_else(|| super::title_textures::address(r)); + if super::present::is_watched(r) || (addr.is_some() && addr == w_addr) { + let rt = super::present::rt0_resource(this as usize).unwrap_or(0); + // each (source, target, shaders) once + static SEEN: Mutex> = Mutex::new(Vec::new()); + { + let mut g = SEEN.lock().unwrap(); + if g.len() >= 32 || g.contains(&(r, rt, pso)) { + return; + } + g.push((r, rt, pso)); + } + if !super::present::is_presented(rt) { + super::present::follow(rt); + } + if let Some(dsv) = super::list_x::bound_dsv(this) { + super::list_x::watch_dsv(dsv); + } + let d = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0, d.Flags.0) }); + crate::xlog_info!( + "frame trace: a draw (shaders {:x?}, {}) reads a watched target {r:#x} {:?} at {addr:x?} (slot {k}), drawing into {rt:#x} {:?}{} – {}", + super::real::pso_shaders(pso), + super::list_x::state_summary(this), + d(r), + d(rt), + if super::present::is_presented(rt) { " (presented)" } else { "" }, + root_args_summary(this, 32) + ); + if indirect { + return; + } + let args = DRAW_ARGS.with(|d| d.get()); + crate::xlog_info!( + "frame trace: … that draw: {args:?} (indexed, count, instances, first, base vertex); input layout [{}]; {}", + super::real::pso_layout(pso).unwrap_or_default(), + super::list_x::geometry_summary(this, args) + ); + return; + } + } + } +} + +/// `XCL_TRACE_FRAME`: render targets a draw into the watched target samples (a UI library's +/// layers) are dumped with it (`present::follow`). +unsafe fn follow_layer_sources(this: *mut c_void) { + let (Some(w), Some(rt)) = (super::present::watched_rt(), super::present::rt0_resource(this as usize)) else { return }; + if rt != w { + return; + } + let Some(u) = crate::gpu::uma::get() else { return }; + let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); + let Some(layout) = layout else { return }; + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); + for p in layout.params.iter() { + let Param::Table { at } = *p else { continue }; + let t = word(at as usize) as usize; + for k in 0..4usize { + let Some(r) = super::console_heap::resource_at(u.base() + t + 32 * k) else { continue }; + let layer = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).is_some_and(|x| { + let d = x.GetDesc(); + d.Flags.0 & 1 != 0 && d.Width >= 64 && d.Height >= 32 && d.SampleDesc.Count == 1 + }); + if layer && r != w { + super::present::follow(r); + } + } + } +} + +/// `original`: the pipeline the title bound; `pso`: what it resolved to. `indirect`: an +/// ExecuteIndirect draw, whose arguments are in GPU memory (`DRAW_ARGS` holds the last direct +/// draw's). +unsafe fn trace_ui_draw(this: *mut c_void, original: usize, pso: usize, indirect: bool) { + trace_draw_kinds(this, pso, indirect); + trace_reads_of_watched(this, pso, indirect); + follow_layer_sources(this); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + // `XCL_TRACE_MANY=n`: n draws instead of 24 (a whole frame of a UI) + static CAP: std::sync::OnceLock = std::sync::OnceLock::new(); + let cap = *CAP.get_or_init(|| std::env::var("XCL_TRACE_MANY").ok().and_then(|v| v.parse().ok()).unwrap_or(24)); + if N.load(std::sync::atomic::Ordering::Relaxed) >= cap { + return; + } + let Some(rt) = super::present::rt0_resource(this as usize) else { return }; + let wanted = traced_shaders(); + if wanted.is_empty() { + // draws into a presented target, or – `XCL_TRACE_UI_ANY` – into any target + if super::present::activity().0 < 300 || (!super::present::is_presented(rt) && std::env::var_os("XCL_TRACE_UI_ANY").is_none()) { + return; + } + } else if !super::real::pso_shaders(pso).is_some_and(|(v, p)| wanted.contains(&v) || wanted.contains(&p)) { + return; + } else { + super::present::watch_rt(rt); + } + N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let sh = super::real::pso_shaders(pso).map(|(v, p)| format!("vs {v:016x} ps {p:016x}")); + crate::xlog_info!("frame trace: UI draw (pipeline {original:#x}, {}{}): {}", sh.unwrap_or_default(), if indirect { ", ExecuteIndirect" } else { "" }, root_args_summary(this, 16)); + if !wanted.is_empty() && !indirect { + // the picked shaders' geometry too (vertices dumped at the next present) + let args = DRAW_ARGS.with(|d| d.get()); + crate::xlog_info!( + "frame trace: … that draw: {args:?} (indexed, count, instances, first, base vertex); input layout [{}]; {}", + super::real::pso_layout(pso).unwrap_or_default(), + super::list_x::geometry_summary(this, args) + ); + } +} + +/// A draw's root arguments for the frame trace: constants, root buffers (their first words, as +/// the CPU sees them), the first slots of descriptor tables (the PC resources they name). +unsafe fn root_args_summary(this: *mut c_void, buffer_words: usize) -> String { + let Some(u) = crate::gpu::uma::get() else { return String::new() }; + let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); + let Some(layout) = layout else { return String::new() }; + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); + // `XCL_TRACE_SLOTS=n`: the first n slots of each table instead of 4, with all eight words + // of their image descriptors (a view's levels and its smallest level of detail are in the + // later ones) + static SLOTS: std::sync::OnceLock> = std::sync::OnceLock::new(); + let more = *SLOTS.get_or_init(|| std::env::var("XCL_TRACE_SLOTS").ok().and_then(|v| v.trim().parse().ok())); + let (slots, words) = (more.unwrap_or(4).clamp(1, 64), if more.is_some() { 8 } else { 4 }); + let mut what = Vec::new(); + for (i, p) in layout.params.iter().enumerate() { + match *p { + Param::Constants { at, count } => what.push(format!("p{i} constants {:x?}", (0..count.min(8) as usize).map(|k| word(at as usize + 4 * k)).collect::>())), + Param::Descriptor { at } => { + let va = (word(at as usize) as u64 | (word(at as usize + 4) as u64) << 32) as usize; + let w: Vec = if va != 0 && crate::gpu::shader::readable(va, 4 * buffer_words) { (0..buffer_words).map(|k| ((va + 4 * k) as *const u32).read_unaligned()).collect() } else { Vec::new() }; + what.push(format!("p{i} buffer {va:#x} {w:x?}")); + } + Param::Table { at } => { + let t = word(at as usize) as usize; + let slots: Vec = (0..slots) + .map(|k| { + let at = u.base() + t + 32 * k; + let w = super::console_heap::words_at((t + 32 * k) as u32); + // with `XCL_TRACE_SLOTS`: the image the T# describes (format, width, + // height, first and last level of the view, levels of the texture, smallest + // level of detail), the slot's own index in the shared heap, and the + // resource the T#'s index names there – a T# the title copied as memory + // carries its source slot's index, and samples whatever that slot holds now + let image = w.filter(|_| more.is_some()).and_then(|w| crate::gpu::desc::image(&w)).map_or(String::new(), |t| { + let own = super::console_heap::slot(at as u64).map(|s| s.index); + let named = super::console_heap::named_by_index(w.map_or(0, |w| w[0])); + let nd = (named != 0 && named != super::console_heap::GONE).then(|| ID3D12Resource::from_raw_borrowed(&(named as *mut c_void)).map(|x| x.GetDesc())).flatten(); + if nd.is_some() && super::title_textures::address(named).is_some() { + super::title_textures::probe_gpu_content(named); + } + format!( + " image {:?}, own index {own:?}, its index names {named:#x} {:?} title {:?}", + (t.format, t.width, t.height, t.base_level, t.last_level, t.max_mip, t.min_lod), + nd.map(|d| (d.Width, d.Height, d.Format.0, d.MipLevels)), + super::title_textures::address(named).map(|a| format!("{a:#x}")) + ) + }); + match super::console_heap::resource_at(at) { + Some(r) => { + if super::title_textures::address(r).is_some() { + super::title_textures::probe_gpu_content(r); + } + let d = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| x.GetDesc()); + format!("[{k}] {r:#x} {:?} title {:?} T# {:x?}{image}", d.map(|d| (d.Dimension.0, d.Width, d.Height, d.Format.0)), super::title_textures::address(r).map(|a| format!("{a:#x}")), w.map(|w| w[..words].to_vec())) + } + None => format!("[{k}] - T# {:x?}{image}", w.map(|w| w[..words].to_vec())), + } + }) + .collect(); + what.push(format!("p{i} table {t:#x}: {}", slots.join(", "))); + } + } + } + what.join("; ") +} + +/// #33 SetComputeRootSignature (PC #29) +pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_void, rs: *mut c_void) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::BindState); + let _c = super::capture::op(this, || Some(super::capture::Op::RootSig { gfx: false, rs: rs as usize })); + let layout = console_list::layout_of(rs as usize); + with(this, |s| { + s.args = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; + s.layout = layout; + }); +} + +/// #35 SetComputeRootDescriptorTable (PC #31): the table's console address, 32 bits +pub(super) unsafe extern "system" fn set_compute_root_table(this: *mut c_void, i: u32, handle: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::BindState); + put(this, i, 0, &(handle as u32).to_le_bytes()); +} + +/// #37 SetComputeRoot32BitConstant (PC #33) +pub(super) unsafe extern "system" fn set_compute_root_constant(this: *mut c_void, i: u32, value: u32, offset: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::BindState); + put(this, i, offset, &value.to_le_bytes()); +} + +/// #39 SetComputeRoot32BitConstants (PC #35) +pub(super) unsafe extern "system" fn set_compute_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::BindState); + if !data.is_null() { + let bytes: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); + put(this, i, offset, &bytes); + } +} + +/// #41 / #43 / #45 SetComputeRoot{ConstantBuffer,ShaderResource,UnorderedAccess}View (PC #37 / +/// #39 / #41): the 64-bit GPU address +pub(super) unsafe extern "system" fn set_compute_root_descriptor(this: *mut c_void, i: u32, va: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::BindState); + note_address(va); + put(this, i, 0, &va.to_le_bytes()); +} + +/// #25 SetPipelineState: retain one title identity for the native bind and later emission +/// (`XCL_TWO_PASS_BATCH=2`: with deferred draws on the list, a two-pass pipeline is bound in the +/// run, between the mesh passes where it came, `on_pipeline`; another records the run first). +pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: *mut c_void) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::BindState); + let pso = pso as usize; + let resolution = super::pso_async::begin_pipeline_resolution(pso); + if resolution.is_none() { + super::pso_manifest::note_ready_compute(pso); + } + let deferring = DEFERRING_LISTS.load(Ordering::Relaxed) != 0 && DEFERRING.contains(this as usize); + match on_pipeline(deferring, deferring && super::real::two_pass_of(pso).is_some()) { + OnPipeline::Queue => { + let held = held_pso(pso); + install_tracked_pipeline_state(this, pso, resolution.clone()); + with(this, |s| s.deferred.push(RunItem::Bind { pso, resolution, _held: held })); + return; + } + OnPipeline::FlushThenBind => flush_two_pass(this, RunEnd::Pipeline), + OnPipeline::Bind => {} + } + let _c = super::capture::op(this, || Some(super::capture::Op::Pipeline(pso))); + set_pipeline_state_retained(this, pso, resolution); +} + +#[cfg(test)] +fn set_tracked_pipeline_state(this: *mut c_void, pso: usize) { + let resolution = super::pso_async::begin_pipeline_resolution(pso); + install_tracked_pipeline_state(this, pso, resolution); +} + +fn install_tracked_pipeline_state( + this: *mut c_void, + pso: usize, + resolution: Option, +) { + let old_resolution = with(this, |s| { + s.pso = pso; + std::mem::replace(&mut s.resolution, resolution) + }); + drop(old_resolution); +} + +/// The native pipeline a SetPipelineState of `pso` binds now from its retained `resolution` +/// (Lazy: never waits), and the exact generation it owns. An unavailable identity binds nothing; +/// one that raw native consumers could still bypass poisons the recording. +unsafe fn native_pipeline_choice( + this: *mut c_void, + pso: usize, + resolution: Option<&super::pso_async::PipelineResolution>, +) -> (Option, Option) { + use super::pso_async::{NativePipelineBindMode, NativePipelineChoice}; + let choice = resolution.map(|r| r.select_for_native_bind(NativePipelineBindMode::Lazy)); + match choice { + Some(NativePipelineChoice::Exact { raw, generation }) => (Some(raw), Some(generation)), + Some(NativePipelineChoice::InitialFallback { raw, .. }) => (Some(raw), None), + Some(NativePipelineChoice::Unavailable) if resolution.unwrap().unavailable_is_emission_guarded() => { + (None, None) + } + Some(NativePipelineChoice::Unavailable) => { + // Mesh/raw native consumers can bypass retained draw resolution. Preserve root and + // dynamic state, but make Close/submission reject this whole physical recording. + super::list_x::poison_recording(this as usize); + (None, None) + } + None => (Some(pso), None), + } +} + +unsafe fn set_pipeline_state_retained( + this: *mut c_void, + pso: usize, + resolution: Option, +) { + let (raw, generation) = native_pipeline_choice(this, pso, resolution.as_ref()); + super::list_x::record_native_generation(this as usize, generation); + install_tracked_pipeline_state(this, pso, resolution); + if let Some(raw) = raw { + super::real::bind_pipeline_exact(this, pso, raw); + } + super::list_x::on_set_pipeline_state(this, pso); +} + +/// A SetPipelineState queued in a run of deferred two-pass draws (`RunItem::Bind`), bound where +/// the run records it: as `set_pipeline_state_retained`, the list's tracked state having taken +/// `pso` and `resolution` when the title made the call. +unsafe fn replay_pipeline_bind(this: *mut c_void, pso: usize, resolution: Option<&super::pso_async::PipelineResolution>) { + let (raw, generation) = native_pipeline_choice(this, pso, resolution); + super::list_x::record_native_generation(this as usize, generation); + if let Some(raw) = raw { + super::real::bind_pipeline_exact(this, pso, raw); + } + super::list_x::on_set_pipeline_state(this, pso); +} + +/// ClearState(pso) (`real`): the native ClearState with the retained bind of `pso`, then pipeline, +/// root signature, root argument and heap state as at creation. +pub(super) unsafe fn clear_pipeline_state(this: *mut c_void, pso: usize) { + let resolution = super::pso_async::begin_pipeline_resolution(pso); + clear_pipeline_state_retained(this, pso, resolution); +} + +unsafe fn clear_pipeline_state_retained( + this: *mut c_void, + pso: usize, + resolution: Option, +) { + use super::pso_async::{NativePipelineBindMode, NativePipelineChoice}; + let choice = resolution.as_ref().map(|r| r.select_for_native_bind(NativePipelineBindMode::ForBind)); + let (raw, generation) = match choice { + Some(NativePipelineChoice::Exact { raw, generation }) => (raw, Some(generation)), + Some(NativePipelineChoice::InitialFallback { raw, .. }) => (raw, None), + Some(NativePipelineChoice::Unavailable) => (0, None), + None => (pso, None), + }; + super::list_x::record_native_generation(this as usize, generation); + super::real::clear_pipeline_exact(this, pso, raw); + super::list_x::on_clear_state(this, pso); + install_clear_state(this, pso, resolution); +} + +/// #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 _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDispatch); + dispatch_flags(this, x, y, z, 0); +} + +/// `DispatchX` flag: x, y, z are thread counts, not group counts; the console launches whole +/// groups and leaves the lanes past the count out of EXEC (0x8000, wave32, needs nothing here) +const DISPATCH_THREAD_DIMENSIONS: u32 = 0x20; + +/// What a dispatch of `dims` with `flags` launches on pipeline `pso`: its groups and the thread +/// limits for `IO_THREAD_LIMIT` (0: that axis ends on a whole group). None: it cannot be run +/// as the console would (thread dimensions with a group shape not known). +fn dispatch_groups(pso: usize, dims: [u32; 3], flags: u32) -> Option<([u32; 3], [u32; 3])> { + if flags & DISPATCH_THREAD_DIMENSIONS == 0 { + return Some((dims, [0; 3])); + } + let threads = super::real::pso_threads_exact(pso)?.map(|t| t.max(1)); + let groups = std::array::from_fn(|k| dims[k].div_ceil(threads[k])); + let limits = std::array::from_fn(|k| if dims[k] % threads[k] != 0 { dims[k] } else { 0 }); + Some((groups, limits)) +} + +/// What the frame capture records of a dispatch of `dims` with `flags` on `pso` (the pipeline +/// the title bound): its groups, or a `DispatchX` with thread dimensions' thread counts with the +/// groups they launch, when the group shape is known now (a pipeline still being built has none +/// yet; looked up with nothing sent to the workers, `pso_async::peek`). +fn captured_dispatch(pso: usize, dims: [u32; 3], flags: u32) -> super::capture::WorkKind { + if flags & DISPATCH_THREAD_DIMENSIONS == 0 { + return super::capture::WorkKind::Dispatch(dims); + } + let groups = if super::pso_async::has_real(pso) { dispatch_groups(super::pso_async::peek(pso), dims, flags).map(|(g, _)| g) } else { None }; + super::capture::WorkKind::DispatchThreads { threads: dims, flags, groups } +} + +/// `DispatchX` with thread dimensions launched: how many, and at the first and every power of +/// two the last one's thread counts, its groups and the group shape, logged (whether a title +/// uses the flag, and with what). +fn note_thread_dimensions(threads: [u32; 3], groups: [u32; 3], shape: [u32; 3]) { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + let [t, g, a] = [threads, groups, shape].map(|v| format!("{}x{}x{}", v[0], v[1], v[2])); + crate::xlog_info!("D3D12.X: DispatchX with thread dimensions: {n} so far, last {t} threads as {g} groups of {a}"); + } +} + +fn skip_untranslated_dispatch(pso: usize) { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: Dispatch with a pipeline that has no translated console shader ({pso:#x}) skipped"); + } + count(DISPATCHES_SKIPPED); +} + +/// `Dispatch` / `DispatchX(x, y, z, flags)`. +pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::DispatchRecord); + let (bound_pso, resolution) = with(this, |s| (s.pso, s.resolution.clone())); + let _c = capture_work(this, || captured_dispatch(bound_pso, [x, y, z], flags), false); + // (recorded at the submit through this call, with everything below: counted there) + if let Some(resolution) = &resolution { + if super::list_x::defer_retained(this, resolution, super::list_x::Deferred::Dispatch(x, y, z, flags)) { + super::capture::outcome(super::capture::Outcome::Deferred); + return; + } + } + super::targets::note_dispatch(); + let Some(pso) = resolve_pipeline(this as usize, bound_pso, resolution) else { + super::targets::note_compute(bound_pso, super::targets::Dispatched::Direct([0; 3])); + skip_untranslated_dispatch(bound_pso); + return; + }; + // what it launches: its groups (a `DispatchX` with thread dimensions: whole groups of the + // pipeline's console group shape), and the thread limits; None: thread dimensions on a + // pipeline whose group shape is not known, nothing launched (noted with no groups) + let launch = dispatch_groups(pso, [x, y, z], flags); + super::targets::note_compute(bound_pso, super::targets::Dispatched::Direct(launch.map_or([0; 3], |(g, _)| g))); + 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) + skip_untranslated_dispatch(pso); + return; + } + let Some((groups, limits)) = launch else { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: DispatchX of {x}x{y}x{z} threads (flags {flags:#x}) with a pipeline whose group shape is not known ({pso:#x}) skipped"); + } + count(DISPATCHES_SKIPPED); + return; + }; + if flags != 0 { + // each kind of flags once: what titles pass, and what it launches + static SEEN: Mutex> = Mutex::new(Vec::new()); + let first = { let mut g = SEEN.lock().unwrap(); !g.contains(&flags) && { g.push(flags); true } }; + if first { + crate::xlog_info!("D3D12.X: DispatchX with flags {flags:#x}: {x}x{y}x{z} launched as {}x{}x{} groups (thread limits {limits:?})", groups[0], groups[1], groups[2]); + } + } + if flags & DISPATCH_THREAD_DIMENSIONS != 0 { + note_thread_dimensions([x, y, z], groups, super::real::pso_threads_exact(pso).unwrap_or_default()); + } + // (more groups than the PC takes in one dimension are folded or left out there, not skipped) + let done = translated_dispatch(this, list, bound_pso, pso, groups[0], groups[1], groups[2], limits); + match done { + Ok(()) => count(DISPATCHES), + Err(e) => { + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: Dispatch with a translated pipeline skipped: {e}"); + } + } + } +} + +/// `XCL_TRACE_FRAME`: a full-screen dispatch (enough groups to cover a 4K target in tiles of up +/// to 128 pixels) – what its root arguments say. A bindless title passes the indices of its +/// descriptors in root constants and constant buffers: every small value there is looked up +/// in the dispatch's descriptor tables, and the resources found (the pass's inputs and +/// outputs) are logged. +unsafe fn trace_fullscreen(this: *mut c_void, pso: usize, groups: [u32; 3]) { + if groups[0] < 30 || groups[1] < 17 { + return; + } + let Some(u) = crate::gpu::uma::get() else { return }; + let (layout, args) = with(this, |s| (s.layout.clone(), s.args.clone())); + let Some(layout) = layout else { return }; + static SEEN: Mutex> = Mutex::new(Vec::new()); + { + let mut g = SEEN.lock().unwrap(); + if g.contains(&pso) || g.len() >= 12 { + return; + } + g.push(pso); + } + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); + let mut tables: Vec = Vec::new(); + let mut values: Vec = Vec::new(); + let mut what: Vec = Vec::new(); + for (i, p) in layout.params.iter().enumerate() { + match *p { + Param::Constants { at, count } => { + let w: Vec = (0..count as usize).filter_map(|k| word(at as usize + 4 * k)).collect(); + what.push(format!("p{i} constants {w:x?}")); + values.extend(&w); + } + Param::Descriptor { at } => { + let lo = word(at as usize).unwrap_or(0) as u64; + let hi = word(at as usize + 4).unwrap_or(0) as u64; + let va = (lo | hi << 32) as usize; + let n = 64usize; + if va != 0 && crate::gpu::shader::readable(va, 4 * n) { + let w: Vec = (0..n).map(|k| ((va + 4 * k) as *const u32).read_unaligned()).collect(); + what.push(format!("p{i} buffer {va:#x}: {w:x?}")); + values.extend(&w); + } else { + what.push(format!("p{i} buffer {va:#x} (not readable)")); + } + } + Param::Table { at } => { + let v = word(at as usize).unwrap_or(0); + what.push(format!("p{i} table {v:#x}")); + tables.push(v); + } + } + } + let mut found: Vec<(u32, usize)> = Vec::new(); + for &v in &values { + if v >= 1 << 20 { + continue; + } + for &t in &tables { + let slot = u.base() + t as usize + 32 * v as usize; + if let Some(r) = super::console_heap::resource_at(slot) { + if !found.iter().any(|x| x.1 == r) { + found.push((v, r)); + } + } + } + } + let res: Vec = found + .iter() + .map(|&(v, r)| { + let d = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| x.GetDesc()); + format!("[{v}] {r:#x} {:?}{}", d.map(|d| (d.Dimension.0, d.Width, d.Height, d.Format.0)), if super::present::is_presented(r) { " PRESENTED" } else { "" }) + }) + .collect(); + crate::xlog_info!("frame trace: full-screen dispatch {groups:?}, pipeline {pso:#x}: {}", what.join("; ")); + crate::xlog_info!("frame trace: … its indices name: {}", if res.is_empty() { "nothing".to_string() } else { res.join("; ") }); +} + +/// #148 AllocateUploadMemory(size, alignment) → CPU/GPU pointer in unified memory (used by +/// `XboxBvhBuilder.dll` and other console middleware on default title command lists). +/// Freed automatically when the list's command allocator is reset. +pub(super) unsafe extern "system" fn allocate_upload_memory(this: *mut c_void, size: usize, align: usize) -> *mut u8 { + let Some(u) = crate::gpu::uma::get() else { + return std::ptr::null_mut(); + }; + let size = size.max(16); + let align = align.max(16); + if size <= crate::gpu::uma::ARENA_BLOCK / 2 { + if let Some(p) = with(this, |s| s.arena.take(u, size, align, &mut s.uma)) { + return p; + } + } + if u.has_sparse() { + if let Some((p, _)) = super::sparse::alloc(size, align) { + with(this, |s| s.uma.push(p)); + return p as *mut u8; + } + } + match u.alloc(size, align) { + Some(p) => { + with(this, |s| s.uma.push(p as usize)); + p + } + None => std::ptr::null_mut(), + } +} + +/// Diagnostic: what the committed window looks like when a draw's arguments find no room in it +/// (the first four times, then every power of two). +fn note_arena_full(u: &crate::gpu::uma::Uma, asked: usize) { + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed) + 1; + if k > 4 && !k.is_power_of_two() { + return; + } + let (free, largest, used, pool) = u.committed_state(); + let (allocators, blocks) = console_list::pending_blocks(); + crate::xlog_warn!( + "D3D12.X: no unified memory for draw data ({k} so far): {asked} bytes asked; coherent window {} MB in use, {} MB free (largest run {} KB), {pool} of {} pool blocks left; {blocks} blocks held for {allocators} allocators", + used >> 20, + free >> 20, + largest >> 10, + crate::gpu::uma::POOL / crate::gpu::uma::ARENA_BLOCK + ); +} + +/// A translated dispatch of `x` × `y` × `z` console groups: bound on XCL's ABI, folded where the +/// PC takes fewer groups in a dimension (`fold_counts`), then run (`dispatch_chain::dispatch`: +/// a split program's chain, a wave-local remapped program's scaled grid or its whole form). +unsafe fn translated_dispatch( + this: *mut c_void, + list: &ID3D12GraphicsCommandList, + original: usize, + pso: usize, + x: u32, + y: u32, + z: u32, + limits: [u32; 3], +) -> Result<(), String> { + if super::present::trace_frame() { + trace_fullscreen(this, pso, [x, y, z]); + } + if super::real::skip_named_cs(pso) { + return Ok(()); + } + // more groups in X than D3D12 takes: folded (`recomp::IO_GROUP_LIMIT`). The loop budget is + // the console's groups' share: those are the groups that run + let (limit, folded) = fold_counts(x, y, z); + // (the PC takes 65 535 groups a dimension at most, the debug layer's id 1296: what it does + // with more is not defined. One `fold` cannot fold is clamped: said here, with the program, + // in place of `fold`'s line) + if limit == 0 && folded != [x, y, z] { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + let cs = super::real::pso_shaders(pso).map_or(0, |(cs, _)| cs); + if left_out([x, y, z], folded) { + crate::xlog_warn!("D3D12.X: Dispatch of {x} x {y} x {z} groups with cs {cs:016x}: more groups than a dispatch may have (XCL_INDIRECT_MAX_GROUPS) – left out"); + } else { + crate::xlog_warn!("D3D12.X: Dispatch of {x} x {y} x {z} groups with cs {cs:016x}: past the PC's 65 535 groups a dimension and not foldable – clamped to 65535 a dimension"); + } + } + } + // a folded dispatch's IO_GROUP_LIMIT is the console's X count, which is the GPU's only + // where X is not scaled: a wave-local remapped program runs its whole form then + let whole = if limit != 0 && super::real::pso_dispatch_remap_exact(pso).is_some() { + Some(super::real::remap_fallback::whole_exact(pso)?) + } else { + None + }; + let b = bind_abi_with_root_resolved(this, list, original, pso, false, 0, limits, Some([x, y, z]), limit)?; + // (one span for a split program's whole chain of dispatches, cut into slabs from the folded + // groups; the span names the console's) + let t = super::gpu_profile::begin(this, pso, super::gpu_profile::Kind::Dispatch, [x, y, z]); + let ran = match &whole { + Some(whole) => { + super::real::bind_pipeline_exact(this, original, whole.as_raw() as usize); + list.Dispatch(folded[0], folded[1], folded[2]); + Ok(()) + } + None => super::real::dispatch_chain::dispatch(list, original, pso, b.allocator, folded), + }; + super::gpu_profile::end(this, t); + ran +} + +/// Window 0's GPU address (`window0`: `real::uma_window_va(0)`), which a bind on XCL's ABI +/// reads descriptor tables from and binds for a window without a buffer of its own. Shadowed +/// unified memory whose sparse windows could not be made (no reserved resources either) has +/// none there, and a null root descriptor is not bound. +fn first_window(window0: Option, shadowed: bool) -> Result { + let first = window0.ok_or("unified memory is not open on the GPU")?; + if first == 0 && shadowed { + return Err("window 0 of unified memory has no buffer on the GPU".into()); + } + Ok(first) +} + +/// Whether dispatches pass `recomp::dispatch_loop_budget` (`XCL_DISPATCH_LOOP_BUDGET=0`, read +/// once: they leave `IO_LOOP_BUDGET` at 0 and every loop has the lane's 65 536 passes in both +/// translators, as before, to compare). Here, not in `recomp`: that module's source is part of +/// every translation's cache identity, and the switch changes no translated code. +pub(super) fn dispatch_loop_budget_wanted() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_DISPATCH_LOOP_BUDGET").map_or(true, |v| v.trim() != "0")) +} + +/// A dispatch of `x` × `y` × `z` groups as D3D12 takes it: (the count for +/// `recomp::IO_GROUP_LIMIT` – 0: not folded –, the groups to dispatch). More than 65 535 in X +/// with 1 in Y is folded into Y; any other count past 65 535 is clamped (logged once). +pub(super) fn fold(x: u32, y: u32, z: u32) -> (u32, [u32; 3]) { + let (limit, groups) = fold_counts(x, y, z); + if limit == 0 && groups != [x, y, z] { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + if left_out([x, y, z], groups) { + crate::xlog_warn!("D3D12.X: a dispatch of {x}x{y}x{z} groups is left out: more groups than a dispatch may have (XCL_INDIRECT_MAX_GROUPS)"); + } else { + crate::xlog_warn!("D3D12.X: a dispatch of {x}x{y}x{z} groups cannot be folded – clamped to 65535 a dimension"); + } + } + } + (limit, groups) +} + +/// Whether `fold_counts` left a dispatch of `asked` groups out (it gave no groups for counts +/// that had some). +fn left_out(asked: [u32; 3], groups: [u32; 3]) -> bool { + groups == [0, 0, 0] && asked.iter().all(|&n| n != 0) +} + +/// `fold` without its log line (for a caller that says it with the program) +fn fold_counts(x: u32, y: u32, z: u32) -> (u32, [u32; 3]) { + fold_counts_within(x, y, z, super::indirect_guard::max_groups()) +} + +/// `fold_counts` with `most`, the groups in all a dispatch that needs folding or clamping may +/// still run (`indirect_guard`'s bound). Counts D3D12 takes pass as they are, whatever their +/// product. Past them, more groups than that are counts no title asks for – where the counts +/// should be lies something else: 1 065 353 216, the bits of 1.0f, is 16 257 rows of 65 535 +/// groups once folded, and 70 000 x 70 000 x 16 clamped is still 68 thousand million – and +/// nothing runs: such a dispatch kept an NVIDIA GPU busy until the driver reset the device. +fn fold_counts_within(x: u32, y: u32, z: u32, most: u32) -> (u32, [u32; 3]) { + use crate::gpu::recomp::FOLD_X; + if x <= FOLD_X && y <= 65_535 && z <= 65_535 { + return (0, [x, y, z]); + } + let (limit, groups) = + if y == 1 && z <= 65_535 && x.div_ceil(FOLD_X) <= 65_535 { (x, [FOLD_X, x.div_ceil(FOLD_X), z]) } else { (0, [x.min(65_535), y.min(65_535), z.min(65_535)]) }; + // (a folded dispatch has up to one row of groups more than the console's count; the bound in + // 32 bits, as `clamp`'s pass takes it) + if groups.iter().map(|&n| n as u64).product::() > most.saturating_add(FOLD_X) as u64 { + return (0, [0, 0, 0]); + } + (limit, groups) +} + +/// What a bind on XCL's ABI set on a list, for setting it again after other work in between +/// (`rebind`), the GPU address of its `io`, and the PC allocator the list records with. +pub(super) struct Bound { + rs: ID3D12RootSignature, + views: [u64; 6], + /// the title's pipeline and the PC pipeline bound for it (held) + original: usize, + pso: ID3D12PipelineState, + pub io: u64, + pub allocator: usize, +} + +/// The binding a bind on XCL's ABI made, set on `list` (`this`) again. +pub(super) unsafe fn rebind(this: *mut c_void, list: &ID3D12GraphicsCommandList, b: &Bound, gfx: bool) { + set_abi_roots(list, b, gfx); + // (past the hook of a title's SetPipelineState: the pipeline was resolved at the bind) + super::real::bind_pipeline_exact(this, b.original, b.pso.as_raw() as usize); +} + +/// A bind's root signature and its six root views (`io`, res, the four memory windows) +unsafe fn set_abi_roots(list: &ID3D12GraphicsCommandList, b: &Bound, gfx: bool) { + if gfx { + list.SetGraphicsRootSignature(&b.rs); + for (k, v) in b.views.iter().enumerate() { + list.SetGraphicsRootUnorderedAccessView(k as u32, *v); + } + } else { + list.SetComputeRootSignature(&b.rs); + for (k, v) in b.views.iter().enumerate() { + list.SetComputeRootUnorderedAccessView(k as u32, *v); + } + } +} + +/// XCL's ABI for a translated pipeline: its root signature, the user SGPRs (`io`, the kept +/// arguments the console's way – compute or graphics) and the argument table in unified +/// memory, u1 res, u2… the memory windows; then the pipeline. The list's arguments and its +/// pieces of unified memory are taken under one lock. +struct PreparedAbiState { + layout: Option>, + args: Vec, + inline: usize, + table_at: usize, + io_at: usize, + res_at: usize, + allocator: usize, + heaps: [u32; 2], +} + +fn prepare_abi_state( + this: *mut c_void, + u: &crate::gpu::uma::Uma, + gfx: bool, + user_sgprs: Option, +) -> Result { + // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) + let full = |asked: usize| { + note_arena_full(u, asked); + "unified memory is full".to_string() + }; + with(this, |state| { + let (layout, args) = if gfx { + (state.layout_gfx.clone(), state.args_gfx.clone()) + } else { + (state.layout.clone(), state.args.clone()) + }; + let inline = layout + .as_ref() + .map_or(0, |layout| if gfx { layout.inline_gfx } else { console_list::inline_for(layout, user_sgprs) } as usize) + .min(args.len()); + let table_bytes = (args.len() - inline).max(16); + let table_at = state.arena.take(u, table_bytes, 256, &mut state.uma) + .ok_or_else(|| full(table_bytes))? as usize; + let io_bytes = crate::gpu::recomp::KERNEL_SGPRS * std::mem::size_of::(); + let io_at = state.arena.take(u, io_bytes, 256, &mut state.uma).ok_or_else(|| full(io_bytes))? as usize; + let res_at = state.arena.take(u, 256, 256, &mut state.uma).ok_or_else(|| full(256))? as usize; + Ok(PreparedAbiState { layout, args, inline, table_at, io_at, res_at, allocator: state.allocator, heaps: state.heaps }) + }) +} + +/// The user SGPRs of a bind (`io`). `groups`: the thread groups of a dispatch whose counts are +/// known here (`IO_LOOP_BUDGET`: the console's, also when folded). `group_limit`: a folded +/// dispatch's group count in X (`recomp::IO_GROUP_LIMIT`), 0 for any other. `limits`: a +/// `DispatchX` with thread dimensions' thread counts (`IO_THREAD_LIMIT`, compute only). +fn prepared_abi_io( + layout: Option<&Layout>, args: &[u8], table_at: usize, gfx: bool, + user_sgprs: Option, uma_base: usize, heaps: [u32; 2], limits: [u32; 3], + groups: Option<[u32; 3]>, group_limit: u32, +) -> Vec { + let mut io = match layout { + Some(layout) if gfx => console_list::with_heaps(layout, None, console_list::user_data_gfx(layout, args, table_at as u64), heaps), + Some(layout) => console_list::with_heaps(layout, user_sgprs, console_list::user_data_for(layout, user_sgprs, args, table_at as u64), heaps), + None => vec![table_at as u32, (table_at >> 32) as u32], + }; + io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + io[crate::gpu::recomp::IO_UMA_BASE_HI] = (uma_base >> 32) as u32; + if let Some(groups) = groups.filter(|_| dispatch_loop_budget_wanted()) { + io[crate::gpu::recomp::IO_LOOP_BUDGET] = crate::gpu::recomp::dispatch_loop_budget(groups); + } + io[crate::gpu::recomp::IO_GROUP_LIMIT] = group_limit; + if !gfx { + for (k, limit) in limits.into_iter().enumerate() { + io[crate::gpu::recomp::IO_THREAD_LIMIT[k]] = limit; + } + } + io +} + +/// A draw's or an indirect command's bind on XCL's ABI (no groups known here) +unsafe fn bind_abi_resolved( + this: *mut c_void, list: &ID3D12GraphicsCommandList, original: usize, pso: usize, gfx: bool, +) -> Result { + bind_abi_with_root_resolved(this, list, original, pso, gfx, 0, [0; 3], None, 0) +} + +/// A bind on XCL's ABI of `pso`, the PC pipeline resolved for the title's `original`. `root`: +/// a root signature to bind in place of the pipeline's (a split chain's indirect form; the +/// pipeline is then not bound here). +unsafe fn bind_abi_with_root_resolved( + this: *mut c_void, list: &ID3D12GraphicsCommandList, original: usize, pso: usize, gfx: bool, + root: usize, limits: [u32; 3], groups: Option<[u32; 3]>, group_limit: u32, +) -> Result { + #[cfg(test)] + { + if STOP_ABI_LIST.load(Ordering::Acquire) == this as usize { + LAST_ABI_PSO.store(pso, Ordering::Release); + return Err("stopped after resolved PSO for test".into()); + } + } + #[cfg(test)] + if STOP_ABI_AFTER_BIND_LIST.load(Ordering::Acquire) == this as usize && root == 0 { + super::real::bind_pipeline_exact(this, original, pso); + LAST_ABI_PSO.store(pso, Ordering::Release); + return Err("stopped after exact native bind for test".into()); + } + // the shared view and sampler heaps: once a recording until the title sets heaps again + // (`heaps_changed`), and whether the shared view heap is among them + let cached = with(this, |s| s.heap_bound.then_some(s.shared_view_bound)); + let shared_view_bound = match cached { + Some(shared) => shared, + None => { + let shared = super::list_x::ensure_view_heap(this); + with(this, |s| { + s.heap_bound = true; + s.shared_view_bound = shared; + }); + shared + } + }; + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let first = first_window(super::real::uma_window_va(0), u.shadowed())?; + // 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_exact(pso) }; + let prepared = prepare_abi_state(this, u, gfx, user_sgprs)?; + let PreparedAbiState { layout, args, inline, table_at, io_at, res_at, allocator, heaps } = prepared; + want_root_views(layout.as_deref(), &args, super::view_want::Path::RootView); + std::ptr::copy_nonoverlapping(args[inline..].as_ptr(), table_at as *mut u8, args.len() - inline); + let io = prepared_abi_io(layout.as_deref(), &args, table_at, gfx, user_sgprs, u.base(), heaps, limits, groups, group_limit); + let io_bytes = io.iter().flat_map(|word| word.to_le_bytes()).collect::>(); + std::ptr::copy_nonoverlapping(io_bytes.as_ptr(), io_at as *mut u8, io_bytes.len()); + std::ptr::write_bytes(res_at as *mut u8, 0, 256); + let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); + let rs = (root != 0).then_some(root) + .or_else(|| super::real::pso_root_signature_exact(pso)) + .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")?.clone(); + let mut views = [first; 6]; + views[0] = va(io_at); + views[1] = va(res_at); + // (every window slot gets a buffer: direct DXIL compute reads all four, `with_mem_raw_loads`) + for k in 0..4 { + views[2 + k] = super::real::uma_window_va(k).filter(|&v| v != 0).unwrap_or(first); + } + let pc = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("pipeline")?.clone(); + let b = Bound { rs, views, original, pso: pc, io: views[0], allocator }; + set_abi_roots(list, &b, gfx); + if root == 0 { + super::real::bind_pipeline_exact(this, original, pso); + } + if shared_view_bound && super::vram::srv_tracking_enabled() { + super::list_x::note_shared_view_heap_use(this); + } + Ok(b) +} + +#[cfg(test)] +pub(super) fn last_draw_args() -> (bool, u32, u32, u32, i32) { + DRAW_ARGS.with(|d| d.get()) +} + +#[cfg(test)] +pub(super) fn counts_snapshot() -> [u64; 5] { + std::array::from_fn(|k| COUNTS[k].load(Ordering::Relaxed)) +} + +#[cfg(test)] +pub(super) fn tracked_pso(list: *mut c_void) -> usize { + let Some(entry) = STATES.get(list as usize) else { return 0 }; + let pso = entry.state.lock().unwrap().pso; + pso +} + +#[cfg(test)] +fn state_locks_available_for_test(list: usize) -> bool { + let shard = match STATES.shards[state_shard_index(list)].try_lock() { + Ok(shard) => shard, + Err(_) => return false, + }; + let entry = shard.as_ref().and_then(|states| states.get(&list)).cloned(); + drop(shard); + let Some(entry) = entry else { return true }; + let available = entry.state.try_lock().is_ok(); + available +} + +#[cfg(test)] +mod tests { + use super::super::{device_x, list_x, pso_async, real, title_list}; + use super::*; + use std::collections::HashSet; + use std::sync::atomic::{AtomicBool, AtomicUsize}; + use std::sync::mpsc; + use std::time::Duration; + + #[test] + fn aligned_list_addresses_reach_many_bind_shards() { + let shards = (0..256).map(|index| state_shard_index(0x7100_0000 + index * 16)).collect::>(); + assert!(shards.len() >= STATE_SHARDS / 2, "aligned list addresses reached only {} shards", shards.len()); + } + + #[test] + fn busy_bind_shard_does_not_block_an_unrelated_shard() { + let first = 0x7E57_BA00usize; + let second = (1..STATE_SHARDS) + .map(|index| first + index * 16) + .find(|&key| state_shard_index(key) != state_shard_index(first)) + .expect("shard mixer did not distribute aligned keys"); + let shard = STATES.shards[state_shard_index(first)].lock().unwrap(); + let (sent, received) = mpsc::channel(); + let worker = std::thread::spawn(move || { + drop(STATES.get_or_insert(second)); + sent.send(()).unwrap(); + }); + received.recv_timeout(Duration::from_secs(1)).expect("unrelated bind shard blocked"); + worker.join().unwrap(); + drop(shard); + drop(STATES.remove(second)); + } + + #[test] + fn busy_list_state_does_not_block_another_list_in_the_same_shard() { + let keys = (0..256).map(|index| Box::new(index as u8)).collect::>(); + let mut seen = HashMap::new(); + let (first, second) = keys + .iter() + .map(|key| (&**key as *const u8) as usize) + .find_map(|key| seen.insert(state_shard_index(key), key).map(|first| (first, key))) + .expect("allocator did not provide two keys in one shard"); + let first_entry = STATES.get_or_insert(first); + drop(STATES.get_or_insert(second)); + let state = first_entry.state.lock().unwrap(); + let (sent, received) = mpsc::channel(); + let worker = std::thread::spawn(move || { + with(second as *mut c_void, |state| state.pso = 0x7E57_D201); + sent.send(()).unwrap(); + }); + received.recv_timeout(Duration::from_secs(1)).expect("unrelated list state blocked"); + worker.join().unwrap(); + drop(state); + drop(STATES.remove(first)); + drop(STATES.remove(second)); + } + + #[test] + fn forget_then_same_address_create_uses_a_fresh_entry() { + let key = Box::new(0u8); + let list = (&*key as *const u8) as *mut c_void; + reset(list, 0, 0x7E57_D211); + let old = STATES.get(list as usize).unwrap(); + forget(list); + reset(list, 0, 0x7E57_D212); + let new = STATES.get(list as usize).unwrap(); + assert!(!Arc::ptr_eq(&old, &new)); + old.state.lock().unwrap().pso = 0x7E57_D213; + assert_eq!(tracked_pso(list), 0x7E57_D212, "orphaned state changed the replacement"); + forget(list); + } + + #[test] + fn warm_bind_cache_does_not_take_the_registry_shard() { + let key = Box::new(0u8); + let list = (&*key as *const u8) as usize; + reset(list as *mut c_void, 0, 0x7E57_D221); + let (ready_tx, ready_rx) = mpsc::channel(); + let (continue_tx, continue_rx) = mpsc::channel(); + let (done_tx, done_rx) = mpsc::channel(); + let worker = std::thread::spawn(move || { + assert_eq!(with(list as *mut c_void, |state| state.pso), 0x7E57_D221); + ready_tx.send(()).unwrap(); + continue_rx.recv().unwrap(); + done_tx.send(with(list as *mut c_void, |state| state.pso)).unwrap(); + }); + ready_rx.recv_timeout(Duration::from_secs(1)).expect("cache worker did not warm its entry"); + let shard = STATES.shards[state_shard_index(list)].lock().unwrap(); + continue_tx.send(()).unwrap(); + assert_eq!(done_rx.recv_timeout(Duration::from_secs(1)).expect("warm cache took its registry shard"), 0x7E57_D221); + drop(shard); + worker.join().unwrap(); + forget(list as *mut c_void); + } + + #[test] + fn tls_cache_keeps_four_entries() { + let mut cache = BindStateCache { entries: [const { None }; STATE_CACHE_ENTRIES], next: 0 }; + let entries = (0..=STATE_CACHE_ENTRIES).map(|_| Arc::new(BindEntry::default())).collect::>(); + for (key, entry) in entries.iter().take(STATE_CACHE_ENTRIES).enumerate() { + cache.insert(key, entry); + } + for key in 0..STATE_CACHE_ENTRIES { + assert!(Arc::ptr_eq(&cache.get(key).unwrap(), &entries[key])); + } + cache.insert(STATE_CACHE_ENTRIES, &entries[STATE_CACHE_ENTRIES]); + assert!(cache.get(0).is_none(), "FIFO cache did not evict its oldest entry"); + for key in 1..=STATE_CACHE_ENTRIES { + assert!(Arc::ptr_eq(&cache.get(key).unwrap(), &entries[key])); + } + } + + #[test] + fn cross_thread_cache_rejects_a_reused_address() { + let key = Box::new(0u8); + let list = (&*key as *const u8) as usize; + reset(list as *mut c_void, 0, 0x7E57_D231); + let old = STATES.get(list).unwrap(); + let (ready_tx, ready_rx) = mpsc::channel(); + let (continue_tx, continue_rx) = mpsc::channel(); + let worker = std::thread::spawn(move || { + assert_eq!(with(list as *mut c_void, |state| state.pso), 0x7E57_D231); + ready_tx.send(()).unwrap(); + continue_rx.recv().unwrap(); + with(list as *mut c_void, |state| state.pso) + }); + ready_rx.recv_timeout(Duration::from_secs(1)).expect("cache worker did not warm its entry"); + forget(list as *mut c_void); + reset(list as *mut c_void, 0, 0x7E57_D232); + continue_tx.send(()).unwrap(); + assert_eq!(worker.join().unwrap(), 0x7E57_D232, "worker reused its orphaned cache entry"); + assert!(!old.live.load(Ordering::Acquire)); + forget(list as *mut c_void); + } + + #[test] + fn cross_thread_cache_observes_reset_on_the_live_entry() { + let key = Box::new(0u8); + let list = (&*key as *const u8) as usize; + reset(list as *mut c_void, 0, 0x7E57_D241); + let (ready_tx, ready_rx) = mpsc::channel(); + let (continue_tx, continue_rx) = mpsc::channel(); + let worker = std::thread::spawn(move || { + assert_eq!(with(list as *mut c_void, |state| state.pso), 0x7E57_D241); + ready_tx.send(()).unwrap(); + continue_rx.recv().unwrap(); + with(list as *mut c_void, |state| state.pso) + }); + ready_rx.recv_timeout(Duration::from_secs(1)).expect("cache worker did not warm its entry"); + reset(list as *mut c_void, 0, 0x7E57_D242); + continue_tx.send(()).unwrap(); + assert_eq!(worker.join().unwrap(), 0x7E57_D242); + forget(list as *mut c_void); + } + + /// Counts D3D12 takes are dispatched as they are; more than 65 535 in X with 1 in Y are + /// folded into Y with the console's count kept (a retail game's 72 512 × 1 × 1); others past + /// the limit are clamped. + #[test] + fn dispatches_past_the_d3d12_limit_are_folded_or_clamped() { + assert_eq!(fold(64, 2, 1), (0, [64, 2, 1])); + assert_eq!(fold(65_535, 1, 1), (0, [65_535, 1, 1])); + assert_eq!(fold(72_512, 1, 1), (72_512, [65_535, 2, 1])); + assert_eq!(fold(131_071, 1, 3), (131_071, [65_535, 3, 3])); + assert_eq!(fold(70_000, 2, 1), (0, [65_535, 2, 1]), "two dimensions in use: clamped"); + // every console group is in the folded grid exactly once, and no more than 65 535 more + for n in [65_536u32, 72_512, 75_072, 200_000] { + let (limit, [x, y, _]) = fold(n, 1, 1); + assert_eq!(limit, n); + assert!(x * y >= n && x * y - n < x, "{n}: {x}x{y}"); + } + } + + /// A dispatch that needs folding or clamping runs at most the groups a dispatch may have: the + /// bits of 1.0f where a count should be are 16 257 rows of 65 535 groups once folded, and + /// nothing of that runs. Counts D3D12 takes are never looked at. + #[test] + fn a_dispatch_past_the_limit_with_more_groups_than_any_title_asks_for_is_left_out() { + let most = 1 << 22; + assert_eq!(fold_counts_within(most, 1, 1, most), (most, [65_535, 65, 1]), "the most that is folded"); + assert_eq!(fold_counts_within(most + 65_536, 1, 1, most), (0, [0, 0, 0])); + assert_eq!(fold_counts_within(0x3F80_0000, 1, 1, most), (0, [0, 0, 0]), "1.0f in X"); + assert_eq!(fold_counts_within(70_000, 70_000, 16, most), (0, [0, 0, 0]), "clamped it is 65 535 x 65 535 x 16"); + assert_eq!(fold_counts_within(u32::MAX, 1, 1, most), (0, [65_535, 1, 1]), "not foldable: one row, as before"); + assert_eq!(fold_counts_within(70_000, 2, 1, most), (0, [65_535, 2, 1])); + assert_eq!(fold_counts_within(4_096, 4_096, 1, most), (0, [4_096, 4_096, 1]), "within D3D12's limits: as it is, whatever the product"); + assert_eq!(fold_counts_within(60_000, 60_000, 2, most), (0, [60_000, 60_000, 2])); + assert!(left_out([0x3F80_0000, 1, 1], [0, 0, 0]) && !left_out([0, 5, 1], [0, 0, 0]) && !left_out([70_000, 2, 1], [65_535, 2, 1])); + } + + /// A pipeline with the rect list GS draws its rect lists whole: draw_rects leaves them alone. + #[test] + fn rect_lists_with_the_rect_list_gs_are_not_expanded_on_the_cpu() { + let (with_gs, without) = (0x7E57_4000usize, 0x7E57_5000usize); + real::register_rect_list_gs_for_test(with_gs); + assert!(!cpu_rect_expansion(with_gs)); + assert!(cpu_rect_expansion(without) && cpu_rect_expansion(0)); + real::forget_pso_for_test(with_gs); + assert!(cpu_rect_expansion(with_gs)); + } + + /// An ExecuteIndirect whose bound pipeline is still being built is skipped (its stand-in + /// with XCL's ABI root signature on the list is the debug layer's 953 and a hung GPU); + /// a built or failed one goes to the PC call. The gate `execute_indirect` uses. + #[test] + fn execute_indirect_with_a_pipeline_still_building_is_skipped() { + let (building, built, failed) = (0x7E57_6001usize, 0x7E57_6002usize, 0x7E57_6003usize); + // 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(failed, false, Box::new(|| 0), 0); + assert!(pso_async::is_pending(building)); + assert_eq!(pso_async::resolve_wait(built), 0x1235); + 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)); + pso_async::released(building); + pso_async::released(built); + pso_async::released(failed); + assert!(!pso_async::is_pending(building)); + } + + /// A dispatch writes an ExecuteIndirect's group count through another buffer over the same + /// memory (as translated shaders write through the memory windows), a UAV barrier (what a + /// console barrier becomes), then the ExecuteIndirect: it runs the count just written, not + /// the one the memory held before the list (`fresh_indirect_arguments`; without it an RTX + /// 5090 ran the old count in nearly every try). + #[test] + fn execute_indirect_reads_the_arguments_written_before_it() { + use crate::gpu::{fence, recomp::runner::skip_test}; + use std::mem::{transmute_copy, ManuallyDrop}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, IDXGIAdapter1, IDXGIFactory6, DXGI_CREATE_FACTORY_FLAGS}; + + const TRIES: u32 = 40; + // mode 0: write (x, 1, 1) at a[0..12]; mode 1: count the groups + let src = r#" +#define RS "RootConstants(num32BitConstants=2, b0), UAV(u0), UAV(u1)" +cbuffer C : register(b0) { uint mode; uint x; }; +RWByteAddressBuffer a : register(u0); +RWByteAddressBuffer c : register(u1); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint t : SV_GroupIndex) { + if (t != 0u) return; + if (mode == 0u) a.Store3(0, uint3(x, 1u, 1u)); else c.InterlockedAdd(0, 1u); +} +"#; + if crate::gpu::recomp::dxc::location().is_err() { + skip_test("no DXC"); + return; + } + unsafe { + let setup = || -> Result<(ID3D12Device, String), String> { + let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| format!("DXGI factory unavailable: {e}"))?; + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let (adapter, name): (IDXGIAdapter1, String) = if sel == crate::gpu::adapter::Selector::Warp { + (factory.EnumWarpAdapter().map_err(|e| format!("WARP unavailable: {e}"))?, "WARP (software renderer)".into()) + } else { + let (adapter, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next() + .ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + (adapter, crate::gpu::adapter::name(&desc)) + }; + let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_11_0).map_err(|e| format!("{name}: D3D12 device unavailable ({e})"))?; + let mut sm = D3D12_FEATURE_DATA_SHADER_MODEL { HighestShaderModel: D3D_SHADER_MODEL_6_6 }; + dev.CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &mut sm as *mut _ as _, std::mem::size_of_val(&sm) as u32) + .map_err(|e| format!("{name}: cannot query SM 6.6 ({e})"))?; + if sm.HighestShaderModel.0 < D3D_SHADER_MODEL_6_6.0 { + return Err(crate::gpu::agility::format_no_sm66_message(&name, crate::gpu::agility::state())); + } + Ok((dev, name)) + }; + let (dev, name) = match setup() { + Ok(selected) => selected, + Err(reason) => { skip_test(&reason); return; } + }; + println!("ExecuteIndirect adapter: {name}"); + let dxil = crate::gpu::recomp::dxc::compile(src, "main", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap(); + let cs = D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }; + let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: cs, ..Default::default() }).unwrap(); + let arg = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }; + let mut sig: Option = None; + dev.CreateCommandSignature(&D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 12, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 }, None, &mut sig).unwrap(); + let sig = sig.unwrap(); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let desc = |width| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: width, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + // the arguments and the buffer the dispatch writes them through: one memory + let mut heap: Option = None; + let heap_desc = D3D12_HEAP_DESC { SizeInBytes: 1 << 16, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }; + dev.CreateHeap(&heap_desc, &mut heap).unwrap(); + let heap = heap.unwrap(); + let placed = || { + let mut r: Option = None; + dev.CreatePlacedResource(&heap, 0, &desc(1 << 16), D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + }; + let (args, written) = (placed(), placed()); + // the group count, read on the CPU + let cpu_heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; + let mut groups: Option = None; + dev.CreateCommittedResource(&cpu_heap, D3D12_HEAP_FLAG_NONE, &desc(256), D3D12_RESOURCE_STATE_COMMON, None, &mut groups).unwrap(); + let groups = groups.unwrap(); + let mut count = std::ptr::null_mut(); + groups.Map(0, None, Some(&mut count)).unwrap(); + let count = count as *mut u32; + let uav_barrier = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: ManuallyDrop::new(None) }) }, + }; + let run = |list: &ID3D12GraphicsCommandList, close: &dyn Fn()| { + close(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let v = done.GetCompletedValue() + 1; + queue.Signal(&done, v).unwrap(); + fence::wait(&done, v, &dev, None, 10_000).unwrap(); + }; + let (mut old, mut wrong) = (0u32, Vec::new()); + for k in 0..TRIES { + // each try writes a count the memory does not hold yet + let new = if k % 2 == 0 { 4096 } else { 0 }; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let record = |x: u32| -> ID3D12GraphicsCommandList { + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, &pso).unwrap(); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(1, written.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, groups.GetGPUVirtualAddress()); + list.SetComputeRoot32BitConstants(0, 2, [0u32, x].as_ptr() as _, 0); + list.Dispatch(1, 1, 1); + list + }; + let before = record(old); + run(&before, &|| before.Close().unwrap()); + alloc.Reset().unwrap(); + *count = 0; + let list = record(new); + list.ResourceBarrier(&[uav_barrier.clone()]); + list.SetComputeRoot32BitConstants(0, 2, [1u32, 0].as_ptr() as _, 0); + // from here as XCL records a title's ExecuteIndirect: on the adopted list + let raw = list.as_raw(); + real::adopt(raw, real::Kind::CommandList); + list_x::on_create(raw, alloc.as_raw() as usize, 0, ty); + type Ei = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); + type Close = unsafe extern "system" fn(*mut c_void) -> windows::core::HRESULT; + let ei: Ei = std::mem::transmute(real::orig_fn(raw, 59)); + fresh_indirect_arguments(raw, || ei(raw, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0, 0)); + let close: Close = std::mem::transmute(real::orig_fn(raw, 9)); + run(&list, &|| close(raw).unwrap()); + let ran = std::ptr::read_volatile(count); + if ran != new { + wrong.push((k, ran)); + } + old = new; + } + groups.Unmap(0, None); + assert!(wrong.is_empty(), "{} of {TRIES} ExecuteIndirects ran another group count than the one written before them (try, groups): {wrong:?}", wrong.len()); + } + } + + /// Minimal RTS0 v2 root signature blob with one 4-constant parameter. + fn test_rts0_blob() -> Vec { + let words: [u32; 12] = [ + 2, 1, 24, 0, 0, 0, // version=2, num_params=1, params_offset=24 + 1, 0, 36, // param 0: type=Constants(1), visibility=0, payload_offset=36 + 0, 0, 4, // shader_reg=0, reg_space=0, num_32bit_values=4 + ]; + words.iter().flat_map(|w| w.to_le_bytes()).collect() + } + + #[test] + fn reset_and_clear_state_track_initial_pso_and_clear_root_args() { + let list = 0x7100_0001usize as *mut c_void; + let rs_compute = 0x7100_0010usize; + let rs_gfx = 0x7100_0020usize; + let alloc1 = 0x7100_0100usize; + let alloc2 = 0x7100_0200usize; + let pso_init = 0x7100_1000usize; + let pso_mid = 0x7100_2000usize; + let pso_cleared = 0x7100_3000usize; + let pso_reset = 0x7100_4000usize; + + let blob = test_rts0_blob(); + console_list::note_root_signature(rs_compute, &blob); + console_list::note_root_signature(rs_gfx, &blob); + + // Initial CreateCommandList / reset seeds PSO and allocator with clean root state. + reset(list, alloc1, pso_init); + with(list, |s| { + assert_eq!(s.pso, pso_init); + assert_eq!(s.allocator, alloc1); + assert!(s.layout.is_none() && s.args.is_empty()); + assert!(s.layout_gfx.is_none() && s.args_gfx.is_empty()); + }); + + // Populate compute + graphics root signatures, constants, and a different PSO. + unsafe { + set_compute_root_signature(list, rs_compute as *mut c_void); + set_compute_root_constant(list, 0, 0xDEAD_BEEF, 0); + set_graphics_root_signature(list, rs_gfx as *mut c_void); + set_graphics_root_constant(list, 0, 0xCAFE_BABE, 0); + } + with(list, |s| { + s.pso = pso_mid; + assert!(s.layout.is_some() && !s.args.is_empty()); + assert!(s.layout_gfx.is_some() && !s.args_gfx.is_empty()); + }); + + // ClearState(pso_cleared) updates PSO and clears root signatures/args while keeping allocator. + clear_state(list, pso_cleared); + with(list, |s| { + assert_eq!(s.pso, pso_cleared); + assert_eq!(s.allocator, alloc1); + assert!(s.layout.is_none() && s.args.is_empty()); + assert!(s.layout_gfx.is_none() && s.args_gfx.is_empty()); + }); + + // ClearState(null) clears PSO to 0. + clear_state(list, 0); + assert_eq!(tracked_pso(list), 0); + + // Re-populate root args, then Reset(alloc2, pso_reset) switches allocator/PSO and clears root args. + unsafe { + set_compute_root_signature(list, rs_compute as *mut c_void); + set_compute_root_constant(list, 0, 0x1234_5678, 0); + set_graphics_root_signature(list, rs_gfx as *mut c_void); + set_graphics_root_constant(list, 0, 0x8765_4321, 0); + } + reset(list, alloc2, pso_reset); + with(list, |s| { + assert_eq!(s.pso, pso_reset); + assert_eq!(s.allocator, alloc2); + assert!(s.layout.is_none() && s.args.is_empty()); + assert!(s.layout_gfx.is_none() && s.args_gfx.is_empty()); + }); + + // Reset with null initial PSO clears stale PSO back to 0. + reset(list, alloc2, 0); + assert_eq!(tracked_pso(list), 0); + + forget(list); + } + + fn probed_resolution( + list: usize, + original: usize, + entry: std::sync::Weak, + dropped: Arc, + ) + -> pso_async::PipelineResolution { + pso_async::pipeline_resolution_for_test(original, move || { + assert!(state_locks_available_for_test(list), "pipeline resolution dropped under bind-state locks"); + let entry = entry.upgrade().expect("old bind entry disappeared before its resolution"); + assert!(entry.state.try_lock().is_ok(), "pipeline resolution dropped under its old entry lock"); + dropped.store(true, Ordering::Release); + }) + } + + #[test] + fn pipeline_changes_retain_the_pending_they_classified() { + let list = 0x7100_4800usize as *mut c_void; + let psos = [0x7100_4810usize, 0x7100_4820, 0x7100_4830]; + for pso in psos { + pso_async::submit_lazy(pso, false, Box::new(|| { + panic!("bind-time classification ran pipeline work") + }), 0); + } + let identity = |pso| with(list, |s| { + assert_eq!(s.pso, pso); + s.resolution.as_ref().expect("registered pipeline was not classified").identity_for_test() + }); + + set_tracked_pipeline_state(list, psos[0]); + assert_eq!(identity(psos[0]), pso_async::pending_identity_for_test(psos[0]).unwrap()); + clear_state(list, psos[1]); + assert_eq!(identity(psos[1]), pso_async::pending_identity_for_test(psos[1]).unwrap()); + reset(list, 0, psos[2]); + assert_eq!(identity(psos[2]), pso_async::pending_identity_for_test(psos[2]).unwrap()); + + set_tracked_pipeline_state(list, 0x7100_4840); + with(list, |s| assert!(s.resolution.is_none(), "unregistered pipeline got a decision")); + clear_state(list, 0); + with(list, |s| assert!(s.resolution.is_none(), "null pipeline got a decision")); + + forget(list); + for pso in psos { + assert_eq!(pso_async::released(pso), 0); + } + } + + #[test] + fn pipeline_bind_retains_pending_across_real_address_reuse() { + let old_list = 0x7100_4850usize as *mut c_void; + let new_list = 0x7100_4860usize as *mut c_void; + let pso = 0x7100_4870usize; + pso_async::submit_lazy(pso, false, Box::new(|| { + panic!("old retained pipeline work ran") + }), 0); + set_tracked_pipeline_state(old_list, pso); + let old_identity = with(old_list, |s| { + s.resolution.as_ref().unwrap().identity_for_test() + }); + assert_eq!(Some(old_identity), pso_async::pending_identity_for_test(pso)); + + assert_eq!(pso_async::released(pso), 0); + assert!(pso_async::pending_identity_for_test(pso).is_none()); + pso_async::submit_lazy(pso, false, Box::new(|| { + panic!("replacement pipeline work ran") + }), 0); + let replacement_identity = pso_async::pending_identity_for_test(pso).unwrap(); + assert_ne!(replacement_identity.1, old_identity.1); + set_tracked_pipeline_state(new_list, pso); + + assert_eq!(with(old_list, |s| s.resolution.as_ref().unwrap().identity_for_test()), old_identity); + assert_eq!(with(new_list, |s| s.resolution.as_ref().unwrap().identity_for_test()), replacement_identity); + forget(old_list); + forget(new_list); + assert_eq!(pso_async::released(pso), 0); + } + + #[repr(C)] + struct ResolutionPso { + vtable: *const usize, + refs: AtomicUsize, + } + + unsafe extern "system" fn resolution_add_ref(this: *mut c_void) -> u32 { + (*(this as *mut ResolutionPso)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 + } + + unsafe extern "system" fn resolution_release(this: *mut c_void) -> u32 { + (*(this as *mut ResolutionPso)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 + } + + #[test] + fn graphics_resolution_uses_retained_identity_and_records_its_pin() { + let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; + let mut old = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let old_raw = &mut old as *mut ResolutionPso as usize; + let replacement_raw = &mut replacement as *mut ResolutionPso as usize; + let standin = 0x7100_4880usize; + let list = 0x7100_4890usize; + pso_async::submit_lazy(standin, false, Box::new(move || old_raw), 0); + assert_eq!(pso_async::resolve_wait(standin), old_raw); + let retained = pso_async::begin_pipeline_resolution(standin).unwrap(); + assert_eq!(pso_async::released(standin), old_raw); + pso_async::submit_lazy(standin, false, Box::new(move || replacement_raw), 0); + + assert_eq!(resolve_pipeline(list, standin, Some(retained)), Some(old_raw)); + assert_eq!(list_x::native_generation_count_for_test(list), 1); + assert_eq!(replacement.refs.load(Ordering::Relaxed), 1, "the reused registry address must not be resolved"); + + list_x::clear_segment_state(list); + assert_eq!(pso_async::released(standin), 0); + assert_eq!(unsafe { resolution_release(old_raw as *mut c_void) }, 0); + assert_eq!(unsafe { resolution_release(replacement_raw as *mut c_void) }, 0); + } + + #[test] + fn graphics_entrypoints_pass_the_retained_raw_to_the_abi() { + let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fake_add_ref as usize; + orig_vt[2] = fake_release as usize; + orig_vt[25] = fake_set_pso as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let fake = Box::new(FakeAdoptedList { + vt: unsafe { ext_vt.as_ptr().add(1) }, refs: AtomicUsize::new(1), + dispatch_calls: AtomicUsize::new(0), set_compute_rs_calls: AtomicUsize::new(0), + set_compute_uav_calls: AtomicUsize::new(0), set_pso_calls: AtomicUsize::new(0), + last_pso: AtomicUsize::new(0), execute_indirect_calls: AtomicUsize::new(0), + }); + let list = &*fake as *const FakeAdoptedList as *mut c_void; + let _class = real::test_command_list_class( + orig_vt.as_ptr() as usize, + unsafe { ext_vt.as_ptr().add(1) } as usize, + ); + let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; + let mut old = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut selected_alias = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let old_raw = &mut old as *mut ResolutionPso as usize; + let replacement_raw = &mut replacement as *mut ResolutionPso as usize; + let selected_alias_raw = &mut selected_alias as *mut ResolutionPso as usize; + let standin = 0x7100_4898usize; + pso_async::submit_lazy(standin, false, Box::new(move || old_raw), 0); + assert_eq!(pso_async::resolve_wait(standin), old_raw); + real::register_translated_graphics_for_test(old_raw); + unsafe { list_x::on_create(list, 0, standin, D3D12_COMMAND_LIST_TYPE_DIRECT) }; + set_tracked_pipeline_state(list, standin); + assert_eq!(pso_async::released(standin), old_raw); + pso_async::submit_lazy(standin, false, Box::new(move || replacement_raw), 0); + let alias_calls = Arc::new(AtomicUsize::new(0)); + let selected_calls = alias_calls.clone(); + pso_async::submit_lazy(old_raw, false, Box::new(move || { + selected_calls.fetch_add(1, Ordering::Relaxed); + selected_alias_raw + }), 0); + STOP_ABI_AFTER_BIND_LIST.store(list as usize, Ordering::Release); + + LAST_ABI_PSO.store(0, Ordering::Release); + assert!(unsafe { graphics_bound(list) }.is_none()); + assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), old_raw); + LAST_ABI_PSO.store(0, Ordering::Release); + assert!(unsafe { prepare_indexed_draw(list, 3, 1, 0, 0) }.is_none()); + assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), old_raw, + "indexed draw must reuse the retained generation, not the title or replacement address"); + assert_eq!(fake.last_pso.load(Ordering::Acquire), old_raw); + assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 2); + assert_eq!(alias_calls.load(Ordering::Relaxed), 0, "graphics ABI bind ran selected raw's alias build"); + assert_eq!(list_x::bound_pipeline_for_test(list as usize), standin, + "graphics ABI bind replaced title-visible pipeline state"); + + STOP_ABI_AFTER_BIND_LIST.store(0, Ordering::Release); + forget(list); + list_x::clear_segment_state(list as usize); + list_x::on_release(list as usize); + assert_eq!(pso_async::released(standin), 0); + assert_eq!(pso_async::released(old_raw), 0); + real::forget_pso_for_test(old_raw); + assert_eq!(unsafe { resolution_release(old_raw as *mut c_void) }, 0); + assert_eq!(unsafe { resolution_release(replacement_raw as *mut c_void) }, 0); + assert_eq!(unsafe { resolution_release(selected_alias_raw as *mut c_void) }, 0); + } + + #[test] + fn dispatch_entrypoint_uses_the_retained_generation_after_address_reuse() { + let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); + let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; + let list_object = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let list = &list_object as *const ResolutionPso as *mut c_void; + let mut original = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let original_raw = &mut original as *mut ResolutionPso as usize; + let replacement_raw = &mut replacement as *mut ResolutionPso as usize; + let standin = 0x7100_489Cusize; + + pso_async::submit_lazy(standin, true, Box::new(move || original_raw), 0); + assert_eq!(pso_async::resolve_wait(standin), original_raw); + real::register_translated_compute_for_test(original_raw); + set_tracked_pipeline_state(list, standin); + let original_owner = pso_async::released(standin); + assert_eq!(original_owner, original_raw); + + let replacement_calls = Arc::new(AtomicUsize::new(0)); + let replacement_build_calls = replacement_calls.clone(); + pso_async::submit_lazy(standin, true, Box::new(move || { + replacement_build_calls.fetch_add(1, Ordering::Relaxed); + replacement_raw + }), 0); + STOP_ABI_LIST.store(list as usize, Ordering::Release); + for _ in 0..2 { + LAST_ABI_PSO.store(0, Ordering::Release); + unsafe { dispatch_flags(list, 1, 1, 1, 0) }; + assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), original_raw); + } + assert_eq!(replacement_calls.load(Ordering::Relaxed), 0, "Dispatch ran the replacement build"); + assert_eq!(replacement.refs.load(Ordering::Relaxed), 1, "Dispatch retained the replacement generation"); + assert_eq!(list_x::native_generation_count_for_test(list as usize), 1, "repeated Dispatch duplicated its exact pin"); + + STOP_ABI_LIST.store(0, Ordering::Release); + forget(list); + list_x::clear_segment_state(list as usize); + assert_eq!(pso_async::released(standin), 0); + real::forget_pso_for_test(original_raw); + assert_eq!(unsafe { resolution_release(original_owner as *mut c_void) }, 0); + assert_eq!(unsafe { resolution_release(replacement_raw as *mut c_void) }, 0); + } + + #[test] + fn execute_indirect_uses_retained_generation_after_address_reuse() { + let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fake_add_ref as usize; + orig_vt[2] = fake_release as usize; + orig_vt[25] = fake_set_pso as usize; + orig_vt[59] = fake_execute_indirect as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let fake = Box::new(FakeAdoptedList { + vt: unsafe { ext_vt.as_ptr().add(1) }, refs: AtomicUsize::new(1), + dispatch_calls: AtomicUsize::new(0), set_compute_rs_calls: AtomicUsize::new(0), + set_compute_uav_calls: AtomicUsize::new(0), set_pso_calls: AtomicUsize::new(0), + last_pso: AtomicUsize::new(0), execute_indirect_calls: AtomicUsize::new(0), + }); + let list = &*fake as *const FakeAdoptedList as *mut c_void; + let _class = real::test_command_list_class( + orig_vt.as_ptr() as usize, + unsafe { ext_vt.as_ptr().add(1) } as usize, + ); + let pso_vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; + let mut original = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut selected_alias = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let original_raw = &mut original as *mut ResolutionPso as usize; + let replacement_raw = &mut replacement as *mut ResolutionPso as usize; + let selected_alias_raw = &mut selected_alias as *mut ResolutionPso as usize; + let standin = 0x7100_48B0usize; + let signature = IndirectSignatureInfo::new(true, false, None); + + pso_async::submit_lazy(standin, true, Box::new(move || original_raw), 0); + assert_eq!(pso_async::resolve_wait(standin), original_raw); + real::register_translated_compute_for_test(original_raw); + unsafe { list_x::on_create(list, 0, standin, D3D12_COMMAND_LIST_TYPE_DIRECT) }; + set_tracked_pipeline_state(list, standin); + let original_owner = pso_async::released(standin); + let replacement_calls = Arc::new(AtomicUsize::new(0)); + let calls = replacement_calls.clone(); + pso_async::submit_lazy(standin, true, Box::new(move || { + calls.fetch_add(1, Ordering::Relaxed); + replacement_raw + }), 0); + let alias_calls = Arc::new(AtomicUsize::new(0)); + let selected_calls = alias_calls.clone(); + pso_async::submit_lazy(original_raw, true, Box::new(move || { + selected_calls.fetch_add(1, Ordering::Relaxed); + selected_alias_raw + }), 0); + STOP_ABI_AFTER_BIND_LIST.store(list as usize, Ordering::Release); + for _ in 0..2 { + LAST_ABI_PSO.store(0, Ordering::Release); + unsafe { execute_indirect_classified(list, 1, 1, 0, 0, 0, 0, signature) }; + assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), original_raw); + assert_eq!(fake.last_pso.load(Ordering::Acquire), original_raw, + "selected raw was redirected through its registry alias at native bind"); + } + assert_eq!(replacement_calls.load(Ordering::Relaxed), 0, "ExecuteIndirect ran a replacement build at the reused title address"); + assert_eq!(alias_calls.load(Ordering::Relaxed), 0, "ExecuteIndirect ran the selected raw's alias build"); + assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 2); + assert_eq!(list_x::bound_pipeline_for_test(list as usize), standin, + "exact internal bind replaced title-visible pipeline state"); + assert_eq!(list_x::native_generation_count_for_test(list as usize), 1, "repeated ExecuteIndirect duplicated its exact pin"); + + STOP_ABI_AFTER_BIND_LIST.store(0, Ordering::Release); + forget(list); + list_x::clear_segment_state(list as usize); + list_x::on_release(list as usize); + assert_eq!(pso_async::released(standin), 0); + assert_eq!(pso_async::released(original_raw), 0); + real::forget_pso_for_test(original_raw); + assert_eq!(unsafe { resolution_release(original_owner as *mut c_void) }, 0); + assert_eq!(unsafe { resolution_release(replacement_raw as *mut c_void) }, 0); + assert_eq!(unsafe { resolution_release(selected_alias_raw as *mut c_void) }, 0); + } + + #[test] + fn execute_indirect_native_snapshot_ignores_a_later_registry_alias() { + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fake_add_ref as usize; + orig_vt[2] = fake_release as usize; + orig_vt[30] = fake_noop_ptr as usize; // SetGraphicsRootSignature + orig_vt[59] = fake_execute_indirect as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let fake = Box::new(FakeAdoptedList { + vt: unsafe { ext_vt.as_ptr().add(1) }, refs: AtomicUsize::new(1), + dispatch_calls: AtomicUsize::new(0), set_compute_rs_calls: AtomicUsize::new(0), + set_compute_uav_calls: AtomicUsize::new(0), set_pso_calls: AtomicUsize::new(0), + last_pso: AtomicUsize::new(0), execute_indirect_calls: AtomicUsize::new(0), + }); + let list = &*fake as *const FakeAdoptedList as *mut c_void; + let native = 0x7100_48B2usize; + reset(list, 0, native); + // a PC pipeline's indirect draw needs the title's graphics root signature (else skipped) + unsafe { set_graphics_root_signature(list, 0x7100_48B4usize as *mut c_void) }; + let build_calls = Arc::new(AtomicUsize::new(0)); + let calls = build_calls.clone(); + pso_async::submit_lazy(native, true, Box::new(move || { + calls.fetch_add(1, Ordering::Relaxed); + 0x7100_48B3 + }), 0); + + unsafe { execute_indirect_classified(list, 1, 1, 0, 0, 0, 0, IndirectSignatureInfo::default()) }; + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 1); + assert_eq!(build_calls.load(Ordering::Relaxed), 0, "native ExecuteIndirect re-resolved its raw address through the registry"); + assert_eq!(list_x::native_generation_count_for_test(list as usize), 0); + + forget(list); + let _ = pso_async::released(native); + } + + #[test] + fn deferred_execute_indirect_replays_its_inherited_resolution_once() { + let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fake_add_ref as usize; + orig_vt[2] = fake_release as usize; + orig_vt[59] = fake_execute_indirect as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let make_list = || Box::new(FakeAdoptedList { + vt: unsafe { ext_vt.as_ptr().add(1) }, refs: AtomicUsize::new(1), + dispatch_calls: AtomicUsize::new(0), set_compute_rs_calls: AtomicUsize::new(0), + set_compute_uav_calls: AtomicUsize::new(0), set_pso_calls: AtomicUsize::new(0), + last_pso: AtomicUsize::new(0), execute_indirect_calls: AtomicUsize::new(0), + }); + let source_object = make_list(); + let replay_object = make_list(); + let source = &*source_object as *const FakeAdoptedList as *mut c_void; + let replay = &*replay_object as *const FakeAdoptedList as *mut c_void; + let pso_vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; + let mut old = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let old_raw = &mut old as *mut ResolutionPso as usize; + let replacement_raw = &mut replacement as *mut ResolutionPso as usize; + let standin = 0x7100_48B4usize; + + pso_async::submit_lazy(standin, true, Box::new(move || old_raw), 0); + assert_eq!(pso_async::resolve_wait(standin), old_raw); + real::register_translated_compute_for_test(old_raw); + set_tracked_pipeline_state(source, standin); + let (inherited_pso, inherited_resolution) = with(source, |state| { + (state.pso, state.resolution.clone()) + }); + with(replay, |state| { + state.pso = inherited_pso; + state.resolution = inherited_resolution; + }); + + let old_owner = pso_async::released(standin); + pso_async::submit_lazy(standin, true, Box::new(move || replacement_raw), 0); + set_tracked_pipeline_state(source, standin); + STOP_ABI_LIST.store(replay as usize, Ordering::Release); + LAST_ABI_PSO.store(0, Ordering::Release); + unsafe { + execute_indirect_retained( + replay, 1, 1, 0, 0, 0, 0, IndirectSignatureInfo::new(true, false, None), + ) + }; + assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), old_raw); + assert_eq!(list_x::native_generation_count_for_test(replay as usize), 1); + assert_eq!(list_x::native_generation_count_for_test(source as usize), 0, + "deferred replay recursively split or pinned the source segment"); + assert_eq!(replacement.refs.load(Ordering::Relaxed), 1, + "deferred replay resolved the replacement generation"); + + STOP_ABI_LIST.store(0, Ordering::Release); + forget(source); + forget(replay); + list_x::clear_segment_state(replay as usize); + assert_eq!(pso_async::released(standin), 0); + real::forget_pso_for_test(old_raw); + assert_eq!(unsafe { resolution_release(old_owner as *mut c_void) }, 0); + assert_eq!(unsafe { resolution_release(replacement_raw as *mut c_void) }, 0); + } + + #[test] + fn unavailable_execute_indirect_counts_one_signature_selected_skip() { + let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fake_add_ref as usize; + orig_vt[2] = fake_release as usize; + orig_vt[59] = fake_execute_indirect as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let fake = Box::new(FakeAdoptedList { + vt: unsafe { ext_vt.as_ptr().add(1) }, refs: AtomicUsize::new(1), + dispatch_calls: AtomicUsize::new(0), set_compute_rs_calls: AtomicUsize::new(0), + set_compute_uav_calls: AtomicUsize::new(0), set_pso_calls: AtomicUsize::new(0), + last_pso: AtomicUsize::new(0), execute_indirect_calls: AtomicUsize::new(0), + }); + let list = &*fake as *const FakeAdoptedList as *mut c_void; + STOP_ABI_LIST.store(list as usize, Ordering::Release); + LAST_ABI_PSO.store(0, Ordering::Release); + let _ = take_indirect_skip_counts(); + + let compute = pso_async::pipeline_resolution_for_compute_test(0x7100_48B6, || {}); + with(list, |state| { + state.pso = 0x7100_48B6; + state.resolution = Some(compute.unavailable_for_test()); + }); + unsafe { + execute_indirect_retained( + list, 1, 1, 0, 0, 0, 0, IndirectSignatureInfo::new(true, false, None), + ) + }; + assert_eq!(take_indirect_skip_counts(), [0, 1]); + + let graphics = pso_async::pipeline_resolution_for_test(0x7100_48B7, || {}); + with(list, |state| { + state.pso = 0x7100_48B7; + state.resolution = Some(graphics.unavailable_for_test()); + }); + unsafe { + execute_indirect_retained(list, 1, 1, 0, 0, 0, 0, IndirectSignatureInfo::default()) + }; + assert_eq!(take_indirect_skip_counts(), [1, 0]); + assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), 0, "unavailable resolution reached ABI binding"); + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0, "unavailable resolution reached PC ExecuteIndirect"); + assert_eq!(list_x::native_generation_count_for_test(list as usize), 0); + + STOP_ABI_LIST.store(0, Ordering::Release); + forget(list); + } + + #[test] + fn dispatch_waits_outside_states_and_selects_the_build_once() { + let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); + let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; + let list_object = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let list = &list_object as *const ResolutionPso as *mut c_void; + let mut native = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut ResolutionPso as usize; + let standin = 0x7100_489Dusize; + let list_key = list as usize; + let calls = Arc::new(AtomicUsize::new(0)); + let build_calls = calls.clone(); + pso_async::submit_lazy(standin, true, Box::new(move || { + assert!(state_locks_available_for_test(list_key), "Dispatch waited for its build under bind-state locks"); + build_calls.fetch_add(1, Ordering::Relaxed); + real::register_translated_compute_for_test(raw); + raw + }), 0); + set_tracked_pipeline_state(list, standin); + STOP_ABI_LIST.store(list as usize, Ordering::Release); + + LAST_ABI_PSO.store(0, Ordering::Release); + unsafe { dispatch_flags(list, 1, 1, 1, 0) }; + assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), raw); + LAST_ABI_PSO.store(0, Ordering::Release); + unsafe { dispatch_flags(list, 1, 1, 1, 0) }; + assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), raw); + assert_eq!(calls.load(Ordering::Relaxed), 1, "repeated Dispatch consumed the build more than once"); + assert_eq!(list_x::native_generation_count_for_test(list as usize), 1); + + STOP_ABI_LIST.store(0, Ordering::Release); + forget(list); + list_x::clear_segment_state(list as usize); + let raw_owner = pso_async::released(standin); + real::forget_pso_for_test(raw); + assert_eq!(unsafe { resolution_release(raw_owner as *mut c_void) }, 0); + } + + #[test] + fn exact_compute_bind_bypasses_a_registry_alias_and_preserves_title_state() { + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fake_add_ref as usize; + orig_vt[2] = fake_release as usize; + orig_vt[25] = fake_set_pso as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let fake = Box::new(FakeAdoptedList { + vt: unsafe { ext_vt.as_ptr().add(1) }, + refs: AtomicUsize::new(1), + dispatch_calls: AtomicUsize::new(0), + set_compute_rs_calls: AtomicUsize::new(0), + set_compute_uav_calls: AtomicUsize::new(0), + set_pso_calls: AtomicUsize::new(0), + last_pso: AtomicUsize::new(0), + execute_indirect_calls: AtomicUsize::new(0), + }); + let list = &*fake as *const FakeAdoptedList as *mut c_void; + let _class = real::test_command_list_class( + orig_vt.as_ptr() as usize, + unsafe { ext_vt.as_ptr().add(1) } as usize, + ); + let original = 0x7100_489Eusize; + let exact_raw = 0x7100_489Fusize; + let replacement = 0x7100_48A1usize; + unsafe { list_x::on_set_pipeline_state(list, original) }; + assert_eq!(list_x::bound_pipeline_for_test(list as usize), original); + pso_async::submit_lazy(exact_raw, false, Box::new(move || replacement), 0); + assert_eq!(pso_async::resolve_wait(exact_raw), replacement); + + unsafe { real::bind_pipeline_exact(list, original, exact_raw) }; + assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 1); + assert_eq!(fake.last_pso.load(Ordering::Acquire), exact_raw, "exact raw was re-resolved through its alias"); + assert_eq!(list_x::bound_pipeline_for_test(list as usize), original, "internal compute bind replaced title-visible state"); + assert_eq!(list_x::native_generation_count_for_test(list as usize), 0, "internal exact bind pinned the alias generation"); + + assert_eq!(pso_async::released(exact_raw), replacement); + list_x::on_release(list as usize); + } + + #[test] + fn graphics_resolution_waits_outside_states_and_selects_only_once() { + let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; + let mut real = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut real as *mut ResolutionPso as usize; + let standin = 0x7100_48A0usize; + let list = 0x7100_48B0usize as *mut c_void; + let list_key = list as usize; + let calls = Arc::new(AtomicUsize::new(0)); + let build_calls = calls.clone(); + pso_async::submit_recipe_keyed(standin, false, pso_async::Recipe::new(move || { + assert!(state_locks_available_for_test(list_key), "pipeline build waited under bind-state locks"); + build_calls.fetch_add(1, Ordering::Relaxed); + raw + }), false, 0, None); + set_tracked_pipeline_state(list, standin); + + assert_eq!(resolve_bound_graphics_pipeline(list, list as usize), Some((standin, raw))); + assert_eq!(calls.load(Ordering::Relaxed), 1); + assert!(cpu_rect_expansion(raw)); + assert_eq!(calls.load(Ordering::Relaxed), 1, "downstream draw decisions must reuse the selected raw PSO"); + + forget(list); + list_x::clear_segment_state(list as usize); + assert_eq!(pso_async::released(standin), raw); + assert_eq!(unsafe { resolution_release(raw as *mut c_void) }, 0); } #[test] - fn reset_and_clear_state_track_initial_pso_and_clear_root_args() { - let list = 0x7100_0001usize as *mut c_void; - let rs_compute = 0x7100_0010usize; - let rs_gfx = 0x7100_0020usize; - let alloc1 = 0x7100_0100usize; - let alloc2 = 0x7100_0200usize; - let pso_init = 0x7100_1000usize; - let pso_mid = 0x7100_2000usize; - let pso_cleared = 0x7100_3000usize; - let pso_reset = 0x7100_4000usize; + fn graphics_resolution_pins_one_shot_and_fails_closed_when_unavailable() { + let one_shot = 0x7100_48C0usize; + let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; + let mut real = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let one_shot_real = &mut real as *mut ResolutionPso as usize; + let calls = Arc::new(AtomicUsize::new(0)); + let build_calls = calls.clone(); + pso_async::submit_lazy(one_shot, false, Box::new(move || { + build_calls.fetch_add(1, Ordering::Relaxed); + one_shot_real + }), 0); + let retained = pso_async::begin_pipeline_resolution(one_shot).unwrap(); + let list = 0x7100_48E0; + assert_eq!(resolve_pipeline(list, one_shot, Some(retained.clone())), Some(one_shot_real)); + assert_eq!(resolve_pipeline(list, one_shot, Some(retained)), Some(one_shot_real)); + assert_eq!(calls.load(Ordering::Relaxed), 1, "one-shot build must be consumed once"); + assert_eq!(list_x::native_generation_count_for_test(list), 1); + assert_eq!(real.refs.load(Ordering::Relaxed), 2, "repeated draws retained more than one COM owner"); + assert_eq!(pso_async::released(one_shot), one_shot_real); + list_x::clear_segment_state(list); + assert_eq!(unsafe { resolution_release(one_shot_real as *mut c_void) }, 0); - let blob = test_rts0_blob(); - console_list::note_root_signature(rs_compute, &blob); - console_list::note_root_signature(rs_gfx, &blob); + let failed = 0x7100_48E8usize; + pso_async::submit_lazy(failed, false, Box::new(|| 0), 0); + let retained = pso_async::begin_pipeline_resolution(failed).unwrap(); + assert_eq!(resolve_pipeline(0x7100_48E9, failed, Some(retained)), None); + assert_eq!(pso_async::released(failed), 0); - // Initial CreateCommandList / reset seeds PSO and allocator with clean root state. - reset(list, alloc1, pso_init); - with(list, |s| { - assert_eq!(s.pso, pso_init); - assert_eq!(s.allocator, alloc1); - assert!(s.layout.is_none() && s.args.is_empty()); - assert!(s.layout_gfx.is_none() && s.args_gfx.is_empty()); - }); + let unavailable = 0x7100_48F0usize; + pso_async::submit_recipe_keyed(unavailable, false, pso_async::Recipe::new(|| panic!("orphan recipe ran")), false, 0, None); + let retained = pso_async::begin_pipeline_resolution(unavailable).unwrap(); + assert_eq!(pso_async::released(unavailable), 0); + assert_eq!(resolve_pipeline(0x7100_4900, unavailable, Some(retained)), None); - // Populate compute + graphics root signatures, constants, and a different PSO. - unsafe { - set_compute_root_signature(list, rs_compute as *mut c_void); - set_compute_root_constant(list, 0, 0xDEAD_BEEF, 0); - set_graphics_root_signature(list, rs_gfx as *mut c_void); - set_graphics_root_constant(list, 0, 0xCAFE_BABE, 0); + let replacement = 0x7100_4910usize; + pso_async::submit_lazy(replacement, false, Box::new(|| panic!("unregistered bind adopted later registry entry")), 0); + assert_eq!(resolve_pipeline(0, replacement, None), Some(replacement)); + assert_eq!(pso_async::released(replacement), 0); + } + + #[test] + fn pipeline_resolution_replacements_drop_outside_state_lock() { + let cases: [fn(*mut c_void); 4] = [ + |list| clear_state(list, 0x7100_5001), + |list| reset(list, 0, 0x7100_5002), + |list| set_tracked_pipeline_state(list, 0x7100_5003), + forget, + ]; + for (n, replace) in cases.into_iter().enumerate() { + let list = (0x7100_5100usize + n) as *mut c_void; + let dropped = Arc::new(AtomicBool::new(false)); + with(list, |_| {}); + let old_entry = STATES.get(list as usize).unwrap(); + let resolution = probed_resolution( + list as usize, + 0x7100_5200 + n, + Arc::downgrade(&old_entry), + dropped.clone(), + ); + with(list, |s| s.resolution = Some(resolution)); + replace(list); + assert!(dropped.load(Ordering::Acquire), "case {n} retained the replaced resolution"); + drop(old_entry); + if n + 1 != cases.len() { + forget(list); + } } - with(list, |s| { - s.pso = pso_mid; - assert!(s.layout.is_some() && !s.args.is_empty()); - assert!(s.layout_gfx.is_some() && !s.args_gfx.is_empty()); - }); + } - // ClearState(pso_cleared) updates PSO and clears root signatures/args while keeping allocator. - clear_state(list, pso_cleared); - with(list, |s| { - assert_eq!(s.pso, pso_cleared); - assert_eq!(s.allocator, alloc1); - assert!(s.layout.is_none() && s.args.is_empty()); - assert!(s.layout_gfx.is_none() && s.args_gfx.is_empty()); + #[test] + fn split_retains_the_exact_resolution_across_address_reuse() { + let from = 0x7100_6001usize as *mut c_void; + let to = 0x7100_6002usize as *mut c_void; + let original = 0x7100_6100usize; + let old = pso_async::pipeline_resolution_for_test(original, || {}); + let old_identity = old.identity_for_test(); + with(from, |s| { + s.pso = original; + s.resolution = Some(old); }); + reset(to, 0, 0); - // ClearState(null) clears PSO to 0. - clear_state(list, 0); - assert_eq!(tracked_pso(list), 0); + let prepared = prepare_split(from, to, 0); + let replacement = pso_async::pipeline_resolution_for_test(original, || {}); + let replacement_identity = replacement.identity_for_test(); + assert_ne!(old_identity.1, replacement_identity.1); + with(from, |s| s.resolution = Some(replacement)); + install_prepared_split(prepared); - // Re-populate root args, then Reset(alloc2, pso_reset) switches allocator/PSO and clears root args. - unsafe { - set_compute_root_signature(list, rs_compute as *mut c_void); - set_compute_root_constant(list, 0, 0x1234_5678, 0); - set_graphics_root_signature(list, rs_gfx as *mut c_void); - set_graphics_root_constant(list, 0, 0x8765_4321, 0); - } - reset(list, alloc2, pso_reset); - with(list, |s| { - assert_eq!(s.pso, pso_reset); - assert_eq!(s.allocator, alloc2); - assert!(s.layout.is_none() && s.args.is_empty()); - assert!(s.layout_gfx.is_none() && s.args_gfx.is_empty()); - }); + assert_eq!(with(to, |s| s.resolution.as_ref().unwrap().identity_for_test()), old_identity, + "split state was redirected to the Pending now stored at the reused title address"); + assert_eq!(with(from, |s| s.resolution.as_ref().unwrap().identity_for_test()), replacement_identity); + forget(from); + forget(to); + } - // Reset with null initial PSO clears stale PSO back to 0. - reset(list, alloc2, 0); - assert_eq!(tracked_pso(list), 0); + #[test] + fn split_reset_uses_only_an_owned_ready_generation() { + let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; + let mut native = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut ResolutionPso as usize; + let standin = 0x7100_6200usize; + let from = 0x7100_6201usize as *mut c_void; + let to = 0x7100_6202usize as *mut c_void; + pso_async::submit_lazy(standin, false, Box::new(move || raw), 0); + assert_eq!(pso_async::resolve_wait(standin), raw); + set_tracked_pipeline_state(from, standin); + reset(to, 0, 0); + let prepared = prepare_split(from, to, 0); + let (initial, pin) = prepared.initial_pipeline(); + assert_eq!(initial, raw); + assert!(pin.is_some(), "ready split initial pipeline has no exact owner"); + drop(pin); drop(prepared); forget(from); forget(to); + let raw_owner = pso_async::released(standin); + assert_eq!(raw_owner, raw); + assert_eq!(unsafe { resolution_release(raw_owner as *mut c_void) }, 0); - forget(list); + let pending = 0x7100_6210usize; + let from = 0x7100_6211usize as *mut c_void; + let to = 0x7100_6212usize as *mut c_void; + pso_async::submit_lazy(pending, false, Box::new(|| panic!("split Reset started pending build")), 0); + set_tracked_pipeline_state(from, pending); + reset(to, 0, 0); + let prepared = prepare_split(from, to, 0); + assert!(matches!(prepared.initial_pipeline(), (0, None)), "pending split consulted its reusable address"); + drop(prepared); forget(from); forget(to); + assert_eq!(pso_async::released(pending), 0); } - fn probed_resolution( - list: usize, - original: usize, - entry: std::sync::Weak, - dropped: Arc, - ) - -> pso_async::PipelineResolution { - pso_async::pipeline_resolution_for_test(original, move || { - assert!(state_locks_available_for_test(list), "pipeline resolution dropped under bind-state locks"); - let entry = entry.upgrade().expect("old bind entry disappeared before its resolution"); - assert!(entry.state.try_lock().is_ok(), "pipeline resolution dropped under its old entry lock"); - dropped.store(true, Ordering::Release); - }) + #[test] + fn kickoff_reset_uses_the_retained_generation_after_address_reuse() { + let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; + let mut original = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let original_raw = &mut original as *mut ResolutionPso as usize; + let replacement_raw = &mut replacement as *mut ResolutionPso as usize; + let standin = 0x7100_6220usize; + let list = 0x7100_6221usize as *mut c_void; + + pso_async::submit_lazy(standin, false, Box::new(move || original_raw), 0); + assert_eq!(pso_async::resolve_wait(standin), original_raw); + set_tracked_pipeline_state(list, standin); + let original_owner = pso_async::released(standin); + assert_eq!(original_owner, original_raw); + + pso_async::submit_lazy(standin, false, Box::new(move || replacement_raw), 0); + assert_eq!(pso_async::resolve_wait(standin), replacement_raw); + let (initial, pin) = initial_pipeline(list); + assert_eq!(initial, original_raw, "Kickoff Reset followed the reused title address"); + assert!(pin.is_some(), "Kickoff Reset did not own the retained generation"); + assert_eq!(replacement.refs.load(Ordering::Relaxed), 1, "Kickoff Reset retained the replacement generation"); + + let replacement_owner = pso_async::released(standin); + assert_eq!(replacement_owner, replacement_raw); + drop(pin); + forget(list); + assert_eq!(unsafe { resolution_release(original_owner as *mut c_void) }, 0); + assert_eq!(unsafe { resolution_release(replacement_owner as *mut c_void) }, 0); } #[test] - fn pipeline_changes_retain_the_pending_they_classified() { - let list = 0x7100_4800usize as *mut c_void; - let psos = [0x7100_4810usize, 0x7100_4820, 0x7100_4830]; - for pso in psos { - pso_async::submit_lazy(pso, false, Box::new(|| { - panic!("bind-time classification ran pipeline work") - }), 0); - } - let identity = |pso| with(list, |s| { - assert_eq!(s.pso, pso); - s.resolution.as_ref().expect("registered pipeline was not classified").identity_for_test() - }); + fn split_preflight_transfers_destination_uma_before_install() { + let from = 0x7101_0001usize as *mut c_void; + let to = 0x7101_0002usize as *mut c_void; + let (old_alloc, new_alloc) = (0x7101_0100usize, 0x7101_0200usize); + let _ = console_list::take_pending_for_test(old_alloc); + seed_reset_state_for_test(from, 0x7101_0300, 0x7101_1000, vec![0x7101_4000]); + seed_reset_state_for_test(to, old_alloc, 0x7101_2000, vec![0x7101_5000, 0x7101_6000]); + + let prepared = prepare_split(from, to, new_alloc); + assert_eq!(reset_state_for_test(from), (0x7101_0300, 0x7101_1000, vec![1, 2, 3, 4], vec![5, 6, 7, 8], vec![0x7101_4000])); + assert_eq!(reset_state_for_test(to), (0, 0x7101_2000, vec![1, 2, 3, 4], vec![5, 6, 7, 8], Vec::new())); + + install_prepared_split(prepared); + assert_eq!(reset_state_for_test(to), (new_alloc, 0x7101_1000, vec![1, 2, 3, 4], vec![5, 6, 7, 8], Vec::new())); + assert_eq!(console_list::take_pending_for_test(old_alloc), vec![0x7101_5000, 0x7101_6000]); + remove_state_for_test(from); + remove_state_for_test(to); + } - set_tracked_pipeline_state(list, psos[0]); - assert_eq!(identity(psos[0]), pso_async::pending_identity_for_test(psos[0]).unwrap()); - clear_state(list, psos[1]); - assert_eq!(identity(psos[1]), pso_async::pending_identity_for_test(psos[1]).unwrap()); - reset(list, 0, psos[2]); - assert_eq!(identity(psos[2]), pso_async::pending_identity_for_test(psos[2]).unwrap()); + #[test] + fn reset_keys_uma_to_the_lists_native_allocator_backing() { + let list = 0x7101_7001usize as *mut c_void; + let (logical, native, old_native, block) = (0x7101_7100usize, 0x7101_7200usize, 0x7101_7300usize, 0x7101_7400usize); + let _ = console_list::take_pending_for_test(old_native); + super::super::alloc_pool::created_on(list as usize, native, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + seed_reset_state_for_test(list, old_native, 0, vec![block]); - set_tracked_pipeline_state(list, 0x7100_4840); - with(list, |s| assert!(s.resolution.is_none(), "unregistered pipeline got a decision")); - clear_state(list, 0); - with(list, |s| assert!(s.resolution.is_none(), "null pipeline got a decision")); + reset(list, logical, 0); - forget(list); - for pso in psos { - assert_eq!(pso_async::released(pso), 0); - } + assert_eq!(reset_state_for_test(list).0, native, + "UMA ownership follows the recording's native backing, not the title allocator"); + assert_eq!(console_list::take_pending_for_test(old_native), vec![block]); + remove_state_for_test(list); + super::super::alloc_pool::forget_list(list as usize); + unsafe { super::super::alloc_pool::forget(native); } } #[test] - fn pipeline_bind_retains_pending_across_real_address_reuse() { - let old_list = 0x7100_4850usize as *mut c_void; - let new_list = 0x7100_4860usize as *mut c_void; - let pso = 0x7100_4870usize; - pso_async::submit_lazy(pso, false, Box::new(|| { - panic!("old retained pipeline work ran") - }), 0); - set_tracked_pipeline_state(old_list, pso); - let old_identity = with(old_list, |s| { - s.resolution.as_ref().unwrap().identity_for_test() - }); - assert_eq!(Some(old_identity), pso_async::pending_identity_for_test(pso)); + fn abandoned_split_preflight_keeps_old_uma_under_its_allocator() { + let from = 0x7102_0001usize as *mut c_void; + let to = 0x7102_0002usize as *mut c_void; + let old_alloc = 0x7102_0100usize; + let _ = console_list::take_pending_for_test(old_alloc); + seed_reset_state_for_test(from, 0x7102_0200, 0x7102_1000, Vec::new()); + seed_reset_state_for_test(to, old_alloc, 0x7102_2000, vec![0x7102_5000]); - assert_eq!(pso_async::released(pso), 0); - assert!(pso_async::pending_identity_for_test(pso).is_none()); - pso_async::submit_lazy(pso, false, Box::new(|| { - panic!("replacement pipeline work ran") - }), 0); - let replacement_identity = pso_async::pending_identity_for_test(pso).unwrap(); - assert_ne!(replacement_identity.1, old_identity.1); - set_tracked_pipeline_state(new_list, pso); + drop(prepare_split(from, to, 0x7102_0300)); + forget(to); - assert_eq!(with(old_list, |s| s.resolution.as_ref().unwrap().identity_for_test()), old_identity); - assert_eq!(with(new_list, |s| s.resolution.as_ref().unwrap().identity_for_test()), replacement_identity); - forget(old_list); - forget(new_list); - assert_eq!(pso_async::released(pso), 0); + assert_eq!(console_list::take_pending_for_test(old_alloc), vec![0x7102_5000]); + assert_eq!(reset_state_for_test(from).0, 0x7102_0200, "the active producer must remain untouched"); + remove_state_for_test(from); } #[repr(C)] - struct ResolutionPso { - vtable: *const usize, + struct FakeAdoptedList { + vt: *const usize, refs: AtomicUsize, + dispatch_calls: AtomicUsize, + set_compute_rs_calls: AtomicUsize, + set_compute_uav_calls: AtomicUsize, + set_pso_calls: AtomicUsize, + last_pso: AtomicUsize, + execute_indirect_calls: AtomicUsize, } - unsafe extern "system" fn resolution_add_ref(this: *mut c_void) -> u32 { - (*(this as *mut ResolutionPso)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 + static FAKE_CLEAR_CALLS: AtomicUsize = AtomicUsize::new(0); + static FAKE_CLOSE_CALLS: AtomicUsize = AtomicUsize::new(0); + static FAKE_CLOSED: AtomicBool = AtomicBool::new(false); + static FAKE_RESET_FAIL: AtomicBool = AtomicBool::new(false); + static FAKE_LAST_RESET_PSO: AtomicUsize = AtomicUsize::new(0); + static FAKE_LAST_CLEAR_PSO: AtomicUsize = AtomicUsize::new(usize::MAX); + static FAKE_PIN_COUNT_AT_SET: AtomicUsize = AtomicUsize::new(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 } - unsafe extern "system" fn resolution_release(this: *mut c_void) -> u32 { - (*(this as *mut ResolutionPso)).refs.fetch_sub(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 } - #[test] - fn graphics_resolution_uses_retained_identity_and_records_its_pin() { - let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; - let mut old = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let mut replacement = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let old_raw = &mut old as *mut ResolutionPso as usize; - let replacement_raw = &mut replacement as *mut ResolutionPso as usize; - let standin = 0x7100_4880usize; - let list = 0x7100_4890usize; - pso_async::submit_lazy(standin, false, Box::new(move || old_raw), 0); - assert_eq!(pso_async::resolve_wait(standin), old_raw); - let retained = pso_async::begin_pipeline_resolution(standin).unwrap(); - assert_eq!(pso_async::released(standin), old_raw); - pso_async::submit_lazy(standin, false, Box::new(move || replacement_raw), 0); - - assert_eq!(resolve_pipeline(list, standin, Some(retained)), Some(old_raw)); - assert_eq!(list_x::native_generation_count_for_test(list), 1); - assert_eq!(replacement.refs.load(Ordering::Relaxed), 1, "the reused registry address must not be resolved"); + 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); + } - list_x::clear_segment_state(list); - assert_eq!(pso_async::released(standin), 0); - assert_eq!(unsafe { resolution_release(old_raw as *mut c_void) }, 0); - assert_eq!(unsafe { resolution_release(replacement_raw as *mut c_void) }, 0); + unsafe extern "system" fn fake_set_pso(this: *mut c_void, pso: *mut c_void) { + let list = &*(this as *const FakeAdoptedList); + FAKE_PIN_COUNT_AT_SET.store(list_x::native_generation_count_for_test(this as usize), Ordering::Release); + list.set_pso_calls.fetch_add(1, Ordering::Relaxed); + list.last_pso.store(pso as usize, Ordering::Release); } - #[test] - fn graphics_entrypoints_pass_the_retained_raw_to_the_abi() { - let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); - let mut orig_vt = [0usize; 64]; - orig_vt[1] = fake_add_ref as usize; - orig_vt[2] = fake_release as usize; - orig_vt[25] = fake_set_pso as usize; - let mut ext_vt = vec![0usize; 65]; - ext_vt[0] = orig_vt.as_ptr() as usize; - ext_vt[1..].copy_from_slice(&orig_vt); - let fake = Box::new(FakeAdoptedList { - vt: unsafe { ext_vt.as_ptr().add(1) }, refs: AtomicUsize::new(1), - dispatch_calls: AtomicUsize::new(0), set_compute_rs_calls: AtomicUsize::new(0), - set_compute_uav_calls: AtomicUsize::new(0), set_pso_calls: AtomicUsize::new(0), - last_pso: AtomicUsize::new(0), execute_indirect_calls: AtomicUsize::new(0), - }); - let list = &*fake as *const FakeAdoptedList as *mut c_void; - let _class = real::test_command_list_class( - orig_vt.as_ptr() as usize, - unsafe { ext_vt.as_ptr().add(1) } as usize, - ); - let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; - let mut old = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let mut replacement = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let mut selected_alias = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let old_raw = &mut old as *mut ResolutionPso as usize; - let replacement_raw = &mut replacement as *mut ResolutionPso as usize; - let selected_alias_raw = &mut selected_alias as *mut ResolutionPso as usize; - let standin = 0x7100_4898usize; - pso_async::submit_lazy(standin, false, Box::new(move || old_raw), 0); - assert_eq!(pso_async::resolve_wait(standin), old_raw); - real::register_translated_graphics_for_test(old_raw); - unsafe { list_x::on_create(list, 0, standin, D3D12_COMMAND_LIST_TYPE_DIRECT) }; - set_tracked_pipeline_state(list, standin); - assert_eq!(pso_async::released(standin), old_raw); - pso_async::submit_lazy(standin, false, Box::new(move || replacement_raw), 0); - let alias_calls = Arc::new(AtomicUsize::new(0)); - let selected_calls = alias_calls.clone(); - pso_async::submit_lazy(old_raw, false, Box::new(move || { - selected_calls.fetch_add(1, Ordering::Relaxed); - selected_alias_raw - }), 0); - STOP_ABI_AFTER_BIND_LIST.store(list as usize, Ordering::Release); + unsafe extern "system" fn fake_clear_state(_this: *mut c_void, pso: *mut c_void) { + FAKE_CLEAR_CALLS.fetch_add(1, Ordering::Relaxed); + FAKE_LAST_CLEAR_PSO.store(pso as usize, Ordering::Release); + } + unsafe extern "system" fn fake_close(_this: *mut c_void) -> windows::core::HRESULT { + FAKE_CLOSE_CALLS.fetch_add(1, Ordering::Relaxed); + FAKE_CLOSED.store(true, Ordering::Release); + windows::core::HRESULT(0) + } + unsafe extern "system" fn fake_reset(_this: *mut c_void, _alloc: usize, pso: usize) -> i32 { + FAKE_LAST_RESET_PSO.store(pso, Ordering::Release); + if FAKE_RESET_FAIL.load(Ordering::Acquire) || !FAKE_CLOSED.swap(false, Ordering::AcqRel) { + crate::util::E_FAIL + } else { 0 } + } + 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); + } - LAST_ABI_PSO.store(0, Ordering::Release); - assert!(unsafe { graphics_bound(list) }.is_none()); - assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), old_raw); - LAST_ABI_PSO.store(0, Ordering::Release); - assert!(unsafe { prepare_indexed_draw(list, 3, 1, 0, 0) }.is_none()); - assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), old_raw, - "indexed draw must reuse the retained generation, not the title or replacement address"); - assert_eq!(fake.last_pso.load(Ordering::Acquire), old_raw); - assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 2); - assert_eq!(alias_calls.load(Ordering::Relaxed), 0, "graphics ABI bind ran selected raw's alias build"); - assert_eq!(list_x::bound_pipeline_for_test(list as usize), standin, - "graphics ABI bind replaced title-visible pipeline state"); + 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); + } - STOP_ABI_AFTER_BIND_LIST.store(0, Ordering::Release); - forget(list); - list_x::clear_segment_state(list as usize); - list_x::on_release(list as usize); - assert_eq!(pso_async::released(standin), 0); - assert_eq!(pso_async::released(old_raw), 0); - real::forget_pso_for_test(old_raw); - assert_eq!(unsafe { resolution_release(old_raw as *mut c_void) }, 0); - assert_eq!(unsafe { resolution_release(replacement_raw as *mut c_void) }, 0); - assert_eq!(unsafe { resolution_release(selected_alias_raw as *mut c_void) }, 0); + 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); } + /// A `DispatchX` with thread dimensions of more than 65 535 groups once converted is folded + /// as a dispatch of that many groups (`translated_dispatch`: conversion first, then `fold`): + /// the console's group count goes to `IO_GROUP_LIMIT`, the thread count to + /// `IO_THREAD_LIMIT`. Taken as groups, the same counts were 64x the groups and left out. #[test] - fn dispatch_entrypoint_uses_the_retained_generation_after_address_reuse() { - let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); - let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; - let list_object = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let list = &list_object as *const ResolutionPso as *mut c_void; - let mut original = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let mut replacement = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let original_raw = &mut original as *mut ResolutionPso as usize; - let replacement_raw = &mut replacement as *mut ResolutionPso as usize; - let standin = 0x7100_489Cusize; - - pso_async::submit_lazy(standin, true, Box::new(move || original_raw), 0); - assert_eq!(pso_async::resolve_wait(standin), original_raw); - real::register_translated_compute_for_test(original_raw); - set_tracked_pipeline_state(list, standin); - let original_owner = pso_async::released(standin); - assert_eq!(original_owner, original_raw); + fn dispatch_x_with_thread_dimensions_past_the_d3d12_limit_is_folded_in_groups() { + let most = 1 << 22; + let pso = 0x7300_0011usize; + real::register_threads_for_test(pso, [64, 1, 1]); + // 10 000 001 threads: 156 251 groups of 64, the last with one thread + let (groups, limits) = dispatch_groups(pso, [10_000_001, 1, 1], 0x20).unwrap(); + assert_eq!((groups, limits), ([156_251, 1, 1], [10_000_001, 0, 0])); + let (limit, folded) = fold_counts_within(groups[0], groups[1], groups[2], most); + assert_eq!((limit, folded), (156_251, [65_535, 3, 1])); + assert!(folded[0] * folded[1] >= groups[0] && folded[0] * folded[1] - groups[0] < folded[0]); + // the counts as groups: past what a dispatch may run, nothing at all + assert_eq!(fold_counts_within(10_000_001, 1, 1, most), (0, [0, 0, 0])); + // 8 x 8 groups, 600 000 x 8 threads: one row of 75 000 groups, foldable (as groups the + // counts were two dimensions past the limit, clamped) + let pso2 = 0x7300_0012usize; + real::register_threads_for_test(pso2, [8, 8, 1]); + let (groups, limits) = dispatch_groups(pso2, [600_000, 8, 1], 0x8020).unwrap(); + assert_eq!((groups, limits), ([75_000, 1, 1], [0, 0, 0])); + assert_eq!(fold_counts_within(groups[0], groups[1], groups[2], most), (75_000, [65_535, 2, 1])); + } - let replacement_calls = Arc::new(AtomicUsize::new(0)); - let replacement_build_calls = replacement_calls.clone(); - pso_async::submit_lazy(standin, true, Box::new(move || { - replacement_build_calls.fetch_add(1, Ordering::Relaxed); - replacement_raw - }), 0); - STOP_ABI_LIST.store(list as usize, Ordering::Release); - for _ in 0..2 { - LAST_ABI_PSO.store(0, Ordering::Release); - unsafe { dispatch_flags(list, 1, 1, 1, 0) }; - assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), original_raw); - } - assert_eq!(replacement_calls.load(Ordering::Relaxed), 0, "Dispatch ran the replacement build"); - assert_eq!(replacement.refs.load(Ordering::Relaxed), 1, "Dispatch retained the replacement generation"); - assert_eq!(list_x::native_generation_count_for_test(list as usize), 1, "repeated Dispatch duplicated its exact pin"); + /// `IO_THREAD_LIMIT` takes three io slots no other value has: in the trap-temp range + /// (ttmp0..15, SGPRs 108..=123, which titles' programs do not use), apart from each other + /// and from the GS, UMA base, loop budget and group limit slots. + #[test] + fn dispatch_thread_limit_slots_collide_with_no_other_io_slot() { + use crate::gpu::recomp::{IO_GROUP_LIMIT, IO_GS_PRIMS, IO_GS_VERTICES, IO_LOOP_BUDGET, IO_THREAD_LIMIT, IO_UMA_BASE_HI, KERNEL_SCC_SLOT, KERNEL_SGPRS}; + let mut all = vec![IO_GS_PRIMS, IO_GS_VERTICES, IO_UMA_BASE_HI, IO_LOOP_BUDGET, IO_GROUP_LIMIT]; + all.extend(IO_THREAD_LIMIT); + let mut unique = all.clone(); + unique.sort_unstable(); + unique.dedup(); + assert_eq!(unique.len(), all.len(), "{all:?}"); + for s in all { + assert!((108..=123).contains(&s) && s < KERNEL_SGPRS && s != KERNEL_SCC_SLOT, "slot {s}"); + } + } - STOP_ABI_LIST.store(0, Ordering::Release); - forget(list); - list_x::clear_segment_state(list as usize); - assert_eq!(pso_async::released(standin), 0); - real::forget_pso_for_test(original_raw); - assert_eq!(unsafe { resolution_release(original_owner as *mut c_void) }, 0); - assert_eq!(unsafe { resolution_release(replacement_raw as *mut c_void) }, 0); + /// The frame capture records a `DispatchX` with thread dimensions with its thread counts, + /// flags and the groups they launch (none known for a pipeline whose group shape is not); + /// other dispatches with their groups. + #[test] + fn a_dispatch_x_with_thread_dimensions_is_captured_with_its_groups() { + use super::super::capture::WorkKind; + let pso = 0x7300_0021usize; + real::register_threads_for_test(pso, [64, 1, 1]); + assert_eq!(captured_dispatch(pso, [100, 1, 1], 0x20), WorkKind::DispatchThreads { threads: [100, 1, 1], flags: 0x20, groups: Some([2, 1, 1]) }); + assert_eq!(captured_dispatch(0x7300_00FE, [100, 1, 1], 0x8020), WorkKind::DispatchThreads { threads: [100, 1, 1], flags: 0x8020, groups: None }); + assert_eq!(captured_dispatch(pso, [7, 2, 1], 0x8000), WorkKind::Dispatch([7, 2, 1])); + assert_eq!(captured_dispatch(pso, [7, 2, 1], 0), WorkKind::Dispatch([7, 2, 1])); } #[test] - fn execute_indirect_uses_retained_generation_after_address_reuse() { + fn title_pipeline_binds_use_one_retained_identity_and_fail_closed() { let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); let mut orig_vt = [0usize; 64]; - orig_vt[1] = fake_add_ref as usize; - orig_vt[2] = fake_release as usize; - orig_vt[25] = fake_set_pso as usize; - orig_vt[59] = fake_execute_indirect as usize; + orig_vt[1] = fake_add_ref as usize; orig_vt[2] = fake_release as usize; + orig_vt[9] = fake_close as usize; orig_vt[11] = fake_clear_state as usize; + orig_vt[10] = fake_reset as usize; orig_vt[14] = fake_dispatch as usize; + orig_vt[25] = fake_set_pso as usize; orig_vt[59] = fake_execute_indirect as usize; let mut ext_vt = vec![0usize; 65]; ext_vt[0] = orig_vt.as_ptr() as usize; ext_vt[1..].copy_from_slice(&orig_vt); @@ -2508,70 +6668,109 @@ void main(uint t : SV_GroupIndex) { orig_vt.as_ptr() as usize, unsafe { ext_vt.as_ptr().add(1) } as usize, ); + unsafe { list_x::on_create(list, 0, 0, D3D12_COMMAND_LIST_TYPE_DIRECT) }; let pso_vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; - let mut original = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut old = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; let mut replacement = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let mut selected_alias = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let original_raw = &mut original as *mut ResolutionPso as usize; + let old_raw = &mut old as *mut ResolutionPso as usize; let replacement_raw = &mut replacement as *mut ResolutionPso as usize; - let selected_alias_raw = &mut selected_alias as *mut ResolutionPso as usize; - let standin = 0x7100_48B0usize; - let signature = IndirectSignatureInfo::new(true, false, None); - - pso_async::submit_lazy(standin, true, Box::new(move || original_raw), 0); - assert_eq!(pso_async::resolve_wait(standin), original_raw); - real::register_translated_compute_for_test(original_raw); - unsafe { list_x::on_create(list, 0, standin, D3D12_COMMAND_LIST_TYPE_DIRECT) }; - set_tracked_pipeline_state(list, standin); - let original_owner = pso_async::released(standin); - let replacement_calls = Arc::new(AtomicUsize::new(0)); - let calls = replacement_calls.clone(); - pso_async::submit_lazy(standin, true, Box::new(move || { + let original = 0x7100_48F8usize; + pso_async::submit_lazy(original, true, Box::new(move || old_raw), 0); + assert_eq!(pso_async::resolve_wait(original), old_raw); + let retained = pso_async::begin_pipeline_resolution(original).unwrap(); + let retained_identity = retained.identity_for_test(); + let old_owner = pso_async::released(original); + let replacement_calls = Arc::new(AtomicUsize::new(0)); let calls = replacement_calls.clone(); + pso_async::submit_lazy(original, true, Box::new(move || { calls.fetch_add(1, Ordering::Relaxed); replacement_raw }), 0); - let alias_calls = Arc::new(AtomicUsize::new(0)); - let selected_calls = alias_calls.clone(); - pso_async::submit_lazy(original_raw, true, Box::new(move || { - selected_calls.fetch_add(1, Ordering::Relaxed); - selected_alias_raw + let alias_calls = Arc::new(AtomicUsize::new(0)); let calls = alias_calls.clone(); + pso_async::submit_lazy(old_raw, true, Box::new(move || { + calls.fetch_add(1, Ordering::Relaxed); + replacement_raw }), 0); - STOP_ABI_AFTER_BIND_LIST.store(list as usize, Ordering::Release); - for _ in 0..2 { - LAST_ABI_PSO.store(0, Ordering::Release); - unsafe { execute_indirect_classified(list, 1, 1, 0, 0, 0, 0, signature) }; - assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), original_raw); - assert_eq!(fake.last_pso.load(Ordering::Acquire), original_raw, - "selected raw was redirected through its registry alias at native bind"); + FAKE_PIN_COUNT_AT_SET.store(0, Ordering::Release); + unsafe { set_pipeline_state_retained(list, original, Some(retained)) }; + assert_eq!(fake.last_pso.load(Ordering::Acquire), old_raw); + assert_eq!(FAKE_PIN_COUNT_AT_SET.load(Ordering::Acquire), 1, "exact generation was not pinned before native SetPipelineState"); + assert_eq!(replacement_calls.load(Ordering::Relaxed), 0); + assert_eq!(alias_calls.load(Ordering::Relaxed), 0); + assert_eq!(list_x::bound_pipeline_for_test(list as usize), original); + assert_eq!(with(list, |s| s.resolution.as_ref().unwrap().identity_for_test()), retained_identity); + let clear_resolution = with(list, |s| s.resolution.clone()); + FAKE_CLEAR_CALLS.store(0, Ordering::Release); + unsafe { clear_pipeline_state_retained(list, original, clear_resolution) }; + assert_eq!(FAKE_CLEAR_CALLS.load(Ordering::Acquire), 1); + assert_eq!(FAKE_LAST_CLEAR_PSO.load(Ordering::Acquire), old_raw); + assert_eq!(list_x::native_generation_count_for_test(list as usize), 1, "Set and Clear duplicated the exact generation pin"); + assert_eq!(replacement_calls.load(Ordering::Relaxed), 0); + assert_eq!(alias_calls.load(Ordering::Relaxed), 0); + let unavailable = pso_async::pipeline_resolution_for_compute_test(original, || {}) + .unavailable_for_test(); + let (before_sets, before_clears) = (fake.set_pso_calls.load(Ordering::Relaxed), FAKE_CLEAR_CALLS.load(Ordering::Relaxed)); + unsafe { set_pipeline_state_retained(list, original, Some(unavailable)) }; + assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), before_sets, "unavailable SetPipelineState rebound the prior native pipeline"); + assert_eq!(FAKE_CLEAR_CALLS.load(Ordering::Relaxed), before_clears, "eligible omission reset logical root state"); + assert!(!list_x::recording_poisoned(list as usize)); + unsafe { + dispatch_flags(list, 1, 1, 1, 0); + execute_indirect_retained( + list, 1, 1, 0, 0, 0, 0, IndirectSignatureInfo::new(true, false, None), + ); } - assert_eq!(replacement_calls.load(Ordering::Relaxed), 0, "ExecuteIndirect ran a replacement build at the reused title address"); - assert_eq!(alias_calls.load(Ordering::Relaxed), 0, "ExecuteIndirect ran the selected raw's alias build"); - assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 2); - assert_eq!(list_x::bound_pipeline_for_test(list as usize), standin, - "exact internal bind replaced title-visible pipeline state"); - assert_eq!(list_x::native_generation_count_for_test(list as usize), 1, "repeated ExecuteIndirect duplicated its exact pin"); + assert_eq!(fake.dispatch_calls.load(Ordering::Relaxed), 0, "unavailable Dispatch executed the preceding PSO"); + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0, "unavailable ExecuteIndirect executed the preceding PSO"); + + let unavailable = pso_async::pipeline_resolution_for_test(original, || {}).unavailable_for_test(); + let (before_sets, before_clears) = (fake.set_pso_calls.load(Ordering::Relaxed), FAKE_CLEAR_CALLS.load(Ordering::Relaxed)); + unsafe { set_pipeline_state_retained(list, original, Some(unavailable)) }; + assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), before_sets); + assert_eq!(FAKE_CLEAR_CALLS.load(Ordering::Relaxed), before_clears, "poisoning reset physical state"); + assert!(list_x::recording_poisoned(list as usize)); + FAKE_CLOSE_CALLS.store(0, Ordering::Release); + FAKE_CLOSED.store(false, Ordering::Release); + assert!(unsafe { real::close_for_test(list) } < 0); + assert_eq!(FAKE_CLOSE_CALLS.load(Ordering::Acquire), 1, "poisoned Close did not close natively"); + assert!(real::submission_rejected_for_test(&[list]), "poisoned recording passed submission guard"); + + let (parent, bundle) = (0x7100_48FAusize, 0x7100_48FBusize); + unsafe { + list_x::on_create(parent as *mut c_void, 0, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + list_x::on_create(bundle as *mut c_void, 0, 0, D3D12_COMMAND_LIST_TYPE_BUNDLE); + } + list_x::poison_recording(bundle); + list_x::on_execute_bundle(parent, bundle); list_x::on_execute_bundle(parent, bundle); + assert!(real::submission_rejected_for_test(&[parent as *mut c_void])); + list_x::on_release(parent); list_x::on_release(bundle); + + let unavailable = pso_async::pipeline_resolution_for_test(original, || {}).unavailable_for_test(); + FAKE_LAST_CLEAR_PSO.store(usize::MAX, Ordering::Release); + unsafe { clear_pipeline_state_retained(list, original, Some(unavailable)) }; + assert_eq!(FAKE_LAST_CLEAR_PSO.load(Ordering::Acquire), 0, "unavailable ClearState did not send NULL"); + assert_eq!(with(list, |s| s.pso), original); + assert_eq!(list_x::bound_pipeline_for_test(list as usize), original); + assert!(list_x::recording_poisoned(list as usize), "ClearState must not unpoison a recording"); + assert_eq!(unsafe { list_x::reset_pc(list, 0, 0) }, 0); + assert!(!list_x::recording_poisoned(list as usize), "successful Reset must clear poison"); - STOP_ABI_AFTER_BIND_LIST.store(0, Ordering::Release); forget(list); list_x::clear_segment_state(list as usize); list_x::on_release(list as usize); - assert_eq!(pso_async::released(standin), 0); - assert_eq!(pso_async::released(original_raw), 0); - real::forget_pso_for_test(original_raw); - assert_eq!(unsafe { resolution_release(original_owner as *mut c_void) }, 0); + assert_eq!(pso_async::released(original), 0); + assert_eq!(pso_async::released(old_raw), 0); + assert_eq!(unsafe { resolution_release(old_owner as *mut c_void) }, 0); assert_eq!(unsafe { resolution_release(replacement_raw as *mut c_void) }, 0); - assert_eq!(unsafe { resolution_release(selected_alias_raw as *mut c_void) }, 0); } #[test] - fn execute_indirect_native_snapshot_ignores_a_later_registry_alias() { + fn prepared_initial_pipeline_commits_only_after_create_or_reset_success() { + let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); let mut orig_vt = [0usize; 64]; - orig_vt[1] = fake_add_ref as usize; - orig_vt[2] = fake_release as usize; - orig_vt[59] = fake_execute_indirect as usize; + orig_vt[1] = fake_add_ref as usize; orig_vt[2] = fake_release as usize; + orig_vt[10] = fake_reset as usize; let mut ext_vt = vec![0usize; 65]; - ext_vt[0] = orig_vt.as_ptr() as usize; - ext_vt[1..].copy_from_slice(&orig_vt); + ext_vt[0] = orig_vt.as_ptr() as usize; ext_vt[1..].copy_from_slice(&orig_vt); let fake = Box::new(FakeAdoptedList { vt: unsafe { ext_vt.as_ptr().add(1) }, refs: AtomicUsize::new(1), dispatch_calls: AtomicUsize::new(0), set_compute_rs_calls: AtomicUsize::new(0), @@ -2579,188 +6778,278 @@ void main(uint t : SV_GroupIndex) { last_pso: AtomicUsize::new(0), execute_indirect_calls: AtomicUsize::new(0), }); let list = &*fake as *const FakeAdoptedList as *mut c_void; - let native = 0x7100_48B2usize; - reset(list, 0, native); - let build_calls = Arc::new(AtomicUsize::new(0)); - let calls = build_calls.clone(); - pso_async::submit_lazy(native, true, Box::new(move || { - calls.fetch_add(1, Ordering::Relaxed); - 0x7100_48B3 - }), 0); - - unsafe { execute_indirect_classified(list, 1, 1, 0, 0, 0, 0, IndirectSignatureInfo::default()) }; - assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 1); - assert_eq!(build_calls.load(Ordering::Relaxed), 0, "native ExecuteIndirect re-resolved its raw address through the registry"); + let _class = real::test_command_list_class( + orig_vt.as_ptr() as usize, + unsafe { ext_vt.as_ptr().add(1) } as usize, + ); + unsafe { list_x::on_create(list, 0, 0, D3D12_COMMAND_LIST_TYPE_DIRECT) }; + let fallback = PreparedNativePipeline::from_resolution( + 0x7100_4900, Some(pso_async::pipeline_resolution_for_test(0x7100_4900, || {})), + ); + assert_eq!(fallback.raw(), 0x7100_4900); drop(fallback); + let pso_vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; + let mut exact = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let (exact_raw, replacement_raw) = (&mut exact as *mut ResolutionPso as usize, &mut replacement as *mut ResolutionPso as usize); + let original = 0x7100_4901usize; + pso_async::submit_lazy(original, false, Box::new(move || exact_raw), 0); + assert_eq!(pso_async::resolve_wait(original), exact_raw); + let failed_create = PreparedNativePipeline::from_resolution( + original, pso_async::begin_pipeline_resolution(original), + ); + assert_eq!(failed_create.raw(), exact_raw); drop(failed_create); assert_eq!(list_x::native_generation_count_for_test(list as usize), 0); + let retained = pso_async::begin_pipeline_resolution(original).unwrap(); + let identity = retained.identity_for_test(); + let prepared = PreparedNativePipeline::from_resolution(original, Some(retained)); + assert_eq!(prepared.raw(), exact_raw); + let exact_owner = pso_async::released(original); + let replacement_calls = Arc::new(AtomicUsize::new(0)); let calls = replacement_calls.clone(); + pso_async::submit_lazy(original, false, Box::new(move || { calls.fetch_add(1, Ordering::Relaxed); replacement_raw }), 0); + prepared.commit(list, 0); + assert_eq!(with(list, |s| s.resolution.as_ref().unwrap().identity_for_test()), identity); + assert_eq!(list_x::native_generation_count_for_test(list as usize), 1); + assert_eq!(replacement_calls.load(Ordering::Relaxed), 0); + + let unavailable = pso_async::pipeline_resolution_for_compute_test(0x7100_4902, || {}).unavailable_for_test(); + let prepared = PreparedNativePipeline::from_resolution(0x7100_4902, Some(unavailable)); + assert_eq!(prepared.raw(), 0); prepared.commit(list, 0); + assert!(!list_x::recording_poisoned(list as usize)); + let unavailable = pso_async::pipeline_resolution_for_test(0x7100_4903, || {}).unavailable_for_test(); + PreparedNativePipeline::from_resolution(0x7100_4903, Some(unavailable)).commit(list, 0); + assert!(list_x::recording_poisoned(list as usize)); + let old_identity = with(list, |s| s.resolution.as_ref().unwrap().identity_for_test()); + drop(PreparedNativePipeline::from_resolution( + 0x7100_4904, Some(pso_async::pipeline_resolution_for_test(0x7100_4904, || {})), + )); + assert_eq!(with(list, |s| s.resolution.as_ref().unwrap().identity_for_test()), old_identity); + assert!(list_x::recording_poisoned(list as usize)); + + let mut reset_exact = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let reset_raw = &mut reset_exact as *mut ResolutionPso as usize; + let reset_original = 0x7100_4906usize; + pso_async::submit_lazy(reset_original, false, Box::new(move || reset_raw), 0); + assert_eq!(pso_async::resolve_wait(reset_original), reset_raw); + FAKE_CLOSED.store(true, Ordering::Release); FAKE_RESET_FAIL.store(true, Ordering::Release); + assert!(unsafe { real::reset_for_test(list, std::ptr::null_mut(), reset_original as *mut c_void) } < 0); + assert_eq!(FAKE_LAST_RESET_PSO.load(Ordering::Acquire), reset_raw); + assert!(list_x::recording_poisoned(list as usize)); + assert_eq!(with(list, |s| s.resolution.as_ref().unwrap().identity_for_test()), old_identity); + assert_eq!(list_x::native_generation_count_for_test(list as usize), 1); + FAKE_RESET_FAIL.store(false, Ordering::Release); + FAKE_CLOSED.store(true, Ordering::Release); + assert_eq!(unsafe { real::reset_for_test(list, std::ptr::null_mut(), std::ptr::null_mut()) }, 0); + assert_eq!(FAKE_LAST_RESET_PSO.load(Ordering::Acquire), 0); + assert!(!list_x::recording_poisoned(list as usize)); + + FAKE_CLOSED.store(true, Ordering::Release); + assert_eq!(unsafe { list_x::reset_pc(list, 0, reset_original) }, 0); + assert_eq!(FAKE_LAST_RESET_PSO.load(Ordering::Acquire), reset_raw); + assert_eq!(tracked_pso(list), reset_original); + assert_eq!(list_x::native_generation_count_for_test(list as usize), 1); + let reset_owner = pso_async::released(reset_original); + + forget(list); list_x::clear_segment_state(list as usize); list_x::on_release(list as usize); + assert_eq!(pso_async::released(original), 0); + assert_eq!(unsafe { resolution_release(exact_owner as *mut c_void) }, 0); + assert_eq!(unsafe { resolution_release(replacement_raw as *mut c_void) }, 0); + assert_eq!(unsafe { resolution_release(reset_owner as *mut c_void) }, 0); + } + + /// `DispatchX` with thread dimensions (flag 0x20, as the BVH builder's rehydration passes + /// use it): the console launches whole groups of the pipeline's `numthreads` and leaves + /// the lanes past the count out; without the flag the counts are groups. With the flag + /// and a group shape not known, nothing is launched (the counts as groups was the bug). + #[test] + fn dispatch_x_with_thread_dimensions_launches_whole_groups() { + let pso = 0x7300_0001usize; + real::register_threads_for_test(pso, [64, 1, 1]); + // 640 threads in groups of 64: 10 groups, the last one whole + assert_eq!(dispatch_groups(pso, [640, 1, 1], 0x20), Some(([10, 1, 1], [0, 0, 0]))); + // 100 threads: 2 groups, and the lanes past 100 to leave out + assert_eq!(dispatch_groups(pso, [100, 1, 1], 0x20), Some(([2, 1, 1], [100, 0, 0]))); + // the wave32 bit (0x8000) changes nothing here + assert_eq!(dispatch_groups(pso, [100, 1, 1], 0x8020), Some(([2, 1, 1], [100, 0, 0]))); + // a 2-D group shape + let pso2 = 0x7300_0002usize; + real::register_threads_for_test(pso2, [8, 8, 1]); + assert_eq!(dispatch_groups(pso2, [20, 16, 3], 0x20), Some(([3, 2, 3], [20, 0, 0]))); + // group counts (Dispatch, DispatchX without the flag) are launched as they are + assert_eq!(dispatch_groups(pso, [7, 2, 1], 0), Some(([7, 2, 1], [0, 0, 0]))); + assert_eq!(dispatch_groups(pso, [7, 2, 1], 0x8000), Some(([7, 2, 1], [0, 0, 0]))); + // no threads: no groups + assert_eq!(dispatch_groups(pso, [0, 1, 1], 0x20), Some(([0, 1, 1], [0, 0, 0]))); + // thread dimensions on a pipeline whose group shape is not known: not launched + assert_eq!(dispatch_groups(0x7300_00FF, [100, 1, 1], 0x20), None); + assert_eq!(dispatch_groups(0x7300_00FF, [100, 1, 1], 0), Some(([100, 1, 1], [0, 0, 0]))); - forget(list); - let _ = pso_async::released(native); + // past the PC's 65 535 groups a dimension: folded (or clamped), never dispatched as asked + let last = 65_535 * 64; + let at_limit = dispatch_groups(pso, [last, 1, 1], 0x20).unwrap().0; + let past_limit = dispatch_groups(pso, [last + 1, 1, 1], 0x20).unwrap().0; + assert_eq!(fold_counts_within(at_limit[0], at_limit[1], at_limit[2], u32::MAX).1, at_limit); + let (limit, folded) = fold_counts_within(past_limit[0], past_limit[1], past_limit[2], u32::MAX); + assert_eq!(limit, 65_536); + assert!(folded.iter().all(|&n| n <= 65_535), "{folded:?}"); + for k in 0..3 { + let mut grid = [1; 3]; + grid[k] = 65_535; + if k > 0 { + assert_eq!(fold_counts_within(grid[0], grid[1], grid[2], u32::MAX), (0, grid), "axis {k} at the D3D12 limit"); + } + grid[k] += 1; + let (_, folded) = fold_counts_within(grid[0], grid[1], grid[2], u32::MAX); + assert!(folded.iter().all(|&n| n <= 65_535), "axis {k} past the D3D12 limit: {folded:?}"); + } } #[test] - fn deferred_execute_indirect_replays_its_inherited_resolution_once() { - let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); - let mut orig_vt = [0usize; 64]; - orig_vt[1] = fake_add_ref as usize; - orig_vt[2] = fake_release as usize; - orig_vt[59] = fake_execute_indirect as usize; - let mut ext_vt = vec![0usize; 65]; - ext_vt[0] = orig_vt.as_ptr() as usize; - ext_vt[1..].copy_from_slice(&orig_vt); - let make_list = || Box::new(FakeAdoptedList { - vt: unsafe { ext_vt.as_ptr().add(1) }, refs: AtomicUsize::new(1), - dispatch_calls: AtomicUsize::new(0), set_compute_rs_calls: AtomicUsize::new(0), - set_compute_uav_calls: AtomicUsize::new(0), set_pso_calls: AtomicUsize::new(0), - last_pso: AtomicUsize::new(0), execute_indirect_calls: AtomicUsize::new(0), + fn abi_preparation_snapshots_state_and_reserves_disjoint_regions() { + let list = 0x7301_0001usize as *mut c_void; + let u = crate::gpu::uma::Uma::with_windows(1, 8 << 20).expect("test UMA"); + let layout = Arc::new(Layout { size: 64, inline: 4, ..Default::default() }); + let args = (0..64u8).collect::>(); + with(list, |state| { + state.layout = Some(layout.clone()); + state.args = args.clone(); + state.allocator = 0x7301_1000; }); - let source_object = make_list(); - let replay_object = make_list(); - let source = &*source_object as *const FakeAdoptedList as *mut c_void; - let replay = &*replay_object as *const FakeAdoptedList as *mut c_void; - let pso_vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; - let mut old = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let mut replacement = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let old_raw = &mut old as *mut ResolutionPso as usize; - let replacement_raw = &mut replacement as *mut ResolutionPso as usize; - let standin = 0x7100_48B4usize; - pso_async::submit_lazy(standin, true, Box::new(move || old_raw), 0); - assert_eq!(pso_async::resolve_wait(standin), old_raw); - real::register_translated_compute_for_test(old_raw); - set_tracked_pipeline_state(source, standin); - let (inherited_pso, inherited_resolution) = with(source, |state| { - (state.pso, state.resolution.clone()) - }); - with(replay, |state| { - state.pso = inherited_pso; - state.resolution = inherited_resolution; + let prepared = prepare_abi_state(list, &u, false, None).unwrap(); + assert!(Arc::ptr_eq(prepared.layout.as_ref().unwrap(), &layout)); + assert_eq!(prepared.args, args); + assert_eq!(prepared.inline, 4); + assert_eq!(prepared.allocator, 0x7301_1000); + assert_eq!((prepared.table_at | prepared.io_at | prepared.res_at) & 255, 0); + assert!(prepared.table_at + 60 <= prepared.io_at); + assert!(prepared.io_at + crate::gpu::recomp::KERNEL_SGPRS * std::mem::size_of::() <= prepared.res_at); + + with(list, |state| { + state.layout = None; + state.args.clear(); + state.allocator = 0x7301_2000; }); + assert!(Arc::ptr_eq(prepared.layout.as_ref().unwrap(), &layout)); + assert_eq!(prepared.args, args); + assert_eq!(prepared.allocator, 0x7301_1000); - let old_owner = pso_async::released(standin); - pso_async::submit_lazy(standin, true, Box::new(move || replacement_raw), 0); - set_tracked_pipeline_state(source, standin); - STOP_ABI_LIST.store(replay as usize, Ordering::Release); - LAST_ABI_PSO.store(0, Ordering::Release); - unsafe { - execute_indirect_retained( - replay, 1, 1, 0, 0, 0, 0, IndirectSignatureInfo::new(true, false, None), - ) - }; - assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), old_raw); - assert_eq!(list_x::native_generation_count_for_test(replay as usize), 1); - assert_eq!(list_x::native_generation_count_for_test(source as usize), 0, - "deferred replay recursively split or pinned the source segment"); - assert_eq!(replacement.refs.load(Ordering::Relaxed), 1, - "deferred replay resolved the replacement generation"); + let state = take_state(list as usize).unwrap(); + assert_eq!(state.uma.len(), 1, "the three reservations should share one arena block"); + for block in state.uma { + assert!(u.free(block)); + } + } - STOP_ABI_LIST.store(0, Ordering::Release); - forget(source); - forget(replay); - list_x::clear_segment_state(replay as usize); - assert_eq!(pso_async::released(standin), 0); - real::forget_pso_for_test(old_raw); - assert_eq!(unsafe { resolution_release(old_owner as *mut c_void) }, 0); - assert_eq!(unsafe { resolution_release(replacement_raw as *mut c_void) }, 0); + #[test] + fn dispatch_limits_are_explicit_and_graphics_ignores_them() { + let slots = crate::gpu::recomp::IO_THREAD_LIMIT; + let compute = prepared_abi_io(None, &[], 0x1234_0000, false, None, 0, [0; 2], [100, 17, 0], None, 0); + assert_eq!([compute[slots[0]], compute[slots[1]], compute[slots[2]]], [100, 17, 0]); + + let ordinary = prepared_abi_io(None, &[], 0x1234_1000, false, None, 0, [0; 2], [0; 3], None, 0); + assert_eq!([ordinary[slots[0]], ordinary[slots[1]], ordinary[slots[2]]], [0; 3]); + + let graphics = prepared_abi_io(None, &[], 0x1234_2000, true, None, 0, [0; 2], [9, 8, 7], None, 0); + assert_eq!([graphics[slots[0]], graphics[slots[1]], graphics[slots[2]]], [0; 3]); } #[test] - fn unavailable_execute_indirect_counts_one_signature_selected_skip() { - let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); - let mut orig_vt = [0usize; 64]; - orig_vt[1] = fake_add_ref as usize; - orig_vt[2] = fake_release as usize; - orig_vt[59] = fake_execute_indirect as usize; - let mut ext_vt = vec![0usize; 65]; - ext_vt[0] = orig_vt.as_ptr() as usize; - ext_vt[1..].copy_from_slice(&orig_vt); - let fake = Box::new(FakeAdoptedList { - vt: unsafe { ext_vt.as_ptr().add(1) }, refs: AtomicUsize::new(1), - dispatch_calls: AtomicUsize::new(0), set_compute_rs_calls: AtomicUsize::new(0), - set_compute_uav_calls: AtomicUsize::new(0), set_pso_calls: AtomicUsize::new(0), - last_pso: AtomicUsize::new(0), execute_indirect_calls: AtomicUsize::new(0), - }); - let list = &*fake as *const FakeAdoptedList as *mut c_void; - STOP_ABI_LIST.store(list as usize, Ordering::Release); - LAST_ABI_PSO.store(0, Ordering::Release); - let _ = take_indirect_skip_counts(); + fn command_signature_recreation_replaces_every_classification_bit() { + assert_eq!(std::mem::size_of::(), 8); + let root_reuse = 0x7301_2800usize; + note_indirect_signature(root_reuse, IndirectSignatureInfo::new(true, true, Some(12))); + note_indirect_signature(root_reuse, IndirectSignatureInfo::default()); + assert_eq!(indirect_signature(root_reuse), IndirectSignatureInfo::default(), + "a plain signature inherited root-changing or dispatch state"); - let compute = pso_async::pipeline_resolution_for_compute_test(0x7100_48B6, || {}); - with(list, |state| { - state.pso = 0x7100_48B6; - state.resolution = Some(compute.unavailable_for_test()); - }); - unsafe { - execute_indirect_retained( - list, 1, 1, 0, 0, 0, 0, IndirectSignatureInfo::new(true, false, None), - ) - }; - assert_eq!(take_indirect_skip_counts(), [0, 1]); + let dispatch_reuse = 0x7301_2810usize; + note_indirect_signature(dispatch_reuse, IndirectSignatureInfo::new(true, false, Some(16))); + let replacement = IndirectSignatureInfo::new(true, true, None); + note_indirect_signature(dispatch_reuse, replacement); + assert_eq!(indirect_signature(dispatch_reuse), replacement, + "a non-dispatch-only replacement inherited the old stride"); + } - let graphics = pso_async::pipeline_resolution_for_test(0x7100_48B7, || {}); - with(list, |state| { - state.pso = 0x7100_48B7; - state.resolution = Some(graphics.unavailable_for_test()); + #[test] + fn command_signature_snapshot_never_mixes_generations() { + let sig = 0x7301_2820usize; + let a = IndirectSignatureInfo::new(true, false, Some(12)); + let b = IndirectSignatureInfo::new(false, true, None); + note_indirect_signature(sig, a); + let writer = std::thread::spawn(move || { + for n in 0..20_000 { + note_indirect_signature(sig, if n & 1 == 0 { b } else { a }); + } }); - unsafe { - execute_indirect_retained(list, 1, 1, 0, 0, 0, 0, IndirectSignatureInfo::default()) + for _ in 0..20_000 { + let seen = indirect_signature(sig); + assert!(seen == a || seen == b, "mixed command-signature snapshot: {seen:?}"); + } + writer.join().unwrap(); + } + + #[test] + fn deferred_indirect_owns_its_command_signature_snapshot() { + let sig = 0x7301_2830usize; + let original = IndirectSignatureInfo::new(true, false, Some(12)); + note_indirect_signature(sig, original); + let deferred = list_x::Deferred::Indirect { + sig: 1, max: 2, args: 3, args_off: 4, count_buf: 5, count_off: 6, + signature: indirect_signature(sig), }; - assert_eq!(take_indirect_skip_counts(), [1, 0]); - assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), 0, "unavailable resolution reached ABI binding"); - assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0, "unavailable resolution reached PC ExecuteIndirect"); - assert_eq!(list_x::native_generation_count_for_test(list as usize), 0); + note_indirect_signature(sig, IndirectSignatureInfo::new(false, true, None)); - STOP_ABI_LIST.store(0, Ordering::Release); - forget(list); + let list_x::Deferred::Indirect { signature: retained, .. } = deferred else { unreachable!() }; + assert_eq!(retained, original, + "deferred replay followed the classification now stored at a reused signature address"); } #[test] - fn dispatch_waits_outside_states_and_selects_the_build_once() { - let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); - let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; - let list_object = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let list = &list_object as *const ResolutionPso as *mut c_void; - let mut native = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let raw = &mut native as *mut ResolutionPso as usize; - let standin = 0x7100_489Dusize; - let list_key = list as usize; - let calls = Arc::new(AtomicUsize::new(0)); - let build_calls = calls.clone(); - pso_async::submit_lazy(standin, true, Box::new(move || { - assert!(state_locks_available_for_test(list_key), "Dispatch waited for its build under bind-state locks"); - build_calls.fetch_add(1, Ordering::Relaxed); - real::register_translated_compute_for_test(raw); - raw - }), 0); - set_tracked_pipeline_state(list, standin); - STOP_ABI_LIST.store(list as usize, Ordering::Release); + fn resolved_compute_metadata_does_not_follow_a_reused_native_address() { + let exact = 0x7301_3000usize; + let replacement = 0x7301_4000usize; + real::register_compute_metadata_for_test(exact, 6, [4, 2, 1], (2, 0), 0x7301_5000); + real::register_compute_metadata_for_test(replacement, 9, [8, 1, 1], (3, 1), 0x7301_6000); + pso_async::submit_lazy(exact, true, Box::new(move || replacement), 0); + assert_eq!(pso_async::resolve_wait(exact), replacement); - LAST_ABI_PSO.store(0, Ordering::Release); - unsafe { dispatch_flags(list, 1, 1, 1, 0) }; - assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), raw); - LAST_ABI_PSO.store(0, Ordering::Release); - unsafe { dispatch_flags(list, 1, 1, 1, 0) }; - assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), raw); - assert_eq!(calls.load(Ordering::Relaxed), 1, "repeated Dispatch consumed the build more than once"); - assert_eq!(list_x::native_generation_count_for_test(list as usize), 1); + assert_eq!(real::pso_threads(exact), Some([8, 1, 1]), + "the title-address accessor should still resolve an active stand-in"); + assert_eq!(real::pso_threads_exact(exact), Some([4, 2, 1])); + assert_eq!(real::pso_user_sgprs_exact(exact), Some(6)); + assert_eq!(real::pso_dispatch_remap_exact(exact), Some((2, 0))); + assert_eq!(real::pso_root_signature_exact(exact), Some(0x7301_5000)); + assert_eq!(dispatch_groups(exact, [8, 4, 1], DISPATCH_THREAD_DIMENSIONS), + Some(([2, 2, 1], [0; 3])), + "an already-selected native generation was redirected through PENDING"); - STOP_ABI_LIST.store(0, Ordering::Release); - forget(list); - list_x::clear_segment_state(list as usize); - let raw_owner = pso_async::released(standin); - real::forget_pso_for_test(raw); - assert_eq!(unsafe { resolution_release(raw_owner as *mut c_void) }, 0); + assert_eq!(pso_async::released(exact), replacement); + real::forget_pso_for_test(exact); + real::forget_pso_for_test(replacement); } #[test] - fn exact_compute_bind_bypasses_a_registry_alias_and_preserves_title_state() { + 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[30] = fake_noop_ptr as usize; // SetGraphicsRootSignature + orig_vt[41] = fake_set_compute_uav as usize; + orig_vt[59] = fake_execute_indirect as usize; + // (a draw signature with a PC pipeline needs the title's graphics root signature) + let title_rs = 0x7200_0200usize; + + // Extended vtable layout expected by `real::orig_fn`: entry -1 holds `orig_vt` pointer, + // and entries 0..64 hold the COM method pointers used via `ID3D12GraphicsCommandList`. let mut ext_vt = vec![0usize; 65]; ext_vt[0] = orig_vt.as_ptr() as usize; ext_vt[1..].copy_from_slice(&orig_vt); + let fake = Box::new(FakeAdoptedList { + // SAFETY: `ext_vt` has 65 elements so `.add(1)` points to slot 0 with `orig_vt` at `-1`. vt: unsafe { ext_vt.as_ptr().add(1) }, refs: AtomicUsize::new(1), dispatch_calls: AtomicUsize::new(0), @@ -2770,1159 +7059,2968 @@ void main(uint t : SV_GroupIndex) { last_pso: AtomicUsize::new(0), execute_indirect_calls: AtomicUsize::new(0), }); - let list = &*fake as *const FakeAdoptedList as *mut c_void; - let _class = real::test_command_list_class( - orig_vt.as_ptr() as usize, - unsafe { ext_vt.as_ptr().add(1) } as usize, - ); - let original = 0x7100_489Eusize; - let exact_raw = 0x7100_489Fusize; - let replacement = 0x7100_48A1usize; - unsafe { list_x::on_set_pipeline_state(list, original) }; - assert_eq!(list_x::bound_pipeline_for_test(list as usize), original); - pso_async::submit_lazy(exact_raw, false, Box::new(move || replacement), 0); - assert_eq!(pso_async::resolve_wait(exact_raw), replacement); - - unsafe { real::bind_pipeline_exact(list, original, exact_raw) }; - assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 1); - assert_eq!(fake.last_pso.load(Ordering::Acquire), exact_raw, "exact raw was re-resolved through its alias"); - assert_eq!(list_x::bound_pipeline_for_test(list as usize), original, "internal compute bind replaced title-visible state"); - assert_eq!(list_x::native_generation_count_for_test(list as usize), 0, "internal exact bind pinned the alias generation"); - - assert_eq!(pso_async::released(exact_raw), replacement); - list_x::on_release(list as usize); - } - - #[test] - fn graphics_resolution_waits_outside_states_and_selects_only_once() { - let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; - let mut real = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let raw = &mut real as *mut ResolutionPso as usize; - let standin = 0x7100_48A0usize; - let list = 0x7100_48B0usize as *mut c_void; - let list_key = list as usize; - let calls = Arc::new(AtomicUsize::new(0)); - let build_calls = calls.clone(); - pso_async::submit_recipe_keyed(standin, false, pso_async::Recipe::new(move || { - assert!(state_locks_available_for_test(list_key), "pipeline build waited under bind-state locks"); - build_calls.fetch_add(1, Ordering::Relaxed); - raw - }), false, 0, None); - set_tracked_pipeline_state(list, standin); - - assert_eq!(resolve_bound_graphics_pipeline(list, list as usize), Some((standin, raw))); - assert_eq!(calls.load(Ordering::Relaxed), 1); - assert!(cpu_rect_expansion(raw)); - assert_eq!(calls.load(Ordering::Relaxed), 1, "downstream draw decisions must reuse the selected raw PSO"); - - forget(list); - list_x::clear_segment_state(list as usize); - assert_eq!(pso_async::released(standin), raw); - assert_eq!(unsafe { resolution_release(raw as *mut c_void) }, 0); - } - - #[test] - fn graphics_resolution_pins_one_shot_and_fails_closed_when_unavailable() { - let one_shot = 0x7100_48C0usize; - let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; - let mut real = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let one_shot_real = &mut real as *mut ResolutionPso as usize; - let calls = Arc::new(AtomicUsize::new(0)); - let build_calls = calls.clone(); - pso_async::submit_lazy(one_shot, false, Box::new(move || { - build_calls.fetch_add(1, Ordering::Relaxed); - one_shot_real - }), 0); - let retained = pso_async::begin_pipeline_resolution(one_shot).unwrap(); - let list = 0x7100_48E0; - assert_eq!(resolve_pipeline(list, one_shot, Some(retained.clone())), Some(one_shot_real)); - assert_eq!(resolve_pipeline(list, one_shot, Some(retained)), Some(one_shot_real)); - assert_eq!(calls.load(Ordering::Relaxed), 1, "one-shot build must be consumed once"); - assert_eq!(list_x::native_generation_count_for_test(list), 1); - assert_eq!(real.refs.load(Ordering::Relaxed), 2, "repeated draws retained more than one COM owner"); - assert_eq!(pso_async::released(one_shot), one_shot_real); - list_x::clear_segment_state(list); - assert_eq!(unsafe { resolution_release(one_shot_real as *mut c_void) }, 0); - - let failed = 0x7100_48E8usize; - pso_async::submit_lazy(failed, false, Box::new(|| 0), 0); - let retained = pso_async::begin_pipeline_resolution(failed).unwrap(); - assert_eq!(resolve_pipeline(0x7100_48E9, failed, Some(retained)), None); - assert_eq!(pso_async::released(failed), 0); + let list_ptr = &*fake as *const FakeAdoptedList as *mut c_void; - let unavailable = 0x7100_48F0usize; - pso_async::submit_recipe_keyed(unavailable, false, pso_async::Recipe::new(|| panic!("orphan recipe ran")), false, 0, None); - let retained = pso_async::begin_pipeline_resolution(unavailable).unwrap(); - assert_eq!(pso_async::released(unavailable), 0); - assert_eq!(resolve_pipeline(0x7100_4900, unavailable, Some(retained)), None); + // 1. Background compute build SUCCEEDS: real PSO R is registered in TRANSLATED_COMPUTE, + // stand-in S is NOT. ExecuteIndirect resolves S -> R and treats it as translated. + let standin_ok = 0x7200_0001usize; + let pso_vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; + let mut real_ok_pso = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let real_ok = &mut real_ok_pso as *mut ResolutionPso as usize; + let sig_root_changing = 0x7200_00F0usize; + note_indirect_signature(sig_root_changing, IndirectSignatureInfo::new(false, true, None)); - let replacement = 0x7100_4910usize; - pso_async::submit_lazy(replacement, false, Box::new(|| panic!("unregistered bind adopted later registry entry")), 0); - assert_eq!(resolve_pipeline(0, replacement, None), Some(replacement)); - assert_eq!(pso_async::released(replacement), 0); - } + pso_async::submit( + standin_ok, + true, + Box::new(move || { + real::register_translated_compute_for_test(real_ok); + real_ok + }), + ); + assert_eq!(pso_async::resolve_wait(standin_ok), real_ok); + assert!(!real::is_translated_compute(standin_ok)); + assert!(real::is_translated_compute(real_ok)); - #[test] - fn pipeline_resolution_replacements_drop_outside_state_lock() { - let cases: [fn(*mut c_void); 4] = [ - |list| clear_state(list, 0x7100_5001), - |list| reset(list, 0, 0x7100_5002), - |list| set_tracked_pipeline_state(list, 0x7100_5003), - forget, - ]; - for (n, replace) in cases.into_iter().enumerate() { - let list = (0x7100_5100usize + n) as *mut c_void; - let dropped = Arc::new(AtomicBool::new(false)); - with(list, |_| {}); - let old_entry = STATES.get(list as usize).unwrap(); - let resolution = probed_resolution( - list as usize, - 0x7100_5200 + n, - Arc::downgrade(&old_entry), - dropped.clone(), - ); - with(list, |s| s.resolution = Some(resolution)); - replace(list); - assert!(dropped.load(Ordering::Acquire), "case {n} retained the replaced resolution"); - drop(old_entry); - if n + 1 != cases.len() { - forget(list); - } + reset(list_ptr, 0x7200_0100, standin_ok); + unsafe { + // With `sig_root_changing`, a translated compute PSO is caught by the root-changing + // guard instead of falling through to `pc` (which happened when `R` wasn't registered). + execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); } - } + assert_eq!( + fake.execute_indirect_calls.load(Ordering::Relaxed), + 0, + "ExecuteIndirect must recognize resolved async compute PSO R as translated" + ); - #[test] - fn split_retains_the_exact_resolution_across_address_reuse() { - let from = 0x7100_6001usize as *mut c_void; - let to = 0x7100_6002usize as *mut c_void; - let original = 0x7100_6100usize; - let old = pso_async::pipeline_resolution_for_test(original, || {}); - let old_identity = old.identity_for_test(); - with(from, |s| { - s.pso = original; - s.resolution = Some(old); - }); - reset(to, 0, 0); + // 2. Background compute build FAILS (returns 0): stand-in S_fail is NOT in + // TRANSLATED_COMPUTE. Dispatch must skip cleanly without binding XCL's ABI RS/UAVs + // onto S_fail, and ExecuteIndirect must not enter bind_abi either. + let standin_fail = 0x7200_0003usize; + pso_async::submit(standin_fail, true, Box::new(|| 0)); + assert_eq!(pso_async::resolve_wait(standin_fail), standin_fail); + assert!(!real::is_translated_compute(standin_fail)); - let prepared = prepare_split(from, to, 0); - let replacement = pso_async::pipeline_resolution_for_test(original, || {}); - let replacement_identity = replacement.identity_for_test(); - assert_ne!(old_identity.1, replacement_identity.1); - with(from, |s| s.resolution = Some(replacement)); - install_prepared_split(prepared); + reset(list_ptr, 0x7200_0100, standin_fail); + unsafe { set_graphics_root_signature(list_ptr, title_rs as *mut c_void) }; + 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!(with(to, |s| s.resolution.as_ref().unwrap().identity_for_test()), old_identity, - "split state was redirected to the Pending now stored at the reused title address"); - assert_eq!(with(from, |s| s.resolution.as_ref().unwrap().identity_for_test()), replacement_identity); - forget(from); - forget(to); - } + 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" + ); - #[test] - fn split_reset_uses_only_an_owned_ready_generation() { - let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; - let mut native = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let raw = &mut native as *mut ResolutionPso as usize; - let standin = 0x7100_6200usize; - let from = 0x7100_6201usize as *mut c_void; - let to = 0x7100_6202usize as *mut c_void; - pso_async::submit_lazy(standin, false, Box::new(move || raw), 0); - assert_eq!(pso_async::resolve_wait(standin), raw); - set_tracked_pipeline_state(from, standin); - reset(to, 0, 0); - let prepared = prepare_split(from, to, 0); - let (initial, pin) = prepared.initial_pipeline(); - assert_eq!(initial, raw); - assert!(pin.is_some(), "ready split initial pipeline has no exact owner"); - drop(pin); drop(prepared); forget(from); forget(to); - let raw_owner = pso_async::released(standin); - assert_eq!(raw_owner, raw); - assert_eq!(unsafe { resolution_release(raw_owner as *mut c_void) }, 0); + // 3. The same failed stand-in (made from a console shader) with a Dispatch signature: + // nothing to run, as for Dispatch – the PC call would pair the stand-in with the list's + // compute root signature (XCL's ABI one after a translated dispatch: debug layer 953) + let sig_dispatch = 0x7200_00F8usize; + real::register_console_compute_for_test(standin_fail); + note_indirect_signature(sig_dispatch, IndirectSignatureInfo::new(true, false, None)); + let before = counts_snapshot(); + unsafe { + execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + } + let after = counts_snapshot(); + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 1, "a dispatch of an untranslated console compute pipeline must not reach the PC ExecuteIndirect"); + assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]); - let pending = 0x7100_6210usize; - let from = 0x7100_6211usize as *mut c_void; - let to = 0x7100_6212usize as *mut c_void; - pso_async::submit_lazy(pending, false, Box::new(|| panic!("split Reset started pending build")), 0); - set_tracked_pipeline_state(from, pending); - reset(to, 0, 0); - let prepared = prepare_split(from, to, 0); - assert!(matches!(prepared.initial_pipeline(), (0, None)), "pending split consulted its reusable address"); - drop(prepared); forget(from); forget(to); - assert_eq!(pso_async::released(pending), 0); - } + // 3b. The same with a shared stand-in (`standin::shell`): the failed build resolves to the + // driver pipeline, which was never registered – the title's object is + let shell_fail = 0x7200_0005usize; + let driver = 0x7200_0006usize; + pso_async::submit(shell_fail, true, Box::new(|| 0)); + pso_async::shared(shell_fail, driver); + assert_eq!(pso_async::resolve_wait(shell_fail), driver); + real::register_console_compute_for_test(shell_fail); + reset(list_ptr, 0x7200_0100, shell_fail); + let before = counts_snapshot(); + unsafe { + execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + } + let after = counts_snapshot(); + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 1, "a failed shared stand-in's dispatch must not reach the PC ExecuteIndirect"); + assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]); + let _ = pso_async::released(shell_fail); + real::forget_pso_for_test(shell_fail); - #[test] - fn kickoff_reset_uses_the_retained_generation_after_address_reuse() { - let vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; - let mut original = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let mut replacement = ResolutionPso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let original_raw = &mut original as *mut ResolutionPso as usize; - let replacement_raw = &mut replacement as *mut ResolutionPso as usize; - let standin = 0x7100_6220usize; - let list = 0x7100_6221usize as *mut c_void; + // 4. A native PC compute pipeline (not made from a console shader) with the same Dispatch + // signature still goes to the PC call, as on main + let native = 0x7200_0004usize; + reset(list_ptr, 0x7200_0100, native); + unsafe { + execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + } + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 2, "a native PC compute pipeline must still reach the PC ExecuteIndirect"); - pso_async::submit_lazy(standin, false, Box::new(move || original_raw), 0); - assert_eq!(pso_async::resolve_wait(standin), original_raw); - set_tracked_pipeline_state(list, standin); - let original_owner = pso_async::released(standin); - assert_eq!(original_owner, original_raw); + // a signature made later at the same address without a Dispatch argument goes to the PC + reset(list_ptr, 0x7200_0100, standin_fail); + note_indirect_signature(sig_dispatch, IndirectSignatureInfo::default()); + unsafe { + set_graphics_root_signature(list_ptr, title_rs as *mut c_void); + execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + } + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 3); - pso_async::submit_lazy(standin, false, Box::new(move || replacement_raw), 0); - assert_eq!(pso_async::resolve_wait(standin), replacement_raw); - let (initial, pin) = initial_pipeline(list); - assert_eq!(initial, original_raw, "Kickoff Reset followed the reused title address"); - assert!(pin.is_some(), "Kickoff Reset did not own the retained generation"); - assert_eq!(replacement.refs.load(Ordering::Relaxed), 1, "Kickoff Reset retained the replacement generation"); + forget(list_ptr); + list_x::on_release(list_ptr as usize); + let real_ok_owner = pso_async::released(standin_ok); + let _ = pso_async::released(standin_fail); + real::forget_pso_for_test(real_ok); + real::forget_pso_for_test(standin_fail); + assert_eq!(real_ok_owner, real_ok); + assert_eq!(unsafe { resolution_release(real_ok_owner as *mut c_void) }, 0); + assert!(!real::is_console_compute(standin_fail), "a released pipeline's address does not stay a console one"); + } - let replacement_owner = pso_async::released(standin); - assert_eq!(replacement_owner, replacement_raw); - drop(pin); - forget(list); - assert_eq!(unsafe { resolution_release(original_owner as *mut c_void) }, 0); - assert_eq!(unsafe { resolution_release(replacement_owner as *mut c_void) }, 0); + /// Two-pass buffers of a recording with no known allocator are kept, not dropped at once (the + /// GPU may not have run the list), and go once they are 10 s old; past the cap the oldest go. + #[test] + fn buffers_with_no_allocator_are_kept_until_old_enough() { + use std::time::{Duration, Instant}; + let t = Instant::now(); + let mut a: Aging = Aging::new(100); + assert_eq!(a.hold(t, vec![(10, 1), (10, 2)]), 0); + assert_eq!(a.hold(t + Duration::from_secs(4), vec![(10, 3)]), 0); + assert!(a.take_older(t + Duration::from_secs(9), UNKNOWN_RES_AGE).is_empty(), "the list may still run"); + assert_eq!(a.take_older(t + Duration::from_secs(10), UNKNOWN_RES_AGE), vec![1, 2]); + assert_eq!(a.take_older(t + Duration::from_secs(14), UNKNOWN_RES_AGE), vec![3]); + assert_eq!(a.bytes, 0); + // past the cap: the oldest go, never the one just handed over + assert_eq!(a.hold(t, vec![(60, 4)]), 0); + assert_eq!(a.hold(t, vec![(60, 5)]), 1); + assert_eq!(a.hold(t, vec![(200, 6)]), 1); + assert_eq!(a.take_older(t + UNKNOWN_RES_AGE, UNKNOWN_RES_AGE), vec![6]); + // through `hold_res_until_reset` with allocator 0: kept, not dropped + unsafe { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + // (WARP only: no hardware device) + let Ok(factory) = CreateDXGIFactory1::() else { return }; + let Ok(warp) = factory.EnumWarpAdapter::() else { return }; + let mut dev: Option = None; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return; + } + let buf = TwoPassBuf::make(&dev.unwrap(), 1 << 16, "test").unwrap(); + let raw = buf.res.as_raw() as usize; + let kept = |r: usize| UNKNOWN_RES.lock().unwrap().held.iter().any(|h| h.2.res.as_raw() as usize == r); + hold_res_until_reset(0, vec![buf]); + assert!(kept(raw), "a buffer of a recording with no allocator is kept"); + } } + /// A draw decides once what its pipeline is, from what its retained resolution gave (the + /// pipeline and whether it was bound unbuilt, `resolve_indirect_pipeline`): the stand-in of a + /// two-pass pipeline whose build finished after that is still the stand-in (skipped), never + /// the two passes with the stand-in as their mesh pipeline; the built one runs the two passes. #[test] - fn split_preflight_transfers_destination_uma_before_install() { - let from = 0x7101_0001usize as *mut c_void; - let to = 0x7101_0002usize as *mut c_void; - let (old_alloc, new_alloc) = (0x7101_0100usize, 0x7101_0200usize); - let _ = console_list::take_pending_for_test(old_alloc); - seed_reset_state_for_test(from, 0x7101_0300, 0x7101_1000, vec![0x7101_4000]); - seed_reset_state_for_test(to, old_alloc, 0x7101_2000, vec![0x7101_5000, 0x7101_6000]); + fn a_draw_with_the_stand_in_of_a_two_pass_pipeline_is_not_recorded_as_its_passes() { + let (standin, real_mesh, failed, native) = (0x7E57_7001usize, 0x7E57_7002usize, 0x7E57_7003usize, 0x7E57_7004usize); + real::register_two_pass_for_test(real_mesh, "MS"); + // lazy submits: no worker starts them, so the states stay under the test's control + pso_async::submit_lazy(standin, false, Box::new(move || real_mesh), 0); + pso_async::submit_lazy(failed, false, Box::new(|| 0), 0); + assert!(matches!(draw_pipeline(standin, true), DrawPipeline::StandIn), "being built"); + // built now: a bind that resolved before has the stand-in (the second resolve that + // `two_pass_of` makes finds the two passes – what recorded them with the stand-in) + assert_eq!(pso_async::resolve_wait(standin), real_mesh); + assert!(real::two_pass_of(standin).is_some()); + assert!(matches!(draw_pipeline(standin, true), DrawPipeline::StandIn), "resolved before the build finished"); + assert!(matches!(draw_pipeline(real_mesh, false), DrawPipeline::TwoPass(_))); + assert_eq!(pso_async::resolve_wait(failed), failed); + assert!(matches!(draw_pipeline(failed, false), DrawPipeline::Other), "a failed build's stand-in draws as before"); + assert!(matches!(draw_pipeline(native, false), DrawPipeline::Other)); + // a shared stand-in (`standin::shell`): `resolve_wait` gives the driver pipeline behind it + let (shell, driver) = (0x7E57_7005usize, 0x7E57_7006usize); + pso_async::submit_lazy(shell, false, Box::new(|| 0), 0); + pso_async::shared(shell, driver); + assert!(matches!(draw_pipeline(driver, true), DrawPipeline::StandIn), "a shared stand-in being built"); + pso_async::released(shell); + pso_async::released(standin); + pso_async::released(failed); + real::forget_pso_for_test(real_mesh); + assert!(matches!(draw_pipeline(real_mesh, false), DrawPipeline::Other)); + } - let prepared = prepare_split(from, to, new_alloc); - assert_eq!(reset_state_for_test(from), (0x7101_0300, 0x7101_1000, vec![1, 2, 3, 4], vec![5, 6, 7, 8], vec![0x7101_4000])); - assert_eq!(reset_state_for_test(to), (0, 0x7101_2000, vec![1, 2, 3, 4], vec![5, 6, 7, 8], Vec::new())); + static FAKE_DRAWS: AtomicUsize = AtomicUsize::new(0); - install_prepared_split(prepared); - assert_eq!(reset_state_for_test(to), (new_alloc, 0x7101_1000, vec![1, 2, 3, 4], vec![5, 6, 7, 8], Vec::new())); - assert_eq!(console_list::take_pending_for_test(old_alloc), vec![0x7101_5000, 0x7101_6000]); - remove_state_for_test(from); - remove_state_for_test(to); + unsafe extern "system" fn fake_draw_instanced(_this: *mut c_void, _v: u32, _i: u32, _sv: u32, _si: u32) { + FAKE_DRAWS.fetch_add(1, Ordering::Relaxed); } - #[test] - fn reset_keys_uma_to_the_lists_native_allocator_backing() { - let list = 0x7101_7001usize as *mut c_void; - let (logical, native, old_native, block) = (0x7101_7100usize, 0x7101_7200usize, 0x7101_7300usize, 0x7101_7400usize); - let _ = console_list::take_pending_for_test(old_native); - super::super::alloc_pool::created_on(list as usize, native, D3D12_COMMAND_LIST_TYPE_DIRECT.0); - seed_reset_state_for_test(list, old_native, 0, vec![block]); - - reset(list, logical, 0); + unsafe extern "system" fn fake_noop_ptr(_this: *mut c_void, _p: *mut c_void) {} - assert_eq!(reset_state_for_test(list).0, native, - "UMA ownership follows the recording's native backing, not the title allocator"); - assert_eq!(console_list::take_pending_for_test(old_native), vec![block]); - remove_state_for_test(list); - super::super::alloc_pool::forget_list(list as usize); - unsafe { super::super::alloc_pool::forget(native); } + /// A two-pass pipeline never reaches a PC call under the title's root signature: not an + /// ExecuteIndirect whose signature is not a noted DispatchMesh one, not a Draw. A draw with a + /// PC pipeline and no graphics root signature on the list is skipped too. + #[test] + fn a_two_pass_pipeline_or_a_list_without_a_root_signature_does_not_reach_the_pc_call() { + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fake_add_ref as usize; + orig_vt[2] = fake_release as usize; + orig_vt[12] = fake_draw_instanced as usize; + orig_vt[25] = fake_set_pso as usize; + orig_vt[30] = fake_noop_ptr as usize; // SetGraphicsRootSignature + orig_vt[59] = fake_execute_indirect as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let fake = Box::new(FakeAdoptedList { + // SAFETY: `ext_vt` has 65 elements so `.add(1)` points to slot 0 with `orig_vt` at `-1`. + vt: unsafe { ext_vt.as_ptr().add(1) }, + refs: AtomicUsize::new(1), + dispatch_calls: AtomicUsize::new(0), + set_compute_rs_calls: AtomicUsize::new(0), + set_compute_uav_calls: AtomicUsize::new(0), + set_pso_calls: AtomicUsize::new(0), + last_pso: AtomicUsize::new(0), + execute_indirect_calls: AtomicUsize::new(0), + }); + let list = &*fake as *const FakeAdoptedList as *mut c_void; + let (mesh, native, rs, sig) = (0x7E57_8001usize, 0x7E57_8002usize, 0x7E57_8003usize, 0x7E57_80F0usize); + real::register_two_pass_for_test(mesh, "MS"); + reset(list, 0x7E57_8100, mesh); + unsafe { + set_graphics_root_signature(list, rs as *mut c_void); + let before = counts_snapshot(); + execute_indirect(list, sig, 1, 0, 0, 0, 0); + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0, "a signature that is not a noted DispatchMesh one"); + draw_instanced(list, 3, 1, 0, 0); + assert_eq!(FAKE_DRAWS.load(Ordering::Relaxed), 0, "a Draw with a mesh pipeline"); + assert!(counts_snapshot()[DRAWS_SKIPPED] >= before[DRAWS_SKIPPED] + 2); + // a PC pipeline draws, with the title's root signature + reset(list, 0x7E57_8100, native); + set_graphics_root_signature(list, rs as *mut c_void); + draw_instanced(list, 3, 1, 0, 0); + execute_indirect(list, sig, 1, 0, 0, 0, 0); + assert_eq!((FAKE_DRAWS.load(Ordering::Relaxed), fake.execute_indirect_calls.load(Ordering::Relaxed)), (1, 1)); + // … and without one (a reset clears it), not: it would run under what the list holds + reset(list, 0x7E57_8100, native); + draw_instanced(list, 3, 1, 0, 0); + execute_indirect(list, sig, 1, 0, 0, 0, 0); + assert_eq!((FAKE_DRAWS.load(Ordering::Relaxed), fake.execute_indirect_calls.load(Ordering::Relaxed)), (1, 1)); + // a dispatch signature does not need it + note_indirect_signature(sig, IndirectSignatureInfo::new(true, false, None)); + execute_indirect(list, sig, 1, 0, 0, 0, 0); + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 2); + note_indirect_signature(sig, IndirectSignatureInfo::default()); + } + forget(list); + real::forget_pso_for_test(mesh); } #[test] - fn abandoned_split_preflight_keeps_old_uma_under_its_allocator() { - let from = 0x7102_0001usize as *mut c_void; - let to = 0x7102_0002usize as *mut c_void; - let old_alloc = 0x7102_0100usize; - let _ = console_list::take_pending_for_test(old_alloc); - seed_reset_state_for_test(from, 0x7102_0200, 0x7102_1000, Vec::new()); - seed_reset_state_for_test(to, old_alloc, 0x7102_2000, vec![0x7102_5000]); + fn execute_indirect_skips_failed_shared_console_compute_standin() { + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fake_add_ref as usize; + orig_vt[2] = fake_release as usize; + orig_vt[14] = fake_dispatch as usize; + orig_vt[25] = fake_set_pso as usize; + orig_vt[29] = fake_set_compute_rs as usize; + orig_vt[41] = fake_set_compute_uav as usize; + orig_vt[59] = fake_execute_indirect as usize; - drop(prepare_split(from, to, 0x7102_0300)); - forget(to); + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); - assert_eq!(console_list::take_pending_for_test(old_alloc), vec![0x7102_5000]); - assert_eq!(reset_state_for_test(from).0, 0x7102_0200, "the active producer must remain untouched"); - remove_state_for_test(from); - } + let fake = Box::new(FakeAdoptedList { + vt: unsafe { ext_vt.as_ptr().add(1) }, + refs: AtomicUsize::new(1), + dispatch_calls: AtomicUsize::new(0), + set_compute_rs_calls: AtomicUsize::new(0), + set_compute_uav_calls: AtomicUsize::new(0), + set_pso_calls: AtomicUsize::new(0), + last_pso: AtomicUsize::new(0), + execute_indirect_calls: AtomicUsize::new(0), + }); + let list_ptr = &*fake as *const FakeAdoptedList as *mut c_void; - #[repr(C)] - struct FakeAdoptedList { - vt: *const usize, - refs: AtomicUsize, - dispatch_calls: AtomicUsize, - set_compute_rs_calls: AtomicUsize, - set_compute_uav_calls: AtomicUsize, - set_pso_calls: AtomicUsize, - last_pso: AtomicUsize, - execute_indirect_calls: AtomicUsize, - } + // With shared stand-ins (`standin::shell`), `dev_create_compute_pso` registers the + // title-facing shell in `CONSOLE_COMPUTE`, while `pso_async::resolve_wait` returns the + // shared driver pipeline when the background build fails. + let shell_fail = 0x7210_0001usize; + let shell_ok = 0x7210_0002usize; + let shared_driver = 0x7210_0003usize; + let pso_vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; + let mut real_ok_pso = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let real_ok = &mut real_ok_pso as *mut ResolutionPso as usize; + let sig_dispatch = 0x7210_00F8usize; + let sig_root_changing = 0x7210_00F0usize; + note_indirect_signature(sig_dispatch, IndirectSignatureInfo::new(true, false, None)); + note_indirect_signature(sig_root_changing, IndirectSignatureInfo::new(false, true, None)); - static FAKE_CLEAR_CALLS: AtomicUsize = AtomicUsize::new(0); - static FAKE_CLOSE_CALLS: AtomicUsize = AtomicUsize::new(0); - static FAKE_CLOSED: AtomicBool = AtomicBool::new(false); - static FAKE_RESET_FAIL: AtomicBool = AtomicBool::new(false); - static FAKE_LAST_RESET_PSO: AtomicUsize = AtomicUsize::new(0); - static FAKE_LAST_CLEAR_PSO: AtomicUsize = AtomicUsize::new(usize::MAX); - static FAKE_PIN_COUNT_AT_SET: AtomicUsize = AtomicUsize::new(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 - } + pso_async::submit_lazy(shell_fail, true, Box::new(|| 0), 0); + pso_async::shared(shell_fail, shared_driver); + real::register_console_compute_for_test(shell_fail); - unsafe extern "system" fn fake_release(this: *mut c_void) -> u32 { - (*(this as *const FakeAdoptedList)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 - } + pso_async::submit_lazy( + shell_ok, + true, + Box::new(move || { + real::register_translated_compute_for_test(real_ok); + real_ok + }), + 0, + ); + pso_async::shared(shell_ok, shared_driver); + real::register_console_compute_for_test(shell_ok); - 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); - } + assert_eq!(pso_async::resolve_wait(shell_fail), shared_driver); + assert!(!pso_async::is_pending(shell_fail)); + assert!(real::is_console_compute(shell_fail)); + assert!(!real::is_console_compute(shared_driver)); - unsafe extern "system" fn fake_set_pso(this: *mut c_void, pso: *mut c_void) { - let list = &*(this as *const FakeAdoptedList); - FAKE_PIN_COUNT_AT_SET.store(list_x::native_generation_count_for_test(this as usize), Ordering::Release); - list.set_pso_calls.fetch_add(1, Ordering::Relaxed); - list.last_pso.store(pso as usize, Ordering::Release); - } + // 1. Failed shared console compute stand-in with a Dispatch signature must be skipped, + // never forwarded to PC ExecuteIndirect with the shared driver pipeline. + reset(list_ptr, 0x7210_0100, shell_fail); + let before = counts_snapshot(); + unsafe { + execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + } + let after = counts_snapshot(); + assert_eq!( + fake.execute_indirect_calls.load(Ordering::Relaxed), + 0, + "failed shared console compute stand-in must not reach PC ExecuteIndirect" + ); + assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]); - unsafe extern "system" fn fake_clear_state(_this: *mut c_void, pso: *mut c_void) { - FAKE_CLEAR_CALLS.fetch_add(1, Ordering::Relaxed); - FAKE_LAST_CLEAR_PSO.store(pso as usize, Ordering::Release); - } - unsafe extern "system" fn fake_close(_this: *mut c_void) -> windows::core::HRESULT { - FAKE_CLOSE_CALLS.fetch_add(1, Ordering::Relaxed); - FAKE_CLOSED.store(true, Ordering::Release); - windows::core::HRESULT(0) - } - unsafe extern "system" fn fake_reset(_this: *mut c_void, _alloc: usize, pso: usize) -> i32 { - FAKE_LAST_RESET_PSO.store(pso, Ordering::Release); - if FAKE_RESET_FAIL.load(Ordering::Acquire) || !FAKE_CLOSED.swap(false, Ordering::AcqRel) { - crate::util::E_FAIL - } else { 0 } - } - 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); - } + // 2. Another shell sharing the same driver pipeline whose build succeeds still takes the + // translated path (caught here by the root-changing guard rather than falling through to PC). + reset(list_ptr, 0x7210_0100, shell_ok); + unsafe { + execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); + } + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0); - 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); - } + // 3. Releasing `shell_fail` forgets its `CONSOLE_COMPUTE` entry so a native PC compute + // pipeline later allocated at the same address still reaches PC ExecuteIndirect. + let _ = pso_async::released(shell_fail); + real::forget_pso_for_test(shell_fail); + assert!(!real::is_console_compute(shell_fail)); + reset(list_ptr, 0x7210_0100, shell_fail); + unsafe { + execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + } + assert_eq!( + fake.execute_indirect_calls.load(Ordering::Relaxed), + 1, + "native PC pipeline at a released shell's address must still reach PC ExecuteIndirect" + ); - unsafe extern "system" fn fake_execute_indirect( - this: *mut c_void, - _sig: usize, - _max: u32, - _args: usize, - _args_off: u64, - _count_buf: usize, - _count_off: u64, - ) { - (*(this as *const FakeAdoptedList)).execute_indirect_calls.fetch_add(1, Ordering::Relaxed); + forget(list_ptr); + note_indirect_signature(sig_dispatch, IndirectSignatureInfo::default()); + list_x::on_release(list_ptr as usize); + let real_ok_owner = pso_async::released(shell_ok); + real::forget_pso_for_test(shell_ok); + real::forget_pso_for_test(real_ok); + assert_eq!(real_ok_owner, real_ok); + assert_eq!(unsafe { resolution_release(real_ok_owner as *mut c_void) }, 0); } #[test] - fn title_pipeline_binds_use_one_retained_identity_and_fail_closed() { - let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); + fn two_pass_pso_skips_direct_draw_and_unmatched_execute_indirect() { + #[repr(C)] + struct FakeTwoPassList { + vt: *const usize, + refs: AtomicUsize, + set_graphics_rs_calls: AtomicUsize, + execute_indirect_calls: AtomicUsize, + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + (*(this as *const FakeTwoPassList)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + (*(this as *const FakeTwoPassList)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 + } + unsafe extern "system" fn set_graphics_rs(this: *mut c_void, _rs: *mut c_void) { + (*(this as *const FakeTwoPassList)).set_graphics_rs_calls.fetch_add(1, Ordering::Relaxed); + } + unsafe extern "system" fn exec_indirect( + this: *mut c_void, + _sig: usize, + _max: u32, + _args: usize, + _args_off: u64, + _count_buf: usize, + _count_off: u64, + ) { + (*(this as *const FakeTwoPassList)).execute_indirect_calls.fetch_add(1, Ordering::Relaxed); + } + let mut orig_vt = [0usize; 64]; - orig_vt[1] = fake_add_ref as usize; orig_vt[2] = fake_release as usize; - orig_vt[9] = fake_close as usize; orig_vt[11] = fake_clear_state as usize; - orig_vt[10] = fake_reset as usize; orig_vt[14] = fake_dispatch as usize; - orig_vt[25] = fake_set_pso as usize; orig_vt[59] = fake_execute_indirect as usize; + orig_vt[1] = add_ref as usize; + orig_vt[2] = release as usize; + orig_vt[30] = set_graphics_rs as usize; + orig_vt[59] = exec_indirect as usize; + let mut ext_vt = vec![0usize; 65]; ext_vt[0] = orig_vt.as_ptr() as usize; ext_vt[1..].copy_from_slice(&orig_vt); - let fake = Box::new(FakeAdoptedList { - vt: unsafe { ext_vt.as_ptr().add(1) }, refs: AtomicUsize::new(1), - dispatch_calls: AtomicUsize::new(0), set_compute_rs_calls: AtomicUsize::new(0), - set_compute_uav_calls: AtomicUsize::new(0), set_pso_calls: AtomicUsize::new(0), - last_pso: AtomicUsize::new(0), execute_indirect_calls: AtomicUsize::new(0), + + let fake = Box::new(FakeTwoPassList { + vt: unsafe { ext_vt.as_ptr().add(1) }, + refs: AtomicUsize::new(1), + set_graphics_rs_calls: AtomicUsize::new(0), + execute_indirect_calls: AtomicUsize::new(0), }); - let list = &*fake as *const FakeAdoptedList as *mut c_void; - let _class = real::test_command_list_class( - orig_vt.as_ptr() as usize, - unsafe { ext_vt.as_ptr().add(1) } as usize, - ); - unsafe { list_x::on_create(list, 0, 0, D3D12_COMMAND_LIST_TYPE_DIRECT) }; + let list_ptr = &*fake as *const FakeTwoPassList as *mut c_void; + + // Register a finished two-pass GS/MS PSO behind an async stand-in (registered in TWO_PASS, + // not TRANSLATED_GRAPHICS). + let standin_tp = 0x7250_0001usize; let pso_vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; - let mut old = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let mut replacement = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let old_raw = &mut old as *mut ResolutionPso as usize; - let replacement_raw = &mut replacement as *mut ResolutionPso as usize; - let original = 0x7100_48F8usize; - pso_async::submit_lazy(original, true, Box::new(move || old_raw), 0); - assert_eq!(pso_async::resolve_wait(original), old_raw); - let retained = pso_async::begin_pipeline_resolution(original).unwrap(); - let retained_identity = retained.identity_for_test(); - let old_owner = pso_async::released(original); - let replacement_calls = Arc::new(AtomicUsize::new(0)); let calls = replacement_calls.clone(); - pso_async::submit_lazy(original, true, Box::new(move || { - calls.fetch_add(1, Ordering::Relaxed); - replacement_raw - }), 0); - let alias_calls = Arc::new(AtomicUsize::new(0)); let calls = alias_calls.clone(); - pso_async::submit_lazy(old_raw, true, Box::new(move || { - calls.fetch_add(1, Ordering::Relaxed); - replacement_raw - }), 0); - FAKE_PIN_COUNT_AT_SET.store(0, Ordering::Release); - unsafe { set_pipeline_state_retained(list, original, Some(retained)) }; - assert_eq!(fake.last_pso.load(Ordering::Acquire), old_raw); - assert_eq!(FAKE_PIN_COUNT_AT_SET.load(Ordering::Acquire), 1, "exact generation was not pinned before native SetPipelineState"); - assert_eq!(replacement_calls.load(Ordering::Relaxed), 0); - assert_eq!(alias_calls.load(Ordering::Relaxed), 0); - assert_eq!(list_x::bound_pipeline_for_test(list as usize), original); - assert_eq!(with(list, |s| s.resolution.as_ref().unwrap().identity_for_test()), retained_identity); - let clear_resolution = with(list, |s| s.resolution.clone()); - FAKE_CLEAR_CALLS.store(0, Ordering::Release); - unsafe { clear_pipeline_state_retained(list, original, clear_resolution) }; - assert_eq!(FAKE_CLEAR_CALLS.load(Ordering::Acquire), 1); - assert_eq!(FAKE_LAST_CLEAR_PSO.load(Ordering::Acquire), old_raw); - assert_eq!(list_x::native_generation_count_for_test(list as usize), 1, "Set and Clear duplicated the exact generation pin"); - assert_eq!(replacement_calls.load(Ordering::Relaxed), 0); - assert_eq!(alias_calls.load(Ordering::Relaxed), 0); - let unavailable = pso_async::pipeline_resolution_for_compute_test(original, || {}) - .unavailable_for_test(); - let (before_sets, before_clears) = (fake.set_pso_calls.load(Ordering::Relaxed), FAKE_CLEAR_CALLS.load(Ordering::Relaxed)); - unsafe { set_pipeline_state_retained(list, original, Some(unavailable)) }; - assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), before_sets, "unavailable SetPipelineState rebound the prior native pipeline"); - assert_eq!(FAKE_CLEAR_CALLS.load(Ordering::Relaxed), before_clears, "eligible omission reset logical root state"); - assert!(!list_x::recording_poisoned(list as usize)); + let mut real_tp_pso = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let real_tp = &mut real_tp_pso as *mut ResolutionPso as usize; + pso_async::submit( + standin_tp, + false, + Box::new(move || { + real::register_two_pass_for_test(real_tp, "GS"); + real_tp + }), + ); + assert_eq!(pso_async::resolve_wait(standin_tp), real_tp); + assert!(real::two_pass_of(real_tp).is_some()); + assert!(!real::is_translated_graphics(real_tp)); + + reset(list_ptr, 0x7250_0100, standin_tp); unsafe { - dispatch_flags(list, 1, 1, 1, 0); - execute_indirect_retained( - list, 1, 1, 0, 0, 0, 0, IndirectSignatureInfo::new(true, false, None), + // Seed a non-null title graphics RS so a fallthrough would visibly call SetGraphicsRootSignature. + set_graphics_root_signature(list_ptr, list_ptr); + } + + // 1. Direct draw (`graphics_bound`) must return None without binding the title's RS. + let before = counts_snapshot(); + let bound = unsafe { graphics_bound(list_ptr) }; + let after = counts_snapshot(); + assert!(bound.is_none(), "two-pass MS/GS PSO must not fall through to PC DrawInstanced"); + assert!(after[DRAWS_SKIPPED] > before[DRAWS_SKIPPED]); + assert_eq!(after[DRAWS_PC], before[DRAWS_PC]); + assert_eq!(fake.set_graphics_rs_calls.load(Ordering::Relaxed), 0); + + // 2. Unmatched `ExecuteIndirect` must skip without binding the title's RS or calling PC ExecuteIndirect. + let before = counts_snapshot(); + unsafe { + execute_indirect(list_ptr, 0x7250_00F0, 1, 0, 0, 0, 0); + } + let after = counts_snapshot(); + assert!(after[DRAWS_SKIPPED] > before[DRAWS_SKIPPED]); + assert_eq!(fake.set_graphics_rs_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0); + + forget(list_ptr); + list_x::clear_segment_state(list_ptr as usize); + let real_tp_owner = pso_async::released(standin_tp); + real::forget_pso_for_test(real_tp); + assert_eq!(real_tp_owner, real_tp); + assert_eq!(unsafe { resolution_release(real_tp_owner as *mut c_void) }, 0); + assert!(real::two_pass_of(real_tp).is_none()); + } + + #[test] + fn create_list_reset_and_clear_state_track_initial_pso_on_d3d12() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + if console_list::enabled() { + return; + } + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.expect("D3D12 device"); + real::adopt(dev.as_raw(), real::Kind::Device); + + // Build two real PC compute PSOs from the inbox dummy CS bytecode. + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).expect("serialize RS"); + let ser = ser.unwrap(); + let rs: ID3D12RootSignature = dev + .CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())) + .expect("CreateRootSignature"); + let cs = real::dummy_cs_bytecode(); + let make_pso = || -> ID3D12PipelineState { + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }, + ..Default::default() + }; + let pso = dev.CreateComputePipelineState(&desc).expect("CreateComputePipelineState"); + std::mem::ManuallyDrop::drop(&mut desc.pRootSignature); + pso + }; + let pso1 = make_pso(); + let pso2 = make_pso(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + + // Stand-in synthetic key backed by real `pso1` in pso_async: CreateCommandList must + // resolve it via resolve_for_bind for PC D3D12 while tracking `standin` in `bind`. + let standin = 0x7300_0001usize; + let pso1_raw = pso1.as_raw() as usize; + pso_async::submit(standin, true, Box::new(move || pso1_raw)); + assert_eq!(pso_async::resolve_wait(standin), pso1_raw); + + let mut raw_list: *mut c_void = std::ptr::null_mut(); + let iid = windows_sys::core::GUID::from_u128(0x5b160d0f_ac1b_4185_8ba8_b3ae42a5a455); + let hr = device_x::create_command_list_pc( + dev.as_raw(), + 0, + D3D12_COMMAND_LIST_TYPE_DIRECT.0 as u32, + alloc.as_raw() as usize, + standin, + &iid, + &mut raw_list, ); + assert!(hr >= 0 && !raw_list.is_null(), "create_command_list_pc failed: {hr:#x}"); + let backing = title_list::backing(raw_list).expect("wrapped in title_list"); + assert_eq!(tracked_pso(backing), standin, "CreateCommandList must seed bind::State.pso"); + + // ClearState(pso2) updates bind::State.pso to pso2 and clears root args. + let rs_key = 0x7300_0010usize; + console_list::note_root_signature(rs_key, &test_rts0_blob()); + set_compute_root_signature(backing, rs_key as *mut c_void); + set_compute_root_constant(backing, 0, 0xABCD, 0); + let cl = ID3D12GraphicsCommandList::from_raw_borrowed(&backing).unwrap(); + cl.ClearState(&pso2); + assert_eq!(tracked_pso(backing), pso2.as_raw() as usize, "ClearState must update bind::State.pso"); + with(backing, |s| assert!(s.layout.is_none() && s.args.is_empty())); + + // ClearState(None) clears bind::State.pso to 0. + cl.ClearState(None); + assert_eq!(tracked_pso(backing), 0, "ClearState(None) must clear bind::State.pso"); + + // Close + reset_x(alloc, pso2) updates bind::State.pso to pso2 and clears root args. + set_graphics_root_signature(backing, rs_key as *mut c_void); + set_graphics_root_constant(backing, 0, 0x1111, 0); + cl.Close().expect("Close"); + let hr = list_x::reset_x(backing, alloc.as_raw() as usize, pso2.as_raw() as usize); + assert!(hr >= 0, "reset_x failed: {hr:#x}"); + assert_eq!(tracked_pso(backing), pso2.as_raw() as usize, "Reset must update bind::State.pso"); + with(backing, |s| assert!(s.layout_gfx.is_none() && s.args_gfx.is_empty())); + + // Release the wrapped title list cleanly (calls bind::forget + list_x::on_release). + let release_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(raw_list as *const *const usize)).add(2)); + assert_eq!(release_fn(raw_list), 0); + let _ = pso_async::released(standin); } - assert_eq!(fake.dispatch_calls.load(Ordering::Relaxed), 0, "unavailable Dispatch executed the preceding PSO"); - assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0, "unavailable ExecuteIndirect executed the preceding PSO"); + } - let unavailable = pso_async::pipeline_resolution_for_test(original, || {}).unavailable_for_test(); - let (before_sets, before_clears) = (fake.set_pso_calls.load(Ordering::Relaxed), FAKE_CLEAR_CALLS.load(Ordering::Relaxed)); - unsafe { set_pipeline_state_retained(list, original, Some(unavailable)) }; - assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), before_sets); - assert_eq!(FAKE_CLEAR_CALLS.load(Ordering::Relaxed), before_clears, "poisoning reset physical state"); - assert!(list_x::recording_poisoned(list as usize)); - FAKE_CLOSE_CALLS.store(0, Ordering::Release); - FAKE_CLOSED.store(false, Ordering::Release); - assert!(unsafe { real::close_for_test(list) } < 0); - assert_eq!(FAKE_CLOSE_CALLS.load(Ordering::Acquire), 1, "poisoned Close did not close natively"); - assert!(real::submission_rejected_for_test(&[list]), "poisoned recording passed submission guard"); + #[test] + fn dispatch_mesh_signature_tracking_returns_companion_and_layout() { + let sig = 0x7400_0001usize; + let companion = 0x7400_0002usize; + assert_eq!(dispatch_mesh_sig_of(sig), None); + note_dispatch_mesh_signature(sig, companion, 28, 16); + assert_eq!( + dispatch_mesh_sig_of(sig), + Some(DispatchMeshSig { companion_dispatch: companion, byte_stride: 28, mesh_offset: 16 }) + ); + DISPATCH_MESH_SIGS.lock().unwrap().as_mut().unwrap().remove(&sig); + assert_eq!(dispatch_mesh_sig_of(sig), None); + } - let (parent, bundle) = (0x7100_48FAusize, 0x7100_48FBusize); + /// A signature made at a freed mesh dispatch signature's address (`create_command_signature_x` + /// forgets every new one first) is not taken for a mesh dispatch with the old companion. + #[test] + fn a_signature_at_a_freed_mesh_signatures_address_has_no_companion() { + let sig = 0x7400_0011usize; + note_dispatch_mesh_signature(sig, 0x7400_0012, 16, 0); + assert!(dispatch_mesh_sig_of(sig).is_some()); + forget_dispatch_mesh_signature(sig); + assert_eq!(dispatch_mesh_sig_of(sig), None); + // nothing noted: nothing to forget + forget_dispatch_mesh_signature(0x7400_0013); + } + + #[test] + fn two_pass_io_carries_the_unified_memory_base() { + use crate::gpu::recomp::{IO_UMA_BASE_HI, KERNEL_SGPRS}; + let base = 0x4_0000_0000usize; + for compute_pass in [true, false] { + let io = two_pass_io(None, &[], 0x4_1234_5600, compute_pass, base, [0; 2]); + assert_eq!(io.len(), KERNEL_SGPRS); + assert_eq!(io[IO_UMA_BASE_HI], 4, "compute pass {compute_pass}"); + } + let io = two_pass_io(None, &[], 0x4_1234_5600, true, base, [0; 2]); + assert_eq!((io[8], io[9]), (0x1234_5600, 4)); + } + + /// The root views of a bind that lie in a GPU view are asked for with `ROOT_VIEW_BYTES` each + /// (their size is not known); constants that look like such an address, tables, null and + /// addresses elsewhere are not, and nothing is without view windows. + #[test] + fn root_views_in_a_gpu_view_are_wanted_with_their_bytes() { + use crate::gpu::uma::{Uma, MAX_HEAP_WINDOWS, MAX_WINDOWS, VIEW_WINDOWS, WINDOW}; + let u = Uma::for_runtime_windows(16 << 20, 16 << 20, MAX_HEAP_WINDOWS).expect("16-window aperture"); + let span = view_span_of(&u); + assert_eq!(span.1, (VIEW_WINDOWS * WINDOW) as u64); + let g = u.view_reserve(1 << 20).expect("a GPU view") as u64; + assert!(in_span(span, g) && in_span(span, span.0 + span.1 - 1)); + assert!(!in_span(span, span.0 - 1) && !in_span(span, span.0 + span.1) && !in_span(span, 0)); + let layout = Layout { + params: vec![Param::Constants { at: 0, count: 2 }, Param::Descriptor { at: 8 }, Param::Table { at: 16 }, Param::Descriptor { at: 20 }, Param::Descriptor { at: 28 }, Param::Descriptor { at: 36 }], + size: 44, + ..Default::default() + }; + let mut args = Vec::new(); + for q in [g + 0x200, g + 0x100] { + args.extend_from_slice(&q.to_le_bytes()); + } + args.extend_from_slice(&(g as u32).to_le_bytes()); + for q in [0x7_1234_0000u64, 0, g + 0x3_0000] { + args.extend_from_slice(&q.to_le_bytes()); + } + let wanted: Vec<(u64, u64)> = root_views_wanted(&layout, &args, span).collect(); + assert_eq!(wanted, vec![(g + 0x100, ROOT_VIEW_BYTES), (g + 0x3_0000, ROOT_VIEW_BYTES)]); + assert_eq!(ROOT_VIEW_BYTES, 64 << 10); + assert_eq!(root_views_wanted(&layout, &args, (0, 0)).count(), 0, "no view windows"); + let four = Uma::for_runtime_windows(16 << 20, 16 << 20, MAX_WINDOWS).expect("4-window aperture"); + assert_eq!(view_span_of(&four), (0, 0)); + assert_eq!(u.view_release(g as usize), Some(1 << 20)); + } + + /// A list a deferred split records into next (`inherit_for_split`) leaves the two-pass record + /// buffers and argument scratch of its previous recording to that recording's allocator, as + /// `reset` does: the GPU may still read them. (Buffers of a software device: no GPU work.) + #[test] + fn a_split_holds_the_previous_record_buffers_for_their_allocator() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + let dev = unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + let mut dev: Option = None; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + dev.unwrap() + }; + let (from, to) = (0x7600_0001usize as *mut c_void, 0x7600_0002usize as *mut c_void); + let (old, new) = (0x7600_0010usize, 0x7600_0020usize); + let record = unsafe { TwoPassBuf::make(&dev, 1 << 16, "record buffer") }.unwrap(); + let block = unsafe { TwoPassBuf::make(&dev, 1 << 16, "argument scratch") }.unwrap(); + let (buf, scratch) = (record.res.clone(), block.res.clone()); + with(to, |s| { + s.allocator = old; + s.res_buf = Some(record); + s.scratch = Some((scratch.clone(), 1 << 16)); + s.res_retired.push(block); + (s.scratch_used, s.scratch_taken) = (256, 1 << 16); + }); + inherit_for_split(from, to, new); + with(to, |s| { + assert_eq!(s.allocator, new); + assert!(s.res_buf.is_none() && s.res_retired.is_empty() && s.scratch.is_none(), "fresh buffers for the new recording"); + assert_eq!((s.scratch_used, s.scratch_taken), (0, 0)); + }); + let held: Vec = ALLOC_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&old)).unwrap_or_default().iter().map(|b| b.res.as_raw() as usize).collect(); + assert_eq!(held.len(), 2, "the record buffer and the scratch block wait for the old allocator"); + assert!(held.contains(&(buf.as_raw() as usize)) && held.contains(&(scratch.as_raw() as usize))); + forget(from); + forget(to); + } + + /// The title's last Release of an allocator gives back the two-pass buffers ended recordings + /// on it left (`alloc_pool::forget`), when nothing records on it and the GPU is done with it: + /// no Reset of it comes any more, and they stayed counted against `two_pass_cap`. Those of an + /// allocator a list still records on stay. (Buffers of a software device: no GPU work.) + #[test] + fn a_released_allocator_gives_back_its_two_pass_buffers() { + let _warp_guard = lock_warp_tests(); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + let dev = unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + let mut dev: Option = None; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + dev.unwrap() + }; + let key = dev.as_raw() as usize; + let ids = Box::new([0u8; 4]); + let (done, busy) = (ids.as_ptr() as usize, ids.as_ptr() as usize + 1); + let (ended, recording) = (done + 2, done + 3); + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT.0; + // a list recorded on `done` and is gone (never submitted); one still records on `busy` + super::super::alloc_pool::created_on(ended, done, ty); + super::super::alloc_pool::forget_list(ended); + super::super::alloc_pool::created_on(recording, busy, ty); + let a = unsafe { TwoPassBuf::make(&dev, 1 << 16, "record buffer") }.unwrap(); + let b = unsafe { TwoPassBuf::make(&dev, 1 << 16, "record buffer") }.unwrap(); + let (a_raw, b_raw) = (a.res.as_raw() as usize, b.res.as_raw() as usize); + hold_res_until_reset(done, vec![a]); + hold_res_until_reset(busy, vec![b]); unsafe { - list_x::on_create(parent as *mut c_void, 0, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); - list_x::on_create(bundle as *mut c_void, 0, 0, D3D12_COMMAND_LIST_TYPE_BUNDLE); + super::super::alloc_pool::forget(done); + super::super::alloc_pool::forget(busy); } - list_x::poison_recording(bundle); - list_x::on_execute_bundle(parent, bundle); list_x::on_execute_bundle(parent, bundle); - assert!(real::submission_rejected_for_test(&[parent as *mut c_void])); - list_x::on_release(parent); list_x::on_release(bundle); + let held = |alloc: usize| -> Vec { + ALLOC_RES.lock().unwrap().as_ref().and_then(|m| m.get(&alloc)).map_or(Vec::new(), |v| v.iter().map(|b| b.res.as_raw() as usize).collect()) + }; + let (held_done, held_busy) = (held(done), held(busy)); + let mut freed = Vec::new(); + while let Some(f) = FREE_RES.lock().unwrap().take(key, 0, u64::MAX) { + freed.push(f.res.as_raw() as usize); + } + // (before the assertions: nothing of this test stays) + let left = ALLOC_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&busy)); + drop(left); + assert!(held_done.is_empty(), "the released allocator's buffers do not wait for a Reset that never comes"); + assert_eq!(freed, vec![a_raw], "they are kept for reuse"); + assert_eq!(held_busy, vec![b_raw], "a list still records on the other: its buffers stay"); + } - let unavailable = pso_async::pipeline_resolution_for_test(original, || {}).unavailable_for_test(); - FAKE_LAST_CLEAR_PSO.store(usize::MAX, Ordering::Release); - unsafe { clear_pipeline_state_retained(list, original, Some(unavailable)) }; - assert_eq!(FAKE_LAST_CLEAR_PSO.load(Ordering::Acquire), 0, "unavailable ClearState did not send NULL"); - assert_eq!(with(list, |s| s.pso), original); - assert_eq!(list_x::bound_pipeline_for_test(list as usize), original); - assert!(list_x::recording_poisoned(list as usize), "ClearState must not unpoison a recording"); - assert_eq!(unsafe { list_x::reset_pc(list, 0, 0) }, 0); - assert!(!list_x::recording_poisoned(list as usize), "successful Reset must clear poison"); + /// Binds on XCL's ABI (`bind_abi`, both two-pass stages) take window 0 the same way: not + /// open on the GPU is refused, and so is shadowed memory without a buffer there (a null root + /// descriptor); unshadowed memory with none keeps going as before. + #[test] + fn binds_refuse_shadowed_memory_without_window_0() { + assert!(first_window(None, false).is_err()); + assert!(first_window(Some(0), true).is_err()); + assert_eq!(first_window(Some(0), false), Ok(0)); + assert_eq!(first_window(Some(0x7_0000_0000), true), Ok(0x7_0000_0000)); + } - forget(list); - list_x::clear_segment_state(list as usize); - list_x::on_release(list as usize); - assert_eq!(pso_async::released(original), 0); - assert_eq!(pso_async::released(old_raw), 0); - assert_eq!(unsafe { resolution_release(old_owner as *mut c_void) }, 0); - assert_eq!(unsafe { resolution_release(replacement_raw as *mut c_void) }, 0); + /// The two passes get the addresses of the heaps set after their arguments, the view heap's + /// first, as `bind_abi`'s stages do (`console_list::with_heaps`): for the console's most + /// common mesh layout (three tables, a root view, two constants) the compute pass's s23 / + /// s24, the pixel shader's right after its arguments from s8. + #[test] + fn two_pass_heap_addresses_follow_the_arguments() { + use crate::gpu::recomp::IO_UMA_BASE_HI; + // RTS0 v2: three tables, a root SRV, two constants; the root signature's flags at 20 + let layout = |flags: u32| { + let params = [(0u32, 0u32), (0, 0), (0, 0), (3, 0), (1, 2)]; + let n = params.len() as u32; + let mut r = vec![2u32, n, 24, 0, 0, flags]; + for (k, &(ty, _)) in params.iter().enumerate() { + r.extend([ty, 0, 24 + 12 * n + 12 * k as u32]); + } + for &(_, count) in ¶ms { + r.extend([0, 0, count]); + } + let blob: Vec = r.iter().flat_map(|w| w.to_le_bytes()).collect(); + console_list::layout_from_blob(&blob).unwrap() + }; + let words = [0x11u32, 0x22, 0x33, 0x5000_0000, 0x7, 5, 6]; + let args: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let heaps = [0x6000_0000, 0x6381_0000]; + let io = |flags: u32, compute_pass: bool| two_pass_io(Some(&layout(flags)), &args, 0x4_0000_0200, compute_pass, 0x4_0000_0000, heaps); + // the compute pass: table at s[8:9], arguments from s16, the heaps at s23 / s24 + let cs = io(0xC00, true); + assert_eq!((cs[8], cs[9]), (0x200, 4)); + assert_eq!(&cs[16..23], &words); + assert_eq!(&cs[23..26], &[0x6000_0000, 0x6381_0000, 0]); + assert_eq!(cs[IO_UMA_BASE_HI], 4); + assert_eq!(&io(0x800, true)[23..25], &[0x6381_0000, 0], "the sampler heap's alone"); + assert_eq!(&io(0x400, true)[23..25], &[0x6000_0000, 0], "the view heap's alone"); + assert_eq!(io(0, true)[23], 0, "no flags: no addresses"); + // the pixel shader: table at s[0:1], arguments from s8, the heaps after them + let ps = io(0xC00, false); + assert_eq!((ps[0], ps[1]), (0x200, 4)); + assert_eq!(&ps[8..15], &words); + assert_eq!(&ps[15..18], &[0x6000_0000, 0x6381_0000, 0]); + assert_eq!(io(0, false)[15], 0, "no flags: no addresses"); } #[test] - fn prepared_initial_pipeline_commits_only_after_create_or_reset_success() { - let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); - let mut orig_vt = [0usize; 64]; - orig_vt[1] = fake_add_ref as usize; orig_vt[2] = fake_release as usize; - orig_vt[10] = fake_reset as usize; - let mut ext_vt = vec![0usize; 65]; - ext_vt[0] = orig_vt.as_ptr() as usize; ext_vt[1..].copy_from_slice(&orig_vt); - let fake = Box::new(FakeAdoptedList { - vt: unsafe { ext_vt.as_ptr().add(1) }, refs: AtomicUsize::new(1), - dispatch_calls: AtomicUsize::new(0), set_compute_rs_calls: AtomicUsize::new(0), - set_compute_uav_calls: AtomicUsize::new(0), set_pso_calls: AtomicUsize::new(0), - last_pso: AtomicUsize::new(0), execute_indirect_calls: AtomicUsize::new(0), - }); - let list = &*fake as *const FakeAdoptedList as *mut c_void; - let _class = real::test_command_list_class( - orig_vt.as_ptr() as usize, - unsafe { ext_vt.as_ptr().add(1) } as usize, - ); - unsafe { list_x::on_create(list, 0, 0, D3D12_COMMAND_LIST_TYPE_DIRECT) }; - let fallback = PreparedNativePipeline::from_resolution( - 0x7100_4900, Some(pso_async::pipeline_resolution_for_test(0x7100_4900, || {})), - ); - assert_eq!(fallback.raw(), 0x7100_4900); drop(fallback); - let pso_vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; - let mut exact = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let mut replacement = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let (exact_raw, replacement_raw) = (&mut exact as *mut ResolutionPso as usize, &mut replacement as *mut ResolutionPso as usize); - let original = 0x7100_4901usize; - pso_async::submit_lazy(original, false, Box::new(move || exact_raw), 0); - assert_eq!(pso_async::resolve_wait(original), exact_raw); - let failed_create = PreparedNativePipeline::from_resolution( - original, pso_async::begin_pipeline_resolution(original), - ); - assert_eq!(failed_create.raw(), exact_raw); drop(failed_create); - assert_eq!(list_x::native_generation_count_for_test(list as usize), 0); - let retained = pso_async::begin_pipeline_resolution(original).unwrap(); - let identity = retained.identity_for_test(); - let prepared = PreparedNativePipeline::from_resolution(original, Some(retained)); - assert_eq!(prepared.raw(), exact_raw); - let exact_owner = pso_async::released(original); - let replacement_calls = Arc::new(AtomicUsize::new(0)); let calls = replacement_calls.clone(); - pso_async::submit_lazy(original, false, Box::new(move || { calls.fetch_add(1, Ordering::Relaxed); replacement_raw }), 0); - prepared.commit(list, 0); - assert_eq!(with(list, |s| s.resolution.as_ref().unwrap().identity_for_test()), identity); - assert_eq!(list_x::native_generation_count_for_test(list as usize), 1); - assert_eq!(replacement_calls.load(Ordering::Relaxed), 0); + fn two_pass_groups_stay_inside_the_record_buffer() { + // #304's transform record: 11 908 dwords + let record = 11_908 * 4; + assert_eq!(record_groups(32 << 20, record, 1), 704); + assert_eq!(record_groups(128 << 20, record, 1), 2817); + // the mesh pass's groups, `split` a record, all in X + assert_eq!(record_groups(1 << 30, 64, 7), 65_535 / 7); + assert_eq!(record_groups(1 << 20, 2 << 20, 1), 0); + } + + /// Every root view the argument pass's program declares (u0..u4) gets an address, even when + /// feedback or count is absent: missing slots fall back to the constants buffer rather than 0. + #[test] + fn the_argument_pass_names_a_buffer_in_every_view_it_declares() { + for register in ["u0", "u1", "u2", "u3", "u4"] { + assert!(SCALE_ARGS_HLSL.contains(&format!("register({register})")), "{register}"); + } + assert!(!SCALE_ARGS_HLSL.contains("register(u5)")); + let with_both = scale_views(0x1000, Some(0x5000), 0x2000, 0x3000, Some(0x4000)); + assert_eq!(with_both, [(0, 0x1000), (1, 0x5000), (2, 0x2000), (3, 0x3000), (4, 0x4000)]); + let without = scale_views(0x1000, None, 0x2000, 0x3000, None); + assert_eq!(without, [(0, 0x1000), (1, 0x1000), (2, 0x2000), (3, 0x3000), (4, 0x1000)]); + assert!(without.iter().all(|&(_, va)| va != 0)); + } - let unavailable = pso_async::pipeline_resolution_for_compute_test(0x7100_4902, || {}).unavailable_for_test(); - let prepared = PreparedNativePipeline::from_resolution(0x7100_4902, Some(unavailable)); - assert_eq!(prepared.raw(), 0); prepared.commit(list, 0); - assert!(!list_x::recording_poisoned(list as usize)); - let unavailable = pso_async::pipeline_resolution_for_test(0x7100_4903, || {}).unavailable_for_test(); - PreparedNativePipeline::from_resolution(0x7100_4903, Some(unavailable)).commit(list, 0); - assert!(list_x::recording_poisoned(list as usize)); - let old_identity = with(list, |s| s.resolution.as_ref().unwrap().identity_for_test()); - drop(PreparedNativePipeline::from_resolution( - 0x7100_4904, Some(pso_async::pipeline_resolution_for_test(0x7100_4904, || {})), - )); - assert_eq!(with(list, |s| s.resolution.as_ref().unwrap().identity_for_test()), old_identity); - assert!(list_x::recording_poisoned(list as usize)); + /// `SCALE_ARGS_HLSL` on `commands` (dwords each, the DispatchMesh argument at dword 1): + /// the compute pass's and the mesh pass's commands. + fn scale_args(commands: &[[u32; 4]], split: u32, cap: u32) -> Option<(Vec<[u32; 4]>, Vec<[u32; 4]>)> { + scale_args_counted(commands, split, cap, None) + } - let mut reset_exact = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let reset_raw = &mut reset_exact as *mut ResolutionPso as usize; - let reset_original = 0x7100_4906usize; - pso_async::submit_lazy(reset_original, false, Box::new(move || reset_raw), 0); - assert_eq!(pso_async::resolve_wait(reset_original), reset_raw); - FAKE_CLOSED.store(true, Ordering::Release); FAKE_RESET_FAIL.store(true, Ordering::Release); - assert!(unsafe { real::reset_for_test(list, std::ptr::null_mut(), reset_original as *mut c_void) } < 0); - assert_eq!(FAKE_LAST_RESET_PSO.load(Ordering::Acquire), reset_raw); - assert!(list_x::recording_poisoned(list as usize)); - assert_eq!(with(list, |s| s.resolution.as_ref().unwrap().identity_for_test()), old_identity); - assert_eq!(list_x::native_generation_count_for_test(list as usize), 1); - FAKE_RESET_FAIL.store(false, Ordering::Release); - FAKE_CLOSED.store(true, Ordering::Release); - assert_eq!(unsafe { real::reset_for_test(list, std::ptr::null_mut(), std::ptr::null_mut()) }, 0); - assert_eq!(FAKE_LAST_RESET_PSO.load(Ordering::Acquire), 0); - assert!(!list_x::recording_poisoned(list as usize)); + /// `scale_args` with a count buffer holding `count` + fn scale_args_counted(commands: &[[u32; 4]], split: u32, cap: u32, count: Option) -> Option<(Vec<[u32; 4]>, Vec<[u32; 4]>)> { + use crate::gpu::recomp::runner; + if runner::adapter().is_err() { + runner::skip_test("no GPU"); + return None; + } + let dxil = crate::gpu::recomp::dxc::compile(SCALE_ARGS_HLSL, "main", "cs_6_6", &[]).unwrap(); + let n = commands.len(); + let (src, dst) = (0u32, 256u32); + let mut mem: Vec = commands.iter().flatten().copied().collect(); + mem.resize(64 + 2 * 4 * n, 0xDEAD); + // the count at dword 60 (u4 is the same memory in the runner) + assert!(4 * n <= 60); + mem[60] = count.unwrap_or(0); + let io = [n as u32, 16, 4, split, cap, src, dst, count.is_some() as u32, 240, 0]; + let out = runner::dispatch(&dxil, [(n as u32).div_ceil(64), 1, 1], &io, &mem).unwrap(); + let cmd = |k: usize| [out[64 + 4 * k], out[65 + 4 * k], out[66 + 4 * k], out[67 + 4 * k]]; + Some(((0..n).map(cmd).collect(), (n..2 * n).map(cmd).collect())) + } - FAKE_CLOSED.store(true, Ordering::Release); - assert_eq!(unsafe { list_x::reset_pc(list, 0, reset_original) }, 0); - assert_eq!(FAKE_LAST_RESET_PSO.load(Ordering::Acquire), reset_raw); - assert_eq!(tracked_pso(list), reset_original); - assert_eq!(list_x::native_generation_count_for_test(list as usize), 1); - let reset_owner = pso_async::released(reset_original); + #[test] + fn gpu_indirect_two_pass_groups_stay_inside_the_record_buffer() { + let Some((compute, mesh)) = scale_args(&[[7, 100, 1, 1], [8, 3, 1, 1], [9, 0, 1, 1]], 2, 10) else { return }; + assert_eq!(compute, [[7, 10, 1, 1], [8, 3, 1, 1], [9, 0, 1, 1]]); + assert_eq!(mesh, [[7, 20, 1, 1], [8, 6, 1, 1], [9, 0, 1, 1]]); + } - forget(list); list_x::clear_segment_state(list as usize); list_x::on_release(list as usize); - assert_eq!(pso_async::released(original), 0); - assert_eq!(unsafe { resolution_release(exact_owner as *mut c_void) }, 0); - assert_eq!(unsafe { resolution_release(replacement_raw as *mut c_void) }, 0); - assert_eq!(unsafe { resolution_release(reset_owner as *mut c_void) }, 0); + #[test] + fn gpu_indirect_two_pass_groups_go_in_x() { + let commands = [[1, 1, 2, 1], [2, 2, 3, 4], [3, 300, 300, 1], [4, 5, 0, 2], [5, 70_000, 70_000, 70_000], [6, 1000, 1, 1], [7, 5000, 1, 1], [8, 5000, 1, 0]]; + let Some((compute, mesh)) = scale_args(&commands, 3, 1000) else { return }; + assert_eq!(compute, [[1, 2, 1, 1], [2, 24, 1, 1], [3, 1000, 1, 1], [4, 0, 1, 1], [5, 1000, 1, 1], [6, 1000, 1, 1], [7, 1000, 1, 1], [8, 0, 1, 1]]); + assert_eq!(mesh, [[1, 6, 1, 1], [2, 72, 1, 1], [3, 3000, 1, 1], [4, 0, 1, 1], [5, 3000, 1, 1], [6, 3000, 1, 1], [7, 3000, 1, 1], [8, 0, 1, 1]]); } - /// `DispatchX` with thread dimensions (flag 0x20, as the BVH builder's rehydration passes - /// use it): the console launches whole groups of the pipeline's `numthreads` and leaves - /// the lanes past the count out; without the flag the counts are groups. With the flag - /// and a group shape not known, nothing is launched (the counts as groups was the bug). + /// Freed two-pass buffers are kept, many of one size too (a frame of recordings hands back + /// tens of 32 MiB ones, and the next takes them again), up to the cap in bytes, oldest let go + /// first; one no recording took for `FREE_RES_IDLE` goes. #[test] - fn dispatch_x_with_thread_dimensions_launches_whole_groups() { - let pso = 0x7300_0001usize; - real::register_threads_for_test(pso, [64, 1, 1]); - // 640 threads in groups of 64: 10 groups, the last one whole - assert_eq!(dispatch_groups(pso, [640, 1, 1], 0x20), Some(([10, 1, 1], [0, 0, 0]))); - // 100 threads: 2 groups, and the lanes past 100 to leave out - assert_eq!(dispatch_groups(pso, [100, 1, 1], 0x20), Some(([2, 1, 1], [100, 0, 0]))); - // the wave32 bit (0x8000) changes nothing here - assert_eq!(dispatch_groups(pso, [100, 1, 1], 0x8020), Some(([2, 1, 1], [100, 0, 0]))); - // a 2-D group shape - let pso2 = 0x7300_0002usize; - real::register_threads_for_test(pso2, [8, 8, 1]); - assert_eq!(dispatch_groups(pso2, [20, 16, 3], 0x20), Some(([3, 2, 3], [20, 0, 0]))); - // group counts (Dispatch, DispatchX without the flag) are launched as they are - assert_eq!(dispatch_groups(pso, [7, 2, 1], 0), Some(([7, 2, 1], [0, 0, 0]))); - assert_eq!(dispatch_groups(pso, [7, 2, 1], 0x8000), Some(([7, 2, 1], [0, 0, 0]))); - // no threads: no groups - assert_eq!(dispatch_groups(pso, [0, 1, 1], 0x20), Some(([0, 1, 1], [0, 0, 0]))); - // thread dimensions on a pipeline whose group shape is not known: not launched - assert_eq!(dispatch_groups(0x7300_00FF, [100, 1, 1], 0x20), None); - assert_eq!(dispatch_groups(0x7300_00FF, [100, 1, 1], 0), Some(([100, 1, 1], [0, 0, 0]))); + fn freed_two_pass_buffers_kept_for_reuse_are_capped() { + use std::time::{Duration, Instant}; + let t = Instant::now(); + let mib = 1u64 << 20; + let mut p: FreePool = FreePool::new(1 << 30); + for k in 0..32 { + assert!(p.put(t, 32 * mib, 7, k).is_empty(), "32 x 32 MiB fit 1 GiB"); + } + assert_eq!(p.bytes, 1 << 30); + assert_eq!(p.put(t, mib, 7, 99), vec![0], "past the cap the oldest goes"); + assert_eq!(p.bytes, (1 << 30) - 31 * mib); + // nothing is idle yet; then all of them are + assert!(p.take_idle(t + Duration::from_millis(1999), FREE_RES_IDLE).is_empty()); + assert_eq!(p.take_idle(t + FREE_RES_IDLE, FREE_RES_IDLE).len(), 32); + assert_eq!((p.bytes, p.free.len()), (0, 0)); + } + + /// Two-pass buffers alive stay within the cap: one that would pass it is not counted (and not + /// made), and freed ones go first to make room for it, oldest first, as many as it takes – + /// none when all of them cannot make it (the draw is skipped anyway, and the next recordings + /// can still take them). + #[test] + fn two_pass_buffers_alive_stay_within_the_cap() { + use std::time::Instant; + let mib = 1u64 << 20; + let alive = AtomicU64::new(0); + assert!(reserve(&alive, 32 * mib, 64 * mib)); + assert!(reserve(&alive, 32 * mib, 64 * mib), "up to the cap itself"); + assert!(!reserve(&alive, mib, 64 * mib)); + assert_eq!(alive.load(Ordering::Relaxed), 64 * mib, "a refused one is not counted"); + assert!(!reserve(&AtomicU64::new(u64::MAX), 1, u64::MAX), "no wrap"); + // room from the free ones + let t = Instant::now(); + let mut p: FreePool<&str> = FreePool::new(1 << 30); + p.put(t, 4 * mib, 1, "4"); + p.put(t, 32 * mib, 2, "32"); + p.put(t, mib, 1, "1"); + assert_eq!(p.take_room(0), Some(vec![])); + assert_eq!(p.take_room(5 * mib), Some(vec!["4", "32"])); + assert_eq!(p.bytes, mib); + assert_eq!(p.take_room(64 * mib), None, "they cannot make the room: none go"); + assert_eq!((p.bytes, p.free.len()), (mib, 1)); + assert_eq!(p.take_room(mib), Some(vec!["1"]), "all there are, when they make it"); + assert_eq!((p.bytes, p.free.len()), (0, 0)); + assert!(two_pass_cap() > 0); + } + + /// A recording takes the smallest freed buffer that is large enough, of its device and within + /// its bound, the one handed back last of those: a large one stays for a large need, and the + /// spare ones of a size grow old. + #[test] + fn a_recording_takes_the_smallest_freed_buffer_that_fits() { + use std::time::{Duration, Instant}; + let t = Instant::now(); + let mib = 1u64 << 20; + let mut p: FreePool<&str> = FreePool::new(1 << 30); + p.put(t, 32 * mib, 1, "32 a"); + p.put(t, 4 * mib, 1, "4 a"); + p.put(t + Duration::from_millis(10), 4 * mib, 1, "4 b"); + p.put(t, mib, 2, "1 other device"); + assert_eq!(p.take(1, mib, u64::MAX), Some("4 b")); + assert_eq!(p.take(1, 8 * mib, 16 * mib), None, "the 32 MiB one is past the bound"); + assert_eq!(p.take(1, 8 * mib, u64::MAX), Some("32 a")); + assert_eq!(p.take(1, mib, u64::MAX), Some("4 a")); + assert_eq!(p.take(1, 0, u64::MAX), None); + assert_eq!(p.take(2, 0, u64::MAX), Some("1 other device")); + assert_eq!(p.bytes, 0); + } + + /// Record buffers come in half-step sizes from 256 KiB, and a draw has at least as many + /// groups as before: none drops groups it drew under power-of-two MiB buckets. Cold + /// ExecuteIndirect starts at full `indirect_record_need` (no cold clamping) before shrinking + /// on feedback. + #[test] + fn two_pass_record_buffers_fit_what_their_draws_need() { + let kib = 1u64 << 10; + let mib = 1u64 << 20; + assert_eq!(record_buffer_bytes(0), 256 * kib); + assert_eq!(record_buffer_bytes(2 * 47_632), 256 * kib, "a DispatchMesh of two groups of #304's record"); + assert_eq!(record_buffer_bytes(256 * kib + 1), 384 * kib); + assert_eq!(record_buffer_bytes(384 * kib + 1), 512 * kib); + assert_eq!(record_buffer_bytes(mib + 1), 1536 * kib); + assert_eq!(record_buffer_bytes(130 * 47_632), 6 * mib); + assert_eq!(record_buffer_bytes(32 * mib), 32 * mib); + assert_eq!(record_buffer_bytes(1 << 40), 128 * mib); + let before = |need: u64| need.max(4 << 20).next_multiple_of(1 << 20).min(128 << 20); + for record in [64u64, 500, 4_096, 47_632, 300_000, 3 << 20, 200 << 20] { + for split in [1u32, 2, 4, 7] { + for groups in [1u32, 2, 8, 52, 92, 130, 704, 2_817, 9_000, 65_535] { + let need = groups as u64 * record; + let old = groups.min(record_groups(before(need), record, split)); + let new = groups.min(record_groups(record_buffer_bytes(need), record, split)); + assert!(new >= old, "{groups} groups of {record} B, split {split}: {new} < {old}"); + } + let ei = record_buffer_bytes(indirect_record_need(record, split)); + assert!(ei <= 32 * mib); + assert_eq!(record_groups(ei, record, split), record_groups(32 * mib, record, split), "{record} B, split {split}"); + } + } + assert_eq!(indirect_record_need(64, 1), 65_535 * 64, "small records: their groups in X bound it"); + assert_eq!(record_buffer_bytes(indirect_record_need(64, 1)), 4 * mib); + assert_eq!(indirect_record_need(47_632, 1), 32 * mib); + assert_eq!(indirect_record_need_hint(47_632, 1, None), 32 * mib); + assert_eq!(indirect_record_need_hint(64, 1, None), 65_535 * 64); + assert_eq!(indirect_record_need_hint(6 * mib, 1, None), 32 * mib); + assert_eq!(indirect_record_need_hint(47_632, 1, Some(0)), RECORD_MIN); + assert_eq!(record_buffer_bytes(indirect_record_need_hint(47_632, 1, Some(1))), 256 * kib); + assert_eq!(record_buffer_bytes(indirect_record_need_hint(47_632, 1, Some(10))), 1 * mib); + } + + /// Without `XCL_TWO_PASS_BATCH` a two-pass draw records what it did before: each command's + /// compute pass and mesh pass (`two_pass_steps`), a UAV barrier on the records after each. + #[test] + fn whole_two_pass_records_keep_a_barrier_after_every_pass() { + for commands in 1..5u32 { + let before: Vec = two_pass_steps(commands).flat_map(|(k, compute)| [TwoPassStep::Pass { k, compute, region: WHOLE }, TwoPassStep::Barrier]).collect(); + assert_eq!(two_pass_plan(commands, Records::Whole, None), before, "{commands} commands"); + // (after a batched draw left a mesh pass reading: a barrier first) + assert_eq!(two_pass_plan(commands, Records::Whole, Some(HALF_1))[1..], before[..]); + assert_eq!(two_pass_plan(commands, Records::Whole, Some(HALF_1))[0], TwoPassStep::Barrier); + } + // a whole draw leaves nothing open + let open = two_pass_plan(3, Records::Whole, None).into_iter().fold(None, open_after); + assert_eq!(open, None); + } + + /// Consecutive draws with records in halves: every compute pass and the barrier after it, + /// then its mesh pass on the same region, and no barrier after a mesh pass – half the + /// barriers of whole records, for DispatchMesh (one command) and ExecuteIndirect alike. + #[test] + fn two_pass_records_in_halves_record_half_the_barriers() { + let barriers = |plans: &[Vec]| plans.iter().flatten().filter(|s| **s == TwoPassStep::Barrier).count(); + for (draws, commands) in [(8usize, 1u32), (5, 3), (1, 4)] { + let mut open = None; + let mut plans = Vec::new(); + for _ in 0..draws { + let plan = two_pass_plan(commands, Records::Halves, open); + open = plan.iter().copied().fold(open, open_after); + plans.push(plan); + } + assert_eq!(barriers(&plans), draws * commands as usize, "{draws} draws of {commands}"); + let whole: Vec<_> = (0..draws).map(|_| two_pass_plan(commands, Records::Whole, None)).collect(); + assert_eq!(barriers(&whole), 2 * draws * commands as usize); + // each command: its compute pass, a barrier, its mesh pass on the same region + for plan in &plans { + for k in 0..commands { + let at = plan.iter().position(|s| matches!(s, TwoPassStep::Pass { k: c, compute: true, .. } if *c == k)).unwrap(); + let TwoPassStep::Pass { region, .. } = plan[at] else { unreachable!() }; + assert_eq!(plan[at + 1], TwoPassStep::Barrier); + assert_eq!(plan[at + 2], TwoPassStep::Pass { k, compute: false, region }); + assert!(region == HALF_0 || region == HALF_1); + } + } + } + } + + /// Whatever the order of draws with records in halves or whole, of one or more commands, no + /// compute pass writes a region a mesh pass may still be reading (no barrier between), and + /// every mesh pass reads records its compute pass wrote before a barrier. + #[test] + fn two_pass_draws_never_write_records_a_mesh_pass_still_reads() { + // (records, commands) of each draw: every sequence of three of these + let kinds = [(Records::Halves, 1u32), (Records::Halves, 2), (Records::Halves, 3), (Records::Whole, 1), (Records::Whole, 2)]; + for a in kinds { + for b in kinds { + for c in kinds { + let (mut reading, mut writing, mut open) = (0u8, 0u8, None); + for (records, commands) in [a, b, c, a] { + let mut wrote = HashMap::new(); + for step in two_pass_plan(commands, records, open) { + match step { + TwoPassStep::Barrier => (reading, writing) = (0, 0), + TwoPassStep::Pass { k, compute: true, region } => { + assert_eq!(region & reading, 0, "{a:?} {b:?} {c:?}: a compute pass writes records a mesh pass reads"); + writing |= region; + wrote.insert(k, region); + } + TwoPassStep::Pass { k, compute: false, region } => { + assert_eq!(region & writing, 0, "{a:?} {b:?} {c:?}: a mesh pass reads records still being written"); + assert_eq!(wrote.get(&k), Some(®ion), "the mesh pass reads its own compute pass's records"); + reading |= region; + } + } + open = open_after(open, step); + assert_eq!(open.unwrap_or(0), reading, "what is kept for the next draw"); + } + } + } + } + } + } - let last = MAX_DISPATCH_GROUPS * 64; - let at_limit = dispatch_groups(pso, [last, 1, 1], 0x20).unwrap().0; - let past_limit = dispatch_groups(pso, [last + 1, 1, 1], 0x20).unwrap().0; - assert!(valid_dispatch_grid(at_limit)); - assert!(!valid_dispatch_grid(past_limit)); - for k in 0..3 { - let mut grid = [1; 3]; - grid[k] = MAX_DISPATCH_GROUPS; - assert!(valid_dispatch_grid(grid), "axis {k} at the D3D12 limit"); - grid[k] += 1; - assert!(!valid_dispatch_grid(grid), "axis {k} past the D3D12 limit"); + /// A record buffer in halves is twice the one the draw would have had whole, so each half + /// has as many groups with a record; past `RECORD_MAX`, or without `XCL_TWO_PASS_BATCH`, + /// the draw takes the whole buffer as before. + #[test] + fn two_pass_record_halves_hold_what_the_whole_buffer_held() { + let mib = 1u64 << 20; + assert_eq!(halves_bytes(0, true), Some(2 * RECORD_MIN)); + assert_eq!(halves_bytes(32 * mib, true), Some(64 * mib)); + assert_eq!(halves_bytes(64 * mib, true), Some(128 * mib)); + assert_eq!(halves_bytes(64 * mib + 1, true), None); + assert_eq!(halves_bytes(32 * mib, false), None); + for record in [64u64, 500, 4_096, 47_632, 300_000] { + for split in [1u32, 2, 7] { + let need = indirect_record_need(record, split); + let half = halves_bytes(need, true).unwrap() / 2; + assert_eq!(record_groups(half, record, split), record_groups(record_buffer_bytes(need), record, split), "{record} B, split {split}"); + for groups in [1u64, 92, 2_817, 9_000] { + let need = groups * record; + if let Some(both) = halves_bytes(need, true) { + assert!(record_groups(both / 2, record, split) >= record_groups(record_buffer_bytes(need), record, split)); + } + } + } } } + /// An ExecuteIndirect's argument block is in COMMON before its first rewrite; with + /// `XCL_TWO_PASS_BATCH` the next rewrite into it takes it from INDIRECT_ARGUMENT. #[test] - fn abi_preparation_snapshots_state_and_reserves_disjoint_regions() { - let list = 0x7301_0001usize as *mut c_void; - let u = crate::gpu::uma::Uma::with_windows(1, 8 << 20).expect("test UMA"); - let layout = Arc::new(Layout { size: 64, inline: 4, ..Default::default() }); - let args = (0..64u8).collect::>(); - with(list, |state| { - state.layout = Some(layout.clone()); - state.args = args.clone(); - state.allocator = 0x7301_1000; - }); + fn the_argument_block_is_taken_from_the_state_it_was_left_in() { + assert_eq!(scratch_state(false), D3D12_RESOURCE_STATE_COMMON); + assert_eq!(scratch_state(true), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + let list = 0x7500_0011usize as *mut c_void; + assert!(!with(list, |s| s.scratch_in_args), "a new recording's block has not been used"); + with(list, |s| (s.scratch_in_args, s.record_open) = (true, Some(HALF_0))); + reset(list, 0, 0); + assert_eq!(with(list, |s| (s.scratch_in_args, s.record_open)), (false, None), "the next recording takes fresh buffers"); + forget(list); + } - let prepared = prepare_abi_state(list, &u, false, None).unwrap(); - assert!(Arc::ptr_eq(prepared.layout.as_ref().unwrap(), &layout)); - assert_eq!(prepared.args, args); - assert_eq!(prepared.inline, 4); - assert_eq!(prepared.allocator, 0x7301_1000); - assert_eq!((prepared.table_at | prepared.io_at | prepared.res_at) & 255, 0); - assert!(prepared.table_at + 60 <= prepared.io_at); - assert!(prepared.io_at + crate::gpu::recomp::KERNEL_SGPRS * std::mem::size_of::() <= prepared.res_at); + /// A deferred DispatchMesh or ExecuteIndirect as `prepare_two_pass_stage` would snapshot it, + /// draw `k` of a run with one pipeline pair: the title's root arguments of each draw give it + /// io blocks of its own; its records are region `k` of the batch buffer at `0x9000_0000`. + fn snap(k: u64, indirect: Option) -> DrawSnap { + let records = 0x9000_0000 + k * 0x1_0000; + let w = [0x5000_0000, 0x5100_0000, 0x5200_0000, 0x5300_0000]; + let compute = StageBind { rs: 0xC0, pso: 0xC1, views: [0x4000_0000 + k * 0x200, records, w[0], w[1], w[2], w[3]] }; + let mesh = StageBind { rs: 0xA0, pso: 0xA1, views: [0x4000_0100 + k * 0x200, records, w[0], w[1], w[2], w[3]] }; + let work = match indirect { + None => DeferredWork::Mesh { groups: 3 + k as u32, mesh_groups: 2 * (3 + k as u32) }, + Some(block) => DeferredWork::Indirect { + rewrite: Rewrite { rs: 0xE0, pso: 0xE1, views: [(0, 0x4100_0000 + k * 0x100), (1, 0x4100_0000 + k * 0x100), (2, 0x4200_0000 + k * 16), (3, 0x7000 + k * 32), (4, 0x4100_0000 + k * 0x100)], groups: 1 }, + block, + before: D3D12_RESOURCE_STATE_COMMON, + companion: 0xD0, + sig: 0xD1, + compute_at: k * 32, + mesh_at: k * 32 + 16, + }, + }; + DrawSnap { compute, mesh, work } + } - with(list, |state| { - state.layout = None; - state.args.clear(); - state.allocator = 0x7301_2000; + /// What the unbatched path records for `d`, as `make_scaled_args_buffer`, + /// `emit_two_pass_stage` and the PC calls after it record it (barriers left out). + fn unbatched_commands(d: &DrawSnap) -> Vec { + let mut v = Vec::new(); + if let DeferredWork::Indirect { rewrite, .. } = d.work { + v.extend([Cmd::ComputeRs(rewrite.rs), Cmd::Pso(rewrite.pso)]); + v.extend(rewrite.views.iter().map(|&(s, va)| Cmd::ComputeView(s, va))); + v.push(Cmd::Dispatch(rewrite.groups)); + } + v.push(Cmd::ComputeRs(d.compute.rs)); + v.extend(d.compute.views.iter().enumerate().map(|(k, &va)| Cmd::ComputeView(k as u32, va))); + v.push(Cmd::Pso(d.compute.pso)); + v.push(match d.work { + DeferredWork::Mesh { groups, .. } => Cmd::Dispatch(groups), + DeferredWork::Indirect { block, companion, compute_at, .. } => Cmd::Indirect(companion, block, compute_at), }); - assert!(Arc::ptr_eq(prepared.layout.as_ref().unwrap(), &layout)); - assert_eq!(prepared.args, args); - assert_eq!(prepared.allocator, 0x7301_1000); - - let state = take_state(list as usize).unwrap(); - assert_eq!(state.uma.len(), 1, "the three reservations should share one arena block"); - for block in state.uma { - assert!(u.free(block)); + v.push(Cmd::GraphicsRs(d.mesh.rs)); + v.extend(d.mesh.views.iter().enumerate().map(|(k, &va)| Cmd::GraphicsView(k as u32, va))); + v.push(Cmd::Pso(d.mesh.pso)); + v.push(match d.work { + DeferredWork::Mesh { mesh_groups, .. } => Cmd::DispatchMesh(mesh_groups), + DeferredWork::Indirect { block, sig, mesh_at, .. } => Cmd::Indirect(sig, block, mesh_at), + }); + v + } + + /// A GPU call with the state it runs with: the call, the pipeline, and the root signature and + /// root views of its side (compute for a Dispatch or an ExecuteIndirect of a companion + /// Dispatch signature – `0xD0` / `0xE0`.. in `snap` – graphics otherwise). + #[derive(Clone, Debug, PartialEq, Eq)] + struct Call { + call: Cmd, + pso: usize, + rs: usize, + views: std::collections::BTreeMap, + } + + /// The calls of `cmds` with the state each runs with (a root signature that changes drops + /// the root views, as D3D12 does). + fn calls(cmds: &[Cmd]) -> Vec { + use std::collections::BTreeMap; + let (mut crs, mut grs, mut pso) = (0, 0, 0); + let (mut cv, mut gv) = (BTreeMap::new(), BTreeMap::new()); + let mut out = Vec::new(); + for c in cmds { + match c { + Cmd::ComputeRs(r) => { + let r = *r; + if r != crs { + cv.clear(); + } + crs = r; + } + Cmd::GraphicsRs(r) => { + let r = *r; + if r != grs { + gv.clear(); + } + grs = r; + } + Cmd::Pso(p) => pso = *p, + Cmd::ComputeView(s, va) => { + cv.insert(*s, *va); + } + Cmd::GraphicsView(s, va) => { + gv.insert(*s, *va); + } + Cmd::Dispatch(_) | Cmd::Indirect(0xD0, ..) => out.push(Call { call: c.clone(), pso, rs: crs, views: cv.clone() }), + Cmd::DispatchMesh(_) | Cmd::Indirect(..) => out.push(Call { call: c.clone(), pso, rs: grs, views: gv.clone() }), + // (the title's pipeline set, with what it sets: as a call of its own, in order) + Cmd::Bind(p) => { + pso = *p; + out.push(Call { call: c.clone(), pso, rs: 0, views: BTreeMap::new() }); + } + Cmd::StencilRef(_) | Cmd::Topology(_) | Cmd::Scissors(_) => { + out.push(Call { call: c.clone(), pso, rs: 0, views: BTreeMap::new() }); + } + Cmd::Barriers { .. } | Cmd::TimesBegin(_) | Cmd::TimesEnd => {} + } } + out } - #[test] - fn dispatch_limits_are_explicit_and_graphics_ignores_them() { - let slots = crate::gpu::recomp::IO_THREAD_LIMIT; - let compute = prepared_abi_io(None, &[], 0x1234_0000, false, None, 0, [100, 17, 0]); - assert_eq!([compute[slots[0]], compute[slots[1]], compute[slots[2]]], [100, 17, 0]); + fn steps(draws: &[DrawSnap]) -> Vec { + draws.iter().map(|&d| Step::Draw(d)).collect() + } - let ordinary = prepared_abi_io(None, &[], 0x1234_1000, false, None, 0, [0; 3]); - assert_eq!([ordinary[slots[0]], ordinary[slots[1]], ordinary[slots[2]]], [0; 3]); + /// `snap` with the pipeline pair `pipe` (its compute pass's and mesh pass's PC pipelines). + fn snap_on(k: u64, pipe: usize, indirect: Option) -> DrawSnap { + let mut d = snap(k, indirect); + d.compute.pso += pipe * 0x10; + d.mesh.pso += pipe * 0x10; + d + } - let graphics = prepared_abi_io(None, &[], 0x1234_2000, true, None, 0, [9, 8, 7]); - assert_eq!([graphics[slots[0]], graphics[slots[1]], graphics[slots[2]]], [0; 3]); + /// A run across the title's SetPipelineState calls (DispatchMesh and ExecuteIndirect draws + /// on two pipelines, root arguments set between them): the compute passes each with their + /// draw's pipeline, then the mesh passes with each pipeline set (`real::bind_pipeline`, with + /// the depth bias and the rest it records) between them where the title made it, and each + /// mesh pass with its own pipeline after it – what the unbatched path gives every call, in + /// the order it gives the mesh passes and the sets. + #[test] + fn a_run_goes_on_across_pipeline_sets_in_the_titles_order() { + let (a, b) = (0x7A00usize, 0x7B00usize); + let run = vec![ + Step::Draw(snap_on(0, 0, None)), + Step::Draw(snap_on(1, 0, Some(0xB1))), + Step::Bind(b), + Step::Draw(snap_on(2, 1, None)), + Step::Draw(snap_on(3, 1, Some(0xB1))), + Step::Bind(a), + Step::Draw(snap_on(4, 0, None)), + ]; + let cmds = batch_commands(&run, 0x900, false); + let batched = calls(&cmds); + let mut alone = Vec::new(); + for s in &run { + match s { + Step::Bind(p) => alone.push(calls(&[Cmd::Bind(*p)])[0].clone()), + Step::StencilRef(r) => alone.push(calls(&[Cmd::StencilRef(*r)])[0].clone()), + Step::Topology(t) => alone.push(calls(&[Cmd::Topology(*t)])[0].clone()), + Step::Scissors(r) => alone.push(calls(&[Cmd::Scissors(r.clone())])[0].clone()), + Step::Draw(d) => alone.extend(calls(&unbatched_commands(d))), + } + } + // the mesh passes and the pipeline sets: the same calls with the same state, in order + let mesh_side = |c: &[Call]| -> Vec { c.iter().filter(|x| matches!(x.call, Cmd::Bind(_) | Cmd::DispatchMesh(_) | Cmd::Indirect(0xD1, ..))).cloned().collect() }; + assert_eq!(mesh_side(&batched), mesh_side(&alone)); + assert_eq!(mesh_side(&batched).iter().map(|x| matches!(x.call, Cmd::Bind(_))).collect::>(), [false, false, true, false, false, true, false]); + // the compute passes and rewrites: each with its draw's pipeline, root signature, views + let compute_side = |c: &[Call]| -> Vec { c.iter().filter(|x| matches!(x.call, Cmd::Dispatch(_) | Cmd::Indirect(0xD0, ..))).cloned().collect() }; + let (mut got, mut want) = (compute_side(&batched), compute_side(&alone)); + got.sort_by_key(|x| (x.pso, format!("{:?}", x.call))); + want.sort_by_key(|x| (x.pso, format!("{:?}", x.call))); + assert_eq!(got, want); + // no pipeline set among the compute passes; a mesh pass sets its pipeline after a set + let first_mesh = cmds.iter().position(|c| matches!(c, Cmd::TimesBegin(Some(_)))).unwrap(); + assert!(!cmds[..first_mesh].iter().any(|c| matches!(c, Cmd::Bind(_)))); + for (i, c) in cmds.iter().enumerate() { + if matches!(c, Cmd::Bind(_)) { + let next_pso = cmds[i..].iter().position(|c| matches!(c, Cmd::Pso(_))).unwrap(); + let next_call = cmds[i..].iter().position(|c| matches!(c, Cmd::DispatchMesh(_) | Cmd::Indirect(..))).unwrap(); + assert!(next_pso < next_call, "the mesh pass after a set binds its own pipeline"); + } + } + assert_eq!(cmds.iter().filter(|c| matches!(c, Cmd::Barriers { .. })).count(), 3, "still three ResourceBarrier calls"); } + /// A run with the title's stencil reference, topology and scissor sets between its draws: the + /// sets come among the mesh passes where the title made them (each mesh pass draws with the + /// state of its draw, as the unbatched path gives it), none among the compute passes. #[test] - fn command_signature_recreation_replaces_every_classification_bit() { - assert_eq!(std::mem::size_of::(), 8); - let root_reuse = 0x7301_2800usize; - note_indirect_signature(root_reuse, IndirectSignatureInfo::new(true, true, Some(12))); - note_indirect_signature(root_reuse, IndirectSignatureInfo::default()); - assert_eq!(indirect_signature(root_reuse), IndirectSignatureInfo::default(), - "a plain signature inherited root-changing or dispatch state"); + fn state_sets_in_a_run_come_between_the_mesh_passes_in_the_titles_order() { + let run = vec![ + Step::Draw(snap(0, None)), + Step::StencilRef(3), + Step::Draw(snap(1, Some(0xB1))), + Step::Scissors(vec![[0, 0, 640, 360]]), + Step::Topology(4), + Step::Draw(snap(2, None)), + Step::Scissors(Vec::new()), + Step::Draw(snap(3, None)), + ]; + let cmds = batch_commands(&run, 0x900, false); + let mut alone = Vec::new(); + for s in &run { + match s { + Step::StencilRef(r) => alone.push(Cmd::StencilRef(*r)), + Step::Topology(t) => alone.push(Cmd::Topology(*t)), + Step::Scissors(r) => alone.push(Cmd::Scissors(r.clone())), + Step::Draw(d) => alone.extend(unbatched_commands(d)), + Step::Bind(p) => alone.push(Cmd::Bind(*p)), + } + } + let mesh_side = |c: &[Cmd]| -> Vec { + c.iter().filter(|x| matches!(x, Cmd::StencilRef(_) | Cmd::Topology(_) | Cmd::Scissors(_) | Cmd::DispatchMesh(_) | Cmd::Indirect(0xD1, ..))).cloned().collect() + }; + assert_eq!(mesh_side(&cmds), mesh_side(&alone)); + let first_mesh = cmds.iter().position(|c| matches!(c, Cmd::TimesBegin(Some(_)))).unwrap(); + assert!(!cmds[..first_mesh].iter().any(|c| matches!(c, Cmd::StencilRef(_) | Cmd::Topology(_) | Cmd::Scissors(_))), "no state set among the compute passes"); + } - let dispatch_reuse = 0x7301_2810usize; - note_indirect_signature(dispatch_reuse, IndirectSignatureInfo::new(true, false, Some(16))); - let replacement = IndirectSignatureInfo::new(true, true, None); - note_indirect_signature(dispatch_reuse, replacement); - assert_eq!(indirect_signature(dispatch_reuse), replacement, - "a non-dispatch-only replacement inherited the old stride"); + /// SetPipelineState with no deferred draws binds as it always did; with them a two-pass + /// pipeline goes into the run and any other pipeline records the run first. Into the run, it + /// becomes the pipeline the next draws resolve, and nothing is recorded yet. + #[test] + fn set_pipeline_state_goes_into_a_run_only_with_a_two_pass_pipeline() { + assert_eq!(on_pipeline(false, true), OnPipeline::Bind); + assert_eq!(on_pipeline(false, false), OnPipeline::Bind); + assert_eq!(on_pipeline(true, true), OnPipeline::Queue); + assert_eq!(on_pipeline(true, false), OnPipeline::FlushThenBind); + let list = 0x7500_0041usize as *mut c_void; + let pso = 0x7C00_0041usize; + real::register_two_pass_for_test(pso, "MS"); + with(list, |s| s.deferred.push(RunItem::Draw(dummy_draw()))); + mark_deferring(list); + unsafe { set_pipeline_state(list, pso as *mut c_void) }; + assert_eq!(with(list, |s| s.pso), pso); + assert_eq!(with(list, |s| s.deferred.iter().map(RunItem::step).collect::>()), [Step::Draw(snap(0, None)), Step::Bind(pso)]); + assert!(DEFERRING.contains(list as usize), "still deferring"); + forget(list); } + /// SetDescriptorHeaps between deferred draws records the run first (the heap a pass reads its + /// views and samplers from is the one bound when it was deferred), as do render target, + /// barrier and other calls; the log names the call that ended each run. #[test] - fn command_signature_snapshot_never_mixes_generations() { - let sig = 0x7301_2820usize; - let a = IndirectSignatureInfo::new(true, false, Some(12)); - let b = IndirectSignatureInfo::new(false, true, None); - note_indirect_signature(sig, a); - let writer = std::thread::spawn(move || { - for n in 0..20_000 { - note_indirect_signature(sig, if n & 1 == 0 { b } else { a }); - } - }); - for _ in 0..20_000 { - let seen = indirect_signature(sig); - assert!(seen == a || seen == b, "mixed command-signature snapshot: {seen:?}"); + fn set_descriptor_heaps_between_deferred_draws_records_the_run_first() { + for newer in [false, true] { + assert!(flush_wanted(32, newer, true, true)); + } + assert_eq!(super::super::real::list_slot_name(32), "SetDescriptorHeaps"); + assert_eq!(run_end_name(run_end_index(RunEnd::Call(32)), false), "SetDescriptorHeaps"); + assert_eq!(run_end_name(run_end_index(RunEnd::Call(26)), false), "ResourceBarrier"); + assert_eq!(run_end_name(run_end_index(RunEnd::Call(50)), false), "OMSetRenderTargets"); + assert_eq!(run_end_name(run_end_index(RunEnd::Call(12)), false), "DrawInstanced"); + assert_eq!(run_end_name(run_end_index(RunEnd::Call(29)), false), "EndQuery"); + assert_eq!(run_end_name(run_end_index(RunEnd::Call(93)), false), "console list method #93"); + assert_eq!(run_end_name(run_end_index(RunEnd::Call(93)), true), "console list slot #93 (newer layout)"); + assert_eq!(run_end_name(run_end_index(RunEnd::Pipeline), false), "SetPipelineState to a pipeline that is not two-pass"); + assert_eq!(run_end_name(run_end_index(RunEnd::Close), false), "Close"); + } + + fn dummy_draw() -> DeferredDraw { + DeferredDraw { + snap: snap(0, None), + _tp: Arc::new(super::super::real::TwoPassPso { compute: 0, compute_rs: 0, mesh_rs: 0, record: Default::default(), mesh_groups_per_record: 1, kind: "MS" }), + _mesh_pso: None, + _block: None, + raw_pso: 0, + kind: "MS", + size: [1, 1, 1], } - writer.join().unwrap(); } + /// A run of N DispatchMesh draws, the title's root arguments set between them (an io block + /// each): every compute pass, then one ResourceBarrier call (a UAV barrier on the records), + /// then every mesh pass in the title's order; the root signatures and pipelines set once, + /// each pass with all its root views. After a run whose mesh passes may still read the + /// records, one barrier on them first. #[test] - fn deferred_indirect_owns_its_command_signature_snapshot() { - let sig = 0x7301_2830usize; - let original = IndirectSignatureInfo::new(true, false, Some(12)); - note_indirect_signature(sig, original); - let deferred = list_x::Deferred::Indirect { - sig: 1, max: 2, args: 3, args_off: 4, count_buf: 5, count_off: 6, - signature: indirect_signature(sig), - }; - note_indirect_signature(sig, IndirectSignatureInfo::new(false, true, None)); + fn a_run_of_deferred_draws_records_its_compute_passes_then_one_barrier_then_its_mesh_passes() { + let n = 5; + let draws: Vec = (0..n).map(|k| snap(k, None)).collect(); + let cmds = batch_commands(&steps(&draws), 0x900, false); + let mut want = vec![Cmd::TimesBegin(None), Cmd::ComputeRs(0xC0), Cmd::Pso(0xC1)]; + for d in &draws { + want.extend(d.compute.views.iter().enumerate().map(|(k, &va)| Cmd::ComputeView(k as u32, va))); + let DeferredWork::Mesh { groups, .. } = d.work else { unreachable!() }; + want.push(Cmd::Dispatch(groups)); + } + want.extend([Cmd::TimesEnd, Cmd::Barriers { all: false, uav: Some(0x900), transitions: vec![] }]); + for (i, d) in draws.iter().enumerate() { + want.push(Cmd::TimesBegin(Some(i))); + if i == 0 { + want.extend([Cmd::GraphicsRs(0xA0), Cmd::Pso(0xA1)]); + } + want.extend(d.mesh.views.iter().enumerate().map(|(k, &va)| Cmd::GraphicsView(k as u32, va))); + let DeferredWork::Mesh { mesh_groups, .. } = d.work else { unreachable!() }; + want.extend([Cmd::DispatchMesh(mesh_groups), Cmd::TimesEnd]); + } + assert_eq!(cmds, want); + let barriers = |c: &[Cmd]| c.iter().filter(|c| matches!(c, Cmd::Barriers { .. })).count(); + assert_eq!(barriers(&cmds), 1, "one ResourceBarrier call for the run"); + let after_open = batch_commands(&steps(&draws), 0x900, true); + assert_eq!(after_open[0], Cmd::Barriers { all: false, uav: Some(0x900), transitions: vec![] }, "the last run's mesh passes first"); + assert_eq!(after_open[1..], cmds[..]); + } + + /// ExecuteIndirect draws in a run: one ResourceBarrier call before the argument rewrites (a + /// UAV barrier on all resources and each argument block, once, from the state it was in, to + /// UNORDERED_ACCESS), the rewrites, one call taking the blocks to INDIRECT_ARGUMENT, the + /// compute passes, one barrier on the records, the mesh passes. + #[test] + fn a_run_of_deferred_execute_indirects_rewrites_every_argument_first() { + use D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT as ARGS; + use D3D12_RESOURCE_STATE_UNORDERED_ACCESS as UAV; + let mut draws: Vec = vec![snap(0, Some(0xB1)), snap(1, None), snap(2, Some(0xB1)), snap(3, Some(0xB2))]; + if let DeferredWork::Indirect { before, .. } = &mut draws[2].work { + // (a later draw in the block found it left in INDIRECT_ARGUMENT by the first) + *before = ARGS; + } + let cmds = batch_commands(&steps(&draws), 0x900, true); + let barriers: Vec<&Cmd> = cmds.iter().filter(|c| matches!(c, Cmd::Barriers { .. })).collect(); + assert_eq!( + barriers, + [ + &Cmd::Barriers { all: true, uav: None, transitions: vec![(0xB1, D3D12_RESOURCE_STATE_COMMON, UAV), (0xB2, D3D12_RESOURCE_STATE_COMMON, UAV)] }, + &Cmd::Barriers { all: false, uav: None, transitions: vec![(0xB1, UAV, ARGS), (0xB2, UAV, ARGS)] }, + &Cmd::Barriers { all: false, uav: Some(0x900), transitions: vec![] }, + ] + ); + let at = |c: &Cmd| cmds.iter().position(|x| x == c).unwrap(); + let c = calls(&cmds); + // three rewrites, four compute passes, four mesh passes, in that order + let kinds: Vec = c.iter().map(|x| if x.pso == 0xE1 { 0 } else if x.pso == 0xC1 { 1 } else { 2 }).collect(); + assert_eq!(kinds, [0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]); + assert!(at(barriers[1]) > at(&Cmd::Dispatch(1)) && at(barriers[1]) < at(&Cmd::Indirect(0xD0, 0xB1, 0))); + } - let list_x::Deferred::Indirect { signature: retained, .. } = deferred else { unreachable!() }; - assert_eq!(retained, original, - "deferred replay followed the classification now stored at a reused signature address"); + /// Each draw of a run runs every call – the rewrite, the compute pass, the mesh pass – with the + /// pipeline, root signature and root views the unbatched path gives it, and its mesh passes + /// keep the title's order. + #[test] + fn deferred_draws_run_with_what_the_unbatched_path_gives_them() { + let draws: Vec = (0..6).map(|k| snap(k, (k % 2 == 1).then_some(0xB0 + k as usize / 4))).collect(); + let batched = calls(&batch_commands(&steps(&draws), 0x900, false)); + let alone: Vec> = draws.iter().map(|d| calls(&unbatched_commands(d))).collect(); + let indirect: Vec = (0..draws.len()).filter(|&k| matches!(draws[k].work, DeferredWork::Indirect { .. })).collect(); + let rewrites: Vec = indirect.iter().map(|&k| alone[k][0].clone()).collect(); + let compute: Vec = alone.iter().map(|c| c[c.len() - 2].clone()).collect(); + let mesh: Vec = alone.iter().map(|c| c[c.len() - 1].clone()).collect(); + let want: Vec = rewrites.into_iter().chain(compute).chain(mesh).collect(); + assert_eq!(batched, want); + } + + /// A run goes on only across the title's root signature and root argument sets, the calls + /// that record nothing, and DispatchMesh / ExecuteIndirect (at their slots of the title's + /// layout): every other title call records it first. Calls from XCL or the runtime, and calls + /// on a list with nothing deferred, do not. + #[test] + fn a_title_call_records_the_deferred_draws_first_unless_it_cannot_change_them() { + for newer in [false, true] { + let kept: Vec = (0..600).filter(|&s| keeps_two_pass_batch(s, newer)).collect(); + let (ei, dm) = if newer { (61, 129) } else { (59, 127) }; + let mut want: Vec = (0..=8).chain([20, 22, 24, 25]).chain(33..=46).chain([ei, dm]).collect(); + if newer { + want.push(142); + } + assert_eq!(kept, want, "newer layout: {newer}"); + // pipelines, barriers, draws, dispatches, copies, clears, IA / RS / OM state, heaps, + // queries, predication, bundles, markers, Close, Reset, the console's own methods + for slot in [26, 12, 13, 14, 15, 16, 17, 18, 19, 21, 23, 27, 28, 29, 30, 31, 32, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 9, 10, 11, 60, 67, 78, 81, 85, 93, 104, 105, 106, 124, 125, 139, 146, 148] { + assert!(flush_wanted(slot, newer, true, true), "slot {slot}, newer layout: {newer}"); + } + // the other layout's DispatchMesh / ExecuteIndirect slots are other methods there + let (other_ei, other_dm) = if newer { (59, 127) } else { (61, 129) }; + assert!(flush_wanted(other_ei, newer, true, true) && flush_wanted(other_dm, newer, true, true)); + assert!(!flush_wanted(ei, newer, true, true) && !flush_wanted(36, newer, true, true)); + assert!(!flush_wanted(25, newer, false, true), "XCL's own calls"); + assert!(!flush_wanted(25, newer, true, false), "nothing deferred"); + } } + /// A two-pass draw is deferred only on a direct list, without a capture, as one command, with + /// records that fit a batch record buffer; otherwise the run is recorded and it goes at once. #[test] - fn resolved_compute_metadata_does_not_follow_a_reused_native_address() { - let exact = 0x7301_3000usize; - let replacement = 0x7301_4000usize; - real::register_compute_metadata_for_test(exact, 6, [4, 2, 1], (2, 0), 0x7301_5000); - real::register_compute_metadata_for_test(replacement, 9, [8, 1, 1], (3, 1), 0x7301_6000); - pso_async::submit_lazy(exact, true, Box::new(move || replacement), 0); - assert_eq!(pso_async::resolve_wait(exact), replacement); + fn only_single_two_pass_draws_on_direct_lists_are_deferred() { + let direct = Some(D3D12_COMMAND_LIST_TYPE_DIRECT); + let mib = 1u64 << 20; + assert_eq!(defer_check(true, direct, false, 1, 32 * mib, 128 * mib), Ok(())); + assert_eq!(defer_check(true, direct, false, 1, 128 * mib, 128 * mib), Ok(())); + assert_eq!(defer_check(false, direct, false, 1, mib, 128 * mib), Err(NoDefer::Off)); + for ty in [Some(D3D12_COMMAND_LIST_TYPE_BUNDLE), Some(D3D12_COMMAND_LIST_TYPE_COMPUTE), None] { + assert_eq!(defer_check(true, ty, false, 1, mib, 128 * mib), Err(NoDefer::NotDirect)); + } + assert_eq!(defer_check(true, direct, true, 1, mib, 128 * mib), Err(NoDefer::Capture)); + for commands in [0, 2, 64] { + assert_eq!(defer_check(true, direct, false, commands, mib, 128 * mib), Err(NoDefer::Commands)); + } + assert_eq!(defer_check(true, direct, false, 1, 128 * mib + 256, 128 * mib), Err(NoDefer::TooBig)); + } - assert_eq!(real::pso_threads(exact), Some([8, 1, 1]), - "the title-address accessor should still resolve an active stand-in"); - assert_eq!(real::pso_threads_exact(exact), Some([4, 2, 1])); - assert_eq!(real::pso_user_sgprs_exact(exact), Some(6)); - assert_eq!(real::pso_dispatch_remap_exact(exact), Some((2, 0))); - assert_eq!(real::pso_root_signature_exact(exact), Some(0x7301_5000)); - assert_eq!(dispatch_groups(exact, [8, 4, 1], DISPATCH_THREAD_DIMENSIONS), - Some(([2, 2, 1], [0; 3])), - "an already-selected native generation was redirected through PENDING"); + /// Each deferred draw has a region of its own in the batch record buffer, one after the other + /// (256-aligned, as much as the draw alone would have); one that does not fit after them has + /// the run recorded first and starts again at the start. An ExecuteIndirect keeps the groups + /// it had alone. + #[test] + fn deferred_draws_take_regions_of_their_own_until_the_buffer_is_full() { + let mib = 1u64 << 20; + assert_eq!(batch_region_bytes(2 * 47_632), 95_488); + assert_eq!(batch_region_bytes(0), 256); + let (mut used, mut at) = (0, Vec::new()); + for need in [95_264u64, 32 * mib, 32 * mib, 32 * mib, 32 * mib] { + let region = batch_region_bytes(need); + let place = batch_place(used, region, 128 * mib); + at.push(place); + used = place.unwrap_or(0) + region; + } + assert_eq!(at, [Some(0), Some(95_488), Some(95_488 + 32 * mib), Some(95_488 + 64 * mib), None], "the fifth after a recorded run"); + assert_eq!(batch_place(96 * mib, 32 * mib, 128 * mib), Some(96 * mib), "up to the end"); + assert_eq!(batch_place(u64::MAX - 8, 256, 128 * mib), None); + for record in [64u64, 4_096, 47_632, 300_000] { + for split in [1u32, 3] { + let need = indirect_record_need(record, split); + assert_eq!(record_groups(batch_region_bytes(need), record, split), record_groups(record_buffer_bytes(need), record, split), "{record} B, split {split}"); + } + } + } - assert_eq!(pso_async::released(exact), replacement); - real::forget_pso_for_test(exact); - real::forget_pso_for_test(replacement); + /// A recording that ends with deferred draws (a Reset with no Close, a list let go) drops them, + /// the list is no longer counted as deferring, and its batch record buffer goes with its others. + #[test] + fn a_recording_that_ends_drops_its_deferred_draws() { + let list = 0x7500_0031usize as *mut c_void; + let draw = || DeferredDraw { + snap: snap(0, None), + _tp: Arc::new(super::super::real::TwoPassPso { compute: 0, compute_rs: 0, mesh_rs: 0, record: Default::default(), mesh_groups_per_record: 1, kind: "MS" }), + _mesh_pso: None, + _block: None, + raw_pso: 0, + kind: "MS", + size: [1, 1, 1], + }; + let before = DEFERRING_LISTS.load(Ordering::Relaxed); + with(list, |s| s.deferred.extend([RunItem::Draw(draw()), RunItem::Draw(draw())])); + mark_deferring(list); + mark_deferring(list); + assert!(DEFERRING.contains(list as usize)); + reset(list, 0, 0); + assert!(!DEFERRING.contains(list as usize)); + assert!(with(list, |s| s.deferred.is_empty() && s.batch_buf.is_none() && !s.batch_open)); + with(list, |s| s.deferred.push(RunItem::Draw(draw()))); + mark_deferring(list); + forget(list); + assert!(!DEFERRING.contains(list as usize)); + // (other tests' lists may come and go meanwhile; this one is counted once and gone) + assert!(DEFERRING_LISTS.load(Ordering::Relaxed) <= before + 1); } #[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; + fn gpu_two_pass_argument_scratch_is_shared_and_capped() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev) }.is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let list = 0x7500_0001usize as *mut c_void; + unsafe { + // small rewrites share one block + let (a, at_a) = scratch_args(list, &dev, 100).unwrap(); + // (a rewrite left it in INDIRECT_ARGUMENT, `two_pass_batch`) + with(list, |s| s.scratch_in_args = true); + let (b, at_b) = scratch_args(list, &dev, 300).unwrap(); + assert_eq!((a.as_raw(), at_a), (b.as_raw(), 0)); + assert_eq!(at_b, 256); + assert!(with(list, |s| s.scratch_in_args), "the same block: in the state it was left in"); + // a recording takes at most SCRATCH_CAP of blocks + let mut taken = 1; + while scratch_args(list, &dev, SCRATCH_BLOCK).is_ok() { + taken += 1; + assert!(taken <= SCRATCH_CAP / SCRATCH_BLOCK, "past the cap"); + assert!(!with(list, |s| s.scratch_in_args), "a new block is in COMMON"); + } + assert!(with(list, |s| s.scratch_taken) <= SCRATCH_CAP); + // the next recording starts again + reset(list, 0, 0); + assert!(scratch_args(list, &dev, SCRATCH_BLOCK).is_ok()); + } + forget(list); + } - // Extended vtable layout expected by `real::orig_fn`: entry -1 holds `orig_vt` pointer, - // and entries 0..64 hold the COM method pointers used via `ID3D12GraphicsCommandList`. - let mut ext_vt = vec![0usize; 65]; - ext_vt[0] = orig_vt.as_ptr() as usize; - ext_vt[1..].copy_from_slice(&orig_vt); + #[test] + fn gpu_indirect_two_pass_commands_past_the_count_get_no_groups() { + let commands = [[1, 3, 1, 1], [2, 2, 1, 1], [3, 4, 1, 1]]; + let Some((compute, mesh)) = scale_args_counted(&commands, 2, 1000, Some(2)) else { return }; + assert_eq!(compute, [[1, 3, 1, 1], [2, 2, 1, 1], [3, 0, 1, 1]]); + assert_eq!(mesh, [[1, 6, 1, 1], [2, 4, 1, 1], [3, 0, 1, 1]]); + let Some((compute, _)) = scale_args_counted(&commands, 2, 1000, Some(7)) else { return }; + assert_eq!(compute, [[1, 3, 1, 1], [2, 2, 1, 1], [3, 4, 1, 1]]); + } + + /// Commands of two-pass draws run in `two_pass_plan` order on the GPU (`run_two_pass_plan`), + /// with records whole and in halves (`XCL_TWO_PASS_BATCH`), with stand-ins for the two passes: + /// the "compute pass" writes each group's record (from the start of its region) with its + /// command's constant, the "mesh pass" copies the records it reads out by command. One draw of + /// three commands, then three draws of one, each mesh pass with no barrier after it in halves. + #[test] + fn gpu_two_pass_indirect_commands_keep_their_own_records() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev) }.is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + gpu_two_pass_records(&dev, Records::Whole); + gpu_two_pass_records(&dev, Records::Halves); + } - let fake = Box::new(FakeAdoptedList { - // SAFETY: `ext_vt` has 65 elements so `.add(1)` points to slot 0 with `orig_vt` at `-1`. - vt: unsafe { ext_vt.as_ptr().add(1) }, - refs: AtomicUsize::new(1), - dispatch_calls: AtomicUsize::new(0), - set_compute_rs_calls: AtomicUsize::new(0), - set_compute_uav_calls: AtomicUsize::new(0), - set_pso_calls: AtomicUsize::new(0), - last_pso: AtomicUsize::new(0), - execute_indirect_calls: AtomicUsize::new(0), - }); - let list_ptr = &*fake as *const FakeAdoptedList as *mut c_void; + fn gpu_two_pass_records(dev: &ID3D12Device, records: Records) { + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + let src = r#" +#define RS "RootConstants(num32BitConstants=1, b0), UAV(u0), UAV(u1)" +cbuffer C : register(b0) { uint v; }; +RWByteAddressBuffer rec : register(u0); +RWByteAddressBuffer o : register(u1); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void cs(uint3 g : SV_GroupID) { rec.Store(g.x * 4u, v); } +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u)); } +"#; + // (constant, groups) of each command + let commands = [(1u32, 3u32), (2, 2), (3, 4), (4, 1), (5, 4), (6, 2)]; + unsafe { + let cs = crate::gpu::recomp::dxc::compile(src, "cs", "cs_6_6", &[]).unwrap(); + let ms = crate::gpu::recomp::dxc::compile(src, "ms", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &cs).unwrap(); + let pso = |dxil: &[u8]| -> ID3D12PipelineState { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }; + dev.CreateComputePipelineState(&desc).unwrap() + }; + let (pass1, pass2) = (pso(&cs), pso(&ms)); + let args = [ + D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT, + Anonymous: D3D12_INDIRECT_ARGUMENT_DESC_0 { Constant: D3D12_INDIRECT_ARGUMENT_DESC_0_1 { RootParameterIndex: 0, DestOffsetIn32BitValues: 0, Num32BitValuesToSet: 1 } }, + }, + D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }, + ]; + let mut sig: Option = None; + dev.CreateCommandSignature(&D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 16, NumArgumentDescs: 2, pArgumentDescs: args.as_ptr(), NodeMask: 0 }, &rs, &mut sig).unwrap(); + let sig = sig.unwrap(); + let buffer = |bytes: u64, cpu: bool| -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let heap = if cpu { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() } + } else { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() } + }; + let mut r: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + }; + let (indirect, rec, out) = (buffer(256, true), buffer(256, false), buffer(1024, true)); + let map = |b: &ID3D12Resource| -> *mut u32 { + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).unwrap(); + p as *mut u32 + }; + let (a, o) = (map(&indirect), map(&out)); + for (k, &(v, x)) in commands.iter().enumerate() { + std::ptr::copy_nonoverlapping([v, x, 1, 1].as_ptr(), a.add(4 * k), 4); + } + std::ptr::write_bytes(o, 0, 256); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, &pass1).unwrap(); + emit_transition(&list, &indirect, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(2, out.GetGPUVirtualAddress()); + // (the recording's state: a key of its own) + let this = 0x7500_0021usize as *mut c_void; + let draws: [&[u64]; 4] = [&[0, 1, 2], &[3], &[4], &[5]]; + for draw in draws { + let plan = two_pass_plan(draw.len() as u32, records, with(this, |s| s.record_open)); + // (the 256 B of records in halves of 128 B: 4 groups at most) + run_two_pass_plan(this, &list, &plan, &rec, rec.GetGPUVirtualAddress(), 128, |k, compute, va| { + list.SetComputeRootUnorderedAccessView(1, va); + list.SetPipelineState(if compute { &pass1 } else { &pass2 }); + list.ExecuteIndirect(&sig, 1, &indirect, draw[k as usize] * 16, None::<&ID3D12Resource>, 0); + Ok(()) + }) + .unwrap(); + } + assert_eq!(with(this, |s| s.record_open).is_some(), records == Records::Halves, "a mesh pass left with no barrier after it"); + forget(this); + emit_transition(&list, &indirect, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, dev, None, 10_000).unwrap(); + for &(v, x) in &commands { + let got: Vec = (0..x).map(|g| *o.add((v * 16 + g) as usize)).collect(); + assert_eq!(got, vec![v; x as usize], "the records the mesh pass of command {v} read ({records:?})"); + } + indirect.Unmap(0, None); + out.Unmap(0, None); + } + } - // 1. Background compute build SUCCEEDS: real PSO R is registered in TRANSLATED_COMPUTE, - // stand-in S is NOT. ExecuteIndirect resolves S -> R and treats it as translated. - let standin_ok = 0x7200_0001usize; - let pso_vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; - let mut real_ok_pso = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let real_ok = &mut real_ok_pso as *mut ResolutionPso as usize; - let sig_root_changing = 0x7200_00F0usize; - note_indirect_signature(sig_root_changing, IndirectSignatureInfo::new(false, true, None)); + /// With heap windows the two-pass programs read the memory windows from the shared heap + /// (`pso::mem_windows`): both passes' binds set it on a list that has none, as `bind_abi` does. + /// (Heap windows are opt-in: run with `XCL_HEAP_WINDOWS=1`, else skipped.) + #[test] + fn two_pass_binds_set_the_shared_view_heap() { + use crate::gpu::recomp::runner::skip_test; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + if !crate::gpu::recomp::pso::heap_windows() { + skip_test("no heap windows (opt-in: XCL_HEAP_WINDOWS=1)"); + return; + } + #[repr(C)] + struct FakeList { + vt: *const usize, + calls: Mutex>>, + } + unsafe extern "system" fn fake_set_heaps(this: *mut c_void, n: u32, heaps: *const usize) { + let v = if heaps.is_null() { Vec::new() } else { std::slice::from_raw_parts(heaps, n as usize).to_vec() }; + (*(this as *const FakeList)).calls.lock().unwrap().push(v); + } + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + // the shared heap with a window view, unless the backend made it already + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1 << 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut window: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut window).unwrap(); + let window = window.unwrap(); + if super::super::console_heap::global_heap().is_none() && !super::super::console_heap::set_window_views(&dev, &[(window.as_raw() as usize, 1 << 16)]) { + skip_test("no shared heap"); + return; + } + let g = super::super::console_heap::global_heap().unwrap().as_raw() as usize; + let mut orig_vt = [0usize; 64]; + orig_vt[28] = fake_set_heaps as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let fake = Box::new(FakeList { vt: ext_vt.as_ptr().add(1), calls: Mutex::new(Vec::new()) }); + let this = &*fake as *const FakeList as *mut c_void; + let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this).unwrap(); + // no root signatures: the bind stops before it records anything else + let tp = super::super::real::TwoPassPso { compute: 0, compute_rs: 0, mesh_rs: 0, record: Default::default(), mesh_groups_per_record: 1, kind: "MS" }; + for compute_pass in [true, false] { + super::super::list_x::set_descriptor_heaps_x(this, 0, std::ptr::null()); + assert!(super::super::list_x::bound_heaps(this, false).is_empty()); + assert!(bind_two_pass_stage(this, list, 0, &tp, 0, compute_pass).is_err()); + // (the shared sampler heap goes with it in the same call when there is one: + // `list_x::ensure_view_heap`; the bind may have made it) + let mut expected = vec![g]; + if let Some(s) = super::super::console_heap::global_sampler_heap() { + expected.push(s.as_raw() as usize); + } + assert_eq!(super::super::list_x::bound_heaps(this, false), expected, "compute pass {compute_pass}: the shared heap is bound"); + assert_eq!(fake.calls.lock().unwrap().last(), Some(&expected), "compute pass {compute_pass}"); + } + super::super::list_x::bound_heaps(this, true); + forget(this); + } + } - pso_async::submit( - standin_ok, - true, - Box::new(move || { - real::register_translated_compute_for_test(real_ok); - real_ok - }), - ); - assert_eq!(pso_async::resolve_wait(standin_ok), real_ok); - assert!(!real::is_translated_compute(standin_ok)); - assert!(real::is_translated_compute(real_ok)); - reset(list_ptr, 0x7200_0100, standin_ok); + /// A reusable block must fit the recording's remaining budget, not just its request. + #[test] + fn gpu_two_pass_pooled_scratch_respects_remaining_budget() { + use windows::Win32::Graphics::{Direct3D::D3D_FEATURE_LEVEL_12_0, Dxgi::*}; + let _warp_guard = lock_warp_tests(); unsafe { - // With `sig_root_changing`, a translated compute PSO is caught by the root-changing - // guard instead of falling through to `pc` (which happened when `R` wasn't registered). - execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); + let factory: IDXGIFactory6 = CreateDXGIFactory1().unwrap(); + let selector = crate::gpu::adapter::Selector::from_env_or("auto"); + let mut chosen: Option<(String, ID3D12Device)> = None; + if selector == crate::gpu::adapter::Selector::Warp { + if let Ok(adapter) = factory.EnumWarpAdapter::() { + let mut dev: Option = None; + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut dev).is_ok() { + chosen = Some(("WARP (software renderer)".into(), dev.unwrap())); + } + } + } else { + for (adapter, desc) in crate::gpu::adapter::candidates(&factory, &selector) { + let mut dev: Option = None; + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut dev).is_ok() { + chosen = Some((crate::gpu::adapter::name(&desc), dev.unwrap())); + break; + } + } + } + let Some((name, dev)) = chosen else { + crate::gpu::recomp::runner::skip_test("no selected D3D12 adapter"); + return; + }; + println!("POOLED_SCRATCH_ADAPTER={name}"); + let key = dev.as_raw() as usize; + // These are state keys only; scratch_args does not call through a list pointer. + let (consumer, producer, empty) = (0x7500_1011usize as *mut c_void, 0x7500_1012usize as *mut c_void, 0x7500_1013usize as *mut c_void); + let allocator = 0x7500_1014usize; + let first = scratch_args(consumer, &dev, SCRATCH_BLOCK).unwrap(); + assert_eq!(with(consumer, |s| s.scratch_taken), SCRATCH_BLOCK); + reset(producer, allocator, 0); + let large = scratch_args(producer, &dev, SCRATCH_CAP).unwrap(); + assert_eq!(large.0.GetDesc().Width, SCRATCH_CAP); + reset(producer, 0, 0); + release_allocator_res(allocator); + let second = scratch_args(consumer, &dev, SCRATCH_BLOCK).unwrap(); + let taken = with(consumer, |s| s.scratch_taken); + println!("POOLED_SCRATCH taken={taken} second_bytes={} cap={SCRATCH_CAP}", second.0.GetDesc().Width); + // If it was too large for consumer, the cached block remains reusable by an empty recording. + let reused = if taken <= SCRATCH_CAP { + let r = scratch_args(empty, &dev, SCRATCH_CAP).unwrap(); + assert_eq!(r.0.as_raw(), large.0.as_raw()); + assert_eq!(with(empty, |s| s.scratch_taken), SCRATCH_CAP); + assert!(scratch_args(empty, &dev, 256).is_err()); + Some(r) + } else { None }; + drop((first, second, large, reused)); + for list in [consumer, producer, empty] { forget(list); } + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + assert!(taken <= SCRATCH_CAP, "pooled block exceeds recording budget: {taken} > {SCRATCH_CAP}"); } - assert_eq!( - fake.execute_indirect_calls.load(Ordering::Relaxed), - 0, - "ExecuteIndirect must recognize resolved async compute PSO R as translated" - ); + } - // 2. Background compute build FAILS (returns 0): stand-in S_fail is NOT in - // TRANSLATED_COMPUTE. Dispatch must skip cleanly without binding XCL's ABI RS/UAVs - // onto S_fail, and ExecuteIndirect must not enter bind_abi either. - let standin_fail = 0x7200_0003usize; - pso_async::submit(standin_fail, true, Box::new(|| 0)); - assert_eq!(pso_async::resolve_wait(standin_fail), standin_fail); - assert!(!real::is_translated_compute(standin_fail)); + #[cfg(test)] + fn make_test_fence(initial: u64) -> (ID3D12Fence, Arc) { + use std::mem::{offset_of, size_of}; + use std::sync::atomic::AtomicU32; + #[repr(C)] + struct TestFence { + vtable: *const usize, + refs: AtomicU32, + value: Arc, + } + unsafe extern "system" fn qi(_: *mut c_void, _: *const windows::core::GUID, out: *mut *mut c_void) -> windows::core::HRESULT { + if !out.is_null() { + *out = std::ptr::null_mut(); + } + windows::Win32::Foundation::E_NOINTERFACE + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + (*this.cast::()).refs.fetch_add(1, Ordering::Relaxed) + 1 + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let f = &*this.cast::(); + let left = f.refs.fetch_sub(1, Ordering::Release) - 1; + if left == 0 { + std::sync::atomic::fence(Ordering::Acquire); + drop(Box::from_raw(this.cast::())); + } + left + } + unsafe extern "system" fn completed(this: *mut c_void) -> u64 { + (*this.cast::()).value.load(Ordering::Acquire) + } + extern "system" fn unexpected() { + std::process::abort(); + } + static VTABLE: std::sync::OnceLock<&'static [usize]> = std::sync::OnceLock::new(); + let vt = *VTABLE.get_or_init(|| { + const SLOT: usize = size_of::(); + let mut v = vec![unexpected as usize; size_of::() / SLOT]; + v[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.QueryInterface) / SLOT] = qi as usize; + v[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.AddRef) / SLOT] = add_ref as usize; + v[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = release as usize; + v[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = completed as usize; + Box::leak(v.into_boxed_slice()) + }); + let value = Arc::new(AtomicU64::new(initial)); + let ptr = Box::into_raw(Box::new(TestFence { vtable: vt.as_ptr(), refs: AtomicU32::new(1), value: Arc::clone(&value) })); + let fence = unsafe { ID3D12Fence::from_raw(ptr.cast()) }; + (fence, value) + } - reset(list_ptr, 0x7200_0100, standin_fail); - let before = counts_snapshot(); + #[cfg(test)] + fn lock_warp_tests() -> std::sync::MutexGuard<'static, ()> { + static LOCK: Mutex<()> = Mutex::new(()); + LOCK.lock().unwrap_or_else(|e| e.into_inner()) + } + + #[cfg(test)] + fn warp_device_for_test() -> Option { + use windows::Win32::Graphics::{Direct3D::D3D_FEATURE_LEVEL_11_0, Dxgi::*}; unsafe { - dispatch(list_ptr, 1, 1, 1); + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let warp: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let mut dev: Option = None; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return None; + } + dev } - let after = counts_snapshot(); - assert_eq!(after[DISPATCHES], before[DISPATCHES]); - assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]); - assert_eq!(fake.set_compute_rs_calls.load(Ordering::Relaxed), 0); - assert_eq!(fake.set_compute_uav_calls.load(Ordering::Relaxed), 0); - assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 0); - assert_eq!(fake.dispatch_calls.load(Ordering::Relaxed), 0); + } - unsafe { - execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); + #[test] + fn submitted_two_pass_buffers_reclaim_via_fence_without_allocator_reset() { + let _warp_guard = lock_warp_tests(); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let ids = Box::new([0u8; 4]); + let list = ids.as_ptr() as *mut c_void; + let (alloc1, alloc2, q1) = (ids.as_ptr() as usize + 1, ids.as_ptr() as usize + 2, (ids.as_ptr() as usize + 3) as *mut c_void); + reset(list, alloc1, 0); + let (_, _, first_scratch_raw, rec_raw) = unsafe { + let (s, _) = scratch_args(list, &dev, SCRATCH_BLOCK).unwrap(); + let rec = TwoPassBuf::make(&dev, RECORD_MIN, "record buffer").unwrap(); + let rec_raw = rec.res.as_raw() as usize; + with(list, |st| { + st.res_buf = Some(rec); + }); + track_two_pass_list(list as usize); + (s.clone(), s.GetDesc().Width, s.as_raw() as usize, rec_raw) + }; + let (fence, val) = make_test_fence(4); + unsafe { two_pass_submitted(q1, Some(&fence), 5, &[list]) }; + reset(list, alloc2, 0); + let still_in_alloc = ALLOC_RES.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&alloc1)); + let early = take_free(key, RECORD_MIN, u64::MAX).map(|b| b.res.as_raw() as usize); + val.store(5, Ordering::Release); + let mut got = Vec::new(); + while let Some(b) = take_free(key, 1, u64::MAX) { + got.push(b.res.as_raw() as usize); } - 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" - ); + forget(list); + assert!(!still_in_alloc, "submitted buffers must wait on their fence, not alloc1"); + assert!(early.is_none(), "incomplete fence must keep buffers out of FREE_RES"); + assert!(got.contains(&first_scratch_raw) && got.contains(&rec_raw), "fence completion reclaims both without allocator reset: got={got:?}"); + } - // 3. The same failed stand-in (made from a console shader) with a Dispatch signature: - // nothing to run, as for Dispatch – the PC call would pair the stand-in with the list's - // compute root signature (XCL's ABI one after a translated dispatch: debug layer 953) - let sig_dispatch = 0x7200_00F8usize; - real::register_console_compute_for_test(standin_fail); - note_indirect_signature(sig_dispatch, IndirectSignatureInfo::new(true, false, None)); - let before = counts_snapshot(); + #[test] + fn split_segment_without_allocator_reclaims_via_fence_instead_of_aging() { + let _warp_guard = lock_warp_tests(); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let ids = Box::new([0u8; 4]); + let (from, to, q1) = (ids.as_ptr() as *mut c_void, (ids.as_ptr() as usize + 1) as *mut c_void, (ids.as_ptr() as usize + 2) as *mut c_void); + let rec = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "record buffer") }.unwrap(); + let rec_raw = rec.res.as_raw() as usize; + with(to, |s| { + s.allocator = 0; + s.res_buf = Some(rec); + }); + track_two_pass_list(to as usize); + let (fence, val) = make_test_fence(2); + unsafe { two_pass_submitted(q1, Some(&fence), 3, &[to]) }; + inherit_for_split(from, to, 0); + let early = take_free(key, RECORD_MIN, u64::MAX).map(|b| b.res.as_raw() as usize); + val.store(3, Ordering::Release); + let after = take_free(key, RECORD_MIN, u64::MAX).map(|b| b.res.as_raw() as usize); + forget(from); + forget(to); + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + assert!(early.is_none()); + assert_eq!(after, Some(rec_raw), "submitted split segment reclaims on fence completion instead of waiting 10 s in UNKNOWN_RES"); + } + + #[test] + fn untracked_submit_falls_back_to_allocator_res() { + let _warp_guard = lock_warp_tests(); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + let ids = Box::new([0u8; 4]); + let list = ids.as_ptr() as *mut c_void; + let (alloc1, alloc2, q1) = (ids.as_ptr() as usize + 1, ids.as_ptr() as usize + 2, (ids.as_ptr() as usize + 3) as *mut c_void); + reset(list, alloc1, 0); + let rec = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "record buffer") }.unwrap(); + let rec_raw = rec.res.as_raw() as usize; + with(list, |s| s.res_buf = Some(rec)); + track_two_pass_list(list as usize); + unsafe { two_pass_submitted(q1, None, 0, &[list]) }; + reset(list, alloc2, 0); + let held: Vec = ALLOC_RES.lock().unwrap().as_ref().and_then(|m| m.get(&alloc1)).map_or(Vec::new(), |v| v.iter().map(|b| b.res.as_raw() as usize).collect()); + release_allocator_res(alloc1); + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + forget(list); + assert_eq!(held, vec![rec_raw]); + } + + #[test] + fn resubmitted_list_waits_for_all_queue_fences() { + let _warp_guard = lock_warp_tests(); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let ids = Box::new([0u8; 5]); + let list = ids.as_ptr() as *mut c_void; + let (alloc1, alloc2) = (ids.as_ptr() as usize + 1, ids.as_ptr() as usize + 2); + let (q1, q2) = ((ids.as_ptr() as usize + 3) as *mut c_void, (ids.as_ptr() as usize + 4) as *mut c_void); + reset(list, alloc1, 0); + let rec = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "record buffer") }.unwrap(); + let rec_raw = rec.res.as_raw() as usize; + with(list, |s| s.res_buf = Some(rec)); + track_two_pass_list(list as usize); + let (f1, v1) = make_test_fence(9); + let (f2, v2) = make_test_fence(1); unsafe { - execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + two_pass_submitted(q1, Some(&f1), 10, &[list]); + two_pass_submitted(q1, Some(&f1), 15, &[list]); + // The callback for the earlier Signal can arrive after the later one. + two_pass_submitted(q1, Some(&f1), 12, &[list]); + two_pass_submitted(q2, Some(&f2), 2, &[list]); } - let after = counts_snapshot(); - assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 1, "a dispatch of an untranslated console compute pipeline must not reach the PC ExecuteIndirect"); - assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]); + reset(list, alloc2, 0); + v1.store(12, Ordering::Release); + v2.store(2, Ordering::Release); + let after_first_only = take_free(key, RECORD_MIN, u64::MAX).map(|b| b.res.as_raw() as usize); + v1.store(15, Ordering::Release); + v2.store(1, Ordering::Release); + let missing_q2 = take_free(key, RECORD_MIN, u64::MAX).map(|b| b.res.as_raw() as usize); + v2.store(2, Ordering::Release); + let ready = take_free(key, RECORD_MIN, u64::MAX).map(|b| b.res.as_raw() as usize); + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + forget(list); + assert!(after_first_only.is_none()); + assert!(missing_q2.is_none()); + assert_eq!(ready, Some(rec_raw)); + } - // 4. A native PC compute pipeline (not made from a console shader) with the same Dispatch - // signature still goes to the PC call, as on main - let native = 0x7200_0004usize; - reset(list_ptr, 0x7200_0100, native); + #[test] + fn empty_allocator_release_trims_idle_two_pass_buffers() { + let _warp_guard = lock_warp_tests(); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let buf = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "idle record buffer") }.unwrap(); + let now = std::time::Instant::now(); + let evicted = { + let mut free = FREE_RES.lock().unwrap(); + let evicted = free.put(now - FREE_RES_IDLE, buf.bytes, key, buf); + free.free.sort_by_key(|entry| entry.0); + evicted + }; + drop(evicted); + let allocator_key = Box::new(0u8); + + release_allocator_res((&*allocator_key as *const u8) as usize); + + // Query the pool directly. take_free would sweep idle buffers itself. + let retained = FREE_RES.lock().unwrap().take(key, 0, u64::MAX); + assert!(retained.is_none(), "idle buffer survived an empty allocator release"); + } + + #[test] + fn removed_device_fence_never_reclaims_two_pass_buffers_for_reuse() { + let _warp_guard = lock_warp_tests(); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let (f, v) = make_test_fence(16); unsafe { - execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + assert_eq!(fence_state(&f, 17), FenceState::Pending); + v.store(17, Ordering::Release); + assert_eq!(fence_state(&f, 17), FenceState::Completed); + v.store(18, Ordering::Release); + assert_eq!(fence_state(&f, 17), FenceState::Completed); + v.store(u64::MAX, Ordering::Release); + assert_eq!(fence_state(&f, 17), FenceState::Removed); + assert_eq!(fence_state(&f, 0), FenceState::Removed); } - assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 2, "a native PC compute pipeline must still reach the PC ExecuteIndirect"); - // a signature made later at the same address without a Dispatch argument goes to the PC - reset(list_ptr, 0x7200_0100, standin_fail); - note_indirect_signature(sig_dispatch, IndirectSignatureInfo::default()); - unsafe { - execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); + let ids = Box::new([0u8; 4]); + let (list1, list2) = (ids.as_ptr() as *mut c_void, (ids.as_ptr() as usize + 1) as *mut c_void); + let (alloc, q) = (ids.as_ptr() as usize + 2, (ids.as_ptr() as usize + 3) as *mut c_void); + + // Case 1: already removed when retired. + reset(list1, alloc, 0); + let rec1 = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "record buffer") }.unwrap(); + let rec1_raw = rec1.res.as_raw() as usize; + with(list1, |s| s.res_buf = Some(rec1)); + track_two_pass_list(list1 as usize); + unsafe { two_pass_submitted(q, Some(&f), 17, &[list1]) }; + reset(list1, alloc, 0); + let retired_removed_free = take_free(key, RECORD_MIN, u64::MAX); + + // Case 2: pending when retired, then transitions to u64::MAX. + let (f2, v2) = make_test_fence(16); + reset(list2, alloc, 0); + let rec2 = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "record buffer") }.unwrap(); + let rec2_raw = rec2.res.as_raw() as usize; + with(list2, |s| s.res_buf = Some(rec2)); + track_two_pass_list(list2 as usize); + unsafe { two_pass_submitted(q, Some(&f2), 17, &[list2]) }; + reset(list2, alloc, 0); + v2.store(u64::MAX, Ordering::Release); + assert_eq!(reclaim_fenced(), 0, "u64::MAX sentinel must not reclaim pending batches"); + let flipped_removed_free = take_free(key, RECORD_MIN, u64::MAX); + + // Clean up the synthetic FENCED_RES batches before asserting. + let mut drained = Vec::new(); + let mut removed_bytes = 0u64; + { + let mut fenced = FENCED_RES.lock().unwrap(); + let mut i = 0; + while i < fenced.len() { + if fenced[i].bufs.iter().any(|b| { + let r = b.res.as_raw() as usize; + r == rec1_raw || r == rec2_raw + }) { + let batch = fenced.remove(i).unwrap(); + removed_bytes += batch.bytes; + drained.extend(batch.bufs); + } else { + i += 1; + } + } + if removed_bytes > 0 { + FENCED_BYTES.fetch_sub(removed_bytes, Ordering::Release); + } } - assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 3); + drop(drained); + forget(list1); + forget(list2); - forget(list_ptr); - list_x::on_release(list_ptr as usize); - let real_ok_owner = pso_async::released(standin_ok); - let _ = pso_async::released(standin_fail); - real::forget_pso_for_test(real_ok); - real::forget_pso_for_test(standin_fail); - assert_eq!(real_ok_owner, real_ok); - assert_eq!(unsafe { resolution_release(real_ok_owner as *mut c_void) }, 0); - assert!(!real::is_console_compute(standin_fail), "a released pipeline's address does not stay a console one"); + assert!(retired_removed_free.is_none(), "device removal must keep retired buffers out of FREE_RES"); + assert!(flipped_removed_free.is_none(), "transition to u64::MAX must keep buffers out of FREE_RES"); } #[test] - fn execute_indirect_skips_failed_shared_console_compute_standin() { - let mut orig_vt = [0usize; 64]; - orig_vt[1] = fake_add_ref as usize; - orig_vt[2] = fake_release as usize; - orig_vt[14] = fake_dispatch as usize; - orig_vt[25] = fake_set_pso as usize; - orig_vt[29] = fake_set_compute_rs as usize; - orig_vt[41] = fake_set_compute_uav as usize; - orig_vt[59] = fake_execute_indirect as usize; + fn closed_list_replay_keeps_two_pass_buffer_across_fence_and_idle_trim() { + let _warp_guard = lock_warp_tests(); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + unsafe { + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list_obj: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let list = list_obj.as_raw(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let make_buf = |heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap(); + r.unwrap() + }; + let upload = make_buf(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let readback = make_buf(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + let rec = TwoPassBuf::make(&dev, RECORD_MIN, "record buffer").unwrap(); + let rec_raw = rec.res.as_raw() as usize; + list_obj.CopyBufferRegion(&rec.res, 0, &upload, 0, 4); + emit_transition(&list_obj, &rec.res, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); + list_obj.CopyBufferRegion(&readback, 0, &rec.res, 0, 4); + emit_transition(&list_obj, &rec.res, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + list_obj.Close().unwrap(); + + reset(list, alloc.as_raw() as usize, 0); + with(list, |s| s.res_buf = Some(rec)); + track_two_pass_list(list as usize); + + let write_upload = |val: u32| { + let mut p = std::ptr::null_mut(); + upload.Map(0, Some(&D3D12_RANGE { Begin: 0, End: 0 }), Some(&mut p)).unwrap(); + *p.cast::() = val; + upload.Unmap(0, None); + }; + let clear_readback = || { + let mut p = std::ptr::null_mut(); + readback.Map(0, Some(&D3D12_RANGE { Begin: 0, End: 0 }), Some(&mut p)).unwrap(); + *p.cast::() = 0; + readback.Unmap(0, None); + }; + let read_word = || -> u32 { + let mut p = std::ptr::null_mut(); + readback.Map(0, Some(&D3D12_RANGE { Begin: 0, End: 4 }), Some(&mut p)).unwrap(); + let out = *p.cast::(); + readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); + out + }; + let cl: ID3D12CommandList = list_obj.cast().unwrap(); + + // Execution #1 of closed list. + write_upload(0x1122_3344); + clear_readback(); + queue.ExecuteCommandLists(&[Some(cl.clone())]); + queue.Signal(&fence, 1).unwrap(); + two_pass_submitted(queue.as_raw(), Some(&fence), 1, &[list]); + while super::super::real::fence_completed(&fence) < 1 { + std::thread::yield_now(); + } + assert_eq!(read_word(), 0x1122_3344); + + // Completing the fence and trimming idle FREE_RES must leave the closed list's buffer intact. + reclaim_fenced(); + let idle_gone = FREE_RES.lock().unwrap().take_idle(std::time::Instant::now() + FREE_RES_IDLE + std::time::Duration::from_secs(1), FREE_RES_IDLE); + drop(idle_gone); + assert!(take_free(key, RECORD_MIN, u64::MAX).is_none(), "closed list must retain its buffer until Reset/Release"); + assert_eq!(with(list, |s| s.res_buf.as_ref().map(|b| b.res.as_raw() as usize)), Some(rec_raw)); + + // Replay #2 of the SAME closed list without Reset. + write_upload(0x5566_7788); + clear_readback(); + queue.ExecuteCommandLists(&[Some(cl)]); + queue.Signal(&fence, 2).unwrap(); + two_pass_submitted(queue.as_raw(), Some(&fence), 2, &[list]); + while super::super::real::fence_completed(&fence) < 2 { + std::thread::yield_now(); + } + assert_eq!(read_word(), 0x5566_7788); + + // Resetting the list now releases its buffer via the completed submit fence. + reset(list, 0, 0); + let reclaimed = take_free(key, RECORD_MIN, u64::MAX).map(|b| b.res.as_raw() as usize); + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + forget(list); + assert_eq!(reclaimed, Some(rec_raw)); + } + } - let mut ext_vt = vec![0usize; 65]; - ext_vt[0] = orig_vt.as_ptr() as usize; - ext_vt[1..].copy_from_slice(&orig_vt); + thread_local! { + static FENCED_PUBLISH_OBSERVATION: std::cell::Cell> = + const { std::cell::Cell::new(None) }; + } - let fake = Box::new(FakeAdoptedList { - vt: unsafe { ext_vt.as_ptr().add(1) }, - refs: AtomicUsize::new(1), - dispatch_calls: AtomicUsize::new(0), - set_compute_rs_calls: AtomicUsize::new(0), - set_compute_uav_calls: AtomicUsize::new(0), - set_pso_calls: AtomicUsize::new(0), - last_pso: AtomicUsize::new(0), - execute_indirect_calls: AtomicUsize::new(0), + pub(super) fn observe_fenced_batch_publication() { + FENCED_PUBLISH_OBSERVATION.with(|observed| { + if observed.get().is_some() { + observed.set(Some(matches!(FENCED_RES.try_lock(), Err(std::sync::TryLockError::WouldBlock)))); + } }); - let list_ptr = &*fake as *const FakeAdoptedList as *mut c_void; - - // With shared stand-ins (`standin::shell`), `dev_create_compute_pso` registers the - // title-facing shell in `CONSOLE_COMPUTE`, while `pso_async::resolve_wait` returns the - // shared driver pipeline when the background build fails. - let shell_fail = 0x7210_0001usize; - let shell_ok = 0x7210_0002usize; - let shared_driver = 0x7210_0003usize; - let pso_vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; - let mut real_ok_pso = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let real_ok = &mut real_ok_pso as *mut ResolutionPso as usize; - let sig_dispatch = 0x7210_00F8usize; - let sig_root_changing = 0x7210_00F0usize; - note_indirect_signature(sig_dispatch, IndirectSignatureInfo::new(true, false, None)); - note_indirect_signature(sig_root_changing, IndirectSignatureInfo::new(false, true, None)); - - pso_async::submit_lazy(shell_fail, true, Box::new(|| 0), 0); - pso_async::shared(shell_fail, shared_driver); - real::register_console_compute_for_test(shell_fail); + } - pso_async::submit_lazy( - shell_ok, - true, - Box::new(move || { - real::register_translated_compute_for_test(real_ok); - real_ok - }), - 0, - ); - pso_async::shared(shell_ok, shared_driver); - real::register_console_compute_for_test(shell_ok); + #[test] + fn fenced_batch_stays_locked_until_its_bytes_are_counted() { + let _warp_guard = lock_warp_tests(); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let buf = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "record buffer") }.unwrap(); + let (fence, completed) = make_test_fence(0); - assert_eq!(pso_async::resolve_wait(shell_fail), shared_driver); - assert!(!pso_async::is_pending(shell_fail)); - assert!(real::is_console_compute(shell_fail)); - assert!(!real::is_console_compute(shared_driver)); + FENCED_PUBLISH_OBSERVATION.set(Some(false)); + retire_recording_res(0, vec![buf], vec![(1, fence, 1)], false); + let observed = FENCED_PUBLISH_OBSERVATION.take(); - // 1. Failed shared console compute stand-in with a Dispatch signature must be skipped, - // never forwarded to PC ExecuteIndirect with the shared driver pipeline. - reset(list_ptr, 0x7210_0100, shell_fail); - let before = counts_snapshot(); - unsafe { - execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); - } - let after = counts_snapshot(); - assert_eq!( - fake.execute_indirect_calls.load(Ordering::Relaxed), - 0, - "failed shared console compute stand-in must not reach PC ExecuteIndirect" - ); - assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]); + completed.store(1, Ordering::Release); + drop(take_free(key, RECORD_MIN, RECORD_MIN)); + assert_eq!(observed, Some(true), "reclamation must wait until the batch is counted"); + } - // 2. Another shell sharing the same driver pipeline whose build succeeds still takes the - // translated path (caught here by the root-changing guard rather than falling through to PC). - reset(list_ptr, 0x7210_0100, shell_ok); - unsafe { - execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); - } - assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0); + #[test] + fn batch_buffer_reclaims_via_fence_when_recording_resets() { + let _warp_guard = lock_warp_tests(); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let ids = Box::new([0u8; 4]); + let list = ids.as_ptr() as *mut c_void; + let (alloc1, alloc2, q1) = (ids.as_ptr() as usize + 1, ids.as_ptr() as usize + 2, (ids.as_ptr() as usize + 3) as *mut c_void); + reset(list, alloc1, 0); + let batch = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "two-pass batch records") }.unwrap(); + let batch_raw = batch.res.as_raw() as usize; + with(list, |s| s.batch_buf = Some(batch)); + track_two_pass_list(list as usize); + let (fence, val) = make_test_fence(2); + unsafe { two_pass_submitted(q1, Some(&fence), 3, &[list]) }; + reset(list, alloc2, 0); + let early = take_free(key, RECORD_MIN, u64::MAX); + val.store(3, Ordering::Release); + let ready = take_free(key, RECORD_MIN, u64::MAX).map(|b| b.res.as_raw() as usize); + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + forget(list); + assert!(early.is_none()); + assert_eq!(ready, Some(batch_raw)); + } - // 3. Releasing `shell_fail` forgets its `CONSOLE_COMPUTE` entry so a native PC compute - // pipeline later allocated at the same address still reaches PC ExecuteIndirect. - let _ = pso_async::released(shell_fail); - real::forget_pso_for_test(shell_fail); - assert!(!real::is_console_compute(shell_fail)); - reset(list_ptr, 0x7210_0100, shell_fail); + #[test] + fn gpu_scale_args_reports_uncapped_group_count_feedback() { + let _warp_guard = lock_warp_tests(); + let Ok(dev) = crate::gpu::recomp::runner::device() else { + crate::gpu::recomp::runner::skip_test("no SM 6.6 GPU"); + return; + }; unsafe { - execute_indirect(list_ptr, sig_dispatch, 1, 0, 0, 0, 0); - } - assert_eq!( - fake.execute_indirect_calls.load(Ordering::Relaxed), - 1, - "native PC pipeline at a released shell's address must still reach PC ExecuteIndirect" - ); + let (rs, pso) = scale_indirect_pipeline(&dev).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let mut fb = IndirectFeedback::new(&dev).unwrap(); + fb.slots.push(IndirectFeedbackSlot::new()); + + let make_buf = |heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES, flags: D3D12_RESOURCE_FLAGS, bytes: u64| -> 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 r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap(); + r.unwrap() + }; + let run_once = |io_words: [u32; 10], src_words: [u32; 4], cnt_val: u32, fb: &mut IndirectFeedback, last_cap: u32, flush_warm: bool| -> (Vec, [u32; 3]) { + let upload = make_buf(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_FLAG_NONE, 1024); + let io = make_buf(D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, 256); + let src = make_buf(D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, 256); + let dst = make_buf(D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, 256); + let cnt = make_buf(D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, 256); + let rb = make_buf(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, 256); + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).unwrap(); + let u = p as *mut u32; + std::ptr::copy_nonoverlapping(io_words.as_ptr(), u, 10); + std::ptr::copy_nonoverlapping(src_words.as_ptr(), u.add(64), 4); + *u.add(128) = cnt_val; + upload.Unmap(0, None); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, Some(&pso)).unwrap(); + list.CopyBufferRegion(&io, 0, &upload, 0, 40); + list.CopyBufferRegion(&src, 0, &upload, 256, 16); + list.CopyBufferRegion(&cnt, 0, &upload, 512, 4); + emit_transition(&list, &io, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + emit_transition(&list, &src, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + emit_transition(&list, &cnt, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetComputeRootSignature(&rs); + for (slot, va) in scale_views(io.GetGPUVirtualAddress(), (io_words[9] != 0).then_some(fb.gpu_va), src.GetGPUVirtualAddress(), dst.GetGPUVirtualAddress(), (io_words[7] != 0).then_some(cnt.GetGPUVirtualAddress())) { + list.SetComputeRootUnorderedAccessView(slot, va); + } + list.Dispatch(1, 1, 1); + emit_transition(&list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.CopyBufferRegion(&rb, 0, &dst, 0, 32); + list.Close().unwrap(); + let cl: ID3D12CommandList = list.cast().unwrap(); + queue.ExecuteCommandLists(&[Some(cl)]); + fb.slots[0].last_cap = last_cap; + fb.slots[0].dirty = true; + fb.dirty = true; + if flush_warm { + assert!(fb.schedule_copy(queue.as_raw() as usize).is_none(), "warm window throttles copyback before 250 ms"); + fb.last_copy = std::time::Instant::now() - std::time::Duration::from_millis(FEEDBACK_WINDOW_MS as u64 + 50); + } + let (copy_cl, fence, val, waits) = fb.schedule_copy(queue.as_raw() as usize).unwrap(); + assert!(waits.is_empty()); + queue.ExecuteCommandLists(&[Some(copy_cl)]); + queue.Signal(&fence, val).unwrap(); + while super::super::real::fence_completed(&fence) < val { + std::thread::yield_now(); + } + assert!(fb.consume_completed()); + let mut rp = std::ptr::null_mut(); + let rrange = D3D12_RANGE { Begin: 0, End: 32 }; + rb.Map(0, Some(&rrange), Some(&mut rp)).unwrap(); + let dst_words = std::slice::from_raw_parts(rp as *const u32, 8).to_vec(); + rb.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); + let rb_range = D3D12_RANGE { Begin: 0, End: 12 }; + let mut fp = std::ptr::null_mut(); + fb.readback.Map(0, Some(&rb_range), Some(&mut fp)).unwrap(); + let hdr_and_slot = std::slice::from_raw_parts(fp.cast::(), 3); + let out_fb = [hdr_and_slot[0], hdr_and_slot[1], hdr_and_slot[2]]; + fb.readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); + (dst_words, out_fb) + }; - forget(list_ptr); - note_indirect_signature(sig_dispatch, IndirectSignatureInfo::default()); - list_x::on_release(list_ptr as usize); - let real_ok_owner = pso_async::released(shell_ok); - real::forget_pso_for_test(shell_ok); - real::forget_pso_for_test(real_ok); - assert_eq!(real_ok_owner, real_ok); - assert_eq!(unsafe { resolution_release(real_ok_owner as *mut c_void) }, 0); + let clamped_before = TWO_PASS[TP_INDIRECT_CLAMPED].load(Ordering::Relaxed); + let dropped_before = TWO_PASS[TP_INDIRECT_GROUPS_DROPPED].load(Ordering::Relaxed); + // Case A: 500 groups clamped to cap=16, feedback enabled (slot 1) -> cold flush, 1 cmd clamped, 484 dropped, raw_n=500 + let (dst_a, fb_a) = run_once([1, 16, 4, 2, 16, 0, 0, 1, 0, 1], [7, 500, 1, 1], 1, &mut fb, 16, false); + assert_eq!(&dst_a[0..8], &[7, 16, 1, 1, 7, 32, 1, 1]); + assert_eq!(fb_a, [1, 484, 501]); + assert_eq!(fb.slots[0].hint(), Some(500)); + assert_eq!(TWO_PASS[TP_INDIRECT_CLAMPED].load(Ordering::Relaxed) - clamped_before, 1); + assert_eq!(TWO_PASS[TP_INDIRECT_GROUPS_DROPPED].load(Ordering::Relaxed) - dropped_before, 484); + + // Case B: live=0 (count=0) after copy_list cleared gpu buffer -> encoded=1 (raw_n=0), active slot stays warm + let (dst_b, fb_b) = run_once([1, 16, 4, 2, 16, 0, 0, 1, 0, 1], [7, 500, 1, 1], 0, &mut fb, 16, true); + assert_eq!(&dst_b[0..8], &[7, 0, 1, 1, 7, 0, 1, 1]); + assert_eq!(fb_b, [0, 0, 1]); + assert_eq!(fb.slots[0].hint(), Some(500), "active slot stays warm across zero-group culling"); + + // Case C: fb_slot=0 leaves feedback buffer at 0 while still clamping normally + let (_, fb_c) = run_once([1, 16, 4, 2, 16, 0, 0, 1, 0, 0], [7, 999, 1, 1], 1, &mut fb, 16, true); + assert_eq!(fb_c, [0, 0, 0]); + } } #[test] - fn two_pass_pso_skips_direct_draw_and_unmatched_execute_indirect() { - #[repr(C)] - struct FakeTwoPassList { - vt: *const usize, - refs: AtomicUsize, - set_graphics_rs_calls: AtomicUsize, - execute_indirect_calls: AtomicUsize, + fn indirect_feedback_copyback_grows_on_clamp_and_decays_over_windows() { + let _warp_guard = lock_warp_tests(); + // Unused PSO drops straight to 0 hint on its first 0-group window. + let mut unused = IndirectFeedbackSlot::new(); + assert_eq!(unused.hint(), None); + unused.in_flight_cap = 100; + unused.apply_window(1); // raw_n = 0, !ever_nonzero + assert_eq!(unused.hint(), Some(0)); + + let mut slot = IndirectFeedbackSlot::new(); + assert_eq!(slot.hint(), None); + // First clamped window bumps all history entries immediately and marks ever_nonzero. + slot.in_flight_cap = 16; + slot.apply_window(501); // raw_n = 500 > cap 16 + assert_eq!(slot.hint(), Some(500)); + // Idle window (encoded=0) preserves history. + slot.in_flight_cap = u32::MAX; + slot.apply_window(0); + assert_eq!(slot.hint(), Some(500)); + // FEEDBACK_HISTORY smaller non-zero windows decay peak back down to 10. + for _ in 0..FEEDBACK_HISTORY { + slot.in_flight_cap = 1000; + slot.apply_window(11); // raw_n = 10 } - unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { - (*(this as *const FakeTwoPassList)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 + assert_eq!(slot.hint(), Some(10)); + // Frustum-culled active PSO (encoded=1 -> raw_n=0) keeps warm history instead of collapsing. + for _ in 0..FEEDBACK_HISTORY { + slot.in_flight_cap = 100; + slot.apply_window(1); } - unsafe extern "system" fn release(this: *mut c_void) -> u32 { - (*(this as *const FakeTwoPassList)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 + assert_eq!(slot.hint(), Some(10)); + + // Also exercise pre-recorded copy_list submission through poll_two_pass_feedback on WARP. + let Some(dev) = warp_device_for_test() else { return }; + unsafe { + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let q_raw = queue.as_raw(); + let dev_key = dev.as_raw() as usize; + let (_va, fb_slot, cold_hint) = prepare_indirect_feedback(&dev, 0x7700_0001).unwrap(); + assert_eq!(cold_hint, None); + mark_indirect_feedback_used(dev_key, fb_slot, 64, q_raw as usize, None); + poll_two_pass_feedback(q_raw); + let wait_fence = { + let g = FEEDBACK.lock().unwrap(); + let fb = &g.as_ref().unwrap()[&dev_key]; + assert!(fb.copy_in_flight); + (fb.copy_fence.clone(), fb.copy_val) + }; + while super::super::real::fence_completed(&wait_fence.0) < wait_fence.1 { + std::thread::yield_now(); + } + poll_two_pass_feedback(q_raw); + FEEDBACK.lock().unwrap().as_mut().unwrap().remove(&dev_key); } - unsafe extern "system" fn set_graphics_rs(this: *mut c_void, _rs: *mut c_void) { - (*(this as *const FakeTwoPassList)).set_graphics_rs_calls.fetch_add(1, Ordering::Relaxed); + } + + #[test] + fn indirect_feedback_waits_for_submit_before_copyback() { + let _warp_guard = lock_warp_tests(); + let Some(dev) = warp_device_for_test() else { return }; + unsafe { + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let q_raw = queue.as_raw(); + let dev_key = dev.as_raw() as usize; + let ids = Box::new([0u8; 2]); + let list = ids.as_ptr() as *mut c_void; + reset(list, ids.as_ptr() as usize + 1, 0); + let (_va, fb_slot, _) = prepare_indirect_feedback(&dev, 0x7700_0002).unwrap(); + with(list, |s| s.fb_uses.push((dev_key, fb_slot, 64))); + track_two_pass_list(list as usize); + + // Recording without submission must not trigger copyback. + poll_two_pass_feedback(q_raw); + { + let g = FEEDBACK.lock().unwrap(); + let fb = &g.as_ref().unwrap()[&dev_key]; + assert!(!fb.dirty && !fb.copy_in_flight); + } + + // Submitting commits `fb_uses`, after which polling submits the copyback. + let (fence, _) = make_test_fence(0); + two_pass_submitted(q_raw, Some(&fence), 2, &[list]); + two_pass_submitted(q_raw, Some(&fence), 1, &[list]); + let pending_value = FEEDBACK.lock().unwrap().as_ref().unwrap()[&dev_key] + .pending_fences.iter().find(|(q, ..)| *q == q_raw as usize).map(|(_, _, value)| *value); + poll_two_pass_feedback(q_raw); + let wait_fence = { + let g = FEEDBACK.lock().unwrap(); + let fb = &g.as_ref().unwrap()[&dev_key]; + assert!(fb.copy_in_flight); + (fb.copy_fence.clone(), fb.copy_val) + }; + while super::super::real::fence_completed(&wait_fence.0) < wait_fence.1 { + std::thread::yield_now(); + } + poll_two_pass_feedback(q_raw); + forget(list); + FEEDBACK.lock().unwrap().as_mut().unwrap().remove(&dev_key); + assert_eq!(pending_value, Some(2), "the delayed callback must not lower the feedback fence"); } - unsafe extern "system" fn exec_indirect( - this: *mut c_void, - _sig: usize, - _max: u32, - _args: usize, - _args_off: u64, - _count_buf: usize, - _count_off: u64, - ) { - (*(this as *const FakeTwoPassList)).execute_indirect_calls.fetch_add(1, Ordering::Relaxed); + } + + #[test] + fn indirect_feedback_ignores_readback_after_device_removal() { + let _warp_guard = lock_warp_tests(); + let Some(dev) = warp_device_for_test() else { return }; + unsafe { + let mut fb = IndirectFeedback::new(&dev).unwrap(); + assert!(fb.slot_for(0x7700_0003).is_some()); + let (removed_fence, _) = make_test_fence(u64::MAX); + fb.copy_fence = removed_fence.clone(); + fb.copy_val = 1; + fb.copy_in_flight = true; + fb.dirty = true; + assert!(!fb.consume_completed()); + assert!(fb.removed); + assert!(fb.copy_in_flight, "removed fence must not release copy_in_flight or map readback"); + assert_eq!(fb.slots[0].hint(), None); + assert!(fb.schedule_copy(0).is_none()); + assert!(fb.slot_for(0x7700_0004).is_none()); + + // Also verify schedule_copy aborts cleanly if a pending queue fence already hit u64::MAX. + let mut fb2 = IndirectFeedback::new(&dev).unwrap(); + assert!(fb2.slot_for(0x7700_0005).is_some()); + fb2.dirty = true; + fb2.pending_fences.push((1, removed_fence, 4)); + assert!(fb2.schedule_copy(0).is_none()); + assert!(fb2.removed); } + } - let mut orig_vt = [0usize; 64]; - orig_vt[1] = add_ref as usize; - orig_vt[2] = release as usize; - orig_vt[30] = set_graphics_rs as usize; - orig_vt[59] = exec_indirect as usize; + struct LaterFenceCompletion { + oldest: ID3D12Fence, + later_value: Arc, + now: std::time::Instant, + } - let mut ext_vt = vec![0usize; 65]; - ext_vt[0] = orig_vt.as_ptr() as usize; - ext_vt[1..].copy_from_slice(&orig_vt); + thread_local! { + // Complete only the fences this test has registered, once allocation actually waits. + static FENCES_TO_SIGNAL_ON_WAIT: std::cell::RefCell)>> = + const { std::cell::RefCell::new(Vec::new()) }; + static LATER_FENCE_COMPLETION: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; + } - let fake = Box::new(FakeTwoPassList { - vt: unsafe { ext_vt.as_ptr().add(1) }, - refs: AtomicUsize::new(1), - set_graphics_rs_calls: AtomicUsize::new(0), - execute_indirect_calls: AtomicUsize::new(0), + pub(super) fn fence_wait_now() -> std::time::Instant { + LATER_FENCE_COMPLETION.with_borrow(|schedule| { + schedule.as_ref().map_or_else(std::time::Instant::now, |s| s.now) + }) + } + + pub(super) fn signal_fence_on_wait(fence: &ID3D12Fence, polls: u32) { + LATER_FENCE_COMPLETION.with_borrow_mut(|schedule| { + if let Some(schedule) = schedule { + if polls >= FENCE_WAIT_YIELD_POLLS { + schedule.now += FENCE_WAIT_SLEEP; + } + if polls == FENCE_WAIT_YIELD_POLLS + 8 && schedule.oldest.as_raw() == fence.as_raw() { + schedule.later_value.store(1, Ordering::Release); + } + } }); - let list_ptr = &*fake as *const FakeTwoPassList as *mut c_void; + FENCES_TO_SIGNAL_ON_WAIT.with_borrow_mut(|signals| { + if let Some(index) = signals.iter().position(|(test, _)| test.as_raw() == fence.as_raw()) { + let (_, value) = signals.swap_remove(index); + value.store(1, Ordering::Release); + } + }); + } - // Register a finished two-pass GS/MS PSO behind an async stand-in (registered in TWO_PASS, - // not TRANSLATED_GRAPHICS). - let standin_tp = 0x7250_0001usize; - let pso_vtable = [0usize, resolution_add_ref as usize, resolution_release as usize]; - let mut real_tp_pso = ResolutionPso { vtable: pso_vtable.as_ptr(), refs: AtomicUsize::new(1) }; - let real_tp = &mut real_tp_pso as *mut ResolutionPso as usize; - pso_async::submit( - standin_tp, - false, - Box::new(move || { - real::register_two_pass_for_test(real_tp, "GS"); - real_tp - }), - ); - assert_eq!(pso_async::resolve_wait(standin_tp), real_tp); - assert!(real::two_pass_of(real_tp).is_some()); - assert!(!real::is_translated_graphics(real_tp)); + #[test] + fn budget_two_pass_cap_scales_with_headroom_and_stays_bounded() { + let mib = 1u64 << 20; + assert_eq!(budget_two_pass_cap(0, 0), 1024 * mib); + assert_eq!(budget_two_pass_cap(0, 800 * mib), 200 * mib); + assert_eq!(budget_two_pass_cap(2500 * mib, 3500 * mib), 256 * mib); + assert_eq!(budget_two_pass_cap(4000 * mib, 7200 * mib), 800 * mib); + assert_eq!(budget_two_pass_cap(10_800 * mib, 11_200 * mib), 350 * mib); + assert_eq!(budget_two_pass_cap(15_000 * mib, 16_384 * mib), 512 * mib); + assert_eq!(budget_two_pass_cap(15_000 * mib, 31_419 * mib), 2048 * mib); + assert_eq!(budget_two_pass_cap(28_000 * mib, 31_419 * mib), (3419 * mib) / 4); + assert_eq!(budget_two_pass_cap(30_000 * mib, 31_419 * mib), 512 * mib); + } - reset(list_ptr, 0x7250_0100, standin_tp); - unsafe { - // Seed a non-null title graphics RS so a fallthrough would visibly call SetGraphicsRootSignature. - set_graphics_root_signature(list_ptr, list_ptr); - } + #[test] + fn wait_oldest_fenced_reclaims_in_flight_buffer_before_refusing() { + let _warp_guard = lock_warp_tests(); + WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let ids = Box::new([0u8; 4]); + let list = ids.as_ptr() as *mut c_void; + let (alloc1, alloc2, q1) = (ids.as_ptr() as usize + 1, ids.as_ptr() as usize + 2, (ids.as_ptr() as usize + 3) as *mut c_void); + let size = 64 << 20; + reset(list, alloc1, 0); + let rec = unsafe { TwoPassBuf::make(&dev, size, "record buffer") }.unwrap(); + let rec_raw = rec.res.as_raw() as usize; + with(list, |s| s.res_buf = Some(rec)); + track_two_pass_list(list as usize); + let (fence, val) = make_test_fence(0); + unsafe { two_pass_submitted(q1, Some(&fence), 1, &[list]) }; + reset(list, alloc2, 0); - // 1. Direct draw (`graphics_bound`) must return None without binding the title's RS. - let before = counts_snapshot(); - let bound = unsafe { graphics_bound(list_ptr) }; - let after = counts_snapshot(); - assert!(bound.is_none(), "two-pass MS/GS PSO must not fall through to PC DrawInstanced"); - assert!(after[DRAWS_SKIPPED] > before[DRAWS_SKIPPED]); - assert_eq!(after[DRAWS_PC], before[DRAWS_PC]); - assert_eq!(fake.set_graphics_rs_calls.load(Ordering::Relaxed), 0); + let waited_before = TWO_PASS[TP_WAITED].load(Ordering::Relaxed); + let tight_cap = TWO_PASS[TP_ALIVE].load(Ordering::Relaxed) + (8 << 20); + FENCES_TO_SIGNAL_ON_WAIT.with_borrow_mut(|signals| signals.push((fence, val))); + let got = unsafe { + acquire_two_pass_buf_with_cap(&dev, size, size.saturating_mul(2), u64::MAX, "record buffer", tight_cap, std::time::Duration::from_millis(250)) + }; + let missed = FENCES_TO_SIGNAL_ON_WAIT.with_borrow_mut(std::mem::take); + for (_, value) in &missed { + value.store(1, Ordering::Release); + } + let got = got.unwrap(); + let got_raw = got.as_ref().map(|b| b.res.as_raw() as usize); + drop(got); + reclaim_fenced(); + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + forget(list); + WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); + assert!(missed.is_empty(), "the acquisition must wait for the pending fence"); + assert_eq!(got_raw, Some(rec_raw)); + assert!(TWO_PASS[TP_WAITED].load(Ordering::Relaxed) > waited_before); + } - // 2. Unmatched `ExecuteIndirect` must skip without binding the title's RS or calling PC ExecuteIndirect. - let before = counts_snapshot(); - unsafe { - execute_indirect(list_ptr, 0x7250_00F0, 1, 0, 0, 0, 0); + #[test] + fn wait_oldest_fenced_advances_past_small_batch_to_reclaim_large_batch() { + let _warp_guard = lock_warp_tests(); + WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let ids = Box::new([0u8; 6]); + let (l1, l2) = (ids.as_ptr() as *mut c_void, (ids.as_ptr() as usize + 1) as *mut c_void); + let (a1, a2, a3, q1) = ( + ids.as_ptr() as usize + 2, + ids.as_ptr() as usize + 3, + ids.as_ptr() as usize + 4, + (ids.as_ptr() as usize + 5) as *mut c_void, + ); + let small = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "small buffer") }.unwrap(); + let large_size = 64 << 20; + let large = unsafe { TwoPassBuf::make(&dev, large_size, "large buffer") }.unwrap(); + let large_raw = large.res.as_raw() as usize; + + reset(l1, a1, 0); + with(l1, |s| s.res_buf = Some(small)); + track_two_pass_list(l1 as usize); + let (f1, v1) = make_test_fence(0); + unsafe { two_pass_submitted(q1, Some(&f1), 1, &[l1]) }; + reset(l1, a3, 0); + + reset(l2, a2, 0); + with(l2, |s| s.res_buf = Some(large)); + track_two_pass_list(l2 as usize); + let (f2, v2) = make_test_fence(0); + unsafe { two_pass_submitted(q1, Some(&f2), 1, &[l2]) }; + reset(l2, a3, 0); + + let tight_cap = TWO_PASS[TP_ALIVE].load(Ordering::Relaxed) + (8 << 20); + FENCES_TO_SIGNAL_ON_WAIT.with_borrow_mut(|signals| signals.extend([(f1, v1), (f2, v2)])); + let got = unsafe { + acquire_two_pass_buf_with_cap(&dev, large_size, large_size.saturating_mul(2), u64::MAX, "record buffer", tight_cap, std::time::Duration::from_millis(250)) + }; + let missed = FENCES_TO_SIGNAL_ON_WAIT.with_borrow_mut(std::mem::take); + for (_, value) in &missed { + value.store(1, Ordering::Release); } - let after = counts_snapshot(); - assert!(after[DRAWS_SKIPPED] > before[DRAWS_SKIPPED]); - assert_eq!(fake.set_graphics_rs_calls.load(Ordering::Relaxed), 0); - assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0); + let got = got.unwrap(); + let got_raw = got.as_ref().map(|b| b.res.as_raw() as usize); + drop(got); + reclaim_fenced(); + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + forget(l1); + forget(l2); + WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); + assert!(missed.is_empty(), "the acquisition must wait for both pending fences"); + assert_eq!(got_raw, Some(large_raw)); + } - forget(list_ptr); - list_x::clear_segment_state(list_ptr as usize); - let real_tp_owner = pso_async::released(standin_tp); - real::forget_pso_for_test(real_tp); - assert_eq!(real_tp_owner, real_tp); - assert_eq!(unsafe { resolution_release(real_tp_owner as *mut c_void) }, 0); - assert!(real::two_pass_of(real_tp).is_none()); + #[test] + fn later_queue_completion_during_sleep_reclaims_before_wait_deadline() { + let _warp_guard = lock_warp_tests(); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let (oldest_fence, oldest_value) = make_test_fence(0); + let (later_fence, later_value) = make_test_fence(0); + let oldest = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "oldest queue") }.unwrap(); + let size = 64 << 20; + let later = unsafe { TwoPassBuf::make(&dev, size, "later queue") }.unwrap(); + let later_raw = later.res.as_raw() as usize; + retire_recording_res(0, vec![oldest], vec![(1, oldest_fence.clone(), 1)], false); + retire_recording_res(0, vec![later], vec![(2, later_fence, 1)], false); + + let start = std::time::Instant::now(); + let deadline = start + FENCE_WAIT_LIMIT; + LATER_FENCE_COMPLETION.with_borrow_mut(|schedule| { + *schedule = Some(LaterFenceCompletion { oldest: oldest_fence, later_value: later_value.clone(), now: start }); + }); + let result = wait_oldest_fenced_until(deadline); + let finished_at = LATER_FENCE_COMPLETION.with_borrow_mut(Option::take).unwrap().now; + let got = FREE_RES.lock().unwrap().take(key, size, size); + let got_raw = got.as_ref().map(|buf| buf.res.as_raw() as usize); + let oldest_still_pending = oldest_value.load(Ordering::Acquire) == 0; + + oldest_value.store(1, Ordering::Release); + later_value.store(1, Ordering::Release); + drop(got); + reclaim_fenced(); + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); + + assert_eq!(result, WaitStep::Progressed); + assert_eq!(got_raw, Some(later_raw)); + assert!(oldest_still_pending); + assert!(finished_at < deadline, "later queue completion was only reclaimed at the wait deadline"); } #[test] - fn create_list_reset_and_clear_state_track_initial_pso_on_d3d12() { - use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; - use windows::Win32::Graphics::Dxgi::*; + fn acquire_res_buf_shrinks_under_tight_cap_instead_of_skipping() { + let _warp_guard = lock_warp_tests(); + WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let tight_cap = TWO_PASS[TP_ALIVE].load(Ordering::Relaxed) + (48 << 20); + let shrunk_before = TWO_PASS[TP_SHRUNK].load(Ordering::Relaxed); + let buf = unsafe { acquire_res_buf_with_cap(&dev, 96 << 20, 47_632, 0, tight_cap, std::time::Duration::ZERO) }.unwrap().unwrap(); + let got_bytes = buf.bytes; + drop(buf); + assert!(got_bytes < (96 << 20) && got_bytes >= RECORD_MIN, "expected shrunk size, got {got_bytes}"); + assert!(TWO_PASS[TP_SHRUNK].load(Ordering::Relaxed) > shrunk_before); + } - if console_list::enabled() { - return; - } - unsafe { - let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); - let mut dev: Option = None; - if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { - let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); - D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); - } - let dev = dev.expect("D3D12 device"); - real::adopt(dev.as_raw(), real::Kind::Device); + #[test] + fn acquire_res_buf_uses_finer_bucket_when_it_fits_the_cap() { + let _warp_guard = lock_warp_tests(); + WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let tight_cap = TWO_PASS[TP_ALIVE].load(Ordering::Relaxed) + (48 << 20); + let buf = unsafe { acquire_res_buf_with_cap(&dev, 64 << 20, 64 << 10, 0, tight_cap, std::time::Duration::ZERO) }.unwrap().unwrap(); + assert_eq!(buf.bytes, 48 << 20, "the next smaller half-step bucket fits available headroom"); + assert_eq!(record_groups(buf.bytes, 64 << 10, 1), 768); + drop(buf); + + let tight_cap = TWO_PASS[TP_ALIVE].load(Ordering::Relaxed) + (32 << 20); + let buf = unsafe { acquire_res_buf_with_cap(&dev, 48 << 20, 64 << 10, 0, tight_cap, std::time::Duration::ZERO) }.unwrap().unwrap(); + assert_eq!(buf.bytes, 32 << 20, "the bucket below 48 MiB also fits"); + drop(buf); + } - // Build two real PC compute PSOs from the inbox dummy CS bytecode. - let mut ser = None; - D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).expect("serialize RS"); - let ser = ser.unwrap(); - let rs: ID3D12RootSignature = dev - .CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())) - .expect("CreateRootSignature"); - let cs = real::dummy_cs_bytecode(); - let make_pso = || -> ID3D12PipelineState { - let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), - CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }, - ..Default::default() - }; - let pso = dev.CreateComputePipelineState(&desc).expect("CreateComputePipelineState"); - std::mem::ManuallyDrop::drop(&mut desc.pRootSignature); - pso - }; - let pso1 = make_pso(); - let pso2 = make_pso(); - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + #[test] + fn acquire_res_buf_stops_shrinking_at_existing_buffer_size() { + let _warp_guard = lock_warp_tests(); + WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let tight_cap = TWO_PASS[TP_ALIVE].load(Ordering::Relaxed) + (8 << 20); + let refused_before = TWO_PASS[TP_REFUSED].load(Ordering::Relaxed); + let res = unsafe { acquire_res_buf_with_cap(&dev, 64 << 20, 47_632, 16 << 20, tight_cap, std::time::Duration::ZERO) }.unwrap(); + assert!(res.is_none()); + assert_eq!(TWO_PASS[TP_REFUSED].load(Ordering::Relaxed), refused_before); + } - // Stand-in synthetic key backed by real `pso1` in pso_async: CreateCommandList must - // resolve it via resolve_for_bind for PC D3D12 while tracking `standin` in `bind`. - let standin = 0x7300_0001usize; - let pso1_raw = pso1.as_raw() as usize; - pso_async::submit(standin, true, Box::new(move || pso1_raw)); - assert_eq!(pso_async::resolve_wait(standin), pso1_raw); + #[test] + fn wait_oldest_fenced_exits_immediately_on_device_removal_without_reclaiming() { + let _warp_guard = lock_warp_tests(); + WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let ids = Box::new([0u8; 6]); + let (l1, l2) = (ids.as_ptr() as *mut c_void, (ids.as_ptr() as usize + 1) as *mut c_void); + let (a1, a2, a3, q1) = ( + ids.as_ptr() as usize + 2, + ids.as_ptr() as usize + 3, + ids.as_ptr() as usize + 4, + (ids.as_ptr() as usize + 5) as *mut c_void, + ); - let mut raw_list: *mut c_void = std::ptr::null_mut(); - let iid = windows_sys::core::GUID::from_u128(0x5b160d0f_ac1b_4185_8ba8_b3ae42a5a455); - let hr = device_x::create_command_list_pc( - dev.as_raw(), - 0, - D3D12_COMMAND_LIST_TYPE_DIRECT.0 as u32, - alloc.as_raw() as usize, - standin, - &iid, - &mut raw_list, - ); - assert!(hr >= 0 && !raw_list.is_null(), "create_command_list_pc failed: {hr:#x}"); - let backing = title_list::backing(raw_list).expect("wrapped in title_list"); - assert_eq!(tracked_pso(backing), standin, "CreateCommandList must seed bind::State.pso"); + reset(l1, a1, 0); + let rem = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "removed buffer") }.unwrap(); + let rem_raw = rem.res.as_raw() as usize; + with(l1, |s| s.res_buf = Some(rem)); + track_two_pass_list(l1 as usize); + let (f_rem, _) = make_test_fence(u64::MAX); + unsafe { two_pass_submitted(q1, Some(&f_rem), 1, &[l1]) }; + reset(l1, a3, 0); + + let timeouts_before = TWO_PASS[TP_WAIT_TIMEOUTS].load(Ordering::Relaxed); + let t0 = std::time::Instant::now(); + let step1 = wait_oldest_fenced_until(t0 + std::time::Duration::from_millis(200)); + assert_eq!(step1, WaitStep::Stopped); + assert!(t0.elapsed() < std::time::Duration::from_millis(50), "device removal must exit immediately without spinning"); + assert_eq!(TWO_PASS[TP_WAIT_TIMEOUTS].load(Ordering::Relaxed), timeouts_before); + assert_eq!(WAIT_BACKOFF_UNTIL_MS.load(Ordering::Acquire), 0); + assert!(take_free(key, RECORD_MIN, u64::MAX).is_none()); + + // Leading removed batch must not starve a healthy batch queued behind it. + reset(l2, a2, 0); + let healthy = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "healthy buffer") }.unwrap(); + let healthy_raw = healthy.res.as_raw() as usize; + with(l2, |s| s.res_buf = Some(healthy)); + track_two_pass_list(l2 as usize); + let (f_ok, v_ok) = make_test_fence(0); + unsafe { two_pass_submitted(q1, Some(&f_ok), 1, &[l2]) }; + reset(l2, a3, 0); + + FENCES_TO_SIGNAL_ON_WAIT.with_borrow_mut(|signals| signals.push((f_ok, v_ok.clone()))); + let step2 = wait_oldest_fenced_until(std::time::Instant::now() + std::time::Duration::from_millis(200)); + let missed = FENCES_TO_SIGNAL_ON_WAIT.with_borrow_mut(std::mem::take); + v_ok.store(1, Ordering::Release); + let got = take_free(key, RECORD_MIN, u64::MAX).map(|b| b.res.as_raw() as usize); + + // Drain the synthetic removed batch left in FENCED_RES so later tests start clean. + { + let mut fenced = FENCED_RES.lock().unwrap(); + let mut removed_bytes = 0u64; + fenced.retain(|batch| { + if batch.bufs.iter().any(|b| b.res.as_raw() as usize == rem_raw) { + removed_bytes += batch.bytes; + false + } else { + true + } + }); + FENCED_BYTES.fetch_sub(removed_bytes, Ordering::Release); + } + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + forget(l1); + forget(l2); + WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); + assert_eq!(step2, WaitStep::Progressed); + assert!(missed.is_empty()); + assert_eq!(got, Some(healthy_raw)); + } - // ClearState(pso2) updates bind::State.pso to pso2 and clears root args. - let rs_key = 0x7300_0010usize; - console_list::note_root_signature(rs_key, &test_rts0_blob()); - set_compute_root_signature(backing, rs_key as *mut c_void); - set_compute_root_constant(backing, 0, 0xABCD, 0); - let cl = ID3D12GraphicsCommandList::from_raw_borrowed(&backing).unwrap(); - cl.ClearState(&pso2); - assert_eq!(tracked_pso(backing), pso2.as_raw() as usize, "ClearState must update bind::State.pso"); - with(backing, |s| assert!(s.layout.is_none() && s.args.is_empty())); + #[test] + fn fence_wait_timeout_backs_off_subsequent_waits_until_reclaim() { + let _warp_guard = lock_warp_tests(); + WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let ids = Box::new([0u8; 4]); + let list = ids.as_ptr() as *mut c_void; + let (alloc1, alloc2, q1) = (ids.as_ptr() as usize + 1, ids.as_ptr() as usize + 2, (ids.as_ptr() as usize + 3) as *mut c_void); + let size = 64 << 20; + reset(list, alloc1, 0); + let rec = unsafe { TwoPassBuf::make(&dev, size, "timeout buffer") }.unwrap(); + let rec_raw = rec.res.as_raw() as usize; + with(list, |s| s.res_buf = Some(rec)); + track_two_pass_list(list as usize); + let (fence, val) = make_test_fence(0); + unsafe { two_pass_submitted(q1, Some(&fence), 1, &[list]) }; + reset(list, alloc2, 0); - // ClearState(None) clears bind::State.pso to 0. - cl.ClearState(None); - assert_eq!(tracked_pso(backing), 0, "ClearState(None) must clear bind::State.pso"); + let tight_cap = TWO_PASS[TP_ALIVE].load(Ordering::Relaxed) + (8 << 20); + let timeouts_before = TWO_PASS[TP_WAIT_TIMEOUTS].load(Ordering::Relaxed); + let res1 = unsafe { + acquire_two_pass_buf_with_cap(&dev, size, size.saturating_mul(2), u64::MAX, "record buffer", tight_cap, std::time::Duration::from_millis(5)) + }.unwrap(); + assert!(res1.is_none()); + assert_eq!(TWO_PASS[TP_WAIT_TIMEOUTS].load(Ordering::Relaxed), timeouts_before + 1); + assert_eq!(active_wait_limit(std::time::Duration::from_millis(200)), std::time::Duration::ZERO); + + // During backoff, a 200 ms wait returns immediately without sleeping or incrementing timeouts. + let t1 = std::time::Instant::now(); + let res2 = unsafe { + acquire_two_pass_buf_with_cap(&dev, size, size.saturating_mul(2), u64::MAX, "record buffer", tight_cap, std::time::Duration::from_millis(200)) + }.unwrap(); + assert!(res2.is_none()); + assert!(t1.elapsed() < std::time::Duration::from_millis(50)); + assert_eq!(TWO_PASS[TP_WAIT_TIMEOUTS].load(Ordering::Relaxed), timeouts_before + 1); + + // Once the GPU fence completes and reclaim_fenced runs, wait backoff clears immediately. + val.store(1, Ordering::Release); + assert!(reclaim_fenced() >= size); + assert_eq!(active_wait_limit(FENCE_WAIT_LIMIT), FENCE_WAIT_LIMIT); + let taken = take_free(key, size, u64::MAX).map(|b| b.res.as_raw() as usize); + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + forget(list); + WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); + assert_eq!(taken, Some(rec_raw)); + } - // Close + reset_x(alloc, pso2) updates bind::State.pso to pso2 and clears root args. - set_graphics_root_signature(backing, rs_key as *mut c_void); - set_graphics_root_constant(backing, 0, 0x1111, 0); - cl.Close().expect("Close"); - let hr = list_x::reset_x(backing, alloc.as_raw() as usize, pso2.as_raw() as usize); - assert!(hr >= 0, "reset_x failed: {hr:#x}"); - assert_eq!(tracked_pso(backing), pso2.as_raw() as usize, "Reset must update bind::State.pso"); - with(backing, |s| assert!(s.layout_gfx.is_none() && s.args_gfx.is_empty())); + #[test] + fn put_free_bufs_retains_buffers_up_to_cap_without_halving_churn() { + let _warp_guard = lock_warp_tests(); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + let buf = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "pool cap test") }.unwrap(); + let expected_cap = two_pass_cap().min(FREE_RES_CAP); + put_free_bufs(vec![buf]); + let pool_cap = FREE_RES.lock().unwrap().cap; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + assert_eq!(pool_cap, expected_cap); + } - // Release the wrapped title list cleanly (calls bind::forget + list_x::on_release). - let release_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(raw_list as *const *const usize)).add(2)); - assert_eq!(release_fn(raw_list), 0); - let _ = pso_async::released(standin); + #[test] + fn records_for_falls_back_to_whole_before_shrinking_halves() { + #[repr(C)] + struct FakeList { + vt: *const usize, + dev: ID3D12Device, + } + unsafe extern "system" fn fake_get_device(this: *mut c_void, _iid: *const c_void, out: *mut *mut c_void) -> i32 { + let f = &*(this as *const FakeList); + *out = f.dev.clone().into_raw(); + 0 + } + let _warp_guard = lock_warp_tests(); + WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); + let Some(dev) = warp_device_for_test() else { return }; + let key = dev.as_raw() as usize; + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + unsafe { + let mut orig_vt = [0usize; 16]; + orig_vt[7] = fake_get_device as *const () as usize; + let mut ext_vt = vec![0usize; 17]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let fake = FakeList { vt: ext_vt.as_ptr().add(1), dev }; + let list = &fake as *const FakeList as *mut c_void; + let alloc_id = list as usize + 1; + reset(list, alloc_id, 0); + + let need = 32 << 20; + let tight_cap = TWO_PASS[TP_ALIVE].load(Ordering::Relaxed) + need; + let refused_before = TWO_PASS[TP_REFUSED].load(Ordering::Relaxed); + let shrunk_before = TWO_PASS[TP_SHRUNK].load(Ordering::Relaxed); + + let (buf, _va, region_cap, layout) = records_for_with_cap(list, need, 47_632, true, tight_cap).unwrap(); + drop(buf); + reset(list, 0, 0); + forget(list); + release_allocator_res(alloc_id); + while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} + WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); + + assert_eq!(layout, Records::Whole); + assert_eq!(region_cap, need); + assert_eq!(TWO_PASS[TP_REFUSED].load(Ordering::Relaxed), refused_before); + assert_eq!(TWO_PASS[TP_SHRUNK].load(Ordering::Relaxed), shrunk_before); } } } diff --git a/crates/xcl/src/hle/d3d12x/bvh_want.rs b/crates/xcl/src/hle/d3d12x/bvh_want.rs new file mode 100644 index 0000000000..0ffdcdc023 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/bvh_want.rs @@ -0,0 +1,324 @@ +//! What a ray traversal of the title's acceleration structures reads, asked of the GPU views. +//! +//! The title's shaders walk a top level from its root, jump through each instance node into a +//! bottom level by address and read parent pointers on the way back (`bvh`); only the view of +//! the top level is ever made. So the structures are walked on the CPU side of the views +//! (`bvh::walk_scene`) and every tile reached is asked for (`view_want::want`): when the view is +//! made, and again – once a frame at most – after the CPU wrote a tile a walk read. + +use super::view_want::{self, Path}; +use crate::gpu::bvh; +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{LazyLock, Mutex}; + +/// top levels kept (the one walked least lately goes) +const TOPS: usize = 64; +/// bottom levels kept: past it all are forgotten (walked again with the next top level) +const BOTTOMS: usize = 1 << 16; +/// top levels walked again a frame +const A_FRAME: usize = 2; +const TILE: u64 = bvh::WALK_TILE; + +struct Top { + va: u64, + /// tiles of its own walk, and the CPU tiles they show + tiles: Vec<(u64, u64)>, + cpu: Vec, + referenced: Vec, + stale: bool, + walking: bool, + /// the frame of its last walk, and `view_want::generation` then + frame: u64, + gen: (u64, u64), +} + +struct Bottom { + tiles: Vec<(u64, u64)>, + cpu: Vec, + nodes: u64, + stale: bool, +} + +#[derive(Default)] +struct Reg { + tops: Vec, + bottoms: HashMap, + /// CPU tile (index) → the structures walked there (top level: address, bottom level: | 1) + watch: HashMap>, + frame: u64, + bottoms_stale: bool, + /// writes found where a walk read (`mark_written`), so far + writes: u64, +} + +static REG: LazyLock> = LazyLock::new(Default::default); +/// whether `Reg::watch` has a tile +static WATCHING: AtomicBool = AtomicBool::new(false); + +fn with(f: impl FnOnce(&mut Reg) -> R) -> R { + f(&mut REG.lock().unwrap_or_else(|e| e.into_inner())) +} + +/// `XCL_BVH_WALK=0`: no walk, only the 64 KiB at a structure's address (as before) +fn on() -> bool { + static ON: LazyLock = LazyLock::new(|| { + let on = std::env::var("XCL_BVH_WALK").map_or(true, |v| v.trim() != "0"); + if !on { + crate::xlog_info!("D3D12.X: XCL_BVH_WALK=0: acceleration structures are asked for 64 KiB from their address only"); + } + on + }); + *ON && super::bind::view_span().1 != 0 +} + +/// The title's bytes behind GPU address `va` (its CPU view), false when any cannot be read (a +/// page not committed, or decommitted while read: the kernel's copy fails, nothing faults). +fn read_title(va: u64, out: &mut [u8]) -> bool { + let Some(c) = view_want::cpu_run(va, out.len() as u64) else { return false }; + unsafe { crate::hle::dstorage::read_own(c as usize, out.as_mut_ptr(), out.len()) } +} + +fn ask(tiles: &[(u64, u64)]) { + for &(at, len) in tiles { + view_want::want(Path::Bvh, at, len); + } +} + +/// The CPU tiles (indices) the GPU tiles a walk of the structure at `base` reached show (its +/// header's when it reached none: a write there makes it worth another walk) +fn cpu_tiles(base: u64, tiles: &[(u64, u64)]) -> Vec { + let header = [(base & !(TILE - 1), TILE)]; + let tiles = if tiles.is_empty() { &header[..] } else { tiles }; + let mut out: Vec = tiles + .iter() + .flat_map(|&(at, len)| (0..len / TILE).map(move |k| at + k * TILE)) + .flat_map(|t| { + let c = view_want::cpu(t); + [c / TILE, (c + TILE - 1) / TILE] + }) + .collect(); + out.sort_unstable(); + out.dedup(); + out +} + +fn watch(w: &mut HashMap>, cpu: &[u64], key: u64, on: bool) { + for t in cpu { + let keys = w.entry(*t).or_default(); + keys.retain(|&k| k != key); + if on { + keys.push(key); + } else if keys.is_empty() { + w.remove(t); + } + } +} + +/// An acceleration-structure view of the top level at `va` was made: what rays can read of it +/// and of its bottom levels is asked for; walked again only when the CPU wrote there since. +pub fn view_made(va: u64) { + if !on() { + return; + } + let gen = view_want::generation(); + let known = with(|r| { + let frame = r.frame; + let t = r.tops.iter_mut().find(|t| t.va == va)?; + if t.walking || (t.stale && t.frame == frame) { + return Some(Vec::new()); + } + if t.stale { + return None; + } + // asked for again only when asks were forgotten since + if t.gen == gen { + return Some(Vec::new()); + } + t.gen = gen; + let mut tiles = t.tiles.clone(); + let Reg { tops, bottoms, .. } = r; + let t = tops.iter().find(|t| t.va == va)?; + tiles.extend(t.referenced.iter().filter_map(|a| bottoms.get(a)).flat_map(|b| b.tiles.iter().copied())); + Some(tiles) + }); + match known { + Some(tiles) => ask(&tiles), + None => walk(va), + } +} + +/// Once a frame: the top levels the CPU wrote (or whose bottom levels it wrote) since their +/// walk are walked again, `A_FRAME` at most, the least lately walked first. +pub fn frame() { + if !on() { + return; + } + for va in with(due) { + walk(va); + } +} + +/// `frame` with the registry locked: the top levels to walk again +fn due(r: &mut Reg) -> Vec { + r.frame += 1; + if std::mem::take(&mut r.bottoms_stale) { + let Reg { tops, bottoms, .. } = r; + for t in tops.iter_mut() { + t.stale |= t.referenced.iter().any(|a| bottoms.get(a).is_some_and(|b| b.stale)); + } + } + let mut due: Vec<(u64, u64)> = r.tops.iter().filter(|t| t.stale && !t.walking).map(|t| (t.frame, t.va)).collect(); + due.sort_unstable(); + due.into_iter().take(A_FRAME).map(|d| d.1).collect() +} + +/// Before a submit, the CPU pages written (`page` bytes each): the structures walked there are +/// walked again (`frame`). +pub fn written(dirty: &[usize], page: usize) { + if !WATCHING.load(Ordering::Relaxed) || dirty.is_empty() { + return; + } + with(|r| mark_written(r, dirty, page as u64)); +} + +fn mark_written(r: &mut Reg, dirty: &[usize], page: u64) { + let mut keys = Vec::new(); + let mut last = u64::MAX; + for &a in dirty { + for t in a as u64 / TILE..=(a as u64 + page.max(1) - 1) / TILE { + if t != last { + last = t; + keys.extend(r.watch.get(&t).into_iter().flatten().copied()); + } + } + } + keys.sort_unstable(); + keys.dedup(); + r.writes += !keys.is_empty() as u64; + for k in keys { + if k & 1 != 0 { + if let Some(b) = r.bottoms.get_mut(&(k & !1)) { + b.stale = true; + r.bottoms_stale = true; + } + } else if let Some(t) = r.tops.iter_mut().find(|t| t.va == k) { + t.stale = true; + } + } +} + +fn walk(va: u64) { + let frame = with(|r| { + if r.tops.iter().any(|t| t.va == va && t.walking) { + return None; + } + if !r.tops.iter().any(|t| t.va == va) { + if r.tops.len() >= TOPS { + if let Some(i) = (0..r.tops.len()).filter(|&i| !r.tops[i].walking).min_by_key(|&i| r.tops[i].frame) { + let t = r.tops.swap_remove(i); + watch(&mut r.watch, &t.cpu, t.va, false); + } + } + r.tops.push(Top { va, tiles: Vec::new(), cpu: Vec::new(), referenced: Vec::new(), stale: true, walking: false, frame: 0, gen: (0, 0) }); + } + r.tops.iter_mut().find(|t| t.va == va)?.walking = true; + Some((r.frame, r.writes)) + }); + let Some((frame, writes)) = frame else { return }; + let t0 = std::time::Instant::now(); + let s = bvh::walk_scene(&mut read_title, va, &bvh::Limits::default(), &mut |b| with(|r| r.bottoms.get(&b).is_none_or(|x| x.stale))); + let us = t0.elapsed().as_micros(); + let gen = view_want::generation(); + let mut tiles: Vec<(u64, u64)> = s.top.tiles.iter().chain(s.bottoms.iter().flat_map(|b| &b.tiles)).copied().collect(); + let top_cpu = cpu_tiles(va, &s.top.tiles); + let bottoms_cpu: Vec> = s.bottoms.iter().map(|b| cpu_tiles(b.base, &b.tiles)).collect(); + let (nodes, bottom_bytes) = with(|r| { + if r.bottoms.len() + s.bottoms.len() > BOTTOMS { + r.bottoms.clear(); + r.watch.retain(|_, keys| { + keys.retain(|k| k & 1 == 0); + !keys.is_empty() + }); + } + // (a write the walk may have missed: all of it again next frame) + let missed = r.writes != writes; + for (b, cpu) in s.bottoms.iter().zip(bottoms_cpu) { + if let Some(old) = r.bottoms.remove(&b.base) { + watch(&mut r.watch, &old.cpu, b.base | 1, false); + } + watch(&mut r.watch, &cpu, b.base | 1, true); + // (one with no node yet is walked again with its top level) + r.bottoms.insert(b.base, Bottom { tiles: b.tiles.clone(), cpu, nodes: b.nodes, stale: b.nodes == 0 || missed }); + } + let Reg { tops, bottoms, watch: w, .. } = r; + let Some(t) = tops.iter_mut().find(|t| t.va == va) else { return (0, 0) }; + watch(w, &t.cpu, va, false); + watch(w, &top_cpu, va, true); + let known: Vec<&Bottom> = s.referenced.iter().filter_map(|a| bottoms.get(a)).collect(); + // (the bottom levels known already: their tiles again once asks were forgotten since) + if t.gen != gen { + let walked: std::collections::HashSet = s.bottoms.iter().map(|b| b.base).collect(); + tiles.extend(s.referenced.iter().filter(|a| !walked.contains(a)).filter_map(|a| bottoms.get(a)).flat_map(|b| b.tiles.iter().copied())); + } + // a top level with no node yet (not written, or written by the GPU only) is walked again + *t = Top { va, tiles: s.top.tiles.clone(), cpu: top_cpu, referenced: s.referenced.clone(), stale: s.top.nodes == 0 || missed, walking: false, frame, gen }; + WATCHING.store(!w.is_empty(), Ordering::Relaxed); + (s.top.nodes + known.iter().map(|b| b.nodes).sum::(), known.iter().flat_map(|b| &b.tiles).map(|x| x.1).sum::()) + }); + ask(&tiles); + static WALKS: AtomicU64 = AtomicU64::new(0); + let n = WALKS.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + let top_kib = s.top.tiles.iter().map(|x| x.1).sum::() >> 10; + let cut = s.cut.map_or(String::new(), |c| format!(", truncated: {c}")); + let parents = if s.top.nodes != 0 && s.top.parents.is_none() { ", no parent array" } else { "" }; + crate::xlog_info!( + "D3D12.X: acceleration structure at {va:#x}: {nodes} nodes, {top_kib} KiB of top level, {} bottom levels ({} KiB) asked for; walk {us} µs{cut}{parents} (walk {n})", + s.referenced.len(), + bottom_bytes >> 10 + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn top(va: u64, cpu: Vec, referenced: Vec, frame: u64) -> Top { + Top { va, tiles: Vec::new(), cpu, referenced, stale: false, walking: false, frame, gen: (0, 0) } + } + + /// A CPU write in a tile a walk read makes that structure stale – a bottom level's makes the + /// top levels reaching it walked again – and a write elsewhere does nothing; a frame walks + /// `A_FRAME` of them at most, the least lately walked first. + #[test] + fn a_write_where_a_walk_read_walks_it_again_once_a_frame() { + const T: u64 = 0x10_0000; + const B: u64 = 0x20_0000; + let mut r = Reg::default(); + for (k, f) in [(0u64, 5u64), (1, 3), (2, 4)] { + r.tops.push(top(T + k * 0x100, vec![T / TILE + k], vec![B], f)); + watch(&mut r.watch, &[T / TILE + k], T + k * 0x100, true); + } + r.bottoms.insert(B, Bottom { tiles: Vec::new(), cpu: vec![B / TILE, B / TILE + 1], nodes: 9, stale: false }); + watch(&mut r.watch, &[B / TILE, B / TILE + 1], B | 1, true); + mark_written(&mut r, &[(T + 3 * TILE) as usize, (B + 5 * TILE) as usize], 0x1000); + assert!(r.tops.iter().all(|t| !t.stale) && !r.bottoms[&B].stale, "written elsewhere"); + assert!(due(&mut r).is_empty()); + mark_written(&mut r, &[(T + TILE + 0x3000) as usize], 0x1000); + assert!(r.tops[1].stale && !r.tops[0].stale && !r.tops[2].stale); + assert_eq!(due(&mut r), [T + 0x100]); + r.tops[1].stale = false; + // a page reaching into the bottom level's second tile + mark_written(&mut r, &[(B + TILE - 0x1000) as usize], 0x2000); + assert!(r.bottoms[&B].stale); + assert_eq!(due(&mut r), [T + 0x100, T + 0x200], "all three reach it: two a frame, least lately walked first"); + // a structure walked again where it is no more + watch(&mut r.watch, &[T / TILE], T, false); + r.tops[0].stale = false; + mark_written(&mut r, &[T as usize], 0x1000); + assert!(!r.tops[0].stale); + assert!(!r.watch.contains_key(&(T / TILE))); + } +} diff --git a/crates/xcl/src/hle/d3d12x/capture.rs b/crates/xcl/src/hle/d3d12x/capture.rs new file mode 100644 index 0000000000..47a09928cb --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/capture.rs @@ -0,0 +1,1797 @@ +//! `XCL_CAPTURE_FRAME=[,]`: one frame's command stream, written to disk, so a +//! rendering fault can be studied without running the title again for every question. +//! +//! The frame is the first with at least `work` draws and dispatches, not before `after_s` seconds +//! after the first present, and not the first frame recorded (its lists began before the +//! recording did). It goes to `/capture_/`: +//! - `frame.jsonl`: one object per operation in the order the GPU got them – the submits in their +//! order, each list's operations in the order the title recorded them – with `i` (its place) +//! and, for a draw or dispatch, `n` (its number among them), the render targets bound, the root +//! arguments (only the ones changed since the list's last draw or dispatch where that is +//! smaller: `"delta": true`) and how it went; +//! - `resources.jsonl`, `pipelines.jsonl`: what the operations name; +//! - `shaders/`: each referenced pipeline's console shaders translated again and disassembled; +//! - `summary.txt`: counts by kind, pass and pipeline, and what looks wrong. +//! +//! What is recorded is what the title called (on its lists: `title_list`), as it called it; a +//! barrier also as XCL sent it where that differs. XCL's own commands inside a title's call are +//! not recorded, and nothing recorded changes what goes to the PC. Lists are recorded by the +//! object the title holds and submits (a list split into segments is one recording). With the +//! switch on, every frame is recorded until the one written; the writing is done on a thread of +//! its own after that frame's present. Unset, each entry point checks one cached value. + +use std::cell::Cell; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::ffi::c_void; +use std::io::Write; +use std::mem::transmute_copy; +use std::sync::atomic::{AtomicU64, AtomicU8, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use serde_json::{json, Map, Value}; +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use super::sharded::Sharded; + +/// operations of a frame written at most (and of one list's recording kept at most) +const OPS_MOST: usize = 2_000_000; +/// argument bytes of one ExecuteIndirect read at most +const INDIRECT_BYTES_MOST: usize = 16 << 10; +/// descriptor slots at the start of each root table whose resources a draw or dispatch names +pub(super) const TABLE_SLOTS: usize = 16; +/// passes listed in `summary.txt` at most +const PASSES_LISTED: usize = 400; + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Config { + /// draws and dispatches the frame needs + work: u64, + /// none before this long after the first present + after: Duration, +} + +/// `[,]` +fn parse(v: &str) -> Option { + let mut it = v.split(',').map(str::trim); + let work = it.next()?.parse::().ok().filter(|&w| w > 0)?; + let after = match it.next() { + Some(s) => Duration::try_from_secs_f64(s.parse::().ok()?).ok()?, + None => Duration::ZERO, + }; + it.next().is_none().then_some(Config { work, after }) +} + +fn config() -> Option { + static C: OnceLock> = OnceLock::new(); + *C.get_or_init(|| { + let v = std::env::var("XCL_CAPTURE_FRAME").ok()?; + let c = parse(&v); + if c.is_none() { + crate::xlog_warn!("D3D12.X: XCL_CAPTURE_FRAME={v:?} is not [,]: no frame captured"); + } + c + }) +} + +const UNSET: u8 = 0; +const OFF: u8 = 1; +/// the switch is on, the recording has not begun +const WAITING: u8 = 2; +const RECORDING: u8 = 3; +/// the frame was taken (or the switch is off) +const DONE: u8 = 4; +static STATE: AtomicU8 = AtomicU8::new(UNSET); + +fn state() -> u8 { + let s = STATE.load(Ordering::Relaxed); + if s != UNSET { + return s; + } + let _ = STATE.compare_exchange(UNSET, if config().is_some() { WAITING } else { OFF }, Ordering::Relaxed, Ordering::Relaxed); + STATE.load(Ordering::Relaxed) +} + +/// The switch is on and no frame was taken yet: what is made is noted (resources, views, +/// pipelines, command signatures), for whichever frame is captured. +pub fn enabled() -> bool { + matches!(state(), WAITING | RECORDING) +} + +/// Operations are being recorded. +#[inline] +pub fn on() -> bool { + state() == RECORDING +} + +// --------------------------------------------------------------------------------------- +// what an operation holds +// --------------------------------------------------------------------------------------- + +#[derive(Clone, Debug, PartialEq)] +pub(super) enum RootVal { + /// a descriptor table: the 32-bit console address of its first descriptor + Table(u32), + Constants(Vec), + /// a root CBV / SRV / UAV: its GPU address + View(u64), +} + +#[derive(Clone, Debug, PartialEq)] +pub(super) struct RootArg { + pub i: u32, + pub v: RootVal, +} + +/// A render target or depth-stencil view: its handle, resource, format and subresource. +#[derive(Clone, Debug, Default, PartialEq)] +pub(super) struct View { + handle: usize, + res: usize, + format: i32, + mip: u32, + slice: u32, +} + +/// Where a copy reads or writes. +#[derive(Clone, Debug, PartialEq)] +pub(super) enum Loc { + None, + /// a buffer at an offset + Buffer(usize, u64), + /// a subresource of a texture + Sub(usize, u32), + /// a placed footprint in a buffer: offset, format, width, height, depth, row pitch + Footprint(usize, u64, i32, u32, u32, u32, u32), + /// a GPU address (CopyMemoryX) + Address(u64), +} + +#[derive(Clone, Debug, PartialEq)] +pub(super) enum WorkKind { + Draw { vertices: u32, instances: u32, first_vertex: u32, first_instance: u32 }, + DrawIndexed { indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32 }, + /// DrawIndexedX: indices read from an address + DrawIndexedX { va: u64, format: i32, indices: u32 }, + Dispatch([u32; 3]), + /// DispatchX with thread dimensions (flag 0x20): the thread counts, the flags and the groups + /// they launch (None: the pipeline's group shape was not known when it was recorded) + DispatchThreads { threads: [u32; 3], flags: u32, groups: Option<[u32; 3]> }, + DispatchMesh([u32; 3]), + Indirect(Box), +} + +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Indirect { + sig: usize, + /// the signature's stride and argument types (0 / none: made before the switch) + stride: u32, + types: Vec, + dispatches: bool, + args: usize, + args_off: u64, + count: usize, + count_off: u64, + max: u32, + /// the arguments and the count as the CPU saw them when the call was recorded (None: not in + /// CPU-readable title memory) + values: Option>, + count_value: Option, +} + +/// How a draw or dispatch went. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Outcome { + /// on its translated pipeline + Ran, + Skipped, + /// with a PC pipeline (untranslated) + Pc, + /// with the stand-in of a pipeline still being built: drew nothing + StandIn, + /// put off to the submit (its pipeline was being built) + Deferred, +} + +impl Outcome { + fn name(self) -> &'static str { + match self { + Outcome::Ran => "ran", + Outcome::Skipped => "skipped", + Outcome::Pc => "pc", + Outcome::StandIn => "standin", + Outcome::Deferred => "deferred", + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Work { + kind: WorkKind, + /// the title's pipeline + pso: usize, + /// graphics root arguments (else compute) + gfx: bool, + targets: Vec, + dsv: Option, + /// the root arguments: all of them, or (`delta`) the ones changed since the list's last + /// draw or dispatch with the same kind of arguments + root: Vec, + delta: bool, + heaps: [u32; 2], + /// resources the first slots of its descriptor tables name + views: Vec, + outcome: Option, +} + +impl Work { + fn dispatch(&self) -> bool { + match &self.kind { + WorkKind::Dispatch(_) | WorkKind::DispatchThreads { .. } => true, + WorkKind::Indirect(i) => i.dispatches, + _ => false, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub(super) enum Op { + /// a list's recording begins (with its initial pipeline) + Begin(usize), + End, + /// a list goes on after a KickoffX submitted what it held + Continue, + Pipeline(usize), + RootSig { gfx: bool, rs: usize }, + /// the heaps set: (heap, its console address, sampler) + Heaps(Vec<(usize, u32, bool)>), + Targets { rtvs: Vec, dsv: Option }, + Viewports(Vec<[f32; 6]>), + Scissors(Vec<[i32; 4]>), + /// as the title gave them, as XCL sent them, and how many depth plane copies went around them + Barrier { title: Vec<[u32; 8]>, sent: Vec<[u32; 8]>, plane_copies: usize }, + Work(Box), + Copy { kind: &'static str, dst: Loc, src: Loc, at: [u32; 3], bx: Option<[u32; 6]>, bytes: Option, refused: bool }, + /// rtv / dsv / uav_uint / uav_float: the view (handle), its resource, the values (floats as + /// their bits), the rectangles, whether it was not done + Clear { kind: &'static str, view: u64, res: usize, values: [u32; 4], flags: u32, rects: u32, refused: bool }, + Resolve { dst: usize, dst_sub: u32, src: usize, src_sub: u32, format: i32, region: Option<(u32, u32, Option<[i32; 4]>, i32)> }, +} + +impl Op { + fn name(&self) -> &'static str { + match self { + Op::Begin(_) => "list_begin", + Op::End => "list_end", + Op::Continue => "list_continue", + Op::Pipeline(_) => "set_pipeline", + Op::RootSig { .. } => "root_signature", + Op::Heaps(_) => "heaps", + Op::Targets { .. } => "set_render_targets", + Op::Viewports(_) => "viewport", + Op::Scissors(_) => "scissor", + Op::Barrier { .. } => "barrier", + Op::Work(w) => match w.kind { + WorkKind::Draw { .. } => "draw", + WorkKind::DrawIndexed { .. } => "draw_indexed", + WorkKind::DrawIndexedX { .. } => "draw_indexed_x", + WorkKind::Dispatch(_) | WorkKind::DispatchThreads { .. } => "dispatch", + WorkKind::DispatchMesh(_) => "dispatch_mesh", + WorkKind::Indirect(_) => "execute_indirect", + }, + Op::Copy { .. } => "copy", + Op::Clear { .. } => "clear", + Op::Resolve { .. } => "resolve", + } + } +} + +/// The root arguments to record of a draw or dispatch, given the list's previous ones of that +/// kind: (only the changed ones, them) where that is fewer, else (false, all). +pub(super) fn root_delta(prev: Option<&[RootArg]>, now: &[RootArg]) -> (bool, Vec) { + match prev { + Some(p) if p.len() == now.len() => { + let changed: Vec = now.iter().filter(|a| !p.contains(a)).cloned().collect(); + if changed.len() < now.len() { + (true, changed) + } else { + (false, now.to_vec()) + } + } + _ => (false, now.to_vec()), + } +} + +/// The heap and slot a root table at console address `va` starts at, from the heaps set (view, +/// sampler): the nearest base below it. +pub(super) fn table_index(va: u32, heaps: [u32; 2]) -> Option<(&'static str, u32)> { + [("view", heaps[0], super::console_heap::SLOT), ("sampler", heaps[1], super::console_heap::SAMPLER_SLOT)] + .into_iter() + .filter(|&(_, base, _)| base != 0 && va >= base) + .min_by_key(|&(_, base, _)| va - base) + .map(|(heap, base, slot)| (heap, (va - base) / slot)) +} + +/// A view's mip and first slice from the 3 words of its description's union (`dsv`: a +/// depth-stencil view's dimensions). +pub(super) fn mip_slice(dsv: bool, dim: i32, w: [u32; 3]) -> (u32, u32) { + match (dsv, dim) { + // RTV: 1D, 2D; DSV: 1D, 2D + (false, 2 | 4) | (true, 1 | 3) => (w[0], 0), + // RTV: 1D array, 2D array, 3D (first W slice); DSV: 1D array, 2D array + (false, 3 | 5 | 8) | (true, 2 | 4) => (w[0], w[1]), + // multisampled arrays + (false, 7) | (true, 6) => (0, w[0]), + _ => (0, 0), + } +} + +// --------------------------------------------------------------------------------------- +// recordings +// --------------------------------------------------------------------------------------- + +/// What a list recorded since its Reset. +#[derive(Default)] +struct Rec { + ops: Vec, + work: u64, + /// the recording as closed (Close), with its draws and dispatches + closed: Option<(Arc>, u64)>, + seen: bool, + /// the list began before the recording did + partial: bool, + /// operations left out past `OPS_MOST` + dropped: u64, + /// the root arguments of the last draw or dispatch: compute, graphics + prev: [Option>; 2], +} + +/// `op` onto `r`: its place there (None: past the bound) +fn push_to(r: &mut Rec, mut op: Op, most: usize) -> Option { + if !r.seen { + r.seen = true; + r.partial = !matches!(op, Op::Begin(_)); + } + if r.ops.len() >= most { + r.dropped += 1; + return None; + } + match &mut op { + Op::RootSig { gfx, .. } => r.prev[*gfx as usize] = None, + Op::Work(w) => { + let b = w.gfx as usize; + let full = std::mem::take(&mut w.root); + (w.delta, w.root) = root_delta(r.prev[b].as_deref(), &full); + r.prev[b] = Some(full); + r.work += 1; + } + _ => {} + } + r.ops.push(op); + Some(r.ops.len() - 1) +} + +fn begin(r: &mut Rec, pso: usize) { + *r = Rec::default(); + push_to(r, Op::Begin(pso), OPS_MOST); +} + +fn close(r: &mut Rec) { + if !r.seen { + return; + } + push_to(r, Op::End, OPS_MOST + 1); + r.closed = Some((Arc::new(std::mem::take(&mut r.ops)), std::mem::take(&mut r.work))); +} + +/// the recording of each list, by the object the title has +static RECS: Sharded = Sharded::new(); + +thread_local! { + /// entry points of the title's this thread is in (the ones inside the first are XCL's) + static DEPTH: Cell = const { Cell::new(0) }; + /// the operation the outermost of them recorded (list, place) + static CURRENT: Cell> = const { Cell::new(None) }; +} + +/// An entry point of the title's being recorded (`op`), until it returns. +pub(super) struct Guard { + entered: bool, + outer: bool, + at: Option<(usize, usize)>, +} + +impl Guard { + const NONE: Guard = Guard { entered: false, outer: false, at: None }; + + /// Changes the operation recorded (what XCL sent, whether it was done). + pub(super) fn amend(&self, f: impl FnOnce(&mut Op)) { + if let Some((key, i)) = self.at { + RECS.with(key, |r| { + if let Some(op) = r.ops.get_mut(i) { + f(op) + } + }); + } + } +} + +impl Drop for Guard { + fn drop(&mut self) { + if self.entered { + DEPTH.with(|d| d.set(d.get().saturating_sub(1))); + if self.outer { + CURRENT.with(|c| c.set(None)); + } + } + } +} + +/// The object a title's call on the PC list `this` was made on (a split list's segments are one). +fn key_of(this: *mut c_void) -> usize { + super::title_list::wrapper_of(this).map_or(this as usize, |w| w as usize) +} + +/// The title called an entry point on `this`: `make` is what it did (None: nothing to record). +/// Calls inside it (XCL's) are not recorded, nor the calls a submit records for put-off +/// dispatches (they were recorded when the title made them). +pub(super) fn op(this: *mut c_void, make: impl FnOnce() -> Option) -> Guard { + if !on() { + return Guard::NONE; + } + let depth = DEPTH.with(|d| d.replace(d.get() + 1)); + if depth > 0 || super::pso_async::is_at_submit() { + return Guard { entered: true, outer: depth == 0, at: None }; + } + let key = key_of(this); + let at = make().and_then(|op| RECS.with(key, |r| push_to(r, op, OPS_MOST))).map(|i| (key, i)); + CURRENT.with(|c| c.set(at)); + Guard { entered: true, outer: true, at } +} + +/// How the draw or dispatch being recorded on this thread went (the first word counts). +pub(super) fn outcome(o: Outcome) { + if !on() { + return; + } + let Some((key, i)) = CURRENT.with(|c| c.get()) else { return }; + let pso = RECS.with(key, |r| match r.ops.get(i) { + Some(Op::Work(w)) if w.outcome.is_none() => Some(w.pso), + _ => None, + }); + let Some(pso) = pso else { return }; + // (not drawn, or with a PC pipeline, while its real one is being built: its stand-in's) + let o = if matches!(o, Outcome::Skipped | Outcome::Pc) && super::pso_async::is_pending(pso) { Outcome::StandIn } else { o }; + RECS.with(key, |r| { + if let Some(Op::Work(w)) = r.ops.get_mut(i) { + w.outcome.get_or_insert(o); + } + }); +} + +/// A list `key` (the title's object) begins a recording with pipeline `pso` (made, or Reset). +pub(super) fn list_begin(key: usize, pso: usize) { + if on() { + RECS.with(key, |r| begin(r, pso)); + } +} + +/// The title closed list `key`. +pub(super) fn list_end(key: usize) { + if on() { + RECS.with(key, close); + } +} + +/// List `key` is gone. +pub(super) fn forget(key: usize) { + if on() { + RECS.remove(key); + } +} + +/// A draw or dispatch on `this` with the title's pipeline `pso`: the render targets bound now and +/// the root arguments (`root`, of the graphics ones with `gfx`) with the heaps set. +pub(super) unsafe fn work(this: *mut c_void, kind: WorkKind, pso: usize, gfx: bool, root: Vec, heaps: [u32; 2], views: Vec) -> Op { + let mut targets: Vec = super::list_x::bound_render_targets(this).into_iter().filter_map(view_res).collect(); + targets.dedup(); + let dsv = super::list_x::bound_dsv(this).and_then(view_res); + for &r in targets.iter().chain(dsv.iter()).chain(views.iter()) { + describe(r); + } + Op::Work(Box::new(Work { kind, pso, gfx, targets, dsv, root, delta: false, heaps, views, outcome: None })) +} + +/// An ExecuteIndirect's call: with its arguments and count as the CPU sees them now, where they +/// are in title memory it can read. +pub(super) unsafe fn indirect(sig: usize, dispatches: bool, max: u32, args: usize, args_off: u64, count: usize, count_off: u64) -> WorkKind { + let (stride, types) = SIGNATURES.lock().unwrap().as_ref().and_then(|m| m.get(&sig).cloned()).unwrap_or((0, Vec::new())); + describe(args); + describe(count); + let values = super::real::console_buffer(args).and_then(|(p, n)| { + let bytes = (max as usize).saturating_mul(stride as usize).min(INDIRECT_BYTES_MOST).min(n.saturating_sub(args_off as usize)); + let at = p + args_off as usize; + (stride != 0 && bytes >= 4 && crate::gpu::shader::readable(at, bytes)).then(|| (0..bytes / 4).map(|k| ((at + 4 * k) as *const u32).read_unaligned()).collect()) + }); + let count_value = super::real::console_buffer(count) + .filter(|&(_, n)| count_off as usize + 4 <= n) + .map(|(p, _)| p + count_off as usize) + .filter(|&at| crate::gpu::shader::readable(at, 4)) + .map(|at| (at as *const u32).read_unaligned()); + WorkKind::Indirect(Box::new(Indirect { sig, stride, types, dispatches, args, args_off, count, count_off, max, values, count_value })) +} + +/// The render targets `this` has bound now (after an OMSetRenderTargets). +pub(super) unsafe fn targets_op(this: *mut c_void) -> Op { + let rtvs = super::list_x::bound_render_targets(this).into_iter().map(|h| view(h)).collect(); + let dsv = super::list_x::bound_dsv(this).map(|h| view(h)); + Op::Targets { rtvs, dsv } +} + +/// A copy location (a texture's subresource, or a footprint in a buffer). +pub(super) unsafe fn location(l: *const D3D12_TEXTURE_COPY_LOCATION) -> Loc { + let Some(l) = l.as_ref() else { return Loc::None }; + let r: usize = transmute_copy(&l.pResource); + describe(r); + if l.Type == D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT { + let f = l.Anonymous.PlacedFootprint; + Loc::Footprint(r, f.Offset, f.Footprint.Format.0, f.Footprint.Width, f.Footprint.Height, f.Footprint.Depth, f.Footprint.RowPitch) + } else { + Loc::Sub(r, l.Anonymous.SubresourceIndex) + } +} + +/// A buffer location (described). +pub(super) unsafe fn buffer(res: usize, offset: u64) -> Loc { + describe(res); + Loc::Buffer(res, offset) +} + +/// A clear through `view` (an RTV / DSV handle, or a UAV's GPU handle with its resource `res`). +pub(super) unsafe fn clear(kind: &'static str, view: u64, res: Option, values: [u32; 4], flags: u32, rects: u32) -> Op { + let res = res.or_else(|| view_res(view as usize)).unwrap_or(0); + describe(res); + Op::Clear { kind, view, res, values, flags, rects, refused: false } +} + +/// The resources of a barrier call (described), and the call. +pub(super) unsafe fn barrier(title: &[[u32; 8]]) -> Op { + for b in title { + for r in barrier_resources(b) { + describe(r); + } + } + Op::Barrier { title: title.to_vec(), sent: title.to_vec(), plane_copies: 0 } +} + +fn barrier_resources(b: &[u32; 8]) -> Vec { + let r = |lo: usize| (b[lo] as u64 | (b[lo + 1] as u64) << 32) as usize; + match b[0] { + 0 | 2 => vec![r(2)], + 1 => vec![r(2), r(4)], + _ => vec![], + } + .into_iter() + .filter(|&r| r != 0) + .collect() +} + +/// A resource some operation names: described for the frame (once a frame). +pub(super) unsafe fn describe(r: usize) -> usize { + if r == 0 || !on() { + return r; + } + let e = EPOCH.load(Ordering::Relaxed); + if DESCS.with(r, |i| i.epoch == e) { + return r; + } + let p = r as *mut c_void; + let desc = ID3D12Resource::from_raw_borrowed(&p).map(|x| x.GetDesc()); + let title = super::real::title_address(r); + let kept_at = super::title_textures::address(r); + let uma_buffer = super::real::console_buffer(r).is_some(); + DESCS.with(r, |i| *i = ResInfo { epoch: e, title, kept_at, uma_buffer, desc }); + r +} + +/// The resource of an RTV / DSV handle. +fn view_res(handle: usize) -> Option { + VIEWS.get(handle).map(|v| v.res).filter(|&r| r != 0).or_else(|| super::present::rtv_resource(handle)) +} + +unsafe fn view(handle: usize) -> View { + let mut v = VIEWS.get(handle).unwrap_or_default(); + if v.res == 0 { + v.res = super::present::rtv_resource(handle).unwrap_or(0); + } + v.handle = handle; + describe(v.res); + v +} + +// --------------------------------------------------------------------------------------- +// what was made (kept while the switch is on, whichever frame is captured) +// --------------------------------------------------------------------------------------- + +#[derive(Clone, Default)] +struct ResInfo { + /// the frame it was described in + epoch: u64, + title: Option, + /// a texture kept in step with the title's memory there (`title_textures`) + kept_at: Option, + /// a console buffer in unified memory + uma_buffer: bool, + desc: Option, +} + +#[derive(Clone, Default)] +struct Created { + how: String, + /// the console description's format, flags and layout + console: Option<[u32; 3]>, + va: Option, + kept: bool, + /// its width and height then (a resource made later at its address through another path is not it) + size: (u64, u32), +} + +/// resources as the frames described them +static DESCS: Sharded = Sharded::new(); +static CREATED: Sharded = Sharded::new(); +/// RTV / DSV handles: what their views name +static VIEWS: Sharded = Sharded::new(); +/// command signatures: stride, argument types +static SIGNATURES: Mutex)>>> = Mutex::new(None); +/// frames recorded (resources are described once each) +static EPOCH: AtomicU64 = AtomicU64::new(1); + +/// Resource `res` was made by `how` (`lut3d::created`'s arguments). +pub(super) unsafe fn created(how: &str, res: *mut c_void, console: Option<&[u8; 0x38]>, va: Option, kept: bool) { + if !enabled() || res.is_null() { + return; + } + let u = |x: &[u8; 0x38], o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); + let size = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()).map_or((0, 0), |d| (d.Width, d.Height)); + CREATED.insert(res as usize, Created { how: how.to_string(), console: console.map(|x| [u(x, 0x20), u(x, 0x30), u(x, 0x2C)]), va, kept, size }); +} + +/// A render target view (`dsv`: a depth-stencil view) of `res` made at `handle`; `desc`: the six +/// words of its description as the PC got it (format, dimension, then the union – a DSV's after +/// its flags). +pub(super) fn note_view(handle: usize, res: usize, dsv: bool, desc: Option<[u32; 6]>) { + if !enabled() { + return; + } + let v = match desc { + Some(w) => { + let u = if dsv { [w[3], w[4], w[5]] } else { [w[2], w[3], w[4]] }; + let (mip, slice) = mip_slice(dsv, w[1] as i32, u); + View { handle, res, format: w[0] as i32, mip, slice } + } + None => View { handle, res, ..Default::default() }, + }; + VIEWS.insert(handle, v); +} + +/// A command signature: its stride and argument types (PC ones). +pub(super) fn note_signature(sig: usize, stride: u32, types: &[i32]) { + if enabled() { + SIGNATURES.lock().unwrap().get_or_insert_with(HashMap::new).insert(sig, (stride, types.to_vec())); + } +} + +/// A pipeline as the title made it. +struct Pipe { + kind: &'static str, + /// `real::shaders_key` of its shaders (graphics) + set: Option, + /// (stage, `real::shader_key`, dump hash, bytes kept) + stages: Vec<(&'static str, u64, u64, Option>)>, + state: Value, + split: bool, +} + +static PIPES: Mutex>>> = Mutex::new(None); + +fn keep_pipe(pso: usize, p: Pipe) { + PIPES.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, Arc::new(p)); +} + +fn stages_of(stages: &[(&'static str, &[u8])]) -> Vec<(&'static str, u64, u64, Option>)> { + stages + .iter() + .map(|&(s, b)| { + let (key, hash, blob) = super::targets::keep_shader(b); + (s, key, hash, blob) + }) + .collect() +} + +/// Graphics pipeline `pso` was made from `d` with `stages` (VS, PS, DS, HS, GS as present). +pub(super) fn note_graphics(pso: usize, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, stages: &[(&'static str, &[u8])], split: bool) { + if !enabled() || pso == 0 { + return; + } + let set = super::real::shaders_key(&stages.iter().map(|(_, b)| b.to_vec()).collect::>()); + keep_pipe(pso, Pipe { kind: "graphics", set: Some(set), stages: stages_of(stages), state: graphics_state(d), split }); +} + +/// Compute pipeline `pso` was made from `cs`. +pub(super) fn note_compute(pso: usize, cs: &[u8]) { + if !enabled() || pso == 0 { + return; + } + keep_pipe(pso, Pipe { kind: "compute", set: None, stages: stages_of(&[("cs", cs)]), state: Value::Null, split: false }); +} + +/// Pipeline `pso` was made from a pipeline stream (one the graphics or compute path did not note). +pub(super) fn note_stream(pso: usize) { + if !enabled() || pso == 0 { + return; + } + let mut g = PIPES.lock().unwrap(); + g.get_or_insert_with(HashMap::new).entry(pso).or_insert_with(|| Arc::new(Pipe { kind: "stream", set: None, stages: Vec::new(), state: Value::Null, split: false })); +} + +fn graphics_state(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Value { + let n = (d.NumRenderTargets as usize).min(8); + let b = &d.BlendState; + let rts = if b.IndependentBlendEnable.as_bool() { n.max(1) } else { 1 }; + let blend: Vec = b.RenderTarget[..rts].iter().map(|r| Value::String(super::targets::blend_text(r))).collect(); + let r = &d.RasterizerState; + let s = &d.DepthStencilState; + let face = |f: &D3D12_DEPTH_STENCILOP_DESC| json!({"fail": f.StencilFailOp.0, "depth_fail": f.StencilDepthFailOp.0, "pass": f.StencilPassOp.0, "func": f.StencilFunc.0}); + json!({ + "blend": {"alpha_to_coverage": b.AlphaToCoverageEnable.as_bool(), "independent": b.IndependentBlendEnable.as_bool(), "targets": blend}, + "sample_mask": hex(d.SampleMask as u64), + "raster": {"fill": r.FillMode.0, "cull": r.CullMode.0, "front_ccw": r.FrontCounterClockwise.as_bool(), "depth_bias": r.DepthBias, "depth_bias_clamp": r.DepthBiasClamp, "slope_scaled_depth_bias": r.SlopeScaledDepthBias, "depth_clip": r.DepthClipEnable.as_bool(), "conservative": r.ConservativeRaster.0}, + "depth_stencil": {"depth": s.DepthEnable.as_bool(), "write_mask": s.DepthWriteMask.0, "func": s.DepthFunc.0, "stencil": s.StencilEnable.as_bool(), "read_mask": s.StencilReadMask, "stencil_write_mask": s.StencilWriteMask, "front": face(&s.FrontFace), "back": face(&s.BackFace)}, + "rt_formats": d.RTVFormats[..n].iter().map(|f| f.0).collect::>(), + "ds_format": d.DSVFormat.0, + "topology_type": d.PrimitiveTopologyType.0, + "samples": d.SampleDesc.Count, + "strip_cut": d.IBStripCutValue.0, + }) +} + +// --------------------------------------------------------------------------------------- +// the frame +// --------------------------------------------------------------------------------------- + +/// Whether a submitted list had a recording. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Recorded { + Yes, + /// it began before the recording did: its first operations are missing + Partial, + /// none (XCL's own, or recorded before the capture and not reset since) + No, +} + +pub(super) enum Item { + Submit { queue: usize, lists: Vec<(usize, Recorded)>, kickoff: bool }, + List { key: usize, ops: Arc> }, + Present { queue: usize, res: Vec, frame: u64 }, +} + +#[derive(Default)] +pub(super) struct Frame { + items: Vec, + work: u64, + ops: usize, + /// operations left out: past the frame's bound, and past a list's + truncated: u64, + dropped: u64, + /// the first frame recorded (its lists began before) + first: bool, +} + +/// A submitted list's recording: (its operations, draws and dispatches, partial, operations +/// it left out); None: no recording. +type Part = Option<(Arc>, u64, bool, u64)>; + +/// Of `n` more operations onto `total`, how many fit in `most`. +pub(super) fn admit(total: usize, n: usize, most: usize) -> usize { + n.min(most.saturating_sub(total)) +} + +impl Frame { + /// A submit to `queue` of the lists `parts` (in their order). + fn submit(&mut self, queue: usize, parts: Vec<(usize, Part)>, kickoff: bool, most: usize) { + let lists = parts + .iter() + .map(|(k, p)| (*k, p.as_ref().map_or(Recorded::No, |p| if p.2 { Recorded::Partial } else { Recorded::Yes }))) + .collect(); + self.items.push(Item::Submit { queue, lists, kickoff }); + for (key, part) in parts { + let Some((ops, work, _, dropped)) = part else { continue }; + let take = admit(self.ops, ops.len(), most); + self.truncated += (ops.len() - take) as u64; + self.dropped += dropped; + if take == 0 { + continue; + } + let whole = take == ops.len(); + self.work += if whole { work } else { ops[..take].iter().filter(|o| matches!(o, Op::Work(_))).count() as u64 }; + let ops = if whole { ops } else { Arc::new(ops[..take].to_vec()) }; + self.ops += take; + self.items.push(Item::List { key, ops }); + } + } +} + +static FRAME: Mutex> = Mutex::new(None); + +/// The title submits `lists` (its objects) to `queue`. +pub(super) unsafe fn submit(queue: *mut c_void, lists: &[*mut c_void]) { + if !on() { + return; + } + let parts: Vec<(usize, Part)> = lists + .iter() + .map(|&l| { + let key = l as usize; + let part = RECS.with(key, |r| { + r.seen.then(|| match &r.closed { + Some((ops, work)) => (ops.clone(), *work, r.partial, r.dropped), + None => (Arc::new(r.ops.clone()), r.work, r.partial, r.dropped), + }) + }); + (key, part) + }) + .collect(); + if let Some(f) = FRAME.lock().unwrap().as_mut() { + f.submit(queue as usize, parts, false, OPS_MOST); + } +} + +/// KickoffX on `this` to `queue`: what the list recorded so far is submitted, and it goes on. +pub(super) fn kickoff(this: *mut c_void, queue: usize) { + if !on() { + return; + } + let key = key_of(this); + let part = RECS.with(key, |r| { + let part = r.seen.then(|| (Arc::new(std::mem::take(&mut r.ops)), std::mem::take(&mut r.work), r.partial, r.dropped)); + // (what follows is the same recording; its root arguments start over) + r.prev = [None, None]; + if r.seen { + push_to(r, Op::Continue, OPS_MOST); + } + part + }); + if let Some(f) = FRAME.lock().unwrap().as_mut() { + f.submit(queue, vec![(key, part)], true, OPS_MOST); + } +} + +/// Whether frame `f` is the one to write. +fn due(c: &Config, f: &Frame) -> bool { + !f.first && f.work >= c.work +} + +/// The title presents `res` on `queue` (the `frame`th present): the frame ends. +pub(super) unsafe fn present(queue: usize, res: &[usize], frame: u64) { + let s = state(); + if s != WAITING && s != RECORDING { + return; + } + let Some(c) = config() else { return }; + static T0: OnceLock = OnceLock::new(); + let t0 = *T0.get_or_init(Instant::now); + if s == WAITING { + if t0.elapsed() >= c.after { + *FRAME.lock().unwrap() = Some(Frame { first: true, ..Default::default() }); + STATE.store(RECORDING, Ordering::Relaxed); + crate::xlog_info!("D3D12.X: XCL_CAPTURE_FRAME: recording from present {frame} on, until a frame has {} draws and dispatches", c.work); + } + return; + } + for &r in res { + describe(r); + } + let mut f = FRAME.lock().unwrap().take().unwrap_or_default(); + f.items.push(Item::Present { queue, res: res.to_vec(), frame }); + if !due(&c, &f) { + EPOCH.fetch_add(1, Ordering::Relaxed); + *FRAME.lock().unwrap() = Some(Frame::default()); + return; + } + STATE.store(DONE, Ordering::Relaxed); + let mut keys = Vec::new(); + RECS.for_each(|k, _| keys.push(k)); + for k in keys { + RECS.remove(k); + } + let Some(logs) = crate::state::boot().map(|b| b.logs_dir()) else { return }; + let dir = logs.join(format!("capture_{frame}")); + crate::xlog_info!("D3D12.X: XCL_CAPTURE_FRAME: frame {frame} captured ({} draws and dispatches, {} operations): writing {}", f.work, f.ops, dir.display()); + let _ = std::thread::Builder::new().name("xcl-capture".into()).spawn(move || { + match write(&dir, &f, frame) { + Ok(()) => crate::xlog_info!("D3D12.X: XCL_CAPTURE_FRAME: {} written", dir.display()), + Err(e) => crate::xlog_warn!("D3D12.X: XCL_CAPTURE_FRAME: writing {}: {e}", dir.display()), + } + }); +} + +// --------------------------------------------------------------------------------------- +// writing +// --------------------------------------------------------------------------------------- + +/// An operation of the frame in execution order. +pub(super) enum Entry<'a> { + Op { list: usize, op: &'a Op, n: Option }, + Item(&'a Item), +} + +/// The frame's operations in the order the GPU got them, draws and dispatches numbered. +pub(super) fn flatten(items: &[Item]) -> Vec> { + let mut out = Vec::new(); + let mut n = 0u64; + for it in items { + match it { + Item::List { key, ops } => { + for op in ops.iter() { + let k = matches!(op, Op::Work(_)).then(|| { + n += 1; + n - 1 + }); + out.push(Entry::Op { list: *key, op, n: k }); + } + } + _ => out.push(Entry::Item(it)), + } + } + out +} + +fn hex(v: u64) -> String { + format!("{v:#x}") +} + +fn res_json(r: usize) -> Value { + if r == 0 { + return Value::Null; + } + match DESCS.get(r).and_then(|i| i.title.or(i.kept_at)) { + Some(t) => json!({"pc": hex(r as u64), "title": hex(t as u64)}), + None => json!({"pc": hex(r as u64)}), + } +} + +fn sub_json(s: u32) -> Value { + if s == u32::MAX { + json!("all") + } else { + json!(s) + } +} + +fn view_json(v: &View) -> Value { + let d = DESCS.get(v.res).and_then(|i| i.desc); + json!({ + "handle": hex(v.handle as u64), + "res": res_json(v.res), + "w": d.map(|d| d.Width), + "h": d.map(|d| d.Height), + "format": if v.format != 0 { v.format } else { d.map_or(0, |d| d.Format.0) }, + "mip": v.mip, + "slice": v.slice, + }) +} + +fn loc_json(l: &Loc) -> Value { + match *l { + Loc::None => Value::Null, + Loc::Buffer(r, o) => json!({"res": res_json(r), "offset": o}), + Loc::Sub(r, s) => json!({"res": res_json(r), "sub": sub_json(s)}), + Loc::Footprint(r, o, f, w, h, d, p) => json!({"res": res_json(r), "footprint": {"offset": o, "format": f, "w": w, "h": h, "d": d, "row_pitch": p}}), + Loc::Address(va) => json!({"address": hex(va)}), + } +} + +fn barrier_json(b: &[u32; 8]) -> Value { + let r = |lo: usize| (b[lo] as u64 | (b[lo + 1] as u64) << 32) as usize; + match b[0] { + 0 => json!({"type": "transition", "res": res_json(r(2)), "sub": sub_json(b[4]), "before": hex(b[5] as u64), "after": hex(b[6] as u64), "flags": b[1]}), + 1 => json!({"type": "aliasing", "before": res_json(r(2)), "after": res_json(r(4)), "flags": b[1]}), + 2 => json!({"type": "uav", "res": res_json(r(2)), "flags": b[1]}), + t => json!({"type": t, "words": b.iter().map(|&w| hex(w as u64)).collect::>()}), + } +} + +fn root_json(a: &RootArg, heaps: [u32; 2]) -> Value { + match &a.v { + RootVal::Table(va) => { + let (heap, index) = table_index(*va, heaps).map_or((None, None), |(h, k)| (Some(h), Some(k))); + json!({"i": a.i, "table": {"va": hex(*va as u64), "heap": heap, "index": index}}) + } + RootVal::Constants(w) => json!({"i": a.i, "constants": w.iter().map(|&w| format!("{w:#010x}")).collect::>()}), + RootVal::View(va) => json!({"i": a.i, "view": hex(*va)}), + } +} + +/// A pipeline's kind and shaders, as the frame's lines name it. +fn pipe_brief(pso: usize) -> Map { + let mut m = Map::new(); + let p = PIPES.lock().unwrap().as_ref().and_then(|m| m.get(&pso).cloned()); + m.insert("kind".into(), json!(pipe_kind(pso, p.as_deref()))); + if let Some(p) = p { + m.insert("shaders".into(), Value::Object(p.stages.iter().map(|(s, k, _, _)| (s.to_string(), json!(format!("{k:016x}")))).collect())); + m.insert("hashes".into(), Value::Object(p.stages.iter().map(|(s, _, h, _)| (s.to_string(), json!(format!("{h:016x}")))).collect())); + } + m +} + +fn pipe_kind(pso: usize, p: Option<&Pipe>) -> String { + let real = super::pso_async::peek(pso); + if let Some(tp) = super::real::two_pass_of(real) { + return format!("mesh two-pass ({})", tp.kind); + } + if let Some(p) = p { + return p.kind.to_string(); + } + if super::real::is_translated_compute(real) || super::real::is_console_compute(pso) { + "compute".into() + } else if super::real::is_translated_graphics(real) { + "graphics".into() + } else { + "unknown (made before the switch, or not a console pipeline)".into() + } +} + +fn work_json(w: &Work, m: &mut Map) { + let mut put = |k: &str, v: Value| { + m.insert(k.into(), v); + }; + match &w.kind { + WorkKind::Draw { vertices, instances, first_vertex, first_instance } => { + put("vertices", json!(vertices)); + put("instances", json!(instances)); + put("first_vertex", json!(first_vertex)); + put("first_instance", json!(first_instance)); + } + WorkKind::DrawIndexed { indices, instances, first_index, base_vertex, first_instance } => { + put("indices", json!(indices)); + put("instances", json!(instances)); + put("first_index", json!(first_index)); + put("base_vertex", json!(base_vertex)); + put("first_instance", json!(first_instance)); + } + WorkKind::DrawIndexedX { va, format, indices } => { + put("index_address", json!(hex(*va))); + put("index_format", json!(format)); + put("indices", json!(indices)); + } + WorkKind::Dispatch(g) | WorkKind::DispatchMesh(g) => put("groups", json!(g)), + WorkKind::DispatchThreads { threads, flags, groups } => { + put("groups", json!(groups)); + put("threads", json!(threads)); + put("dispatch_flags", json!(hex(*flags as u64))); + } + WorkKind::Indirect(i) => { + put("signature", json!(hex(i.sig as u64))); + put("stride", json!(i.stride)); + put("argument_types", json!(i.types)); + put("dispatches", json!(i.dispatches)); + put("arguments", json!({"res": res_json(i.args), "offset": i.args_off})); + put("count", if i.count == 0 { Value::Null } else { json!({"res": res_json(i.count), "offset": i.count_off}) }); + put("max_count", json!(i.max)); + put("values", i.values.as_ref().map_or(Value::Null, |v| json!(v))); + put("count_value", json!(i.count_value)); + } + } + put("pso", json!(hex(w.pso as u64))); + put("targets", Value::Array(w.targets.iter().map(|&r| res_json(r)).collect())); + put("dsv", w.dsv.map_or(Value::Null, res_json)); + put("root", json!({"bind": if w.gfx { "graphics" } else { "compute" }, "delta": w.delta, "args": w.root.iter().map(|a| root_json(a, w.heaps)).collect::>()})); + put("views", Value::Array(w.views.iter().map(|&r| res_json(r)).collect())); + put("outcome", json!(w.outcome.map_or("unknown", Outcome::name))); +} + +fn entry_json(i: usize, e: &Entry) -> Value { + let mut m = Map::new(); + m.insert("i".into(), json!(i)); + match e { + Entry::Item(Item::Submit { queue, lists, kickoff }) => { + m.insert("op".into(), json!("submit")); + m.insert("queue".into(), json!(hex(*queue as u64))); + m.insert( + "lists".into(), + Value::Array(lists.iter().map(|(l, r)| json!({"list": hex(*l as u64), "recorded": match r { Recorded::Yes => json!(true), Recorded::Partial => json!("partial"), Recorded::No => json!(false) }})).collect()), + ); + if *kickoff { + m.insert("kickoff".into(), json!(true)); + } + } + Entry::Item(Item::Present { queue, res, frame }) => { + m.insert("op".into(), json!("present")); + m.insert("queue".into(), json!(hex(*queue as u64))); + m.insert("resources".into(), Value::Array(res.iter().map(|&r| res_json(r)).collect())); + m.insert("frame".into(), json!(frame)); + } + Entry::Item(Item::List { .. }) => {} + Entry::Op { list, op, n } => { + m.insert("op".into(), json!(op.name())); + m.insert("list".into(), json!(hex(*list as u64))); + if let Some(n) = n { + m.insert("n".into(), json!(n)); + } + match op { + Op::Begin(pso) => { + m.insert("pso".into(), if *pso == 0 { Value::Null } else { json!(hex(*pso as u64)) }); + } + Op::End | Op::Continue => {} + Op::Pipeline(pso) => { + m.insert("pso".into(), json!(hex(*pso as u64))); + m.extend(pipe_brief(*pso)); + } + Op::RootSig { gfx, rs } => { + m.insert("bind".into(), json!(if *gfx { "graphics" } else { "compute" })); + m.insert("rs".into(), json!(hex(*rs as u64))); + } + Op::Heaps(h) => { + m.insert("heaps".into(), Value::Array(h.iter().map(|&(o, base, s)| json!({"heap": hex(o as u64), "address": hex(base as u64), "sampler": s})).collect())); + } + Op::Targets { rtvs, dsv } => { + m.insert("rtvs".into(), Value::Array(rtvs.iter().map(view_json).collect())); + m.insert("dsv".into(), dsv.as_ref().map_or(Value::Null, view_json)); + } + Op::Viewports(v) => { + m.insert("viewports".into(), json!(v)); + } + Op::Scissors(r) => { + m.insert("rects".into(), json!(r)); + } + Op::Barrier { title, sent, plane_copies } => { + m.insert("barriers".into(), Value::Array(title.iter().map(barrier_json).collect())); + if title != sent { + m.insert("sent".into(), Value::Array(sent.iter().map(barrier_json).collect())); + m.insert("rewritten".into(), json!(true)); + } + if *plane_copies > 0 { + m.insert("plane_copies".into(), json!(plane_copies)); + } + } + Op::Work(w) => work_json(w, &mut m), + Op::Copy { kind, dst, src, at, bx, bytes, refused } => { + m.insert("kind".into(), json!(kind)); + m.insert("dst".into(), loc_json(dst)); + m.insert("src".into(), loc_json(src)); + if *at != [0; 3] { + m.insert("at".into(), json!(at)); + } + if let Some(b) = bx { + m.insert("box".into(), json!(b)); + } + if let Some(b) = bytes { + m.insert("bytes".into(), json!(b)); + } + if *refused { + m.insert("refused".into(), json!(true)); + } + } + Op::Clear { kind, view, res, values, flags, rects, refused } => { + m.insert("kind".into(), json!(kind)); + m.insert("view".into(), json!(hex(*view))); + m.insert("res".into(), res_json(*res)); + let v = match *kind { + "uav_uint" => json!(values), + "dsv" => json!({"depth": f32::from_bits(values[0]), "stencil": values[1], "flags": flags}), + _ => json!(values.iter().map(|&b| f32::from_bits(b)).collect::>()), + }; + m.insert("values".into(), v); + m.insert("rects".into(), json!(rects)); + if *refused { + m.insert("refused".into(), json!(true)); + } + } + Op::Resolve { dst, dst_sub, src, src_sub, format, region } => { + m.insert("dst".into(), json!({"res": res_json(*dst), "sub": sub_json(*dst_sub)})); + m.insert("src".into(), json!({"res": res_json(*src), "sub": sub_json(*src_sub)})); + m.insert("format".into(), json!(format)); + if let Some((x, y, rect, mode)) = region { + m.insert("region".into(), json!({"x": x, "y": y, "rect": rect, "mode": mode})); + } + } + } + } + } + Value::Object(m) +} + +/// The resources an operation names. +fn resources_of(op: &Op, out: &mut BTreeSet) { + let mut add = |r: usize| { + if r != 0 { + out.insert(r); + } + }; + let loc = |l: &Loc| match *l { + Loc::Buffer(r, _) | Loc::Sub(r, _) | Loc::Footprint(r, ..) => r, + _ => 0, + }; + match op { + Op::Targets { rtvs, dsv } => rtvs.iter().chain(dsv.iter()).for_each(|v| add(v.res)), + Op::Barrier { title, sent, .. } => title.iter().chain(sent.iter()).flat_map(barrier_resources).for_each(add), + Op::Work(w) => { + w.targets.iter().chain(w.dsv.iter()).chain(w.views.iter()).for_each(|&r| add(r)); + if let WorkKind::Indirect(i) = &w.kind { + add(i.args); + add(i.count); + } + } + Op::Copy { dst, src, .. } => { + add(loc(dst)); + add(loc(src)); + } + Op::Clear { res, .. } => add(*res), + Op::Resolve { dst, src, .. } => { + add(*dst); + add(*src); + } + _ => {} + } +} + +fn resource_json(r: usize) -> Value { + let i = DESCS.get(r).unwrap_or_default(); + let d = i.desc; + let c = CREATED.get(r).filter(|c| d.is_some_and(|d| (d.Width, d.Height) == c.size)); + let dimension = d.map(|d| match d.Dimension { + D3D12_RESOURCE_DIMENSION_BUFFER => "buffer", + D3D12_RESOURCE_DIMENSION_TEXTURE1D => "texture1d", + D3D12_RESOURCE_DIMENSION_TEXTURE2D => "texture2d", + D3D12_RESOURCE_DIMENSION_TEXTURE3D => "texture3d", + _ => "unknown", + }); + let (how, kept) = match &c { + Some(c) => (Some(c.how.clone()), Some(c.kept)), + None if i.uma_buffer => (Some("a console buffer in unified memory (the title's memory itself)".to_string()), Some(true)), + None if i.kept_at.is_some() => (Some("a texture kept in step with the title's memory (uploaded from it)".to_string()), Some(true)), + None => (None, None), + }; + json!({ + "pc": hex(r as u64), + "title": i.title.or(i.kept_at).or(c.as_ref().and_then(|c| c.va)).map(|a| hex(a as u64)), + "dimension": dimension, + "width": d.map(|d| d.Width), + "height": d.map(|d| d.Height), + "depth_or_array": d.map(|d| d.DepthOrArraySize), + "mips": d.map(|d| d.MipLevels), + "format": d.map(|d| d.Format.0), + "console_format": c.as_ref().and_then(|c| c.console).map(|x| x[0]), + "console_flags": c.as_ref().and_then(|c| c.console).map(|x| hex(x[1] as u64)), + "console_layout": c.as_ref().and_then(|c| c.console).map(|x| hex(x[2] as u64)), + "flags": d.map(|d| hex(d.Flags.0 as u64)), + "samples": d.map(|d| d.SampleDesc.Count), + "layout": d.map(|d| d.Layout.0), + "created": how, + "kept_in_step": kept, + }) +} + +/// What the frame's draws and dispatches with one pipeline did. +#[derive(Default)] +struct PipeUse { + draws: u64, + dispatches: u64, + outcomes: BTreeMap<&'static str, u64>, +} + +/// A pass: draws and dispatches in a row with the same render targets. +#[derive(Debug, PartialEq)] +pub(super) struct Pass { + pub targets: Vec, + pub dsv: Option, + pub draws: u64, + pub dispatches: u64, + pub pipelines: BTreeSet, + pub first: usize, + pub last: usize, +} + +/// The passes of the frame's operations (`flatten`'s, by their place). +pub(super) fn passes(entries: &[Entry]) -> Vec { + let mut out: Vec = Vec::new(); + for (i, e) in entries.iter().enumerate() { + let Entry::Op { op: Op::Work(w), .. } = e else { continue }; + let same = out.last().is_some_and(|p| p.targets == w.targets && p.dsv == w.dsv); + if !same { + out.push(Pass { targets: w.targets.clone(), dsv: w.dsv, draws: 0, dispatches: 0, pipelines: BTreeSet::new(), first: i, last: i }); + } + let p = out.last_mut().unwrap(); + if w.dispatch() { + p.dispatches += 1; + } else { + p.draws += 1; + } + p.pipelines.insert(w.pso); + p.last = i; + } + out +} + +/// groups one ExecuteIndirect may run past which the guard drops a dispatch (`indirect_guard`'s +/// default `XCL_INDIRECT_MAX_GROUPS`) +const GUARD_GROUPS: u64 = 4 << 20; + +fn write(dir: &std::path::Path, f: &Frame, frame: u64) -> std::io::Result<()> { + std::fs::create_dir_all(dir.join("shaders"))?; + let entries = flatten(&f.items); + let mut counts: BTreeMap<&'static str, u64> = BTreeMap::new(); + let mut resources = BTreeSet::new(); + let mut psos = BTreeSet::new(); + let mut uses: BTreeMap = BTreeMap::new(); + let mut warn: BTreeMap<&'static str, Vec> = BTreeMap::new(); + let mut note = |what: &'static str, at: String| warn.entry(what).or_default().push(at); + { + let mut out = std::io::BufWriter::new(std::fs::File::create(dir.join("frame.jsonl"))?); + for (i, e) in entries.iter().enumerate() { + match e { + Entry::Op { op, n, .. } => { + *counts.entry(op.name()).or_default() += 1; + resources_of(op, &mut resources); + match op { + Op::Pipeline(p) => { + psos.insert(*p); + } + Op::Work(w) => { + psos.insert(w.pso); + let u = uses.entry(w.pso).or_default(); + if w.dispatch() { + u.dispatches += 1; + } else { + u.draws += 1; + } + let o = w.outcome.map_or("unknown", Outcome::name); + *u.outcomes.entry(o).or_default() += 1; + let at = format!("n={} i={i}", n.unwrap_or(0)); + if w.outcome == Some(Outcome::StandIn) { + note("draws or dispatches with a stand-in pipeline (drew nothing)", at.clone()); + } + if w.outcome == Some(Outcome::Skipped) { + note("draws or dispatches XCL skipped", at.clone()); + } + match &w.kind { + WorkKind::Dispatch(g) | WorkKind::DispatchMesh(g) | WorkKind::DispatchThreads { threads: g, .. } if g.contains(&0) => note("dispatches with zero groups", at.clone()), + WorkKind::Indirect(x) => { + if x.max == 0 { + note("ExecuteIndirects with a max count of 0", at.clone()); + } + if x.dispatches && x.stride >= 12 { + let big = x.values.as_ref().is_some_and(|v| { + let per = x.stride as usize / 4; + let n = x.count_value.map_or(x.max, |c| c.min(x.max)) as usize; + // (a plain dispatch signature: its groups are its last 3 words) + v.chunks(per).take(n).any(|c| c.len() >= 3 && c[c.len() - 3..].iter().map(|&g| g as u64).product::() > GUARD_GROUPS) + }); + if big { + note("ExecuteIndirect dispatches past the guard's group count (the guard runs zeros there)", at.clone()); + } + } + } + _ => {} + } + } + Op::Copy { refused: true, .. } | Op::Clear { refused: true, .. } => note("copies or clears XCL did not do", format!("i={i}")), + Op::Barrier { title, sent, .. } if title != sent => note("barrier calls XCL rewrote (state bits dropped, transitions dropped, UAV barriers widened or added, depth twins)", format!("i={i}")), + _ => {} + } + } + Entry::Item(Item::Submit { lists, .. }) => { + *counts.entry("submit").or_default() += 1; + for (l, r) in lists { + match r { + Recorded::Partial => note("lists that began before the recording (their first operations are missing)", format!("i={i} list {l:#x}")), + Recorded::No => note("lists submitted with no recording (XCL's own, or recorded before the capture and not reset since)", format!("i={i} list {l:#x}")), + Recorded::Yes => {} + } + } + } + Entry::Item(Item::Present { res, .. }) => { + *counts.entry("present").or_default() += 1; + resources.extend(res.iter().copied().filter(|&r| r != 0)); + } + Entry::Item(_) => {} + } + serde_json::to_writer(&mut out, &entry_json(i, e))?; + out.write_all(b"\n")?; + } + out.flush()?; + } + { + let mut out = std::io::BufWriter::new(std::fs::File::create(dir.join("resources.jsonl"))?); + for &r in &resources { + serde_json::to_writer(&mut out, &resource_json(r))?; + out.write_all(b"\n")?; + } + out.flush()?; + } + let pipes = PIPES.lock().unwrap().clone().unwrap_or_default(); + let mut shaders: Vec = Vec::new(); + let mut written = BTreeSet::new(); + { + let mut out = std::io::BufWriter::new(std::fs::File::create(dir.join("pipelines.jsonl"))?); + for &pso in &psos { + let p = pipes.get(&pso); + let real = super::pso_async::peek(pso); + let u = uses.get(&pso); + let mut m = pipe_brief(pso); + m.insert("pso".into(), json!(hex(pso as u64))); + m.insert("set".into(), json!(p.and_then(|p| p.set).map(|s| format!("{s:016x}")))); + m.insert("state".into(), p.map_or(Value::Null, |p| p.state.clone())); + m.insert("wave32".into(), json!(p.map(|p| p.split))); + m.insert("translated_now".into(), json!(super::real::is_translated_graphics(real) || super::real::is_translated_compute(real) || super::real::two_pass_of(real).is_some())); + m.insert("building_now".into(), json!(super::pso_async::is_pending(pso))); + m.insert("draws".into(), json!(u.map_or(0, |u| u.draws))); + m.insert("dispatches".into(), json!(u.map_or(0, |u| u.dispatches))); + m.insert("outcomes".into(), json!(u.map(|u| u.outcomes.clone()))); + serde_json::to_writer(&mut out, &Value::Object(m))?; + out.write_all(b"\n")?; + if let Some(p) = p { + let vs = p.stages.iter().find(|s| s.0 == "vs").and_then(|s| s.3.clone()); + for (s, key, _, blob) in &p.stages { + if let Some(b) = blob.as_ref().filter(|_| written.insert((*s, *key))) { + shaders.push((format!("shaders/{s}_{key:016x}"), s, b.clone(), vs.clone(), p.split)); + } + } + } + } + out.flush()?; + } + write_summary(dir, f, frame, &entries, &counts, &uses, &pipes, &warn)?; + let n = shaders.len(); + super::targets::write_shaders(dir, shaders, super::targets::HLSL_BYTES_MOST); + crate::xlog_info!("D3D12.X: XCL_CAPTURE_FRAME: {n} shaders translated again"); + Ok(()) +} + +#[allow(clippy::too_many_arguments)] +fn write_summary( + dir: &std::path::Path, + f: &Frame, + frame: u64, + entries: &[Entry], + counts: &BTreeMap<&'static str, u64>, + uses: &BTreeMap, + pipes: &HashMap>, + warn: &BTreeMap<&'static str, Vec>, +) -> std::io::Result<()> { + let mut s = String::new(); + use std::fmt::Write as _; + let _ = writeln!(s, "XCL_CAPTURE_FRAME: frame {frame}: {} draws and dispatches, {} operations ({} lines)", f.work, f.ops, entries.len()); + if f.truncated > 0 { + let _ = writeln!(s, "TRUNCATED: {} operations past the bound of {OPS_MOST} left out", f.truncated); + } + if f.dropped > 0 { + let _ = writeln!(s, "TRUNCATED: {} operations past one list's bound of {OPS_MOST} were not recorded", f.dropped); + } + let _ = writeln!(s, "\noperations by kind:"); + for (k, n) in counts { + let _ = writeln!(s, " {k:<20} {n}"); + } + let ps = passes(entries); + let short = |r: &usize| format!("{r:#x}"); + let _ = writeln!(s, "\npasses (draws and dispatches in a row with the same render targets): {}", ps.len()); + for (k, p) in ps.iter().enumerate().take(PASSES_LISTED) { + let t: Vec = p.targets.iter().map(short).collect(); + let _ = writeln!( + s, + " pass {k}: i {}..{}, targets [{}] dsv {}: {} draws, {} dispatches, {} pipelines", + p.first, + p.last, + t.join(" "), + p.dsv.as_ref().map_or("-".into(), short), + p.draws, + p.dispatches, + p.pipelines.len() + ); + } + if ps.len() > PASSES_LISTED { + let _ = writeln!(s, " and {} more", ps.len() - PASSES_LISTED); + } + let _ = writeln!(s, "\npipelines by draws and dispatches: {}", uses.len()); + let mut by: Vec<(&usize, &PipeUse)> = uses.iter().collect(); + by.sort_by(|a, b| (b.1.draws + b.1.dispatches).cmp(&(a.1.draws + a.1.dispatches)).then(a.0.cmp(b.0))); + for (pso, u) in by { + let p = pipes.get(pso); + let shaders: Vec = p.map_or(Vec::new(), |p| p.stages.iter().map(|(s, k, _, _)| format!("{s} {k:016x}")).collect()); + let o: Vec = u.outcomes.iter().map(|(k, n)| format!("{k} {n}")).collect(); + let _ = writeln!(s, " {pso:#x} {}: {} draws, {} dispatches ({}) {}", pipe_kind(*pso, p.map(|p| &**p)), u.draws, u.dispatches, o.join(", "), shaders.join(" ")); + } + let _ = writeln!(s, "\nwarnings:"); + if warn.is_empty() { + let _ = writeln!(s, " none"); + } + for (what, at) in warn { + let shown: Vec<&str> = at.iter().take(24).map(|x| x.as_str()).collect(); + let _ = writeln!(s, " {} {what}: {}{}", at.len(), shown.join(", "), if at.len() > 24 { ", …" } else { "" }); + } + let _ = writeln!( + s, + "\nnot recorded: console-shaped lists (XCL_CONSOLE_LISTS), bundles' contents, ExecuteBundle, enhanced barriers, descriptor copies and \ + writes, CopyTiles, queries, predication, vertex and index buffers, topology, blend factor, stencil reference, depth bounds, \ + ClearState, the memory writes, waits and cache flushes of the console's list methods (#60-#72, #88-#90, #131, #132, #146)" + ); + std::fs::write(dir.join("summary.txt"), s) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn draw(pso: usize, targets: &[usize], root: Vec) -> Op { + Op::Work(Box::new(Work { + kind: WorkKind::Draw { vertices: 3, instances: 1, first_vertex: 0, first_instance: 0 }, + pso, + gfx: true, + targets: targets.to_vec(), + dsv: None, + root, + delta: false, + heaps: [0x1000, 0x8000], + views: Vec::new(), + outcome: None, + })) + } + + fn dispatch(pso: usize, root: Vec) -> Op { + Op::Work(Box::new(Work { + kind: WorkKind::Dispatch([4, 4, 1]), + pso, + gfx: false, + targets: Vec::new(), + dsv: None, + root, + delta: false, + heaps: [0; 2], + views: Vec::new(), + outcome: None, + })) + } + + fn c(i: u32, w: u32) -> RootArg { + RootArg { i, v: RootVal::Constants(vec![w]) } + } + + fn part(r: &Rec) -> Part { + r.closed.as_ref().map(|(ops, w)| (ops.clone(), *w, r.partial, r.dropped)) + } + + /// A `DispatchX` with thread dimensions is written as a dispatch with the groups it launched + /// (null: not known when recorded), its thread counts and its flags. + #[test] + fn a_dispatch_with_thread_dimensions_is_written_with_its_threads_and_groups() { + let Op::Work(mut w) = dispatch(0xd0, vec![]) else { unreachable!() }; + w.kind = WorkKind::DispatchThreads { threads: [100, 1, 1], flags: 0x8020, groups: Some([2, 1, 1]) }; + assert!(w.dispatch()); + assert_eq!(Op::Work(w.clone()).name(), "dispatch"); + let mut m = Map::new(); + work_json(&w, &mut m); + assert_eq!((&m["groups"], &m["threads"], &m["dispatch_flags"]), (&json!([2, 1, 1]), &json!([100, 1, 1]), &json!("0x8020"))); + w.kind = WorkKind::DispatchThreads { threads: [100, 1, 1], flags: 0x20, groups: None }; + let mut m = Map::new(); + work_json(&w, &mut m); + assert_eq!(m["groups"], Value::Null); + } + + #[test] + fn the_switch_takes_a_work_threshold_and_seconds() { + assert_eq!(parse("500"), Some(Config { work: 500, after: Duration::ZERO })); + assert_eq!(parse(" 500 , 2.5 "), Some(Config { work: 500, after: Duration::from_millis(2500) })); + for bad in ["0", "x", "500,x", "500,-1", "500,1,2", ""] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + let c = Config { work: 10, after: Duration::ZERO }; + let f = |work, first| Frame { work, first, ..Default::default() }; + assert!(due(&c, &f(10, false))); + assert!(!due(&c, &f(9, false)), "too little work"); + assert!(!due(&c, &f(100, true)), "the first frame recorded began before the recording"); + } + + /// Lists recorded at once (on several threads: their operations interleaved in time) come out + /// in the order they were submitted, each in its own order, the draws numbered so. + #[test] + fn operations_come_out_in_the_order_they_were_executed() { + let (mut a, mut b) = (Rec::default(), Rec::default()); + begin(&mut a, 0); + begin(&mut b, 0); + // a and b interleaved: a0 b0 a1 b1 b2 + push_to(&mut a, Op::Pipeline(0xa0), OPS_MOST); + push_to(&mut b, Op::Pipeline(0xb0), OPS_MOST); + push_to(&mut a, draw(0xa0, &[0x10], vec![]), OPS_MOST); + push_to(&mut b, draw(0xb0, &[0x20], vec![]), OPS_MOST); + push_to(&mut b, dispatch(0xb1, vec![]), OPS_MOST); + close(&mut a); + close(&mut b); + // submitted b, then a (b on a second queue first), then a again + let mut f = Frame::default(); + f.submit(0x51, vec![(0xb, part(&b)), (0xc, None)], false, OPS_MOST); + f.submit(0x52, vec![(0xa, part(&a))], false, OPS_MOST); + f.submit(0x52, vec![(0xa, part(&a))], false, OPS_MOST); + assert_eq!(f.work, 2 + 1 + 1); + let e = flatten(&f.items); + let seq: Vec = e + .iter() + .map(|e| match e { + Entry::Op { list, op, n } => format!("{list:x}:{}{}", op.name(), n.map_or(String::new(), |n| format!("#{n}"))), + Entry::Item(Item::Submit { queue, lists, .. }) => format!("submit {queue:x} {:?}", lists.iter().map(|l| l.1).collect::>()), + Entry::Item(_) => "?".into(), + }) + .collect(); + assert_eq!( + seq, + [ + "submit 51 [Yes, No]", + "b:list_begin", + "b:set_pipeline", + "b:draw#0", + "b:dispatch#1", + "b:list_end", + "submit 52 [Yes]", + "a:list_begin", + "a:set_pipeline", + "a:draw#2", + "a:list_end", + "submit 52 [Yes]", + "a:list_begin", + "a:set_pipeline", + "a:draw#3", + "a:list_end", + ] + ); + // the passes: b's draw into 0x20, b's dispatch (no targets bound), a's draws into 0x10 + let p = passes(&e); + assert_eq!(p.iter().map(|p| (p.targets.clone(), p.draws, p.dispatches)).collect::>(), vec![(vec![0x20], 1, 0), (vec![], 0, 1), (vec![0x10], 2, 0)]); + assert_eq!((p[2].first, p[2].last), (9, 14)); + // a list recorded from the middle (no Begin): partial + let mut late = Rec::default(); + push_to(&mut late, draw(1, &[], vec![]), OPS_MOST); + close(&mut late); + let mut f = Frame::default(); + f.submit(1, vec![(0xd, part(&late))], false, OPS_MOST); + assert!(matches!(&f.items[0], Item::Submit { lists, .. } if lists[0].1 == Recorded::Partial)); + } + + /// Root arguments: all at a list's first draw and after a root signature is set, then only the + /// changed ones where they are fewer – per kind (graphics, compute) – flagged as such. + #[test] + fn root_arguments_are_recorded_as_changed_since_the_last_draw() { + assert_eq!(root_delta(None, &[c(0, 1), c(1, 2)]), (false, vec![c(0, 1), c(1, 2)])); + assert_eq!(root_delta(Some(&[c(0, 1), c(1, 2)]), &[c(0, 1), c(1, 3)]), (true, vec![c(1, 3)])); + assert_eq!(root_delta(Some(&[c(0, 1), c(1, 2)]), &[c(0, 1), c(1, 2)]), (true, vec![]), "nothing changed"); + assert_eq!(root_delta(Some(&[c(0, 1), c(1, 2)]), &[c(0, 5), c(1, 6)]), (false, vec![c(0, 5), c(1, 6)]), "all changed: not smaller"); + assert_eq!(root_delta(Some(&[c(0, 1)]), &[c(0, 1), c(1, 2)]), (false, vec![c(0, 1), c(1, 2)]), "another layout"); + let mut r = Rec::default(); + begin(&mut r, 0); + let t = |i, va| RootArg { i, v: RootVal::Table(va) }; + let v = |i, va| RootArg { i, v: RootVal::View(va) }; + push_to(&mut r, draw(1, &[], vec![t(0, 0x100), c(1, 7), v(2, 0x9000)]), OPS_MOST); + push_to(&mut r, dispatch(2, vec![c(0, 1), c(1, 2)]), OPS_MOST); + push_to(&mut r, draw(1, &[], vec![t(0, 0x100), c(1, 8), v(2, 0x9000)]), OPS_MOST); + push_to(&mut r, dispatch(2, vec![c(0, 1), c(1, 3)]), OPS_MOST); + push_to(&mut r, Op::RootSig { gfx: true, rs: 9 }, OPS_MOST); + push_to(&mut r, draw(1, &[], vec![t(0, 0x100), c(1, 8), v(2, 0x9000)]), OPS_MOST); + let got: Vec<(bool, Vec)> = r.ops.iter().filter_map(|o| if let Op::Work(w) = o { Some((w.delta, w.root.clone())) } else { None }).collect(); + assert_eq!( + got, + vec![ + (false, vec![t(0, 0x100), c(1, 7), v(2, 0x9000)]), + (false, vec![c(0, 1), c(1, 2)]), + (true, vec![c(1, 8)]), + (true, vec![c(1, 3)]), + (false, vec![t(0, 0x100), c(1, 8), v(2, 0x9000)]), + ] + ); + // the heap slot a table starts at: the nearest heap below it + assert_eq!(table_index(0x1000 + 5 * 32, [0x1000, 0x8000]), Some(("view", 5))); + assert_eq!(table_index(0x8000 + 3 * 16, [0x1000, 0x8000]), Some(("sampler", 3))); + assert_eq!(table_index(0x800, [0x1000, 0]), None); + // a view's mip and first slice by its dimension (RTV 2D array, 3D; DSV 2D, MS array) + assert_eq!(mip_slice(false, 5, [2, 7, 1]), (2, 7)); + assert_eq!(mip_slice(false, 8, [1, 4, 2]), (1, 4)); + assert_eq!(mip_slice(true, 3, [3, 9, 9]), (3, 0)); + assert_eq!(mip_slice(true, 6, [5, 1, 0]), (0, 5)); + } + + /// A frame of each kind of operation goes to `frame.jsonl` one object a line, in order, with the + /// draws numbered and the root arguments as recorded; the other files are there. + /// (`XCL_CAPTURE_TEST_DIR=`: written there and kept, for reading it with a script.) + #[test] + fn a_frame_is_written_one_operation_a_line() { + let kept = std::env::var_os("XCL_CAPTURE_TEST_DIR").map(std::path::PathBuf::from); + let dir = kept.clone().unwrap_or_else(|| std::env::temp_dir().join(format!("xcl-capture-test-{}", std::process::id()))); + let mut r = Rec::default(); + begin(&mut r, 0); + let rt = View { handle: 0x500, res: 0x7000, format: 10, mip: 0, slice: 0 }; + for op in [ + Op::Heaps(vec![(0x60, 0x1000, false), (0x61, 0x8000, true)]), + Op::Pipeline(0xa0), + Op::RootSig { gfx: true, rs: 0x99 }, + Op::Targets { rtvs: vec![rt], dsv: None }, + Op::Viewports(vec![[0.0, 0.0, 1920.0, 1080.0, 0.0, 1.0]]), + Op::Scissors(vec![[0, 0, 1920, 1080]]), + Op::Barrier { title: vec![[0, 0, 0x7000, 0, u32::MAX, 0x800_0000 | 4, 0x40, 0]], sent: vec![[0, 0, 0x7000, 0, u32::MAX, 4, 0x40, 0], [2, 0, 0, 0, 0, 0, 0, 0]], plane_copies: 0 }, + draw(0xa0, &[0x7000], vec![RootArg { i: 0, v: RootVal::Table(0x1000 + 64) }, c(1, 5)]), + draw(0xa0, &[0x7000], vec![RootArg { i: 0, v: RootVal::Table(0x1000 + 64) }, c(1, 6)]), + dispatch(0xb0, vec![c(0, 1)]), + Op::Copy { kind: "texture_region", dst: Loc::Sub(0x7100, 0), src: Loc::Footprint(0x7200, 512, 28, 64, 64, 1, 256), at: [0; 3], bx: None, bytes: None, refused: false }, + Op::Clear { kind: "uav_float", view: 0x1040, res: 0x7100, values: [1.0f32.to_bits(), 0, 0, 0], flags: 0, rects: 0, refused: true }, + Op::Resolve { dst: 0x7300, dst_sub: 0, src: 0x7000, src_sub: 0, format: 28, region: None }, + ] { + push_to(&mut r, op, OPS_MOST); + } + let mut ind = dispatch(0xb0, vec![c(0, 1)]); + if let Op::Work(w) = &mut ind { + w.kind = WorkKind::Indirect(Box::new(Indirect { sig: 0x40, stride: 12, types: vec![2], dispatches: true, args: 0x7400, args_off: 16, count: 0, count_off: 0, max: 2, values: Some(vec![8, 8, 1, 0, 1, 1]), count_value: None })); + w.outcome = Some(Outcome::StandIn); + } + push_to(&mut r, ind, OPS_MOST); + close(&mut r); + let mut f = Frame::default(); + f.submit(0x51, vec![(0xa, part(&r)), (0xc, None)], false, OPS_MOST); + f.items.push(Item::Present { queue: 0x51, res: vec![0x7300], frame: 7 }); + write(&dir, &f, 7).unwrap(); + let text = std::fs::read_to_string(dir.join("frame.jsonl")).unwrap(); + let lines: Vec = text.lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + let ops: Vec<&str> = lines.iter().map(|l| l["op"].as_str().unwrap()).collect(); + assert_eq!( + ops, + [ + "submit", "list_begin", "heaps", "set_pipeline", "root_signature", "set_render_targets", "viewport", "scissor", "barrier", "draw", "draw", "dispatch", "copy", "clear", + "resolve", "execute_indirect", "list_end", "present" + ] + ); + assert!(lines.iter().enumerate().all(|(i, l)| l["i"] == json!(i))); + assert_eq!(lines[9]["n"], json!(0)); + assert_eq!(lines[9]["root"]["args"][0]["table"], json!({"va": "0x1040", "heap": "view", "index": 2})); + assert_eq!((lines[10]["root"]["delta"].clone(), lines[10]["root"]["args"].clone()), (json!(true), json!([{"i": 1, "constants": ["0x00000006"]}]))); + assert_eq!(lines[10]["targets"], json!([{"pc": "0x7000"}])); + assert_eq!(lines[8]["rewritten"], json!(true)); + assert_eq!(lines[8]["barriers"][0]["sub"], json!("all")); + assert_eq!(lines[15]["values"], json!([8, 8, 1, 0, 1, 1])); + assert_eq!(lines[15]["outcome"], json!("standin")); + assert_eq!(lines[0]["lists"], json!([{"list": "0xa", "recorded": true}, {"list": "0xc", "recorded": false}])); + let res = std::fs::read_to_string(dir.join("resources.jsonl")).unwrap(); + assert_eq!(res.lines().count(), 5, "0x7000 0x7100 0x7200 0x7300 0x7400: {res}"); + let pipes = std::fs::read_to_string(dir.join("pipelines.jsonl")).unwrap(); + assert_eq!(pipes.lines().count(), 2); + let summary = std::fs::read_to_string(dir.join("summary.txt")).unwrap(); + assert!(summary.contains("passes (draws and dispatches in a row with the same render targets): 2"), "{summary}"); + assert!(summary.contains("1 barrier calls XCL rewrote"), "{summary}"); + assert!(summary.contains("1 copies or clears XCL did not do"), "{summary}"); + assert!(summary.contains("1 draws or dispatches with a stand-in pipeline"), "{summary}"); + if kept.is_none() { + let _ = std::fs::remove_dir_all(&dir); + } + } + + /// A list keeps `most` operations (the rest counted as dropped), a frame takes as many as fit + /// in its bound (the rest counted as truncated, and their draws not counted). + #[test] + fn a_frame_and_a_list_stop_at_their_bounds() { + assert_eq!(admit(0, 5, 10), 5); + assert_eq!(admit(8, 5, 10), 2); + assert_eq!(admit(10, 5, 10), 0); + assert_eq!(admit(12, 5, 10), 0); + let mut r = Rec::default(); + begin(&mut r, 0); + for _ in 0..6 { + push_to(&mut r, draw(1, &[], vec![]), 4); + } + assert_eq!((r.ops.len(), r.dropped, r.work), (4, 3, 3), "begin + 3 draws kept, 3 dropped"); + close(&mut r); + let ops = r.closed.as_ref().unwrap().0.clone(); + assert!(matches!(ops.last(), Some(Op::End)), "the end is kept past the bound"); + // a frame of 6 at most: the first list whole (5), one operation of the second + let mut f = Frame::default(); + f.submit(1, vec![(0xa, part(&r)), (0xb, part(&r))], false, 6); + assert_eq!((f.ops, f.truncated, f.dropped, f.work), (6, 4, 6, 3 + 0)); + f.submit(1, vec![(0xc, part(&r))], false, 6); + assert_eq!((f.ops, f.truncated), (6, 9)); + assert_eq!(flatten(&f.items).iter().filter(|e| matches!(e, Entry::Op { .. })).count(), 6); + } +} diff --git a/crates/xcl/src/hle/d3d12x/clamp.rs b/crates/xcl/src/hle/d3d12x/clamp.rs new file mode 100644 index 0000000000..d18cf537ea --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/clamp.rs @@ -0,0 +1,371 @@ +//! Indirect compute dispatches with group counts D3D12 takes (`XCL_CLAMP_INDIRECT=1`: on). +//! +//! The console runs up to 2^32 − 1 groups a dimension; D3D12 takes 65 535, and past that the +//! dispatch is undefined – on an NVIDIA GPU it ran on until the driver reset the device +//! (0x887A0006). A retail game's world loading dispatches a compute program indirectly with +//! 72 512 × 1 × 1 and 75 072 × 1 × 1 groups, counts another dispatch wrote, so the CPU never sees +//! them. +//! +//! Before such a dispatch a one-thread pass reads its three counts and writes the ones to +//! dispatch into a slot of XCL's own buffer: more than 65 535 in X with 1 in Y folded into Y, +//! with the console's count written into the dispatch's io (`recomp::IO_GROUP_LIMIT`: the +//! program takes its group in X from both and leaves out the groups past the count), any other +//! count past 65 535 clamped. The dispatch then reads the slot. How many were folded and clamped, +//! and the latest counts, are kept in the buffer's first 32 bytes and logged now and then (the +//! buffer is CPU-visible memory, a custom heap). +//! +//! Counts that need folding or clamping and still give more groups in all than a dispatch may +//! have (`indirect_guard::max_groups`) are not counts: the bits of 1.0f in X are 16 257 rows of +//! 65 535 groups once folded. Such a dispatch gets no groups (`bind::fold` decides the same on +//! the CPU). + +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +/// Slots of 16 bytes after the header; reused in turn (a slot is read by the dispatch recorded +/// right after it is written, long before 65 536 more indirect dispatches come). +const SLOTS: u64 = 1 << 16; +/// Counts clamped (count, the last x, y, z), folded (count, the last x) and left out (count, +/// the last x) – 32 bytes. +const HEADER: u64 = 32; + +const HLSL: &str = r#" +#define RS "RootConstants(num32BitConstants=2, b0), UAV(u0), UAV(u1), UAV(u2)" +cbuffer C : register(b0) { uint slot; uint bound; }; +RWByteAddressBuffer src : register(u0); +RWByteAddressBuffer dst : register(u1); +RWByteAddressBuffer io : register(u2); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint3 g = src.Load3(0); + uint3 c; + uint folded = 0u; + // rows of 65 535 groups (a ceiling without an addition that could wrap near 2^32) + uint rows = g.x / 65535u + (g.x % 65535u != 0u ? 1u : 0u); + if (g.x > 65535u && g.y == 1u && g.z <= 65535u && rows <= 65535u) { + // more groups in X than D3D12 takes: folded into Y, the program told the count + // (as `bind::fold` does on the CPU) + folded = g.x; + c = uint3(65535u, rows, g.z); + } else { + c = min(g, 65535u); + } + // more groups in all than a dispatch may have (`bound`: the guard's, and the one row more a + // fold can add): what lies where the counts should be is something else, and nothing runs. + // (No count is over 65 535 here, so the product of two fits 32 bits.) + bool left = any(c != g) && c.z != 0u && c.x * c.y > bound / c.z; + if (left) { + folded = 0u; + c = uint3(0u, 0u, 0u); + } + io.Store(0, folded); + if (left) { + uint n; + dst.InterlockedAdd(24, 1, n); + dst.Store(28, g.x); + } else if (folded != 0u) { + uint n; + dst.InterlockedAdd(16, 1, n); + dst.Store(20, g.x); + } else if (any(c != g)) { + uint n; + dst.InterlockedAdd(0, 1, n); + dst.Store3(4, g); + } + dst.Store3(32 + slot * 16, c); +} +"#; + +struct Clamp { + rs: ID3D12RootSignature, + pso: ID3D12PipelineState, + buf: ID3D12Resource, + gpu: u64, + cpu: *const u32, +} +// SAFETY: D3D12 objects are free-threaded; `cpu` is the persistent map of `buf`, only read +unsafe impl Send for Clamp {} +unsafe impl Sync for Clamp {} + +/// `XCL_CLAMP_INDIRECT=1`. Off unless asked for: with the pass on, a retail title's first world +/// frames ended in a device removal on an NVIDIA GPU (0x887A0006 eight seconds after the pass +/// first ran, the driver's breadcrumbs inside a Dispatch; a run of the same build with the pass +/// off had none). Arguments that are not counts reach the pass there (0 x 1 065 353 216 x 16 was +/// logged), which is what the bound on the groups in all is for – until a run with the pass on +/// shows that this was all of it, the counts go to the PC as the title gave them. +pub fn enabled() -> bool { + static E: OnceLock = OnceLock::new(); + *E.get_or_init(|| std::env::var("XCL_CLAMP_INDIRECT").is_ok_and(|v| v.trim() == "1")) +} + +fn get(list: &ID3D12GraphicsCommandList) -> Option<&'static Clamp> { + static C: OnceLock> = OnceLock::new(); + C.get_or_init(|| match unsafe { make(list) } { + Ok(c) => { + crate::xlog_info!("D3D12.X: indirect dispatches past 65535 groups a dimension are folded or clamped on the GPU"); + Some(c) + } + Err(e) => { + crate::xlog_warn!("D3D12.X: indirect dispatches are not clamped: {e}"); + None + } + }) + .as_ref() +} + +unsafe fn make(list: &ID3D12GraphicsCommandList) -> Result { + let mut dev: Option = None; + list.GetDevice(&mut dev).map_err(|e| e.to_string())?; + let dev = dev.ok_or("no device")?; + let dxil = crate::gpu::recomp::dxc::compile(HLSL, "main", "cs_6_0", &[])?; + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).map_err(|e| format!("root signature: {e}"))?; + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const c_void, BytecodeLength: dxil.len() }, + ..Default::default() + }; + let pso: Result = dev.CreateComputePipelineState(&desc); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + let pso = pso.map_err(|e| format!("pipeline: {e}"))?; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let bdesc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: HEADER + SLOTS * 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buf: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &bdesc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("buffer: {e}"))?; + let buf = buf.ok_or("buffer")?; + let mut p: *mut c_void = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).map_err(|e| format!("map: {e}"))?; + std::ptr::write_bytes(p as *mut u8, 0, HEADER as usize); + Ok(Clamp { rs, pso, gpu: buf.GetGPUVirtualAddress(), buf, cpu: p as *const u32 }) +} + +fn transition(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: unsafe { std::mem::transmute_copy(res) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + } +} + +/// Before one indirect dispatch whose counts are at `args` + `off` (a buffer that takes UAV +/// access): the counts as D3D12 takes them – more than 65 535 in X (1 in Y) folded into Y with +/// the console's count written to `io_limit` (the dispatch's `recomp::IO_GROUP_LIMIT` word, 0 +/// otherwise), any other count past 65 535 clamped – in a slot of XCL's buffer, which is +/// returned with the slot's offset, in INDIRECT_ARGUMENT state; `done` returns it to UAV after +/// the dispatch. None: left as it was (the caller dispatches from `args`). The list's compute +/// root signature, root arguments and pipeline are changed: the caller sets its own again. +pub unsafe fn before(list: &ID3D12GraphicsCommandList, args: usize, off: u64, io_limit: u64) -> Option<(usize, u64)> { + if !enabled() { + return None; + } + pass(list, args, off, io_limit, super::indirect_guard::max_groups()) +} + +/// `before` with the pass on and `most` groups in all for a dispatch it folds or clamps. +unsafe fn pass(list: &ID3D12GraphicsCommandList, args: usize, off: u64, io_limit: u64, most: u32) -> Option<(usize, u64)> { + let raw = args as *mut c_void; + let res = ID3D12Resource::from_raw_borrowed(&raw)?; + let d = res.GetDesc(); + if d.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 || off % 4 != 0 || off + 12 > d.Width { + static N: AtomicU32 = AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: an indirect dispatch's arguments ({:?}, flags {:#x}, offset {off:#x}) cannot be clamped", d.Dimension, d.Flags.0); + } + return None; + } + let c = get(list)?; + static NEXT: AtomicU64 = AtomicU64::new(0); + let slot = NEXT.fetch_add(1, Ordering::Relaxed) % SLOTS; + let uav = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) } }; + // the counts were written as UAVs just before (by `indirect_guard`'s pass): read after that + list.ResourceBarrier(std::slice::from_ref(&uav)); + // COMMON at the list's start: promoted to UAV by its first use + list.SetComputeRootSignature(&c.rs); + set_pipeline(list, &c.pso); + list.SetComputeRoot32BitConstant(0, slot as u32, 0); + // (as `bind::fold_counts_within` bounds the product) + list.SetComputeRoot32BitConstant(0, most.saturating_add(crate::gpu::recomp::FOLD_X), 1); + list.SetComputeRootUnorderedAccessView(1, res.GetGPUVirtualAddress() + off); + list.SetComputeRootUnorderedAccessView(2, c.gpu); + list.SetComputeRootUnorderedAccessView(3, io_limit); + list.Dispatch(1, 1, 1); + // the slot for the dispatch's arguments; the io word for its program (a UAV barrier on all) + barrier(list, &c.buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + list.ResourceBarrier(std::slice::from_ref(&uav)); + report(c); + Some((c.buf.as_raw() as usize, HEADER + slot * 16)) +} + +/// After the dispatch `before` clamped: XCL's buffer back in UAV state. +pub unsafe fn done(list: &ID3D12GraphicsCommandList) { + if let Some(c) = get(list) { + barrier(list, &c.buf, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } +} + +/// The pass's pipeline on `list`: on a list XCL adopted (a title's) past the hook of a title's +/// SetPipelineState, which would make it the list's bound pipeline (as `indirect_guard` and +/// `dispatch_chain` set theirs). +unsafe fn set_pipeline(list: &ID3D12GraphicsCommandList, pso: &ID3D12PipelineState) { + if super::real::is_adopted(list.as_raw()) { + super::list_x::set_compute_pipeline(list.as_raw(), pso.as_raw()); + } else { + list.SetPipelineState(pso); + } +} + +/// A transition of XCL's buffer on `list`: on an adopted list past the hook of a title's +/// ResourceBarrier, which takes the console's barriers. +unsafe fn barrier(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + if super::real::is_adopted(list.as_raw()) { + super::list_x::transition(list.as_raw(), res.as_raw() as usize, before, after); + } else { + list.ResourceBarrier(&[transition(res, before, after)]); + } +} + +/// The counts the GPU had to change so far: logged when more were changed (at most every 2 s). +fn report(c: &Clamp) { + static SEEN: AtomicU32 = AtomicU32::new(0); + static LAST: Mutex> = Mutex::new(None); + let mut l = LAST.lock().unwrap(); + if l.is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(2)) { + return; + } + *l = Some(std::time::Instant::now()); + // SAFETY: the mapped header of `buf` (16 bytes) + let w = |k: usize| unsafe { std::ptr::read_volatile(c.cpu.add(k)) }; + let n = w(0); + if n != SEEN.swap(n, Ordering::Relaxed) { + crate::xlog_warn!("D3D12.X: {n} indirect dispatches had group counts clamped so far (the latest asked for {}x{}x{})", w(1), w(2), w(3)); + } + static FOLDED: AtomicU32 = AtomicU32::new(0); + let f = w(4); + if f != FOLDED.swap(f, Ordering::Relaxed) { + crate::xlog_info!("D3D12.X: {f} indirect dispatches folded so far (the latest of {} groups in X)", w(5)); + } + static LEFT: AtomicU32 = AtomicU32::new(0); + let l = w(6); + if l != LEFT.swap(l, Ordering::Relaxed) { + crate::xlog_warn!("D3D12.X: {l} indirect dispatches left out so far: more groups than a dispatch may have (XCL_INDIRECT_MAX_GROUPS; the latest with {:#x} in X)", w(7)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A CPU-visible buffer that takes UAV access (a custom heap), mapped. + unsafe fn visible(dev: &ID3D12Device, bytes: u64) -> (ID3D12Resource, *mut u32) { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buf: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf).unwrap(); + let buf = buf.unwrap(); + let mut p: *mut c_void = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).unwrap(); + (buf, p as *mut u32) + } + + /// The pass writes the counts D3D12 takes into its slot: 72 512 × 1 × 1 folded into + /// 65 535 × 2 × 1 with 72 512 in io; 70 000 × 2 × 1 clamped with 0 in io; 300 × 4 × 2 as + /// it was; and no groups for counts that would still run more than a dispatch may have (the + /// bits of 1.0f in X; 65 535 × 65 535 × 16 once clamped). + #[test] + fn indirect_group_counts_are_folded_or_clamped_on_the_gpu() { + use crate::gpu::recomp::runner; + unsafe { + let dev = match (runner::device(), crate::gpu::recomp::dxc::location()) { + (Ok(d), Ok(_)) => d, + _ => { + runner::skip_test("no GPU or DXC"); + return; + } + }; + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + // (65 535² would fold into exactly 65 535 rows, far more groups than a dispatch may + // have; one more or u32::MAX would need 65 536 rows – clamped to one row, as + // `bind::fold` does; 2^22 is the most that is folded) + for (k, (args, want, io_want)) in [ + ([72_512u32, 1, 1], [65_535u32, 2, 1], 72_512u32), + ([70_000, 2, 1], [65_535, 2, 1], 0), + ([300, 4, 2], [300, 4, 2], 0), + ([1 << 22, 1, 1], [65_535, 65, 1], 1 << 22), + ([(1 << 22) + 65_536, 1, 1], [0, 0, 0], 0), + ([65_535 * 65_535, 1, 1], [0, 0, 0], 0), + ([0x3F80_0000, 1, 1], [0, 0, 0], 0), + ([70_000, 70_000, 16], [0, 0, 0], 0), + ([70_000, 70_000, 0], [65_535, 65_535, 0], 0), + ([65_535 * 65_535 + 1, 1, 1], [65_535, 1, 1], 0), + ([u32::MAX, 1, 1], [65_535, 1, 1], 0), + ] + .into_iter() + .enumerate() + { + let (limit, groups) = super::super::bind::fold(args[0], args[1], args[2]); + assert_eq!((groups, limit), (want, io_want), "{args:?}: the CPU's fold, which the GPU's must match"); + let (a, ap) = visible(&dev, 256); + let (io, iop) = visible(&dev, 256); + std::ptr::copy_nonoverlapping(args.as_ptr(), ap.add(16), 3); + *iop = 0xDEAD; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let (buf, off) = pass(&list, a.as_raw() as usize, 64, io.GetGPUVirtualAddress(), super::super::indirect_guard::max_groups()).expect("clamped"); + done(&list); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, k as u64 + 1).unwrap(); + let t = std::time::Instant::now(); + while fence.GetCompletedValue() < k as u64 + 1 { + assert!(t.elapsed().as_secs() < 10, "the pass did not finish"); + std::thread::yield_now(); + } + let c = get(&list).unwrap(); + assert_eq!(buf, c.buf.as_raw() as usize); + let slot = c.cpu.add(off as usize / 4); + let got = [*slot, *slot.add(1), *slot.add(2)]; + assert_eq!(got, want, "{args:?}"); + assert_eq!(*iop, io_want, "{args:?}: io"); + } + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 60a3136444..3c9dd506b8 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -25,7 +25,8 @@ //! Without the shared heap (it could not be made) a heap keeps its own PC heap: SRV at 2k, //! UAV at 2k + 1. -use std::sync::atomic::{AtomicU64, Ordering}; +use std::collections::{HashMap, VecDeque}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering::{self, Acquire, Relaxed, Release}}; use std::sync::Mutex; use windows::core::Interface; @@ -170,6 +171,90 @@ impl Drop for PublishLease { } } +/// Released descriptor range in `GLOBAL` or `GLOBAL_SAMPLER` awaiting active GPU queues before +/// being returned to `free` (prevents overwriting shader-visible descriptors still read in flight). +struct RetiredRange { + first: u32, + count: u32, + /// Fence marks across all live queues on the device (`None` = signal failed, keep held). + marks: Option>, +} + +/// Pop retired ranges whose queue fences have all completed. A `None` entry (failed signal) stays +/// quarantined without wedging subsequent healthy ranges. +fn pop_ready_ranges( + retired: &mut VecDeque>, + mut completed: impl FnMut(&F) -> u64, +) -> Vec<(u32, u32)> { + let mut ready = Vec::new(); + let mut kept = VecDeque::new(); + while let Some(r) = retired.pop_front() { + match r.marks.as_ref() { + Some(m) if m.iter().all(|(f, v)| completed(f) >= *v) => ready.push((r.first, r.count)), + None => kept.push_back(r), + Some(_) => { + kept.push_back(r); + break; + } + } + } + while let Some(r) = kept.pop_back() { + retired.push_front(r); + } + ready +} + +struct QueueFences(HashMap); + +// D3D12 fences are free-threaded; accessed only under HEAP_FENCES lock. +unsafe impl Send for QueueFences {} + +static HEAP_FENCES: Mutex> = Mutex::new(None); +static GLOBAL_RETIRED: AtomicBool = AtomicBool::new(false); +/// Serialises `drain_global_retired` across `fill_nulls` and `merge_release` so a concurrent +/// `slot()` cannot miss ranges popped from `GLOBAL.retired` before they reach `GLOBAL.free`. +/// Lock order: `GLOBAL_DRAIN` -> `SLOT_WRITES` -> `GLOBAL` (never held alongside `HEAPS`). +static GLOBAL_DRAIN: Mutex<()> = Mutex::new(()); +/// Incremented under `GLOBAL` whenever descriptors are merged back into `GLOBAL.free`. +static GLOBAL_DRAIN_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Signal every known live title queue belonging to `dev` (called outside `GLOBAL`, +/// `GLOBAL_SAMPLER`, `HEAPS`, and `SLOT_WRITES`). Returns `Some(vec![])` when no live queues +/// exist for `dev`, or `None` if fence creation or signaling fails so released descriptor ranges +/// stay safely quarantined. +unsafe fn signal_live_queues_for(dev: &ID3D12Device) -> Option> { + let dev_raw = dev.as_raw(); + let mut queues: Vec<(usize, ID3D12CommandQueue)> = Vec::new(); + for q in super::present::known_queues_held() { + let mut qdev: Option = None; + if q.GetDevice(&mut qdev).is_ok() && qdev.as_ref().is_some_and(|d| d.as_raw() == dev_raw) { + queues.push((q.as_raw() as usize, q)); + } + } + if queues.is_empty() { + return Some(Vec::new()); + } + let mut guard = HEAP_FENCES.lock().unwrap(); + let map = &mut guard.get_or_insert_with(|| QueueFences(HashMap::new())).0; + let mut marks = Vec::with_capacity(queues.len()); + for (key, q) in queues { + let (fence, val) = match map.entry(key) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(e) => { + let f: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + e.insert((f, 0)) + } + }; + let next = *val + 1; + if super::real::native_queue_signal(&q, &*fence, next).is_err() { + return None; + } + *val = next; + marks.push((fence.clone(), next)); + } + Some(marks) +} + /// The shader-visible PC heap of all console view heaps. struct Global { dev: ID3D12Device, @@ -179,8 +264,13 @@ struct Global { inc: u32, cap: u32, next: u32, - /// released ranges (first, count) + /// released ranges (first, count) proven GPU-idle free: Vec<(u32, u32)>, + /// released ranges awaiting live GPU queue completion before nulling and entering `free` + retired: VecDeque>, + /// a CPU-only heap of `NULL_BLOCK` null views (even SRV, odd UAV) and its start: copied over + /// every range of the shared heap that is not handed out (`fill_nulls`) + nulls: Option<(ID3D12DescriptorHeap, u64)>, leases: PublishLeases, } @@ -197,6 +287,141 @@ pub const GLOBAL_MAX: u32 = 1_000_000; // smaller than that bound: an index past the heap's end hangs NVIDIA GPUs, which took 1 000 000 // while the bound was 2^21 – a raw console T# of a texture at 256–512 MB passed it.) +/// null views in the CPU-only heap the shared heap's free ranges are filled from +const NULL_BLOCK: u32 = 4096; + +/// Copy null views (`nulls`, a CPU-only heap of `NULL_BLOCK` of them, even SRV, odd UAV) over +/// descriptors `from..to` of the heap at `cpu`, a block at a time; an odd `from` starts from +/// the block's first UAV, so every even descriptor stays an SRV and every odd one a UAV, as the +/// SRV / UAV pair of a console slot. +unsafe fn fill_nulls(dev: &ID3D12Device, cpu: u64, inc: u32, from: u32, to: u32, nulls: u64) { + let mut at = from; + while at < to { + let skew = at % 2; + let n = (NULL_BLOCK - skew).min(to - at); + copy_views(dev, n, cpu + at as u64 * inc as u64, nulls + skew as u64 * inc as u64); + at += n; + } +} + +/// CopyDescriptorsSimple of `n` view descriptors, past XCL's hook of an adopted device (which +/// looks up the console heaps for each call: `HEAPS`, then `GLOBAL`), so that it can be made +/// with `SLOT_WRITES` held. +unsafe fn copy_views(dev: &ID3D12Device, n: u32, dst: u64, src: u64) { + let raw = dev.as_raw(); + if super::real::is_adopted(raw) { + let f: unsafe extern "system" fn(*mut std::ffi::c_void, u32, u64, u64, u32) = std::mem::transmute(super::real::orig_fn(raw, 24)); + return f(raw, n, dst, src, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32); + } + dev.CopyDescriptorsSimple(n, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); +} + +/// Which PC resource the descriptor at each index of the shared heap names, and the other way +/// round – so that the views of a resource that is destroyed can be made null views. +/// +/// A title keeps T#s (each with an index in the shared heap) in its own memory, and its shaders +/// read them from there. On the console a T# of a released texture still names memory (leftover +/// bytes, nothing faults), and a title can sample a texture it has released (a material table +/// not updated yet, a sample of weight zero). On the PC the slot would keep a descriptor of a +/// destroyed resource: a shader that samples it touches an unmapped address. +struct Names { + /// index → the resource its descriptor names (0: none, a null view, or not known; `GONE`: the + /// null view `resource_gone` wrote there); the truth + slots: Vec, + /// resource → indexes that named it (some may name another since: `slots` says) + by: super::sharded::Sharded>, +} + +impl Names { + fn new(n: usize) -> Names { + Names { slots: (0..n).map(|_| AtomicUsize::new(0)).collect(), by: super::sharded::Sharded::new() } + } + + fn name(&self, i: u32) -> usize { + self.slots.get(i as usize).map_or(0, |s| s.load(Relaxed)) + } + + /// The descriptor at `i` names `res` now (0: none; `GONE`: it was made the null view of a + /// destroyed resource's). With `SLOT_WRITES` held, along with the write of the descriptor. + fn note(&self, i: u32, res: usize) { + let Some(s) = self.slots.get(i as usize) else { return }; + if s.swap(res, Relaxed) == res || res == 0 || res == GONE { + return; + } + self.by.with(res, |v| { + v.push(i); + // a resource whose views are made again and again: only the indexes that still name it + if v.len() >= 64 && v.len().is_power_of_two() { + v.retain(|&j| self.name(j) == res); + v.sort_unstable(); + v.dedup(); + } + }); + } + + fn clear(&self, from: u32, to: u32) { + for i in from..to { + if let Some(s) = self.slots.get(i as usize) { + s.store(0, Relaxed); + } + } + } + + /// The indexes whose descriptor may name `res` (None: none ever did – the common case, one + /// lookup), forgotten here. + fn candidates(&self, res: usize) -> Option> { + self.by.remove(res) + } + + /// Whether the descriptor at `i` still names `res`: then it is `GONE` from now on (the caller + /// writes a null view there, with `SLOT_WRITES` held). One overwritten since names another + /// resource and stays. + fn claim(&self, i: u32, res: usize) -> bool { + self.slots.get(i as usize).is_some_and(|s| s.compare_exchange(res, GONE, Relaxed, Relaxed).is_ok()) + } +} + +/// What `Names` (and `names_of`) give for a descriptor `resource_gone` made a null view. The +/// title's own CPU-only mirror slot still holds the destroyed resource's view there, so a copy +/// of that slot writes the null view in the shared heap instead of the mirror's (`publish_range`). +pub const GONE: usize = usize::MAX; + +/// (made with the first view written to the shared heap: 8 bytes an index) +static NAMES: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Writes of descriptors into the shared heap and of what they name (`NAMES`), one at a time: +/// a null view for a destroyed resource must not come over a view another thread just wrote. +/// Taken before `GLOBAL` or `HEAPS`, never with them held. +static SLOT_WRITES: Mutex<()> = Mutex::new(()); + +fn names() -> &'static Names { + NAMES.get_or_init(|| Names::new(GLOBAL_MAX as usize)) +} + +/// What null views are copied from: the device, the shared heap's start and increment, the +/// null views' start (None: no shared heap, or no null views). +fn null_source() -> Option<(ID3D12Device, u64, u32, u64)> { + GLOBAL.lock().unwrap().as_ref().and_then(|s| s.nulls.as_ref().map(|n| (s.dev.clone(), s.cpu, s.inc, n.1))) +} + +/// The PC resource `res` is destroyed next: every descriptor of the shared heap that still names +/// it becomes the null view of its kind (SRV at even indexes, UAV at odd). The number of them. +/// A resource that never had a view in the shared heap costs one lookup. +pub fn resource_gone(res: usize) -> usize { + let Some(n) = NAMES.get() else { return 0 }; + let Some(candidates) = n.candidates(res) else { return 0 }; + let Some((dev, cpu, inc, nulls)) = null_source() else { return 0 }; + let _w = SLOT_WRITES.lock().unwrap(); + let mut nulled = 0; + for i in candidates { + if n.claim(i, res) { + unsafe { fill_nulls(&dev, cpu, inc, i, i + 1, nulls) }; + nulled += 1; + } + } + nulled +} + /// view slots per page of a heap's place in the shared heap (2 PC descriptors each) pub const PAGE_SLOTS: u32 = 256; /// a page with no place in the shared heap yet @@ -249,29 +474,58 @@ unsafe fn global_cap(dev: &ID3D12Device) -> u32 { /// The shared shader-visible heap, made on first use. False: there is none (it could not be /// made) – view heaps then keep their own. pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { - use std::sync::atomic::Ordering::Relaxed; - let mut g = GLOBAL.lock().unwrap(); - if g.is_none() { + { + let g = GLOBAL.lock().unwrap(); + if g.is_some() { + return true; + } if GLOBAL_FAILED.load(Relaxed) { return false; } - let cap = global_cap(dev); - let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: cap, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }; - let heap: ID3D12DescriptorHeap = match dev.CreateDescriptorHeap(&d) { - Ok(h) => h, - Err(e) => { - GLOBAL_FAILED.store(true, Relaxed); - crate::xlog_warn!("console descriptor heaps: no shared shader-visible heap of {cap} ({e}) – each keeps its own"); - return false; - } - }; - crate::xlog_info!("console descriptor heaps: one shader-visible PC heap of {cap} view descriptors for all of them"); - let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - null_views(dev, heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, inc); - null_window_views(dev, heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, inc); + } + // Made and filled without `GLOBAL` held: the device may be adopted, and its descriptor hooks + // look up the console heaps (`HEAPS`, then `GLOBAL`). Two threads that get here at once both + // make one; the first to store it wins. + let cap = global_cap(dev); + let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: cap, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }; + let heap = match dev.CreateDescriptorHeap::(&d) { + Ok(h) => h, + Err(e) => { + GLOBAL_FAILED.store(true, Relaxed); + crate::xlog_warn!("console descriptor heaps: no shared shader-visible heap of {cap} ({e}) – each keeps its own"); + return false; + } + }; + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + let cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr as u64; + let start = std::time::Instant::now(); + null_views(dev, cpu, inc); + null_window_views(dev, cpu, inc); + // D3D12 leaves a new heap's descriptors undefined: every one XCL has not handed out holds a + // null view, so an index a shader takes from a stale or garbage T# reads zeros, never a + // descriptor of whatever the memory held (the memory windows' views come over theirs next) + let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: NULL_BLOCK, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0 }; + let nulls = dev.CreateDescriptorHeap::(&d).ok().map(|h| { + let at = h.GetCPUDescriptorHandleForHeapStart().ptr as u64; + null_views_in(dev, at, inc, NULL_BLOCK as u64); + fill_nulls(dev, cpu, inc, crate::gpu::recomp::MEM_HEAP_BASE, cap, at); + (h, at) + }); + crate::xlog_info!( + "console descriptor heaps: one shader-visible PC heap of {cap} view descriptors for all of them ({})", + if nulls.is_some() { format!("null views in the rest, {} ms", start.elapsed().as_millis()) } else { "no null views past the first: no CPU-only heap for them".into() } + ); + if cap < GLOBAL_MAX { + crate::xlog_warn!( + "console descriptor heaps: the shared view heap has {cap} descriptors, fewer than the {GLOBAL_MAX} translated shaders allow for: a texture whose T# index is from {cap} to {} reads past the heap's end (their guard does not cover that)", + GLOBAL_MAX - 1 + ); + } + let mut g = GLOBAL.lock().unwrap(); + if g.is_none() { *g = Some(Global { dev: dev.clone(), - cpu: heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, + cpu, gpu: heap.GetGPUDescriptorHandleForHeapStart().ptr, inc, heap, @@ -279,6 +533,8 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { // the memory windows and their two out-of-range null UAVs come first next: crate::gpu::recomp::MEM_NULL_STORE + 1, free: Vec::new(), + retired: VecDeque::new(), + nulls, leases: PublishLeases::default(), }); } @@ -289,7 +545,12 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { /// console slot: even SRV, odd UAV), where shaders land for a T# of zeros (word 0, the PC index, /// is 0): they read zeros there rather than whatever an unwritten descriptor holds. unsafe fn null_views(dev: &ID3D12Device, cpu: u64, inc: u32) { - for k in 0..crate::gpu::recomp::MEM_HEAP_BASE as u64 { + null_views_in(dev, cpu, inc, crate::gpu::recomp::MEM_HEAP_BASE as u64) +} + +/// `n` null views from `cpu`: even SRV, odd UAV (`null_views`). +unsafe fn null_views_in(dev: &ID3D12Device, cpu: u64, inc: u32, n: u64) { + for k in 0..n { let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + k * inc as u64) as usize }; if k % 2 == 0 { let d = D3D12_SHADER_RESOURCE_VIEW_DESC { @@ -333,8 +594,10 @@ pub fn window_views_failed() -> bool { /// The memory windows' buffers `(resource, bytes)` as raw UAVs at `MEM_HEAP_BASE + k` of the /// shared heap, made now if need be (`Options::heap_windows`: shaders take window k from there). -/// Active windows (`bytes > 0`) in wider layouts (8 / 16) must all have a valid buffer; unused -/// trailing slots (`(0, 0)`) safely alias window 0's buffer. +/// Active windows (`bytes > 0`) in wider layouts (8 / 16) must all have a valid buffer; a slot +/// without one (`(0, 0)`: a window with no memory) gets a null raw UAV – shaders read 0 there and +/// their stores go nowhere. (It once aliased window 0: what was at such an address read window +/// 0's bytes, and GPU writes there overwrote its descriptor heaps.) pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) -> bool { let count = windows.len().max(crate::gpu::uma::MAX_WINDOWS); let complete = count <= crate::gpu::uma::MAX_WINDOWS || windows.iter().all(|&(raw, bytes)| raw != 0 || bytes == 0); @@ -346,11 +609,18 @@ pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) - }; // The device may be adopted: its UAV hook re-enters descriptor bookkeeping. for k in 0..count { - let (raw, bytes) = windows.get(k).copied().filter(|w| w.0 != 0).unwrap_or(windows[0]); + let (raw, bytes) = windows.get(k).copied().unwrap_or((0, 0)); let raw = raw as *mut std::ffi::c_void; - let Some(r) = ID3D12Resource::from_raw_borrowed(&raw) else { continue }; let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + (crate::gpu::recomp::MEM_HEAP_BASE as u64 + k as u64) * inc as u64) as usize }; - device.CreateUnorderedAccessView(r, None::<&ID3D12Resource>, Some(&crate::gpu::recomp::runner::raw_window_uav(bytes as u64)), at); + match ID3D12Resource::from_raw_borrowed(&raw) { + Some(r) => device.CreateUnorderedAccessView(r, None::<&ID3D12Resource>, Some(&crate::gpu::recomp::runner::raw_window_uav(bytes as u64)), at), + None => device.CreateUnorderedAccessView( + None::<&ID3D12Resource>, + None::<&ID3D12Resource>, + Some(&crate::gpu::recomp::runner::raw_window_uav(crate::gpu::uma::MAX_SIZE as u64)), + at, + ), + } } true }; @@ -369,15 +639,46 @@ fn reserve_global(count: u32) -> Option { let (cap, mut next) = (s.cap, s.next); let r = take_range(&mut s.free, &mut next, cap, count); s.next = next; - if r.is_none() { - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0 { - crate::xlog_warn!("console descriptor heaps: the shared heap ({cap}) is full – shaders do not see the views of slots past it"); + let used = in_use(s.next, &s.free); + if r.is_some() { + let placed = PAGES_PLACED.fetch_add(1, Relaxed) + 1; + let marks = marks_passed(used, cap); + if marks > FILL_SAID.fetch_max(marks, Relaxed) { + crate::xlog_info!("console descriptor heaps: the shared heap is past {} % full: {used} of its {cap} descriptors in use, {placed} pages placed", FILL_MARKS[marks - 1]); + } + } else { + let n = NO_ROOM.fetch_add(1, Relaxed) + 1; + if n.is_power_of_two() { + crate::xlog_warn!( + "console descriptor heaps: the shared heap ({cap}) is full – a page of slots found no place there ({n} times so far; {used} descriptors in use, {} pages placed): those slots name the null views at 0 / 1, shaders see none of their views", + PAGES_PLACED.load(Relaxed) + ); } } r } +/// Pages that asked for a place in the shared heap and found no room (each try counts). +static NO_ROOM: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); +/// Pages of console heaps with a place in the shared heap now. +static PAGES_PLACED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); +/// How many of `FILL_MARKS` the log has said the shared heap passed. +static FILL_SAID: AtomicUsize = AtomicUsize::new(0); + +/// How full the shared heap is said to be in the log (percent), each once, the first time. +const FILL_MARKS: [u32; 3] = [50, 75, 90]; + +/// Descriptors of the shared heap handed out: those below the cursor `next` but the released +/// ranges in `free` (the null views and the memory windows at its start count). +fn in_use(next: u32, free: &[(u32, u32)]) -> u32 { + next.saturating_sub(free.iter().map(|&(_, n)| n).sum()) +} + +/// How many of `FILL_MARKS` `used` descriptors of a shared heap of `cap` are past. +fn marks_passed(used: u32, cap: u32) -> usize { + FILL_MARKS.iter().filter(|&&m| used as u64 * 100 > m as u64 * cap as u64).count() +} + /// The place in the shared heap of the page slot `k` of `h` is in – (index of the page's /// first SRV there, the page's first slot) – given now if the page has none yet. None: the /// heap is not in the shared heap, or that is full. @@ -391,14 +692,94 @@ fn page_of(h: &mut Heap, k: u32) -> Option<(u32, u32)> { Some((first, p as u32 * PAGE_SLOTS)) } -/// The shared range starting at `first` (`count` descriptors) is free again. +/// Move completed `GLOBAL.retired` ranges to `GLOBAL.free`, nulling their view descriptors and +/// clearing `NAMES` under `SLOT_WRITES` before another heap can allocate them. Must be called +/// outside `SLOT_WRITES`, `HEAPS`, and `GLOBAL`. +fn drain_global_retired() -> bool { + drain_global_retired_since(GLOBAL_DRAIN_SEQ.load(Acquire)) +} + +fn drain_global_retired_since(before_seq: u64) -> bool { + drain_global_retired_with(before_seq, |dev, cpu, inc, nulls, ready| { + let _w = SLOT_WRITES.lock().unwrap(); + for &(first, count) in ready { + unsafe { fill_nulls(dev, cpu, inc, first, first + count, nulls) }; + if let Some(n) = NAMES.get() { + n.clear(first, first + count); + } + } + }) +} + +fn drain_global_retired_with( + before_seq: u64, + on_nulls: impl FnOnce(&ID3D12Device, u64, u32, u64, &[(u32, u32)]), +) -> bool { + if !GLOBAL_RETIRED.load(Acquire) { + return GLOBAL_DRAIN_SEQ.load(Acquire) != before_seq; + } + let _drain = GLOBAL_DRAIN.lock().unwrap(); + let (ready, nulls_info) = { + let mut g = GLOBAL.lock().unwrap(); + let Some(s) = g.as_mut() else { + GLOBAL_RETIRED.store(false, Release); + return GLOBAL_DRAIN_SEQ.load(Acquire) != before_seq; + }; + let ready = pop_ready_ranges(&mut s.retired, |f| unsafe { super::real::fence_completed(f) }); + if ready.is_empty() { + GLOBAL_RETIRED.store(!s.retired.is_empty(), Release); + return GLOBAL_DRAIN_SEQ.load(Acquire) != before_seq; + } + // Keep `GLOBAL_RETIRED` true across `fill_nulls` until `merge_release` completes. + let nulls_info = s.nulls.as_ref().map(|n| (s.dev.clone(), s.cpu, s.inc, n.1)); + (ready, nulls_info) + }; + if let Some((dev, cpu, inc, nulls)) = nulls_info { + on_nulls(&dev, cpu, inc, nulls, &ready); + } + if let Some(s) = GLOBAL.lock().unwrap().as_mut() { + for (first, count) in ready { + s.leases.release_range(&mut s.free, first, count); + } + GLOBAL_DRAIN_SEQ.fetch_add(1, Release); + GLOBAL_RETIRED.store(!s.retired.is_empty(), Release); + } else { + GLOBAL_RETIRED.store(false, Release); + } + true +} + +/// The shared range starting at `first` (`count` descriptors) is quarantined behind active GPU +/// queues before its views are made null views and it returns to `free`, preventing overwrites +/// of live shader-visible descriptors. pub fn release_global(first: u32, count: u32) { if count == 0 { return; } + let dev = GLOBAL.lock().unwrap().as_ref().map(|s| s.dev.clone()); + let Some(dev) = dev else { return }; + let marks = unsafe { signal_live_queues_for(&dev) }; + if marks.as_ref().is_some_and(Vec::is_empty) { + if let Some((dev, cpu, inc, nulls)) = null_source() { + // (the range is still the released heap's) + let _w = SLOT_WRITES.lock().unwrap(); + unsafe { fill_nulls(&dev, cpu, inc, first, first + count, nulls) }; + if let Some(n) = NAMES.get() { + n.clear(first, first + count); + } + } + if let Some(s) = GLOBAL.lock().unwrap().as_mut() { + s.leases.release_range(&mut s.free, first, count); + GLOBAL_DRAIN_SEQ.fetch_add(1, Release); + } + drain_global_retired(); + return; + } if let Some(s) = GLOBAL.lock().unwrap().as_mut() { - s.leases.release_range(&mut s.free, first, count); + s.retired.push_back(RetiredRange { first, count, marks }); + GLOBAL_RETIRED.store(true, Release); } + drain_global_retired(); } /// Add a released range to `free`, merging the ranges it touches: adjacent releases become @@ -433,17 +814,45 @@ unsafe fn title_memory(u: &crate::gpu::uma::Uma, bytes: usize) -> Option use crate::hle::kernelx::{runtime_alloc, runtime_free, D3D_DESCRIPTOR_HEAP}; let p = runtime_alloc(bytes, D3D_DESCRIPTOR_HEAP)?; let readable = crate::gpu::shader::readable(p, bytes); - if readable && u.window_of(p) == Some(0) && u.window_of(p + bytes - 1) == Some(0) { + if title_memory_fits(u, p, bytes, readable) { return Some(p); } static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 8 { - crate::xlog_warn!("console descriptor heap: the title's memory {p:#x} ({bytes:#x} bytes) not used (window {:?}, committed {readable})", u.window_of(p)); + let (free, largest) = u.sparse_free_in(0); + crate::xlog_warn!( + "console descriptor heap: the title's memory {p:#x} ({bytes:#x} bytes) not used (window {:?}, committed {readable}; window 0 has {} MB free, {} MB at most in one run)", + u.window_of(p), + free >> 20, + largest >> 20 + ); } runtime_free(p, D3D_DESCRIPTOR_HEAP); None } +/// Whether the title's `[p, p + bytes)` can hold a heap's slots: committed (`readable`) and all +/// in window 0. A descriptor table is a 32-bit address, high half 0, which shaders and +/// `words_at` read in window 0 – at `base + (p as u32)`. In another window the tables would name +/// other bytes, and the substitute heap the title then gets does not start at its memory (a +/// retail game asserts that it does). +fn title_memory_fits(u: &crate::gpu::uma::Uma, p: usize, bytes: usize, readable: bool) -> bool { + readable && bytes > 0 && u.window_of(p) == Some(0) && p.checked_add(bytes - 1).is_some_and(|e| u.window_of(e) == Some(0)) +} + +/// PC samplers of a console sampler heap of `n` slots: a shader-visible one gets the 2 048 a +/// shader-visible PC sampler heap holds at most, whatever `n` is. Translated shaders index the +/// bound sampler heap with S# word 3 [10:0] (0..2047), and a title builds S#s itself (a border +/// color pointer there): with only `n` PC samplers an index from `n` on read past the heap's end. +/// The samplers past `n` are the zero sampler; the console heap keeps its `n` slots. +pub fn pc_samplers(n: u32, visible: bool) -> u32 { + if visible { + n.max(D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE) + } else { + n + } +} + /// `obj` is a PC heap from `pc_cpu` / `pc_gpu` (increment `inc`; `pc_gpu` 0 when not shader /// visible) with 2·`n` view descriptors or `n` samplers: give it `n` console slots in /// unified memory. `shared`: its views go to the shared heap (`shared_heap`), a page at a @@ -538,6 +947,7 @@ pub fn free(Taken(h): Taken) { release_global_sampler(f, sampler_page_descriptors(h.n, p as u32)); } else { release_global(f, page_descriptors(h.n, p as u32)); + PAGES_PLACED.fetch_sub(1, Relaxed); } } match h.memory { @@ -553,6 +963,11 @@ pub fn free(Taken(h): Taken) { } } +/// Whether heap `obj` holds samplers, and the 32-bit console address of its slots. +pub fn base(obj: usize) -> Option<(bool, u32)> { + HEAPS.lock().unwrap().iter().find(|h| h.obj == obj).map(|h| (h.sampler, h.shadow as u32)) +} + /// Start of the console slots of heap `obj` (CPU handle = GPU handle on the console). pub fn start(obj: usize) -> Option { HEAPS.lock().unwrap().iter().find(|h| h.obj == obj).map(|h| h.shadow as u64) @@ -652,13 +1067,32 @@ pub(super) fn lease_view_slot(generation: u64, k: u32, pc_srv: u64, shared_srv: Some(ViewSlotLease { pc_srv, shared_srv, index, _device: device, _source_heap: source_heap, _shared_heap: shared_heap }) } +fn finish_view_slot(h: &Heap, k: u32, page: Option<(u32, u32)>) -> Slot { + let uav = ((2 * k + 1) * h.inc) as u64; + let shared = page.and_then(|(first, k0)| { + let g = GLOBAL.lock().unwrap(); + let g = g.as_ref()?; + let i = first + 2 * (k - k0); + Some((i, g.gpu + (i as u64 + 1) * g.inc as u64, g.cpu + i as u64 * g.inc as u64)) + }); + // A heap meant for the shared heap whose page found no room there: lists bind only the + // shared heap, where 2k is another heap's view, a memory window's raw UAV (k from 2 to 9) or + // past the heap's end; its T#s name the null views at 0 / 1 instead, and nothing is copied. + let own = if h.pages.is_empty() { (2 * k, if h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav }, 0) } else { (0, 0, 0) }; + let (index, pc_gpu_uav, shared_srv) = shared.unwrap_or(own); + Slot { generation: h.generation, at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k, remaining: h.n - k } +} + /// The slot behind a console CPU handle (None: not one of XCL's console heaps). A view slot -/// of a heap in the shared heap gets its page's place there now if the page has none yet. +/// of a heap in the shared heap gets its page's place there now if the page has none yet; one +/// whose page finds no room there gets index 0, the null SRV / UAV pair. pub fn slot(cpu: u64) -> Option { + drain_global_retired(); let mut heaps = HEAPS.lock().unwrap(); - let h = heaps.iter_mut().find(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64)?; - let k = ((cpu - h.shadow as u64) / h.slot_bytes() as u64) as u32; - if h.sampler { + let idx = heaps.iter().position(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64)?; + let k = ((cpu - heaps[idx].shadow as u64) / heaps[idx].slot_bytes() as u64) as u32; + if heaps[idx].sampler { + let h = &mut heaps[idx]; let shared = sampler_page_of(h, k).and_then(|(first, k0)| { let g = GLOBAL_SAMPLER.lock().unwrap(); let g = g.as_ref()?; @@ -671,19 +1105,31 @@ pub fn slot(cpu: u64) -> Option { let (index, shared_srv) = shared.unwrap_or_else(|| (sampler_unmapped_index(!h.pages.is_empty(), k), 0)); return Some(Slot { generation: h.generation, at: h.shadow + (k * SAMPLER_SLOT) as usize, index, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, pc_gpu_uav: 0, sampler: true, shared_srv, k, remaining: h.n - k }); } - let uav = ((2 * k + 1) * h.inc) as u64; - let shared = page_of(h, k).and_then(|(first, k0)| { - let g = GLOBAL.lock().unwrap(); - let g = g.as_ref()?; - let i = first + 2 * (k - k0); - Some((i, g.gpu + (i as u64 + 1) * g.inc as u64, g.cpu + i as u64 * g.inc as u64)) - }); - let (index, pc_gpu_uav, shared_srv) = shared.unwrap_or((2 * k, if h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav }, 0)); - Some(Slot { generation: h.generation, at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k, remaining: h.n - k }) + let drain_seq = GLOBAL_DRAIN_SEQ.load(Acquire); + let page = page_of(&mut heaps[idx], k); + if page.is_none() && !heaps[idx].pages.is_empty() { + // Check `GLOBAL_RETIRED` before `GLOBAL_DRAIN_SEQ` (reverse of the Release order in + // `drain_global_retired_with`): observing `GLOBAL_RETIRED == false` guarantees the + // preceding `GLOBAL_DRAIN_SEQ` increment is visible. + if GLOBAL_RETIRED.load(Acquire) { + drop(heaps); + let drained = drain_global_retired_since(drain_seq); + heaps = HEAPS.lock().unwrap(); + let h = heaps.iter_mut().find(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64)?; + let page = if drained || GLOBAL_DRAIN_SEQ.load(Acquire) != drain_seq { page_of(h, k) } else { None }; + return Some(finish_view_slot(h, k, page)); + } + if GLOBAL_DRAIN_SEQ.load(Acquire) != drain_seq { + let page = page_of(&mut heaps[idx], k); + return Some(finish_view_slot(&heaps[idx], k, page)); + } + } + Some(finish_view_slot(&heaps[idx], k, page)) } -/// The view (or sampler) just made in slot `s` (its SRV, or with `uav` its UAV) goes to the shared heap. -pub unsafe fn publish(s: &Slot, uav: bool) { +/// The view (or sampler) just made in slot `s` (its SRV, or with `uav` its UAV) of the PC +/// resource `res` (0: a null view; samplers: 0) goes to the shared heap. +pub unsafe fn publish(s: &Slot, uav: bool, res: usize) { if s.shared_srv == 0 { return; } @@ -735,12 +1181,34 @@ pub unsafe fn publish(s: &Slot, uav: bool) { let Some((dev, _source_owner, _lease, dst, src, ty)) = snapshot else { return; }; - dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, ty); + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER { + dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, ty); + return; + } + // (past the device hook: `SLOT_WRITES` is held, and the lease keeps the index this heap's) + let _w = SLOT_WRITES.lock().unwrap(); + copy_views(&dev, 1, dst, src); + names().note(s.index + uav as u32, res); +} + +/// The PC resources the SRV and the UAV of view slot `s` name in the shared heap (0: not known, +/// a sampler, or the slot has no place there): what `publish_range` takes for a copy of it. +pub fn names_of(s: &Slot) -> (usize, usize) { + if s.sampler { + return (0, 0); + } + match (s.shared_srv, NAMES.get()) { + (0, _) | (_, None) => (0, 0), + (_, Some(n)) => (n.name(s.index), n.name(s.index + 1)), + } } /// `n` view or sampler slots from `first` were copied (in the title's heap): they go to the shared heap, -/// a run per page (a heap's pages lie apart there), stopping at the title heap's end. -pub unsafe fn publish_range(first: &Slot, n: u32) { +/// a run per page (a heap's pages lie apart there), stopping at the title heap's end. `names`: what +/// the source view slots' SRV and UAV name (`names_of`), one pair a slot (none for samplers). A +/// source descriptor that is `GONE` gets the null view in the shared heap, not the copy of the +/// destroyed resource's view the title's heap still holds. +pub unsafe fn publish_range(first: &Slot, n: u32, names: &[(usize, usize)]) { if n == 0 || first.shared_srv == 0 { return; } @@ -812,22 +1280,44 @@ pub unsafe fn publish_range(first: &Slot, n: u32) { let Some((dev, _source_owner, _lease, cpu, inc, runs, ty)) = snapshot else { return; }; + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER { + for (at, src, count) in runs { + dev.CopyDescriptorsSimple( + count, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + at as u64 * inc as u64) as usize }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, + ty, + ); + } + return; + } + // the null views, taken before `SLOT_WRITES` when a source descriptor is `GONE` + let nulls = if names.iter().any(|&(srv, uav)| srv == GONE || uav == GONE) { null_source() } else { None }; + // (past the device hook: `SLOT_WRITES` is held, and the leases keep the indexes this heap's) + let _w = SLOT_WRITES.lock().unwrap(); + let m = self::names(); + let mut done = 0usize; for (at, src, count) in runs { - dev.CopyDescriptorsSimple( - count, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + at as u64 * inc as u64) as usize }, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, - ty, - ); + copy_views(&dev, count, cpu + at as u64 * inc as u64, src); + for j in 0..count / 2 { + let (srv, uav) = names.get(done + j as usize).copied().unwrap_or((0, 0)); + for (i, res) in [(at + 2 * j, srv), (at + 2 * j + 1, uav)] { + if let Some((ndev, ncpu, ninc, nat)) = nulls.as_ref().filter(|_| res == GONE) { + fill_nulls(ndev, *ncpu, *ninc, i, i + 1, *nat); + } + m.note(i, res); + } + } + done += (count / 2) as usize; } } -/// view slot address → the resource its view names (`XCL_TRACE_FRAME` diagnostics) +/// view slot address → the resource its view names (`XCL_TRACE_FRAME`, `XCL_DUMP_TARGETS`) static RES: Mutex>> = Mutex::new(None); /// The view in slot `s` names `res` (0: none). pub fn note_resource(s: &Slot, res: usize) { - if s.sampler || !super::present::trace_frame() { + if s.sampler || !(super::present::trace_frame() || super::targets::enabled() || super::capture::enabled()) { return; } let mut g = RES.lock().unwrap(); @@ -844,6 +1334,13 @@ pub fn resource_at(at: usize) -> Option { RES.lock().unwrap().as_ref()?.get(&at).copied() } +/// The PC resource the descriptor at index `i` of the shared heap names (0: none or not known; +/// `GONE`: the null view of a destroyed resource) – what a T# with that index in word 0 samples, +/// whichever slot the T# lies in (`XCL_TRACE_FRAME` diagnostics). +pub fn named_by_index(i: u32) -> usize { + NAMES.get().map_or(0, |n| n.name(i)) +} + pub fn write(s: &Slot, words: &[u32]) { let n = words.len().min(if s.sampler { 4 } else { 8 }); unsafe { std::ptr::copy_nonoverlapping(words.as_ptr(), s.at as *mut u32, n) }; @@ -914,7 +1411,8 @@ pub fn census() { let mut examples: Vec<(u32, u32)> = Vec::new(); let own_index = |k: u32| match h.pages.get((k / PAGE_SLOTS) as usize) { Some(&f) if f != UNMAPPED => f + 2 * (k % PAGE_SLOTS), - _ => 2 * k, + Some(_) => 0, + None => 2 * k, }; for k in 0..h.n { let w = unsafe { std::slice::from_raw_parts((h.shadow + (k * SLOT) as usize) as *const u32, 8) }; @@ -1019,6 +1517,7 @@ struct GlobalSampler { cap: u32, next: u32, free: Vec<(u32, u32)>, + retired: VecDeque>, leases: PublishLeases, } @@ -1058,18 +1557,7 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { }; let cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr as u64; let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); - let zero = D3D12_SAMPLER_DESC { - Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, - AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP, - AddressV: D3D12_TEXTURE_ADDRESS_MODE_WRAP, - AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP, - MipLODBias: 0.0, - MaxAnisotropy: 1, - ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, - BorderColor: [0.0; 4], - MinLOD: 0.0, - MaxLOD: 0.0, - }; + let zero = zero_sampler(); for k in 0..GLOBAL_SAMPLER_MAX as u64 { dev.CreateSampler(&zero, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + k * inc as u64) as usize }); } @@ -1083,6 +1571,7 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { // Reserve slot 0 as the immutable point-wrap zero sampler for empty/zeroed S# entries. next: 1, free: Vec::new(), + retired: VecDeque::new(), leases: PublishLeases::default(), }); } @@ -1092,6 +1581,9 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { fn reserve_global_sampler(count: u32) -> Option { let mut g = GLOBAL_SAMPLER.lock().unwrap(); let s = g.as_mut()?; + for (first, n) in pop_ready_ranges(&mut s.retired, |f| unsafe { super::real::fence_completed(f) }) { + s.leases.release_range(&mut s.free, first, n); + } let (cap, mut next) = (s.cap, s.next); let r = take_range(&mut s.free, &mut next, cap, count); s.next = next; @@ -1118,8 +1610,18 @@ fn release_global_sampler(first: u32, count: u32) { if count == 0 { return; } + let dev = GLOBAL_SAMPLER.lock().unwrap().as_ref().map(|s| s.dev.clone()); + let Some(dev) = dev else { return }; + let marks = unsafe { signal_live_queues_for(&dev) }; if let Some(s) = GLOBAL_SAMPLER.lock().unwrap().as_mut() { - s.leases.release_range(&mut s.free, first, count); + if marks.as_ref().is_some_and(Vec::is_empty) { + s.leases.release_range(&mut s.free, first, count); + } else { + s.retired.push_back(RetiredRange { first, count, marks }); + } + for (f, n) in pop_ready_ranges(&mut s.retired, |f| unsafe { super::real::fence_completed(f) }) { + s.leases.release_range(&mut s.free, f, n); + } } } @@ -1133,6 +1635,34 @@ pub fn in_global_sampler(obj: usize) -> bool { HEAPS.lock().unwrap().iter().any(|h| h.obj == obj && h.sampler && !h.pages.is_empty()) } +/// The zero sampler: what an S# of zeros is on the console (point filtering, wrap, mip 0 only), +/// and what a shader gets whose S# XCL takes for a heap entry it is not (entry 0). +/// `XCL_ZERO_SAMPLER_LINEAR=1` (a diagnostic): linear filtering, clamp, every mip instead; a +/// picture that changes with it samples through the zero sampler. +pub(super) fn zero_sampler() -> D3D12_SAMPLER_DESC { + static LINEAR: std::sync::OnceLock = std::sync::OnceLock::new(); + let linear = *LINEAR.get_or_init(|| { + let on = std::env::var("XCL_ZERO_SAMPLER_LINEAR").is_ok_and(|v| v.trim() == "1"); + if on { + crate::xlog_info!("D3D12.X: XCL_ZERO_SAMPLER_LINEAR=1 - the zero sampler is linear, clamp, all mips (a diagnostic)"); + } + on + }); + let address = if linear { D3D12_TEXTURE_ADDRESS_MODE_CLAMP } else { D3D12_TEXTURE_ADDRESS_MODE_WRAP }; + D3D12_SAMPLER_DESC { + Filter: if linear { D3D12_FILTER_MIN_MAG_MIP_LINEAR } else { D3D12_FILTER_MIN_MAG_MIP_POINT }, + AddressU: address, + AddressV: address, + AddressW: address, + MipLODBias: 0.0, + MaxAnisotropy: 1, + ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, + BorderColor: [0.0; 4], + MinLOD: 0.0, + MaxLOD: if linear { 1000.0 } else { 0.0 }, + } +} + #[cfg(test)] mod tests { use super::*; @@ -1154,6 +1684,27 @@ mod tests { assert!(bound < cap, "shaders accept indices up to {bound}, the shared heap holds {cap}"); } + /// The title's memory holds a heap only when committed and all in window 0: where a Series X + /// run's view heap was (0xf2e00000 into window 0), not where a Series S run's was (window 1, + /// 0x1400000 in), nor across the end of window 0, nor outside unified memory. + #[test] + fn title_memory_holds_a_heap_only_in_window_0() { + use crate::gpu::uma::{Uma, WINDOW}; + let u = Uma::for_runtime_windows(16 << 20, 512 << 20, 16).expect("16-window aperture"); + let b = u.base(); + let view_heap = (1_245_184 * SLOT) as usize; // 0x2600000 + assert!(title_memory_fits(&u, b + 0xf2e0_0000, view_heap, true)); + assert!(!title_memory_fits(&u, b + 0xf2e0_0000, view_heap, false), "not committed"); + assert!(!title_memory_fits(&u, b + WINDOW + 0x140_0000, view_heap, true)); + assert!(!title_memory_fits(&u, b + WINDOW - 0x1_0000, view_heap, true), "into window 1"); + assert!(title_memory_fits(&u, b + WINDOW - view_heap, view_heap, true), "the end of window 0"); + // the coherent window, a view window, plain memory + for p in [b + 3 * WINDOW, b + 4 * WINDOW, 0xf2e0_0000] { + assert!(!title_memory_fits(&u, p, 0x1_0000, true), "{p:#x}"); + } + assert!(!title_memory_fits(&u, b + 0x2001_0000, 0, true)); + } + /// Ranges of the shared heap: released ones first (first fit, split), then new ones, and /// none past its size. #[test] @@ -1170,6 +1721,18 @@ mod tests { assert!(free.is_empty()); } + /// How full the shared heap is: descriptors below the cursor but the released ones, and the + /// marks (50, 75, 90 %) that use is past. + #[test] + fn shared_heap_use_and_the_marks_it_passes() { + assert_eq!(in_use(100, &[]), 100); + assert_eq!(in_use(100, &[(20, 10), (50, 6)]), 84); + for (used, marks) in [(0, 0), (500, 0), (501, 1), (750, 1), (751, 2), (900, 2), (901, 3), (1000, 3)] { + assert_eq!(marks_passed(used, 1000), marks, "{used} of 1000"); + } + assert_eq!(marks_passed(1 << 21, 1 << 21), 3, "no overflow at the largest heap"); + } + #[test] fn exact_view_slot_lease_survives_detach_and_rejects_address_reuse() { const CHILD: &str = "XCL_TEST_VIEW_SLOT_LEASE_CHILD"; @@ -1208,6 +1771,8 @@ mod tests { heap: ID3D12DescriptorHeap::from_raw((&mut global_heap as *mut Object).cast()), cpu: 0x10_0000, gpu: 0x20_0000, inc: 32, cap: 128, next: 80, free: Vec::new(), leases: PublishLeases::default(), + nulls: None, + retired: VecDeque::new(), }); HEAPS.lock().unwrap().push(Heap { generation: 70, obj: &mut source_heap as *mut Object as usize, shadow: 0x5000, @@ -1282,13 +1847,19 @@ mod tests { use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; static UNLOCKED: AtomicBool = AtomicBool::new(true); static CALLS: AtomicU32 = AtomicU32::new(0); + // slot k (bit k) got a null resource + static NULLS: AtomicU32 = AtomicU32::new(0); #[repr(C)] struct Object { vt: *const usize } unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 } - unsafe extern "system" fn create_uav(_this: *mut c_void, _resource: *mut c_void, _counter: *mut c_void, _desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, _at: D3D12_CPU_DESCRIPTOR_HANDLE) { + unsafe extern "system" fn create_uav(_this: *mut c_void, resource: *mut c_void, _counter: *mut c_void, _desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { // The adopted device hook can re-enter descriptor bookkeeping. UNLOCKED.fetch_and(GLOBAL.try_lock().is_ok(), Ordering::Relaxed); CALLS.fetch_add(1, Ordering::Relaxed); + if resource.is_null() { + let k = (at.ptr - 0x1000) / 32 - crate::gpu::recomp::MEM_HEAP_BASE as usize; + NULLS.fetch_or(1 << k, Ordering::Relaxed); + } } let mut vt = [0usize; 20]; vt[1] = retain as usize; @@ -1303,19 +1874,24 @@ mod tests { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, - next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, free: Vec::new(), leases: PublishLeases::default(), + next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, free: Vec::new(), retired: VecDeque::new(), nulls: None, leases: PublishLeases::default(), }); let window = (&mut resource as *mut _ as usize, 0x10000); + // the root-UAV slots past the windows there are: null views, not window 0 again assert!(set_window_views(&dev, &[window])); assert_eq!(CALLS.swap(0, Ordering::Relaxed), crate::gpu::uma::MAX_WINDOWS as u32); + assert_eq!(NULLS.swap(0, Ordering::Relaxed), 0b1110); let mut windows = [window; crate::gpu::uma::MAX_HEAP_WINDOWS]; assert!(set_window_views(&dev, &windows)); assert_eq!(CALLS.swap(0, Ordering::Relaxed), windows.len() as u32); - // Unused trailing window `(0, 0)` safely aliases window 0; an active window that failed - // to open `(0, bytes > 0)` is rejected. + assert_eq!(NULLS.swap(0, Ordering::Relaxed), 0); + // A window without memory `(0, 0)` (16 windows: the ones after the views) gets a null + // view; an active window that failed to open `(0, bytes > 0)` is rejected. windows[7] = (0, 0); + windows[15] = (0, 0); assert!(set_window_views(&dev, &windows)); assert_eq!(CALLS.swap(0, Ordering::Relaxed), windows.len() as u32); + assert_eq!(NULLS.swap(0, Ordering::Relaxed), 1 << 7 | 1 << 15); windows[7] = (0, 0x10000); assert!(!set_window_views(&dev, &windows)); assert_eq!(CALLS.load(Ordering::Relaxed), 0); @@ -1357,6 +1933,110 @@ mod tests { } } + /// A shader-visible sampler heap has a PC sampler at every index a translated shader forms + /// (S# word 3 & 0x7FF), whatever the title asked for (a retail title: 128); a CPU-only one + /// as many as its slots. D3D12 makes a shader-visible sampler heap of that size. + #[test] + fn every_sampler_index_a_shader_forms_is_in_the_pc_heap() { + for n in [1, 16, 128, 2047, 2048] { + assert_eq!(pc_samplers(n, true), 2048, "{n} slots"); + assert!(u32::MAX & 0x7FF < pc_samplers(n, true), "{n} slots: the highest index a shader forms"); + assert_eq!(pc_samplers(n, false), n, "{n} slots, CPU only"); + } + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + let dev = unsafe { + let mut dev: Option = None; + match CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()) { + Ok(warp) if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() => dev.unwrap(), + _ => return crate::gpu::recomp::runner::skip_test("no WARP device"), + } + }; + let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, NumDescriptors: pc_samplers(128, true), Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }; + let made = unsafe { dev.CreateDescriptorHeap::(&d) }; + assert!(made.is_ok(), "a shader-visible sampler heap of {}: {made:?}", d.NumDescriptors); + } + + /// Every descriptor of a range that is not handed out gets a null view, an SRV at even and a + /// UAV at odd indices (a range starting at an odd one too), a block at a time. + #[test] + fn free_ranges_of_the_shared_heap_get_null_views() { + use std::ffi::c_void; + use std::sync::Mutex as M; + static COPIES: M> = M::new(Vec::new()); + #[repr(C)] + struct Object { vt: *const usize } + unsafe extern "system" fn copy(_this: *mut c_void, n: u32, dst: D3D12_CPU_DESCRIPTOR_HANDLE, src: D3D12_CPU_DESCRIPTOR_HANDLE, ty: D3D12_DESCRIPTOR_HEAP_TYPE) { + assert_eq!(ty, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + COPIES.lock().unwrap().push((n, dst.ptr, src.ptr)); + } + let mut vt = [0usize; 25]; + vt[24] = copy as usize; + let mut device = Object { vt: vt.as_ptr() }; + let (heap, nulls, inc) = (0x10_0000u64, 0x90_0000u64, 32u32); + for (from, to) in [(16u32, 3 * NULL_BLOCK + 5), (7, 9), (2 * NULL_BLOCK - 1, 2 * NULL_BLOCK + 1)] { + COPIES.lock().unwrap().clear(); + unsafe { + let dev = std::mem::ManuallyDrop::new(ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void)); + fill_nulls(&dev, heap, inc, from, to, nulls); + } + let mut at = from; + for &(n, dst, src) in COPIES.lock().unwrap().iter() { + assert_eq!(dst as u64, heap + at as u64 * inc as u64, "{from}..{to}: contiguous"); + let k = (src as u64 - nulls) / inc as u64; + assert_eq!(k % 2, at as u64 % 2, "{from}..{to}: an SRV over an SRV, a UAV over a UAV"); + assert!(k + n as u64 <= NULL_BLOCK as u64, "{from}..{to}: within the null block"); + at += n; + } + assert_eq!(at, to, "{from}..{to}: all of it"); + } + } + + /// What each index of the shared heap names: a destroyed resource's views (also copies of + /// them) are claimed for null views, an index overwritten since by another resource's view + /// is not, and a resource that never had a view costs one lookup and claims nothing. + #[test] + fn a_destroyed_resources_views_are_claimed_and_no_other() { + let (a, b, c) = (0xA000usize, 0xB000usize, 0xC000usize); + let n = Names::new(64); + n.note(4, a); // SRV of slot 2 + n.note(5, a); // its UAV + n.note(8, a); + n.note(8, b); // overwritten by a view of b + // a copy of slot 2 to slot 6 (`names_of` of the source, then `publish_range`) + let (srv, uav) = (n.name(4), n.name(5)); + n.note(12, srv); + n.note(13, uav); + n.note(20, a); + n.clear(20, 22); // a released range: null views there already + assert!(n.candidates(c).is_none(), "a resource without views"); + let mut claimed: Vec = n.candidates(a).unwrap().into_iter().filter(|&i| n.claim(i, a)).collect(); + claimed.sort_unstable(); + assert_eq!(claimed, vec![4, 5, 12, 13], "a's views and their copies; not 8 (b's now), not 20 (nulled)"); + assert_eq!((n.name(4), n.name(8), n.name(12)), (GONE, b, GONE)); + assert!(n.candidates(a).is_none(), "forgotten"); + // b goes: its one view + let claimed: Vec = n.candidates(b).unwrap().into_iter().filter(|&i| n.claim(i, b)).collect(); + assert_eq!(claimed, vec![8]); + } + + /// A resource whose views are made again and again into the same few slots keeps a list of + /// those slots, not one entry for each view. + #[test] + fn views_made_again_do_not_grow_a_resources_list() { + let (a, b) = (0xA000usize, 0xB000usize); + let n = Names::new(64); + for k in 0..10_000u32 { + n.note(k % 4, a); + n.note(k % 4, b); + } + n.note(1, a); + let v = n.candidates(a).unwrap(); + assert!(v.len() < 128, "{} entries", v.len()); + assert_eq!(v.iter().filter(|&&i| n.claim(i, a)).count(), 1, "only slot 1 is a's now"); + assert!(n.candidates(b).unwrap().len() < 128); + } + #[test] fn slots_copy_and_release() { let Some(u) = crate::gpu::uma::get() else { return }; @@ -1396,6 +2076,77 @@ mod tests { assert!(start(0xA1).is_none() && slot(v).is_none() && slot(sm).is_none()); } + /// The shared heap full: the slots of a page that finds no place there name the null views + /// at 0 / 1, never 2k (in the shared heap, the only view heap lists bind, that is another + /// heap's view, a memory window's raw UAV for k from 2 to 9, or past its end); a T# copied + /// there too. A page placed before keeps its place, and one placed once room is free again + /// gets its own. Every page that found no room is counted. + #[test] + fn a_slot_whose_page_finds_no_room_names_the_null_views() { + const CHILD: &str = "XCL_TEST_SHARED_HEAP_FULL_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::console_heap::tests::a_slot_whose_page_finds_no_room_names_the_null_views", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + let Some(u) = crate::gpu::uma::get() else { return }; + use std::ffi::c_void; + #[repr(C)] + struct Object { vt: *const usize } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 } + let mut vt = [0usize; 4]; + vt[1] = retain as usize; + vt[2] = retain as usize; + let mut device = Object { vt: vt.as_ptr() }; + let mut heap = Object { vt: vt.as_ptr() }; + // room for one page of 256 slots past the null views and the memory windows + let base = crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32; + unsafe { + *GLOBAL.lock().unwrap() = Some(Global { + dev: ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void), + heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), + cpu: 0x10_0000, gpu: 0x20_0000, inc: 32, cap: base + 2 * PAGE_SLOTS, + next: base, free: Vec::new(), retired: VecDeque::new(), nulls: None, + leases: PublishLeases::default(), + }); + } + let rel = |p: u64| (p as usize - u.base()) as u32; + assert!(register(0xC1, 2 * PAGE_SLOTS, 0x30_0000, 0, 32, false, true, true)); + assert!(register(0xC2, 16, 0x40_0000, 0, 32, false, true, true)); + let (a, b) = (start(0xC1).unwrap(), start(0xC2).unwrap()); + let placed = slot(a + 2 * SLOT as u64).unwrap(); + assert_eq!(placed.index, base + 4, "page 0 of the first heap takes the room there is"); + assert_ne!(placed.shared_srv, 0); + let k = PAGE_SLOTS + 2; + let s = slot(a + (k * SLOT) as u64).unwrap(); + assert_eq!((s.index, s.shared_srv, s.pc_gpu_uav), (0, 0, 0), "slot {k} of the first heap: its page found no room"); + assert_eq!(s.pc_srv, 0x30_0000 + (2 * k * 32) as u64, "views are still made in the title's heap"); + for k in 0..16 { + let s = slot(b + (k * SLOT) as u64).unwrap(); + assert_eq!((s.index, s.shared_srv), (0, 0), "slot {k} of the second heap: no room for its page"); + } + assert_eq!(NO_ROOM.load(Relaxed), 17, "every page that found no room, each time"); + assert_eq!((PAGES_PLACED.load(Relaxed), FILL_SAID.load(Relaxed)), (1, FILL_MARKS.len()), "one page placed; the heap is past every mark"); + // a 2D T# copied into a slot without a place names the null views + write(&placed, &[base + 4, 0x0470_0000, 0, 9 << 28, 0, 0, 0, 0]); + copy_words(&placed, &s); + assert_eq!(words_at(rel(a + (k * SLOT) as u64)).unwrap()[..4], [0, 0x0470_0000, 0, 9 << 28]); + assert_eq!(slot(a + 2 * SLOT as u64).unwrap().index, base + 4, "a placed page keeps its place"); + // the first heap goes: the second heap's page gets the room it left + unregister(0xC1); + let s = slot(b + 2 * SLOT as u64).unwrap(); + assert_eq!(s.index, base + 4); + assert_ne!(s.shared_srv, 0); + assert_eq!(PAGES_PLACED.load(Relaxed), 1, "the first heap's page went with it"); + unregister(0xC2); + assert_eq!(PAGES_PLACED.load(Relaxed), 0); + *GLOBAL.lock().unwrap() = None; + } + /// Minecraft's view heaps: eight of 73 727 slots, 147 454 PC descriptors each – more in all /// than an NVIDIA shared heap holds (1 000 000). Each gets a place there for the pages it /// uses; before, the seventh and eighth got none and their views were lost (flicker). @@ -1495,7 +2246,7 @@ mod tests { *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { dev: ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), - cpu: 0x1000, inc: 32, cap: 17, next: 1, free: Vec::new(), leases: PublishLeases::default(), + cpu: 0x1000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), leases: PublishLeases::default(), }); assert_eq!(reserve_global_sampler(4), Some(1)); assert_eq!(reserve_global_sampler(4), Some(5)); @@ -1554,12 +2305,12 @@ mod tests { *GLOBAL.lock().unwrap() = Some(Global { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut view_heap as *mut _ as *mut c_void), - cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), leases: PublishLeases::default(), + cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), retired: VecDeque::new(), nulls: None, leases: PublishLeases::default(), }); *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { dev, heap: ID3D12DescriptorHeap::from_raw(&mut sampler_heap as *mut _ as *mut c_void), - cpu: 0x4000, inc: 32, cap: 17, next: 1, free: Vec::new(), leases: PublishLeases::default(), + cpu: 0x4000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), leases: PublishLeases::default(), }); if crate::gpu::uma::get().is_some() { assert!(register(0xC100, 16, 0x9000, 0, 16, true, true, true)); @@ -1610,6 +2361,295 @@ mod tests { assert_eq!(sampler_own_index(&[], 42), 42); } + /// Released ranges in `GLOBAL` and `GLOBAL_SAMPLER` stay quarantined (and view descriptors + /// are not overwritten with null views) while a live queue on the device still has work in + /// flight, and are nulled and reclaimed once that queue's fence completes. + #[test] + fn released_shared_ranges_stay_quarantined_until_queue_completes() { + const CHILD: &str = "XCL_TEST_SHARED_QUARANTINE_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::console_heap::tests::released_shared_ranges_stay_quarantined_until_queue_completes", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + if crate::gpu::uma::get().is_none() { + return; + } + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + unsafe { + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + super::super::present::note_execute(queue.as_raw(), &[]); + + let base = crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32; + let view_cap = base + 2 * PAGE_SLOTS; + let view_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: view_cap, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }).unwrap(); + let null_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: NULL_BLOCK, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }).unwrap(); + let view_inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + let nulls_at = null_heap.GetCPUDescriptorHandleForHeapStart().ptr as u64; + null_views_in(&dev, nulls_at, view_inc, NULL_BLOCK as u64); + + let sampler_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + NumDescriptors: 5, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }).unwrap(); + let sampler_inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); + + *GLOBAL.lock().unwrap() = Some(Global { + dev: dev.clone(), + cpu: view_heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, + gpu: view_heap.GetGPUDescriptorHandleForHeapStart().ptr, + heap: view_heap, + inc: view_inc, + cap: view_cap, + next: base, + free: Vec::new(), + retired: VecDeque::new(), + nulls: Some((null_heap, nulls_at)), + leases: PublishLeases::default(), + }); + *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { + dev: dev.clone(), + cpu: sampler_heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, + heap: sampler_heap, + inc: sampler_inc, + cap: 5, + next: 1, + free: Vec::new(), + retired: VecDeque::new(), + leases: PublishLeases::default(), + }); + + assert!(register(0xD100, PAGE_SLOTS, 0x10_0000, 0, 32, false, true, true)); + assert!(register(0xD200, 4, 0x20_0000, 0, 16, true, true, true)); + let s_view = slot(start(0xD100).unwrap()).unwrap(); + let s_samp = slot(start(0xD200).unwrap()).unwrap(); + assert_eq!(s_view.index, base); + assert_eq!(s_samp.index, 1); + names().note(s_view.index, 0xCAFE_0001); + assert_eq!(named_by_index(s_view.index), 0xCAFE_0001); + + unregister(0xD100); + unregister(0xD200); + + // Queue is still waiting on `gate`: ranges must stay quarantined and live view names intact. + std::thread::sleep(std::time::Duration::from_millis(50)); + assert!(GLOBAL.lock().unwrap().as_ref().unwrap().free.is_empty(), "view range returned to free while queue in flight"); + assert!(GLOBAL_SAMPLER.lock().unwrap().as_ref().unwrap().free.is_empty(), "sampler range returned to free while queue in flight"); + assert_eq!(named_by_index(base), 0xCAFE_0001, "view range overwritten while queue in flight"); + + assert!(register(0xD101, PAGE_SLOTS, 0x30_0000, 0, 32, false, true, true)); + assert!(register(0xD201, 4, 0x40_0000, 0, 16, true, true, true)); + assert_eq!(slot(start(0xD101).unwrap()).unwrap().shared_srv, 0, "quarantined view range must not be reused yet"); + assert_eq!(slot(start(0xD201).unwrap()).unwrap().shared_srv, 0, "quarantined sampler range must not be reused yet"); + + // Complete the queue fence: ranges are nulled/cleared and reclaimed on subsequent allocation. + gate.Signal(1).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + let mut got_view = 0; + let mut got_samp = 0; + while (got_view == 0 || got_samp == 0) && std::time::Instant::now() < deadline { + if got_view == 0 { + let s = slot(start(0xD101).unwrap()).unwrap(); + if s.shared_srv != 0 { + got_view = s.index; + } + } + if got_samp == 0 { + let s = slot(start(0xD201).unwrap()).unwrap(); + if s.shared_srv != 0 { + got_samp = s.index; + } + } + if got_view == 0 || got_samp == 0 { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + } + assert_eq!(got_view, base, "view range reclaimed after fence completion"); + assert_eq!(got_samp, 1, "sampler range reclaimed after fence completion"); + assert_eq!(named_by_index(base), 0, "reclaimed view range had NAMES cleared before reuse"); + + unregister(0xD101); + unregister(0xD201); + *GLOBAL_SAMPLER.lock().unwrap() = None; + *GLOBAL.lock().unwrap() = None; + } + } + + #[test] + fn retired_descriptor_ranges_stay_quarantined_until_all_queues_complete() { + use std::sync::{atomic::{AtomicU64, Ordering}, Arc}; + let f1 = Arc::new(AtomicU64::new(0)); + let f2 = Arc::new(AtomicU64::new(0)); + let mut retired: VecDeque>> = VecDeque::new(); + let mut free: Vec<(u32, u32)> = Vec::new(); + retired.push_back(RetiredRange { first: 64, count: 16, marks: Some(vec![(f1.clone(), 1), (f2.clone(), 1)]) }); + retired.push_back(RetiredRange { first: 80, count: 16, marks: Some(vec![(f1.clone(), 2), (f2.clone(), 1)]) }); + retired.push_back(RetiredRange { first: 96, count: 16, marks: None }); + + let drain = |r: &mut VecDeque>>, free: &mut Vec<(u32, u32)>| { + for (first, count) in pop_ready_ranges(r, |f| f.load(Ordering::SeqCst)) { + merge_release(free, first, count); + } + }; + + // While f2 is still pending, neither range may re-enter `free`. + f1.store(1, Ordering::SeqCst); + drain(&mut retired, &mut free); + assert!(free.is_empty() && retired.len() == 3); + + // Once both queues pass mark 1, only range 1 returns; range 2 waits for f1 == 2. + f2.store(1, Ordering::SeqCst); + drain(&mut retired, &mut free); + assert_eq!(free, vec![(64, 16)]); + assert_eq!(retired.len(), 2); + + // Passing mark 2 coalesces [80, 96) with [64, 80); failed-signal range stays quarantined. + f1.store(2, Ordering::SeqCst); + drain(&mut retired, &mut free); + assert_eq!(free, vec![(64, 32)]); + assert_eq!(retired.len(), 1); + + // A failed-signal (`None`) range at the front stays quarantined without wedging later healthy ranges. + retired.push_back(RetiredRange { first: 112, count: 16, marks: Some(vec![(f1.clone(), 3), (f2.clone(), 1)]) }); + drain(&mut retired, &mut free); + assert_eq!(free, vec![(64, 32)]); + assert_eq!(retired.len(), 2); + f1.store(3, Ordering::SeqCst); + drain(&mut retired, &mut free); + assert_eq!(free, vec![(64, 32), (112, 16)]); + assert_eq!(retired.len(), 1); + } + + /// While `drain_global_retired` is running `fill_nulls` outside `GLOBAL`, `GLOBAL_RETIRED` + /// stays set and a concurrent `slot()` waits for the in-flight drain to finish merging into + /// `GLOBAL.free` instead of returning the unmapped null slot (`shared_srv == 0`). + #[test] + fn slot_waits_for_in_flight_drain_before_returning_unmapped() { + const CHILD: &str = "XCL_TEST_DRAIN_WINDOW_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::console_heap::tests::slot_waits_for_in_flight_drain_before_returning_unmapped", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + use std::ffi::c_void; + #[repr(C)] + struct Object { vt: *const usize } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 } + let mut vt = [0usize; 25]; + vt[1] = retain as usize; + vt[2] = retain as usize; + let mut dev_obj = Object { vt: vt.as_ptr() }; + let mut heap_obj = Object { vt: vt.as_ptr() }; + let mut null_obj = Object { vt: vt.as_ptr() }; + + let base = crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32; + let range = 2 * PAGE_SLOTS; + unsafe { + *GLOBAL.lock().unwrap() = Some(Global { + dev: ID3D12Device::from_raw(&mut dev_obj as *mut _ as *mut c_void), + heap: ID3D12DescriptorHeap::from_raw(&mut heap_obj as *mut _ as *mut c_void), + cpu: 0x10_0000, + gpu: 0x20_0000, + inc: 32, + cap: base + range, + next: base + range, + free: Vec::new(), + retired: VecDeque::from([RetiredRange { first: base, count: range, marks: Some(Vec::new()) }]), + nulls: Some((ID3D12DescriptorHeap::from_raw(&mut null_obj as *mut _ as *mut c_void), 0x90_0000)), + leases: PublishLeases::default(), + }); + GLOBAL_RETIRED.store(true, Release); + HEAPS.lock().unwrap().push(Heap { + obj: 0xE100, + shadow: 0x50_0000, + n: PAGE_SLOTS, + pc_cpu: 0x60_0000, + pc_gpu: 0, + inc: 32, + sampler: false, + pages: vec![UNMAPPED], + visible: true, + memory: Memory::Uma, + generation: NEXT_HEAP_GENERATION.fetch_add(1, Ordering::Relaxed).wrapping_add(1), + }); + } + + let (entered_tx, entered_rx) = std::sync::mpsc::channel(); + let before_seq = GLOBAL_DRAIN_SEQ.load(Acquire); + let drainer = std::thread::spawn(move || { + drain_global_retired_with(before_seq, |_, _, _, _, _| { + entered_tx.send(()).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(80)); + }) + }); + + // Wait until `drainer` has popped `s.retired`, released `GLOBAL`, and is inside `on_nulls`. + entered_rx.recv().unwrap(); + let retired_during_nulls = GLOBAL_RETIRED.load(Acquire); + + let s = slot(0x50_0000).unwrap(); + let drained = drainer.join().unwrap(); + assert!(retired_during_nulls, "GLOBAL_RETIRED dropped before merge_release completed"); + assert!(drained); + assert_ne!(s.shared_srv, 0, "concurrent slot() got unmapped null slot during in-flight drain"); + assert_eq!(s.index, base, "concurrent slot() must receive the reclaimed descriptor range"); + assert!(!GLOBAL_RETIRED.load(Acquire)); + + // Second path: `slot()` already past its entry drain (holding `HEAPS` when the drain starts) + // hits the post-`page_of` fallback (`GLOBAL_RETIRED` -> `drain_global_retired_since`). + { + let mut g = GLOBAL.lock().unwrap(); + let gs = g.as_mut().unwrap(); + gs.free.clear(); + gs.retired.push_back(RetiredRange { first: base, count: range, marks: Some(Vec::new()) }); + GLOBAL_RETIRED.store(true, Release); + } + HEAPS.lock().unwrap()[0].pages[0] = UNMAPPED; + let (entered2_tx, entered2_rx) = std::sync::mpsc::channel(); + let before_seq2 = GLOBAL_DRAIN_SEQ.load(Acquire); + let drainer2 = std::thread::spawn(move || { + drain_global_retired_with(before_seq2, |_, _, _, _, _| { + entered2_tx.send(()).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(80)); + }) + }); + entered2_rx.recv().unwrap(); + let retired_during_nulls2 = GLOBAL_RETIRED.load(Acquire); + let fallback_drained = drain_global_retired_since(before_seq2); + let drained2 = drainer2.join().unwrap(); + assert!(retired_during_nulls2); + assert!(drained2 && fallback_drained, "drain_global_retired_since must wait for and observe in-flight merge"); + assert_eq!(reserve_global(range), Some(base)); + + HEAPS.lock().unwrap().clear(); + *GLOBAL.lock().unwrap() = None; + } + #[test] fn publish_range_stops_at_small_and_tail_heap_bounds() { const CHILD: &str = "XCL_TEST_PUBLISH_BOUNDS_CHILD"; @@ -1666,7 +2706,8 @@ mod tests { cap: 4096, next: 64, free: Vec::new(), - leases: PublishLeases::default(), + leases: PublishLeases::default(), retired: VecDeque::new(), + nulls: None, }); *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { dev, @@ -1676,7 +2717,7 @@ mod tests { cap: 256, next: 1, free: Vec::new(), - leases: PublishLeases::default(), + leases: PublishLeases::default(), retired: VecDeque::new(), }); { let mut heaps = HEAPS.lock().unwrap(); @@ -1685,11 +2726,11 @@ mod tests { heaps.push(Heap { generation: 3, obj: &mut source260 as *mut Object as usize, shadow: view260.as_ptr() as usize, n: 260, pc_cpu: 0x50_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED; 2], visible: true, memory: Memory::Uma }); } let v1 = slot(view4.as_ptr() as u64 + SLOT as u64).unwrap(); - publish_range(&v1, 10); + publish_range(&v1, 10, &[]); let s1 = slot(sampler3.as_ptr() as u64 + SAMPLER_SLOT as u64).unwrap(); - publish_range(&s1, 10); + publish_range(&s1, 10, &[]); let v250 = slot(view260.as_ptr() as u64 + (250 * SLOT) as u64).unwrap(); - publish_range(&v250, 20); + publish_range(&v250, 20, &[]); HEAPS.lock().unwrap().clear(); *GLOBAL_SAMPLER.lock().unwrap() = None; *GLOBAL.lock().unwrap() = None; @@ -1764,14 +2805,15 @@ mod tests { dev: ID3D12Device::from_raw((&mut device as *mut Object).cast()), heap: ID3D12DescriptorHeap::from_raw((&mut global_heap as *mut Object).cast()), cpu: 0x10_0000, gpu: 0x18_0000, inc: 32, cap: 4096, next: 72, - free: Vec::new(), leases: PublishLeases::default(), + free: Vec::new(), leases: PublishLeases::default(), retired: VecDeque::new(), + nulls: None, }); HEAPS.lock().unwrap().push(Heap { generation: 77, obj: &mut source_heap as *mut Object as usize, shadow: shadow.as_ptr() as usize, n: 4, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![64], visible: true, memory: Memory::Uma, }); let stale = slot(shadow.as_ptr() as u64).unwrap(); - let worker = std::thread::spawn(move || publish(&stale, false)); + let worker = std::thread::spawn(move || publish(&stale, false, 0)); entered.wait(); assert_eq!(source_heap.refs.load(Ordering::Relaxed), 2, "source heap must stay owned during the device call"); let Taken(old) = take(&mut source_heap as *mut Object as usize).unwrap(); @@ -1783,12 +2825,12 @@ mod tests { assert!(LOCKS_FREE.load(Ordering::Relaxed)); assert_eq!(source_heap.refs.load(Ordering::Relaxed), 1); assert_eq!(reserve_global(8), Some(64), "deferred range must return when publication finishes"); - publish(&stale, false); + publish(&stale, false, 0); assert_eq!(CALLS.load(Ordering::Relaxed), 1, "a stale generation must not publish into its replacement"); GLOBAL.lock().unwrap().as_mut().unwrap().next = 88; let stale_range = slot(shadow.as_ptr() as u64).unwrap(); - let worker = std::thread::spawn(move || publish_range(&stale_range, 4)); + let worker = std::thread::spawn(move || publish_range(&stale_range, 4, &[])); entered.wait(); assert_eq!(source_heap.refs.load(Ordering::Relaxed), 2, "range source heap must stay owned during the device call"); let Taken(old) = take(&mut source_heap as *mut Object as usize).unwrap(); @@ -1799,7 +2841,7 @@ mod tests { worker.join().unwrap(); assert_eq!(source_heap.refs.load(Ordering::Relaxed), 1); assert_eq!(reserve_global(8), Some(80), "deferred range must return when range publication finishes"); - publish_range(&stale_range, 4); + publish_range(&stale_range, 4, &[]); assert_eq!(CALLS.load(Ordering::Relaxed), 2, "a stale range generation must not publish into its replacement"); HEAPS.lock().unwrap().clear(); *GLOBAL.lock().unwrap() = None; diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 9d39e2730e..e49665ee70 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -74,15 +74,25 @@ pub struct Layout { pub size: u32, pub inline: u32, pub inline_gfx: u32, + /// the shaders index the view heap / the sampler heap themselves (the root signature's + /// CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED / SAMPLER_HEAP_DIRECTLY_INDEXED): they take the 32-bit + /// address of each from a user SGPR after the arguments, the view heap's first + pub heaps: [bool; 2], + pub inline_ms: u32, } +const CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED: u32 = 0x400; +const SAMPLER_HEAP_DIRECTLY_INDEXED: u32 = 0x800; + /// User SGPRs the console's compiler gives root arguments: compute s4…s15 (s0…s3 are the /// driver's), graphics stages (VS, PS) s8…s31 (s0…s7: the driver's, s[4:5] of a VS the /// fetch shader) – both measured on its output (`tests/console_shaders.rs`). const INLINE_SGPRS: u32 = 12; const INLINE_SGPRS_GFX: u32 = 24; +const INLINE_SGPRS_MS: u32 = 16; const FIRST_SGPR: usize = 4; const FIRST_SGPR_GFX: usize = 8; +const FIRST_SGPR_MS: usize = 16; /// Most bytes of root arguments a layout has. The PC's limit is 64 DWORDs (256 bytes: a /// constant or a table 1, a root descriptor 2, D3D12 "Root Signature Limits"); the console's /// is not known, so 16 times that. A malformed blob (a count of 0x3FFF_FFFF constants) gets no @@ -100,11 +110,12 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { }; let r = |o: usize| rts0.get(o..o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); let (n, poff) = (r(4)? as usize, r(8)? as usize); - let mut l = Layout::default(); + let flags = r(20).unwrap_or(0); + let mut l = Layout { heaps: [CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED, SAMPLER_HEAP_DIRECTLY_INDEXED].map(|f| flags & f != 0), ..Default::default() }; // the parameters go into user SGPRs in order while each fits whole; from the first one // that does not, the rest go to the table (packed from its start) – as the console's // compiler expects them (HANDOFF: root argument binding) - let (mut spilled, mut spilled_gfx) = (false, false); + let (mut spilled, mut spilled_gfx, mut spilled_ms) = (false, false, false); for k in 0..n { let (ty, pay) = (r(poff + 12 * k)?, r(poff + 12 * k + 8)? as usize); let p = match ty { @@ -127,12 +138,24 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { if !spilled_gfx { l.inline_gfx += bytes; } + spilled_ms |= l.inline_ms + bytes > 4 * INLINE_SGPRS_MS; + if !spilled_ms { + l.inline_ms += bytes; + } l.size = size; l.params.push(p); } Some(l) } +/// The addresses of the root views (root CBV / SRV / UAV) among `args`, packed by `l`. +pub(super) fn root_views<'a>(l: &'a Layout, args: &'a [u8]) -> impl Iterator + 'a { + l.params.iter().filter_map(move |p| match *p { + Param::Descriptor { at } => args.get(at as usize..at as usize + 8).map(|b| u64::from_le_bytes(b.try_into().unwrap())), + _ => None, + }) +} + /// The user SGPRs of a dispatch: s[0:1] = `table_at` (where the bytes of `args` past the /// inline part are), from s4 the inline part of `args` (all arguments packed by `l`). pub fn user_data(l: &Layout, args: &[u8], table_at: u64) -> Vec { @@ -170,6 +193,32 @@ pub fn user_data_gfx(l: &Layout, args: &[u8], table_at: u64) -> Vec { sgprs(FIRST_SGPR_GFX, l.inline_gfx, args, table_at) } +/// `sgprs` (`user_data_for` / `user_data_gfx`) and the addresses of the view heap and the sampler +/// heap set that the shaders index (`Layout::heaps`). A compute shader without registers left +/// for them (`user_sgprs`: its count) gets none. +pub fn with_heaps(l: &Layout, user_sgprs: Option, mut sgprs: Vec, heaps: [u32; 2]) -> Vec { + for (_, base) in l.heaps.iter().zip(heaps).filter(|(&used, _)| used) { + if user_sgprs.is_some_and(|n| sgprs.len() as u32 >= n) { + break; + } + sgprs.push(base); + } + sgprs +} + +pub fn user_data_ms(l: &Layout, args: &[u8], table_at: u64) -> Vec { + let mut s = vec![0u32; FIRST_SGPR_MS]; + s[8] = table_at as u32; + s[9] = (table_at >> 32) as u32; + let inline = &args[..(l.inline_ms as usize).min(args.len())]; + s.extend(inline.chunks(4).map(|c| { + let mut w = [0u8; 4]; + w[..c.len()].copy_from_slice(c); + u32::from_le_bytes(w) + })); + s +} + fn sgprs(first: usize, inline: u32, args: &[u8], table_at: u64) -> Vec { let mut s = vec![0u32; first]; s[0] = table_at as u32; @@ -304,11 +353,12 @@ struct ListState { } static LISTS: Mutex>> = Mutex::new(None); -/// unified-memory blocks of finished recordings, freed when their allocator is reset +/// unified-memory blocks of finished recordings by the PC allocator they were on, freed when the +/// GPU is done with it (it is reset, or `alloc_pool` sees it pass their submits) static PENDING: Mutex>>> = Mutex::new(None); -/// Unified-memory blocks a recording on `allocator` uses: freed when it is reset (no -/// allocator known: kept until the next reset of any – never freed early). +/// Unified-memory blocks a recording on the PC allocator `allocator` uses: freed when the GPU is +/// done with it (no allocator known: kept until the next reset of any – never freed early). pub(super) fn hold_until_reset(allocator: usize, blocks: Vec) { if !blocks.is_empty() { PENDING.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().extend(blocks); @@ -325,12 +375,14 @@ pub(crate) fn take_pending_for_test(allocator: usize) -> Vec { PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)).unwrap_or_default() } -/// An allocator was reset: the GPU no longer uses what its recordings put in unified memory. +/// The GPU no longer uses what recordings on the PC allocator `allocator` put in unified memory: +/// it was reset, or `alloc_pool` saw the GPU pass their submits. pub fn allocator_reset(allocator: *mut c_void) { let blocks = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&(allocator as usize))); if let Some(b) = blocks { unsafe { free_uma(&b) }; } + super::bind::release_allocator_res(allocator as usize); } fn with_list(obj: usize, f: impl FnOnce(&mut ListState) -> R) -> Option { @@ -389,6 +441,7 @@ unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 { }) .unwrap_or(0); if left == 0 { + super::title_textures::forget_list_closed(obj); if let Some(st) = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&obj)) { free_uma(&st.uma); let release: unsafe extern "system" fn(usize) -> u32 = std::mem::transmute(pc_vtable_call(st.pc, 2)); @@ -429,6 +482,7 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, ps }) else { return crate::util::E_FAIL; }; + super::title_textures::forget_list_closed(obj); // what the previous recording left in unified memory lives until its allocator resets if !blocks.is_empty() { PENDING.lock().unwrap().get_or_insert_with(HashMap::new).entry(old_alloc).or_default().extend(blocks); @@ -631,6 +685,15 @@ pub fn pc_list(obj: *mut c_void) -> Option<*mut c_void> { with_list(obj as usize, |st| st.pc as *mut c_void) } +/// Whether `pc` is the internal PC command list behind an active `console_list` wrapper. +pub(super) fn is_backing(pc: *mut c_void) -> bool { + if !enabled() || pc.is_null() { + return false; + } + let p = pc as usize; + LISTS.lock().unwrap().as_ref().is_some_and(|m| m.values().any(|st| st.pc == p)) +} + /// The PC pipeline state behind a console-shaped one (others unchanged). pub fn pc_pso(pso: *mut c_void) -> *mut c_void { if pso.is_null() || unsafe { *(pso as *const usize) } != pso_vtable() { @@ -816,18 +879,30 @@ pub unsafe fn close(obj: *mut c_void) -> Result { } else if w0 == TRANSITIONS_MARKER { let n = get(1) as usize; let words = &words[(at + 2).min(words.len())..(at + 2 + 8 * n).min(words.len())]; - if words.len() == 8 * n && n > 0 { + // (a depth buffer whose depth plane can have a twin rests in `depth_uav::PARK` + // where the title has it in UNORDERED_ACCESS, here as on every list; a compute + // list copies nothing) + let parked = (words.len() == 8 * n && super::depth_uav::any_kept()).then(|| { + let mut v: Vec<[u32; 8]> = words.chunks_exact(8).map(|c| c.try_into().unwrap()).collect(); + let _ = super::depth_uav::plan_barriers(&mut v, false, &mut Vec::new()); + v + }); + let (sent, m) = parked.as_ref().map_or((words, n), |v| (v.as_flattened(), v.len())); + if words.len() == 8 * n && m > 0 { // 4-byte aligned in the stream: copy out; the resource pointers are // borrowed (ManuallyDrop fields, nothing released) - let mut b: Vec = vec![0; 4 * n]; - std::ptr::copy_nonoverlapping(words.as_ptr() as *const u8, b.as_mut_ptr() as *mut u8, 32 * n); - if super::title_textures::any() { + let mut b: Vec = vec![0; 4 * m]; + std::ptr::copy_nonoverlapping(sent.as_ptr() as *const u8, b.as_mut_ptr() as *mut u8, 32 * m); + if super::title_textures::any() || super::lut3d::on() { // each barrier: type | flags, resource, subresource | before, after let t: Vec<(usize, u32, D3D12_RESOURCE_STATES)> = b.chunks_exact(4).filter(|c| c[0] as u32 == 0).map(|c| (c[1] as usize, c[2] as u32, D3D12_RESOURCE_STATES(c[3] as u32 as i32))).collect(); super::list_x::note_texture_transitions(st.pc, &t); } - list.ResourceBarrier(std::slice::from_raw_parts(b.as_ptr() as *const D3D12_RESOURCE_BARRIER, n)); + for c in b.chunks_exact(4).filter(|c| c[0] as u32 == 0) { + super::placements::note_use(c[1] as usize); + } + list.ResourceBarrier(std::slice::from_raw_parts(b.as_ptr() as *const D3D12_RESOURCE_BARRIER, m)); } out.barriers += n as u32; at += 2 + 8 * n; @@ -847,15 +922,22 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let res = q(2) as *mut c_void; let (gpu, cpu) = (super::console_heap::slot(q(0)), super::console_heap::slot(q(1))); match (gpu, cpu, ID3D12Resource::from_raw_borrowed(&res)) { - (Some(g), Some(c), Some(r)) if g.pc_gpu_uav != 0 => { - let (gh, ch) = (D3D12_GPU_DESCRIPTOR_HANDLE { ptr: g.pc_gpu_uav }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: c.pc_uav as usize }); - if get(1) != 0 { - let f = values.map(f32::from_bits); - list.ClearUnorderedAccessViewFloat(gh, ch, r, &f, &[]); + (Some(g), Some(c), Some(_)) if g.pc_gpu_uav != 0 => { + // a view of a depth buffer's twin is cleared through the twin (as a direct + // list's clear: `list_x::clear_uav`); None: not done + let target = super::list_x::uav_clear_resource(res as usize, Some(g)).map(|t| t as *mut c_void); + if let Some(r) = target.as_ref().and_then(|t| ID3D12Resource::from_raw_borrowed(t)) { + let (gh, ch) = (D3D12_GPU_DESCRIPTOR_HANDLE { ptr: g.pc_gpu_uav }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: c.pc_uav as usize }); + if get(1) != 0 { + let f = values.map(f32::from_bits); + list.ClearUnorderedAccessViewFloat(gh, ch, r, &f, &[]); + } else { + list.ClearUnorderedAccessViewUint(gh, ch, r, &values, &[]); + } + out.clears += 1; } else { - list.ClearUnorderedAccessViewUint(gh, ch, r, &values, &[]); + out.skipped += 1; } - out.clears += 1; } _ => out.skipped += 1, } @@ -907,6 +989,8 @@ pub unsafe fn close(obj: *mut c_void) -> Result { continue; } let user_sgprs = super::real::pso_user_sgprs_exact(real); + // (the list is submitted after this: its root views in a GPU view get their tiles there) + super::bind::want_root_views(layout.as_deref(), &table, super::view_want::Path::RootView); let inline = layout.as_ref().map_or(0, |l| inline_for(l, user_sgprs) as usize).min(table.len()); let table_at = uma_copy(st, &table[inline..]).ok_or("UMA: argument table")?; let mut io = match layout.as_ref() { @@ -915,6 +999,13 @@ 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; + // (the console's counts: the groups that run, also when folded below) + if super::bind::dispatch_loop_budget_wanted() { + io[crate::gpu::recomp::IO_LOOP_BUDGET] = crate::gpu::recomp::dispatch_loop_budget([x, y, z]); + } + // more groups in X than D3D12 takes: folded (`recomp::IO_GROUP_LIMIT`) + let (limit, folded) = super::bind::fold(x, y, z); + io[crate::gpu::recomp::IO_GROUP_LIMIT] = limit; let io_at = uma_copy(st, bytemuck_u32(&io)).ok_or("UMA: io")?; let res_at = uma_copy(st, &[0u8; 256]).ok_or("UMA: res")?; // the pipeline's own root signature when it has static samplers @@ -926,11 +1017,16 @@ pub unsafe fn close(obj: *mut c_void) -> Result { shared_view_bound = ensure_dispatch_heaps(&list, &mut bound_heaps, &mut has_sampler_heap, shared_view_bound); list.SetComputeRootUnorderedAccessView(0, va(io_at)); list.SetComputeRootUnorderedAccessView(1, va(res_at)); + // (every window slot gets a buffer: direct DXIL compute reads all four, as in `bind`) for k in 0..4 { - list.SetComputeRootUnorderedAccessView(2 + k as u32, windows.get(k).copied().unwrap_or(uma_va)); + list.SetComputeRootUnorderedAccessView(2 + k as u32, windows.get(k).copied().filter(|&v| v != 0).unwrap_or(uma_va)); } super::real::bind_pipeline_exact(list.as_raw(), (*p).pc, real); - super::real::dispatch_chain::dispatch(&list, (*p).pc, real, st.allocator, [x, y, z])?; + // (the span names the console's groups, the chain dispatches the folded ones) + let t = super::gpu_profile::begin(list.as_raw(), real, super::gpu_profile::Kind::Dispatch, [x, y, z]); + let ran = super::real::dispatch_chain::dispatch(&list, (*p).pc, real, st.allocator, folded); + super::gpu_profile::end(list.as_raw(), t); + ran?; recording_uses_shared_view |= track_shared_view && shared_view_bound; out.dispatches += 1; } @@ -995,6 +1091,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { crate::xlog_warn!("console list: unknown record {w:#010x} (word {at}) – rest skipped"); } list.Close().map_err(|e| format!("Close: {e}"))?; + super::title_textures::note_list_closed(obj); Ok(out) } @@ -1065,6 +1162,36 @@ mod tests { r.iter().flat_map(|w| w.to_le_bytes()).collect() } + /// Shaders that index the heaps set themselves get the heaps' addresses after their + /// arguments, the view heap's first; a compute shader without registers for them does not. + #[test] + fn heap_addresses_follow_the_arguments() { + let layout = |flags: u32, p: &[(u32, u32)]| { + let mut blob = rts0(p); + blob[20..24].copy_from_slice(&flags.to_le_bytes()); + layout_from_blob(&blob).unwrap() + }; + let heaps = [0x6000_0000, 0x6381_0000]; + // a table and two constants + let args: Vec = [0x80u32, 5, 0].iter().flat_map(|w| w.to_le_bytes()).collect(); + let gfx = |flags: u32| { + let l = layout(flags, &[(0, 0), (1, 2)]); + with_heaps(&l, None, user_data_gfx(&l, &args, 0x200), heaps)[8..].to_vec() + }; + assert_eq!(gfx(1), [0x80, 5, 0]); + assert_eq!(gfx(0x801), [0x80, 5, 0, 0x6381_0000]); + assert_eq!(gfx(0x401), [0x80, 5, 0, 0x6000_0000]); + assert_eq!(gfx(0xC01), [0x80, 5, 0, 0x6000_0000, 0x6381_0000]); + let cs = |flags: u32, user: u32| { + let l = layout(flags, &[(0, 0), (1, 2)]); + with_heaps(&l, Some(user), user_data_for(&l, Some(user), &args, 0x200), heaps)[4..].to_vec() + }; + assert_eq!(cs(0xC00, 9), [0x80, 5, 0, 0x6000_0000, 0x6381_0000]); + assert_eq!(cs(0xC00, 8), [0x80, 5, 0, 0x6000_0000]); + assert_eq!(cs(0xC00, 7), [0x80, 5, 0], "no register left"); + assert_eq!(cs(0, 9), [0x80, 5, 0]); + } + /// A blob whose constant count makes the arguments overflow u32 (0x4000_0000) or take /// gigabytes (0x3FFF_FFFF: 0xFFFF_FFFC bytes, allocated at every Set*RootSignature) has no /// layout; the largest one allowed still has one. @@ -1109,6 +1236,21 @@ mod tests { assert_eq!(user_data_gfx(&l, &args, 0x200), vec![0x200, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0x5000, 4, 0x80]); } + #[test] + fn mesh_arguments_go_in_user_sgprs_from_s16() { + let inline = |p: &[(u32, u32)]| layout_from_blob(&rts0(p)).unwrap().inline_ms; + assert_eq!(inline(&[(1, 2), (2, 0), (0, 0)]), 20); + assert_eq!(inline(&[(1, 14), (2, 0)]), 64); + assert_eq!(inline(&[(1, 15), (2, 0)]), 60); + assert_eq!(inline(&[(1, 17), (2, 0)]), 0); + let l = layout_from_blob(&rts0(&[(1, 2), (2, 0), (0, 0)])).unwrap(); + let args: Vec = [1u32, 2, 0x5000, 4, 0x80].iter().flat_map(|w| w.to_le_bytes()).collect(); + let got = user_data_ms(&l, &args, 0x7_0000_0200); + assert_eq!(got[8], 0x200); + assert_eq!(got[9], 7); + assert_eq!(&got[16..], &[1, 2, 0x5000, 4, 0x80]); + } + #[test] fn default_dispatch_heaps_binds_and_upgrades_missing_view_or_sampler() { // 0 heaps bound: binds both under heap_windows, or sampler alone when view == None. diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 1d8f484f7d..f672e42f0a 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -71,13 +71,13 @@ fn worker() -> &'static Mutex> { let spawned = std::thread::Builder::new().name("xcl-cpu-writes".into()).spawn(move || unsafe { let event = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()); for job in rx { - if job.fence.GetCompletedValue() < job.value && job.fence.SetEventOnCompletion(job.value, HANDLE(event as *mut c_void)).is_ok() { + if super::real::fence_completed(&job.fence) < job.value && job.fence.SetEventOnCompletion(job.value, HANDLE(event as *mut c_void)).is_ok() { th::WaitForSingleObject(event, WAIT_MS); - if job.fence.GetCompletedValue() < job.value { + if super::real::fence_completed(&job.fence) < job.value { 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: {k} writes after the GPU so far done although their queue had not got there after {WAIT_MS} ms (fence at {}, wanted {}; {} writes)", job.fence.GetCompletedValue(), job.value, job.writes.len()); + crate::xlog_warn!("D3D12.X: {k} writes after the GPU so far done although their queue had not got there after {WAIT_MS} ms (fence at {}, wanted {}; {} writes)", super::real::fence_completed(&job.fence), job.value, job.writes.len()); } } } @@ -102,9 +102,42 @@ fn worker() -> &'static Mutex> { }) } +/// Where the CPU writes for the GPU at `va`: at the CPU view behind a GPU view of the title's +/// memory in a view window (the CPU cannot touch the GPU view; its tiles show the CPU view, and +/// the write reaches them as any CPU write does), else at `va`. +fn cpu_at(va: usize) -> usize { + cpu_at_in(va, |a| super::view_want::is_view(a as u64)) +} + +/// `cpu_at`, with `in_view` saying which addresses lie in a view window. +fn cpu_at_in(va: usize, in_view: impl Fn(usize) -> bool) -> usize { + if in_view(va) { + super::view_want::cpu(va as u64) as usize + } else { + va + } +} + /// The dwords at `va`, if the memory is still there and writable. unsafe fn write_now(va: usize, words: &[u32]) { + write_now_in(va, words, &|a, n| if super::view_want::is_view(a as u64) { super::view_want::cpu_run(a as u64, n as u64).map(|c| c as usize) } else { Some(a) }); +} + +/// `write_now`, with `run` giving where the CPU writes `[a, a + n)` (`cpu_at`) when that is one +/// piece, None when the range covers pages of a GPU view kept apart (the queue's page mappings): +/// then the dwords are written in two calls, split at the first 64 KiB page boundary, each part +/// where its own pages are. +unsafe fn write_now_in(va: usize, words: &[u32], run: &dyn Fn(usize, usize) -> Option) { let bytes = 4 * words.len(); + let asked = va; + let Some(va) = run(va, bytes) else { + let first = ((va | 0xFFFF) - va + 1).div_ceil(4); + if first < words.len() { + write_now_in(va, &words[..first], run); + write_now_in(va + 4 * first, &words[first..], run); + } + return; + }; if !crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); @@ -118,6 +151,19 @@ unsafe fn write_now(va: usize, words: &[u32]) { for (i, &w) in words.iter().enumerate() { (*((va + 4 * i) as *const AtomicU32)).store(w, Ordering::Release); } + note_placed(asked, va, bytes); +} + +/// A write for the GPU at `va` was made at `at`, where XCL keeps the page the queue's page +/// mappings put at `va` (`kernelx::mirrors`): it is told as XCL's own write there +/// (`title_textures::note_known_write`) – that place may be a home, which is not write-watched, +/// and the tiles and textures that show the page would not see it. One atomic load while nothing +/// is mapped. +fn note_placed(va: usize, at: usize, bytes: usize) { + use crate::hle::kernelx::mirrors::{any_mapped, shows, Shows}; + if at != va && any_mapped() && matches!(shows(va), Shows::Page { .. }) { + super::title_textures::note_known_write(at, bytes); + } } /// Whether `[va, va + 8)` is 8-byte aligned, committed, and writable without `PAGE_GUARD`. @@ -141,22 +187,29 @@ unsafe fn u64_writable_now(va: usize) -> bool { /// An 8-byte aligned 64-bit value at `va`, if the memory is still there and writable. unsafe fn write_u64_now(va: usize, value: u64) { + let (asked, va) = (va, cpu_at(va)); if u64_writable_now(va) { (*(va as *const AtomicU64)).store(value, Ordering::Release); + note_placed(asked, va, 8); } } /// Advance an 8-byte aligned 64-bit value at `va` to at least `value` (`fetch_max`), if the memory -/// is still committed and writable. Best-effort check before the atomic write (same TOCTOU -/// trade-off as `write_u64_now`: a concurrent title decommit between check and store is unguarded). +/// is still committed and writable (a GPU view's at its CPU view, `cpu_at`). Best-effort check +/// before the atomic write (same TOCTOU trade-off as `write_u64_now`: a concurrent title decommit +/// between check and store is unguarded). pub(super) unsafe fn max_u64_now(va: usize, value: u64) { + let (asked, va) = (va, cpu_at(va)); if u64_writable_now(va) { (*(va as *const AtomicU64)).fetch_max(value, Ordering::AcqRel); + note_placed(asked, va, 8); } } -/// Whether `[va, va + bytes)` is memory the CPU can write for the GPU later. +/// Whether `[va, va + bytes)` is memory the CPU can write for the GPU later (a GPU view's at its +/// CPU view, `cpu_at`). pub(super) fn writable(va: usize, bytes: usize) -> bool { + let va = cpu_at(va); if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { return true; } @@ -260,6 +313,94 @@ mod tests { } } + /// A write for the GPU into a GPU view of the title's memory is made at the CPU view behind + /// it (the CPU cannot touch the GPU view: such a write was not done); any other address, and + /// every one without view windows, is written where it is. + #[test] + fn a_write_into_a_gpu_view_is_made_at_its_cpu_view() { + use crate::hle::kernelx::mirrors; + const SIZE: usize = 71 << 16; + // (addresses far above anything Windows hands out: only the pairing is used) + let (c, g) = (0x7260_0000_0000usize, 0x7268_0000_0000usize); + mirrors::reserved(c, SIZE, 0x2040_2000, 0x04); + assert!(mirrors::reserved(g, SIZE, 0x2040_2000, 0x801)); + let view = |a: usize| (g..g + SIZE).contains(&a); + assert_eq!(cpu_at_in(g + 0x4_5678, view), c + 0x4_5678); + assert_eq!(cpu_at_in(c + 0x10, view), c + 0x10); + assert_eq!(cpu_at_in(g + 0x10, |_| false), g + 0x10, "no view windows: as it was"); + mirrors::released(c); + } + + /// Dwords for the GPU over two pages of a GPU view whose pages are kept apart land, each, + /// where its own page is; a write that is one piece is made in one. + #[test] + fn a_write_over_pages_kept_apart_is_made_page_by_page() { + unsafe { + const PAGE: usize = 0x1_0000; + // (two pages of a view, kept in two buffers of their own) + let (mut one, mut two) = (vec![0u32; 8], vec![0u32; 8]); + let (p1, p2) = (one.as_mut_ptr() as usize, two.as_mut_ptr() as usize); + let g = 0x7268_0000_0000usize; + let place = |a: usize| if a < g + PAGE { p1 + 16 + (a - (g + PAGE - 16)) } else { p2 + (a - (g + PAGE)) }; + let calls = std::cell::Cell::new(0); + let run = |a: usize, n: usize| { + calls.set(calls.get() + 1); + ((a ^ (a + n.max(1) - 1)) < PAGE).then(|| place(a)) + }; + write_now_in(g + PAGE - 8, &[1, 2, 3, 4, 5], &run); + assert_eq!(one[4..], [0, 0, 1, 2]); + assert_eq!(two[..4], [3, 4, 5, 0]); + assert_eq!(calls.get(), 3, "split once, at the page boundary"); + write_now_in(g + PAGE + 4, &[6, 7], &run); + assert_eq!(two[..4], [3, 6, 7, 0]); + assert_eq!(calls.get(), 4, "inside one page: one piece"); + } + } + + /// A write for the GPU into a GPU-view page the queue's page mappings named is made where its + /// page is kept – here its home, which is not write-watched – and told as XCL's own write + /// there; one into a page never named is made at the CPU view, as before, and not told. + #[test] + fn a_write_where_a_mapped_page_is_kept_is_a_known_write() { + use crate::hle::kernelx::{self, mirrors::{self, PAGE}}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + unsafe { + if crate::gpu::uma::get().is_none() { + return crate::gpu::recomp::runner::skip_test("no unified memory"); + } + // a pair of views of a size of the test's own, and a physical page at its home: the pool + let size = 211 * PAGE; + let cpu = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE, PAGE_READWRITE) as usize; + let gpu = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE, PAGE_READWRITE) as usize; + assert!(cpu != 0 && gpu != 0); + mirrors::reserved(cpu, size, 0x2040_2000, 0x04); + assert!(mirrors::reserved(gpu, size, 0x2040_2000, 0x801)); + let (mut n, mut pages) = (1usize, [0usize; 1]); + assert_eq!(kernelx::AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let home = kernelx::MapTitlePhysicalPages(std::ptr::null_mut(), 1, 0, 4, pages.as_mut_ptr()) as usize; + assert_ne!(home, 0); + // pool page 0 at view page 1 + let ranges: [[u32; 3]; 1] = [[0, 0, 1]]; + let batch = [(gpu + PAGE) as u64, 1, ranges.as_ptr() as u64]; + assert!(mirrors::apply_batches(1, batch.as_ptr() as usize, home, 1).is_some()); + let run = |a: usize, n: usize| super::super::view_want::cpu_run(a as u64, n as u64).map(|c| c as usize); + let known = |at: usize| super::super::title_textures::known_in(at, PAGE); + write_now_in(gpu + PAGE + 0x40, &[1, 2], &run); + assert_eq!(*((home + 0x40) as *const [u32; 2]), [1, 2]); + assert_eq!(known(home), vec![(home + 0x40, 8)]); + // a page never named: the CPU view, write-watched as the title's + assert_eq!(VirtualAlloc(cpu as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE) as usize, cpu); + write_now_in(gpu + 0x40, &[3], &run); + assert_eq!(*((cpu + 0x40) as *const u32), 3); + assert!(known(cpu).is_empty()); + super::super::title_textures::forget_known_in(home, PAGE); + kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), 1, pages.as_mut_ptr()); + mirrors::released(cpu); + VirtualFree(cpu as *mut c_void, 0, MEM_RELEASE); + VirtualFree(gpu as *mut c_void, 0, MEM_RELEASE); + } + } + /// 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/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs new file mode 100644 index 0000000000..d2a60e5c1b --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -0,0 +1,1421 @@ +//! Depth buffers that the console also lets shaders write (ALLOW_DEPTH_STENCIL | +//! ALLOW_UNORDERED_ACCESS). The PC refuses the pair: `device_x::pc_resource_desc` keeps the depth +//! buffer and drops ALLOW_UNORDERED_ACCESS, so a UAV of such a buffer is a null view and what a +//! compute program stores through it is lost. +//! +//! This module keeps what XCL knows of these buffers: each object by its address, the objects at +//! one title address and shape together in a `Cell` (on the PC they share texels, `vram`), and the +//! DSVs that name them. A UAV of the stencil plane of such a buffer is made on a twin of the +//! plane: an R8 texture with unordered access, made at the first such UAV (`resolve_uav`). The +//! store, the load (the slot's companion SRV) and the T# of the UAV slot then use the twin. +//! +//! The depth plane of a D32, D16 or D32S8 buffer has a twin too (R32 or R16), kept in step with +//! the plane around the title's transitions (`plan_barriers`): the PC buffer cannot be in +//! UNORDERED_ACCESS, so where the title has it there it rests in `PARK`; the title's transition +//! into UNORDERED_ACCESS is followed by a copy of the plane into the twin (what was drawn reaches +//! the shaders), its transition out of it is preceded by a copy of the twin into the plane (what +//! the shaders wrote reaches the next depth test or sampling). A transition names the state it +//! leaves and the one it enters, so each copy starts and ends in states the title gave. +//! +//! Behind `XCL_DEPTH_UAV_TWIN=1`; with the switch off nothing is registered, a UAV of a depth +//! buffer stays a null view and every hook stops at one atomic load. +//! +//! (After the depth+UAV twins of xcl-dev/xcl#1989 by raylitebull: registering at creation, DSVs, +//! forgetting at the last release, the UAV on a twin and its formats; and #1063 by IvyNotFound: +//! the PC state a buffer was created in.) + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, Weak}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::sharded::Sharded; + +/// The switch's value when `XCL_DEPTH_UAV_TWIN` is not set. +const DEFAULT_ON: bool = false; + +/// Whether depth buffers with unordered access are kept (`XCL_DEPTH_UAV_TWIN`). +pub(super) fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| on(std::env::var("XCL_DEPTH_UAV_TWIN").ok().as_deref(), DEFAULT_ON)) +} + +/// "0" off, "1" on, anything else (or nothing) `default`. +fn on(v: Option<&str>, default: bool) -> bool { + match v.map(str::trim) { + Some("0") => false, + Some("1") => true, + _ => default, + } +} + +/// What makes objects one buffer: on the PC, objects at one title address share texels. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +struct Key { + /// `vram::canonical_va` of the title address, or the object's address when it has none + at: usize, + /// `at` is a title address + placed: bool, + width: u32, + height: u32, + array: u16, + mips: u16, + /// the PC resource format: 19, 39, 44 or 53 + format: u32, +} + +struct Cell { + key: Key, + /// its number: what a list notes of it (`plan_barriers`) is not taken for a later Cell at the + /// same address + id: u64, + /// the format of the console's description + console_format: u32, + /// a twin was made + twinned: AtomicBool, + /// the last transition into UNORDERED_ACCESS recorded put the depth plane's twin in step with + /// the plane (a copy, or the two known to hold the same): only then is the twin copied back + /// (`plan_barriers`) + entered: AtomicBool, + inner: Mutex, +} + +#[derive(Default)] +struct Inner { + /// registered objects of this buffer + members: u32, + /// the PC state of the first object a title's creation call made (not the object of a view + /// by address, which is made in COMMON: `by_address`) + made_in: Option, + /// [depth, stencil] + twins: [Option; 2], +} + +/// A plane's twin: a colour texture of the plane's size with unordered access, resting in +/// UNORDERED_ACCESS. +struct Twin { + res: ID3D12Resource, + /// its number in the log (`#n`) + n: u64, +} + +// D3D12 resources are free-threaded +unsafe impl Send for Twin {} +unsafe impl Sync for Twin {} + +impl Drop for Twin { + fn drop(&mut self) { + TWINS.fetch_sub(1, Ordering::Relaxed); + } +} + +#[derive(Clone)] +struct Object { + cell: Arc, + /// the PC state the object was created in + state: u32, +} + +#[derive(Clone)] +#[allow(dead_code)] // (read once DSV binds are followed) +struct Dsv { + res: usize, + /// D3D12_DSV_FLAGS of the view: 1 read-only depth, 2 read-only stencil + flags: u32, + cell: Weak, +} + +/// Every Cell by its key: taken at creation and release only. +static CELLS: Mutex>>> = Mutex::new(None); +/// Registered objects by their address. +static OBJECTS: Sharded = Sharded::new(); +/// DSV handles that name a registered object. +static DSVS: Sharded = Sharded::new(); +/// The gates: entries in OBJECTS and DSVS. +static REGISTERED: AtomicUsize = AtomicUsize::new(0); +static DSV_ENTRIES: AtomicUsize = AtomicUsize::new(0); +/// Twins alive. +static TWINS: AtomicUsize = AtomicUsize::new(0); +/// Twins made, UAVs made on a twin, UAVs of depth buffers left null views. +static MADE: AtomicU64 = AtomicU64::new(0); +static REDIRECTED: AtomicU64 = AtomicU64::new(0); +static NULL_VIEWS: AtomicU64 = AtomicU64::new(0); +/// ClearUnorderedAccessView* done on a twin, and not done because what the view names is not known. +static UAV_CLEARS: AtomicU64 = AtomicU64::new(0); +static CLEARS_NOT_DONE: AtomicU64 = AtomicU64::new(0); +/// Cell numbers given. +static CELL_IDS: AtomicU64 = AtomicU64::new(1); +/// Copies of a depth plane into its twin, of a twin into its plane, and copies into the twin not +/// done since the two were in step (`plan_barriers`). +static TO_TWIN: AtomicU64 = AtomicU64::new(0); +static TO_PLANE: AtomicU64 = AtomicU64::new(0); +static IN_STEP: AtomicU64 = AtomicU64::new(0); + +/// Whether a twin is alive: the gate of the paths that record. +pub(super) fn any() -> bool { + TWINS.load(Ordering::Relaxed) != 0 +} + +/// Whether a buffer is kept: the gate of ResourceBarrier (`plan_barriers`). +pub(super) fn any_kept() -> bool { + REGISTERED.load(Ordering::Relaxed) != 0 +} + +fn u32_at(x: &[u8; 0x38], o: usize) -> u32 { + u32::from_le_bytes(x[o..o + 4].try_into().unwrap()) +} + +/// The PC object `res` was made for the console description `console_desc` in PC state +/// `pc_state` (the state of the call that succeeded), at the title address `va` (None: memory of +/// its own). Kept when it is a single-sample 2D depth buffer with unordered access. +pub(super) fn note_created(res: *mut c_void, console_desc: &[u8; 0x38], va: Option, pc_state: u32) { + if !enabled() || res.is_null() { + return; + } + register(res as usize, console_desc, va.map(super::vram::canonical_va), pc_state); +} + +/// `note_created` without the switch, `at` already canonical. True: kept. +fn register(res: usize, x: &[u8; 0x38], at: Option, pc_state: u32) -> bool { + let format = u32_at(&super::device_x::pc_resource_desc(x), 0x20); + if u32_at(x, 0) != D3D12_RESOURCE_DIMENSION_TEXTURE2D.0 as u32 || u32_at(x, 0x30) & 6 != 6 || u32_at(x, 0x24) > 1 || !matches!(format, 19 | 39 | 44 | 53) { + return false; + } + let key = Key { + at: at.unwrap_or(res), + placed: at.is_some(), + width: u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()) as u32, + height: u32_at(x, 0x18), + array: u16::from_le_bytes(x[0x1C..0x1E].try_into().unwrap()), + mips: u16::from_le_bytes(x[0x1E..0x20].try_into().unwrap()), + format, + }; + let mut g = CELLS.lock().unwrap(); + let cells = g.get_or_insert_with(HashMap::new); + let cell = cells + .entry(key) + .or_insert_with(|| Arc::new(Cell { key, id: CELL_IDS.fetch_add(1, Ordering::Relaxed), console_format: u32_at(x, 0x20), twinned: AtomicBool::new(false), entered: AtomicBool::new(false), inner: Mutex::new(Inner::default()) })) + .clone(); + { + let mut inner = cell.inner.lock().unwrap(); + inner.members += 1; + if inner.made_in.is_none() && !BY_ADDRESS.with(std::cell::Cell::get) { + inner.made_in = Some(pc_state); + } + } + // `XCL_TRACE_FRAME`: the big ones, with where they are – two buffers at one title address + // are one memory on the console + if key.width >= 1920 && super::present::trace_frame() { + static N: AtomicU32 = AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 96 { + crate::xlog_info!( + "frame trace: depth buffer with unordered access {res:#x}: {}x{}x{} mips {}, PC format {}, console format {}, {} {:#x}, made in PC state {pc_state:#x}{}", + key.width, + key.height, + key.array, + key.mips, + key.format, + u32_at(x, 0x20), + if key.placed { "at title address" } else { "memory of its own, object" }, + key.at, + if BY_ADDRESS.with(std::cell::Cell::get) { " (for a view by address)" } else { "" } + ); + } + } + let gone = match OBJECTS.insert(res, Object { cell, state: pc_state }) { + None => { + REGISTERED.fetch_add(1, Ordering::Relaxed); + Default::default() + } + // (an object XCL did not see released: its membership goes back) + Some(old) => leave(cells, &old.cell), + }; + drop(g); + drop(gone); + true +} + +thread_local! { + /// this thread is making the object of a view by address (`by_address`) + static BY_ADDRESS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// `f` makes the object of a view by address (`real::resource_at`): XCL makes it in COMMON, so +/// its state is not the one the title made the buffer in. +pub(super) fn by_address(f: impl FnOnce() -> R) -> R { + BY_ADDRESS.with(|b| b.set(true)); + let r = f(); + BY_ADDRESS.with(|b| b.set(false)); + r +} + +/// One object of `cell` is gone; the last one takes the Cell with it, and its twins, which the +/// caller drops outside every lock (their Release goes through `real::res_release`). +#[must_use] +fn leave(cells: &mut HashMap>, cell: &Arc) -> [Option; 2] { + let mut inner = cell.inner.lock().unwrap(); + inner.members = inner.members.saturating_sub(1); + if inner.members == 0 && cells.get(&cell.key).is_some_and(|c| Arc::ptr_eq(c, cell)) { + cells.remove(&cell.key); + return std::mem::take(&mut inner.twins); + } + Default::default() +} + +/// The last reference of `res` goes (`real::res_release`). +pub(super) fn forget(res: usize) { + if REGISTERED.load(Ordering::Relaxed) == 0 { + return; + } + let Some(o) = OBJECTS.remove(res) else { return }; + REGISTERED.fetch_sub(1, Ordering::Relaxed); + let gone = CELLS.lock().unwrap().as_mut().map(|cells| leave(cells, &o.cell)); + drop(gone); +} + +/// What a UAV of a resource is made on (`resolve_uav`). +pub(super) enum Resolve { + /// the twin, and the view of it + Twin(*mut c_void, D3D12_UNORDERED_ACCESS_VIEW_DESC), + /// a depth buffer whose UAV stays a null view, and why + Null(&'static str), + /// not a depth buffer with unordered access + NotOurs, +} + +/// CreateUnorderedAccessView of `res` (description `rd`) with the title's view `view` as it came: +/// a UAV of the stencil plane of a kept two-plane depth buffer, or of the depth plane of a kept +/// D32, D16 or D32S8 one, is made on the plane's twin (made now when there is none yet). +pub(super) unsafe fn resolve_uav(dev: *mut c_void, res: *mut c_void, rd: Option<&D3D12_RESOURCE_DESC>, view: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>) -> Resolve { + let Some(rd) = rd.filter(|d| d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0 && d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0) else { + return Resolve::NotOurs; + }; + if !enabled() { + static SAID: AtomicBool = AtomicBool::new(false); + if !SAID.swap(true, Ordering::Relaxed) { + crate::xlog_info!("D3D12.X: depth UAV twins are off (XCL_DEPTH_UAV_TWIN): a UAV of a depth buffer is a null view"); + } + return Resolve::Null("XCL_DEPTH_UAV_TWIN is off"); + } + if rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || rd.SampleDesc.Count > 1 { + return Resolve::Null("not a single-sample 2D depth buffer"); + } + if view.is_some_and(|v| !matches!(v.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE2D | D3D12_UAV_DIMENSION_TEXTURE2DARRAY)) { + return Resolve::Null("not a 2D view"); + } + // (no twin on a guessed state) + let Some(o) = OBJECTS.get(res as usize) else { return Resolve::Null("XCL did not see the buffer created") }; + let key = o.cell.key; + // `XCL_TRACE_FRAME`: which of the big buffers shaders get a UAV of, and of which plane + if key.width >= 1920 && super::present::trace_frame() { + static N: AtomicU32 = AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 96 { + crate::xlog_info!( + "frame trace: UAV of depth buffer {:#x} ({}x{} PC format {}, console format {}, at {:#x}): view format {}, its {} plane", + res as usize, + key.width, + key.height, + key.format, + o.cell.console_format, + key.at, + view.map_or(-1, |v| v.Format.0), + if stencil_view(view) { "stencil" } else { "depth" } + ); + } + } + let stencil = stencil_view(view); + // (a D24S8's depth plane: no UAV format holds it as a shader reads it) + if if stencil { !matches!(key.format, 19 | 44) } else { !matches!(key.format, 19 | 39 | 53) } { + return Resolve::Null("its depth plane has no twin yet"); + } + // (its states stay the title's: the twin would never be copied) + if !stencil && (o.cell.inner.lock().unwrap().made_in.unwrap_or(o.state) | o.state) & UNORDERED_ACCESS != 0 { + return Resolve::Null("the buffer was made in UNORDERED_ACCESS"); + } + // (the Cell holds the twin) + let Some((twin, _)) = plane_twin(&o, stencil as usize, dev) else { return Resolve::Null("the twin could not be made") }; + REDIRECTED.fetch_add(1, Ordering::Relaxed); + Resolve::Twin(twin.as_raw(), if stencil { twin_view(view, key.array) } else { depth_twin_view(view, key.array, key.format == 53) }) +} + +/// The twin of `plane` (0 depth, 1 stencil) of the buffer `o` is in, and its number: the one it +/// has, or one made now on the device `dev` (None: it could not be made). +unsafe fn plane_twin(o: &Object, plane: usize, dev: *mut c_void) -> Option<(ID3D12Resource, u64)> { + let key = o.cell.key; + let mut inner = o.cell.inner.lock().unwrap(); + if let Some(t) = &inner.twins[plane] { + return Some((t.res.clone(), t.n)); + } + let t = make_twin(dev, &key, twin_format(key.format, plane))?; + TWINS.fetch_add(1, Ordering::Relaxed); + let n = MADE.fetch_add(1, Ordering::Relaxed) + 1; + inner.twins[plane] = Some(Twin { res: t.clone(), n }); + o.cell.twinned.store(true, Ordering::Relaxed); + // (the state of the title's object; that of the UAV's own when the title made none) + let state = inner.made_in.unwrap_or(o.state); + if n <= 8 || n.is_power_of_two() { + if plane == 1 { + crate::xlog_info!( + "D3D12.X: depth UAV twin #{n}: the stencil plane of a {}x{}x{} depth buffer (PC format {}, console format {}) at {:#x} is an R8 texture; the buffer was made in state {:#x}", + key.width, + key.height, + key.array, + key.format, + o.cell.console_format, + key.at, + state + ); + } else { + crate::xlog_info!( + "D3D12.X: depth UAV twin #{n}: the depth plane of a {}x{}x{} depth buffer (PC format {}, console format {}) at {:#x} is an R{} texture, copied from the plane when the title moves the buffer into UNORDERED_ACCESS and back when it moves it out; the buffer was made in state {:#x}", + key.width, + key.height, + key.array, + key.format, + o.cell.console_format, + key.at, + if key.format == 53 { 16 } else { 32 }, + state + ); + } + } + Some((t, n)) +} + +/// The format of the twin of `plane` of a buffer of the PC format `format`: R8 for the stencil +/// plane, R16 for D16's depth, R32 for D32's and D32S8's (the plane copies as R32_TYPELESS). +fn twin_format(format: u32, plane: usize) -> DXGI_FORMAT { + match (plane, format) { + (1, _) => DXGI_FORMAT_R8_TYPELESS, + (_, 53) => DXGI_FORMAT_R16_TYPELESS, + _ => DXGI_FORMAT_R32_TYPELESS, + } +} + +/// Where a buffer whose depth plane can have a twin rests while the title has it in +/// UNORDERED_ACCESS: COPY_SOURCE, the state the plane is copied into the twin from. +pub(super) const PARK: u32 = 0x800; +/// D3D12_RESOURCE_STATE_UNORDERED_ACCESS, COPY_DEST +const UNORDERED_ACCESS: u32 = 0x8; +const COPY_DEST: u32 = 0x400; +/// The states in which nothing writes a depth plane: DEPTH_READ, NON_PIXEL_SHADER_RESOURCE, +/// PIXEL_SHADER_RESOURCE, INDIRECT_ARGUMENT, COPY_SOURCE, RESOLVE_SOURCE (and their sums). +const READ_ONLY: u32 = 0x20 | 0x40 | 0x80 | 0x200 | 0x800 | 0x2000; +/// D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY, END_ONLY +const BEGIN_ONLY: u32 = 1; +const END_ONLY: u32 = 2; + +/// A copy between depth plane subresources of a title's object and the same ones of the twin. +pub(super) struct PlaneCopy { + /// the object the title's transition names + pub depth: usize, + /// the subresource the transition names (or D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES) + pub sub: u32, + /// the depth plane's subresources it copies (the twin's have the same numbers) + pub subs: Vec, + pub twin: ID3D12Resource, +} + +/// What goes on the PC list with a title's barriers (`plan_barriers`). +#[derive(Default)] +pub(super) struct Plan { + /// before them: twins into depth planes (the buffer goes PARK → COPY_DEST, the title's + /// transition takes it on from COPY_DEST; the twin UNORDERED_ACCESS → COPY_SOURCE and back) + pub to_plane: Vec, + /// after them: depth planes into twins (the buffer rests in PARK; the twin + /// UNORDERED_ACCESS → COPY_DEST and back) + pub to_twin: Vec, +} + +/// Whether the depth plane of `o`'s buffer can have a twin: a D32, D16 or D32S8 buffer, and the +/// object was not made in UNORDERED_ACCESS (that object's states stay the title's). +fn plane_twinnable(o: &Object) -> bool { + matches!(o.cell.key.format, 19 | 39 | 53) && o.state & UNORDERED_ACCESS == 0 +} + +/// The title's barriers `barriers` (PC D3D12_RESOURCE_BARRIERs as words, the console's bits +/// dropped) on a list (`direct`: a DIRECT one) as they go to the PC, and the copies around +/// them. A transition of an object whose depth plane can have a twin into or out of +/// UNORDERED_ACCESS goes into or out of `PARK` instead (also on lists that copy nothing, so the +/// buffer's states agree wherever the title moves it; a split one at its end, whole); on a +/// DIRECT list the twin is copied from the plane after a transition into it (the twin made +/// then, when there is none yet) and into the plane before a transition out of it. +/// +/// `in_step` holds the Cells whose planes and twins are known to hold the same since a copy +/// earlier on this recording, with no transition to a state that writes the plane after it: +/// their copy into the twin is not done. It is the list's, and goes with its recording – what +/// another list did in between is not seen from here. +pub(super) fn plan_barriers(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec) -> Plan { + plan_with(barriers, direct, in_step, &mut |res, o| unsafe { + let r = res as *mut c_void; + let mut dev: Option = None; + ID3D12Resource::from_raw_borrowed(&r)?.GetDevice(&mut dev).ok()?; + plane_twin(o, 0, dev?.as_raw()) + }) +} + +/// `plan_barriers` with `twin` giving the depth twin of an object (made when there is none). +fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, twin: &mut dyn FnMut(usize, &Object) -> Option<(ID3D12Resource, u64)>) -> Plan { + let mut plan = Plan::default(); + if !any_kept() { + return plan; + } + let mut out = Vec::with_capacity(barriers.len()); + for mut b in barriers.drain(..) { + let res = (b[2] as u64 | (b[3] as u64) << 32) as usize; + let Some(o) = (b[0] == 0).then(|| OBJECTS.get(res)).flatten().filter(plane_twinnable) else { + out.push(b); + continue; + }; + let id = o.cell.id; + let (flags, sub, mut before, mut after) = (b[1], b[4], b[5], b[6]); + let (leaving, entering) = (before == UNORDERED_ACCESS, after == UNORDERED_ACCESS); + let writes = |s: u32| s == 0 || s & !READ_ONLY != 0; + if !leaving && !entering { + if writes(after) { + in_step.retain(|&c| c != id); + } + out.push(b); + continue; + } + // a split transition is done whole at its end: the copies go where the buffer is in the + // state the title left + if flags & BEGIN_ONLY != 0 { + continue; + } + b[1] = flags & !END_ONLY; + // the depth plane's subresources the transition names (the stencil plane's come after them) + let n = o.cell.key.mips.max(1) as u32 * o.cell.key.array.max(1) as u32; + let subs: Vec = if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES { (0..n).collect() } else { (sub < n).then_some(sub).into_iter().collect() }; + let entered = &o.cell.entered; + if !direct && o.cell.inner.lock().unwrap().twins[0].is_some() { + static SAID: AtomicBool = AtomicBool::new(false); + if !SAID.swap(true, Ordering::Relaxed) { + crate::xlog_warn!("D3D12.X: a buffer with a depth UAV twin goes into or out of UNORDERED_ACCESS on a compute or copy list: the twin is not copied there"); + } + } + if leaving { + before = PARK; + // (a twin whose last way in was not copied holds something else than the plane: not + // copied back – what the shaders wrote into it is lost, as without a twin) + let t = (direct && !subs.is_empty()).then(|| twin_if_made(&o)).flatten(); + if let Some((t, k)) = t.filter(|_| entered.load(Ordering::Relaxed)) { + before = COPY_DEST; + let c = TO_PLANE.fetch_add(1, Ordering::Relaxed) + 1; + if c <= 4 || c.is_power_of_two() { + crate::xlog_info!("D3D12.X: depth UAV twin #{k}: the title moves depth buffer {res:#x} out of UNORDERED_ACCESS into state {after:#x}: the twin is copied into its depth plane first ({c} such copies so far)"); + } + if subs.len() as u32 == n && !in_step.contains(&id) { + in_step.push(id); + } + plan.to_plane.push(PlaneCopy { depth: res, sub, subs: subs.clone(), twin: t }); + } + if writes(after) { + in_step.retain(|&c| c != id); + } + } + if entering { + after = PARK; + if !direct { + entered.store(false, Ordering::Relaxed); + } else if !subs.is_empty() { + // (a plane written since the copy that put the two in step: again) + if in_step.contains(&id) && !writes(before) { + IN_STEP.fetch_add(1, Ordering::Relaxed); + entered.store(true, Ordering::Relaxed); + } else if let Some((t, k)) = twin(res, &o) { + let c = TO_TWIN.fetch_add(1, Ordering::Relaxed) + 1; + if c <= 4 || c.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: depth UAV twin #{k}: the title moves depth buffer {res:#x} from state {before:#x} into UNORDERED_ACCESS: its depth plane is copied into the twin ({c} such copies so far, {} not needed)", + IN_STEP.load(Ordering::Relaxed) + ); + } + if subs.len() as u32 == n && !in_step.contains(&id) { + in_step.push(id); + } + entered.store(true, Ordering::Relaxed); + plan.to_twin.push(PlaneCopy { depth: res, sub, subs, twin: t }); + } else { + entered.store(false, Ordering::Relaxed); + } + } + } + (b[5], b[6]) = (before, after); + if before != after { + out.push(b); + } + } + *barriers = out; + plan +} + +/// The depth twin of `o`'s buffer when it has one, and its number. +fn twin_if_made(o: &Object) -> Option<(ID3D12Resource, u64)> { + o.cell.inner.lock().unwrap().twins[0].as_ref().map(|t| (t.res.clone(), t.n)) +} + +/// A UAV of a depth buffer stays a null view (`Resolve::Null`). +pub(super) fn null_view(why: &'static str) { + #[cfg(test)] + NULL_REASONS.lock().unwrap().push(why); + let n = NULL_VIEWS.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_warn!("D3D12.X: a UAV of a depth buffer stays a null view ({why}): {n} so far"); + } +} + +#[cfg(test)] +static NULL_REASONS: Mutex> = Mutex::new(Vec::new()); + +/// What a ClearUnorderedAccessView* goes to the PC with (`clear_target`). +#[derive(Debug, PartialEq)] +pub(super) enum Clear { + /// the resource the title gave + AsIs, + /// the twin the slot's view names + Twin(usize), + /// nothing: what the slot's view names is not known, or it is a null view + NotDone, +} + +/// ClearUnorderedAccessView* of `res` through a GPU slot whose UAV in the shared heap names +/// `named` (`console_heap::names_of`; None: the slot is not in the shared heap). The PC clear of +/// a view of a twin must name the twin: the depth buffer with the twin's view is an invalid pair. +/// A buffer with a twin whose slot names 0 or `GONE` is not cleared: 0 is also what a copy from a +/// slot outside the shared heap notes, and that copy may hold the twin's view. +pub(super) fn clear_target(res: usize, named: Option) -> Clear { + if !any() { + return Clear::AsIs; + } + let Some(o) = OBJECTS.get(res) else { return Clear::AsIs }; + let twins = o.cell.inner.lock().unwrap().twins.each_ref().map(|t| t.as_ref().map(|t| t.res.as_raw() as usize)); + let c = clear_choice(twins, named); + match c { + Clear::Twin(_) => UAV_CLEARS.fetch_add(1, Ordering::Relaxed), + Clear::NotDone => CLEARS_NOT_DONE.fetch_add(1, Ordering::Relaxed), + Clear::AsIs => 0, + }; + c +} + +/// `clear_target` for a buffer with the twins `twins`: the twin when the view names one; not +/// done when what it names is not known (a null view clears nothing either); else as it came +/// (a view of another resource). +fn clear_choice(twins: [Option; 2], named: Option) -> Clear { + if twins.iter().all(Option::is_none) { + return Clear::AsIs; + } + match named { + None | Some(0) | Some(super::console_heap::GONE) => Clear::NotDone, + Some(n) if twins.contains(&Some(n)) => Clear::Twin(n), + Some(_) => Clear::AsIs, + } +} + +/// `XCL_DUMP_TARGETS`: every twin alive, with its tag in the dump ("twin "). Each +/// rests in UNORDERED_ACCESS. +pub(super) fn twins_to_dump() -> Vec<(String, ID3D12Resource)> { + if !any() { + return Vec::new(); + } + let cells: Vec> = CELLS.lock().unwrap().as_ref().map_or(Vec::new(), |m| m.values().filter(|c| c.twinned.load(Ordering::Relaxed)).cloned().collect()); + let mut out = Vec::new(); + for c in cells { + let inner = c.inner.lock().unwrap(); + for (t, plane) in inner.twins.iter().zip(["depth", "stencil"]) { + if let Some(t) = t { + out.push((format!("twin{} {plane}", t.n), t.res.clone())); + } + } + } + out +} + +/// `XCL_DUMP_TARGETS`: what the twin dumped as `tag` (`twins_to_dump`) into the readback buffer +/// `rb` at `fp` holds: its most frequent values, how many differ and the share of zeros. +pub(super) unsafe fn log_values(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, tag: &str) { + let mut p: *mut c_void = std::ptr::null_mut(); + if rb.Map(0, None, Some(&mut p)).is_err() || p.is_null() { + return; + } + let f = &fp.Footprint; + let len = (rb.GetDesc().Width as usize).saturating_sub(fp.Offset as usize); + let data = std::slice::from_raw_parts((p as *const u8).add(fp.Offset as usize), len); + let counts = byte_counts(data, f.Width as usize, f.Height as usize, f.RowPitch as usize); + rb.Unmap(0, None); + let (top, distinct, zero) = most_frequent(&counts); + let (n, plane) = tag.strip_prefix("twin").and_then(|t| t.split_once(' ')).unwrap_or((tag, "")); + let values = top.iter().map(|(v, c)| format!("{v} ×{c}")).collect::>().join(", "); + crate::xlog_info!("D3D12.X: target dump: depth UAV twin #{n} ({}x{}, {plane}): {values} ({distinct} distinct values, {zero:.1} % zero)", f.Width, f.Height); +} + +/// Texels by byte value of a `w`x`h` 8-bit image whose rows start `pitch` bytes apart (the +/// padding after each row is not counted; a short buffer ends the count). +fn byte_counts(data: &[u8], w: usize, h: usize, pitch: usize) -> [u64; 256] { + let mut c = [0u64; 256]; + for y in 0..h { + let Some(row) = data.get(y * pitch..y * pitch + w) else { break }; + for &v in row { + c[v as usize] += 1; + } + } + c +} + +/// The eight most frequent values with their counts (most first; equal counts: the smaller +/// value first), the number of distinct values and the share of zeros in %. +fn most_frequent(c: &[u64; 256]) -> (Vec<(u8, u64)>, usize, f64) { + let mut v: Vec<(u8, u64)> = (0..256).filter(|&i| c[i] != 0).map(|i| (i as u8, c[i])).collect(); + let distinct = v.len(); + let total: u64 = c.iter().sum(); + v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + v.truncate(8); + (v, distinct, if total == 0 { 0.0 } else { c[0] as f64 * 100.0 / total as f64 }) +} + +/// A plane's twin of `key`: `format` (`twin_format`) with unordered access, of the buffer's +/// size, array and mips, in UNORDERED_ACCESS. Made through `real::dev_create_committed_resource`: +/// a PC resource, adopted, never in title memory. +unsafe fn make_twin(dev: *mut c_void, key: &Key, format: DXGI_FORMAT) -> Option { + if dev.is_null() { + return None; + } + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Alignment: 0, + Width: key.width as u64, + Height: key.height, + DepthOrArraySize: key.array.max(1), + MipLevels: key.mips, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + }; + let mut out = std::ptr::null_mut(); + let hr = super::real::dev_create_committed_resource( + dev, + &heap as *const _ as usize, + 0, + &desc as *const _ as usize, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as usize, + 0, + &ID3D12Resource::IID as *const _ as *const windows_sys::core::GUID, + &mut out, + ); + (hr >= 0 && !out.is_null()).then(|| ID3D12Resource::from_raw(out)) +} + +/// The view names the stencil plane: plane slice 1, or a stencil or 8-bit format. +fn stencil_view(view: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>) -> bool { + let Some(v) = view else { return false }; + let plane = unsafe { + match v.ViewDimension { + D3D12_UAV_DIMENSION_TEXTURE2D => v.Anonymous.Texture2D.PlaneSlice, + D3D12_UAV_DIMENSION_TEXTURE2DARRAY => v.Anonymous.Texture2DArray.PlaneSlice, + _ => 0, + } + }; + plane == 1 || matches!(v.Format.0, 22 | 47 | 60..=64 | 120) +} + +/// The twin's view: the title's (a Texture2D or Texture2DArray one when it gave none) on plane 0, +/// R8_UINT or the 8-bit class the title asked for (UNORM, SNORM, SINT). +fn twin_view(view: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>, array: u16) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + let mut v = plane_view(view, array); + v.Format = match v.Format { + f @ (DXGI_FORMAT_R8_UNORM | DXGI_FORMAT_R8_SNORM | DXGI_FORMAT_R8_SINT) => f, + _ => DXGI_FORMAT_R8_UINT, + }; + v +} + +/// The depth twin's view (`r16`: of a D16's R16 twin, else of an R32 one): the title's on plane +/// 0, as `twin_view`'s; R32_FLOAT or R16_UNORM – the depth as a shader reads it – unless the +/// title asked for another class of the twin's size (R32_UINT, R16_UINT …). +fn depth_twin_view(view: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>, array: u16, r16: bool) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + let mut v = plane_view(view, array); + v.Format = match (r16, v.Format) { + (false, f @ (DXGI_FORMAT_R32_FLOAT | DXGI_FORMAT_R32_UINT | DXGI_FORMAT_R32_SINT)) => f, + (false, _) => DXGI_FORMAT_R32_FLOAT, + (true, f @ (DXGI_FORMAT_R16_UNORM | DXGI_FORMAT_R16_UINT | DXGI_FORMAT_R16_SNORM | DXGI_FORMAT_R16_SINT | DXGI_FORMAT_R16_FLOAT)) => f, + (true, _) => DXGI_FORMAT_R16_UNORM, + }; + v +} + +/// The title's view (a Texture2D or Texture2DArray one of the whole buffer when it gave none) +/// on plane 0, its format as it came. +fn plane_view(view: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>, array: u16) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + let mut v = match view { + Some(v) => *v, + None if array > 1 => D3D12_UNORDERED_ACCESS_VIEW_DESC { + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture2DArray: D3D12_TEX2D_ARRAY_UAV { MipSlice: 0, FirstArraySlice: 0, ArraySize: array as u32, PlaneSlice: 0 } }, + ..Default::default() + }, + None => D3D12_UNORDERED_ACCESS_VIEW_DESC { ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, ..Default::default() }, + }; + match v.ViewDimension { + D3D12_UAV_DIMENSION_TEXTURE2D => v.Anonymous.Texture2D.PlaneSlice = 0, + D3D12_UAV_DIMENSION_TEXTURE2DARRAY => v.Anonymous.Texture2DArray.PlaneSlice = 0, + _ => {} + } + v +} + +/// (tests) Whether `res` is kept. +#[cfg(test)] +pub(super) fn kept(res: usize) -> bool { + OBJECTS.contains(res) +} + +/// (tests) The state line L2 gives for the buffer `res` is in, and whether that buffer has a +/// title address. +#[cfg(test)] +pub(super) fn made_in(res: usize) -> Option<(Option, Option)> { + let o = OBJECTS.get(res)?; + let made_in = o.cell.inner.lock().unwrap().made_in; + Some((made_in, o.cell.key.placed.then_some(o.cell.key.at))) +} + +/// (tests) The stencil twin of the buffer `res` is in. +#[cfg(test)] +pub(super) fn twin_of(res: usize) -> Option { + OBJECTS.get(res)?.cell.inner.lock().unwrap().twins[1].as_ref().map(|t| t.res.as_raw() as usize) +} + +/// (tests) The depth twin of the buffer `res` is in. +#[cfg(test)] +pub(super) fn depth_twin_of(res: usize) -> Option { + OBJECTS.get(res)?.cell.inner.lock().unwrap().twins[0].as_ref().map(|t| t.res.as_raw() as usize) +} + +/// (tests) Copies of depth planes into their twins, of twins into their planes, and copies into +/// twins not done since the two were in step. +#[cfg(test)] +pub(super) fn plane_copies() -> (u64, u64, u64) { + (TO_TWIN.load(Ordering::Relaxed), TO_PLANE.load(Ordering::Relaxed), IN_STEP.load(Ordering::Relaxed)) +} + +/// (tests) The object a DSV handle names. +#[cfg(test)] +pub(super) fn dsv_names(handle: usize) -> Option { + DSVS.get(handle).map(|d| d.res) +} + +/// (tests) Twins made, twins alive, UAVs made on a twin, and the reasons of the null views so far. +#[cfg(test)] +pub(super) fn counts() -> (u64, usize, u64, Vec<&'static str>) { + (MADE.load(Ordering::Relaxed), TWINS.load(Ordering::Relaxed), REDIRECTED.load(Ordering::Relaxed), NULL_REASONS.lock().unwrap().clone()) +} + +/// (tests) UAV clears done on a twin, and not done. +#[cfg(test)] +pub(super) fn clears() -> (u64, u64) { + (UAV_CLEARS.load(Ordering::Relaxed), CLEARS_NOT_DONE.load(Ordering::Relaxed)) +} + +/// CreateDepthStencilView of `res` at `handle` with D3D12_DSV_FLAGS `flags`. +pub(super) fn note_dsv(handle: usize, res: usize, flags: u32) { + if REGISTERED.load(Ordering::Relaxed) == 0 && DSV_ENTRIES.load(Ordering::Relaxed) == 0 { + return; + } + match OBJECTS.get(res) { + Some(o) => { + if DSVS.insert(handle, Dsv { res, flags, cell: Arc::downgrade(&o.cell) }).is_none() { + DSV_ENTRIES.fetch_add(1, Ordering::Relaxed); + } + } + None => forget_dsv(handle), + } +} + +/// The D3D12_DSV_FLAGS of the DSV at `handle` when it names a kept buffer (`XCL_TRACE_FRAME`). +pub(super) fn dsv_flags(handle: usize) -> Option { + if DSV_ENTRIES.load(Ordering::Relaxed) == 0 { + return None; + } + DSVS.get(handle).map(|d| d.flags) +} + +fn forget_dsv(handle: usize) { + if DSV_ENTRIES.load(Ordering::Relaxed) != 0 && DSVS.remove(handle).is_some() { + DSV_ENTRIES.fetch_sub(1, Ordering::Relaxed); + } +} + +/// The DSV handle increment of `dev`, read once. +unsafe fn dsv_increment(dev: *mut c_void) -> u64 { + static INC: AtomicU32 = AtomicU32::new(0); + let mut inc = INC.load(Ordering::Relaxed); + if inc == 0 { + let Some(d) = ID3D12Device::from_raw_borrowed(&dev) else { return 0 }; + inc = d.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); + INC.store(inc, Ordering::Relaxed); + } + inc as u64 +} + +/// CopyDescriptorsSimple of `n` DSVs from `src` to `dst`: each destination names what its source +/// names, or nothing. +pub(super) unsafe fn dsvs_copied(dev: *mut c_void, n: u32, dst: u64, src: u64) { + if DSV_ENTRIES.load(Ordering::Relaxed) == 0 { + return; + } + copy_dsvs(n, dst, src, dsv_increment(dev)); +} + +/// CopyDescriptors of DSVs: destination and source ranges (start, length; no lengths: 1 each) +/// walked in step. +#[allow(clippy::too_many_arguments)] +pub(super) unsafe fn dsv_ranges_copied(dev: *mut c_void, nd: u32, dsts: *const u64, dsizes: *const u32, ns: u32, srcs: *const u64, ssizes: *const u32) { + if DSV_ENTRIES.load(Ordering::Relaxed) == 0 || dsts.is_null() || srcs.is_null() { + return; + } + let ranges = |starts: *const u64, sizes: *const u32, n: u32| -> Vec<(u64, u32)> { + (0..n as usize).map(|r| (*starts.add(r), if sizes.is_null() { 1 } else { *sizes.add(r) })).collect() + }; + let inc = dsv_increment(dev); + for (dst, src, n) in pieces(&ranges(dsts, dsizes, nd), &ranges(srcs, ssizes, ns), inc) { + copy_dsvs(n, dst, src, inc); + } +} + +/// Destination and source ranges cut where either one ends: (dst, src, n) runs. +fn pieces(dsts: &[(u64, u32)], srcs: &[(u64, u32)], inc: u64) -> Vec<(u64, u64, u32)> { + let (mut out, mut d, mut s, mut dk, mut sk) = (Vec::new(), 0, 0, 0u32, 0u32); + while d < dsts.len() && s < srcs.len() { + let n = (dsts[d].1 - dk).min(srcs[s].1 - sk); + if n > 0 { + out.push((dsts[d].0 + dk as u64 * inc, srcs[s].0 + sk as u64 * inc, n)); + } + dk += n; + sk += n; + if dk == dsts[d].1 { + (d, dk) = (d + 1, 0); + } + if sk == srcs[s].1 { + (s, sk) = (s + 1, 0); + } + } + out +} + +fn copy_dsvs(n: u32, dst: u64, src: u64, inc: u64) { + for k in 0..n as u64 { + let (to, from) = ((dst + k * inc) as usize, (src + k * inc) as usize); + match DSVS.get(from) { + Some(v) => { + if DSVS.insert(to, v).is_none() { + DSV_ENTRIES.fetch_add(1, Ordering::Relaxed); + } + } + None => forget_dsv(to), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A console resource description: 2D, `w`x`h`, one slice and mip, `samples`, `flags`. + fn desc(dim: u32, w: u64, h: u32, format: u32, samples: u32, flags: u32) -> [u8; 0x38] { + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&dim.to_le_bytes()); + x[0x10..0x18].copy_from_slice(&w.to_le_bytes()); + x[0x18..0x1C].copy_from_slice(&h.to_le_bytes()); + x[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + x[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + x[0x20..0x24].copy_from_slice(&format.to_le_bytes()); + x[0x24..0x28].copy_from_slice(&samples.to_le_bytes()); + x[0x30..0x34].copy_from_slice(&flags.to_le_bytes()); + x + } + + fn cell_of(res: usize) -> Option> { + OBJECTS.get(res).map(|o| o.cell) + } + + #[test] + fn the_switch_reads_0_and_1() { + assert!(!on(Some("0"), true)); + assert!(on(Some("1"), false)); + assert!(on(Some(" 1\n"), false), "trimmed"); + assert!(on(Some("yes"), true) && !on(Some("yes"), false), "anything else: the default"); + assert!(on(None, true) && !on(None, false)); + } + + #[test] + fn only_depth_buffers_that_allow_unordered_access_are_kept() { + let base = 0x7A00_0000_0000usize; + // console D24S8 (45), D16S8 (118), D32 (40), D16 (55), D32S8 (20) with flags 6 + for (k, f) in [45u32, 118, 40, 55, 20].into_iter().enumerate() { + let res = base + k * 0x100; + assert!(register(res, &desc(3, 64, 32, f, 1, 6), Some(res), 0x10), "format {f}"); + assert_eq!(cell_of(res).unwrap().key.format, [44, 44, 39, 53, 19][k]); + forget(res); + assert!(cell_of(res).is_none()); + } + let refused = [ + ("depth only", desc(3, 64, 32, 45, 1, 2)), + ("unordered access only", desc(3, 64, 32, 41, 1, 4)), + ("4 samples", desc(3, 64, 32, 45, 4, 6)), + ("a 3D texture", desc(4, 64, 32, 45, 1, 6)), + ("a colour format", desc(3, 64, 32, 28, 1, 6)), + ]; + for (k, (what, x)) in refused.iter().enumerate() { + let res = base + 0x1_0000 + k * 0x100; + assert!(!register(res, x, None, 0x10), "{what}"); + assert!(cell_of(res).is_none(), "{what}"); + } + } + + #[test] + fn depth_buffers_at_one_title_address_share_a_cell_until_the_last_is_released() { + let (a, b, c, at) = (0x7B00_0000_1000usize, 0x7B00_0000_2000usize, 0x7B00_0000_3000usize, 0x2_0000_0000usize); + let x = desc(3, 2560, 1440, 45, 1, 6); + assert!(register(a, &x, Some(at), 0x10)); + assert!(register(b, &x, Some(at), 0)); + let (ca, cb) = (cell_of(a).unwrap(), cell_of(b).unwrap()); + assert!(Arc::ptr_eq(&ca, &cb), "one address, one shape: one Cell"); + assert_eq!(ca.inner.lock().unwrap().members, 2); + assert_eq!((OBJECTS.get(a).unwrap().state, OBJECTS.get(b).unwrap().state), (0x10, 0), "each object keeps its own state"); + // another shape at the address, and memory of its own: Cells of their own + assert!(register(c, &desc(3, 1280, 720, 45, 1, 6), Some(at), 0x10)); + assert!(!Arc::ptr_eq(&ca, &cell_of(c).unwrap())); + let own = 0x7B00_0000_4000usize; + assert!(register(own, &x, None, 0x10)); + let co = cell_of(own).unwrap(); + assert!(!co.key.placed && co.key.at == own && !Arc::ptr_eq(&ca, &co)); + + let in_cells = |k: &Key| CELLS.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(k)); + forget(a); + assert!(in_cells(&ca.key) && ca.inner.lock().unwrap().members == 1, "b still holds it"); + forget(b); + assert!(!in_cells(&ca.key), "the last release takes the Cell"); + // a second registration of one address without a release gives the first one's membership back + assert!(register(own, &x, None, 0x10)); + assert_eq!(cell_of(own).unwrap().inner.lock().unwrap().members, 1); + forget(own); + forget(c); + assert!(!in_cells(&co.key) && cell_of(c).is_none()); + } + + /// The library's tests run with the switch as the process has it (by default as DEFAULT_ON). + #[test] + fn the_switch_decides_whether_a_buffer_is_kept_and_its_uavs_redirected() { + let res = 0x7B20_0000_1000usize; + note_created(res as *mut c_void, &desc(3, 64, 64, 45, 1, 6), Some(0x2_2000_0000), 0x10); + assert_eq!(kept(res), enabled(), "registered only with the switch on"); + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R24G8_TYPELESS, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + // (no device: with the switch on the twin cannot be made, it is never a twin here) + let why = match unsafe { resolve_uav(std::ptr::null_mut(), res as *mut c_void, Some(&rd), Some(&uav2d(DXGI_FORMAT_X24_TYPELESS_G8_UINT, 1))) } { + Resolve::Null(why) => Some(why), + Resolve::Twin(..) | Resolve::NotOurs => None, + }; + if enabled() { + assert_eq!(why, Some("the twin could not be made")); + } else { + assert_eq!(why, Some("XCL_DEPTH_UAV_TWIN is off"), "off: a null view, as before the twins"); + } + forget(res); + assert!(!kept(res)); + } + + #[test] + fn the_state_a_buffer_was_made_in_is_that_of_the_titles_object() { + let (view, title, at) = (0x7B10_0000_1000usize, 0x7B10_0000_2000usize, 0x2_1000_0000usize); + let x = desc(3, 2560, 1440, 45, 1, 6); + // the object of a view by address comes first and is made in COMMON: not the buffer's state + assert!(by_address(|| register(view, &x, Some(at), 0))); + assert_eq!(made_in(view), Some((None, Some(at)))); + assert!(!BY_ADDRESS.with(std::cell::Cell::get), "the mark ends with the call"); + assert!(register(title, &x, Some(at), 0x10)); + assert_eq!(made_in(view), Some((Some(0x10), Some(at))), "the title's object gives it"); + // a later object, or one made by address again, does not change it + assert!(by_address(|| register(view, &x, Some(at), 0))); + assert_eq!(made_in(title), Some((Some(0x10), Some(at)))); + forget(view); + forget(title); + assert!(cell_of(title).is_none()); + } + + #[test] + fn a_copied_dsv_names_what_its_source_names() { + let (res, inc) = (0x7C00_0000_1000usize, 0x20u64); + let (heap, other) = (0x5_0000_0000u64, 0x6_0000_0000u64); + assert!(register(res, &desc(3, 64, 64, 45, 1, 6), None, 0x10)); + note_dsv(heap as usize, res, 2); + assert!(DSVS.get(heap as usize).is_some_and(|d| d.res == res && d.flags == 2)); + // a DSV of a resource that is not kept: not known (and an older entry there goes) + note_dsv(heap as usize + 0x20, 0x7C00_0000_9000, 0); + assert!(DSVS.get(heap as usize + 0x20).is_none()); + + // two descriptors from `heap`: the first names `res`, the second nothing + note_dsv(other as usize + 0x20, res, 0); + copy_dsvs(2, other, heap, inc); + assert!(DSVS.get(other as usize).is_some_and(|d| d.res == res && d.flags == 2 && d.cell.upgrade().is_some())); + assert!(DSVS.get(other as usize + 0x20).is_none(), "a copy from an unknown handle forgets the destination"); + + // ranges are cut where either side ends + assert_eq!(pieces(&[(0x100, 3)], &[(0x500, 1), (0x900, 2)], inc), vec![(0x100, 0x500, 1), (0x120, 0x900, 2)]); + assert_eq!(pieces(&[(0x100, 1), (0x300, 2)], &[(0x500, 2)], inc), vec![(0x100, 0x500, 1), (0x300, 0x520, 1)]); + assert_eq!(pieces(&[(0x100, 0), (0x300, 1)], &[(0x500, 1)], inc), vec![(0x300, 0x500, 1)]); + + forget(res); + assert!(DSVS.get(other as usize).is_some_and(|d| d.cell.upgrade().is_none()), "a DSV of a buffer that went names no Cell"); + forget_dsv(heap as usize); + forget_dsv(other as usize); + } + + fn uav2d(format: DXGI_FORMAT, plane: u32) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: format, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: plane } }, + } + } + + fn uav2d_array(format: DXGI_FORMAT, mip: u32, first: u32, n: u32, plane: u32) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: format, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture2DArray: D3D12_TEX2D_ARRAY_UAV { MipSlice: mip, FirstArraySlice: first, ArraySize: n, PlaneSlice: plane } }, + } + } + + #[test] + fn a_view_names_the_stencil_plane_by_format_or_plane_slice() { + // X32_TYPELESS_G8X24_UINT, X24_TYPELESS_G8_UINT, the R8 formats, the console's X16_TYPELESS_G8_UINT + for f in [22, 47, 60, 61, 62, 63, 64, 120] { + assert!(stencil_view(Some(&uav2d(DXGI_FORMAT(f), 0))), "format {f}"); + } + assert!(stencil_view(Some(&uav2d(DXGI_FORMAT_R32_UINT, 1))), "plane slice 1"); + assert!(stencil_view(Some(&uav2d_array(DXGI_FORMAT_UNKNOWN, 0, 0, 2, 1))), "plane slice 1 of an array view"); + // R24_UNORM_X8_TYPELESS, R32_FLOAT, R16_UNORM, R32_UINT, R32_FLOAT_X8X24_TYPELESS on plane 0; no view + for f in [46, 41, 56, 42, 21] { + assert!(!stencil_view(Some(&uav2d(DXGI_FORMAT(f), 0))), "format {f}"); + } + assert!(!stencil_view(None)); + } + + #[test] + fn the_twins_view_keeps_the_slices_and_the_r8_class_asked_for() { + let v = twin_view(Some(&uav2d_array(DXGI_FORMAT_X24_TYPELESS_G8_UINT, 1, 2, 3, 1)), 6); + assert_eq!((v.Format, v.ViewDimension), (DXGI_FORMAT_R8_UINT, D3D12_UAV_DIMENSION_TEXTURE2DARRAY)); + let a = unsafe { v.Anonymous.Texture2DArray }; + assert_eq!((a.MipSlice, a.FirstArraySlice, a.ArraySize, a.PlaneSlice), (1, 2, 3, 0)); + let v = twin_view(Some(&uav2d(DXGI_FORMAT(120), 1)), 1); + assert_eq!((v.Format, v.ViewDimension, unsafe { v.Anonymous.Texture2D.PlaneSlice }), (DXGI_FORMAT_R8_UINT, D3D12_UAV_DIMENSION_TEXTURE2D, 0)); + for f in [DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8_SNORM, DXGI_FORMAT_R8_SINT, DXGI_FORMAT_R8_UINT] { + assert_eq!(twin_view(Some(&uav2d(f, 0)), 1).Format, f, "{f:?}"); + } + // no view: the whole buffer + let v = twin_view(None, 4); + assert_eq!((v.Format, v.ViewDimension, unsafe { v.Anonymous.Texture2DArray.ArraySize }), (DXGI_FORMAT_R8_UINT, D3D12_UAV_DIMENSION_TEXTURE2DARRAY, 4)); + let v = twin_view(None, 1); + assert_eq!((v.Format, v.ViewDimension, unsafe { v.Anonymous.Texture2D.PlaneSlice }), (DXGI_FORMAT_R8_UINT, D3D12_UAV_DIMENSION_TEXTURE2D, 0)); + } + + #[test] + fn a_depth_view_is_a_view_of_a_twin_of_the_planes_size() { + assert_eq!( + [twin_format(39, 0), twin_format(19, 0), twin_format(53, 0), twin_format(44, 1), twin_format(19, 1)], + [DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_TYPELESS], + "D32, D32S8, D16 depth; stencil" + ); + // an R32 twin: the depth as a float unless the title asked for another R32 class + for (asked, got) in [ + (DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32_FLOAT), + (DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_R32_FLOAT), + (DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_FLOAT), + (DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, DXGI_FORMAT_R32_FLOAT), + (DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_R32_FLOAT), + (DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32_UINT), + ] { + assert_eq!(depth_twin_view(Some(&uav2d(asked, 0)), 1, false).Format, got, "{asked:?}"); + } + // an R16 one: UNORM unless another R16 class was asked for + for (asked, got) in [ + (DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R16_UNORM), + (DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_R16_UNORM), + (DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UNORM), + (DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R16_UNORM), + (DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R16_UINT), + ] { + assert_eq!(depth_twin_view(Some(&uav2d(asked, 0)), 1, true).Format, got, "{asked:?}"); + } + let v = depth_twin_view(Some(&uav2d_array(DXGI_FORMAT_R32_FLOAT, 1, 2, 3, 0)), 6, false); + let a = unsafe { v.Anonymous.Texture2DArray }; + assert_eq!((v.ViewDimension, a.MipSlice, a.FirstArraySlice, a.ArraySize, a.PlaneSlice), (D3D12_UAV_DIMENSION_TEXTURE2DARRAY, 1, 2, 3, 0)); + // no view: the whole buffer + let v = depth_twin_view(None, 4, true); + assert_eq!((v.Format, v.ViewDimension, unsafe { v.Anonymous.Texture2DArray.ArraySize }), (DXGI_FORMAT_R16_UNORM, D3D12_UAV_DIMENSION_TEXTURE2DARRAY, 4)); + // (the stencil twin's view is as it was) + assert_eq!(twin_view(None, 1).Format, DXGI_FORMAT_R8_UINT); + } + + /// The library's tests run with the switch as the process has it (by default as DEFAULT_ON). + #[test] + fn a_depth_uav_of_a_d32_or_d16_buffer_asks_for_a_twin_and_a_d24s8_one_stays_null() { + let rd = |format| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let base = 0x7B30_0000_1000usize; + // console D32, D16, D32S8, D24S8; the PC formats of the buffers; the views of their depth + for (k, (console, pc, view, on)) in [ + (40u32, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_FLOAT, "the twin could not be made"), + (55, DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UNORM, "the twin could not be made"), + (20, DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, "the twin could not be made"), + (45, DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_R24_UNORM_X8_TYPELESS, "its depth plane has no twin yet"), + ] + .into_iter() + .enumerate() + { + let res = base + k * 0x100; + note_created(res as *mut c_void, &desc(3, 64, 64, console, 1, 6), None, 0x10); + // (no device: with the switch on a twin is asked for and cannot be made) + let why = match unsafe { resolve_uav(std::ptr::null_mut(), res as *mut c_void, Some(&rd(pc)), Some(&uav2d(view, 0))) } { + Resolve::Null(why) => Some(why), + Resolve::Twin(..) | Resolve::NotOurs => None, + }; + assert_eq!(why, Some(if enabled() { on } else { "XCL_DEPTH_UAV_TWIN is off" }), "console format {console}"); + forget(res); + } + } + + #[test] + fn the_resource_of_a_uav_clear_is_what_the_view_names() { + let (twin, buffer, other) = (0x7D00_0000_1000usize, 0x7D00_0000_2000usize, 0x7D00_0000_3000usize); + let twinned = [None, Some(twin)]; + assert_eq!(clear_choice(twinned, Some(twin)), Clear::Twin(twin), "the view names the twin"); + assert_eq!(clear_choice(twinned, Some(other)), Clear::AsIs, "a view of another resource"); + assert_eq!(clear_choice(twinned, None), Clear::NotDone, "a slot outside the shared heap: not known"); + // 0: a null view, or a copy of a slot outside the shared heap (which may hold the twin's + // view); GONE: the null view of a destroyed resource + assert_eq!(clear_choice(twinned, Some(0)), Clear::NotDone, "0: not known"); + assert_eq!(clear_choice(twinned, Some(super::super::console_heap::GONE)), Clear::NotDone, "GONE"); + // a buffer without a twin, whatever the slot + for named in [None, Some(0), Some(buffer)] { + assert_eq!(clear_choice([None, None], named), Clear::AsIs, "{named:?}"); + } + + // the lookup: a kept buffer with a stand-in twin (a COM object that only counts + // references), one without a twin, and one XCL does not keep + unsafe extern "system" fn add_ref(_this: *mut c_void) -> u32 { + 1 + } + let vt: &'static [usize; 3] = Box::leak(Box::new([0, add_ref as usize, add_ref as usize])); + let fake: &'static mut *const usize = Box::leak(Box::new(vt.as_ptr())); + let fake = fake as *mut *const usize as *mut c_void; + let untwinned = 0x7D00_0000_4000usize; + assert!(register(buffer, &desc(3, 64, 64, 45, 1, 6), None, 0x10)); + assert!(register(untwinned, &desc(3, 32, 32, 45, 1, 6), None, 0x10)); + { + let o = OBJECTS.get(buffer).unwrap(); + TWINS.fetch_add(1, Ordering::Relaxed); + o.cell.inner.lock().unwrap().twins[1] = Some(Twin { res: unsafe { ID3D12Resource::from_raw(fake) }, n: 0 }); + } + let t = fake as usize; + let before = clears(); + assert_eq!(clear_target(buffer, Some(t)), Clear::Twin(t), "the slot names the twin"); + assert_eq!(clear_target(buffer, None), Clear::NotDone, "not known"); + assert_eq!(clear_target(buffer, Some(0)), Clear::NotDone, "0"); + assert_eq!(clear_target(buffer, Some(other)), Clear::AsIs, "a view of another resource"); + assert_eq!(clear_target(untwinned, None), Clear::AsIs, "a kept buffer without a twin"); + assert_eq!(clear_target(other, None), Clear::AsIs, "a buffer XCL does not keep"); + let after = clears(); + assert_eq!((after.0 - before.0, after.1 - before.1), (1, 2), "one clear on the twin, two not done"); + // (the last release takes the stand-in twin with the Cell) + forget(buffer); + forget(untwinned); + } + + /// A stand-in for a twin: a COM object that only counts references. + fn stand_in() -> ID3D12Resource { + unsafe extern "system" fn add_ref(_this: *mut c_void) -> u32 { + 1 + } + let vt: &'static [usize; 3] = Box::leak(Box::new([0, add_ref as usize, add_ref as usize])); + let fake: &'static mut *const usize = Box::leak(Box::new(vt.as_ptr())); + unsafe { ID3D12Resource::from_raw(fake as *mut *const usize as *mut c_void) } + } + + /// `res` (kept) gets the stand-in twin `t` for its depth plane. + fn plant_depth_twin(res: usize, t: &ID3D12Resource) { + let o = OBJECTS.get(res).unwrap(); + TWINS.fetch_add(1, Ordering::Relaxed); + o.cell.inner.lock().unwrap().twins[0] = Some(Twin { res: t.clone(), n: 0 }); + } + + fn tr(res: usize, sub: u32, before: u32, after: u32) -> [u32; 8] { + [0, 0, res as u32, (res as u64 >> 32) as u32, sub, before, after, 0] + } + + const ALL: u32 = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + const UA: u32 = UNORDERED_ACCESS; + const DEPTH_WRITE: u32 = 0x10; + const DEPTH_READ: u32 = 0x20; + + /// (the copies of a plan: (object, subresource of the transition, subresources copied, twin)) + fn copies(c: &[PlaneCopy]) -> Vec<(usize, u32, Vec, usize)> { + c.iter().map(|c| (c.depth, c.sub, c.subs.clone(), c.twin.as_raw() as usize)).collect() + } + + #[test] + fn the_titles_unordered_access_of_a_depth_buffer_is_parked_and_its_twin_copied_around_it() { + let res = 0x7E00_0000_1000usize; + // a console D32 with unordered access, made in DEPTH_WRITE, with a depth twin + assert!(register(res, &desc(3, 64, 64, 40, 1, 6), None, DEPTH_WRITE)); + let t = stand_in(); + plant_depth_twin(res, &t); + let tw = t.as_raw() as usize; + assert_eq!(depth_twin_of(res), Some(tw)); + let id = cell_of(res).unwrap().id; + let asked = std::cell::Cell::new(0); + let mut twin = |_r: usize, o: &Object| { + asked.set(asked.get() + 1); + twin_if_made(o) + }; + let mut in_step = Vec::new(); + let mut plan = |b: [u32; 8], direct: bool, in_step: &mut Vec| { + let mut v = vec![b]; + let p = plan_with(&mut v, direct, in_step, &mut twin); + (v, copies(&p.to_plane), copies(&p.to_twin)) + }; + let one = |sub: u32| vec![(res, sub, vec![0], tw)]; + + // into UNORDERED_ACCESS: the buffer goes to PARK, its plane is copied into the twin after + // the barriers; the two are in step + assert_eq!(plan(tr(res, ALL, DEPTH_WRITE, UA), true, &mut in_step), (vec![tr(res, ALL, DEPTH_WRITE, PARK)], vec![], one(ALL))); + assert_eq!(in_step, [id]); + // out of it into DEPTH_READ: the twin is copied into the plane first, the transition goes + // on from COPY_DEST; still in step (nothing writes the plane in DEPTH_READ) + assert_eq!(plan(tr(res, ALL, UA, DEPTH_READ), true, &mut in_step), (vec![tr(res, ALL, COPY_DEST, DEPTH_READ)], one(ALL), vec![])); + assert_eq!(in_step, [id]); + // into it again from DEPTH_READ: the twin holds the plane, no copy + let (_, _, skipped) = plane_copies(); + assert_eq!(plan(tr(res, ALL, DEPTH_READ, UA), true, &mut in_step), (vec![tr(res, ALL, DEPTH_READ, PARK)], vec![], vec![])); + assert!(plane_copies().2 > skipped, "counted as not needed"); + // out into DEPTH_WRITE: copied back; the plane is drawn into from then on + assert_eq!(plan(tr(res, ALL, UA, DEPTH_WRITE), true, &mut in_step), (vec![tr(res, ALL, COPY_DEST, DEPTH_WRITE)], one(ALL), vec![])); + assert!(in_step.is_empty()); + // so into it again is a copy again + assert_eq!(plan(tr(res, ALL, DEPTH_WRITE, UA), true, &mut in_step), (vec![tr(res, ALL, DEPTH_WRITE, PARK)], vec![], one(ALL))); + // a split transition out: its beginning goes, its end is done whole, with the copy + let mut begin = tr(res, ALL, UA, DEPTH_WRITE); + begin[1] = BEGIN_ONLY; + assert_eq!(plan(begin, true, &mut in_step), (vec![], vec![], vec![])); + let mut end = tr(res, ALL, UA, DEPTH_WRITE); + end[1] = END_ONLY; + assert_eq!(plan(end, true, &mut in_step), (vec![tr(res, ALL, COPY_DEST, DEPTH_WRITE)], one(ALL), vec![])); + // a transition that leaves nothing to do (COPY_SOURCE is PARK) still copies + assert_eq!(plan(tr(res, ALL, PARK, UA), true, &mut in_step).2, one(ALL)); + assert_eq!(plan(tr(res, ALL, UA, PARK), true, &mut in_step), (vec![tr(res, ALL, COPY_DEST, PARK)], one(ALL), vec![])); + // on a compute list: parked, nothing copied – and a twin whose way in was not copied is + // not copied back on the next DIRECT list either (it does not hold the plane) + let before = asked.get(); + assert_eq!(plan(tr(res, ALL, DEPTH_READ, UA), false, &mut Vec::new()), (vec![tr(res, ALL, DEPTH_READ, PARK)], vec![], vec![])); + assert_eq!(plan(tr(res, ALL, UA, DEPTH_READ), true, &mut Vec::new()), (vec![tr(res, ALL, PARK, DEPTH_READ)], vec![], vec![])); + assert_eq!(asked.get(), before, "no twin asked for on a compute list or on the way out"); + // other transitions go as they came + assert_eq!(plan(tr(res, ALL, DEPTH_READ, DEPTH_WRITE), true, &mut in_step), (vec![tr(res, ALL, DEPTH_READ, DEPTH_WRITE)], vec![], vec![])); + forget(res); + } + + #[test] + fn only_depth_plane_subresources_are_copied_and_other_buffers_go_as_they_came() { + let (res, d24, in_ua, unknown) = (0x7E10_0000_1000usize, 0x7E10_0000_2000usize, 0x7E10_0000_3000usize, 0x7E10_0000_4000usize); + // a console D32S8 of 2 mips: depth plane subresources 0 and 1, stencil 2 and 3 + let mut x = desc(3, 64, 64, 20, 1, 6); + x[0x1E..0x20].copy_from_slice(&2u16.to_le_bytes()); + assert!(register(res, &x, None, DEPTH_WRITE)); + let t = stand_in(); + plant_depth_twin(res, &t); + let tw = t.as_raw() as usize; + let mut twin = |_r: usize, o: &Object| twin_if_made(o); + let mut plan = |b: [u32; 8]| { + let mut v = vec![b]; + let p = plan_with(&mut v, true, &mut Vec::new(), &mut twin); + (v, copies(&p.to_twin)) + }; + assert_eq!(plan(tr(res, ALL, DEPTH_WRITE, UA)), (vec![tr(res, ALL, DEPTH_WRITE, PARK)], vec![(res, ALL, vec![0, 1], tw)])); + assert_eq!(plan(tr(res, 1, DEPTH_WRITE, UA)), (vec![tr(res, 1, DEPTH_WRITE, PARK)], vec![(res, 1, vec![1], tw)])); + assert_eq!(plan(tr(res, 2, DEPTH_WRITE, UA)), (vec![tr(res, 2, DEPTH_WRITE, PARK)], vec![]), "a stencil subresource: parked, not copied"); + + // a D24S8 (its depth plane has no twin), an object made in UNORDERED_ACCESS, one XCL does + // not keep, a UAV barrier: as they came + assert!(register(d24, &desc(3, 64, 64, 45, 1, 6), None, DEPTH_WRITE)); + assert!(register(in_ua, &desc(3, 64, 64, 40, 1, 6), None, UA)); + let uav_barrier = [2, 0, res as u32, (res as u64 >> 32) as u32, 0, 0, 0, 0]; + for b in [tr(d24, ALL, DEPTH_WRITE, UA), tr(in_ua, ALL, UA, DEPTH_WRITE), tr(unknown, ALL, DEPTH_WRITE, UA), uav_barrier] { + assert_eq!(plan(b), (vec![b], vec![]), "{b:x?}"); + } + forget(res); + forget(d24); + forget(in_ua); + } + + /// The library's tests run with the switch as the process has it (by default as DEFAULT_ON). + #[test] + fn with_the_switch_off_the_titles_barriers_go_as_they_came() { + let res = 0x7E20_0000_1000usize; + note_created(res as *mut c_void, &desc(3, 64, 64, 40, 1, 6), None, DEPTH_WRITE); + let mut b = vec![tr(res, ALL, DEPTH_WRITE, UA)]; + // (no device: no twin is made here) + let p = plan_with(&mut b, true, &mut Vec::new(), &mut |_, _| None); + if enabled() { + assert_eq!(b, [tr(res, ALL, DEPTH_WRITE, PARK)], "on: parked"); + } else { + assert_eq!(b, [tr(res, ALL, DEPTH_WRITE, UA)], "off: as it came"); + } + assert!(p.to_plane.is_empty() && p.to_twin.is_empty()); + forget(res); + } + + #[test] + fn the_values_of_a_twin_are_counted_by_row_pitch() { + // 3x2 texels, rows 8 bytes apart: the padding (0xEE) is not counted + let data = [0, 8, 8, 0xEE, 0xEE, 0xEE, 0xEE, 0xEE, 7, 8, 0, 0xEE]; + let c = byte_counts(&data, 3, 2, 8); + assert_eq!((c[0], c[7], c[8], c[0xEE]), (2, 1, 3, 0)); + let (top, distinct, zero) = most_frequent(&c); + assert_eq!((top, distinct), (vec![(8, 3), (0, 2), (7, 1)], 3)); + assert!((zero - 100.0 * 2.0 / 6.0).abs() < 1e-9, "{zero}"); + // a buffer shorter than the rows it should hold: the rows that are there + assert_eq!(byte_counts(&data[..10], 3, 2, 8).iter().sum::(), 3); + // ten values once each and 200 three times: 200 first, then the smaller values, eight in all + let mut c = [0u64; 256]; + (1..=10).for_each(|v| c[v] = 1); + c[200] = 3; + let (top, distinct, zero) = most_frequent(&c); + assert_eq!((top, distinct, zero), (vec![(200, 3), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1)], 11, 0.0)); + assert_eq!(most_frequent(&[0; 256]), (vec![], 0, 0.0), "nothing counted"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index f51d923633..260207086e 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -38,6 +38,9 @@ const IID_GRAPHICS_COMMAND_LIST: GUID = GUID::from_u128(0x5b160d0f_ac1b_4185_8ba const IID_PIPELINE_STATE: GUID = GUID::from_u128(0x765a30f3_f624_4c6f_a828_ace948622445); /// D3D12_INDIRECT_ARGUMENT_TYPE of the console's DispatchX const XBOX_ARG_DISPATCH_X: u32 = 105; +/// D3D12_INDIRECT_ARGUMENT_TYPE of the console's DispatchMesh (a UE5 title's mesh dispatch +/// signature: this one argument, stride 16) +const XBOX_ARG_DISPATCH_MESH_X: u32 = 107; fn guid_bytes(g: &GUID) -> (u32, u16, u16, [u8; 8]) { (g.data1, g.data2, g.data3, g.data4) @@ -128,6 +131,7 @@ unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: // console's shape (`title_list`) if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && !super::console_list::enabled() { *ppv = super::title_list::wrap(*ppv); + super::capture::list_begin(*ppv as usize, pso); } hr } @@ -1160,12 +1164,16 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, if desc.is_null() || ppv.is_null() || !crate::gpu::shader::readable(desc as usize, 0x38) { return E_INVALIDARG; } + let mut cost = crate::hle::api_cost::time(crate::hle::api_cost::Call::PlacedTexture); // the PC's reserved resource and tile mappings for it can take long where the console's // placement takes no time (`pso_async::title_held`) let _in_pc = super::pso_async::pc_call(); let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); let d = pc_resource_desc_for_device(this, &x); let buffer = u32::from_le_bytes(d[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32; + if buffer { + cost.call = crate::hle::api_cost::Call::PlacedBuffer; + } 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 @@ -1203,6 +1211,8 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } } real::note_title_address(*ppv as usize, va as usize); + super::depth_uav::note_created(*ppv, &x, Some(va as usize), state); + super::lut3d::created("CreatePlacedResourceX (GPU-owned: on the title's pages / an arena)", *ppv, Some(&x), Some(va as usize), false, state); } return hr; } @@ -1210,7 +1220,9 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, placed_hr = super::vram::place_pages(this, va as usize, &pc, state, clear, console_bytes, riid, ppv); } } - let hr = match placed_hr { + // (a small one the shared pages do not take: on a 4 KiB placement, `XCL_SMALL_TEXTURES=1`) + let small_hr = if placed_hr.is_none() && !buffer { super::small_tex::place(this, &std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC), state, clear, riid, ppv) } else { None }; + let hr = match placed_hr.or(small_hr) { Some(hr) => hr, None => { let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; @@ -1222,6 +1234,8 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)) { Ok(()) => { real::note_title_address(*ppv as usize, va as usize); + super::depth_uav::note_created(*ppv, &x, Some(va as usize), state); + super::lut3d::created(if placed_hr.is_some() { "CreatePlacedResourceX (sampled: on shared pages)" } else if small_hr.is_some() { "CreatePlacedResourceX (sampled: 4 KiB placement)" } else { "CreatePlacedResourceX (sampled: committed)" }, *ppv, Some(&x), Some(va as usize), true, state); return hr; } Err(e) if once(&M, 4) => { @@ -1237,6 +1251,10 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } if hr >= 0 && !(*ppv).is_null() { real::note_title_address(*ppv as usize, va as usize); + if !buffer { + super::depth_uav::note_created(*ppv, &x, Some(va as usize), state); + super::lut3d::created("CreatePlacedResourceX (a resource of its own: not kept in step)", *ppv, Some(&x), Some(va as usize), false, state); + } } if hr < 0 || once(&N, 4) { let w = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); @@ -1306,8 +1324,32 @@ pub(super) unsafe extern "system" fn get_copyable_footprints_x( } } -/// device #41 CreateCommandSignature(desc, root signature, riid, signature): the console's -/// DispatchX argument (105) is a PC Dispatch; the root signature only goes with arguments +/// The PC argument type of a console one: DispatchX (105) is a PC Dispatch, DispatchMeshX (107) +/// a PC DispatchMesh (the PC refuses both console types: debug layer 743, "Unexpected +/// parameter type"); the others are the PC's own. +fn pc_argument_type(t: u32) -> u32 { + match t { + XBOX_ARG_DISPATCH_X => D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32, + XBOX_ARG_DISPATCH_MESH_X => D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH.0 as u32, + t => t, + } +} + +fn indirect_arg_bytes(arg: &[u32; 4]) -> u32 { + match arg[0] { + 0 => 16, + 1 => 20, + 2 | 10 => 12, + 3 | 4 => 16, + 5 => arg[3].saturating_mul(4), + 6..=8 => 8, + 9 => 108, + _ => 0, + } +} + +/// device #41 CreateCommandSignature(desc, root signature, riid, signature): console argument +/// types become the PC's (`pc_argument_type`); the root signature only goes with arguments /// that need one (constants, CBV / SRV / UAV) pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_void, desc: *const u8, root: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { if desc.is_null() || ppv.is_null() { @@ -1319,14 +1361,42 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi let args = u64::from_le_bytes(pc[8..16].try_into().unwrap()) as *const [u32; 4]; let mut list: Vec<[u32; 4]> = if args.is_null() || n > 64 { Vec::new() } else { (0..n).map(|i| args.add(i).read_unaligned()).collect() }; for a in list.iter_mut() { - if a[0] == XBOX_ARG_DISPATCH_X { - a[0] = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32; - } + a[0] = pc_argument_type(a[0]); } let needs_root = list.iter().any(|a| (5..=8).contains(&a[0])); pc[8..16].copy_from_slice(&(if list.is_empty() { 0 } else { list.as_ptr() as u64 }).to_le_bytes()); let hr = real::dev_create_command_signature(this, pc.as_ptr() as usize, if needs_root { root } else { 0 }, riid, ppv); + if hr < 0 { + crate::xlog_warn!( + "D3D12.X: CreateCommandSignature stride {} node mask {:#x} root {root:#x} arguments {:?} → {hr:#x}", + u32::from_le_bytes(pc[0..4].try_into().unwrap()), + u32::from_le_bytes(pc[16..20].try_into().unwrap()), + list + ); + } + if hr >= 0 && !ppv.is_null() { + // noted at every creation, so a signature made at a freed one's address does not keep + // its companion + super::bind::forget_dispatch_mesh_signature(*ppv as usize); + // (a signature that changes root arguments gets no companion; it is noted as one in + // `IndirectSignatureInfo` below) + if let Some(idx) = list.iter().position(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH.0 as u32).filter(|_| !needs_root) { + let offset: u32 = list[..idx].iter().map(indirect_arg_bytes).sum(); + let byte_stride = u32::from_le_bytes(pc[0..4].try_into().unwrap()); + let mut dispatch_list = list.clone(); + dispatch_list[idx][0] = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32; + let mut dpc = pc; + dpc[8..16].copy_from_slice(&(dispatch_list.as_ptr() as u64).to_le_bytes()); + let mut companion: *mut c_void = std::ptr::null_mut(); + let hr2 = real::dev_create_command_signature(this, dpc.as_ptr() as usize, 0, riid, &mut companion); + if hr2 >= 0 && !companion.is_null() { + super::bind::note_dispatch_mesh_signature(*ppv as usize, companion as usize, byte_stride, offset); + } + } + } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + // (noted at every creation, so a signature made at a freed one's address does not keep + // the old one's kind) let dispatches = list.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32); let stride = u32::from_le_bytes(pc[..4].try_into().unwrap()); let dispatch_only = list.len() == 1 && dispatches @@ -1334,6 +1404,10 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi super::bind::note_indirect_signature(*ppv as usize, super::bind::IndirectSignatureInfo::new( dispatches, needs_root, dispatch_only.then_some(stride), )); + super::indirect_guard::note_signature(*ppv as usize, &list.iter().map(|a| a[0] as i32).collect::>()); + if super::capture::enabled() { + super::capture::note_signature(*ppv as usize, u32::from_le_bytes(pc[0..4].try_into().unwrap()), &list.iter().map(|a| a[0] as i32).collect::>()); + } } hr } @@ -1350,6 +1424,15 @@ mod tests { }), 0x2000); } + #[test] + fn console_indirect_argument_types_become_pc_ones() { + assert_eq!(pc_argument_type(105), D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32); + assert_eq!(pc_argument_type(107), D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH.0 as u32); + for t in 0..=10 { + assert_eq!(pc_argument_type(t), t, "PC type {t} stays"); + } + } + #[test] fn console_types_and_descs_become_pc_ones() { assert_eq!(pc_list_type(XBOX_TYPE_DMA), D3D12_COMMAND_LIST_TYPE_COPY.0 as u32); diff --git a/crates/xcl/src/hle/d3d12x/dred.rs b/crates/xcl/src/hle/d3d12x/dred.rs index 85bb784bdf..4eef23183e 100644 --- a/crates/xcl/src/hle/d3d12x/dred.rs +++ b/crates/xcl/src/hle/d3d12x/dred.rs @@ -46,7 +46,7 @@ pub fn label(pso: usize, shaders: &[(&str, Option<&[u8]>)]) { LABELS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, text); } -fn label_of(pso: usize) -> Option { +pub(super) fn label_of(pso: usize) -> Option { LABELS.lock().unwrap().as_ref()?.get(&pso).cloned() } @@ -56,8 +56,11 @@ pub unsafe fn mark_pipeline(list: *mut c_void, pso: usize, bound: usize) { if !on() || list.is_null() { return; } - // nothing labelled: a stand-in still building, or a pipeline of PC shaders - let text = label_of(bound).unwrap_or_else(|| format!("pipeline {pso:#x} (a stand-in, or not translated)")); + // nothing labelled: a stand-in still building (named by what it is being built from), or a + // pipeline of PC shaders + let text = label_of(bound) + .or_else(|| super::pso_async::describe(pso)) + .unwrap_or_else(|| format!("pipeline {pso:#x} (a stand-in, or not translated)")); let first = !MARKS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).and_then(|r| r.last()).is_some_and(|v| v.iter().any(Option::is_some)); push(list as usize, Some(text)); if let Some(l) = ID3D12GraphicsCommandList::from_raw_borrowed(&list) { @@ -147,6 +150,54 @@ pub fn bound_after(list: usize, history: &[i32], done: usize) -> Vec { marks.iter().take(total).skip(n).flatten().cloned().collect() } +/// Operations `from..to` of a list's DRED history by name; a marker of XCL's shows as the label +/// of the pipeline bound from there. From the first operation not done to the list's end it is +/// what the list was about to run: DRED's count can lag, so the one that faulted is among them. +pub fn ops(list: usize, history: &[i32], from: usize, to: usize) -> String { + let g = MARKS.lock().unwrap(); + let marks = g.as_ref().and_then(|m| m.get(&list)).and_then(|r| recording_of(r, history)); + let mut n = markers_before(history, from); + let mut out = Vec::new(); + for &op in history.iter().take(to).skip(from) { + if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER.0 { + let label = marks.and_then(|m| m.get(n)).cloned().flatten(); + n += 1; + out.push(label.map_or_else(|| "marker".to_string(), |l| format!("[{l}]"))); + } else { + out.push(op_name(op)); + } + } + out.join(" ") +} + +/// A breadcrumb operation by name (D3D12_AUTO_BREADCRUMB_OP), the ones a title's lists hold. +fn op_name(op: i32) -> String { + let name = match op { + 3 => "Draw", + 4 => "DrawIndexed", + 5 => "ExecuteIndirect", + 6 => "Dispatch", + 7 => "CopyBufferRegion", + 8 => "CopyTextureRegion", + 9 => "CopyResource", + 10 => "CopyTiles", + 11 => "ResolveSubresource", + 12 => "ClearRTV", + 13 => "ClearUAV", + 14 => "ClearDSV", + 15 => "Barrier", + 18 => "ResolveQueryData", + 23 | 24 => "AtomicCopy", + 25 => "ResolveSubresourceRegion", + 26 => "WriteBufferImmediate", + 42 => "DispatchMesh", + 45 => "Barrier2", + 46 => "Begin", + n => return format!("op{n}"), + }; + name.to_string() +} + /// The label of the pipeline `list` had bound at operation `done` of its DRED history. pub fn bound_at(list: usize, history: &[i32], done: usize) -> Option { let n = markers_before(history, done); @@ -208,6 +259,10 @@ mod tests { assert_eq!(bound_at(0xdead, &h, 6), None); assert_eq!(bound_after(list, &h, 2), vec!["ms b ps c".to_string()]); assert_eq!(bound_after(list, &h, 6), Vec::::new()); + // from the first dispatch on: names, XCL's markers as labels, the title's as "marker" + assert_eq!(ops(list, &h, 2, 16), "Dispatch marker Dispatch [ms b ps c] Dispatch"); + assert_eq!(ops(list, &h, 0, 3), "Begin [cs a] Dispatch"); + assert_eq!(ops(0xdead, &[46, 0, 42, 99], 0, 16), "Begin marker DispatchMesh op99"); MARKS.lock().unwrap().as_mut().unwrap().remove(&list); } } diff --git a/crates/xcl/src/hle/d3d12x/fence_x.rs b/crates/xcl/src/hle/d3d12x/fence_x.rs index babd5744fb..348b70fbc0 100644 --- a/crates/xcl/src/hle/d3d12x/fence_x.rs +++ b/crates/xcl/src/hle/d3d12x/fence_x.rs @@ -55,7 +55,12 @@ impl FenceTable { if !*live { return; } - if let Some(v) = unsafe { borrowed(fence, |f| f.GetCompletedValue()) } { + if let Some(v) = unsafe { borrowed(fence, |f| super::real::fence_completed(f)) } { + // what the lists wrote into the title's memory lands before the value that says they + // are done (the title reads a cell and then the memory: the cell is no promise of the + // hooked GetCompletedValue, which lands it as well) + // (under this cell's lock only: `note_queue_signal` takes the table's) + unsafe { super::sparse::settle_readbacks_within(20) }; if super::title_textures::complete_fence_downloads(fence, v) { mirror.cell.0.store(v, Ordering::Release); } @@ -98,7 +103,7 @@ impl FenceTable { }; let mut parts = Vec::new(); for (p, signalled, waited, has_cell) in snap { - let done = unsafe { borrowed(p, |f| f.GetCompletedValue()) }.unwrap_or(0); + let done = unsafe { borrowed(p, |f| super::real::fence_completed(f)) }.unwrap_or(0); if done < signalled || done < waited { parts.push(format!("{p:#x}(done={done:#x}/sig={signalled:#x}/wait={waited:#x},cell={has_cell})")); } diff --git a/crates/xcl/src/hle/d3d12x/file_reads.rs b/crates/xcl/src/hle/d3d12x/file_reads.rs new file mode 100644 index 0000000000..60d0caa23c --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/file_reads.rs @@ -0,0 +1,99 @@ +//! What file reads put into the title's graphics memory. +//! +//! An unbuffered read arrives by DMA: the CPU writes nothing, and the write watch reports at most +//! that the pages were locked for it – before the bytes are there. A look that takes that report in +//! between leaves the bytes out for good. So the range of a read into graphics memory is a write +//! XCL knows of (`title_textures::note_known_write`) once it is finished: at once when ReadFile says +//! so, else at the first look that finds its OVERLAPPED done. + +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +const ERROR_IO_PENDING: u32 = 997; +const STATUS_PENDING: u64 = 0x103; +/// a read that looks unfinished for longer is taken to be done (its OVERLAPPED may be another's) +const GIVE_UP: Duration = Duration::from_secs(10); + +struct Pending { + overlapped: usize, + at: usize, + len: usize, + since: Instant, +} + +static PENDING: Mutex> = Mutex::new(Vec::new()); +static ANY: AtomicBool = AtomicBool::new(false); + +/// ReadFile of `len` bytes to `at` returned `ok` (with `got`, and `error` when it did not). +pub unsafe fn returned(ok: bool, error: u32, at: *mut c_void, len: u32, got: *const u32, overlapped: *const c_void) { + if at.is_null() || len == 0 { + return; + } + let (a, n) = (at as usize, len as usize); + let graphics = crate::gpu::uma::get().is_some_and(|u| u.contains(a)) || crate::hle::kernelx::in_graphics_reservation(a); + if !graphics { + return; + } + if ok { + let got = if got.is_null() { n } else { (got.read_unaligned() as usize).min(n) }; + super::title_textures::note_known_write(a, got); + } else if error == ERROR_IO_PENDING && !overlapped.is_null() { + PENDING.lock().unwrap().push(Pending { overlapped: overlapped as usize, at: a, len: n, since: Instant::now() }); + ANY.store(true, Ordering::Release); + } +} + +/// The reads that finished since the last look are known writes. +pub unsafe fn take_finished() { + if !ANY.load(Ordering::Acquire) { + return; + } + let mut g = PENDING.lock().unwrap(); + g.retain(|p| { + let pending = crate::gpu::shader::readable(p.overlapped, 8) && (p.overlapped as *const u64).read_volatile() == STATUS_PENDING; + if pending && p.since.elapsed() < GIVE_UP { + return true; + } + super::title_textures::note_known_write(p.at, p.len); + false + }); + ANY.store(!g.is_empty(), Ordering::Release); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A read is known when it returns, or – an overlapped one – at the first look that finds it + /// done; reads elsewhere are nothing to XCL. + #[test] + fn a_finished_read_is_a_known_write() { + let Some(u) = crate::gpu::uma::get() else { return }; + unsafe { + let Some(p) = u.alloc(0x1_0000, 0x1000) else { return }; + let at = p as usize; + let known = || super::super::title_textures::known_in(at, 0x1_0000); + let mut heap = [0u8; 64]; + returned(true, 0, heap.as_mut_ptr() as *mut c_void, 64, std::ptr::null(), std::ptr::null()); + assert!(known().is_empty()); + let got = 0x300u32; + returned(true, 0, p as *mut c_void, 0x1000, &got, std::ptr::null()); + assert_eq!(known(), vec![(at, 0x300)]); + // an overlapped one, first unfinished + let mut ov = [STATUS_PENDING, 0, 0, 0]; + returned(false, ERROR_IO_PENDING, (at + 0x4000) as *mut c_void, 0x2000, std::ptr::null(), ov.as_ptr() as *const c_void); + returned(false, 5, (at + 0x8000) as *mut c_void, 0x2000, std::ptr::null(), ov.as_ptr() as *const c_void); + take_finished(); + assert_eq!(known(), vec![(at, 0x300)], "still on its way"); + std::ptr::write_volatile(&mut ov[0], 0); + take_finished(); + assert_eq!(known(), vec![(at, 0x300), (at + 0x4000, 0x2000)], "done (the refused one is not)"); + take_finished(); + assert_eq!(known().len(), 2, "once"); + super::super::title_textures::forget_known_in(at, 0x1_0000); + u.free(at); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/frame.rs b/crates/xcl/src/hle/d3d12x/frame.rs index c98fd55c2d..f8d8f88407 100644 --- a/crates/xcl/src/hle/d3d12x/frame.rs +++ b/crates/xcl/src/hle/d3d12x/frame.rs @@ -452,6 +452,8 @@ fn trace_calls(what: std::fmt::Arguments) { } pub unsafe extern "system" fn wait_frame_event_x(_this: *mut std::ffi::c_void, ty: u32, timeout_ms: u32, block: *const u8, flags: u32, token: *mut u64) -> HRESULT { + // (`XCL_LOOK_STATS=2`: a frame's time on the thread that submits, added up) + let _cost = super::look_stats::deep().then(|| crate::hle::api_cost::time(crate::hle::api_cost::Call::WaitFrameEvent)); trace_calls(format_args!("WaitFrameEventX(type {ty}, timeout {timeout_ms} ms, block {block:p}, flags {flags:#x}, token in {:#x})", if token.is_null() { 0 } else { *token })); let scheduled = with(|c| { ((ty as usize) < TYPES && c.kinds[ty as usize].scheduled) diff --git a/crates/xcl/src/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs index 16d8edb6f3..70c30c1641 100644 --- a/crates/xcl/src/hle/d3d12x/gfx_records.rs +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -53,12 +53,18 @@ pub(crate) fn payload_key(payload: &[u8]) -> u64 { /// New records belong to the active title. A shared translation cache can serve unrelated titles. pub(crate) fn path() -> PathBuf { - if let Some(boot) = crate::state::boot() { return boot.cache_dir().join("used-graphics-pipelines.bin"); } + let name = history_file_name(); + if let Some(boot) = crate::state::boot() { return boot.cache_dir().join(name); } shared_history_path() } +/// `used-graphics-pipelines.bin`, or its Series S (`lockhart`) name. +fn history_file_name() -> String { + super::pso_async::used_file_name("used-graphics-pipelines", "bin", super::pso_async::profile_is_series_s()) +} + pub(crate) fn shared_history_path() -> PathBuf { - crate::gpu::recomp::dxc::cache_dir().join("used-graphics-pipelines.bin") + crate::gpu::recomp::dxc::cache_dir().join(history_file_name()) } /// `XCL_GFX_RECORDS_MB`: the most the records may take on disk (64 MB: ~300 000 pipelines). diff --git a/crates/xcl/src/hle/d3d12x/gpu_profile.rs b/crates/xcl/src/hle/d3d12x/gpu_profile.rs new file mode 100644 index 0000000000..0317192fa0 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/gpu_profile.rs @@ -0,0 +1,567 @@ +//! `XCL_GPU_PROFILE=1`: the GPU time each console program takes. +//! +//! Each draw, dispatch and ExecuteIndirect of console code gets a timestamp query on its PC +//! list right before it and one right after it, and the pair is resolved into a readback buffer +//! right behind them. The resolve waits on the GPU for the op to finish, so with the profile on +//! a queue runs its ops one after the other. Nothing on the CPU waits for them: a reporter thread looks at the pairs +//! every 100 ms, adds the ones the GPU has written to their program, and every 2 s logs the 15 +//! programs that took the most GPU time in those 2 s (every 20 s: since the start), with their +//! calls, longest call, group counts and, for compute, thread group size, wave size and code size. +//! +//! A pair measures the GPU clock between the two stamps (ticks of a title queue's +//! `GetTimestampFrequency`): the time the op held its queue. Queues run on the GPU at the same +//! time, so the time of ops that overlap is counted for each of them, and the sum over programs +//! can exceed the wall time. The driver decides when a stamp is taken relative to the work +//! around it. Bundles get no stamps (no queries in bundles), and a recording that runs again +//! without a Reset is counted once. + +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::{offset_of, size_of, transmute}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{LazyLock, Mutex}; +use std::time::{Duration, Instant}; + +use windows::core::{Interface, HRESULT}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +use super::real; + +/// begin / end pairs in flight (a ring): two queries and 16 readback bytes each +const PAIRS: usize = 1 << 17; +/// programs a log names +const TOP: usize = 15; +const POLL: Duration = Duration::from_millis(100); +const WINDOW: Duration = Duration::from_secs(2); +/// windows between two logs of the totals since the start +const SINCE_START_EVERY: u32 = 10; + +pub(super) fn on() -> bool { + static ON: LazyLock = LazyLock::new(|| std::env::var("XCL_GPU_PROFILE").is_ok_and(|v| v.trim() == "1")); + *ON +} + +/// The op a pair times. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub(super) enum Kind { + Dispatch, + /// an ExecuteIndirect of dispatches with a translated pipeline + IndirectDispatch, + Draw, + /// an ExecuteIndirect of draws with a translated pipeline + IndirectDraw, + /// an ExecuteIndirect with a PC pipeline + PcIndirect, +} + +impl Kind { + fn name(self) -> &'static str { + match self { + Kind::Dispatch => "Dispatch", + Kind::IndirectDispatch => "ExecuteIndirect (dispatches)", + Kind::Draw => "draw", + Kind::IndirectDraw => "ExecuteIndirect (draws)", + Kind::PcIndirect => "ExecuteIndirect with a PC pipeline", + } + } +} + +/// A program: the kind of op and its console shaders, (CS, 0) or (VS, PS); (0, 0): none known. +type Key = (Kind, u64, u64); + +struct Op { + key: Key, + /// a dispatch's groups, a draw's (vertices or indices, instances, 0), an ExecuteIndirect's + /// (max count, 0, 0) + size: [u32; 3], + /// an ExecuteIndirect whose counts XCL reads (`indirect_guard`): where they are + counts: Option, +} + +impl Op { + /// its size, with the counts the GPU read where they are known + fn size_now(&self) -> [u32; 3] { + self.counts.and_then(super::indirect_guard::counts).unwrap_or(self.size) + } +} + +#[derive(Default, Clone, Debug, PartialEq)] +struct Total { + calls: u64, + ticks: u64, + /// ticks of the longest call, and its size + max: u64, + size: [u32; 3], +} + +/// What a pair of readback words holds. +#[derive(Debug, PartialEq)] +pub(super) enum Stamps { + /// not both written yet + Pending, + /// the end before the begin: the GPU wrote an earlier op's pair over the slot + Bad, + Span(u64), +} + +pub(super) fn stamps(begin: u64, end: u64) -> Stamps { + match (begin, end) { + (0, _) | (_, 0) => Stamps::Pending, + (b, e) if e < b => Stamps::Bad, + (b, e) => Stamps::Span(e - b), + } +} + +fn add(totals: &mut HashMap, key: Key, ticks: u64, size: [u32; 3]) { + let t = totals.entry(key).or_default(); + t.calls += 1; + t.ticks += ticks; + if ticks >= t.max { + t.max = ticks; + t.size = size; + } +} + +/// The `n` programs of `totals` with the most ticks, most first. +fn top(totals: &HashMap, n: usize) -> Vec<(Key, Total)> { + let mut v: Vec<(Key, Total)> = totals.iter().map(|(k, t)| (*k, t.clone())).collect(); + v.sort_by(|a, b| b.1.ticks.cmp(&a.1.ticks).then(b.1.calls.cmp(&a.1.calls)).then((a.0 .1, a.0 .2).cmp(&(b.0 .1, b.0 .2)))); + v.truncate(n); + v +} + +/// A console compute program as its pipeline was made. +#[derive(Clone, Copy)] +struct Shape { + threads: [u32; 3], + wave64: bool, + /// run as two 32-lane halves (`docs/wave64-on-wave32.md`) + split: bool, + code: usize, + dxil: usize, +} + +/// console CS hash → its shape +static SHAPES: Mutex>> = Mutex::new(None); + +/// A translated compute pipeline of console shader `blob` (hash `hash`, `dxil` bytes of DXIL) +/// was made, on a device that runs wave64 programs split (`split_device`). +pub(super) fn note_compute(hash: u64, blob: &[u8], dxil: usize, split_device: bool) { + if !on() && !super::gpu_times::enabled() { + return; + } + let mut g = SHAPES.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + if m.contains_key(&hash) { + return; + } + if let Some((threads, wave64, code)) = crate::gpu::recomp::pso::compute_shape(blob) { + m.insert(hash, Shape { threads, wave64, split: wave64 && split_device, code, dxil }); + } +} + +/// The wave size console compute program `hash` runs with (None: not noted). +pub(super) fn wave_of(hash: u64) -> Option<&'static str> { + let s = *SHAPES.lock().unwrap().as_ref()?.get(&hash)?; + Some(if s.split { "wave64 split in halves" } else if s.wave64 { "wave64" } else { "wave32" }) +} + +/// ticks a second of the title queues' timestamps (0: no queue seen yet) +static FREQUENCY: AtomicU64 = AtomicU64::new(0); + +/// `queue` (a title queue) executes lists: its timestamp frequency converts the pairs' ticks. +pub(super) unsafe fn note_queue(queue: *mut c_void) { + if !on() || queue.is_null() || FREQUENCY.load(Ordering::Relaxed) != 0 { + return; + } + const SLOT: usize = offset_of!(ID3D12CommandQueue_Vtbl, GetTimestampFrequency) / size_of::(); + let f: unsafe extern "system" fn(*mut c_void, *mut u64) -> HRESULT = transmute(pc_fn(queue, SLOT)); + let mut hz = 0u64; + if f(queue, &mut hz).is_ok() && hz != 0 && FREQUENCY.swap(hz, Ordering::Relaxed) == 0 { + crate::xlog_info!("D3D12.X: XCL_GPU_PROFILE: GPU timestamps at {hz} Hz"); + } +} + +struct Profile { + _heap: ID3D12QueryHeap, + _buf: ID3D12Resource, + heap: usize, + buf: usize, + /// the readback buffer's mapping: two u64 a pair + words: usize, + /// two dwords a pair the GPU sets to 1: [everything before the op has finished, the op has] + _marks: ID3D12Resource, + marks_va: u64, + marks: usize, + /// ops seen begun and not ended, and since when + running: HashMap, + next: usize, + ops: Vec>, + in_flight: usize, + window: HashMap, + since_start: HashMap, + /// pairs taken again before the GPU wrote them, and pairs the GPU wrote out of order + lost: u64, + bad: u64, +} + +// SAFETY: the readback mapping lives as long as `_buf`; D3D12 objects are free-threaded. +unsafe impl Send for Profile {} + +static STATE: Mutex> = Mutex::new(None); + +unsafe fn init(dev: &ID3D12Device) -> Option { + let mut heap: Option = None; + let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: 2 * PAIRS as u32, NodeMask: 0 }; + if let Err(e) = dev.CreateQueryHeap(&desc, &mut heap) { + crate::xlog_warn!("D3D12.X: XCL_GPU_PROFILE: no timestamp query heap ({e})"); + return None; + } + let heap = heap?; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: (PAIRS * 16) as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let props = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let mut buf: Option = None; + if let Err(e) = dev.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut buf) { + crate::xlog_warn!("D3D12.X: XCL_GPU_PROFILE: no readback buffer ({e})"); + return None; + } + let buf = buf?; + let mut p = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).ok()?; + std::ptr::write_bytes(p.cast::(), 0, PAIRS * 16); + let mut md = desc; + md.Width = (PAIRS * 8) as u64; + let mut marks: Option = None; + if let Err(e) = dev.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &md, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut marks) { + crate::xlog_warn!("D3D12.X: XCL_GPU_PROFILE: no buffer for the marks ({e})"); + return None; + } + let marks = marks?; + let mut mp = std::ptr::null_mut(); + marks.Map(0, None, Some(&mut mp)).ok()?; + std::ptr::write_bytes(mp.cast::(), 0, PAIRS * 8); + let marks_va = marks.GetGPUVirtualAddress(); + let _ = std::thread::Builder::new().name("xcl-gpu-profile".into()).spawn(|| { + let (mut last, mut windows) = (Instant::now(), 0u32); + loop { + std::thread::sleep(POLL); + poll(); + if last.elapsed() >= WINDOW && report(last.elapsed(), (windows + 1) % SINCE_START_EVERY == 0) { + windows += 1; + last = Instant::now(); + } + } + }); + crate::xlog_info!("D3D12.X: XCL_GPU_PROFILE: draws, dispatches and ExecuteIndirects of console code are timed on the GPU; the programs that take the most GPU time are logged every 2 s"); + Some(Profile { + heap: heap.as_raw() as usize, + buf: buf.as_raw() as usize, + _heap: heap, + _buf: buf, + words: p as usize, + _marks: marks, + marks_va, + marks: mp as usize, + running: HashMap::new(), + next: 0, + ops: (0..PAIRS).map(|_| None).collect(), + in_flight: 0, + window: HashMap::new(), + since_start: HashMap::new(), + lost: 0, + bad: 0, + }) +} + +/// The profile, made on first use with `dev` (outside the lock: the device calls go through +/// XCL's hooks). +fn with_state(dev: impl FnOnce() -> Option, f: impl FnOnce(&mut Profile) -> R) -> Option { + static INIT: std::sync::Once = std::sync::Once::new(); + if !INIT.is_completed() { + let dev = dev()?; + INIT.call_once(|| { + let s = unsafe { init(&dev) }; + *STATE.lock().unwrap() = s; + }); + } + STATE.lock().unwrap().as_mut().map(f) +} + +impl Profile { + fn word(&self, i: usize) -> &AtomicU64 { + unsafe { &*(self.words as *const AtomicU64).add(i) } + } + + fn mark(&self, i: usize) -> &std::sync::atomic::AtomicU32 { + unsafe { &*(self.marks as *const std::sync::atomic::AtomicU32).add(i) } + } +} + +type WriteImmediateFn = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, *const D3D12_WRITEBUFFERIMMEDIATE_MODE); + +/// The GPU writes 1 at `va` once everything recorded on `list` before this has finished. +unsafe fn mark_done(list: *mut c_void, va: u64) { + const WRITE: usize = offset_of!(ID3D12GraphicsCommandList2_Vtbl, WriteBufferImmediate) / size_of::(); + let f: WriteImmediateFn = transmute(pc_fn(list, WRITE)); + let p = D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: va, Value: 1 }; + let m = D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT; + f(list, 1, &p, &m); +} + +/// The PC method in `slot` of `obj` (an adopted object's own, not XCL's console-layout entry). +pub(super) unsafe fn pc_fn(obj: *mut c_void, slot: usize) -> usize { + if real::is_adopted(obj) { + real::orig_fn(obj, slot) + } else { + *(*(obj as *const *const usize)).add(slot) + } +} + +type EndQueryFn = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32); +type ResolveFn = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32, u32, usize, u64); + +/// The begin stamp of an op on a list: `end` records the end stamp and the resolve. +pub(super) struct Pair { + k: u32, + heap: usize, + buf: usize, + marks_va: u64, + end_query: EndQueryFn, + resolve: ResolveFn, +} + +/// Before the PC call of an op of console code on `list` (`pso`: its pipeline as bound). +pub(super) unsafe fn begin(list: *mut c_void, pso: usize, kind: Kind, size: [u32; 3]) -> Option { + // (every draw and dispatch with a translated pipeline comes by here: the ring of the last ones) + super::watch::note(pso, kind as u8 + 1, size); + super::gpu_times::before_op(list, pso, kind, size); + if !on() || list.is_null() { + return None; + } + const GET_TYPE: usize = offset_of!(ID3D12CommandList_Vtbl, GetType) / size_of::(); + const END_QUERY: usize = offset_of!(ID3D12GraphicsCommandList_Vtbl, EndQuery) / size_of::(); + const RESOLVE: usize = offset_of!(ID3D12GraphicsCommandList_Vtbl, ResolveQueryData) / size_of::(); + let get_type: unsafe extern "system" fn(*mut c_void) -> D3D12_COMMAND_LIST_TYPE = transmute(pc_fn(list, GET_TYPE)); + let ty = get_type(list); + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return None; + } + let (a, b) = real::pso_shaders(super::pso_async::resolve(pso)).unwrap_or((0, 0)); + let key = (kind, a, b); + let (k, heap, buf, marks_va) = with_state( + || { + let mut dev: Option = None; + ID3D12GraphicsCommandList::from_raw_borrowed(&list)?.GetDevice(&mut dev).ok()?; + dev + }, + |s| { + let k = s.next; + s.next = (k + 1) % PAIRS; + if s.ops[k].is_some() { + s.lost += 1; + } else { + s.in_flight += 1; + } + s.word(2 * k).store(0, Ordering::Release); + s.word(2 * k + 1).store(0, Ordering::Release); + s.mark(2 * k).store(0, Ordering::Release); + s.mark(2 * k + 1).store(0, Ordering::Release); + s.running.remove(&k); + s.ops[k] = Some(Op { key, size, counts: None }); + (k as u32, s.heap, s.buf, s.marks_va) + }, + )?; + let pair = Pair { k, heap, buf, marks_va, end_query: transmute(pc_fn(list, END_QUERY)), resolve: transmute(pc_fn(list, RESOLVE)) }; + mark_done(list, marks_va + 8 * k as u64); + (pair.end_query)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * k); + Some(pair) +} + +/// The op of `pair` runs the counts in slot `slot` (`indirect_guard`). +pub(super) fn note_counts(pair: &Option, slot: u32) { + let Some(p) = pair else { return }; + if let Some(op) = STATE.lock().unwrap().as_mut().and_then(|s| s.ops[p.k as usize].as_mut()) { + op.counts = Some(slot); + } +} + +/// After the PC call of the op `begin` gave `pair` for. +pub(super) unsafe fn end(list: *mut c_void, pair: Option) { + super::gpu_times::after(list); + let Some(p) = pair else { return }; + (p.end_query)(list, p.heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * p.k + 1); + mark_done(list, p.marks_va + 8 * p.k as u64 + 4); + (p.resolve)(list, p.heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * p.k, 2, p.buf, 16 * p.k as u64); +} + +/// Add the pairs the GPU has written to their programs. +fn poll() { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + let mut left = s.in_flight; + for k in 0..PAIRS { + if left == 0 { + break; + } + let Some(op) = &s.ops[k] else { continue }; + left -= 1; + let span = match stamps(s.word(2 * k).load(Ordering::Acquire), s.word(2 * k + 1).load(Ordering::Acquire)) { + Stamps::Pending => { + if s.mark(2 * k).load(Ordering::Acquire) != 0 && s.mark(2 * k + 1).load(Ordering::Acquire) == 0 { + s.running.entry(k).or_insert_with(Instant::now); + } else { + s.running.remove(&k); + } + continue; + } + Stamps::Bad => None, + Stamps::Span(t) => Some(t), + }; + let (key, size) = (op.key, op.size_now()); + match span { + Some(t) => { + add(&mut s.window, key, t, size); + add(&mut s.since_start, key, t, size); + } + None => s.bad += 1, + } + s.ops[k] = None; + s.running.remove(&k); + s.in_flight -= 1; + } +} + +fn program(key: Key, shapes: &HashMap) -> String { + let (kind, a, b) = key; + match kind { + Kind::Dispatch | Kind::IndirectDispatch => { + let shape = shapes.get(&a).map_or(String::new(), |s| { + format!( + "; {}x{}x{} threads, {}, {} B code, {} B DXIL", + s.threads[0], + s.threads[1], + s.threads[2], + if s.split { "wave64 split in halves" } else if s.wave64 { "wave64" } else { "wave32" }, + s.code, + s.dxil + ) + }); + format!("CS {a:016x} {}{shape}", kind.name()) + } + Kind::Draw | Kind::IndirectDraw if a != 0 => format!("VS {a:016x} PS {b:016x} {}", kind.name()), + Kind::Draw | Kind::IndirectDraw => format!("{} with no console shader known", kind.name()), + Kind::PcIndirect => kind.name().to_owned(), + } +} + +fn size_text(kind: Kind, size: [u32; 3]) -> String { + match kind { + Kind::Dispatch => format!("{}x{}x{} groups", size[0], size[1], size[2]), + Kind::Draw => format!("{} vertices or indices x {} instances", size[0], size[1]), + Kind::IndirectDispatch if size[1..] != [0, 0] => format!("{}x{}x{} groups, the GPU's", size[0], size[1], size[2]), + Kind::IndirectDraw if size[1..] != [0, 0] => format!("{} vertices or indices x {} instances, the GPU's", size[0], size[1]), + Kind::IndirectDispatch | Kind::IndirectDraw | Kind::PcIndirect => format!("max count {} (its counts are the GPU's)", size[0]), + } +} + +/// Calls and ticks of `totals`, summed. +fn sums(totals: &HashMap) -> (u64, u64) { + totals.values().fold((0, 0), |(n, ticks), t| (n + t.calls, ticks + t.ticks)) +} + +/// Log the programs that took the most GPU time in the last `elapsed` (and since the start). +/// False: nothing logged (no queue's timestamp frequency yet); the window goes on. +fn report(elapsed: Duration, since_start: bool) -> bool { + let hz = FREQUENCY.load(Ordering::Relaxed); + if hz == 0 { + return false; + } + let (window, all, in_flight, lost, bad, running) = { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return false }; + let all = since_start.then(|| (top(&s.since_start, TOP), sums(&s.since_start))); + let mut running: Vec<(u128, Key, [u32; 3])> = s + .running + .iter() + .filter_map(|(&k, t)| s.ops[k].as_ref().map(|op| (t.elapsed().as_millis(), op.key, op.size_now()))) + .filter(|r| r.0 >= 500) + .collect(); + running.sort_by(|a, b| b.0.cmp(&a.0)); + running.truncate(6); + (std::mem::take(&mut s.window), all, s.in_flight, s.lost, s.bad, running) + }; + let ms = |ticks: u64| ticks as f64 * 1000.0 / hz as f64; + let shapes = SHAPES.lock().unwrap().clone().unwrap_or_default(); + let lines = |what: &str, totals: Vec<(Key, Total)>, (ops, ticks): (u64, u64)| { + crate::xlog_info!( + "D3D12.X: XCL_GPU_PROFILE: {what}: {:.1} ms of GPU time in {ops} op(s) of console code ({in_flight} in flight, {lost} lost, {bad} out of order); the {} that took most:", + ms(ticks), + totals.len() + ); + for (i, ((kind, a, b), t)) in totals.into_iter().enumerate() { + crate::xlog_info!( + "D3D12.X: XCL_GPU_PROFILE: {:>2}. {:>9.1} ms {}: {} call(s), longest {:.1} ms ({})", + i + 1, + ms(t.ticks), + program((kind, a, b), &shapes), + t.calls, + ms(t.max), + size_text(kind, t.size) + ); + } + }; + if !window.is_empty() { + lines(&format!("last {:.1} s", elapsed.as_secs_f64()), top(&window, TOP), sums(&window)); + } + for (ms_running, key, size) in running { + crate::xlog_warn!("D3D12.X: XCL_GPU_PROFILE: RUNNING for {ms_running} ms and not finished: {} ({})", program(key, &shapes), size_text(key.0, size)); + } + if let Some((all, sum)) = all { + lines("since the start", all, sum); + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pair_counts_once_both_stamps_are_written_and_in_order() { + assert_eq!(stamps(0, 0), Stamps::Pending); + // (the resolve's copy can be seen half done) + assert_eq!(stamps(1_000, 0), Stamps::Pending); + assert_eq!(stamps(0, 1_000), Stamps::Pending); + assert_eq!(stamps(2_000, 1_000), Stamps::Bad); + assert_eq!(stamps(1_000, 1_000), Stamps::Span(0)); + assert_eq!(stamps(1_000, 4_500), Stamps::Span(3_500)); + } + + #[test] + fn programs_are_ranked_by_their_total_and_keep_their_longest_call() { + let mut t = HashMap::new(); + let (a, b, c) = ((Kind::Dispatch, 0xA, 0), (Kind::IndirectDispatch, 0xB, 0), (Kind::Draw, 0xC, 0xD)); + add(&mut t, a, 10, [1, 1, 1]); + add(&mut t, a, 30, [8, 4, 1]); + add(&mut t, a, 20, [2, 1, 1]); + add(&mut t, b, 100, [1, 0, 0]); + add(&mut t, c, 5, [3, 1, 0]); + let r = top(&t, 2); + assert_eq!(r.len(), 2); + assert_eq!(r[0], (b, Total { calls: 1, ticks: 100, max: 100, size: [1, 0, 0] })); + assert_eq!(r[1], (a, Total { calls: 3, ticks: 60, max: 30, size: [8, 4, 1] })); + // the same op with the same program under two kinds stays two programs + add(&mut t, (Kind::IndirectDispatch, 0xA, 0), 1, [1, 0, 0]); + assert_eq!(top(&t, 10).len(), 4); + } +} diff --git a/crates/xcl/src/hle/d3d12x/gpu_times.rs b/crates/xcl/src/hle/d3d12x/gpu_times.rs new file mode 100644 index 0000000000..9835891881 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/gpu_times.rs @@ -0,0 +1,891 @@ +//! `XCL_GPU_TIMES=[,]`: the GPU time each program of a few frames takes. +//! +//! From the first present `after_s` seconds (default 0) after the first present on, every draw, +//! dispatch, ExecuteIndirect and two-pass DispatchMesh of console code recorded on a direct or +//! compute list gets a timestamp query after it (the first of a list's recording one before it +//! too), resolved into a readback buffer before the list closes. A call's interval is its stamp +//! minus the one before it on its list: one query between two calls, not two a call. A list's +//! calls count for the frame of its submit (the frame ends at the next PresentX). The first frame +//! (its lists began before the stamps did) and frames with fewer than `MIN_CALLS` calls measured +//! do not count, as the dump switches skip frames with little work (`targets`, `capture`). After +//! `frames` frames (16 at most) one table is logged (`D3D12.X: GPU times:`): each frame's wall +//! time, measured sum and per-submit totals, then the `TOP` programs by GPU time per frame. +//! +//! What it does not tell: on a desktop GPU a timestamp is written once the work before it is done, +//! and the work after it may already run, so intervals bracket calls coarsely – fine for ranking, +//! not exact per call. An interval also holds what was recorded between the two calls (barriers, +//! copies, clears, XCL's own passes). The direct and compute queues run side by side, so their +//! sums can pass the wall time. Bundles and copy lists get no stamps; a list submitted twice +//! counts once; a list recorded before the measuring began is not measured. Unset, no query heap +//! is made and each hook checks one cached value. + +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::{offset_of, size_of, transmute}; +use std::sync::atomic::{AtomicU32, AtomicU64, AtomicU8, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use windows::core::{Interface, HRESULT}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +use super::gpu_profile::{pc_fn, stamps, Stamps}; +use super::sharded::Sharded; + +/// timestamps the query heap has for each measured frame (two frames more: the first, which does +/// not count, and one light frame) +const PER_FRAME: u32 = 1 << 16; +const FRAMES_MOST: u32 = 16; +/// queries a list takes at a time, in a row (one resolve each) +const BLOCK: u32 = 64; +/// calls measured a frame needs to count +const MIN_CALLS: u64 = 100; +/// programs the table lists +const TOP: usize = 60; +/// how long the report waits for the GPU to write the frames' stamps +const READ_WAIT: Duration = Duration::from_secs(10); + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Config { + frames: u32, + /// none before this long after the first present + after: Duration, +} + +/// `[,]` (frames: 1 ..= `FRAMES_MOST`) +fn parse(v: &str) -> Option { + let mut it = v.split(',').map(str::trim); + let frames = it.next()?.parse::().ok().filter(|&n| n > 0)?.min(FRAMES_MOST); + let after = match it.next() { + Some(s) => Duration::try_from_secs_f64(s.parse::().ok()?).ok()?, + None => Duration::ZERO, + }; + it.next().is_none().then_some(Config { frames, after }) +} + +fn config() -> Option { + static C: OnceLock> = OnceLock::new(); + *C.get_or_init(|| { + let v = std::env::var("XCL_GPU_TIMES").ok()?; + let c = parse(&v); + if c.is_none() { + crate::xlog_warn!("D3D12.X: XCL_GPU_TIMES={v:?} is not [,]: nothing measured"); + } + c + }) +} + +const UNSET: u8 = 0; +const OFF: u8 = 1; +/// the switch is on, the measuring has not begun +const WAITING: u8 = 2; +const RECORDING: u8 = 3; +/// the frames were taken (or the heap could not be made) +const DONE: u8 = 4; +static STATE: AtomicU8 = AtomicU8::new(UNSET); + +fn state() -> u8 { + let s = STATE.load(Ordering::Relaxed); + if s != UNSET { + return s; + } + let _ = STATE.compare_exchange(UNSET, if config().is_some() { WAITING } else { OFF }, Ordering::Relaxed, Ordering::Relaxed); + STATE.load(Ordering::Relaxed) +} + +/// The switch is on and the frames are not measured yet: pipelines note their console shaders. +pub(super) fn enabled() -> bool { + matches!(state(), WAITING | RECORDING) +} + +#[inline] +fn recording() -> bool { + state() == RECORDING +} + +/// What a call ran. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)] +pub(super) enum Kind { + Compute, + Graphics, + /// a pipeline XCL built from a console MS or GS ("MS" / "GS"): a compute pass and a mesh pass + Mesh(&'static str), + /// an ExecuteIndirect with a PC pipeline + Pc, + /// the argument rewrites and compute passes of a run of deferred two-pass draws + /// (`XCL_TWO_PASS_BATCH=2`), all programs together; their mesh passes are `Mesh` + MeshBatch, +} + +/// A program: the kind of call and its console shaders' dump hashes – CS, or VS / MS / GS and +/// PS (0: none) – or, where they are not known, the pipeline. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)] +struct Program { + kind: Kind, + a: u64, + b: u64, + pso: usize, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Op { + program: Program, + /// a dispatch's groups, a draw's (vertices or indices, instances, 0), an ExecuteIndirect's + /// (max count, 0, 0) + size: [u32; 3], + indirect: bool, +} + +/// A measured call: the queries before and after it. +#[derive(Clone, Copy, Debug)] +struct Span { + start: u32, + end: u32, + op: Op, +} + +/// A PC list's recording. +#[derive(Default)] +struct Rec { + /// the stamp after the last call (or the opening one): the next call's start + last: Option, + /// the call begun and not ended + open: Option<(u32, Op)>, + spans: Vec, + /// its queries: blocks (first, used) + runs: Vec<(u32, u32)>, + /// the calls of the recording closed last, resolved, waiting for its submit + closed: Option>, +} + +static RECS: Sharded = Sharded::new(); + +struct Heap { + _heap: ID3D12QueryHeap, + _buf: ID3D12Resource, + heap: usize, + buf: usize, + /// the readback buffer's mapping: a u64 a query + words: usize, + count: u32, + next: AtomicU32, +} + +// SAFETY: the mapping lives as long as `_buf`; D3D12 objects are free-threaded. +unsafe impl Send for Heap {} +unsafe impl Sync for Heap {} + +impl Heap { + unsafe fn make(dev: &ID3D12Device, count: u32) -> Result { + let mut heap: Option = None; + let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: count, NodeMask: 0 }; + dev.CreateQueryHeap(&desc, &mut heap).map_err(|e| format!("no timestamp query heap of {count} ({e})"))?; + let heap = heap.ok_or("no timestamp query heap")?; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 8 * count as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let props = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let mut buf: Option = None; + dev.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut buf).map_err(|e| format!("no readback buffer ({e})"))?; + let buf = buf.ok_or("no readback buffer")?; + let mut p = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).map_err(|e| format!("the readback buffer does not map ({e})"))?; + // (0: not written yet) + std::ptr::write_bytes(p.cast::(), 0, 8 * count as usize); + Ok(Heap { heap: heap.as_raw() as usize, buf: buf.as_raw() as usize, _heap: heap, _buf: buf, words: p as usize, count, next: AtomicU32::new(0) }) + } + + /// `n` queries in a row (None: the heap is used up) + fn take(&self, n: u32) -> Option { + if self.full() { + return None; + } + let first = self.next.fetch_add(n, Ordering::Relaxed); + (first.checked_add(n)? <= self.count).then_some(first) + } + + fn full(&self) -> bool { + self.next.load(Ordering::Relaxed) >= self.count + } + + fn word(&self, q: u32) -> u64 { + assert!(q < self.count); + unsafe { (*(self.words as *const AtomicU64).add(q as usize)).load(Ordering::Acquire) } + } +} + +static HEAP: OnceLock = OnceLock::new(); + +/// The next query of a recording whose blocks are `runs`: the next of its last block, or the +/// first of a block `take` gives (None: no more). +fn next_query(runs: &mut Vec<(u32, u32)>, take: impl FnOnce() -> Option) -> Option { + match runs.last_mut() { + Some((first, used)) if *used < BLOCK => { + *used += 1; + Some(*first + *used - 1) + } + _ => { + let first = take()?; + runs.push((first, 1)); + Some(first) + } + } +} + +type EndQueryFn = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32); +type ResolveFn = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32, u32, usize, u64); +type GetTypeFn = unsafe extern "system" fn(*mut c_void) -> D3D12_COMMAND_LIST_TYPE; +const END_QUERY: usize = offset_of!(ID3D12GraphicsCommandList_Vtbl, EndQuery) / size_of::(); +const RESOLVE: usize = offset_of!(ID3D12GraphicsCommandList_Vtbl, ResolveQueryData) / size_of::(); +const GET_TYPE: usize = offset_of!(ID3D12CommandList_Vtbl, GetType) / size_of::(); + +unsafe fn list_type(list: *mut c_void) -> D3D12_COMMAND_LIST_TYPE { + let f: GetTypeFn = transmute(pc_fn(list, GET_TYPE)); + f(list) +} + +/// A timestamp on `list` (the PC's own EndQuery) in the next query of its recording. +unsafe fn stamp(heap: &Heap, r: &mut Rec, list: *mut c_void) -> Option { + let q = next_query(&mut r.runs, || heap.take(BLOCK))?; + let f: EndQueryFn = transmute(pc_fn(list, END_QUERY)); + f(list, heap.heap, D3D12_QUERY_TYPE_TIMESTAMP, q); + Some(q) +} + +/// Before call `op`: it starts at the stamp after the list's last call, or at one made now. +/// False: the heap is used up. +unsafe fn open(heap: &Heap, r: &mut Rec, list: *mut c_void, op: Op) -> bool { + let Some(start) = r.last.or_else(|| stamp(heap, r, list)) else { return false }; + r.last = Some(start); + r.open = Some((start, op)); + true +} + +/// After the call `open` began: its end stamp, the next call's start. False: the heap is used up. +unsafe fn shut(heap: &Heap, r: &mut Rec, list: *mut c_void) -> bool { + let Some((start, op)) = r.open.take() else { return true }; + let end = stamp(heap, r, list); + if let Some(end) = end { + r.spans.push(Span { start, end, op }); + } + r.last = end; + end.is_some() +} + +/// Before `list` closes: its stamps resolved into the readback buffer, its calls kept for its +/// submit. Returns the calls of an earlier recording that was never submitted. +unsafe fn resolve(heap: &Heap, r: &mut Rec, list: *mut c_void) -> usize { + if !r.runs.is_empty() { + let f: ResolveFn = transmute(pc_fn(list, RESOLVE)); + for &(first, used) in &r.runs { + f(list, heap.heap, D3D12_QUERY_TYPE_TIMESTAMP, first, used, heap.buf, 8 * first as u64); + } + } + r.runs.clear(); + r.last = None; + r.open = None; + let spans = std::mem::take(&mut r.spans); + r.closed.replace(spans).map_or(0, |old| old.len()) +} + +/// calls not measured since the last present (the heap was used up), and calls of recordings +/// closed again before their submit +static UNMEASURED: AtomicU64 = AtomicU64::new(0); +static NOT_SUBMITTED: AtomicU64 = AtomicU64::new(0); + +fn program_of(pso: usize, kind: Kind) -> Program { + match super::real::pso_shaders(super::pso_async::resolve(pso)) { + Some((a, b)) if a != 0 && kind != Kind::Pc => Program { kind, a, b, pso: 0 }, + _ => Program { kind, a: 0, b: 0, pso }, + } +} + +/// Before the PC call of a call of `kind` with pipeline `pso` (as bound) on `list`. +pub(super) unsafe fn before(list: *mut c_void, pso: usize, kind: Kind, size: [u32; 3], indirect: bool) { + if !recording() || list.is_null() { + return; + } + let Some(heap) = HEAP.get() else { return }; + let ty = list_type(list); + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return; + } + let op = Op { program: program_of(pso, kind), size, indirect }; + if !RECS.with(list as usize, |r| open(heap, r, list, op)) { + UNMEASURED.fetch_add(1, Ordering::Relaxed); + } +} + +/// `before` for a call `gpu_profile::begin` sees. +pub(super) unsafe fn before_op(list: *mut c_void, pso: usize, kind: super::gpu_profile::Kind, size: [u32; 3]) { + if !recording() { + return; + } + use super::gpu_profile::Kind as P; + let (kind, indirect) = match kind { + P::Dispatch => (Kind::Compute, false), + P::IndirectDispatch => (Kind::Compute, true), + P::Draw => (Kind::Graphics, false), + P::IndirectDraw => (Kind::Graphics, true), + P::PcIndirect => (Kind::Pc, true), + }; + before(list, pso, kind, size, indirect); +} + +/// After the PC call `before` saw on `list`. +pub(super) unsafe fn after(list: *mut c_void) { + if !recording() || list.is_null() { + return; + } + let Some(heap) = HEAP.get() else { return }; + if !RECS.with(list as usize, |r| shut(heap, r, list)) { + UNMEASURED.fetch_add(1, Ordering::Relaxed); + } +} + +/// Before the PC Close of `list`. +pub(super) unsafe fn before_close(list: *mut c_void) { + if !recording() || list.is_null() { + return; + } + let Some(heap) = HEAP.get() else { return }; + let dropped = RECS.with(list as usize, |r| resolve(heap, r, list)); + NOT_SUBMITTED.fetch_add(dropped as u64, Ordering::Relaxed); +} + +/// A PC submit of `lists`. +struct Submit { + ty: D3D12_COMMAND_LIST_TYPE, + /// the queue's timestamp ticks a second + hz: u64, + /// lists in it, and of them the ones with no call measured + lists: usize, + bare: usize, + spans: Vec, +} + +struct Frame { + first: bool, + began: Instant, + submits: Vec, +} + +impl Frame { + fn new(first: bool) -> Frame { + Frame { first, began: Instant::now(), submits: Vec::new() } + } +} + +/// A frame taken for the report. +struct Taken { + /// the present that ended it + present: u64, + wall: Duration, + unmeasured: u64, + dropped: u64, + submits: Vec, +} + +static FRAME: Mutex> = Mutex::new(None); +static TAKEN: Mutex> = Mutex::new(Vec::new()); + +unsafe fn frequency(queue: *mut c_void) -> u64 { + const SLOT: usize = offset_of!(ID3D12CommandQueue_Vtbl, GetTimestampFrequency) / size_of::(); + let f: unsafe extern "system" fn(*mut c_void, *mut u64) -> HRESULT = transmute(pc_fn(queue, SLOT)); + let mut hz = 0u64; + if f(queue, &mut hz).is_ok() { + hz + } else { + 0 + } +} + +/// `queue` (the PC queue) executes `lists` (PC lists). +pub(super) unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { + if !recording() || queue.is_null() || lists.is_empty() { + return; + } + let ty = list_type(lists[0]); + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return; + } + let (mut spans, mut bare) = (Vec::new(), 0); + for &l in lists { + match RECS.with(l as usize, |r| r.closed.take()) { + Some(s) if !s.is_empty() => spans.extend(s), + _ => bare += 1, + } + } + let s = Submit { ty, hz: frequency(queue), lists: lists.len(), bare, spans }; + if let Some(f) = FRAME.lock().unwrap().as_mut() { + f.submits.push(s); + } +} + +/// The title presents (the `present`th PresentX): a frame ends. +pub(super) unsafe fn present(present: u64) { + let s = state(); + if s != WAITING && s != RECORDING { + return; + } + let Some(c) = config() else { return }; + static T0: OnceLock = OnceLock::new(); + let t0 = *T0.get_or_init(Instant::now); + if s == WAITING { + if t0.elapsed() < c.after { + return; + } + let count = (c.frames + 2) * PER_FRAME; + let raw = super::real::device_raw(); + let made = match ID3D12Device::from_raw_borrowed(&raw) { + Some(dev) => Heap::make(dev, count), + None => Err("no device".into()), + }; + match made { + Ok(h) => { + let _ = HEAP.set(h); + } + Err(e) => { + STATE.store(DONE, Ordering::Relaxed); + crate::xlog_warn!("D3D12.X: GPU times: {e}: nothing measured"); + return; + } + } + *FRAME.lock().unwrap() = Some(Frame::new(true)); + STATE.store(RECORDING, Ordering::Relaxed); + crate::xlog_info!( + "D3D12.X: GPU times: measuring {} frame(s) from present {present} on, in a query heap of {count} timestamps ({PER_FRAME} for each frame)", + c.frames + ); + return; + } + let Some(f) = std::mem::replace(&mut *FRAME.lock().unwrap(), Some(Frame::new(false))) else { return }; + let (unmeasured, dropped) = (UNMEASURED.swap(0, Ordering::Relaxed), NOT_SUBMITTED.swap(0, Ordering::Relaxed)); + let calls: usize = f.submits.iter().map(|s| s.spans.len()).sum(); + let full = HEAP.get().is_some_and(Heap::full); + let mut taken = TAKEN.lock().unwrap(); + if !f.first && calls as u64 >= MIN_CALLS { + taken.push(Taken { present, wall: f.began.elapsed(), unmeasured, dropped, submits: f.submits }); + } + if (taken.len() as u32) < c.frames && !full { + return; + } + STATE.store(DONE, Ordering::Relaxed); + *FRAME.lock().unwrap() = None; + let frames = std::mem::take(&mut *taken); + let _ = std::thread::Builder::new().name("xcl-gpu-times".into()).spawn(move || report(frames, c, full)); +} + +/// Waits for the GPU to write the frames' stamps (`READ_WAIT` at most) and logs the table. +fn report(frames: Vec, c: Config, full: bool) { + let Some(heap) = HEAP.get() else { return }; + let deadline = Instant::now() + READ_WAIT; + let all = || frames.iter().flat_map(|f| &f.submits).flat_map(|s| &s.spans).all(|s| heap.word(s.start) != 0 && heap.word(s.end) != 0); + while !all() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + let reads: Vec = frames + .iter() + .map(|f| FrameRead { + present: f.present, + wall: f.wall, + unmeasured: f.unmeasured, + dropped: f.dropped, + submits: f + .submits + .iter() + .map(|s| SubmitRead { ty: s.ty, hz: s.hz, lists: s.lists, bare: s.bare, calls: s.spans.iter().map(|sp| (sp.op, heap.word(sp.start), heap.word(sp.end))).collect() }) + .collect(), + }) + .collect(); + for line in lines(&reads, &c, full, heap.count, &super::gpu_profile::wave_of) { + crate::xlog_info!("D3D12.X: GPU times: {line}"); + } +} + +// --------------------------------------------------------------------------------------- +// the table (no GPU) +// --------------------------------------------------------------------------------------- + +struct SubmitRead { + ty: D3D12_COMMAND_LIST_TYPE, + hz: u64, + lists: usize, + bare: usize, + /// each call and its two stamps as read back + calls: Vec<(Op, u64, u64)>, +} + +struct FrameRead { + present: u64, + wall: Duration, + unmeasured: u64, + dropped: u64, + submits: Vec, +} + +#[derive(Default, Clone, Debug, PartialEq)] +struct Total { + calls: u64, + ns: u64, + /// the longest call, and its size + max: u64, + size: [u32; 3], + indirect: bool, +} + +#[derive(Default, Debug, PartialEq)] +struct FrameSum { + present: u64, + wall: Duration, + calls: u64, + ns: u64, + /// first stamp to last, where every submit's queue has the same clock + span: Option, + unmeasured: u64, + dropped: u64, + /// stamps not written by the time the report read them, and written out of order + pending: u64, + bad: u64, + bare: usize, + /// (queue type, lists, calls, ns) of each submit + submits: Vec<(i32, usize, u64, u64)>, +} + +fn ticks_ns(ticks: u64, hz: u64) -> u64 { + (ticks as u128 * 1_000_000_000 / hz.max(1) as u128) as u64 +} + +/// The programs' totals over all `frames`, and each frame's sums. +fn summarize(frames: &[FrameRead]) -> (HashMap, Vec) { + let mut totals: HashMap = HashMap::new(); + let mut sums = Vec::new(); + for f in frames { + let mut s = FrameSum { present: f.present, wall: f.wall, unmeasured: f.unmeasured, dropped: f.dropped, ..Default::default() }; + let one_clock = f.submits.windows(2).all(|w| w[0].hz == w[1].hz); + let (mut lo, mut hi) = (u64::MAX, 0u64); + for sub in &f.submits { + s.bare += sub.bare; + let (mut calls, mut ns) = (0, 0); + for &(op, start, end) in &sub.calls { + let t = match stamps(start, end) { + Stamps::Pending => { + s.pending += 1; + continue; + } + Stamps::Bad => { + s.bad += 1; + continue; + } + Stamps::Span(t) if sub.hz != 0 => ticks_ns(t, sub.hz), + Stamps::Span(_) => { + s.bad += 1; + continue; + } + }; + (lo, hi) = (lo.min(start), hi.max(end)); + calls += 1; + ns += t; + let total = totals.entry(op.program).or_default(); + total.calls += 1; + total.ns += t; + if t >= total.max { + (total.max, total.size, total.indirect) = (t, op.size, op.indirect); + } + } + s.calls += calls; + s.ns += ns; + s.submits.push((sub.ty.0, sub.lists, calls, ns)); + } + if one_clock && hi > lo { + s.span = f.submits.first().map(|sub| ticks_ns(hi - lo, sub.hz)); + } + sums.push(s); + } + (totals, sums) +} + +/// The `n` programs of `totals` with the most GPU time, most first (ties: more calls first). +fn ranked(totals: &HashMap, n: usize) -> Vec<(Program, Total)> { + let mut v: Vec<(Program, Total)> = totals.iter().map(|(p, t)| (*p, t.clone())).collect(); + v.sort_by(|a, b| b.1.ns.cmp(&a.1.ns).then(b.1.calls.cmp(&a.1.calls)).then(a.0.cmp(&b.0))); + v.truncate(n); + v +} + +/// A shader as the target dump names it: its `real::shader_key` and its dump hash. +fn shader_text(stage: &str, hash: u64) -> String { + format!("{stage} {:016x} (dump hash {hash:016x})", super::real::shader_key_of_hash(hash)) +} + +fn program_text(p: &Program, wave: &dyn Fn(u64) -> Option<&'static str>) -> String { + let ps = |b: u64| if b != 0 { shader_text("ps", b) } else { "no ps".into() }; + match p.kind { + Kind::Compute if p.a != 0 => format!("compute {}{}", shader_text("cs", p.a), wave(p.a).map_or(String::new(), |w| format!(", {w}"))), + Kind::Graphics if p.a != 0 => format!("graphics {}, {}", shader_text("vs", p.a), ps(p.b)), + Kind::Mesh(k) if p.a != 0 => format!("mesh two-pass {}, {}", shader_text(&k.to_lowercase(), p.a), ps(p.b)), + Kind::Compute => format!("compute pipeline {:#x} (its CS not known)", p.pso), + Kind::Graphics => format!("graphics pipeline {:#x} (its shaders not known)", p.pso), + Kind::Mesh(k) => format!("mesh two-pass {k} pipeline {:#x} (its shaders not known)", p.pso), + Kind::Pc => format!("PC pipeline {:#x}", p.pso), + Kind::MeshBatch => "mesh two-pass compute passes of deferred draws (all programs)".into(), + } +} + +fn size_text(kind: Kind, size: [u32; 3], indirect: bool) -> String { + match (kind, indirect) { + (Kind::MeshBatch, _) => format!("{} draws", size[0]), + (_, true) => format!("ExecuteIndirect, max count {}", size[0]), + (Kind::Graphics, false) => format!("{} vertices or indices x {} instances", size[0], size[1]), + _ => format!("{}x{}x{} groups", size[0], size[1], size[2]), + } +} + +fn queue_name(ty: i32) -> &'static str { + match D3D12_COMMAND_LIST_TYPE(ty) { + D3D12_COMMAND_LIST_TYPE_DIRECT => "direct", + D3D12_COMMAND_LIST_TYPE_COMPUTE => "compute", + _ => "other", + } +} + +/// The report's lines (each logged after `D3D12.X: GPU times: `). +fn lines(frames: &[FrameRead], c: &Config, full: bool, heap_count: u32, wave: &dyn Fn(u64) -> Option<&'static str>) -> Vec { + let (totals, sums) = summarize(frames); + let n = frames.len().max(1) as f64; + let ms = |ns: u64| ns as f64 / 1e6; + let mut out = vec![ + format!( + "{} frame(s) measured (of {} asked for; a frame counts with {MIN_CALLS} calls measured or more, not before {} s after the first present); a call's time is its timestamp minus the one before it on its list (one query between two calls)", + frames.len(), + c.frames, + c.after.as_secs_f64() + ), + "caveats: a desktop GPU writes a timestamp once the work before it is done while later work may already run, so a call's time is coarse (fine for ranking) and holds what was recorded between the two calls (barriers, copies, clears, XCL's own passes); the direct and compute queues overlap, so sums can pass the wall time; bundles and copy lists get no stamps, a list submitted twice counts once, lists recorded before the measuring began are not measured".into(), + ]; + let unmeasured: u64 = sums.iter().map(|s| s.unmeasured).sum(); + if full || unmeasured > 0 { + out.push(format!("the query heap ({heap_count} timestamps, {PER_FRAME} for each frame) ran out: {unmeasured} call(s) in the frames counted were not measured")); + } + for s in &sums { + out.push(format!( + "frame ending at present {}: wall {:.2} ms, GPU first to last stamp {}, measured {:.2} ms in {} calls; not measured: {} (heap full), {} not read back, {} out of order, {} of a recording never submitted; {} list(s) submitted with no call measured", + s.present, + s.wall.as_secs_f64() * 1e3, + s.span.map_or("n/a (queues with different clocks)".into(), |ns| format!("{:.2} ms", ms(ns))), + ms(s.ns), + s.calls, + s.unmeasured, + s.pending, + s.bad, + s.dropped, + s.bare + )); + let subs: Vec = s.submits.iter().enumerate().map(|(k, &(ty, lists, calls, ns))| format!("#{k} {} {lists} lists {calls} calls {:.3} ms", queue_name(ty), ms(ns))).collect(); + out.push(format!("frame ending at present {}: {} submit(s): {}", s.present, subs.len(), subs.join(" | "))); + } + let top = ranked(&totals, TOP); + out.push(format!("the {} of {} programs with the most GPU time, ms per frame averaged over {} frame(s):", top.len(), totals.len(), frames.len())); + for (i, (p, t)) in top.iter().enumerate() { + out.push(format!( + "{:>2}. {:>8.3} ms/frame {}: {} calls ({:.1}/frame), longest {:.3} ms ({})", + i + 1, + ms(t.ns) / n, + program_text(p, wave), + t.calls, + t.calls as f64 / n, + ms(t.max), + size_text(p.kind, t.size, t.indirect) + )); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_switch_takes_frames_and_seconds() { + assert_eq!(parse("3"), Some(Config { frames: 3, after: Duration::ZERO })); + assert_eq!(parse(" 3 , 200 "), Some(Config { frames: 3, after: Duration::from_secs(200) })); + assert_eq!(parse("2,2.5"), Some(Config { frames: 2, after: Duration::from_millis(2500) })); + assert_eq!(parse("100"), Some(Config { frames: FRAMES_MOST, after: Duration::ZERO }), "16 frames at most"); + for bad in ["0", "", "x", "3,x", "3,-1", "3,inf", "3,1,2", "-3"] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + /// A list takes its queries a block at a time; a call needs one query, a list's first call two. + #[test] + fn queries_come_in_blocks_until_the_heap_is_used_up() { + let mut runs = Vec::new(); + let mut blocks = vec![Some(128), Some(512), None].into_iter(); + let mut take = || blocks.next().unwrap(); + let got: Vec> = (0..2 * BLOCK + 1).map(|_| next_query(&mut runs, &mut take)).collect(); + assert_eq!(got[0], Some(128)); + assert_eq!(got[BLOCK as usize - 1], Some(128 + BLOCK - 1)); + assert_eq!(got[BLOCK as usize], Some(512), "a new block"); + assert_eq!(got[2 * BLOCK as usize - 1], Some(512 + BLOCK - 1)); + assert_eq!(got[2 * BLOCK as usize], None, "the heap is used up"); + assert_eq!(runs, vec![(128, BLOCK), (512, BLOCK)]); + } + + fn op(kind: Kind, a: u64, size: [u32; 3]) -> Op { + Op { program: Program { kind, a, b: 0, pso: 0 }, size, indirect: false } + } + + /// Stamps become ns by their queue's clock; programs add up over the frames and keep their + /// longest call; stamps not written or out of order do not count. + #[test] + fn intervals_add_up_by_program_and_by_submit() { + let (cs, other) = (op(Kind::Compute, 0xc5, [80, 45, 1]), op(Kind::Graphics, 0x75, [3, 1, 0])); + let big = Op { size: [160, 90, 1], ..cs }; + // 10 MHz: a tick is 100 ns + let frame = |present: u64, calls: Vec<(Op, u64, u64)>, more: Vec<(Op, u64, u64)>| FrameRead { + present, + wall: Duration::from_millis(200), + unmeasured: 0, + dropped: 0, + submits: vec![ + SubmitRead { ty: D3D12_COMMAND_LIST_TYPE_DIRECT, hz: 10_000_000, lists: 2, bare: 1, calls }, + SubmitRead { ty: D3D12_COMMAND_LIST_TYPE_COMPUTE, hz: 10_000_000, lists: 1, bare: 0, calls: more }, + ], + }; + let frames = vec![ + // one query between two calls: [1000, 1100] [1100, 1400] + frame(10, vec![(cs, 1000, 1100), (big, 1100, 1400), (other, 1400, 1450)], vec![(cs, 2000, 2010), (cs, 0, 2020), (cs, 2030, 2025)]), + frame(11, vec![(cs, 5000, 5100)], vec![]), + ]; + let (totals, sums) = summarize(&frames); + let t = &totals[&cs.program]; + assert_eq!((t.calls, t.ns, t.max, t.size), (4, (100 + 300 + 10 + 100) * 100, 30_000, [160, 90, 1])); + assert_eq!(totals[&other.program].ns, 5_000); + let s = &sums[0]; + assert_eq!((s.calls, s.ns, s.pending, s.bad, s.bare), (4, 46_000, 1, 1, 1)); + assert_eq!(s.submits, vec![(D3D12_COMMAND_LIST_TYPE_DIRECT.0, 2, 3, 45_000), (D3D12_COMMAND_LIST_TYPE_COMPUTE.0, 1, 1, 1_000)]); + assert_eq!(s.span, Some((2010 - 1000) * 100), "first to last stamp"); + assert_eq!(sums[1].ns, 10_000); + // a queue of another clock: no span across them + let mut odd = frame(12, vec![(cs, 1, 2)], vec![(cs, 1, 2)]); + odd.submits[1].hz = 1_000; + assert_eq!(summarize(&[odd]).1[0].span, None); + } + + /// The table: by ms per frame, most first (ties: more calls); each row names the shader as + /// the target dump does and the costliest call's size. + #[test] + fn the_table_ranks_programs_by_time() { + let mut t = HashMap::new(); + let p = |kind: Kind, a: u64, pso: usize| Program { kind, a, b: if kind == Kind::Graphics { 0x99 } else { 0 }, pso }; + let (x, y, z, w) = (p(Kind::Compute, 1, 0), p(Kind::Graphics, 2, 0), p(Kind::Mesh("GS"), 3, 0), p(Kind::Pc, 0, 0x40)); + t.insert(x, Total { calls: 2, ns: 500, max: 400, size: [8, 4, 1], indirect: false }); + t.insert(y, Total { calls: 9, ns: 900, max: 100, size: [3, 2, 0], indirect: false }); + t.insert(z, Total { calls: 3, ns: 500, max: 200, size: [64, 0, 0], indirect: true }); + t.insert(w, Total { calls: 1, ns: 50, max: 50, size: [1, 0, 0], indirect: true }); + let order: Vec = ranked(&t, 10).into_iter().map(|r| r.0).collect(); + assert_eq!(order, vec![y, z, x, w]); + assert_eq!(ranked(&t, 2).len(), 2); + let wave = |h: u64| (h == 1).then_some("wave64 split in halves"); + assert_eq!(program_text(&x, &wave), format!("compute {}, wave64 split in halves", shader_text("cs", 1))); + assert!(shader_text("cs", 1).starts_with(&format!("cs {:016x} (dump hash 0000000000000001)", super::super::real::shader_key_of_hash(1)))); + assert_eq!(program_text(&y, &wave), format!("graphics {}, {}", shader_text("vs", 2), shader_text("ps", 0x99))); + assert_eq!(program_text(&z, &wave), format!("mesh two-pass {}, no ps", shader_text("gs", 3))); + assert_eq!(program_text(&w, &wave), "PC pipeline 0x40"); + assert_eq!(size_text(Kind::Compute, [8, 4, 1], false), "8x4x1 groups"); + assert_eq!(size_text(Kind::Graphics, [3, 2, 0], false), "3 vertices or indices x 2 instances"); + assert_eq!(size_text(Kind::Mesh("GS"), [64, 0, 0], true), "ExecuteIndirect, max count 64"); + assert_eq!(size_text(Kind::MeshBatch, [12, 0, 0], false), "12 draws"); + assert_eq!(program_text(&p(Kind::MeshBatch, 0, 0), &wave), "mesh two-pass compute passes of deferred draws (all programs)"); + let c = Config { frames: 2, after: Duration::ZERO }; + let frames = vec![FrameRead { + present: 7, + wall: Duration::from_millis(5), + unmeasured: 3, + dropped: 0, + submits: vec![SubmitRead { ty: D3D12_COMMAND_LIST_TYPE_DIRECT, hz: 1_000_000_000, lists: 1, bare: 0, calls: vec![(op(Kind::Compute, 1, [2, 1, 1]), 10, 2_000_010)] }], + }]; + let l = lines(&frames, &c, false, 1 << 17, &wave); + assert!(l.iter().any(|s| s.contains("ran out: 3 call(s)")), "{l:#?}"); + assert!(l.iter().any(|s| s.contains("#0 direct 1 lists 1 calls 2.000 ms")), "{l:#?}"); + let row = l.last().unwrap(); + assert!(row.starts_with(" 1. 2.000 ms/frame compute cs ") && row.ends_with(": 1 calls (1.0/frame), longest 2.000 ms (2x1x1 groups)"), "{row}"); + } + + /// On a D3D12 device (WARP if no other): two dispatches on a list stamped as the switch + /// stamps them get two intervals that share their middle query, both read back in order. + #[test] + fn two_dispatches_get_two_intervals() { + use crate::gpu::{fence, recomp::runner::skip_test}; + use std::mem::transmute_copy; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + if crate::gpu::recomp::dxc::location().is_err() { + skip_test("no DXC"); + return; + } + let src = "[RootSignature(\"RootFlags(0)\")]\n[numthreads(64, 1, 1)]\nvoid main() {}\n"; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + let mut dev: Option = None; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let dxil = crate::gpu::recomp::dxc::compile(src, "main", "cs_6_0", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap(); + let cs = D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }; + let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: cs, ..Default::default() }).unwrap(); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, &pso).unwrap(); + list.SetComputeRootSignature(&rs); + let heap = Heap::make(&dev, 4 * BLOCK).unwrap(); + let raw = list.as_raw(); + let mut r = Rec::default(); + let c = op(Kind::Compute, 0xc5, [1024, 1, 1]); + for _ in 0..2 { + assert!(open(&heap, &mut r, raw, c)); + list.Dispatch(1024, 1, 1); + assert!(shut(&heap, &mut r, raw)); + } + assert_eq!(r.spans.len(), 2); + assert_eq!(r.spans[0].end, r.spans[1].start, "one query between the two calls"); + assert_eq!(r.runs, vec![(0, 3)]); + assert_eq!(resolve(&heap, &mut r, raw), 0); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&done, 1).unwrap(); + fence::wait(&done, 1, &dev, None, 10_000).unwrap(); + let hz = frequency(queue.as_raw()); + assert!(hz > 0); + let spans = r.closed.take().unwrap(); + let read = FrameRead { + present: 1, + wall: Duration::ZERO, + unmeasured: 0, + dropped: 0, + submits: vec![SubmitRead { ty, hz, lists: 1, bare: 0, calls: spans.iter().map(|s| (s.op, heap.word(s.start), heap.word(s.end))).collect() }], + }; + for s in &spans { + assert!(matches!(stamps(heap.word(s.start), heap.word(s.end)), Stamps::Span(_)), "{} {}", heap.word(s.start), heap.word(s.end)); + } + let (totals, sums) = summarize(&[read]); + assert_eq!((sums[0].calls, sums[0].pending, sums[0].bad), (2, 0, 0)); + assert_eq!(totals[&c.program].calls, 2); + println!("two dispatches: {} ns in all at {hz} Hz", totals[&c.program].ns); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/guard.rs b/crates/xcl/src/hle/d3d12x/guard.rs index 6d3d9da240..fd3cf03834 100644 --- a/crates/xcl/src/hle/d3d12x/guard.rs +++ b/crates/xcl/src/hle/d3d12x/guard.rs @@ -233,6 +233,13 @@ pub fn make_call_tracer(original: usize, name: String) -> usize { p as usize } +/// `before(return address, data, frame)` and then `original`, with every argument (registers, +/// floating-point ones and the stack) as the caller passed it; `before` returns 0. `frame`: the +/// saved r9, r8, rdx, rcx at +0x68, +0x70, +0x78, +0x80. +pub fn make_before(original: usize, data: u64, before: unsafe extern "system" fn(usize, u64, *const u64) -> usize) -> usize { + thunk(Tail::GuardOr(original), data, before as usize) +} + /// Thunk: `decide(return address, data)` with all argument registers preserved, then `tail`. fn thunk(tail: Tail, data: u64, decide: usize) -> usize { let mut c: Vec = Vec::with_capacity(128); @@ -330,6 +337,23 @@ mod tests { assert_eq!(f(1, 2, 3, 4, 5, 6.0), 327160.5); } + static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + + unsafe extern "system" fn note_first(_caller: usize, data: u64, frame: *const u64) -> usize { + SEEN.store(*frame.add(0x80 / 8) * 100 + data, std::sync::atomic::Ordering::Relaxed); + 0 + } + + /// The hook before a call sees its first argument (the object) and its data; the original + /// then gets every argument and its result goes back. + #[test] + fn a_hook_before_a_call_sees_the_object_and_forwards_everything() { + let t = make_before(original as usize, 7, note_first); + let f: extern "system" fn(u64, u64, u64, u64, u64, f64) -> u64 = unsafe { std::mem::transmute(t) }; + assert_eq!(f(1, 2, 3, 4, 5, 6.0), 654321); + assert_eq!(SEEN.load(std::sync::atomic::Ordering::Relaxed), 107); + } + #[test] fn guard_forwards_calls_that_do_not_come_from_a_game_image() { let info = stubs::new_info("unit.dll", "IGuard::#7", 0); diff --git a/crates/xcl/src/hle/d3d12x/indirect_guard.rs b/crates/xcl/src/hle/d3d12x/indirect_guard.rs new file mode 100644 index 0000000000..e34169cfc4 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/indirect_guard.rs @@ -0,0 +1,670 @@ +//! The counts of an ExecuteIndirect, looked at before the GPU runs them. +//! +//! The counts come from memory the GPU (or an older copy) wrote. Where they are not what the +//! title meant, they can be anything: a float's bits are a billion groups, and a dispatch of a +//! billion groups or a draw of a billion vertices holds the GPU for seconds or until Windows +//! resets the driver (a retail title's world on an RTX 5090: culling passes that ran for 1.4 to +//! 30 s, and an indirect draw that ended in a driver error). So a program of XCL's own reads the +//! counts first and hands them to the ExecuteIndirect through a buffer of XCL's own: zeros where +//! they are out of range. It also writes them where the CPU reads them: the log names the first +//! ones out of range, and the profile (`XCL_GPU_PROFILE=1`) shows what an ExecuteIndirect ran. +//! +//! `XCL_INDIRECT_GUARD=0` turns it off (`=dispatch`: only dispatches are checked); +//! `XCL_INDIRECT_MAX_GROUPS` is the most groups one ExecuteIndirect may run (4 Mi: a 4K target +//! in 8x8 groups has 130 thousand). + +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::{transmute_copy, ManuallyDrop}; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Arc, LazyLock, Mutex}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +use super::real; + +/// ExecuteIndirects whose counts are kept (a ring). A title can submit a recording again seconds +/// later, when its slot has been given to another: then one of the two runs the other's counts +/// (in range, but another program's), so the ring holds minutes of them. +const SLOTS: u32 = 1 << 18; +/// bytes of a slot in `out` and in `seen`: the arguments (5 words at most), in `seen` then 1 +const SLOT: u32 = 32; +/// the word of a `seen` slot that says the GPU read it +const SEEN_WORD: u32 = 5; +/// `seen`: how many counts were out of range, how many the title's buffer showed differently, how +/// many of either kind, the first of these, then the slots +const BAD_AT: u32 = 32; +const BAD_SIZE: u32 = 64; +const BAD_KEPT: u32 = 128; +const SEEN_AT: u32 = BAD_AT + BAD_KEPT * BAD_SIZE; + +/// vertices (indices) and instances one draw may have, and their product: far above what a +/// frame draws +const MAX_VERTICES: u32 = 1 << 28; +const MAX_INSTANCES: u32 = 1 << 24; + +/// `XCL_INDIRECT_GUARD=compare`: what the title's buffer shows is read as well and compared with +/// the memory window (a diagnostic: the two are one memory). +fn compare() -> bool { + static ON: LazyLock = LazyLock::new(|| std::env::var("XCL_INDIRECT_GUARD").is_ok_and(|v| v.trim() == "compare")); + *ON +} + +/// What a command signature of one argument runs. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Counts { + /// groups x, y, z + Dispatch = 0, + /// vertices, instances, first vertex, first instance + Draw = 1, + /// indices, instances, first index, base vertex, first instance + DrawIndexed = 2, +} + +fn on(kind: Counts) -> bool { + static MODE: LazyLock = LazyLock::new(|| match std::env::var("XCL_INDIRECT_GUARD").as_deref().map(str::trim) { + Ok("0") => 0, + Ok("dispatch") => 1, + _ => 2, + }); + *MODE == 2 || (*MODE == 1 && kind == Counts::Dispatch) +} + +/// The groups in all a dispatch whose counts XCL has to check, fold or clamp may have +/// (`XCL_INDIRECT_MAX_GROUPS`, 2^22 unless set). +pub(super) fn max_groups() -> u32 { + static MAX: LazyLock = LazyLock::new(|| std::env::var("XCL_INDIRECT_MAX_GROUPS").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(1 << 22)); + *MAX +} + +/// command signatures of one dispatch or draw and nothing else (its counts come first) +static PLAIN: Mutex>> = Mutex::new(None); + +/// A command signature was made from arguments of the types `types` (at each creation: one at a +/// freed one's address does not keep what that was). +pub(super) fn note_signature(sig: usize, types: &[i32]) { + let counts = match types { + [t] if *t == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 => Some(Counts::Dispatch), + [t] if *t == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW.0 => Some(Counts::Draw), + [t] if *t == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED.0 => Some(Counts::DrawIndexed), + _ => None, + }; + let mut g = PLAIN.lock().unwrap(); + let g = g.get_or_insert_with(Default::default); + match counts { + Some(c) => { + g.insert(sig, c); + } + None => { + g.remove(&sig); + } + } +} + +/// Whether `sig` is a signature of one dispatch and nothing else (its group counts first). +pub(super) fn plain_dispatch(sig: usize) -> bool { + PLAIN.lock().unwrap().as_ref().and_then(|g| g.get(&sig).copied()) == Some(Counts::Dispatch) +} + +fn program() -> String { + format!( + r#" +cbuffer C : register(b0) {{ uint max_groups, slot, id_lo, id_hi, at_lo, at_hi, kind; }}; +RWByteAddressBuffer args : register(u0); +RWByteAddressBuffer outp : register(u1); +RWByteAddressBuffer seen : register(u2); +// the same memory as the title's buffer shows it +RWByteAddressBuffer shown : register(u3); +[numthreads(1, 1, 1)] +void main() {{ + // (what lies behind the arguments may be no memory at all) + uint4 a = uint4(args.Load3(0u), 0u); + uint4 b = uint4(shown.Load3(0u), 0u); + uint a4 = 0u; + uint b4 = 0u; + [branch] if (kind != 0u) {{ a.w = args.Load(12u); b.w = shown.Load(12u); }} + [branch] if (kind == 2u) {{ a4 = args.Load(16u); b4 = shown.Load(16u); }} + // (as floats: the product of the counts does not fit 32 bits; a count of 0 runs nothing) + bool ok; + if (kind == 0u) + ok = a.x == 0u || a.y == 0u || a.z == 0u || (a.x <= max_groups && a.y <= 65535u && a.z <= 65535u && (float)a.x * (float)a.y * (float)a.z <= (float)max_groups); + else + ok = a.x == 0u || a.y == 0u || (a.x <= {MAX_VERTICES}u && a.y <= {MAX_INSTANCES}u && (float)a.x * (float)a.y <= (float){MAX_VERTICES}u); + uint at = slot * {SLOT}u; + outp.Store4(at, ok ? a : uint4(0u, 0u, 0u, 0u)); + outp.Store(at + 16u, ok ? a4 : 0u); + seen.Store4({SEEN_AT}u + at, a); + seen.Store2({SEEN_AT}u + at + 16u, uint2(a4, 1u)); + bool differs = any(a != b) || a4 != b4; + if (differs) {{ + uint m; + seen.InterlockedAdd(4u, 1u, m); + }} + if (!ok) {{ + uint m; + seen.InterlockedAdd(0u, 1u, m); + }} + if (!ok || differs) {{ + uint n; + seen.InterlockedAdd(8u, 1u, n); + if (n < {BAD_KEPT}u) {{ + uint r = {BAD_AT}u + n * {BAD_SIZE}u; + seen.Store4(r, a); + seen.Store4(r + 16u, uint4(id_lo, id_hi, at_lo, at_hi)); + seen.Store4(r + 32u, b); + // (the last word says that the record is there) + seen.Store4(r + 48u, uint4(kind, (differs ? 1u : 0u) | (ok ? 0u : 2u), slot, 1u)); + }} + }} +}} +"# + ) +} + +struct Guard { + dev: usize, + rs: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// the arguments the ExecuteIndirects read: COMMON between its uses + out: ID3D12Resource, + out_va: u64, + /// what the GPU found, on the CPU + _seen: ID3D12Resource, + seen_va: u64, + seen_at: usize, + next: AtomicU32, +} + +// SAFETY: the mapping lives as long as `_seen`; D3D12 objects are free-threaded. +unsafe impl Send for Guard {} +unsafe impl Sync for Guard {} + +impl Guard { + fn word(&self, byte: u32) -> &AtomicU32 { + unsafe { &*((self.seen_at + byte as usize) as *const AtomicU32) } + } +} + +static GUARD: Mutex>> = Mutex::new(None); + +/// The device's guard, made on first use; None: not possible (logged once) +unsafe fn guard_of(list: &ID3D12GraphicsCommandList) -> Option> { + static FAILED: AtomicU32 = AtomicU32::new(0); + if FAILED.load(Ordering::Relaxed) != 0 { + return None; + } + let mut dev: Option = None; + list.GetDevice(&mut dev).ok()?; + let dev = dev?; + let mut g = GUARD.lock().unwrap(); + if let Some(g) = g.as_ref().filter(|g| g.dev == dev.as_raw() as usize) { + return Some(g.clone()); + } + match super::title_textures::own_work(|| make(&dev)) { + Ok(n) => { + let n = Arc::new(n); + *g = Some(n.clone()); + Some(n) + } + Err(e) => { + FAILED.store(1, Ordering::Relaxed); + crate::xlog_warn!("D3D12.X: ExecuteIndirect: the counts are not checked ({e})"); + None + } + } +} + +unsafe fn make(dev: &ID3D12Device) -> Result { + let cs = real::compile(&program(), "cs_5_0"); + if cs.is_empty() { + return Err("its program does not compile".into()); + } + let root = |ty, anonymous| D3D12_ROOT_PARAMETER { ParameterType: ty, Anonymous: anonymous, ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL }; + let uav = |k| root(D3D12_ROOT_PARAMETER_TYPE_UAV, D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: k, RegisterSpace: 0 } }); + let params = [ + root(D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 7 } }), + uav(0), + uav(1), + uav(2), + uav(3), + ]; + let desc = D3D12_ROOT_SIGNATURE_DESC { NumParameters: params.len() as u32, pParameters: params.as_ptr(), ..Default::default() }; + let mut blob: Option = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).map_err(|e| format!("root signature: {e}"))?; + let blob = blob.ok_or("root signature")?; + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())).map_err(|e| format!("CreateRootSignature: {e}"))?; + let code = D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }; + let pso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: code, ..Default::default() }) + .map_err(|e| format!("CreateComputePipelineState: {e}"))?; + let buffer = |heap: D3D12_HEAP_PROPERTIES, width: u64| -> Result { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: width, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).map_err(|e| format!("a buffer of {width} bytes: {e}"))?; + r.ok_or_else(|| "a buffer".into()) + }; + let out = buffer(D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, SLOTS as u64 * SLOT as u64)?; + let cpu = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; + let bytes = SEEN_AT as u64 + SLOTS as u64 * SLOT as u64; + let seen = buffer(cpu, bytes)?; + let mut p = std::ptr::null_mut(); + seen.Map(0, None, Some(&mut p)).map_err(|e| format!("Map: {e}"))?; + std::ptr::write_bytes(p.cast::(), 0, bytes as usize); + Ok(Guard { + dev: dev.as_raw() as usize, + out_va: out.GetGPUVirtualAddress(), + seen_va: seen.GetGPUVirtualAddress(), + seen_at: p as usize, + rs, + pso, + out, + _seen: seen, + next: AtomicU32::new(0), + }) +} + +/// bytes of an argument record the program reads (`check`) +const COUNT_BYTES: usize = 5 * 4; + +/// The GPU address of the arguments at UMA address `t` through their memory window, when all +/// `COUNT_BYTES` of them are in one window. The program reads them through a root UAV, which +/// has no bounds: a record across a view window's end would be read past that window's buffer +/// (the view windows are separate 4 GiB resources). None: the caller reads the title's buffer. +fn counts_va(t: usize) -> Option { + counts_va_in(t, |p, n| real::uma_window_buffer_gpu(p, n).is_some(), real::uma_va_of) +} + +/// `counts_va` with the window lookups given: whether `n` bytes at an address are in one +/// window, and an address's GPU address. +fn counts_va_in(t: usize, in_one_window: impl Fn(usize, usize) -> bool, va_of: impl Fn(usize) -> Option) -> Option { + in_one_window(t, COUNT_BYTES).then(|| va_of(t)).flatten() +} + +/// An ExecuteIndirect whose counts XCL's program reads: what it runs instead of the title's. +pub(super) struct Checked { + guard: Arc, + pub(super) slot: u32, +} + +/// Record the check of an ExecuteIndirect's counts (`args` + `args_off`, the PC buffer and the +/// offset in it) on `list`; None: not one this checks, it runs as it is. Binds a compute root +/// signature and a pipeline: the caller binds the dispatch's or draw's after it. +pub(super) unsafe fn check(list: *mut c_void, pso: usize, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize) -> Option { + if max != 1 || count_buf != 0 { + return None; + } + let kind = *PLAIN.lock().unwrap().as_ref()?.get(&sig)?; + if !on(kind) { + return None; + } + let ty = super::list_x::tracked_list_type(list)?; + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return None; + } + let l = ID3D12GraphicsCommandList::from_raw_borrowed(&list)?; + let res = args as *mut c_void; + let va = ID3D12Resource::from_raw_borrowed(&res)?.GetGPUVirtualAddress(); + if va == 0 || (va + args_off) % 4 != 0 { + return None; + } + let shown = va + args_off; + // The memory window is what the title's shaders write: the counts are read there. (The + // title's buffer is a resource of its own over the same video memory.) + let delta = real::buffer_delta(args); + let title = real::console_buffer(args).and_then(|(p, _)| Some(p + args_off.checked_sub(delta)? as usize)); + // (in a GPU view: its window, which has the arguments once their tiles are asked for; the + // program reads them on the GPU only) + if let Some(t) = title { + super::bind::want_view(super::view_want::Path::MemoryOp, t as u64, COUNT_BYTES as u64); + } + let va = title.and_then(counts_va).filter(|v| v % 4 == 0).unwrap_or(shown); + let shown = if compare() { shown } else { va }; + let g = guard_of(l)?; + let slot = g.next.fetch_add(1, Ordering::Relaxed) % SLOTS; + g.word(SEEN_AT + slot * SLOT + 4 * SEEN_WORD).store(0, Ordering::Release); + let id = real::pso_shaders(pso).map_or(0, |(a, _)| a); + // the counts were written as UAVs: they are read after those writes + let written = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: ManuallyDrop::new(None) }) }, + }; + l.ResourceBarrier(&[written]); + l.SetComputeRootSignature(&g.rs); + // (past the hook of a title's call: what the title bound stays the list's pipeline) + super::list_x::set_compute_pipeline(list, g.pso.as_raw()); + // (the title's address, for the log; a buffer that is not in unified memory: the GPU's) + let at = title.map_or(va, |t| t as u64); + let constants = [max_groups(), slot, id as u32, (id >> 32) as u32, at as u32, (at >> 32) as u32, kind as u32]; + l.SetComputeRoot32BitConstants(0, constants.len() as u32, constants.as_ptr() as *const c_void, 0); + l.SetComputeRootUnorderedAccessView(1, va); + l.SetComputeRootUnorderedAccessView(2, g.out_va); + l.SetComputeRootUnorderedAccessView(3, g.seen_va); + l.SetComputeRootUnorderedAccessView(4, shown); + l.Dispatch(1, 1, 1); + report(&g); + Some(Checked { guard: g, slot }) +} + +impl Checked { + /// `op(buffer, offset)`: the ExecuteIndirect with the checked counts. + pub(super) unsafe fn run(&self, list: *mut c_void, op: impl FnOnce(usize, u64)) { + let out = self.guard.out.as_raw() as usize; + // (the driver reads the counts after the program's writes with this transition only, + // `bind::fresh_indirect_arguments`) + super::list_x::transition(list, out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + op(out, self.slot as u64 * SLOT as u64); + super::list_x::transition(list, out, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + } + + /// Where the checked counts are (buffer, offset), for a pass that reads them as a UAV in place + /// of `run` (`clamp::before`); `read` after it. + pub(super) fn arguments(&self) -> (usize, u64) { + (self.guard.out.as_raw() as usize, self.slot as u64 * SLOT as u64) + } + + /// After a pass read the counts at `arguments`: the buffer back to COMMON (its write and that + /// read left it in UNORDERED_ACCESS). + pub(super) unsafe fn read(&self, list: *mut c_void) { + super::list_x::transition(list, self.guard.out.as_raw() as usize, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + } +} + +/// The counts slot `slot`'s ExecuteIndirect was asked to run (groups; vertices or indices, +/// instances, the first of them), once the GPU has read them. +pub(super) fn counts(slot: u32) -> Option<[u32; 3]> { + let g = GUARD.lock().unwrap().clone()?; + let at = SEEN_AT + slot * SLOT; + (g.word(at + 4 * SEEN_WORD).load(Ordering::Acquire) != 0).then(|| std::array::from_fn(|k| g.word(at + 4 * k as u32).load(Ordering::Relaxed))) +} + +/// Counts out of range so far. +fn bad_so_far(g: &Guard) -> u32 { + g.word(0).load(Ordering::Acquire) +} + +/// A counter that stood at `last` when it was last logged and stands at `now`: is it logged again +/// (the first few, then at each doubling)? It is looked at now and then, so it jumps. +fn logged_again(last: u64, now: u64) -> bool { + now > last && (last < 4 || now.ilog2() > last.ilog2()) +} + +/// `report` from elsewhere (the GPU wait watchdog: nothing may be recorded any more). +pub(super) fn report_now() { + let g = GUARD.lock().unwrap().clone(); + if let Some(g) = g { + report(&g); + } +} + +/// Log the counts found out of range since the last time (and how often the window and the +/// title's buffer held different ones). +fn report(g: &Guard) { + static DIFFERED: AtomicU64 = AtomicU64::new(0); + static BAD: AtomicU64 = AtomicU64::new(0); + static RECORDS: Mutex = Mutex::new(0); + let (bad, d, n) = (bad_so_far(g) as u64, g.word(4).load(Ordering::Acquire) as u64, g.word(8).load(Ordering::Acquire)); + let records = RECORDS.try_lock(); + let Ok(mut records) = records else { return }; + while *records < n.min(BAD_KEPT) { + let at = BAD_AT + *records * BAD_SIZE; + // (a record the GPU has counted but not written yet is logged the next time) + if g.word(at + 60).load(Ordering::Acquire) == 0 { + break; + } + *records += 1; + let w: [u32; 16] = std::array::from_fn(|i| g.word(at + 4 * i as u32).load(Ordering::Relaxed)); + let id = w[4] as u64 | (w[5] as u64) << 32; + let title = w[6] as u64 | (w[7] as u64) << 32; + let what = match w[12] { + 0 => format!("CS {id:016x}: {:#x} x {:#x} x {:#x} groups", w[0], w[1], w[2]), + _ => format!("VS {id:016x}: {:#x} vertices or indices x {:#x} instances", w[0], w[1]), + }; + let shown = if w[13] & 1 != 0 { format!(" (the title's buffer shows {:#x}, {:#x}, {:#x})", w[8], w[9], w[10]) } else { String::new() }; + let verdict = if w[13] & 2 != 0 { "out of range, not run" } else { "run" }; + crate::xlog_warn!("D3D12.X: ExecuteIndirect of {what}, arguments at {title:#x}{shown} – {verdict} ({bad} out of range so far)"); + } + drop(records); + for (counter, now, what) in [(&BAD, bad, "counts out of range so far, not run"), (&DIFFERED, d, "time(s) the title's buffer did not show the counts the memory window holds")] { + let last = counter.load(Ordering::Relaxed); + if logged_again(last, now) && counter.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_ok() && last >= BAD_KEPT as u64 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect: {now} {what}"); + } + } +} + +#[cfg(test)] +mod tests { + use super::super::list_x; + use super::*; + use crate::gpu::{fence, recomp::runner::skip_test}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + + type Close = unsafe extern "system" fn(*mut c_void) -> windows::core::HRESULT; + + /// the guard (and its count of what was out of range) is the device's: one test at a time + static ONE: Mutex<()> = Mutex::new(()); + + unsafe fn device() -> Option { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + skip_test("no GPU"); + return None; + } + dev + } + + /// A buffer the CPU and the GPU see, and its mapping. + unsafe fn cpu_buffer(dev: &ID3D12Device, width: u64) -> (ID3D12Resource, *mut u32) { + let cpu = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: width, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&cpu, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + let r = r.unwrap(); + let mut p = std::ptr::null_mut(); + r.Map(0, None, Some(&mut p)).unwrap(); + (r, p as *mut u32) + } + + unsafe fn signature(dev: &ID3D12Device, ty: D3D12_INDIRECT_ARGUMENT_TYPE, stride: u32) -> ID3D12CommandSignature { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { Type: ty, ..Default::default() }; + let mut sig: Option = None; + dev.CreateCommandSignature(&D3D12_COMMAND_SIGNATURE_DESC { ByteStride: stride, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 }, None, &mut sig).unwrap(); + let sig = sig.unwrap(); + note_signature(sig.as_raw() as usize, &[ty.0]); + sig + } + + /// A list of `ty` as XCL has a title's. + unsafe fn title_list(dev: &ID3D12Device, ty: D3D12_COMMAND_LIST_TYPE) -> (ID3D12CommandAllocator, ID3D12GraphicsCommandList) { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + real::adopt(list.as_raw(), real::Kind::CommandList); + list_x::on_create(list.as_raw(), alloc.as_raw() as usize, 0, ty); + (alloc, list) + } + + unsafe fn run(dev: &ID3D12Device, queue: &ID3D12CommandQueue, list: &ID3D12GraphicsCommandList) { + let close: Close = std::mem::transmute(real::orig_fn(list.as_raw(), 9)); + close(list.as_raw()).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&done, 1).unwrap(); + fence::wait(&done, 1, dev, None, 10_000).unwrap(); + } + + /// The program reads the arguments through their memory window only when the whole record is + /// in that window: one across a window's end is read through the title's buffer instead. + #[test] + fn arguments_across_a_window_end_are_not_read_through_the_window() { + // windows of 0x1000 bytes from 0x1_0000, each at its own GPU address (separate buffers) + let in_one_window = |p: usize, n: usize| p >= 0x1_0000 && (p - 0x1_0000) % 0x1000 + n <= 0x1000; + let va_of = |p: usize| (p >= 0x1_0000).then(|| 0x7000_0000 + ((p - 0x1_0000) / 0x1000) as u64 * 0x10_0000 + ((p - 0x1_0000) % 0x1000) as u64); + assert_eq!(counts_va_in(0x1_0100, in_one_window, va_of), Some(0x7000_0100)); + assert_eq!(counts_va_in(0x1_1000 - COUNT_BYTES, in_one_window, va_of), Some(0x7000_1000 - COUNT_BYTES as u64), "the last record in a window"); + assert_eq!(counts_va_in(0x1_1000 - 8, in_one_window, va_of), None, "a record across the window's end"); + assert_eq!(counts_va_in(0x100, in_one_window, va_of), None, "not in a window"); + } + + #[test] + fn a_counter_is_logged_at_its_first_values_and_at_each_doubling_however_it_jumps() { + assert!(logged_again(0, 1) && logged_again(0, 7) && logged_again(3, 5)); + assert!(logged_again(7, 8) && logged_again(7, 100) && logged_again(64, 129)); + assert!(!logged_again(7, 7) && !logged_again(8, 15) && !logged_again(100, 127)); + } + + /// Garbage counts run 0 groups and are kept for the log; counts in range run as they are. Each + /// case takes the slot the one before it ran from, so that a guard that writes nothing would + /// run that one's counts. + #[test] + fn an_execute_indirect_with_garbage_counts_runs_no_groups() { + // the counts the memory holds, and the groups that may run + let cases: [([u32; 3], u32); 8] = [ + ([7, 1, 1], 7), + ([3, 4, 5], 60), + ([0, 1, 1], 0), + ([7, 1, 1], 7), + // (garbage beside a 0 runs nothing as it is) + ([0x3F80_0000, 0, 1], 0), + // the bits of 1.0f, a count below 2^32 that is none, and a product too large + ([0x3F80_0000, 1, 1], 0), + ([1, 0xFFFF_FFFF, 1], 0), + ([60_000, 60_000, 2], 0), + ]; + let src = r#" +RWByteAddressBuffer c : register(u0); +[numthreads(1, 1, 1)] +void main() { c.InterlockedAdd(0, 1u); } +"#; + unsafe { + let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); + let Some(dev) = device() else { return }; + let cs = real::compile(src, "cs_5_0"); + assert!(!cs.is_empty()); + let param = D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let desc = D3D12_ROOT_SIGNATURE_DESC { NumParameters: 1, pParameters: ¶m, ..Default::default() }; + let mut blob: Option = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).unwrap(); + let blob = blob.unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())).unwrap(); + let code = D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as _, BytecodeLength: cs.len() }; + let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: code, ..Default::default() }).unwrap(); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let sig = signature(&dev, D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, 12); + let ((args, args_at), (groups, groups_at)) = (cpu_buffer(&dev, 256), cpu_buffer(&dev, 256)); + let s = sig.as_raw() as usize; + let a = args.as_raw() as usize; + for (k, (want, runs)) in cases.iter().enumerate() { + // (at an offset: the title's arguments are anywhere in its buffer) + let off = 4 * k as u64; + for (i, w) in want.iter().enumerate() { + *args_at.add(k + i) = *w; + } + *groups_at = 0; + let (_alloc, list) = title_list(&dev, ty); + let raw = list.as_raw(); + type Ei = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); + let ei: Ei = std::mem::transmute(real::orig_fn(raw, 59)); + let before = GUARD.lock().unwrap().as_ref().map_or(0, |g| bad_so_far(g)); + if let Some(g) = GUARD.lock().unwrap().as_ref() { + g.next.store(0, Ordering::Relaxed); + } + let checked = check(raw, 0, s, 1, a, off, 0).expect("checked"); + assert!(k == 0 || checked.slot == 0); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, groups.GetGPUVirtualAddress()); + checked.run(raw, |b, o| ei(raw, s, 1, b, o, 0, 0)); + run(&dev, &queue, &list); + assert_eq!(std::ptr::read_volatile(groups_at), *runs, "{want:x?}: groups run"); + assert_eq!(counts(checked.slot), Some(*want), "{want:x?}: what the CPU sees"); + let bad = bad_so_far(&checked.guard) - before; + assert_eq!(bad, (*runs == 0 && !want.contains(&0)) as u32, "{want:x?}: counted as out of range"); + } + // a count buffer or several commands: not checked; nor a signature with more arguments + let (_alloc, list) = title_list(&dev, ty); + let raw = list.as_raw(); + assert!(check(raw, 0, s, 2, a, 0, 0).is_none()); + assert!(check(raw, 0, s, 1, a, 0, a).is_none()); + note_signature(s, &[D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT.0, D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0]); + assert!(check(raw, 0, s, 1, a, 0, 0).is_none()); + } + } + + /// The arguments a draw gets: all of them as they are, or zeros where a count is garbage. + #[test] + fn an_execute_indirect_with_garbage_counts_draws_nothing() { + let cases: [(bool, [u32; 5], bool); 6] = [ + (false, [3, 2, 7, 9, 0xDEAD], true), + (true, [36, 100_000, 5, 0xFFFF_FFF0, 3], true), + (true, [0, 0, 0, 0, 0], true), + (true, [0x3F80_0000, 1, 0, 0, 0], false), + (false, [3, 0xFFFF_FFFF, 0, 0, 0], false), + (true, [1 << 20, 1 << 20, 0, 0, 0], false), + ]; + unsafe { + let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); + let Some(dev) = device() else { return }; + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let plain = signature(&dev, D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, 16); + let indexed = signature(&dev, D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED, 20); + let ((args, args_at), (got, got_at)) = (cpu_buffer(&dev, 256), cpu_buffer(&dev, 256)); + for (is_indexed, want, ok) in cases { + let words = if is_indexed { 5 } else { 4 }; + for (i, w) in want.iter().enumerate() { + *args_at.add(i) = *w; + *got_at.add(i) = 0xAAAA_AAAA; + } + let (_alloc, list) = title_list(&dev, ty); + let raw = list.as_raw(); + let sig = if is_indexed { &indexed } else { &plain }; + let checked = check(raw, 0, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0).expect("checked"); + // (the arguments, copied out instead of drawn) + checked.run(raw, |b, o| { + list_x::transition(raw, b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE); + let b_raw = b as *mut c_void; + let buf = ID3D12Resource::from_raw_borrowed(&b_raw).unwrap(); + list.CopyBufferRegion(&got, 0, buf, o, 20); + list_x::transition(raw, b, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + }); + run(&dev, &queue, &list); + let drawn: Vec = (0..5).map(|i| std::ptr::read_volatile(got_at.add(i))).collect(); + let mut expect = if ok { want } else { [0; 5] }; + if words == 4 { + expect[4] = 0; + } + assert_eq!(drawn, expect, "{want:x?}"); + assert_eq!(counts(checked.slot), Some([want[0], want[1], want[2]]), "{want:x?}: what the CPU sees"); + } + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 2c5e07afd1..8b93a92a53 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -10,6 +10,7 @@ //! signalled on every queue with work on it; the batch goes once all of them have passed it. use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Mutex; use std::time::{Duration, Instant}; @@ -21,8 +22,22 @@ const SEAL_EVERY: Duration = Duration::from_millis(10); /// how often the thread here looks for batches that can go const TICK: Duration = Duration::from_millis(4); +/// What is let go when the queues are past it. +#[derive(Clone, Copy, PartialEq, Debug)] +enum Dead { + /// an adopted resource's last reference (its original Release ends it) + Resource(usize), + /// a pipeline state XCL owns (`hold_pipeline`) + Pipeline(usize), + /// a heap XCL owns (`hold_heap`) + Heap(usize), + /// a reference of XCL's own to a superseded target, whose tiles then leave the shared pages + /// (`hold_unmap`) + Unmap(usize), +} + struct Batch { - dead: Vec, + dead: Vec, /// (fence, value) a queue: all reached = nothing submitted before the batch closed is left marks: Vec<(ID3D12Fence, u64)>, } @@ -31,7 +46,7 @@ struct Batch { struct Held { /// queue → its fence here and the last value signalled on it fences: HashMap, - open: Vec, + open: Vec, sealed: VecDeque, last_seal: Option, } @@ -45,8 +60,8 @@ impl Held { } /// Close the open batch (at most every `SEAL_EVERY`, or `seal_now`) with a fence value on each of `queues`, - /// and take out the batches every queue is past: the resources to release now. - unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec { + /// and take out the batches every queue is past: what to release now. + unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec { if !self.open.is_empty() && (seal_now || self.last_seal.is_none_or(|t| t.elapsed() >= SEAL_EVERY)) { let mut marks = Vec::with_capacity(queues.len()); let mut ok = true; @@ -77,7 +92,7 @@ impl Held { } } let mut gone = Vec::new(); - while self.sealed.front().is_some_and(|b| b.marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)) { + while self.sealed.front().is_some_and(|b| b.marks.iter().all(|(f, v)| super::real::fence_completed(&f) >= *v)) { gone.extend(self.sealed.pop_front().unwrap().dead); } gone @@ -104,25 +119,62 @@ pub fn enabled() -> bool { /// how long a last `Release` itself waits for queues with nothing to do to say so const IDLE_WAIT: Duration = Duration::from_micros(300); +/// how long queues that had work then are taken to have some: the next releases leave theirs to the +/// thread at once (a title that streams releases many at a time, each with a `Signal` on every queue +/// and `IDLE_WAIT` of its own) +const BUSY_FOR: Duration = Duration::from_millis(5); + +/// Whether queues that were found busy are still taken to be. +#[derive(Default)] +struct Busy(Mutex>); + +impl Busy { + fn is(&self, now: Instant) -> bool { + self.0.lock().unwrap().is_some_and(|until| now < until) + } -/// `res` (an adopted resource) holds one reference that is now this module's. With no work in -/// flight it goes before this returns (the queues pass a fence value at once): a title that -/// frees the memory under a resource right after its last `Release` finds it unpinned, as -/// before. Otherwise the thread here lets it go. -pub unsafe fn hold(res: usize) { - HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(res); + fn found(&self, now: Instant) { + *self.0.lock().unwrap() = Some(now + BUSY_FOR); + } +} + +static BUSY: Busy = Busy(Mutex::new(None)); + +/// `res` (an adopted resource) holds one reference that is now this module's. With `pinned` (it may +/// be over pages that are freed next) and no work in flight it goes before this returns (the queues +/// pass a fence value at once): a title that frees the memory under a resource right after its last +/// `Release` finds it unpinned, as before. Otherwise the thread here lets it go – the driver takes +/// ~100 us to end a texture, and a title ends thousands of them when it changes places. +pub unsafe fn hold(res: usize, pinned: bool) { + HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(Dead::Resource(res)); let start = Instant::now(); - drain_known(true); - while start.elapsed() < IDLE_WAIT && HELD.lock().unwrap().as_ref().is_some_and(|h| !h.is_empty()) { - std::hint::spin_loop(); - drain_known(false); + let busy = !pinned || BUSY.is(start); + if !busy { + drain_known(true); + while start.elapsed() < IDLE_WAIT && HELD.lock().unwrap().as_ref().is_some_and(|h| !h.is_empty()) { + std::hint::spin_loop(); + drain_known(false); + } + if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { + return; + } + BUSY.found(Instant::now()); } - if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { - return; + { + static N: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + let n = N[0].fetch_add(1, Ordering::Relaxed) + 1; + let left = N[1].fetch_add(busy as u64, Ordering::Relaxed) + busy as u64; + if n.is_power_of_two() && n >= 1024 { + crate::xlog_info!("D3D12.X: {n} last releases left to the thread so far, {left} of them without a look at the queues"); + } } - // A thread of its own lets the held ones go: the title may release a resource and then - // wait for its memory without another submit (an imported heap pins the pages under its - // resources – unmapping them stood still while one was held "until the next submit"). + start_thread(); +} + +/// A thread of its own lets the held ones go: the title may release a resource and then wait +/// for its memory without another submit (an imported heap pins the pages under its resources – +/// unmapping them stood still while one was held "until the next submit"). +fn start_thread() { static THREAD: std::sync::Once = std::sync::Once::new(); THREAD.call_once(|| { let _ = std::thread::Builder::new().name("xcl-late-release".into()).spawn(|| loop { @@ -132,6 +184,47 @@ pub unsafe fn hold(res: usize) { }); } +/// A pipeline state XCL owns (raw pointer, 0 = none) is let go: the compute pass of a two-pass +/// pipeline, the real pipeline behind a title's stand-in. Lists in flight may bind it (the title +/// released its own pipeline, not XCL's, and D3D12 asks that a pipeline outlives the work that +/// runs it), so it is released as a resource's last reference is: once every queue is past a +/// fence value signalled after this. `XCL_LATE_RELEASE=0`: now. +pub fn hold_pipeline(p: usize) { + if p == 0 { + return; + } + if !enabled() { + return super::pso_async::release(p); + } + HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(Dead::Pipeline(p)); + start_thread(); +} + +/// A heap XCL owns that reserved resources mapped tiles of (`vram`'s page pools) is let go: a +/// resource the title released maps them until it goes here, and work queued before still reads +/// them – with the heap gone under that work the GPU faults. So it goes as such a resource does, +/// and not before those held earlier: once every queue is past a fence value signalled after this. +/// `XCL_LATE_RELEASE=0`: now. +pub fn hold_heap(heap: ID3D12Heap) { + if !enabled() { + return drop(heap); + } + HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(Dead::Heap(heap.into_raw() as usize)); + start_thread(); +} + +/// A target superseded by a newer placement over its pages (`placements`) leaves the shared pages +/// once every queue is past a fence value signalled after this: work submitted before may still +/// draw to it or read it. `XCL_LATE_RELEASE=0`: now. +pub fn hold_unmap(res: ID3D12Resource) { + if !enabled() { + unsafe { super::placements::unmap_if_superseded(&res) }; + return drop(res); + } + HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(Dead::Unmap(res.into_raw() as usize)); + start_thread(); +} + /// Release what every queue XCL knows of is past: the title's, the tile-mapping one, the /// upload ones. pub unsafe fn drain_known(seal_now: bool) { @@ -146,7 +239,34 @@ pub unsafe fn drain_known(seal_now: bool) { None => return, }; // (outside the lock: a release may end other objects, whose releases come back here) - for res in gone { + for dead in gone { + let res = match dead { + Dead::Resource(res) => res, + Dead::Pipeline(p) => { + super::pso_async::release(p); + continue; + } + Dead::Heap(h) => { + drop(ID3D12Heap::from_raw(h as *mut c_void)); + continue; + } + Dead::Unmap(r) => { + // (then the reference goes: the title's last one may have gone meanwhile) + let r = ID3D12Resource::from_raw(r as *mut c_void); + super::placements::unmap_if_superseded(&r); + continue; + } + }; + // (its views in the shared heap become null views before the object goes) + super::real::resource_ending(res); + // A placed buffer's tiles stay pinned until here: the held object maps them, and work + // queued before its release reads them through it. Unpinned right before the object goes + // (the queues are past that work), not after: then another thread could have made a + // buffer at the same address, whose tiles this would unpin. (`forget_buffer` takes no + // lock of this module's and does not wait for the sparse state's.) + super::sparse::forget_buffer(res); + super::placements::gone(res); + super::small_tex::gone(res); let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(res as *mut c_void, 2)); f(res as *mut c_void); } @@ -184,7 +304,7 @@ mod tests { let raw = res.unwrap().into_raw() as usize; let mut held = Held::default(); - held.open.push(raw); + held.open.push(Dead::Resource(raw)); let queues = [queue.clone()]; assert!(held.drain(&queues, false).is_empty(), "the queue has not passed the batch's fence value"); std::thread::sleep(Duration::from_millis(100)); @@ -198,18 +318,63 @@ mod tests { std::thread::sleep(Duration::from_millis(5)); gone = held.drain(&queues, false); } - assert_eq!(gone, vec![raw], "released once the queue is past the batch"); + assert_eq!(gone, vec![Dead::Resource(raw)], "released once the queue is past the batch"); assert!(held.is_empty()); drop(ID3D12Resource::from_raw(raw as *mut c_void)); } } + /// Queues found busy are taken to be for a moment, and looked at again after it. + #[test] + fn busy_queues_are_looked_at_again_after_a_moment() { + let busy = Busy::default(); + let t = Instant::now(); + assert!(!busy.is(t), "never looked at"); + busy.found(t); + assert!(busy.is(t) && busy.is(t + BUSY_FOR / 2)); + assert!(!busy.is(t + BUSY_FOR)); + busy.found(t + BUSY_FOR); + assert!(busy.is(t + BUSY_FOR + BUSY_FOR / 2)); + } + /// With no queue at all nothing can be in flight: the next drain lets the batch go. #[test] fn without_queues_a_batch_goes_at_once() { let mut held = Held::default(); - held.open.push(0x1000); - assert_eq!(unsafe { held.drain(&[], false) }, vec![0x1000]); + held.open.push(Dead::Resource(0x1000)); + held.open.push(Dead::Pipeline(0x2000)); + assert_eq!(unsafe { held.drain(&[], false) }, vec![Dead::Resource(0x1000), Dead::Pipeline(0x2000)]); assert!(held.is_empty()); } + + /// A pipeline state XCL lets go goes into a batch (a list in flight may bind it), and the + /// thread here releases it once the queues are past – through its COM Release. (That a batch + /// waits for a busy queue is `a_held_resource_goes_when_the_queue_is_past_its_batch`.) + #[test] + fn a_pipeline_xcl_lets_go_is_released_by_the_thread() { + use std::sync::atomic::AtomicU32; + #[repr(C)] + struct Fake { + vt: *const usize, + refs: AtomicU32, + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + (*(this as *const Fake)).refs.fetch_add(1, Ordering::SeqCst) + 1 + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + (*(this as *const Fake)).refs.fetch_sub(1, Ordering::SeqCst) - 1 + } + let vt = [0usize, add_ref as usize, release as usize]; + let fake = Box::new(Fake { vt: vt.as_ptr(), refs: AtomicU32::new(1) }); + let p = &*fake as *const Fake as usize; + hold_pipeline(p); + assert!(enabled()); + // (a queue XCL knows of may still be busy: the batch waits for its fence) + let start = Instant::now(); + while fake.refs.load(Ordering::SeqCst) != 0 && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(fake.refs.load(Ordering::SeqCst), 0, "released once the queues are past"); + hold_pipeline(0); + } } diff --git a/crates/xcl/src/hle/d3d12x/layout.rs b/crates/xcl/src/hle/d3d12x/layout.rs index f0744d4506..59575f94b8 100644 --- a/crates/xcl/src/hle/d3d12x/layout.rs +++ b/crates/xcl/src/hle/d3d12x/layout.rs @@ -56,4 +56,19 @@ mod tests { let g = parse_guid(dev.iid); assert_eq!(guid_string(&g), "189819f1-1db6-4b57-be54-1821339b85f7"); } + + /// A method is at the same slot in every version of an interface (`real::pc_slot!`). + #[test] + fn a_method_stays_at_its_slot_in_later_versions() { + for base in ["ID3D12GraphicsCommandList", "ID3D12CommandQueue", "ID3D12Fence", "ID3D12Resource"] { + let b = find(base).unwrap(); + let versions = chain(base); + assert!(!versions.is_empty()); + for i in versions { + for m in b.methods { + assert_eq!(slot(i, m), slot(b, m), "{}::{m}", i.name); + } + } + } + } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index daecb16a16..0210c522f1 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -14,8 +14,11 @@ //! the inner one is a real query (Fortnite nests its per-object queries in a dummy outer one). //! //! Console GPU addresses in unified memory are the title's own addresses; memory operations -//! go to that window's buffer (`real::uma_window_buffer`), which is in COMMON between them. +//! go to that window's buffer (`real::uma_window_buffer_gpu`), which is in COMMON between them. //! An index buffer at such an address is given to the PC as the window buffer's GPU address. +//! An address in a GPU view of the title's memory (a view window) has its tiles asked for first +//! (`view_want`); what the lists write there is read back to its CPU view, and the CPU reads its +//! values there (`cpu_at`): the CPU cannot touch the GPU view. use std::collections::{BTreeMap, HashMap, HashSet}; use std::ffi::c_void; @@ -105,6 +108,11 @@ pub(super) fn tracked_list_type(list: *mut c_void) -> Option(list, PC_SET_PIPELINE_STATE)(list, pso); +} + pub(super) unsafe fn transition(list: *mut c_void, res: usize, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { let b = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, @@ -236,6 +244,7 @@ pub(super) fn note_dropped_draw(list: *mut c_void) { /// matching AMD PM4 `WAIT_REG_MEM` semantics. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct PendingWait { + /// where the CPU has the value (`cpu_at`: the CPU view of an address in a GPU view) va: u64, width: u8, // 4 or 8 comparison: u32, @@ -340,6 +349,8 @@ impl PendingWait { Duration::from_millis(1) }; std::thread::sleep(step); + // a value a list wrote into a sparse window reaches this memory with its copy back + super::sparse::settle_readbacks(); if self.is_satisfied() { return true; } @@ -392,15 +403,41 @@ pub(super) fn rect_list_state(list: *mut c_void) -> Option u64 { +pub fn pc_va_of(va: u64) -> u64 { pc_va(va) } +/// Where the CPU has the value at GPU address `va`: the CPU view of an address in a GPU view (the +/// title's CPU writes and reads it there; the CPU cannot touch the GPU view), else `va`. Waits +/// read their value there, and a write and a wait meet in one `SyncCell` whichever view each +/// names. One compare for an address outside the view windows. +pub fn cpu_at(va: u64) -> u64 { + cpu_at_in(super::bind::view_span(), va) +} + +/// `cpu_at` with the view windows `span` (`bind::view_span`). +fn cpu_at_in(span: (u64, u64), va: u64) -> u64 { + if super::bind::in_span(span, va) { + super::view_want::cpu(va) + } else { + va + } +} + +/// A GPU write at `va` reaches the CPU's view only when read back after the submit (`note_write`): +/// a window the GPU has a copy of (`Uma::is_gpu_copy`), or a GPU view, whose tiles are read +/// back to its CPU view (`sparse::readback_after_execute`). +fn read_back(va: u64) -> bool { + crate::gpu::uma::get().is_some_and(|u| u.is_gpu_copy(va as usize) || u.is_view(va as usize)) +} + /// `XCL_TRACE_FRAME`: the fixed-function state a list last set (topology, first viewport and -/// scissor, render targets) as text. +/// scissor, render targets) as text, and what the bound DSV names (`XCL_DUMP_TARGETS` keeps that). pub(super) fn state_summary(list: *mut c_void) -> String { let mut out = String::new(); + let mut dsv = None; with_bindings(list, |b| { + dsv = b.render_targets.as_ref().and_then(|rt| rt.dsv); let vp = b.viewports.first().map(|v| (v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth)); let sc = b.scissors.first().map(|r| (r.left, r.top, r.right, r.bottom)); out = format!( @@ -413,6 +450,16 @@ pub(super) fn state_summary(list: *mut c_void) -> String { b.render_targets.as_ref().and_then(|rt| rt.dsv).map_or(String::new(), |d| format!(", DSV {d:#x}")) ); }); + // (after the bindings' lock: the map has its own; the resource is taken with a reference of + // its own there, since another CreateDepthStencilView at the handle releases the map's) + if let Some(x) = dsv.and_then(super::present::rtv_resource).and_then(|r| unsafe { super::present::view_resource(r) }) { + let d = unsafe { x.GetDesc() }; + // flags: the resource's; the view's (1 read-only depth, 2 read-only stencil) when `depth_uav` keeps the DSV + out += &format!(" names {:#x} {}x{} PC format {} flags {:#x}", x.as_raw() as usize, d.Width, d.Height, d.Format.0, d.Flags.0); + if let Some(f) = dsv.and_then(super::depth_uav::dsv_flags) { + out += &format!(", view flags {f:#x}"); + } + } out } @@ -523,6 +570,17 @@ fn with_bindings(list: *mut c_void, f: impl FnOnce(&mut Bindings)) { f(&mut g.get_or_insert_with(HashMap::new).entry(list as usize).or_default().bindings); } +/// (tests) The view heaps XCL counts as bound on `list`; forgetting the list with `forget`. +#[cfg(test)] +pub(super) fn bound_heaps(list: *mut c_void, forget: bool) -> Vec { + let mut heaps = Vec::new(); + with_bindings(list, |b| heaps = b.heaps.clone()); + if forget { + LISTS.lock().unwrap().as_mut().map(|m| m.remove(&(list as usize))); + } + heaps +} + const PC_IA_SET_PRIMITIVE_TOPOLOGY: usize = 20; const PC_RS_SET_VIEWPORTS: usize = 21; const PC_RS_SET_SCISSOR_RECTS: usize = 22; @@ -554,6 +612,13 @@ pub(super) unsafe extern "system" fn ia_set_topology_x(this: *mut c_void, t: u32 crate::xlog_warn!("D3D12.X: IASetPrimitiveTopology({t}) – a console topology the PC does not have{}", if t == RECT_LIST { ": rect lists are drawn as triangle lists, completed by a GS in rect list pipelines" } else { "" }); } } + if super::bind::queue_topology(this, t) { + return; + } + apply_topology(this, t); +} + +pub(super) unsafe fn apply_topology(this: *mut c_void, t: u32) { let rect = t == RECT_LIST; let t = if t == RECT_LIST { windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32 } else { t }; with_bindings(this, |b| { @@ -565,6 +630,10 @@ pub(super) unsafe extern "system" fn ia_set_topology_x(this: *mut c_void, t: u32 /// console #21 RSSetViewports (PC #21) pub(super) unsafe extern "system" fn rs_set_viewports_x(this: *mut c_void, n: u32, v: *const D3D12_VIEWPORT) { + let _c = super::capture::op(this, || { + let vs = if v.is_null() { &[][..] } else { std::slice::from_raw_parts(v, n as usize) }; + Some(super::capture::Op::Viewports(vs.iter().map(|v| [v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth]).collect())) + }); if !v.is_null() { let vs = std::slice::from_raw_parts(v, n as usize).to_vec(); with_bindings(this, |b| b.viewports = vs); @@ -574,13 +643,37 @@ pub(super) unsafe extern "system" fn rs_set_viewports_x(this: *mut c_void, n: u3 /// console #22 RSSetScissorRects (PC #22) pub(super) unsafe extern "system" fn rs_set_scissors_x(this: *mut c_void, n: u32, r: *const windows::Win32::Foundation::RECT) { - if !r.is_null() { - let rs = std::slice::from_raw_parts(r, n as usize).to_vec(); - with_bindings(this, |b| b.scissors = rs); + let _c = super::capture::op(this, || { + let rs = if r.is_null() { &[][..] } else { std::slice::from_raw_parts(r, n as usize) }; + Some(super::capture::Op::Scissors(rs.iter().map(|r| [r.left, r.top, r.right, r.bottom]).collect())) + }); + if !r.is_null() && n > 0 { + let rs = std::slice::from_raw_parts(r, n as usize); + let rects: Vec<[i32; 4]> = rs.iter().map(|r| [r.left, r.top, r.right, r.bottom]).collect(); + if super::bind::queue_scissors(this, rects) { + return; + } + with_bindings(this, |b| b.scissors = rs.to_vec()); + } else if r.is_null() || n == 0 { + if super::bind::queue_scissors(this, Vec::new()) { + return; + } } pc::(this, PC_RS_SET_SCISSOR_RECTS)(this, n, r) } +pub(super) unsafe fn apply_scissors(this: *mut c_void, rects: &[[i32; 4]]) { + let rs: Vec = rects + .iter() + .map(|&[left, top, right, bottom]| windows::Win32::Foundation::RECT { left, top, right, bottom }) + .collect(); + if !rs.is_empty() { + with_bindings(this, |b| b.scissors = rs.clone()); + } + let ptr = if rs.is_empty() { std::ptr::null() } else { rs.as_ptr() }; + pc::(this, PC_RS_SET_SCISSOR_RECTS)(this, rs.len() as u32, ptr) +} + /// console #23 OMSetBlendFactor (PC #23) pub(super) unsafe extern "system" fn om_set_blend_factor_x(this: *mut c_void, f: *const [f32; 4]) { let v = f.as_ref().copied(); @@ -590,6 +683,13 @@ pub(super) unsafe extern "system" fn om_set_blend_factor_x(this: *mut c_void, f: /// console #24 OMSetStencilRef (PC #24) pub(super) unsafe extern "system" fn om_set_stencil_ref_x(this: *mut c_void, r: u32) { + if super::bind::queue_stencil_ref(this, r) { + return; + } + apply_stencil_ref(this, r); +} + +pub(super) unsafe fn apply_stencil_ref(this: *mut c_void, r: u32) { with_bindings(this, |b| b.stencil = Some(r)); pc::(this, PC_OM_SET_STENCIL_REF)(this, r) } @@ -605,6 +705,24 @@ pub(super) unsafe fn note_render_targets(this: *mut c_void, n: u32, rtvs: *const with_bindings(this, |b| b.render_targets = Some(RenderTargets { num_targets, handles, single, dsv: d })); } +/// The render target views bound on `list` (each one of a single descriptor range too). +pub(super) unsafe fn bound_render_targets(list: *mut c_void) -> Vec { + static INC: AtomicU32 = AtomicU32::new(0); + let Some(rt) = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).and_then(|s| s.bindings.render_targets.clone()) else { + return Vec::new(); + }; + if rt.single == 0 || rt.num_targets <= 1 { + return rt.handles; + } + let Some(&base) = rt.handles.first() else { return Vec::new() }; + let mut inc = INC.load(Ordering::Relaxed) as usize; + if inc == 0 { + inc = device_of(list).map_or(0, |d| d.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize); + INC.store(inc as u32, Ordering::Relaxed); + } + (0..rt.num_targets as usize).map(|i| base + i * inc).collect() +} + /// Set again what `b` holds (after KickoffX's Reset or a deferred mid-list split). unsafe fn restore_bindings(this: *mut c_void, b: &Bindings, ty: D3D12_COMMAND_LIST_TYPE) { if ty == D3D12_COMMAND_LIST_TYPE_COPY { @@ -803,6 +921,10 @@ struct ListState { texture_transitions: Vec, /// A translated draw/dispatch in this physical segment successfully bound the shared view heap. uses_shared_view_heap: bool, + /// Bottom-of-pipe immediates into a window the GPU has a copy of: (address, value, bytes). + /// XCL knows what the GPU writes there, so the CPU's view gets the value from XCL once the + /// submission is done on the GPU (`sparse::readback_after_execute`), without a copy back. + sparse_imm: Vec<(usize, u64, u8)>, /// Non-timestamp 64-bit `(va, value)` writes recorded by `Write64BitValue{Bottom,Top}OfPipeX` /// so `ExecuteCommandLists` / `KickoffX` can signal per-address GPU fences for cross-queue /// `Wait64BitValueX` without blocking the submitter thread on the CPU. @@ -825,6 +947,8 @@ struct ListState { deferred: Option, /// on a title list's first segment: the allocator its deferred segments record on (the title's may be recording another list by the submit) own_alloc: Option, + /// depth buffers whose depth plane and twin hold the same on this recording (`depth_uav::plan_barriers`) + depth_in_step: Vec, } /// A `Dispatch` or a dispatching `ExecuteIndirect` put off to the submit, with its arguments. @@ -891,20 +1015,38 @@ impl ListState { } self.written_ranges.insert(producer, va, size); self.segment_write_producers.insert(producer, va, size); - if producer == WriteProducer::InSegmentGpu && crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va as usize)) { - if self.sparse_writes.is_empty() { + if producer == WriteProducer::InSegmentGpu && read_back(va) { + if !self.has_sparse() { SPARSE_WRITE_LISTS.fetch_add(1, Ordering::AcqRel); } self.sparse_writes.push((va as usize, size as usize)); + super::sparse::will_write(va as usize, size as usize); } } - fn clear_sparse_writes(&mut self) -> Vec<(usize, usize)> { - if self.sparse_writes.is_empty() { - return Vec::new(); + fn has_sparse(&self) -> bool { + !self.sparse_writes.is_empty() || !self.sparse_imm.is_empty() + } + + /// `note_write` for an immediate of `bytes` (4 or 8) into a window the GPU has a copy of + fn note_imm(&mut self, va: u64, value: u64, bytes: u8) { + // (a GPU write of the segment: later waits in it are ordered after it, as `note_write`'s) + let size = (bytes & 0x7f) as u64; + self.written_ranges.insert(WriteProducer::InSegmentGpu, va, size); + self.segment_write_producers.insert(WriteProducer::InSegmentGpu, va, size); + if !self.has_sparse() { + SPARSE_WRITE_LISTS.fetch_add(1, Ordering::AcqRel); + } + self.sparse_imm.push((va as usize, value, bytes)); + super::sparse::will_write(va as usize, (bytes & 0x7f) as usize); + } + + fn clear_sparse_writes(&mut self) -> (Vec<(usize, usize)>, Vec<(usize, u64, u8)>) { + if !self.has_sparse() { + return (Vec::new(), Vec::new()); } SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); - std::mem::take(&mut self.sparse_writes) + (std::mem::take(&mut self.sparse_writes), std::mem::take(&mut self.sparse_imm)) } fn push_write64_signal(&mut self, va: u64, value: u64) { @@ -1146,7 +1288,8 @@ pub(super) fn clear_texture_transitions(list: usize) { struct KickoffEffects { waits: Vec, - sparse_writes: Vec<(usize, usize)>, + /// GPU writes and immediates into windows read back after the submit (`ListState::clear_sparse_writes`) + sparse_writes: (Vec<(usize, usize)>, Vec<(usize, u64, u8)>), texture_writes: Vec, texture_transitions: Vec, uses_shared_view_heap: bool, @@ -1287,6 +1430,13 @@ struct QueueInfo { static LISTS: Mutex>> = Mutex::new(None); static POISONED_EVER: AtomicBool = AtomicBool::new(false); + +/// `f` with what is kept of every list. +fn every_list(mut f: impl FnMut(&mut ListState)) { + if let Some(m) = LISTS.lock().unwrap().as_mut() { + m.values_mut().for_each(&mut f); + } +} static LIVE_QUEUES: Mutex> = Mutex::new(Vec::new()); static NEXT_QUEUE_ID: AtomicU64 = AtomicU64::new(0); /// Number of lists with recorded sparse-window memory writes (fast-path guard for post-execute readback). @@ -1305,6 +1455,8 @@ pub(super) struct SegmentEffects { write_producers: RecordedWriteProducers, write64_signals: Vec<(u64, u64)>, sparse_writes: Vec<(usize, usize)>, + /// Immediates into windows the GPU has a copy of: the CPU's view gets them from XCL. + sparse_imm: Vec<(usize, u64, u8)>, texture_writes: Vec, texture_transitions: Vec, uses_shared_view_heap: bool, @@ -1345,6 +1497,7 @@ impl SubmissionPlan { write_producers: s.segment_write_producers.clone(), write64_signals: s.write64_signals.clone(), sparse_writes: s.sparse_writes.clone(), + sparse_imm: s.sparse_imm.clone(), texture_writes: s.texture_writes.clone(), texture_transitions: s.texture_transitions.clone(), uses_shared_view_heap: s.uses_shared_view_heap, @@ -1573,13 +1726,11 @@ pub(super) fn on_queue_release(queue: usize) { /// Stop non-owning internal users (notably `KickoffX`) from selecting a retiring queue. pub(super) fn stop_queue_submissions(queue: usize) { LIVE_QUEUES.lock().unwrap().retain(|q| q.queue != queue); - if let Some(m) = LISTS.lock().unwrap().as_mut() { - for s in m.values_mut() { - if s.last_queue == Some(queue) { - s.last_queue = None; - } + every_list(|s| { + if s.last_queue == Some(queue) { + s.last_queue = None; } - } + }); } /// Remove every cached use of a retired raw queue address before it can be reused. This is later @@ -1681,7 +1832,7 @@ pub(super) unsafe fn on_create_with_backing(list: *mut c_void, alloc: usize, bac let m = g.get_or_insert_with(HashMap::new); let old = m.remove(&key); if let Some(ref old) = old { - if !old.sparse_writes.is_empty() { + if old.has_sparse() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } if !old.write64_signals.is_empty() { @@ -1693,6 +1844,7 @@ pub(super) unsafe fn on_create_with_backing(list: *mut c_void, alloc: usize, bac old }; drop(old); + super::lut3d::list_reset(key); // Dynamic-depth-bias PSOs ignore baked RasterizerState depth bias; seed the list with the // initial PSO's static bias if non-zero (CreateCommandList resets RSSetDepthBias to 0). if ty != D3D12_COMMAND_LIST_TYPE_BUNDLE && pso != 0 { @@ -1712,9 +1864,10 @@ pub(super) fn on_release(list: usize) { super::alloc_pool::forget_list(list); release_copy_scratch(list); super::real::dispatch_chain::list_reset(list); + super::lut3d::list_reset(list); let old = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)); if let Some(old) = old { - if !old.sparse_writes.is_empty() { + if old.has_sparse() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } if !old.write64_signals.is_empty() { @@ -1722,6 +1875,9 @@ pub(super) fn on_release(list: usize) { } // (the title may release a list the GPU still runs: its allocator must outlive that) if let Some(a) = old.own_alloc { + // (the segments that recorded on it go with the list: they hold its PC allocators no + // more, which are released with it once the GPU is done with them) + super::alloc_pool::unpin_users(a.as_raw() as usize); if unsafe { super::alloc_pool::allocator_in_flight(a.as_raw() as usize) } { std::mem::forget(a); } @@ -1732,6 +1888,7 @@ pub(super) fn on_release(list: usize) { /// Clear per-recording sync/write tracking on a split segment moved into `title_list`'s spare pool. pub(super) fn clear_segment_state(list: usize) { trace_list(list, ListEvent::Reset); + super::lut3d::list_reset(list); let old_generations = { let mut g = LISTS.lock().unwrap(); let Some(s) = g.as_mut().and_then(|m| m.get_mut(&list)) else { return }; @@ -1761,13 +1918,11 @@ pub(super) fn has_list_state(list: usize) -> bool { /// Forget a released command allocator so `KickoffX` will not reset a list with a dead allocator. pub(super) fn on_allocator_release(alloc: usize) { - if let Some(m) = LISTS.lock().unwrap().as_mut() { - for s in m.values_mut() { - if s.allocator == alloc { - s.allocator = 0; - } + every_list(|s| { + if s.allocator == alloc { + s.allocator = 0; } - } + }); } /// Track `SetPipelineState` on a command list (for `RSSetDepthBiasX` and `KickoffX`), @@ -1877,11 +2032,9 @@ pub(super) unsafe fn note_queue_for_lists(queue: usize, lists: &[*mut c_void]) { } } } - let mut g = LISTS.lock().unwrap(); - let m = g.get_or_insert_with(HashMap::new); for &l in lists { if !l.is_null() { - m.entry(l as usize).or_default().last_queue = Some(queue); + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(l as usize).or_default().last_queue = Some(queue); } } } @@ -1905,6 +2058,21 @@ fn note_texture_write(list: usize, res: usize, subresource: u32) { LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().texture_writes.push(write); } +/// A PC copy into `[offset, offset + n)` of console buffer `dst` whose memory the GPU only has +/// a copy of in a committed window (`Uma::shadowed`: readback buffers live there, and titles +/// read them through a pointer they keep mapped, without another Map), or placed in a GPU view +/// (what the GPU writes there is its tiles', and the title reads it at the CPU view): the bytes +/// come back to the CPU's view after the submit, like the lists' own memory writes. +fn note_copy_into(list: usize, dst: usize, offset: u64, n: u64) { + let Some(u) = crate::gpu::uma::get().filter(|u| u.shadowed() || super::bind::view_span().1 != 0) else { return }; + let Some((p, bytes)) = real::console_buffer(dst).filter(|&(p, _)| (u.shadowed() && u.is_committed(p)) || u.is_view(p)) else { return }; + let offset = offset.min(bytes as u64); + let (at, n) = (p as u64 + offset, n.min(bytes as u64 - offset)); + // (a buffer placed in a GPU view is over its tiles already: this counts the path) + super::bind::want_view(super::view_want::Path::CopyInto, at, n); + note_write(list, WriteProducer::InSegmentGpu, at, n); +} + // --------------------------------------------------------------------------------------- // per-address GPU fence bridge for monotonic 64-bit Write64BitValue* -> Wait64BitValueX // --------------------------------------------------------------------------------------- @@ -1951,8 +2119,7 @@ impl WriteTraceRing { static WRITE_TRACE: Mutex = Mutex::new(WriteTraceRing::new()); fn record_write_trace(list: *mut c_void, va: u64, value: u64, flags: u32, what: &'static str) { - let ty = LISTS - .lock() + let ty = LISTS.lock() .unwrap() .as_ref() .and_then(|m| m.get(&(list as usize))) @@ -2137,19 +2304,134 @@ static QUEUE_IDS: Mutex> = Mutex::new(Vec::new()); /// producer queue that stands behind one of them shows in the log. struct InternalWait { what: &'static str, + /// the cell's address for a bridged `Wait64BitValueX` (0: not one) + va: u64, fence: ID3D12Fence, value: u64, at: Instant, } +/// queue → its private progress fence, the submits signalled on it, and when each of the +/// last ones was signalled (diagnostic: how far behind a queue is, and since when) +struct Progress { + fence: ID3D12Fence, + submitted: u64, + recent: std::collections::VecDeque<(u64, Instant)>, +} + +unsafe impl Send for Progress {} + +static PROGRESS: Mutex>> = Mutex::new(None); + +/// After a submit to `queue`: a Signal of its private progress fence. +pub(super) unsafe fn note_submitted(queue: *mut c_void) { + if queue.is_null() { + return; + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let mut g = PROGRESS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + if !m.contains_key(&(queue as usize)) { + let mut dev: Option = None; + if q.GetDevice(&mut dev).is_err() { + return; + } + let Some(dev) = dev else { return }; + let Ok(fence) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return }; + m.insert(queue as usize, Progress { fence, submitted: 0, recent: Default::default() }); + } + let p = m.get_mut(&(queue as usize)).unwrap(); + p.submitted += 1; + if super::real::native_queue_signal(q, &p.fence, p.submitted).is_ok() { + p.recent.push_back((p.submitted, Instant::now())); + while p.recent.len() > 4096 { + p.recent.pop_front(); + } + } +} + +/// `q / submits (oldest unfinished for ms)` for every queue behind. +fn progress_summary() -> String { + let rows: Vec<(usize, String)> = { + let mut g = PROGRESS.lock().unwrap(); + g.iter_mut() + .flat_map(|m| m.iter_mut()) + .filter_map(|(&q, p)| { + let done = unsafe { super::real::fence_completed(&p.fence) }; + while p.recent.front().is_some_and(|&(n, _)| n <= done) { + p.recent.pop_front(); + } + (done < p.submitted).then(|| (q, format!("{done}/{} submits (oldest unfinished for {} ms)", p.submitted, p.recent.front().map_or(0, |&(_, t)| t.elapsed().as_millis())))) + }) + .collect() + }; + if rows.is_empty() { + return "no queue is behind".into(); + } + let mut rows: Vec = rows.into_iter().map(|(q, s)| format!("q{} {s}", queue_id(q))).collect(); + rows.sort(); + rows.join(", ") +} + +/// Diagnostic: the wait-for edges of the sync graph, one per GPU wait not yet met: who waits +/// for which value of which cell (or title fence), and which submitted signal (queue, its +/// place among that queue's calls) will meet it. A wait for a value no signal has been submitted +/// for says what was recorded instead. +fn edges_summary() -> String { + let g = SYNC_GRAPH.lock().unwrap(); + g.as_ref().map_or("none".into(), edges_of) +} + +fn edges_of(graph: &SyncGraph) -> String { + let mut rows: Vec = Vec::new(); + for (&va, cell) in &graph.cells { + let done = cell.fence.as_ref().map_or(0, |f| unsafe { super::real::fence_completed(f) }); + for aw in &cell.armed_waits { + if aw.val <= done { + continue; + } + let met = cell.submitted_signals.iter().find(|s| s.val >= aw.val); + let by = match met { + Some(s) => format!("q{}@{} (signal {:#x})", queue_id(s.queue), s.seq, s.val), + None => format!("none submitted (recorded up to {:#x}, submitted up to {:#x} by {:?})", cell.recorded_max, cell.submitted_max, cell.submitted_queue.map(queue_id)), + }; + rows.push(format!("q{}@{} waits {va:#x} >= {:#x} (done {done:#x}) <- {by}", queue_id(aw.waiting_queue), aw.wait_seq, aw.val)); + } + } + for (&f, tf) in &graph.title_fences { + for &(val, q, seq) in &tf.waits { + let met = tf.signals.iter().find(|s| s.val >= val); + let by = match met { + Some(s) => format!("q{}@{} (signal {:#x})", queue_id(s.queue), s.seq, s.val), + None => "none submitted".to_string(), + }; + rows.push(format!("q{}@{seq} waits title fence {f:#x} >= {val:#x} <- {by}", queue_id(q))); + } + } + rows.sort(); + let n = rows.len(); + rows.truncate(140); + format!("{n} waits: {}", rows.join("; ")) +} + +/// `queue` was made to wait for the fence of the cell at `va` to reach `value` (a bridged +/// `Wait64BitValueX`): listed with XCL's own waits while it is unmet, whatever the sync graph +/// has done with it since. +fn note_cell_wait(queue: usize, va: u64, fence: &ID3D12Fence, value: u64) { + let mut g = INTERNAL_WAITS.lock().unwrap(); + let waits = g.get_or_insert_with(HashMap::new).entry(queue).or_default(); + waits.retain(|w| unsafe { super::real::fence_completed(&w.fence) } < w.value); + waits.push(InternalWait { what: "Wait64 cell", va, fence: fence.clone(), value, at: Instant::now() }); +} + static INTERNAL_WAITS: Mutex>>> = Mutex::new(None); /// `queue` was made to wait for `fence` >= `value` by XCL (`what` says for what). pub(super) fn note_internal_wait(queue: usize, what: &'static str, fence: &ID3D12Fence, value: u64) { let mut g = INTERNAL_WAITS.lock().unwrap(); let waits = g.get_or_insert_with(HashMap::new).entry(queue).or_default(); - waits.retain(|w| unsafe { w.fence.GetCompletedValue() } < w.value); - waits.push(InternalWait { what, fence: fence.clone(), value, at: Instant::now() }); + waits.retain(|w| unsafe { super::real::fence_completed(&w.fence) } < w.value); + waits.push(InternalWait { what, va: 0, fence: fence.clone(), value, at: Instant::now() }); } /// The internal waits not yet met: `q: >= (done , ms)`. @@ -2160,8 +2442,9 @@ fn internal_waits_summary() -> String { .flat_map(|m| m.iter()) .flat_map(|(&q, waits)| waits.iter().map(move |w| (q, w))) .filter_map(|(q, w)| { - let done = unsafe { w.fence.GetCompletedValue() }; - (done < w.value).then(|| (q, format!("{} >= {:#x} (done {done:#x}, {} ms)", w.what, w.value, w.at.elapsed().as_millis()))) + let done = unsafe { super::real::fence_completed(&w.fence) }; + let what = if w.va != 0 { format!("{} {:#x}", w.what, w.va) } else { w.what.to_string() }; + (done < w.value).then(|| (q, format!("{what} >= {:#x} (done {done:#x}, {} ms)", w.value, w.at.elapsed().as_millis()))) }) .collect() }; @@ -2222,6 +2505,41 @@ pub fn log_sync_state(at: &str) { }); } +/// Diagnostic (`XCL_SYNC_TRACE=1`): the last sync events in the order XCL made them. +static SYNC_TRACE: Mutex> = Mutex::new(std::collections::VecDeque::new()); + +fn sync_trace_on() -> bool { + static ON: LazyLock = LazyLock::new(|| std::env::var("XCL_SYNC_TRACE").is_ok_and(|v| v.trim() == "1")); + *ON +} + +fn sync_trace(what: impl FnOnce() -> String) { + if !sync_trace_on() { + return; + } + static T0: LazyLock = LazyLock::new(Instant::now); + let t = T0.elapsed().as_micros() as u64; + let w = what(); + let mut g = SYNC_TRACE.lock().unwrap(); + if g.len() >= 1500 { + g.pop_front(); + } + g.push_back((t, w)); +} + +/// Log the ring (`why`), `times` times in all for each reason's counter. +fn dump_sync_trace(why: &str, n: &AtomicU64, times: u64) { + if !sync_trace_on() || n.fetch_add(1, Ordering::Relaxed) >= times { + return; + } + let g = SYNC_TRACE.lock().unwrap(); + let last = g.back().map_or(0, |e| e.0); + crate::xlog_warn!("SYNC TRACE ({why}): {} events, the last at 0:", g.len()); + for (t, w) in g.iter() { + crate::xlog_warn!("SYNC {:>9.3} {w}", (*t as f64 - last as f64) / 1000.0); + } +} + fn queue_id(q: usize) -> usize { let mut g = QUEUE_IDS.lock().unwrap(); if let Some(pos) = g.iter().position(|&x| x == q) { @@ -2237,7 +2555,7 @@ fn queue_id(q: usize) -> usize { /// was removed). Returns the fence's current completed value (or `0` if no fence exists yet). unsafe fn prune_completed_waits(cell: &mut SyncCell) -> u64 { let Some(ref fence) = cell.fence else { return 0 }; - let completed = fence.GetCompletedValue(); + let completed = super::real::fence_completed(&fence); if completed == u64::MAX { let removed = cell.armed_waits.len(); cell.armed_waits.clear(); @@ -2268,7 +2586,7 @@ unsafe fn prune_title_fence(fence_raw: usize, tf: &mut TitleFenceSync) { } let p = fence_raw as *mut c_void; let Some(f) = ID3D12Fence::from_raw_borrowed(&p) else { return }; - let completed = f.GetCompletedValue(); + let completed = super::real::fence_completed(&f); if completed == u64::MAX { tf.waits.clear(); tf.signals.clear(); @@ -2296,7 +2614,15 @@ unsafe fn would_signal_close_cycle(graph: &mut SyncGraph, sig_q: usize, target_v if completed == u64::MAX || target.armed_waits.is_empty() { return false; } - target.armed_waits.iter().filter(|aw| aw.val <= sig_val).map(|aw| (aw.waiting_queue, aw.wait_seq)).collect() + // A wait an earlier signal of this cell already satisfies (GPU or CPU) does not wait on + // this one: counting it made every pipelined frame (wait N armed, signal N+1 next) a cycle. + let covered = target.submitted_max.max(target.cpu_signaled_max); + target + .armed_waits + .iter() + .filter(|aw| aw.val <= sig_val && aw.val > covered) + .map(|aw| (aw.waiting_queue, aw.wait_seq)) + .collect() }; if target_waiters.is_empty() { return false; @@ -2435,7 +2761,10 @@ pub(super) unsafe fn break_cycles_before_title_signal(sig_q: usize, title_fence: let Some(graph) = g.as_mut() else { return }; let Some(tf) = graph.title_fences.get_mut(&title_fence) else { return }; prune_title_fence(title_fence, tf); - let target_waiters: Vec<(usize, u64)> = tf.waits.iter().filter(|&&(v, _, _)| v <= sig_val).map(|&(_, wq, wseq)| (wq, wseq)).collect(); + // (a wait an earlier signal of the fence satisfies does not wait on this one, as for the + // cells in `would_signal_close_cycle`) + let covered = tf.signals.iter().map(|s| s.val).max().unwrap_or(0); + let target_waiters: Vec<(usize, u64)> = tf.waits.iter().filter(|&&(v, _, _)| v <= sig_val && v > covered).map(|&(_, wq, wseq)| (wq, wseq)).collect(); if target_waiters.is_empty() { return; } @@ -2561,6 +2890,28 @@ fn take_expired_gpu_wait(cell: &mut SyncCell, held: bool) -> Option bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| wait_timeout_continues_from(std::env::var("XCL_WAIT_TIMEOUT_CONTINUE").ok().as_deref())) +} + +fn wait_timeout_continues_from(v: Option<&str>) -> bool { + v.is_some_and(|v| v.trim() == "1") +} + +/// `XCL_WAIT_TIMEOUT_CONTINUE`: the expired wait at `val` on `cell` counts as signalled on the +/// CPU (a later GPU signal at or below it no longer stands, and a rewind is guarded against); +/// the fence to signal to `val`, if the cell has one. +fn release_expired_on_cpu(cell: &mut SyncCell, val: u64) -> Option { + cell.cpu_signaled_max = cell.cpu_signaled_max.max(val); + cell.submitted_signals.retain(|s| s.val > val); + cell.fence.clone() +} + fn stop_for_unresolved_wait(reason: &str) -> ! { let message = format!("{reason} – the title is stopped before its remaining GPU submission"); crate::xlog_error!("{message}"); @@ -2580,8 +2931,23 @@ fn wake_sync_watchdog() { let _ = cv.wait_timeout(guard, Duration::from_millis(50)).unwrap(); let (expired, rewinds) = { let mut g = SYNC_GRAPH.lock().unwrap(); + // the graph as it is while the waits stand (what is released below changes it at once) + static BEFORE: AtomicU64 = AtomicU64::new(0); + if let Some(graph) = g.as_ref() { + let timeout = gpu_wait_watchdog_timeout(); + let late = graph.cells.values().any(|c| { + let done = c.fence.as_ref().map_or(0, |f| unsafe { super::real::fence_completed(f) }); + c.armed_waits.iter().any(|w| w.val > done && w.armed_at.elapsed() >= timeout) + }); + if late && BEFORE.fetch_add(1, Ordering::Relaxed) < 3 { + crate::xlog_warn!("D3D12.X: wait edges before the release: {}", edges_of(graph)); + static DUMPS: AtomicU64 = AtomicU64::new(0); + dump_sync_trace("before the watchdog's release", &DUMPS, 2); + } + } let mut out: Vec<(u64, u64, usize, i32, Option, Option, u64, u64, u64)> = Vec::new(); let mut rew: Vec<(ID3D12Fence, u64)> = Vec::new(); + let continues = wait_timeout_continues(); if let Some(graph) = g.as_mut() { for (&va, cell) in graph.cells.iter_mut() { if cell.armed_waits.is_empty() && cell.cpu_signaled_max == 0 { @@ -2609,6 +2975,11 @@ fn wake_sync_watchdog() { ARMED_GPU_WAITS.fetch_sub(removed, Ordering::AcqRel); } if let Some(expired) = expired { + if continues { + if let Some(f) = release_expired_on_cpu(cell, expired.val) { + rew.push((f, expired.val)); + } + } out.push(( va, expired.val, @@ -2631,6 +3002,9 @@ fn wake_sync_watchdog() { } } let had_expired = !expired.is_empty(); + if had_expired { + super::indirect_guard::report_now(); + } for &(va, val, waiter_q, waiter_ty, prod_q, prod_ty, rec, sub, done) in &expired { let wq = queue_id(waiter_q); let pq = prod_q.map(queue_id); @@ -2642,7 +3016,16 @@ fn wake_sync_watchdog() { if had_expired { crate::xlog_warn!("D3D12.X: pending title ID3D12Fences during GPU wait timeout: {}", super::fence_x::pending_summary()); crate::xlog_warn!("D3D12.X: XCL's own queue waits unmet during GPU wait timeout: {}", internal_waits_summary()); - stop_for_unresolved_wait("a GPU queue wait exceeded its watchdog without a graph-proven cycle"); + crate::xlog_warn!("D3D12.X: queues behind during GPU wait timeout: {}", progress_summary()); + static PRINTED: AtomicU64 = AtomicU64::new(0); + if PRINTED.fetch_add(1, Ordering::Relaxed) < 3 { + crate::xlog_warn!("D3D12.X: wait edges at that time-out: {}", edges_summary()); + } + if wait_timeout_continues() { + crate::xlog_warn!("D3D12.X: XCL_WAIT_TIMEOUT_CONTINUE=1 – the timed-out GPU queue waits were released on the CPU and the title goes on"); + } else { + stop_for_unresolved_wait("a GPU queue wait exceeded its watchdog without a graph-proven cycle"); + } } }); }); @@ -2706,6 +3089,8 @@ fn note_write64_recorded(list: *mut c_void, va: u64, value: u64) { if value == 0 || !va.is_multiple_of(8) { return; } + // (the cell is the CPU's: a wait on the other view of the same memory meets it) + let va = cpu_at(va); let (lty, last_q, recording) = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); @@ -2853,6 +3238,19 @@ unsafe fn signal_write64_pairs(queue: *mut c_void, pairs: &[(u64, u64)]) { } } }; + sync_trace(|| { + let how = match &action { + SignalAction::Skip => "nobody needs it".to_string(), + SignalAction::GpuSignal => "SIGNAL".to_string(), + SignalAction::CpuCycleBreak(w) => format!("CYCLE – signalled on the CPU, waiters {:?}", w.iter().map(|x| queue_id(x.0)).collect::>()), + }; + let seq = SYNC_GRAPH.lock().unwrap().as_ref().and_then(|g| g.cells.get(&va)).and_then(|c| c.submitted_signals.iter().rev().find(|x| x.queue == sig_q && x.val == val).map(|x| x.seq)); + format!("q{}@{} signal {va:#x} = {val:#x}: {how}", queue_id(sig_q), seq.map_or("-".to_string(), |x| x.to_string())) + }); + if matches!(action, SignalAction::CpuCycleBreak(_)) { + static DUMPS: AtomicU64 = AtomicU64::new(0); + dump_sync_trace("cycle break", &DUMPS, 3); + } match action { SignalAction::Skip => {} SignalAction::GpuSignal => { @@ -2894,11 +3292,9 @@ pub(super) unsafe fn signal_write64_fences(queue: *mut c_void, lists: &[*mut c_v trace_list(l as usize, ListEvent::Executed); } let pairs: Vec<(u64, u64)> = { - let g = LISTS.lock().unwrap(); - let Some(m) = g.as_ref() else { return }; let mut out = Vec::new(); for &l in lists { - if let Some(s) = m.get(&(l as usize)) { + if let Some(s) = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(l as usize))) { out.extend_from_slice(&s.write64_signals); } } @@ -2960,11 +3356,13 @@ unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait, list_writes: &[(u64, // Already released on CPU (cycle break or watchdog): never re-arm a GPU wait that could // observe a vkd3d-proton fence rewind. if cpu_sig_max >= w.value { + sync_trace(|| format!("q{} wait {:#x} >= {:#x}: released on the CPU before", queue_id(q_raw), w.va, w.value)); return GpuWaitOutcome::Handled; } // Producer already submitted earlier on THIS EXACT queue: D3D12 FIFO executes it strictly // before this list without needing a CPU wait or redundant queue.Wait. if sub_max >= w.value && sub_q == Some(q_raw) { + sync_trace(|| format!("q{} wait {:#x} >= {:#x}: this queue signals {sub_max:#x} before", queue_id(q_raw), w.va, w.value)); return GpuWaitOutcome::Handled; } // Same-batch self-wait: this very submission writes `(w.va, >= w.value)`, so hoisting a GPU @@ -2999,6 +3397,8 @@ unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait, list_writes: &[(u64, let completed = prune_completed_waits(cell); if completed >= w.value { // Fence already reached `w.value`: trust it if CPU memory agrees (not reset). + drop(g); + super::sparse::settle_readbacks(); return if w.is_satisfied() { GpuWaitOutcome::Handled } else { GpuWaitOutcome::FallbackCpu }; } if cell.submitted_max >= w.value && cell.submitted_queue == Some(q_raw) { @@ -3021,6 +3421,17 @@ unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait, list_writes: &[(u64, ARMED_GPU_WAITS.fetch_add(1, Ordering::AcqRel); (pre_ok.0, pre_ok.1, pre_ok.2, wait_seq) }; + sync_trace(|| { + format!( + "q{}@{wait_seq} WAIT {:#x} >= {:#x} (submitted {sub_max:#x} by {:?}{}{})", + queue_id(q_raw), + w.va, + w.value, + sub_q.map(queue_id), + if unsubmitted { ", not signalled yet" } else { "" }, + if w.after_write64 { ", after a Write64 of its list" } else { "" } + ) + }); if let Err(e) = super::real::native_queue_wait(q, &fence, w.value) { let mut g = SYNC_GRAPH.lock().unwrap(); @@ -3034,6 +3445,7 @@ unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait, list_writes: &[(u64, return GpuWaitOutcome::FallbackCpu; } + note_cell_wait(q_raw, w.va, &fence, w.value); wake_sync_watchdog(); if unsubmitted { static LOGGED: AtomicU64 = AtomicU64::new(0); @@ -3053,23 +3465,38 @@ unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait, list_writes: &[(u64, GpuWaitOutcome::Handled } +#[cfg(test)] unsafe fn wait_all_on_with_timeout( queue: *mut c_void, waits: &[PendingWait], list_writes: &[(u64, u64)], timeout: Duration, ) -> bool { + wait_all_on_noting_cpu(queue, waits, list_writes, timeout).0 +} + +/// `wait_all_on_with_timeout`, and whether a wait was waited for on the CPU. +unsafe fn wait_all_on_noting_cpu( + queue: *mut c_void, + waits: &[PendingWait], + list_writes: &[(u64, u64)], + timeout: Duration, +) -> (bool, bool) { static TIMEOUTS: AtomicU64 = AtomicU64::new(0); static RING_DUMPED: AtomicU64 = AtomicU64::new(0); let q_ty = queue_device_and_type(queue).map_or(-1, |(_, _, t)| t.0); + let mut on_cpu = false; for w in waits { if w.is_satisfied() { + sync_trace(|| format!("q{} wait {:#x} >= {:#x}: memory holds it", queue_id(queue as usize), w.va, w.value)); continue; } let outcome = try_gpu_wait(queue, w, list_writes); if wait_is_resolved(outcome, false) { continue; } + on_cpu = true; + sync_trace(|| format!("q{} wait {:#x} (op {}) {:#x}: on the CPU", queue_id(queue as usize), w.va, w.comparison, w.value)); let memory_stall = crate::stall::span(crate::stall::StallKind::MemorySynchronization); let satisfied = w.wait_until_satisfied(timeout); drop(memory_stall); @@ -3079,8 +3506,9 @@ unsafe fn wait_all_on_with_timeout( if once(&TIMEOUTS, 40) { let cell_diag = { let g = SYNC_GRAPH.lock().unwrap(); - g.as_ref().and_then(|gr| gr.cells.get(&w.va)).map(|c| (c.recorded_max, c.submitted_max, c.non_monotonic, c.recorded_list_type.map(|t| t.0))) + g.as_ref().and_then(|gr| gr.cells.get(&w.va)).map(|c| (c.recorded_max, c.submitted_max, c.non_monotonic, c.recorded_list_type.map(|t| t.0), c.submitted_queue.map(queue_id))) }; + let behind = progress_summary(); crate::xlog_warn!( "D3D12.X: Wait{}BitValueX timed out after {} ms at {:#x} (op {}, want {:#x}, mask {:#x}; memory holds {:x?}; queue_type={}, after_write64={}, sync={cell_diag:x?})", w.width * 8, @@ -3093,6 +3521,9 @@ unsafe fn wait_all_on_with_timeout( q_ty, w.after_write64 ); + if !behind.is_empty() { + crate::xlog_warn!("D3D12.X: queues behind at that time-out: {behind}"); + } if once(&RING_DUMPED, 2) { let (total, entries) = WRITE_TRACE.lock().unwrap().snapshot(); let summary: Vec = entries @@ -3104,15 +3535,20 @@ unsafe fn wait_all_on_with_timeout( crate::xlog_warn!("D3D12.X: recent Write32/64 calls ({total} total): [{}]", summary.join(", ")); } } - return false; + return (false, on_cpu); } - true + (true, on_cpu) } -unsafe fn wait_all_on(queue: *mut c_void, waits: &[PendingWait], list_writes: &[(u64, u64)]) { - if !wait_all_on_with_timeout(queue, waits, list_writes, wait_timeout()) { +/// The waits of a list before it goes: on the GPU where they can be, else on the CPU. Whether one +/// was waited for on the CPU. +unsafe fn wait_all_on(queue: *mut c_void, waits: &[PendingWait], list_writes: &[(u64, u64)]) -> bool { + let (resolved, on_cpu) = wait_all_on_noting_cpu(queue, waits, list_writes, wait_timeout()); + // (`XCL_WAIT_TIMEOUT_CONTINUE=1`: the list goes out after the time-out, as before the merge on nvidia-dev) + if !resolved && !wait_timeout_continues() { stop_for_unresolved_wait("a CPU fallback memory wait timed out without a proven completion"); } + on_cpu } /// Copy any GPU memory writes into sparse VRAM windows recorded by `lists` back into their @@ -3121,35 +3557,65 @@ pub(super) unsafe fn readback_sparse_writes(queue: *mut c_void, lists: &[*mut c_ if SPARSE_WRITE_LISTS.load(Ordering::Acquire) == 0 || queue.is_null() || lists.is_empty() { return; } - let ranges: Vec<(usize, usize)> = { - let g = LISTS.lock().unwrap(); - let Some(m) = g.as_ref() else { return }; - let mut out = Vec::new(); + let (ranges, imms): (Vec<(usize, usize)>, Vec<(usize, u64, u8)>) = { + let (mut out, mut imm) = (Vec::new(), Vec::new()); for &l in lists { - if let Some(s) = m.get(&(l as usize)) { + if let Some(s) = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(l as usize))) { out.extend_from_slice(&s.sparse_writes); + imm.extend_from_slice(&s.sparse_imm); } } - out + (out, imm) }; - if ranges.is_empty() { + if ranges.is_empty() && imms.is_empty() { return; } if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { - super::sparse::readback_after_execute(q, &ranges); + // (lock order: the queue's submit lease, then the copy back's submit lock; the lease is + // re-entrant, so a caller already inside it keeps its turn) + super::queue_submit::with(queue as usize, || super::sparse::readback_after_execute(q, &ranges, &imms)); } } /// After `lists` went to `queue`: their writes into memory the GPU does not see (`cpu_writes`). pub(super) unsafe fn cpu_writes_after(queue: *mut c_void, lists: &[*mut c_void]) { let writes: Vec = { - let g = LISTS.lock().unwrap(); - let Some(m) = g.as_ref() else { return }; - lists.iter().filter_map(|&l| m.get(&(l as usize))).flat_map(|s| s.cpu_writes.iter().cloned()).collect() + let of = |&l: &*mut c_void| LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(l as usize))).map(|s| s.cpu_writes.clone()); + lists.iter().filter_map(of).flatten().collect() }; super::cpu_writes::after(queue, writes); } +/// After a wait on the CPU inside a submit: what the title committed meanwhile (the thread that +/// writes the value may have) is mapped, and cleared, before the lists that go out now – the +/// submit's own `before_execute` came before the wait. +unsafe fn mapped_after_wait(queue: *mut c_void) { + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { + // (fails closed as the submit's own preparation does: `real::prepare_title_submission`) + match super::sparse::before_execute(q, &[], 0x1000, None) { + super::sparse::PreparationOutcome::Ready => {} + super::sparse::PreparationOutcome::RetryRequired => stop_for_unresolved_wait("sparse upload preparation after a wait inside a submit still failed after bounded retries"), + super::sparse::PreparationOutcome::ExecutedUntracked => stop_for_unresolved_wait("a sparse upload after a wait inside a submit executed without a retirement signal"), + } + } +} + +/// `XCL_SPLIT_SPARSE=cpu` (off unless set): after a split at waits that all went to the GPU (or +/// held already), the sparse windows are not brought up to date again (`mapped_after_wait`): the +/// lists before and after the split went out within the submit, as an unsplit submit's do. A +/// retail title's world split many of its ~19 submits a frame at Wait64BitValueX waits bridged to +/// the GPU, and each split took the sparse state's lock again. +fn split_sparse_after_cpu_waits_only() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SPLIT_SPARSE").is_ok_and(|v| v.trim().eq_ignore_ascii_case("cpu"))) +} + +/// Whether a split, whose waits were (`on_cpu`) or were not waited for on the CPU, brings the +/// sparse windows up to date again (`only_after_cpu`: `XCL_SPLIT_SPARSE=cpu`). +fn sparse_again_after_split(on_cpu: bool, only_after_cpu: bool) -> bool { + on_cpu || !only_after_cpu +} + /// Capture every mutable per-list effect once, before any part of this submission reaches the /// driver. Resetting or re-recording a list after this point cannot change the returned plan. pub(super) fn submission_plan(lists: &[*mut c_void]) -> SubmissionPlan { @@ -3165,9 +3631,11 @@ unsafe fn submit_segment_effects(queue: *mut c_void, effects: &[SegmentEffects], signal_write64_pairs(queue, &write64_signals); let sparse_writes: Vec<(usize, usize)> = effects.iter().flat_map(|e| e.sparse_writes.iter().copied()).collect(); - if !sparse_writes.is_empty() { + let sparse_imm: Vec<(usize, u64, u8)> = effects.iter().flat_map(|e| e.sparse_imm.iter().copied()).collect(); + if !sparse_writes.is_empty() || !sparse_imm.is_empty() { if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { - super::sparse::readback_after_execute(q, &sparse_writes); + // (lease before the copy back's submit lock, as in `readback_sparse_writes`) + super::queue_submit::with(queue as usize, || super::sparse::readback_after_execute(q, &sparse_writes, &sparse_imm)); } } @@ -3197,6 +3665,20 @@ unsafe fn execute_submission_plan_with_completions( let (submitted, completion) = submit(chunk(0, plan.lists.len())); return (completion.into_iter().collect(), submitted); } + sync_trace(|| { + let rows: Vec = plan + .lists + .iter() + .zip(&plan.effects) + .map(|(l, e)| { + let wrapper = super::title_list::wrapper_of(*l).map_or(0, |p| p as usize) & 0xFFFFF; + let waits: Vec = e.waits.iter().map(|p| format!("W{:x}>={:x}{}", p.va & 0xFFF, p.value, if p.is_satisfied() { "ok" } else { "" })).collect(); + let writes: Vec = e.write64_signals.iter().map(|p| format!("S{:x}={:x}", p.0 & 0xFFF, p.1)).collect(); + format!("{:x}/{wrapper:x}[{} | {}]", *l as usize & 0xFFFFF, waits.join(" "), writes.join(" ")) + }) + .collect(); + format!("q{} EXECUTE {} lists: {}", queue_id(queue as usize), plan.lists.len(), rows.join(" ")) + }); let mut completions = Vec::new(); let mut start = 0usize; for (i, effects) in plan.effects.iter().enumerate() { @@ -3208,6 +3690,7 @@ unsafe fn execute_submission_plan_with_completions( continue; } if i > start { + sync_trace(|| format!("q{} submit lists {start}..{i}", queue_id(queue as usize))); let (submitted, completion) = submit(chunk(start, i)); if !submitted { return (completions, false); @@ -3219,10 +3702,17 @@ unsafe fn execute_submission_plan_with_completions( let _ = completion.wait(); } } - wait_all_on(queue, &effects.waits, &effects.write64_signals); + let t = Instant::now(); + let on_cpu = wait_all_on(queue, &effects.waits, &effects.write64_signals); + let t_waited = Instant::now(); + if sparse_again_after_split(on_cpu, split_sparse_after_cpu_waits_only()) { + mapped_after_wait(queue); + } + super::submit_cost::split(t_waited - t, t_waited.elapsed()); start = i; } if start < plan.lists.len() { + sync_trace(|| format!("q{} submit lists {start}..{}", queue_id(queue as usize), plan.lists.len())); let (submitted, completion) = submit(chunk(start, plan.lists.len())); if !submitted { return (completions, false); @@ -3277,12 +3767,22 @@ pub(super) unsafe fn execute_with_waits(lists: &[*mut c_void], submit: impl FnMu /// command list #60 CopyMemoryToMemoryX(destination, source, size, flags) pub(super) unsafe extern "system" fn copy_memory_x(this: *mut c_void, dst: u64, src: u64, size: u64, _flags: u32) { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListCopy); static N: AtomicU64 = AtomicU64::new(0); const W: &str = "CopyMemoryToMemoryX"; - if size == 0 || !size.is_multiple_of(4) { + let refused = size == 0 || !size.is_multiple_of(4); + let _c = super::capture::op(this, || { + use super::capture as c; + Some(c::Op::Copy { kind: "memory", dst: c::Loc::Address(dst), src: c::Loc::Address(src), at: [0; 3], bx: None, bytes: Some(size), refused }) + }); + if refused { return warn(&N, W, format_args!("size {size:#x} is not a non-zero multiple of 4")); } - let (Some((d, doff)), Some((s, soff))) = (real::uma_window_buffer(dst as usize, size as usize), real::uma_window_buffer(src as usize, size as usize)) else { + // In a GPU view: its tiles, asked for here, are filled from the CPU view before the list runs, + // and what the copy writes is read back to the CPU view (`note_write`) + super::bind::want_view(super::view_want::Path::MemoryOp, src, size); + super::bind::want_view(super::view_want::Path::MemoryOp, dst, size); + let (Some((d, doff)), Some((s, soff))) = (real::uma_window_buffer_gpu(dst as usize, size as usize), real::uma_window_buffer_gpu(src as usize, size as usize)) else { note_gpu_write("CopyMemoryToMemoryX", dst as usize, size); return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) is not in unified memory")); }; @@ -3335,7 +3835,7 @@ struct CopyScratch { impl CopyScratch { fn idle(&mut self) -> bool { - self.marks.retain(|_, (fence, value)| unsafe { fence.GetCompletedValue() < *value }); + self.marks.retain(|_, (fence, value)| unsafe { super::real::fence_completed(&fence) < *value }); !self.untracked_submission && self.marks.is_empty() } } @@ -3542,7 +4042,9 @@ unsafe fn fill(list: *mut c_void, va: u64, size: u64, pat: [u8; 16], unit: u64, if size == 0 || !size.is_multiple_of(unit) || size > MAX_FILL { return warn(&N, what, format_args!("size {size:#x} (a non-zero multiple of {unit} up to {MAX_FILL:#x} is filled)")); } - let Some((d, off)) = real::uma_window_buffer(va as usize, size as usize) else { + // (in a GPU view: on its tiles, read back to the CPU view after the submit) + super::bind::want_view(super::view_want::Path::MemoryOp, va, size); + let Some((d, off)) = real::uma_window_buffer_gpu(va as usize, size as usize) else { return warn(&N, what, format_args!("{va:#x} ({size:#x} bytes) is not in unified memory")); }; let Some(src) = pattern_buffer(list, pat, size) else { @@ -3562,21 +4064,34 @@ fn pattern(bytes: &[u8]) -> [u8; 16] { /// command list #61 FillMemoryWith32BitValueX(address, size, value) pub(super) unsafe extern "system" fn fill32_x(this: *mut c_void, va: u64, size: u64, value: u32) { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListCopy); fill(this, va, size, pattern(&value.to_le_bytes()), 4, "FillMemoryWith32BitValueX"); } /// command list #62 FillMemoryWith64BitValueX(address, size, value) pub(super) unsafe extern "system" fn fill64_x(this: *mut c_void, va: u64, size: u64, value: u64) { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListCopy); fill(this, va, size, pattern(&value.to_le_bytes()), 8, "FillMemoryWith64BitValueX"); } /// command list #63 FillMemoryWith128BitValueX(address, size, value*) pub(super) unsafe extern "system" fn fill128_x(this: *mut c_void, va: u64, size: u64, value: *const [u8; 16]) { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListCopy); if !value.is_null() { fill(this, va, size, value.read_unaligned(), 16, "FillMemoryWith128BitValueX"); } } +/// `XCL_IMM_BY_CPU=0`: a bottom-of-pipe immediate into a window the GPU has a copy of comes +/// back to the CPU's view with a copy, like the lists' other memory writes. Otherwise XCL stores +/// the value it was given there once the submission is done on the GPU. A retail title's CPU +/// waits on such cells; copied back, one of them held a value up to 46 frames old in the CPU's +/// view (and older than it had held before) while its GPU fence was reached. +fn imm_by_cpu() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_IMM_BY_CPU").map_or(true, |v| v.trim() != "0")) +} + /// Values written by the GPU at `va` (WriteBufferImmediate: MARKER_IN = when the command is /// reached, MARKER_OUT = when the work before it is done). unsafe fn write(list: *mut c_void, va: u64, words: &[u32], mode: D3D12_WRITEBUFFERIMMEDIATE_MODE, what: &str) { @@ -3585,8 +4100,10 @@ unsafe fn write(list: *mut c_void, va: u64, words: &[u32], mode: D3D12_WRITEBUFF if !va.is_multiple_of(n) { return warn(&N, what, format_args!("{va:#x} is not {n}-byte aligned")); } - let (Some((d, _)), Some(at)) = (real::uma_window_buffer(va as usize, n as usize), real::uma_va_of(va as usize)) else { - // the title's own memory: written by the CPU once the GPU is there + // (in a GPU view: on its tiles, and the CPU view gets the value after the submit) + super::bind::want_view(super::view_want::Path::MemoryOp, va, n); + let (Some((d, _)), Some(at)) = (real::uma_window_buffer_gpu(va as usize, n as usize), real::uma_va_of(va as usize)) else { + // the title's own memory: written by the CPU once the GPU is there (never a GPU view) if super::cpu_writes::writable(va as usize, n as usize) { if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { s.note_write(WriteProducer::CpuAfterSegment, va, n); @@ -3596,7 +4113,17 @@ unsafe fn write(list: *mut c_void, va: u64, words: &[u32], mode: D3D12_WRITEBUFF } return warn(&N, what, format_args!("{va:#x} is not in unified memory")); }; - note_write(list as usize, WriteProducer::InSegmentGpu, va, n); + // into a window the GPU only has a copy of: the CPU's view gets the value from XCL + if words.len() <= 2 && imm_by_cpu() && read_back(va) { + let value = words.iter().enumerate().fold(0u64, |v, (i, &w)| v | (w as u64) << (32 * i)); + // a counter the title's queues write in turn (a `SyncCell` whose values only rose): a list + // that runs late does not take the CPU's view of it back (`sparse::IMM_KEEP_MAX`) + let counter = words.len() == 2 && SYNC_GRAPH.lock().unwrap().as_ref().and_then(|g| g.cells.get(&cpu_at(va))).is_some_and(|c| !c.non_monotonic && c.recorded_max != 0); + let bytes = n as u8 | if counter { super::sparse::IMM_KEEP_MAX } else { 0 }; + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default().note_imm(va, value, bytes); + } else { + note_write(list as usize, WriteProducer::InSegmentGpu, va, n); + } let params: Vec = words.iter().enumerate().map(|(i, &w)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: at + 4 * i as u64, Value: w }).collect(); let modes = vec![mode; words.len()]; type F = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, *const D3D12_WRITEBUFFERIMMEDIATE_MODE); @@ -3657,7 +4184,9 @@ unsafe fn timestamp(list: *mut c_void, va: u64, what: &str) { if !va.is_multiple_of(8) { return warn(&N, what, format_args!("{va:#x} is not 8-byte aligned")); } - let uma_dst = real::uma_window_buffer(va as usize, 8); + // (in a GPU view: resolved into its tile, read back to the CPU view after the submit) + super::bind::want_view(super::view_want::Path::MemoryOp, va, 8); + let uma_dst = real::uma_window_buffer_gpu(va as usize, 8); if uma_dst.is_none() && !super::cpu_writes::writable(va as usize, 8) { return warn(&N, what, format_args!("{va:#x} is not in unified memory")); } @@ -3713,12 +4242,14 @@ unsafe fn timestamp(list: *mut c_void, va: u64, what: &str) { /// # Safety /// `this` must be a valid adopted `ID3D12GraphicsCommandList` pointer. pub unsafe extern "system" fn write32_bottom_x(this: *mut c_void, va: u64, value: u32, _flush: u32, flags: u32) { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListCopy); record_write_trace(this, va, value as u64, flags, "W32B"); write(this, va, &[value], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT, "Write32BitValueBottomOfPipeX"); } /// command list #70 Write64BitValueBottomOfPipeX(address, value, flush, flags) pub(super) unsafe extern "system" fn write64_bottom_x(this: *mut c_void, va: u64, value: u64, _flush: u32, flags: u32) { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListCopy); const W: &str = "Write64BitValueBottomOfPipeX"; record_write_trace(this, va, value, flags, "W64B"); if flags & BOTTOM_TIMESTAMPS != 0 { @@ -3734,6 +4265,7 @@ pub(super) unsafe extern "system" fn write64_bottom_x(this: *mut c_void, va: u64 /// NVIDIA removes the device). The new recording goes onto a spare PC list of the wrapper whose /// submits are done, or a new one, reset like `primary` would be. None: it could not be. pub(super) unsafe fn reset_stand_in(wrapper: *mut c_void, primary: *mut c_void, alloc: usize, pso: usize) -> Option { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListLifecycle); let ty = list_type(primary); if ty == D3D12_COMMAND_LIST_TYPE_BUNDLE || alloc == 0 { return None; @@ -3755,7 +4287,7 @@ pub(super) unsafe fn reset_stand_in(wrapper: *mut c_void, primary: *mut c_void, made } }; - if reset_pc(spare, alloc, pso) < 0 { + if reset_pc_inner(spare, alloc, pso) < 0 { super::title_list::put_spare(wrapper, spare); return None; } @@ -3828,15 +4360,29 @@ pub(super) unsafe fn defer_retained( fn exact_restoration_waits_bounded(_configured: bool) -> bool { false } unsafe fn defer_with(list: *mut c_void, what: Deferred, waits_bounded: bool, demand: impl FnOnce()) -> bool { + // (one the submit records now waits there: `record_deferred`) + if super::pso_async::is_at_submit() { + return false; + } + // (without the allocator swap the submit would reset the list's own allocator while the GPU + // may still run what its last submit recorded on it: the dispatch waits in the call) + if !super::alloc_pool::enabled() { + super::pso_async::note_put_off(super::pso_async::PutOff::Refused); + return false; + } // A bounded bind records now and waits for the same bound. Deferring it only adds a segment; // thousands of these exhausted command-list memory in a retail title with a 1 ms budget. - if !defer_pipeline_wait( - waits_bounded, - demand, - || split_recording(list, SegmentReason::DeferredDispatch(what)).is_some(), - ) { + let mut refused = false; + if !defer_pipeline_wait(waits_bounded, demand, || { + refused = split_recording(list, SegmentReason::DeferredDispatch(what)).is_none(); + !refused + }) { + if refused { + super::pso_async::note_put_off(super::pso_async::PutOff::Refused); + } return false; } + super::pso_async::note_put_off(super::pso_async::PutOff::Deferred); static N: AtomicU64 = AtomicU64::new(0); let n = N.fetch_add(1, Ordering::Relaxed) + 1; if n <= 4 || n.is_power_of_two() { @@ -3862,13 +4408,21 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { super::title_list::push_segments(wrapper, &mut segs); let Some(&first) = segs.first() else { return }; segs.retain(|&seg| seg == first || LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(seg as usize))).is_some_and(|s| s.deferred.is_some())); + if segs.len() < 2 { + return; + } + // (on the primary list, which stays the wrapper's: `deferred_segment`) + let own = super::title_list::backing(wrapper).and_then(|p| LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(p as usize))?.own_alloc.clone())); + // (its waits and own builds are the submit's: the put-off line) + let _at_submit = super::pso_async::at_submit(); let mut last: Option<*mut c_void> = None; for &seg in segs.iter().skip(1) { let Some((what, ty, heaps)) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(seg as usize))).and_then(|s| Some((s.deferred.take()?, s.list_type?, s.bindings.heaps.clone()))) else { continue; }; - let Some(own) = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(first as usize))?.own_alloc.clone()) else { + let Some(own) = own.as_ref() else { super::bind::dispatch_dropped(); + super::pso_async::note_put_off(super::pso_async::PutOff::Dropped); continue; }; let own = own.as_raw(); @@ -3885,6 +4439,7 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { static RESET_ERR: AtomicU64 = AtomicU64::new(0); warn(&RESET_ERR, "deferred dispatch", format_args!("Reset failed ({hr:#x})")); super::bind::dispatch_dropped(); + super::pso_async::note_put_off(super::pso_async::PutOff::Dropped); continue; } reset_copy_scratch(seg); @@ -3895,6 +4450,13 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { super::bind::pass_arena(last, seg); real::dispatch_chain::list_follows(last as usize, seg as usize); } + // (a recording of its own, made here and not through `cl_reset`: its pipeline is named + // before the dispatch, for the device-removal report) + super::dred::reset(seg); + let p = super::bind::bound_pso(seg); + if p != 0 { + super::dred::mark_pipeline(seg, p, super::pso_async::peek(p)); + } match what { Deferred::Dispatch(x, y, z, flags) => super::bind::dispatch_flags(seg, x, y, z, flags), Deferred::Indirect { sig, max, args, args_off, count_buf, count_off, signature } => { @@ -3903,6 +4465,10 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { ) } } + let built = super::pso_async::has_real(super::bind::bound_pso(seg)); + super::pso_async::note_put_off(if built { super::pso_async::PutOff::Recorded } else { super::pso_async::PutOff::Skipped }); + super::bind::flush_two_pass(seg, super::bind::RunEnd::Segment); + super::gpu_times::before_close(seg); let ext = *(seg as *const usize); let hr = segment_close(wrapper, seg); real::preserve_vtable(seg, ext); @@ -4027,7 +4593,10 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - None }; let mut continuation_state = carry.continuation_state(ty); - let next_bindings = super::bind::prepare_split(list, next_pc, alloc); + // (what the segments put in unified memory is held for the PC allocator they record on, as + // `next_pc`'s: the GPU is done with it when with that list's other segments) + let on = super::alloc_pool::current(alloc); + let next_bindings = super::bind::prepare_split(list, next_pc, on); let (init_pso, init_generation) = if ty == D3D12_COMMAND_LIST_TYPE_COPY { (0, None) } else { @@ -4036,7 +4605,7 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - if let Some(generation) = init_generation { drop(continuation_state.pin_native_generation(generation)); } - let deferred_bindings = deferred.as_ref().map(|(seg, _)| super::bind::prepare_split(list, *seg, alloc)); + let deferred_bindings = deferred.as_ref().map(|(seg, _)| super::bind::prepare_split(list, *seg, on)); // Commit starts here: all allocation is complete and the continuation exists closed. { @@ -4044,6 +4613,7 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - let s = g.as_mut()?.get_mut(&(list as usize))?; carry.commit_state(s); } + super::bind::flush_two_pass(list, super::bind::RunEnd::Segment); if let Some(((h, i), qty)) = carry.active_query { pc::(list, PC_END_QUERY)(list, h, qty, i); } @@ -4053,6 +4623,7 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - } } + super::gpu_times::before_close(list); let ext = *(list as *const usize); let close_hr = pc:: i32>(list, PC_CLOSE)(list); real::preserve_vtable(list, ext); @@ -4086,7 +4657,7 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - let m = g.get_or_insert_with(HashMap::new); let old = m.remove(&(next_pc as usize)); if let Some(ref o) = old { - if !o.sparse_writes.is_empty() { + if o.has_sparse() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } if !o.write64_signals.is_empty() { @@ -4101,6 +4672,7 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - }; drop(old_next); super::bind::install_prepared_split(next_bindings); + super::lut3d::list_reset(next_pc as usize); restore_bindings(next_pc, bindings, ty); if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { @@ -4231,9 +4803,10 @@ unsafe fn reset_reserved_segment(list: *mut c_void, alloc: usize, ty: D3D12_COMM /// Prepare a closed, empty dispatch segment without publishing it into the recording. unsafe fn prepare_deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_COMMAND_LIST_TYPE) -> Option<*mut c_void> { let dev = device_of(list)?; - let mut segs = Vec::new(); - super::title_list::push_segments(wrapper, &mut segs); - let first = *segs.first()? as usize; + // (kept on the primary PC list: the first segment of a recording can be a spare standing in + // for it, `title_list::reset`, which goes back to the spares, and a split that takes it + // again replaces what is kept of it; `record_deferred` looks it up there) + let first = super::title_list::backing(wrapper)? as usize; let own = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&first)?.own_alloc.clone()); let _own = match own { Some(a) => a, @@ -4263,8 +4836,11 @@ unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, va if !va.is_multiple_of(n) { return warn(&N, what, format_args!("{va:#x} is not {n}-byte aligned")); } - // (the wait reads the memory on the CPU: the title's own memory too, which `cpu_writes` fills) - if real::uma_window_buffer(va as usize, width as usize).is_none() && !crate::gpu::shader::readable(va as usize, width as usize) { + // (the wait reads the memory on the CPU: the title's own memory too, which `cpu_writes` fills; + // in a GPU view at its CPU view, where what the lists write into its tiles is read back) + let at = cpu_at(va); + super::bind::want_view(super::view_want::Path::Wait, va, n); + if real::uma_window_buffer_gpu(va as usize, width as usize).is_none() && !crate::gpu::shader::readable(at as usize, width as usize) { return warn(&N, what, format_args!("{va:#x} is not readable memory")); } if compare_u64(comparison, 0, 0).is_none() { @@ -4283,7 +4859,7 @@ unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, va match placement { WaitPlacement::OrderedInSegment => return, WaitPlacement::RecordHere => { - s.push_wait(PendingWait { va, width, comparison, value, mask, after_write64: false }); + s.push_wait(PendingWait { va: at, width, comparison, value, mask, after_write64: false }); return; } WaitPlacement::SplitAfterCpuWrite | WaitPlacement::SplitAfterWrite64 => placement, @@ -4301,7 +4877,7 @@ unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, va let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(target as usize).or_default(); let after_write64 = !s.write64_signals.is_empty(); - s.push_wait(PendingWait { va, width, comparison, value, mask, after_write64 }); + s.push_wait(PendingWait { va: at, width, comparison, value, mask, after_write64 }); } /// command list #71 Wait32BitValueX(address, comparison, value, mask, flags) @@ -4352,9 +4928,7 @@ pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u3 super::bind::dispatch_flags(this, x, y, z, flags); } -/// command list #146 console compute/UAV barrier (used by `XboxBvhBuilder.dll` between BVH -/// build passes): emits a global UAV barrier so UMA writes become visible to the next pass -pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, _n: u32, _barriers: *const c_void) { +unsafe fn emit_uav_barrier_pc(this: *mut c_void) { let b = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, @@ -4365,6 +4939,41 @@ pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, _n: u32, _ pc::(this, PC_RESOURCE_BARRIER)(this, 1, &b); } +/// command list #146 console compute/UAV barrier (used by `XboxBvhBuilder.dll` between BVH +/// build passes): emits a global UAV barrier so UMA writes become visible to the next pass +pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, _n: u32, _barriers: *const c_void) { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListBarrier); + emit_uav_barrier_pc(this); +} + +/// A UAV barrier for all resources on `list`, where a list takes one (a copy list and a bundle +/// do not). +unsafe fn flush_barrier(list: *mut c_void) { + let ty = list_type(list); + if ty == D3D12_COMMAND_LIST_TYPE_DIRECT || ty == D3D12_COMMAND_LIST_TYPE_COMPUTE { + emit_uav_barrier_pc(list); + } +} + +/// command list #131 FlushGpuCacheRangeX / #132 FlushShaderCacheRangeX (cache flags, wait flags, +/// address, bytes), the newer layout's: the console writes its caches back (or drops what they +/// hold) for a range of memory and waits for the work before it. It is how a title orders a pass +/// behind the one that wrote what it reads – a retail title calls them thousands of times a minute, +/// and answered with nothing its passes had no order there. The PC has no ranges of caches: a UAV +/// barrier for everything. +pub(super) unsafe extern "system" fn flush_cache_range_x(this: *mut c_void, flags: u32, wait: u32, _va: u64, bytes: u64) { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListBarrier); + if (flags != 0 || wait != 0) && bytes != 0 { + flush_barrier(this); + } +} + +/// command list #67 (newer layout: #69) FlushPipelineX(flags, address, bytes) +pub(super) unsafe extern "system" fn flush_pipeline_x(this: *mut c_void, _flags: u32, _va: u64, _bytes: u64) { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListBarrier); + flush_barrier(this); +} + /// command list #84 CopyResourceX(destination, source, flags); in place (the console's /// compression operations) there is nothing to do on PC pub(super) unsafe extern "system" fn copy_resource_flags_x(this: *mut c_void, dst: usize, src: usize, _flags: u32) { @@ -4375,8 +4984,7 @@ pub(super) unsafe extern "system" fn copy_resource_flags_x(this: *mut c_void, ds /// Return `list`'s dedicated 256-byte predication buffer, creating it lazily in `COMMON` state. unsafe fn predication_buffer(list: *mut c_void) -> Option { - if let Some(p) = LISTS - .lock() + if let Some(p) = LISTS.lock() .unwrap() .as_ref() .and_then(|m| m.get(&(list as usize))) @@ -4464,8 +5072,7 @@ pub(super) fn on_pc_reset(list: *mut c_void) { unsafe fn apply_predication_copy(this: *mut c_void, uma_buf: usize, off: u64, pb: usize, op: D3D12_PREDICATION_OP) { type F = unsafe extern "system" fn(*mut c_void, usize, u64, D3D12_PREDICATION_OP); let f = pc::(this, PC_SET_PREDICATION); - let (was_active, was_in_state) = LISTS - .lock() + let (was_active, was_in_state) = LISTS.lock() .unwrap() .as_ref() .and_then(|m| m.get(&(this as usize))) @@ -4528,7 +5135,9 @@ pub unsafe extern "system" fn set_predication_buffer_x(this: *mut c_void, desc: if op_raw > 1 { return warn(&N, "SetPredicationBufferX", format_args!("unknown predication op {op_raw}")); } - let Some((uma_buf, off)) = real::uma_window_buffer(va as usize, 8).filter(|&(b, _)| b != 0 && va.is_multiple_of(8)) else { + // (the GPU alone reads the predicate: in a GPU view, from its tile) + super::bind::want_view(super::view_want::Path::MemoryOp, va, 8); + let Some((uma_buf, off)) = real::uma_window_buffer_gpu(va as usize, 8).filter(|&(b, _)| b != 0 && va.is_multiple_of(8)) else { return warn(&N, "SetPredicationBufferX", format_args!("{va:#x} is not 8-byte aligned in unified memory")); }; let Some(pb) = predication_buffer(this) else { @@ -4619,6 +5228,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { (s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, preclose_effects, current_trace) }; + super::bind::flush_two_pass(this, super::bind::RunEnd::Segment); // End any active occlusion query before Close (PC forbids closing with an open query). if let Some(((h, i), qty)) = active_query { pc::(this, PC_END_QUERY)(this, h, qty, i); @@ -4629,6 +5239,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } } + super::gpu_times::before_close(this); let ext = *(this as *const usize); let close_hr = pc:: i32>(this, PC_CLOSE)(this); real::preserve_vtable(this, ext); @@ -4644,19 +5255,22 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let effects = match preclose_effects { Some(effects) => effects, None => LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))).map(take_kickoff_effects).unwrap_or(KickoffEffects { - waits: Vec::new(), sparse_writes: Vec::new(), texture_writes: Vec::new(), texture_transitions: Vec::new(), uses_shared_view_heap: false, write64_signals: Vec::new(), cpu_writes: Vec::new(), native_generations: Vec::new(), + waits: Vec::new(), sparse_writes: (Vec::new(), Vec::new()), texture_writes: Vec::new(), texture_transitions: Vec::new(), uses_shared_view_heap: false, write64_signals: Vec::new(), cpu_writes: Vec::new(), native_generations: Vec::new(), }), }; let KickoffEffects { waits, sparse_writes, texture_writes, texture_transitions, uses_shared_view_heap, write64_signals, cpu_writes, native_generations, } = effects; - if let Some(wrapper) = super::title_list::wrapper_of(this) { + let kickoff_wrapper = super::title_list::wrapper_of(this); + if let Some(wrapper) = kickoff_wrapper { record_deferred(wrapper); } + super::capture::kickoff(this, queue); let q_raw = queue_pin.as_raw(); - real::prepare_title_submission(q_raw); + real::prepare_title_submission(q_raw, &[this]); + super::gpu_profile::note_queue(q_raw); type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = transmute_copy(&real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); @@ -4687,13 +5301,19 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { ) { return (false, None); } + super::gpu_times::executed(q_raw, lists); submitted.extend_from_slice(lists); copy_scratch_submitted(q_raw, lists); - (true, chunk.submit_effects(q_raw)) + let completion = chunk.submit_effects(q_raw); + note_submitted(q_raw); + (true, completion) }) }); prior_cpu_completions = completions; + // (`XCL_DUMP_TARGETS`' 3D textures: what ran is in their states, the segments record anew) + super::lut3d::submitted(&submitted); for &p in &submitted { + super::lut3d::list_reset(p as usize); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(p as usize))) { s.texture_transitions.clear(); } @@ -4706,7 +5326,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let _ = completion.wait(); } } - wait_all_on(q_raw, &waits, &write64_signals); + if sparse_again_after_split(wait_all_on(q_raw, &waits, &write64_signals), split_sparse_after_cpu_waits_only()) { + mapped_after_wait(q_raw); + } } let one = [this]; @@ -4725,15 +5347,22 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if let Some(trace) = ¤t_trace { mark_trace(trace, ListEvent::Executed); } + super::gpu_times::executed(q_raw, &one); + super::lut3d::submitted(&one); + super::lut3d::list_reset(this as usize); copy_scratch_submitted(q_raw, &one); super::title_textures::publish_submission_effects(queue_identity(q_raw as usize), &texture_writes, &texture_transitions); + if let Some(w) = kickoff_wrapper { + super::title_textures::forget_list_closed(w as usize); + } signal_write64_pairs(q_raw, &write64_signals); - if !sparse_writes.is_empty() { + if !sparse_writes.0.is_empty() || !sparse_writes.1.is_empty() { if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&q_raw) { - super::sparse::readback_after_execute(q, &sparse_writes); + super::sparse::readback_after_execute(q, &sparse_writes.0, &sparse_writes.1); } } super::cpu_writes::after(q_raw, cpu_writes); + note_submitted(q_raw); } submitted }); @@ -4753,7 +5382,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { (Vec::new(), None, Bindings::default()) } }; - super::bind::inherit_for_split(this, primary, alloc); + // (`primary` records on the PC allocator the title's allocator stands for: its Reset below) + super::bind::inherit_for_split(this, primary, super::alloc_pool::current(alloc)); for seg in reclaimed { super::bind::reset(seg as *mut c_void, 0, 0); clear_segment_state(seg); @@ -4818,6 +5448,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { s.native_bias = DepthBias::ZERO; s.using_fallback_pso = false; s.pso_dirty = false; + // (other queues may run between what went and what follows) + s.depth_in_step.clear(); } if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { let info = if bound_pso != 0 { device_x::base_depth_bias_info(bound_pso) } else { None }; @@ -5009,10 +5641,52 @@ pub(super) unsafe fn prepare_draw(list: *mut c_void) { /// A GPU address the title gave: its memory's PC address when it is the title's memory, else /// as it is (a PC resource's GPU address – it may lie in a window's range by number). fn pc_va(va: u64) -> u64 { - if !crate::gpu::uma::get().is_some_and(|u| u.is_title_address(va as usize)) { - return va; + match crate::gpu::uma::get() { + Some(u) => pc_va_in(u, va, real::uma_window_va), + None => va, + } +} + +/// `pc_va` in `u`, whose windows have the PC addresses `window_va` (`real::uma_window_va`). A +/// GPU view of the title's memory without a PC address of its window gets none (0, read as +/// nothing): as it is, the console address is no PC address and hangs the device. +fn pc_va_in(u: &crate::gpu::uma::Uma, va: u64, window_va: impl Fn(usize) -> Option) -> u64 { + let p = va as usize; + let Some(k) = u.window_of(p).filter(|_| u.is_title_address(p)) else { return va }; + match window_va(k) { + Some(w) => w + (p - u.window(k).0) as u64, + None if u.is_view_window(k) => 0, + None => va, } - real::uma_va_of(va as usize).unwrap_or(va) +} + +/// The bytes of a view of `bytes` at the title's address `va` that the PC can bind as one range: +/// up to the end of the memory window `va` is in. The title's GPU view is one range, but its +/// windows are separate buffers on the PC (a GPU view spans six of 4 GiB): a view across a +/// window's end, bound as it is, runs past that window's buffer into addresses nothing maps. +/// The GPU reads zeros past the clamped size. (Logged once.) +fn view_bytes(va: u64, bytes: u32) -> u32 { + match crate::gpu::uma::get().and_then(|u| bytes_in_window(u, va, bytes)) { + Some(n) => { + static N: AtomicBool = AtomicBool::new(false); + if !N.swap(true, Ordering::Relaxed) { + crate::xlog_warn!("D3D12.X: a vertex or index buffer at {va:#x} ({bytes} bytes) runs past the end of its memory window: bound up to it ({n} bytes)"); + } + n + } + None => bytes, + } +} + +/// `view_bytes` in `u`: the clamped size when `[va, va + bytes)` starts in the title's memory +/// of a window and runs past that window's end (None: it does not). +fn bytes_in_window(u: &crate::gpu::uma::Uma, va: u64, bytes: u32) -> Option { + let p = va as usize; + let k = u.window_of(p)?; + let (base, size) = u.window(k); + let room = (base + size).checked_sub(p)?; + // (the title's memory is looked up only for a view across the end: a lock) + (bytes as usize > room && u.is_title_address(p)).then_some(room as u32) } /// `pc_va` for an index or vertex buffer of `bytes` bytes bound on `list`. A retail title also @@ -5028,12 +5702,15 @@ fn pc_va(va: u64) -> u64 { /// whole buffer at every bind filled unified memory within two minutes of a retail title's /// menus, and missed what the title wrote after the bind.) unsafe fn gpu_va(list: *mut c_void, va: u64, bytes: usize, what: &str, mirror: bool) -> u64 { + // in a GPU view: its window's PC address, over tiles asked for here + super::bind::want_view(super::view_want::Path::VertexIndex, va, bytes as u64); let t = pc_va(va); if t != va || va == 0 || bytes == 0 { return t; } - // in a window by number: a PC resource's GPU address - if crate::gpu::uma::get().is_none_or(|u| u.contains(va as usize)) { + // in a window by number: a PC resource's GPU address (never mirrored: a view window is no + // memory the CPU reads) + if crate::gpu::uma::get().is_none_or(|u| u.contains(va as usize) || u.is_view(va as usize)) { return t; } // a buffer bound before has its mirror: no `readable` (a `VirtualQuery` walk of the title's @@ -5334,8 +6011,15 @@ pub(super) unsafe fn ensure_view_heap(this: *mut c_void) -> bool { /// console #32 SetDescriptorHeaps (PC #28) pub(super) unsafe extern "system" fn set_descriptor_heaps_x(this: *mut c_void, n: u32, heaps: *const usize) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::BindState); const PC_SET_DESCRIPTOR_HEAPS: usize = 28; let f = pc::(this, PC_SET_DESCRIPTOR_HEAPS); + let _c = super::capture::op(this, || { + let given = if heaps.is_null() { &[][..] } else { std::slice::from_raw_parts(heaps, n as usize) }; + Some(super::capture::Op::Heaps(given.iter().map(|&h| super::console_heap::base(h).map_or((h, 0, false), |(s, b)| (h, b, s))).collect())) + }); + super::bind::heaps_changed(this); + super::bind::set_heaps(this, if heaps.is_null() { &[] } else { std::slice::from_raw_parts(heaps, n as usize) }); if heaps.is_null() || n == 0 { // no heaps: nothing bound any more (`ensure_view_heap` binds the shared heaps again // before a translated draw or dispatch reads memory windows or samplers from them) @@ -5376,6 +6060,7 @@ const PC_IA_SET_VERTEX_BUFFERS: usize = 44; /// command list #48 IASetVertexBuffers(start slot, count, views) (PC #44): the addresses are /// the title's (its memory: the GPU address of that memory for the PC) pub(super) unsafe extern "system" fn ia_set_vertex_buffers_x(this: *mut c_void, start: u32, n: u32, views: *const D3D12_VERTEX_BUFFER_VIEW) { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::BindState); let f = pc::(this, PC_IA_SET_VERTEX_BUFFERS); if views.is_null() || n == 0 { return f(this, start, n, views); @@ -5384,6 +6069,7 @@ pub(super) unsafe extern "system" fn ia_set_vertex_buffers_x(this: *mut c_void, .map(|k| { let mut v = views.add(k).read_unaligned(); let title = v.BufferLocation; + v.SizeInBytes = view_bytes(title, v.SizeInBytes); v.BufferLocation = gpu_va(this, v.BufferLocation, v.SizeInBytes as usize, "vertex buffer", true); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); @@ -5421,6 +6107,7 @@ pub(super) unsafe extern "system" fn ia_set_vertex_buffers_x(this: *mut c_void, /// command list #47 IASetIndexBuffer(view) (PC #43): the address is the title's pub(super) unsafe extern "system" fn ia_set_index_buffer_x(this: *mut c_void, view: *const D3D12_INDEX_BUFFER_VIEW) { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::BindState); let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); if view.is_null() { @@ -5431,6 +6118,7 @@ pub(super) unsafe extern "system" fn ia_set_index_buffer_x(this: *mut c_void, vi let mut v = view.read_unaligned(); s.bindings.index_title = Some((v.BufferLocation, v.SizeInBytes, v.Format.0)); drop(g); + v.SizeInBytes = view_bytes(v.BufferLocation, v.SizeInBytes); v.BufferLocation = gpu_va(this, v.BufferLocation, v.SizeInBytes as usize, "index buffer", true); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { s.index_buffer = Some(v); @@ -5441,6 +6129,8 @@ pub(super) unsafe extern "system" fn ia_set_index_buffer_x(this: *mut c_void, vi /// command list #81 DrawIndexedX(index address, index format, index count, flags): one /// instance of `count` indices read from that address; the bound index buffer stays pub(super) unsafe extern "system" fn draw_indexed_x(this: *mut c_void, va: u64, format: DXGI_FORMAT, count: u32, _flags: u32) { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::DrawRecord); + let _c = super::bind::capture_work(this, || super::capture::WorkKind::DrawIndexedX { va, format: format.0, indices: count }, true); static N: AtomicU64 = AtomicU64::new(0); let stride = match format { DXGI_FORMAT_R16_UINT => 2, @@ -5455,7 +6145,9 @@ pub(super) unsafe extern "system" fn draw_indexed_x(this: *mut c_void, va: u64, }; let bound = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).and_then(|s| s.index_buffer)); sync_title_buffers(this, None, 0, 0, 2); - let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: gpu_va(this, va, count.saturating_mul(stride) as usize, "DrawIndexedX indices", false), SizeInBytes: count.saturating_mul(stride), Format: format }; + // (indices past the clamped size read as 0) + let bytes = view_bytes(va, count.saturating_mul(stride)); + let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: gpu_va(this, va, bytes as usize, "DrawIndexedX indices", false), SizeInBytes: bytes, Format: format }; set_index_buffer(this, Some(&view)); super::bind::emit_prepared_indexed_draw(&list, count, 1, 0, 0, 0); set_index_buffer(this, bound.as_ref()); @@ -5489,7 +6181,11 @@ pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usiz if let Some(w) = super::title_list::wrapper_of(this) { return super::title_list::reset(w, alloc, pso); } - reset_pc(this, alloc, pso) + let hr = reset_pc(this, alloc, pso); + if hr >= 0 { + super::capture::list_begin(this as usize, pso); + } + hr } /// Reset of the PC list `this` (allocator, initial pipeline): updates allocator/pipeline and @@ -5498,6 +6194,11 @@ pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usiz /// # Safety /// `this` must be a valid adopted `ID3D12GraphicsCommandList` pointer. pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i32 { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListLifecycle); + reset_pc_inner(this, alloc, pso) +} + +unsafe fn reset_pc_inner(this: *mut c_void, alloc: usize, pso: usize) -> i32 { // A failed native Reset leaves the old recording alive. Do not discard its tracked state or // transfer its allocations until the driver accepts the new recording. let ext = *(this as *const usize); @@ -5505,7 +6206,9 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 let resolved = prepared.raw(); // (the PC allocator the title's allocator stands for now: `alloc_pool`) let ty = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).and_then(|s| s.list_type).map_or(-1, |t| t.0); + let mut on = alloc; let hr = super::alloc_pool::reset_list(this as usize, alloc, ty, |pc_alloc| { + on = pc_alloc; pc:: i32>(this, PC_RESET)(this, pc_alloc, resolved) }); real::preserve_vtable(this, ext); @@ -5542,10 +6245,13 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 s.predication = None; s.pred_in_state = false; s.bindings = Bindings::default(); + s.depth_in_step.clear(); (s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE), old_generations) }; drop(old_generations); - prepared.commit(this, alloc); + // (what the new recording puts in unified memory belongs to the PC allocator it is on) + prepared.commit(this, on); + super::lut3d::list_reset(this as usize); super::dred::reset(this); if pso != 0 && resolved != 0 { super::dred::mark_pipeline(this, pso, resolved); @@ -5570,10 +6276,12 @@ const PC_STATES: u32 = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x80 | 0x100 /// transition left with nothing to do goes, aliasing barriers name placed textures pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u32, barriers: *const [u32; 8]) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBarrier); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListBarrier); static N: AtomicU64 = AtomicU64::new(0); if barriers.is_null() || n == 0 { return; } + let capture = super::capture::op(this, || Some(super::capture::barrier(&(0..n as usize).map(|k| barriers.add(k).read_unaligned()).collect::>()))); let mut out: Vec<[u32; 8]> = Vec::with_capacity(n as usize + 1); // a UAV barrier for all resources is in `out` / a transition from or to UNORDERED_ACCESS let (mut any_uav, mut uav_transition) = (false, false); @@ -5589,12 +6297,21 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } } } - if ty > 2 || flags > 3 { + if ty > 2 { if N.fetch_add(1, Ordering::Relaxed) < 16 { crate::xlog_warn!("D3D12.X: ResourceBarrier: console barrier type {ty} flags {flags:#x} dropped ({:x?})", b); } continue; } + // Console cache hints must not discard the transition or memory ordering itself. + // Keep the PC split-barrier bits and let the PC perform its normal synchronization. + const PC_FLAGS: u32 = (D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY.0 | D3D12_RESOURCE_BARRIER_FLAG_END_ONLY.0) as u32; + if flags & !PC_FLAGS != 0 { + if N.fetch_add(1, Ordering::Relaxed) < 16 { + crate::xlog_warn!("D3D12.X: ResourceBarrier: console flag bits {:#x} dropped", flags & !PC_FLAGS); + } + b[1] &= PC_FLAGS; + } if ty == 1 { // Keep the identity of textures that really share placed GPU memory. // Committed resources still need the wildcard form on the PC. @@ -5642,15 +6359,72 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 if uav_transition && !any_uav { out.push([2, 0, 0, 0, 0, 0, 0, 0]); } + // depth buffers whose depth plane can have a twin: in PARK where the title has them in + // UNORDERED_ACCESS, the twin copied around the transitions (`depth_uav`) + let plane_copies = super::depth_uav::any_kept().then(|| { + let direct = list_type(this) == D3D12_COMMAND_LIST_TYPE_DIRECT; + let mut in_step = std::mem::take(&mut LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(this as usize).or_default().depth_in_step); + let plan = super::depth_uav::plan_barriers(&mut out, direct, &mut in_step); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { + s.depth_in_step = in_step; + } + plan + }); // the states uploads into textures kept in step start from once this list has run - if super::title_textures::any() { + if super::title_textures::any() || super::lut3d::on() { let t: Vec<(usize, u32, D3D12_RESOURCE_STATES)> = out.iter().filter(|b| b[0] == 0).map(|b| ((b[2] as u64 | (b[3] as u64) << 32) as usize, b[4], D3D12_RESOURCE_STATES(b[6] as i32))).collect(); note_texture_transitions(this as usize, &t); + super::lut3d::note_transitions(this as usize, &t); + } + // (a superseded target the title moves is used again: `placements`) + for b in out.iter().filter(|b| b[0] == 0) { + super::placements::note_use((b[2] as u64 | (b[3] as u64) << 32) as usize); + } + capture.amend(|op| { + if let super::capture::Op::Barrier { sent, plane_copies: copies, .. } = op { + sent.clone_from(&out); + *copies = plane_copies.as_ref().map_or(0, |p| p.to_plane.len() + p.to_twin.len()); + } + }); + if let Some(p) = &plane_copies { + plane_copies_on(this, &p.to_plane, false); } if !out.is_empty() { pc::(this, PC_RESOURCE_BARRIER)(this, out.len() as u32, out.as_ptr()); } + if let Some(p) = &plane_copies { + plane_copies_on(this, &p.to_twin, true); + } +} + +/// The copies between depth planes and their twins around a title's barriers +/// (`depth_uav::plan_barriers`) on `list`: into the twins (`to_twin`, after the barriers: the +/// buffer rests in `depth_uav::PARK`, COPY_SOURCE) or into the planes (before them: the buffer +/// goes PARK → COPY_DEST, where the title's transition out of UNORDERED_ACCESS takes it on). The +/// twin rests in UNORDERED_ACCESS. Whole subresources, of one format family on both sides (a +/// D3D12 copy of a depth plane takes the whole of it). +unsafe fn plane_copies_on(list: *mut c_void, copies: &[super::depth_uav::PlaneCopy], to_twin: bool) { + let barriers = |b: &[[u32; 8]]| pc::(list, PC_RESOURCE_BARRIER)(list, b.len() as u32, b.as_ptr()); + let tr = |res: usize, sub: u32, before: u32, after: u32| [0, 0, res as u32, (res as u64 >> 32) as u32, sub, before, after, 0]; + let all = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + let at = |res: usize, k: u32| D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&res), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k } }; + let copy = pc::(list, PC_COPY_TEXTURE_REGION); + let (copy_src, copy_dst) = (D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32); + for c in copies { + let twin = c.twin.as_raw() as usize; + let twin_in = if to_twin { copy_dst } else { copy_src }; + if to_twin { + barriers(&[tr(twin, all, UNORDERED_ACCESS, twin_in)]); + } else { + barriers(&[tr(twin, all, UNORDERED_ACCESS, twin_in), tr(c.depth, c.sub, super::depth_uav::PARK, copy_dst)]); + } + for &k in &c.subs { + let (dst, src) = if to_twin { (at(twin, k), at(c.depth, k)) } else { (at(c.depth, k), at(twin, k)) }; + copy(list, &dst, 0, 0, 0, &src, std::ptr::null()); + } + barriers(&[tr(twin, all, twin_in, UNORDERED_ACCESS)]); + } } /// D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER | INDEX_BUFFER: valid for buffers only @@ -5668,9 +6442,18 @@ unsafe fn is_buffer(res: usize) -> bool { /// DMA list #9 Close: as on the PC; a failure is logged (the title stops on it) pub(super) unsafe extern "system" fn dma_close_x(this: *mut c_void) -> i32 { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailListLifecycle); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListLifecycle); let ext = *(this as *const usize); let hr = pc:: i32>(this, 9)(this); real::preserve_vtable(this, ext); + if hr >= 0 + && !super::title_textures::is_own_work() + && !super::present::presenting() + && super::title_list::wrapper_of(this).is_none() + && !super::console_list::is_backing(this) + { + super::title_textures::note_list_closed(this as usize); + } if hr < 0 { let ty = pc:: i32>(this, PC_GET_TYPE)(this); crate::xlog_warn!("D3D12.X: DMA list Close → {:#x} (PC list type {ty})", hr as u32); @@ -5707,6 +6490,11 @@ fn note_gpu_write(what: &str, va: usize, n: u64) { pub(super) unsafe extern "system" fn copy_buffer_region_x(this: *mut c_void, dst: usize, dst_off: u64, src: usize, src_off: u64, n: u64) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListCopy); + let _c = super::capture::op(this, || { + use super::capture as c; + Some(c::Op::Copy { kind: "buffer_region", dst: c::buffer(dst, dst_off), src: c::buffer(src, src_off), at: [0; 3], bx: None, bytes: Some(n), refused: false }) + }); copy_buffer_region_inner(this, dst, dst_off, src, src_off, n) } @@ -5716,6 +6504,7 @@ unsafe fn copy_buffer_region_inner(this: *mut c_void, dst: usize, dst_off: u64, note_gpu_write("CopyBufferRegion", a + dst_off as usize, n); } } + note_copy_into(this as usize, dst, dst_off, n); pc::(this, PC_COPY_BUFFER_REGION)(this, dst, dst_off + real::buffer_delta(dst), src, src_off + real::buffer_delta(src), n) } @@ -5746,6 +6535,12 @@ unsafe fn trace_watched_copy(what: &str, dst: usize, src: usize) { /// CopyTextureRegion(dst, x, y, z, src, box) (PC #16; DMA list #12) pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, dst: *const D3D12_TEXTURE_COPY_LOCATION, x: u32, y: u32, z: u32, src: *const D3D12_TEXTURE_COPY_LOCATION, bx: *const D3D12_BOX) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListCopy); + let _c = super::capture::op(this, || { + use super::capture as c; + let b = bx.as_ref().map(|b| [b.left, b.top, b.front, b.right, b.bottom, b.back]); + Some(c::Op::Copy { kind: "texture_region", dst: c::location(dst), src: c::location(src), at: [x, y, z], bx: b, bytes: None, refused: dst.is_null() || src.is_null() }) + }); if let Some(d) = dst.as_ref() { let r: usize = transmute_copy(&d.pResource); super::present::note_use(r, super::present::USE_COPY); @@ -5755,6 +6550,23 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES }; note_texture_write(this as usize, r, sub); + super::placements::note_use(r); + if let Some(s) = src.as_ref() { + super::placements::note_use(transmute_copy(&s.pResource)); + } + super::lut3d::wrote(r, true, || { + let from = src.as_ref().map_or("nothing".to_string(), |sl| { + let sr: usize = transmute_copy(&sl.pResource); + if sl.Type == D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT { + let f = sl.Anonymous.PlacedFootprint; + format!("buffer {sr:#x} (title address {:?}) at {:#x}, footprint format {} {}x{}x{} row pitch {}", real::title_address(sr).map(|a| format!("{a:#x}")), f.Offset, f.Footprint.Format.0, f.Footprint.Width, f.Footprint.Height, f.Footprint.Depth, f.Footprint.RowPitch) + } else { + format!("subresource {} of {sr:#x}", sl.Anonymous.SubresourceIndex) + } + }); + let b = bx.as_ref().map(|b| (b.left, b.top, b.front, b.right, b.bottom, b.back)); + format!("CopyTextureRegion into subresource {} at ({x}, {y}, {z}) from {from}, box {b:?}", d.Anonymous.SubresourceIndex) + }); if super::present::trace_frame() { if let Some(va) = super::title_textures::address(r) { static N: AtomicU64 = AtomicU64::new(0); @@ -5821,6 +6633,12 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds } } } + if let Some(l) = dst.as_ref().filter(|l| l.Type == D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT) { + // (the rows of the footprint: at most what the copy writes) + let f = &l.Anonymous.PlacedFootprint; + let n = f.Footprint.RowPitch as u64 * f.Footprint.Height.max(1) as u64 * f.Footprint.Depth.max(1) as u64; + note_copy_into(this as usize, transmute_copy::<_, usize>(&l.pResource), f.Offset, n); + } let (Some(d), Some(s)) = (pc_location(dst), pc_location(src)) else { return }; pc::(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); std::mem::forget((d, s)); // borrowed resource pointers @@ -5836,6 +6654,8 @@ const PC_CLEAR_DEPTH_STENCIL_VIEW: usize = 47; /// command list #51 ClearDepthStencilView(dsv, flags, depth, stencil, rects, rect list) (PC #47) pub(super) unsafe extern "system" fn clear_depth_stencil_x(this: *mut c_void, dsv: usize, flags: u32, depth: f32, stencil: u8, n: u32, rects: *const windows::Win32::Foundation::RECT) { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListCopy); + let _c = super::capture::op(this, || Some(super::capture::clear("dsv", dsv as u64, None, [depth.to_bits(), stencil as u32, 0, 0], flags, n))); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); static W: AtomicU64 = AtomicU64::new(0); @@ -5874,12 +6694,35 @@ fn uav_clear_handles(gpu: Option, cpu: Option) -> Option { + if !super::depth_uav::any() { + return Some(res); + } + let named = gpu.filter(|s| s.shared_srv != 0).map(|s| super::console_heap::names_of(&s).1); + match super::depth_uav::clear_target(res, named) { + super::depth_uav::Clear::AsIs => Some(res), + super::depth_uav::Clear::Twin(t) => Some(t), + super::depth_uav::Clear::NotDone => None, + } +} + /// command list #53 / #54 ClearUnorderedAccessViewUint / Float(GPU handle, CPU handle, /// resource, values[4], rects, rect list) (PC #49 / #50): console handles are addresses of -/// console heap slots (heap #9 / #10), not PC descriptors +/// console heap slots (heap #9 / #10), not PC descriptors. A depth buffer whose UAV views are +/// views of its twin (`depth_uav`) is cleared through the twin the GPU slot's view names. unsafe fn clear_uav(this: *mut c_void, slot: usize, gpu: u64, cpu: u64, res: usize, values: *const c_void, n: u32, rects: *const windows::Win32::Foundation::RECT) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); - let (gpu, cpu) = match uav_clear_handles(super::console_heap::slot(gpu), super::console_heap::slot(cpu)) { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListCopy); + let capture = super::capture::op(this, || { + let v = values.cast::<[u32; 4]>().as_ref().copied().unwrap_or_default(); + Some(super::capture::clear(if slot == PC_CLEAR_UAV_UINT { "uav_uint" } else { "uav_float" }, gpu, Some(res), v, 0, n)) + }); + let refused = || capture.amend(|op| if let super::capture::Op::Clear { refused, .. } = op { *refused = true }); + let gpu_slot = super::console_heap::slot(gpu); + let (gpu, cpu) = match uav_clear_handles(gpu_slot, super::console_heap::slot(cpu)) { UavClearHandles::Console { gpu, cpu } => (gpu, cpu), UavClearHandles::Pc => (gpu, cpu), UavClearHandles::Unusable => { @@ -5887,9 +6730,10 @@ unsafe fn clear_uav(this: *mut c_void, slot: usize, gpu: u64, cpu: u64, res: usi if once(&N, 1) { crate::xlog_warn!("D3D12.X: ClearUnorderedAccessView with GPU handle {gpu:#x} / CPU handle {cpu:#x}: not both a console slot with a shader-visible UAV – not done"); } - return; + return refused(); } }; + let Some(res) = uav_clear_resource(res, gpu_slot) else { return refused() }; pc::(this, slot)(this, gpu, cpu, res, values, n, rects) } @@ -5932,7 +6776,13 @@ unsafe fn trace_resolve(what: &str, dst: usize, src: usize, format: i32, extra: /// command list #19 ResolveSubresource(dst, dst sub, src, src sub, format) (PC #19) pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, dst: usize, dst_sub: u32, src: usize, src_sub: u32, format: i32) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListCopy); + let _c = super::capture::op(this, || { + use super::capture as c; + Some(c::Op::Resolve { dst: c::describe(dst), dst_sub, src: c::describe(src), src_sub, format, region: None }) + }); super::present::note_use(dst, super::present::USE_COPY); + note_texture_write(this as usize, dst, dst_sub); trace_resolve("ResolveSubresource", dst, src, format, ""); pc::(this, PC_RESOLVE_SUBRESOURCE)(this, dst, dst_sub, src, src_sub, format) } @@ -5942,7 +6792,14 @@ pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, ds #[allow(clippy::too_many_arguments)] pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_void, dst: usize, dst_sub: u32, x: u32, y: u32, src: usize, src_sub: u32, rect: *const windows::Win32::Foundation::RECT, format: i32, mode: i32) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListCopy); + let _c = super::capture::op(this, || { + use super::capture as c; + let r = rect.as_ref().map(|r| [r.left, r.top, r.right, r.bottom]); + Some(c::Op::Resolve { dst: c::describe(dst), dst_sub, src: c::describe(src), src_sub, format, region: Some((x, y, r, mode)) }) + }); super::present::note_use(dst, super::present::USE_COPY); + note_texture_write(this as usize, dst, dst_sub); if super::present::trace_frame() { trace_resolve("ResolveSubresourceRegion", dst, src, format, &format!(" mode {mode} at ({x}, {y}) rect {:?}", rect.as_ref().map(|r| (r.left, r.top, r.right, r.bottom)))); } @@ -5953,13 +6810,22 @@ pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_v /// are copied as their own bytes (the PC resources also hold what lies before them) pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usize, src: usize) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListCopy); + let _c = super::capture::op(this, || { + use super::capture as c; + Some(c::Op::Copy { kind: "resource", dst: c::buffer(dst, 0), src: c::buffer(src, 0), at: [0; 3], bx: None, bytes: None, refused: false }) + }); super::present::note_use(dst, super::present::USE_COPY); note_texture_write(this as usize, dst, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES); + super::placements::note_use(dst); + super::placements::note_use(src); + super::lut3d::wrote(dst, true, || format!("CopyResource from {src:#x}")); if super::present::trace_frame() { trace_watched_copy("CopyResource", dst, src); } let (dd, sd) = (real::buffer_delta(dst), real::buffer_delta(src)); if dd == 0 && sd == 0 { + note_copy_into(this as usize, dst, 0, u64::MAX); return pc::(this, PC_COPY_RESOURCE)(this, dst, src); } let n = real::console_buffer(dst).or(real::console_buffer(src)).map_or(0, |b| b.1 as u64); @@ -5970,8 +6836,7 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi pub(super) unsafe extern "system" fn begin_query_x(this: *mut c_void, heap: usize, ty: D3D12_QUERY_TYPE, index: u32) { static N: AtomicU64 = AtomicU64::new(0); if is_occlusion(ty) { - let outer = LISTS - .lock() + let outer = LISTS.lock() .unwrap() .get_or_insert_with(HashMap::new) .entry(this as usize) @@ -5994,8 +6859,7 @@ pub(super) unsafe extern "system" fn begin_query_x(this: *mut c_void, heap: usiz /// command list #29 EndQuery(heap, type, index) (PC #53) pub(super) unsafe extern "system" fn end_query_x(this: *mut c_void, heap: usize, ty: D3D12_QUERY_TYPE, index: u32) { if is_occlusion(ty) { - let (forward, force_visible) = LISTS - .lock() + let (forward, force_visible) = LISTS.lock() .unwrap() .get_or_insert_with(HashMap::new) .entry(this as usize) @@ -6018,6 +6882,8 @@ pub(super) unsafe extern "system" fn end_query_x(this: *mut c_void, heap: usize, /// over the resolved data (after it, in COPY_DEST as ResolveQueryData wants the destination). /// Buffers placed below their console address add `buffer_delta(dest)` to the destination offset. pub(super) unsafe extern "system" fn resolve_query_data_x(this: *mut c_void, heap: usize, ty: D3D12_QUERY_TYPE, first: u32, count: u32, dest: usize, offset: u64) { + // (8 bytes a query; pipeline statistics, the largest, are 11 values) + note_copy_into(this as usize, dest, offset, count as u64 * if ty == D3D12_QUERY_TYPE_PIPELINE_STATISTICS { 88 } else { 8 }); let pc_offset = offset.saturating_add(real::buffer_delta(dest)); type F = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32, u32, usize, u64); pc::(this, PC_RESOLVE_QUERY_DATA)(this, heap, ty, first, count, dest, pc_offset); @@ -6263,6 +7129,36 @@ mod tests { assert_eq!(mirror_in(&cache.1, 550, 1), None, "ranges are half-open"); } + /// A wait that times out with no proven producer stops the title unless + /// `XCL_WAIT_TIMEOUT_CONTINUE` is exactly 1. + #[test] + fn an_unresolved_wait_stops_the_title_unless_told_to_continue() { + assert!(!wait_timeout_continues_from(None), "default: the title stops"); + assert!(!wait_timeout_continues_from(Some("0"))); + assert!(!wait_timeout_continues_from(Some("yes"))); + assert!(wait_timeout_continues_from(Some("1"))); + assert!(wait_timeout_continues_from(Some(" 1 "))); + } + + /// `XCL_WAIT_TIMEOUT_CONTINUE=1`: a GPU wait the watchdog releases counts as signalled on the + /// CPU at its value; GPU signals at or below it no longer stand, later ones do. + #[test] + fn a_wait_released_on_the_cpu_marks_its_cell_signalled_there() { + let mut cell = SyncCell { + cpu_signaled_max: 3, + submitted_signals: vec![ + SubmittedSignal { val: 5, queue: 0xA, seq: 1 }, + SubmittedSignal { val: 9, queue: 0xA, seq: 2 }, + ], + ..Default::default() + }; + assert!(release_expired_on_cpu(&mut cell, 7).is_none(), "no fence: nothing to signal"); + assert_eq!(cell.cpu_signaled_max, 7); + assert_eq!(cell.submitted_signals.iter().map(|s| s.val).collect::>(), vec![9]); + release_expired_on_cpu(&mut cell, 2); + assert_eq!(cell.cpu_signaled_max, 7, "a lower release does not take it back"); + } + /// A recorded `Wait64` cell whose page the title decommitted, or made inaccessible, is listed /// as unreadable by the sync-state dump, which does not fault on it. #[test] @@ -6386,6 +7282,174 @@ mod tests { on_release(list); } + // Exercise the console entry point through a fake PC list, without a device or title data. + fn captured_resource_barriers(input: &[[u32; 8]]) -> Vec<[u32; 8]> { + #[repr(C)] + struct FakeList { + vt: *const usize, + sent: Mutex>, + } + unsafe extern "system" fn get_type(_: *mut c_void) -> D3D12_COMMAND_LIST_TYPE { + D3D12_COMMAND_LIST_TYPE_DIRECT + } + unsafe extern "system" fn barrier(this: *mut c_void, n: u32, b: *const [u32; 8]) { + let list = &*(this as *const FakeList); + list.sent.lock().unwrap().extend_from_slice(std::slice::from_raw_parts(b, n as usize)); + } + let mut orig_vt = [0usize; 64]; + orig_vt[PC_GET_TYPE] = get_type as usize; + orig_vt[PC_RESOURCE_BARRIER] = barrier as usize; + let mut ext_vt = [0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + // The CPU fixtures use a stable word value as their resource identity. Give it a + // real object-shaped backing while the hook runs, including an active capture's GetDesc. + unsafe extern "system" fn get_desc(_: *mut c_void, out: *mut D3D12_RESOURCE_DESC) -> *mut D3D12_RESOURCE_DESC { + out.write(D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: 64, Height: 1, DepthOrArraySize: 1, + MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }); + out + } + let mut resource_vt = [0usize; 16]; + resource_vt[10] = get_desc as usize; + let resource = resource_vt.as_ptr(); + let resource_words = [(&resource as *const _ as usize) as u32, ((&resource as *const _ as usize) as u64 >> 32) as u32]; + let replace_resource = |barriers: &mut [[u32; 8]], from: [u32; 2], to: [u32; 2]| { + for b in barriers { + let end = match b[0] { 0 | 2 => 4, 1 => 6, _ => 2 }; + for words in b[2..end].chunks_exact_mut(2) { + if words == from { words.copy_from_slice(&to); } + } + } + }; + let mut input = input.to_vec(); + replace_resource(&mut input, [0x1234, 0], resource_words); + let mut list = FakeList { vt: unsafe { ext_vt.as_ptr().add(1) }, sent: Mutex::new(Vec::new()) }; + unsafe { resource_barrier_x(&mut list as *mut FakeList as *mut c_void, input.len() as u32, input.as_ptr()) }; + let mut sent = list.sent.into_inner().unwrap(); + replace_resource(&mut sent, resource_words, [0x1234, 0]); + sent + } + + #[test] + fn resource_barrier_console_flags_keep_transition_and_split_bits() { + for extra in [0, 4, 0x0001_0000, 0x8000_0000, 0x8000_0004] { + for split in [0, 1, 2] { + // COPY_DEST -> COPY_SOURCE does not need a resource description lookup. + let input = [0, extra | split, 0x1234, 0, 7, 0x400, 0x800, 0]; + let mut expected = input; + expected[1] = split; + assert_eq!(captured_resource_barriers(&[input]), vec![expected], "extra={extra:#x}, split={split}"); + } + } + } + + #[test] + fn resource_barrier_console_flags_keep_uav_ordering_and_aliasing() { + let transition = [0, 4, 0x1234, 0, u32::MAX, 8, 0x400, 0]; + let mut expected = transition; + expected[1] = 0; + let uav = [2, 0, 0, 0, 0, 0, 0, 0]; + assert_eq!(captured_resource_barriers(&[transition]), vec![expected, uav]); + // Explicit UAV barriers still cover all aliases, and duplicate UAV barriers collapse. + assert_eq!(captured_resource_barriers(&[[2, 4, 0x1234, 0, 0, 0, 0, 0], uav]), vec![uav]); + assert_eq!(captured_resource_barriers(&[[1, 4, 0, 0, 0, 0, 0, 0]]), vec![[1, 0, 0, 0, 0, 0, 0, 0]]); + } + + #[test] + fn resource_barrier_console_flags_leave_existing_filters_in_place() { + assert!(captured_resource_barriers(&[]).is_empty()); + assert!(captured_resource_barriers(&[[3, 4, 0, 0, 0, 0, 0, 0]]).is_empty()); + // Removing console-only state bits can still leave a transition with no work to do. + assert!(captured_resource_barriers(&[[0, 4, 0x1234, 0, 0, 0x8000_0400, 0x400, 0]]).is_empty()); + let input = [0, 4, 0x1234, 0, 0, 0x8000_0400, 0x800, 0]; + assert_eq!(captured_resource_barriers(&[input]), vec![[0, 0, 0x1234, 0, 0, 0x400, 0x800, 0]]); + } + + #[test] + fn gpu_resource_barrier_console_hint_preserves_texture_copy() { + use crate::gpu::{fence, recomp::runner}; + + let dev = match runner::device() { + Ok(dev) => dev, + Err(e) => { + eprintln!("barrier test device unavailable: {e}"); + runner::skip_test("no GPU"); + return; + } + }; + println!("barrier texture-copy adapter: {}", runner::adapter().unwrap_or_default()); + unsafe { + // One ordinary transition, the console hint, and the hint on a split pair. + // No command uses the texture between the two halves of the split transition. + for flags in [&[0u32][..], &[0x0001_0000][..], &[0x0001_0001, 0x0001_0002][..]] { + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 4, Height: 4, DepthOrArraySize: 1, MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, ..Default::default() + }; + let mut texture: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_RENDER_TARGET, None, &mut texture).unwrap(); + let texture = texture.unwrap(); + let rtv: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() }).unwrap(); + let handle = rtv.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(&texture, None, handle); + list.ClearRenderTargetView(handle, &[0.0, 1.0, 0.0, 1.0], None); + + let raw = texture.as_raw() as usize as u64; + let input: Vec<[u32; 8]> = flags.iter().map(|&f| [0, f, raw as u32, (raw >> 32) as u32, u32::MAX, 4, 0x800, 0]).collect(); + let mut expected = input.clone(); + for b in &mut expected { b[1] &= 3; } + let translated = captured_resource_barriers(&input); + // Fail the original-runtime control before submitting a missing transition. + assert_eq!(translated, expected, "console hint must retain the complete native transition: {flags:x?}"); + let native: Vec = translated.iter().map(|b| std::mem::transmute_copy(b)).collect(); + list.ResourceBarrier(&native); + + let readback_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: 4 * 256, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() + }; + let mut readback: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &readback_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback).unwrap(); + let readback = readback.unwrap(); + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: desc.Format, Width: 4, Height: 4, Depth: 1, RowPitch: 256 } + } }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: transmute_copy(&texture), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let complete = queue.Signal(&done, 1).map_err(|e| format!("Signal: {e}")) + .and_then(|_| fence::wait(&done, 1, &dev, None, 2000).map_err(|e| e.to_string())); + if let Err(e) = complete { + // A timed-out copy may still own these objects. Retain this tiny batch until + // the test process exits rather than releasing memory the GPU could use. + std::mem::forget((queue, alloc, list, done, texture, rtv, readback)); + panic!("bounded barrier texture copy did not complete: {e}"); + } + let mut ptr = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut ptr)).unwrap(); + let pixels: Vec<[u8; 4]> = (0..4).flat_map(|y| (0..4).map(move |x| (ptr as *const u8).add(y * 256 + x * 4).cast::<[u8; 4]>().read_unaligned())).collect(); + readback.Unmap(0, None); + assert_eq!(pixels, vec![[0, 255, 0, 255]; 16], "texture copy after flags {flags:x?}"); + } + } + } + use std::sync::Arc; + /// An internal wait shows in the watchdog's summary while its fence is short of the value, /// and is gone from it once the fence gets there. #[test] @@ -6609,6 +7673,49 @@ mod tests { assert_eq!(successful_backing, Some(0x333), "only successful Reset moves the recording to its new allocator"); } + unsafe extern "system" fn reset_ok_native(_this: *mut c_void, _alloc: usize, _pso: usize) -> i32 { + 0 + } + + /// A list reset on a title allocator that stands for another PC allocator (`alloc_pool`) + /// records on that one, and what the recording puts in unified memory is held for it after + /// the next Reset – not for the title's allocator, whose own submits the GPU may have passed + /// while this one's still run (#1358). + #[test] + fn a_recordings_memory_is_held_for_the_pc_allocator_it_is_on() { + let mut native = vec![0usize; PC_RESET + 1]; + native[PC_RESET] = reset_ok_native as usize; + let extended = [native.as_ptr() as usize, 0usize]; + let ext = unsafe { extended.as_ptr().add(1) as usize }; + let mut object = [ext]; + let list = object.as_mut_ptr() as *mut c_void; + let key = list as usize; + let ids = Box::new([0u8; 4]); + let title = ids.as_ptr() as usize; + let (pc, other, block) = (title + 1, title + 2, title + 3); + super::super::alloc_pool::stand_in_for_test(title, pc); + unsafe { on_create(list, title, 0, D3D12_COMMAND_LIST_TYPE_DIRECT) }; + + assert_eq!(unsafe { reset_x(list, title, 0) }, 0); + let recording_on = super::super::bind::reset_state_for_test(list).0; + super::super::bind::seed_reset_state_for_test(list, recording_on, 0, vec![block]); + assert_eq!(unsafe { reset_x(list, other, 0) }, 0); + let held_for_pc = super::super::console_list::take_pending_for_test(pc); + let held_for_title = super::super::console_list::take_pending_for_test(title); + + LISTS.lock().unwrap().as_mut().unwrap().remove(&key); + super::super::bind::remove_state_for_test(list); + super::super::alloc_pool::stand_in_for_test(title, title); + unsafe { + super::super::alloc_pool::forget(title); + super::super::alloc_pool::forget(pc); + super::super::alloc_pool::forget(other); + } + assert_eq!(recording_on, pc, "the recording is on the PC allocator the title's allocator stands for"); + assert_eq!(held_for_pc, vec![block]); + assert!(held_for_title.is_empty()); + } + #[test] fn fill_patterns_repeat_the_value() { assert_eq!(pattern(&0x1122_3344u32.to_le_bytes())[..8], [0x44, 0x33, 0x22, 0x11, 0x44, 0x33, 0x22, 0x11]); @@ -6773,6 +7880,35 @@ mod tests { }); } + /// `wait_all_on` says whether it waited on the CPU: not for waits that held already, yes for + /// one it had to wait for there (no queue: no GPU wait); the split's sparse update follows it + /// only with `XCL_SPLIT_SPARSE=cpu`. + #[test] + fn a_split_brings_the_sparse_windows_up_to_date_after_a_cpu_wait() { + let cell = Arc::new(AtomicU64::new(7)); + let w = |value: u64| PendingWait { + va: Arc::as_ptr(&cell) as u64, + width: 8, + comparison: D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, + value, + mask: u64::MAX, + after_write64: false, + }; + unsafe { + assert!(!wait_all_on(std::ptr::null_mut(), &[w(5), w(7)], &[]), "held already: no CPU wait"); + let writer = cell.clone(); + let t = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(5)); + writer.store(9, Ordering::Release); + }); + assert!(wait_all_on(std::ptr::null_mut(), &[w(5), w(9)], &[]), "waited on the CPU"); + t.join().unwrap(); + } + assert!(sparse_again_after_split(true, true)); + assert!(!sparse_again_after_split(false, true)); + assert!(sparse_again_after_split(false, false) && sparse_again_after_split(true, false), "as before without the switch"); + } + #[test] fn wait64_flags_do_not_mask_the_recorded_counter() { let mut token = 0usize; @@ -8090,6 +9226,8 @@ mod tests { // 1. Untranslated (PC) PSO: routes through bind::draw_indexed_instanced -> DrawIndexedInstanced, // records DRAW_ARGS, binds temp IB, then restores orig_ib. super::super::bind::reset(list_ptr, 0x7400_0100, 0); + // (a draw with a PC pipeline needs the title's root signature on the list) + super::super::bind::set_graphics_root_signature(list_ptr, 0x7400_0200 as *mut c_void); let before = super::super::bind::counts_snapshot(); draw_indexed_x(list_ptr, ib(2), DXGI_FORMAT_R16_UINT, 6, 0); let after = super::super::bind::counts_snapshot(); @@ -9350,6 +10488,173 @@ mod tests { !would_signal_close_cycle(&mut g3, 0xD001, 0x3000, 0x78d), "pipelined 3-queue chain with wait_seq > sig_seq must NOT be treated as a cycle" ); + + // 3. Next frame's signal on a cell whose armed wait an earlier signal already covers + // (a retail title, frame 0x6dc): C (0xC001) signalled A=0x6db, Direct (0xD001) + // waits A >= 0x6db (seq 3544) and later signals B=0x6dc (seq 3572); C waits on + // B >= 0x6dc (seq 34) and now signals A=0x6dc. Direct's wait is satisfied by C's + // 0x6db signal, not by this one: no cycle. + let fa: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let fb: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut gp = SyncGraph::default(); + gp.cells.insert( + 0x4000, + SyncCell { + fence: Some(fa), + device: dev.as_raw() as usize, + recorded_max: 0x6dc, + submitted_max: 0x6db, + submitted_queue: Some(0xC001), + armed_waits: vec![ArmedGpuWait { + val: 0x6db, + waiting_queue: 0xD001, + waiting_queue_ty: D3D12_COMMAND_LIST_TYPE_DIRECT.0, + wait_seq: 3544, + armed_at: Instant::now(), + after_write64: false, + }], + submitted_signals: vec![SubmittedSignal { val: 0x6db, queue: 0xC001, seq: 16 }], + ..Default::default() + }, + ); + gp.cells.insert( + 0x5000, + SyncCell { + fence: Some(fb), + device: dev.as_raw() as usize, + recorded_max: 0x6dc, + submitted_max: 0x6dc, + submitted_queue: Some(0xD001), + armed_waits: vec![ArmedGpuWait { + val: 0x6dc, + waiting_queue: 0xC001, + waiting_queue_ty: D3D12_COMMAND_LIST_TYPE_COMPUTE.0, + wait_seq: 34, + armed_at: Instant::now(), + after_write64: false, + }], + submitted_signals: vec![SubmittedSignal { val: 0x6dc, queue: 0xD001, seq: 3572 }], + ..Default::default() + }, + ); + assert!( + !would_signal_close_cycle(&mut gp, 0xC001, 0x4000, 0x6dc), + "a wait an earlier signal already satisfies must NOT make the next frame's signal a cycle" + ); + // Direct waiting on A >= 0x6dc instead (only this signal satisfies it): a true cycle. + gp.cells.get_mut(&0x4000).unwrap().armed_waits[0].val = 0x6dc; + assert!( + would_signal_close_cycle(&mut gp, 0xC001, 0x4000, 0x6dc), + "a wait only this signal satisfies, armed before the waiter's own signal, MUST be a cycle" + ); + } + } + + /// The console's cache flushes are UAV barriers for all resources on lists that take them; a + /// flush of nothing, a copy list's and a bundle's are not. + #[test] + fn cache_flushes_are_uav_barriers() { + #[repr(C)] + struct FakeFlushList { + vt: *const usize, + ty: i32, + barriers: Mutex>, + } + unsafe extern "system" fn get_type(this: *mut c_void) -> D3D12_COMMAND_LIST_TYPE { + D3D12_COMMAND_LIST_TYPE((*(this as *const FakeFlushList)).ty) + } + unsafe extern "system" fn barrier(this: *mut c_void, n: u32, b: *const D3D12_RESOURCE_BARRIER) { + for k in 0..n as usize { + let b = &*b.add(k); + let res = (*b.Anonymous.UAV).pResource.as_ref().map_or(0, |r| r.as_raw() as usize); + (*(this as *const FakeFlushList)).barriers.lock().unwrap().push((b.Type.0, res)); + } + } + let mut orig_vt = [0usize; 64]; + orig_vt[PC_GET_TYPE] = get_type as usize; + orig_vt[PC_RESOURCE_BARRIER] = barrier as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let mut fake = Box::new(FakeFlushList { vt: unsafe { ext_vt.as_ptr().add(1) }, ty: D3D12_COMMAND_LIST_TYPE_COMPUTE.0, barriers: Mutex::new(Vec::new()) }); + let uav = (D3D12_RESOURCE_BARRIER_TYPE_UAV.0, 0); + unsafe { + let list = &mut *fake as *mut FakeFlushList as *mut c_void; + flush_cache_range_x(list, 0xc3c0, 0x8002_0000, 0, 0xFFFF_FFFF_FF00); + flush_cache_range_x(list, 0, 0x8000_0000, 0x1000, 0x100); + flush_pipeline_x(list, 1, 0, 0); + assert_eq!(*fake.barriers.lock().unwrap(), vec![uav; 3]); + // nothing asked for, or of no memory + flush_cache_range_x(list, 0, 0, 0, 0x1000); + flush_cache_range_x(list, 0xc3c0, 0, 0, 0); + assert_eq!(fake.barriers.lock().unwrap().len(), 3); + fake.ty = D3D12_COMMAND_LIST_TYPE_DIRECT.0; + flush_cache_range_x(list, 0xc3c0, 0, 0, 1); + assert_eq!(fake.barriers.lock().unwrap().len(), 4); + for ty in [D3D12_COMMAND_LIST_TYPE_COPY, D3D12_COMMAND_LIST_TYPE_BUNDLE] { + fake.ty = ty.0; + flush_cache_range_x(list, 0xc3c0, 0, 0, 1); + flush_pipeline_x(list, 1, 0, 0); + } + assert_eq!(fake.barriers.lock().unwrap().len(), 4); + } + } + + /// The next frame's Signal of a title fence does not break a "cycle" through a wait an earlier + /// signal of that fence satisfies; one that only the new signal satisfies is a cycle, broken + /// by releasing the cell's wait. + #[test] + fn a_title_fence_wait_an_earlier_signal_covers_is_no_cycle() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let title: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let cell: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let (q0, q1, va, f) = (0xC0F0usize, 0xC0F1usize, 0x7E57_C0F0u64, title.as_raw() as usize); + // q1 signalled the fence at 1; q0 waits for that and signals the cell later, which q1 + // waits for; q1 is about to signal the fence at 2 + let set = |wait: u64| { + let mut g = SYNC_GRAPH.lock().unwrap(); + let gr = g.get_or_insert_with(SyncGraph::default); + let mut tf = TitleFenceSync::default(); + tf.waits.push((wait, q0, 5)); + tf.signals.push(SubmittedSignal { val: 1, queue: q1, seq: 3 }); + gr.title_fences.insert(f, tf); + if !gr.cells.contains_key(&va) { + ARMED_GPU_WAITS.fetch_add(1, Ordering::AcqRel); + gr.cells.insert( + va, + SyncCell { + fence: Some(cell.clone()), + device: dev.as_raw() as usize, + recorded_max: 9, + submitted_max: 9, + submitted_queue: Some(q0), + armed_waits: vec![ArmedGpuWait { val: 9, waiting_queue: q1, waiting_queue_ty: D3D12_COMMAND_LIST_TYPE_COMPUTE.0, wait_seq: 4, armed_at: Instant::now(), after_write64: false }], + submitted_signals: vec![SubmittedSignal { val: 9, queue: q0, seq: 7 }], + ..Default::default() + }, + ); + } + }; + set(1); + break_cycles_before_title_signal(q1, f, 2); + assert_eq!(cell.GetCompletedValue(), 0, "the wait is the earlier signal's: nothing is released"); + set(2); + break_cycles_before_title_signal(q1, f, 2); + assert_eq!(cell.GetCompletedValue(), 9, "a wait only the new signal satisfies: released"); + let mut g = SYNC_GRAPH.lock().unwrap(); + let gr = g.as_mut().unwrap(); + gr.title_fences.remove(&f); + let left = gr.cells.remove(&va).map_or(0, |c| c.armed_waits.len()); + if left > 0 { + ARMED_GPU_WAITS.fetch_sub(left, Ordering::AcqRel); + } } } @@ -9530,7 +10835,8 @@ mod tests { /// #1452: the title Resets its list and submits the new recording while the GPU still runs /// the previous one (held here by a queue Wait on a fence not yet signalled). The new /// recording must be on another PC list (the PC forbids submitting one again before its last - /// submit is done, debug layer id 553), also one more time; once the GPU is done, the list + /// submit is done, debug layer id 553), also the times after (not on a stand-in moved to the + /// spares while its submit runs); once the GPU is done, the list /// records on its own PC list again. Both ways a title Resets: the list's #10, and the newer /// console layout's #139, which goes through the list's thunk to the PC list it records on /// (`reset_x` on that one) – the retail title's way, which the stand-in did not see at first. @@ -9583,10 +10889,13 @@ mod tests { let (second, again) = submit(); assert_eq!(reset(w, a, 0, second[0]), 0); let (third, again3) = submit(); + // the first stand-in is a spare now, its submit still on the GPU + assert_eq!(reset(w, a, 0, third[0]), 0); + let (more, again4) = submit(); gate.Signal(1).unwrap(); q.Signal(&done, 1).unwrap(); crate::gpu::fence::wait(&done, 1, &dev, None, 5000).expect("the queue finishes"); - assert_eq!(reset(w, a, 0, third[0]), 0); + assert_eq!(reset(w, a, 0, more[0]), 0); let (fourth, _) = submit(); q.Signal(&done, 2).unwrap(); crate::gpu::fence::wait(&done, 2, &dev, None, 5000).expect("the queue finishes"); @@ -9600,6 +10909,9 @@ mod tests { assert_eq!(third.len(), 1); assert!(third[0] != primary && third[0] != second[0], "{how}: nor on the one standing in, also still on the GPU"); assert_eq!(again3, 0, "{how}"); + assert_eq!(more.len(), 1); + assert!(![primary, second[0], third[0]].contains(&more[0]), "{how}: nor on a spare whose submit is still on the GPU"); + assert_eq!(again4, 0, "{how}"); assert_eq!(fourth, vec![primary], "{how}: once the GPU is done the list records on its own PC list"); assert!(removed.is_ok()); } @@ -9856,6 +11168,74 @@ mod tests { } } + /// On the software adapter (the test above opens the default one): two dispatches put off on + /// a title list are recorded at its submit, on the allocator kept on the list's primary PC + /// list, and wait there for the build without being put off again; the segments run. + #[test] + fn put_off_dispatches_wait_at_the_submit_and_run_on_the_software_adapter() { + use super::super::{bind, pso_async, title_list}; + use std::time::Duration; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let mut dev: Option = None; + let warp = CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()); + if warp.and_then(|w| D3D12CreateDevice(&w, D3D_FEATURE_LEVEL_11_0, &mut dev)).is_err() { + crate::gpu::recomp::runner::skip_test("no WARP adapter"); + return; + } + let dev = dev.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let raw: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &alloc, None).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + + let standin = 0x7E57_D101usize; + pso_async::submit( + standin, + true, + Box::new(|| { + std::thread::sleep(Duration::from_millis(500)); + 0 + }), + ); + let pc0 = raw.into_raw(); + real::adopt(pc0, real::Kind::CommandList); + on_create(pc0, alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + bind::reset(pc0, alloc.as_raw() as usize, standin); + let wrap = title_list::wrap(pc0); + + let mut segs = vec![pc0]; + for _ in 0..2 { + bind::dispatch(*segs.last().unwrap(), 1, 1, 1); + segs.clear(); + assert!(title_list::push_segments(wrap, &mut segs)); + } + assert_eq!(segs.len(), 5, "the list before each dispatch, the dispatch, the list after it"); + let close_fn: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(9)); + assert_eq!(close_fn(wrap), 0); + + assert!(pso_async::is_pending(standin)); + let refused = pso_async::put_off_count(pso_async::PutOff::Refused); + record_deferred(wrap); + assert!(!pso_async::is_pending(standin), "the submit waits for the build"); + assert_eq!(pso_async::put_off_count(pso_async::PutOff::Refused), refused, "a dispatch the submit records is not put off again: it waits there"); + let own = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(pc0 as usize))?.own_alloc.clone()); + assert!(own.is_some(), "the list's own allocator is kept on its primary PC list"); + + type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + let exec: ExecFn = std::mem::transmute(*(*(queue.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); + exec(queue.as_raw(), segs.len() as u32, segs.as_ptr()); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 2000).expect("the split list runs"); + + let rel_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(2)); + assert_eq!(rel_fn(wrap), 0); + let _ = pso_async::released(standin); + } + } + /// Reproduces the exact intra-list fork-join pattern seen on retail compute queues: /// q_compute list O_c: Write64(cell_A, frame) -> Wait64(cell_B >= frame) -> Write64(cell_C, frame) /// q_direct list O_d: Wait64(cell_A >= frame) -> Write64(cell_B, frame) @@ -10010,6 +11390,68 @@ mod tests { } } + /// #1452: `KickoffX` on a split list submits its segments and moves them to the spares; the + /// GPU still runs them (held here by a queue Wait on a fence not yet signalled). The next + /// split of the recording that goes on must not record on the segment just submitted (the PC + /// forbids submitting it again before that submit is done, debug layer id 553). + #[test] + fn a_split_after_kickoff_does_not_take_the_segment_just_submitted() { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + unsafe { + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + // (`KickoffX` submits through the queue's original ExecuteCommandLists) + real::adopt(q.as_raw(), real::Kind::CommandQueue); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let a = alloc.as_raw() as usize; + let primary = dev.CreateCommandList::<_, _, ID3D12GraphicsCommandList>(0, ty, &alloc, None).unwrap().into_raw(); + real::adopt(primary, real::Kind::CommandList); + on_create(primary, a, 0, ty); + super::super::bind::reset(primary, a, 0); + let w = super::super::title_list::wrap(primary); + note_queue_for_lists(q.as_raw() as usize, &[primary]); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + // a write, then a wait on another cell, splits the list; the waited-for memory holds + // the value already, so the waits pass on the CPU + let cell_a = Box::new(AtomicU64::new(0)); + let cell_b = Box::new(AtomicU64::new(5)); + let (va_a, va_b) = (&*cell_a as *const AtomicU64 as u64, &*cell_b as *const AtomicU64 as u64); + let split = |list: *mut c_void, frame: u64| { + note_write64_recorded(list, va_a, frame); + wait64_x(list, va_b, D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, frame, 0, 0); + let mut segs = Vec::new(); + assert!(super::super::title_list::push_segments(w, &mut segs)); + segs + }; + + q.Wait(&gate, 1).unwrap(); + let first = split(primary, 1); + kickoff_x(first[first.len() - 1]); + let second = split(primary, 2); + gate.Signal(1).unwrap(); + q.Signal(&done, 1).unwrap(); + let ran = crate::gpu::fence::wait(&done, 1, &dev, None, 5000).is_ok(); + let removed = dev.GetDeviceRemovedReason(); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(w as *const *const usize)).add(2)); + assert_eq!(release(w), 0); + if let Some(gr) = SYNC_GRAPH.lock().unwrap().as_mut() { + gr.cells.remove(&cpu_at(va_a)); + gr.cells.remove(&cpu_at(va_b)); + } + + assert_eq!(first.len(), 2, "the wait after the write splits the list"); + assert_eq!(first[0], primary); + assert_eq!(second.len(), 2, "the recording after KickoffX splits again"); + assert_eq!(second[0], primary, "after KickoffX the recording goes on on the primary PC list"); + assert_ne!(second[1], first[1], "the segment KickoffX just submitted is still on the GPU"); + assert!(ran, "the queue finishes"); + assert!(removed.is_ok()); + } + } + /// A buffer outside unified memory that has a mirror is bound at its mirror again without /// asking whether the title's memory is readable: the source made unreadable after the first /// bind still binds the same mirror (before, the bind asked `readable` first and gave the @@ -10041,6 +11483,84 @@ mod tests { } } + /// Unified memory with the 16-window layout of its own (the process's is chosen once, from + /// the environment): its view windows hold GPU views. + fn sixteen_windows() -> crate::gpu::uma::Uma { + crate::gpu::uma::Uma::for_runtime_windows(16 << 20, 16 << 20, crate::gpu::uma::MAX_HEAP_WINDOWS).expect("16-window aperture") + } + + /// An index or vertex buffer in a GPU view goes to the PC as its view window's address; without + /// one it goes as none, never as the console address (no PC address: the device hangs). + #[test] + fn a_gpu_view_buffer_reaches_the_pc_at_its_windows_address() { + let u = sixteen_windows(); + let g = u.view_reserve(1 << 20).expect("a GPU view"); + let k = u.window_of(g).unwrap(); + assert!(u.is_view_window(k)); + let window_va = |w: usize| Some(0x7A00_0000_0000 + w as u64 * crate::gpu::uma::WINDOW as u64); + let at = g as u64 + 0x40; + assert_eq!(pc_va_in(&u, at, window_va), window_va(k).unwrap() + (g - u.window(k).0) as u64 + 0x40); + assert_eq!(pc_va_in(&u, at, |_| None), 0, "a view window that is not open on the GPU"); + // in a view window but no GPU view of the title's: an address by number, as it is + let other = g as u64 + (2 << 20); + assert_eq!(pc_va_in(&u, other, window_va), other); + assert_eq!(pc_va_in(&u, 0x1234_0000, window_va), 0x1234_0000); + assert_eq!(u.view_release(g), Some(1 << 20)); + } + + /// A vertex or index buffer of a GPU view across a view window's end is bound only up to that + /// end: the windows are separate buffers on the PC. One inside a window stays as it is. + #[test] + fn a_view_across_a_window_end_is_bound_up_to_it() { + use crate::gpu::uma::{GRAIN, WINDOW}; + let u = sixteen_windows(); + let g = u.view_reserve(WINDOW + GRAIN).expect("a GPU view over two windows"); + let end = (g + WINDOW) as u64; + assert_eq!(bytes_in_window(&u, end - 0x100, 0x200), Some(0x100), "across the end"); + assert_eq!(bytes_in_window(&u, end - 0x200, 0x200), None, "up to the end"); + assert_eq!(bytes_in_window(&u, g as u64 + 0x40, 0x1000), None, "inside"); + assert_eq!(bytes_in_window(&u, end + 0x10, 0x100), None, "in the next window"); + assert_eq!(bytes_in_window(&u, 0x1234_0000, 0x1000_0000), None, "not in a window"); + assert_eq!(u.view_release(g), Some(WINDOW + GRAIN)); + } + + /// A wait on an address in a GPU view reads the value at its CPU view, where the title writes + /// it and what the lists write into the view's tiles is read back; a write and a wait naming + /// either view are kept in one sync cell. Without view windows nothing changes. + #[test] + fn a_wait_on_a_gpu_view_reads_its_cpu_view() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + // a size no other test pairs views of (the newest CPU view of a size takes its GPU view) + const SIZE: usize = 0x2D_0000; + let u = sixteen_windows(); + let span = super::super::bind::view_span_of(&u); + let g = u.view_reserve(SIZE).expect("a GPU view"); + unsafe { + let c = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(c, 0); + crate::hle::kernelx::mirrors::reserved(c, SIZE, 0x2040_2000, PAGE_READWRITE); + crate::hle::kernelx::mirrors::reserved(g, SIZE, 0x2040_2000, 0x801); + let x = 0x1_0008u64; + let at = cpu_at_in(span, g as u64 + x); + assert_eq!(at, c as u64 + x, "the CPU view"); + assert_eq!(cpu_at_in(span, c as u64 + x), at, "a write at the CPU view and a wait at the GPU view share their cell"); + ((c as u64 + x) as *mut u64).write(0x5843_4C00_0000_0042); + let w = PendingWait { va: at, width: 8, comparison: D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, value: 0x5843_4C00_0000_0042, mask: u64::MAX, after_write64: false }; + assert_eq!(w.read_value(), Some(0x5843_4C00_0000_0042)); + assert!(w.is_satisfied()); + assert!(!PendingWait { value: 0x5843_4C00_0000_0043, ..w }.is_satisfied()); + // the GPU view is no memory the CPU reads: a wait kept there would read nothing (and pass) + assert_eq!(PendingWait { va: g as u64 + x, ..w }.read_value(), None); + // layouts without view windows: every address is its own + assert_eq!(cpu_at_in((0, 0), g as u64 + x), g as u64 + x); + crate::hle::kernelx::mirrors::released(g); + crate::hle::kernelx::mirrors::released(c); + assert_eq!(cpu_at_in(span, g as u64 + x), g as u64 + x, "unpaired"); + VirtualFree(c as *mut c_void, 0, MEM_RELEASE); + } + assert_eq!(u.view_release(g), Some(SIZE)); + } + #[test] fn occlusion_tracks_dropped_draws_and_active_counter() { let mut occ = Occlusion::default(); diff --git a/crates/xcl/src/hle/d3d12x/look_stats.rs b/crates/xcl/src/hle/d3d12x/look_stats.rs new file mode 100644 index 0000000000..88db61c8df --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/look_stats.rs @@ -0,0 +1,366 @@ +//! Diagnostic (`XCL_LOOK_STATS=1`): what the looks for CPU writes find, as averages over 256 of them +//! (logged): how many of a look's pages the looks before it had found too, in how many runs they +//! lie, how many of the pages scanned had changed, and how long before the submit that looked the +//! youngest of its lists had been closed. +//! +//! `XCL_LOOK_STATS=2` adds the splits (`deep`): where the time of a look, of the scan after it and +//! of the submitting thread goes, finer than `submit_cost`'s line, to choose between the fixes of +//! a slow submit path. + +use std::cell::Cell; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::Duration; + +/// `XCL_LOOK_STATS`: 1 the lines of the looks, 2 those and the splits; 0 when unset +fn level() -> u8 { + static LEVEL: OnceLock = OnceLock::new(); + *LEVEL.get_or_init(|| match std::env::var("XCL_LOOK_STATS").as_deref().map(str::trim) { + Ok("1") => 1, + Ok("2") => 2, + _ => 0, + }) +} + +pub(super) fn on() -> bool { + level() >= 1 +} + +/// `XCL_LOOK_STATS=2`: the splits are measured too +pub(super) fn deep() -> bool { + level() >= 2 +} + +/// the upper ends (µs) of the steps `Stats::ago` counts by; the last step has none +const STEPS: [u64; 6] = [20, 100, 500, 2_000, 10_000, 50_000]; + +#[derive(Default)] +struct Stats { + looks: u64, + us: u64, + pages: u64, + /// of them found between the submits (`XCL_LOOK_AHEAD`) + ahead: u64, + runs: u64, + /// pages also in the look before, and in all three before + once: u64, + thrice: u64, + /// pages scanned (the ones of video memory's windows), and those with a changed chunk + scanned: u64, + changed: u64, + ago: [u64; STEPS.len() + 1], + /// the pages of the three looks before, the last one first + before: [Vec; 3], + /// the looks' write-watch calls (`deep`, `add_call`) + split: [u64; 8], +} + +static STATS: Mutex> = Mutex::new(None); + +thread_local! { + /// the write-watch calls of this thread's look so far (`add_call`): a look's calls are all + /// made on its submitting thread, and `look` takes them + static CALLS: Cell<[u64; 8]> = const { Cell::new([0; 8]) }; +} + +/// One write-watch call into `acc`: [ns, bytes covered, pages, calls] of the calls that returned +/// no page, then the same of those that returned some (ns: a call over little memory takes a few +/// µs). A look over memory nobody wrote costs a walk of its page tables, one with pages a +/// page-table entry changed for each: which of the two a look's time is decides between looking +/// at less memory and taking fewer pages. +fn add_call(acc: &mut [u64; 8], ns: u64, bytes: u64, pages: u64) { + let k = if pages == 0 { 0 } else { 4 }; + acc[k] += ns; + acc[k + 1] += bytes; + acc[k + 2] += pages; + acc[k + 3] += 1; +} + +/// Sums of a `deep` line, added from any thread with relaxed adds (no lock: some are added with +/// the sparse state's held); `take` gives them and starts again (an add made while they are taken +/// may go to the next line's). +pub(super) struct Sums([AtomicU64; N]); + +impl Sums { + pub(super) const fn new() -> Self { + Sums([const { AtomicU64::new(0) }; N]) + } + + /// (the sum with it) + pub(super) fn add(&self, k: usize, v: u64) -> u64 { + self.0[k].fetch_add(v, Ordering::Relaxed) + v + } + + pub(super) fn max(&self, k: usize, v: u64) { + self.0[k].fetch_max(v, Ordering::Relaxed); + } + + pub(super) fn take(&self) -> [u64; N] { + std::array::from_fn(|k| self.0[k].swap(0, Ordering::Relaxed)) + } +} + +/// How stale a look can be (`walk_stale`, `walk_pass`): [looks, looks that began with a block +/// the walk found that no look had taken, walk passes, ns walking, the longest pass's ns]. A look +/// takes the blocks written lately only; a write to another block waits for the walk to find it. +static STALE: Sums<5> = Sums::new(); + +/// A look began (`deep` only); `stale`: the walk had made a block hot since the look before began. +pub(super) fn walk_stale(stale: bool) { + STALE.add(0, 1); + STALE.add(1, stale as u64); +} + +/// A pass of the walk over all watched memory took `took` (`deep` only). +pub(super) fn walk_pass(took: Duration) { + STALE.add(2, 1); + STALE.add(3, took.as_nanos() as u64); + STALE.max(4, took.as_nanos() as u64); +} + +/// The pages XCL wrote into the title's memory itself (`own_writes`): [looks, pages written since +/// the look before (copies back landed, immediates stored), those in the look, those scanned, +/// those the scan found unchanged]. The write watch reports them like the title's writes, and a +/// look and a scan spent on them is spent on nothing new. +static OWN: Sums<5> = Sums::new(); + +/// What a look's submit found of XCL's own writes since the look before (`deep` only). +pub(super) fn own_writes(written: usize, in_look: usize, scanned: usize, unchanged: usize) { + OWN.add(0, 1); + OWN.add(1, written as u64); + OWN.add(2, in_look as u64); + OWN.add(3, scanned as u64); + OWN.add(4, unchanged as u64); +} + +/// The scans (`scan_split`): [submits, ns gathering, ns scanning, jobs shared, their items, those +/// the caller did, ns until a job's first worker began, jobs a worker began] +static SCAN: Sums<8> = Sums::new(); + +/// A submit's scan (`deep` only): `gather` building its pages' slots, `scan` the scan of them, +/// and how that was shared with the workers (None: too few pages to share). +pub(super) fn scan_split(gather: Duration, scan: Duration, shares: Option) { + SCAN.add(0, 1); + SCAN.add(1, gather.as_nanos() as u64); + SCAN.add(2, scan.as_nanos() as u64); + if let Some(s) = shares { + SCAN.add(3, 1); + // (the items done: all of the job's) + SCAN.add(4, (s.by_caller + s.by_workers) as u64); + SCAN.add(5, s.by_caller as u64); + if let Some(d) = s.first { + SCAN.add(6, d.as_nanos() as u64); + SCAN.add(7, 1); + } + } +} + +/// A write-watch call of a look (`deep` only) covered `bytes`, took `took` and returned `pages`. +pub(super) fn watch_call(took: Duration, bytes: usize, pages: usize) { + CALLS.with(|c| { + let mut acc = c.get(); + add_call(&mut acc, took.as_nanos() as u64, bytes as u64, pages as u64); + c.set(acc); + }); +} + +/// How many of `a`'s pages every one of `others` has too (all sorted, each page once). +fn in_all(a: &[usize], others: &[Vec]) -> u64 { + let mut at = vec![0usize; others.len()]; + a.iter() + .filter(|&&p| { + others.iter().zip(at.iter_mut()).all(|(o, k)| { + while *k < o.len() && o[*k] < p { + *k += 1; + } + o.get(*k) == Some(&p) + }) + }) + .count() as u64 +} + +/// The runs of neighbouring pages of `pages` (sorted, 4 KiB each). +fn runs_of(pages: &[usize]) -> u64 { + pages.iter().zip(std::iter::once(&usize::MAX).chain(pages)).filter(|(p, q)| **p != q.wrapping_add(0x1000)).count() as u64 +} + +/// A look found `pages` (sorted), `ahead` of them before its submit; it took `took`. `closed`: how +/// long before its submit the youngest of the submit's lists was closed (None: not known). +pub(super) fn look(pages: &[usize], ahead: usize, took: Duration, closed: Option) { + if !on() { + return; + } + let mut g = STATS.lock().unwrap_or_else(|e| e.into_inner()); + let s = g.get_or_insert_with(Stats::default); + s.looks += 1; + s.us += took.as_micros() as u64; + s.pages += pages.len() as u64; + s.ahead += ahead as u64; + s.runs += runs_of(pages); + s.once += in_all(pages, &s.before[..1]); + s.thrice += in_all(pages, &s.before); + s.before.rotate_right(1); + s.before[0].clear(); + s.before[0].extend_from_slice(pages); + if let Some(us) = closed { + s.ago[STEPS.partition_point(|&e| e <= us)] += 1; + } + if deep() { + let calls = CALLS.with(|c| c.replace([0; 8])); + s.split.iter_mut().zip(calls).for_each(|(a, b)| *a += b); + } + if s.looks % 256 == 0 && deep() { + let x = &s.split; + crate::xlog_info!( + "D3D12.X: look split (256 looks): {:.2} ms a look in {:.1} calls over {} MB that found nothing + {:.2} ms in {:.1} calls over {} MB with {} pages", + x[0] as f64 / 256e6, + x[3] as f64 / 256.0, + (x[1] / 256) >> 20, + x[4] as f64 / 256e6, + x[7] as f64 / 256.0, + (x[5] / 256) >> 20, + x[6] / 256 + ); + let c = SCAN.take(); + let per = |v: u64, of: u64| v as f64 / of.max(1) as f64; + crate::xlog_info!( + "D3D12.X: scan split (256 looks): gather {:.2} ms, scan {:.2} ms a submit; of {:.0} items a job the caller did {:.0} %, the first worker began after {:.0} µs ({} jobs in {} submits, {} with a worker)", + per(c[1], c[0]) / 1e6, + per(c[2], c[0]) / 1e6, + per(c[4], c[3]), + per(c[5] * 100, c[4]), + per(c[6], c[7]) / 1e3, + c[3], + c[0], + c[7] + ); + let w = STALE.take(); + crate::xlog_info!( + "D3D12.X: walk staleness (256 looks): {} of {} looks began with a block the walk found that no look had taken yet; a walk pass took {:.1} ms ({:.1} ms the longest, {} passes)", + w[1], + w[0], + per(w[3], w[2]) / 1e6, + w[4] as f64 / 1e6, + w[2] + ); + let o = OWN.take(); + crate::xlog_info!( + "D3D12.X: XCL's own writes (256 looks): {:.1} pages a look written by XCL since the look before (copies back landed, immediates stored), {:.1} of them in the look, {:.1} scanned, {:.0} % of those found unchanged", + per(o[1], o[0]), + per(o[2], o[0]), + per(o[3], o[0]), + per(o[4] * 100, o[3]) + ); + } + if s.looks % 256 == 0 { + let a = |v: u64| v / 256; + let share = |v: u64, of: u64| if of == 0 { 0 } else { v * 100 / of }; + crate::xlog_info!( + "D3D12.X: the last 256 looks for CPU writes: {:.2} ms and {} pages a look ({} found ahead) in {} runs ({} % of the pages also in the look before, {} % in all three before); {} scanned a look, {} % of them changed; youngest list closed before the submit: {} <20 µs, {} <100 µs, {} <500 µs, {} <2 ms, {} <10 ms, {} <50 ms, {} longer", + s.us as f64 / 256e3, + a(s.pages), + a(s.ahead), + a(s.runs), + share(s.once, s.pages), + share(s.thrice, s.pages), + a(s.scanned), + share(s.changed, s.scanned), + s.ago[0], + s.ago[1], + s.ago[2], + s.ago[3], + s.ago[4], + s.ago[5], + s.ago[6] + ); + *s = Stats { looks: s.looks, before: std::mem::take(&mut s.before), ..Stats::default() }; + } +} + +/// A scan went over `pages` pages and found the changed `runs` (address, length; sorted). +pub(super) fn scan(pages: usize, runs: &[(usize, usize)]) { + if !on() { + return; + } + let mut g = STATS.lock().unwrap_or_else(|e| e.into_inner()); + let s = g.get_or_insert_with(Stats::default); + s.scanned += pages as u64; + let mut next = 0usize; + for &(a, n) in runs { + let (first, end) = ((a & !0xFFF).max(next), (a + n + 0xFFF) & !0xFFF); + if end > first { + s.changed += ((end - first) >> 12) as u64; + next = end; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pages_found_again_and_their_runs() { + let p = |v: &[usize]| v.iter().map(|k| k * 0x1000).collect::>(); + let a = p(&[1, 2, 3, 7, 9, 10]); + assert_eq!(runs_of(&a), 3); + assert_eq!(runs_of(&[]), 0); + assert_eq!(runs_of(&p(&[1])), 1); + assert_eq!(in_all(&a, &[p(&[2, 3, 4, 10])]), 3); + assert_eq!(in_all(&a, &[p(&[2, 3, 4, 10]), p(&[3, 7, 10]), p(&[1, 3])]), 1); + assert_eq!(in_all(&a, &[p(&[])]), 0); + } + + #[test] + fn a_looks_calls_add_up_to_what_was_put_in() { + // (ns, bytes, pages) of the calls of one look + let calls = [(4_000u64, 64u64 << 20, 0u64), (9_000, 2 << 20, 37), (1_500, 4 << 20, 0), (700, 1 << 20, 1)]; + let mut acc = [0u64; 8]; + for &(ns, bytes, pages) in &calls { + add_call(&mut acc, ns, bytes, pages); + } + let sum = |f: fn(&(u64, u64, u64)) -> u64| calls.iter().map(f).sum::(); + assert_eq!(acc[0] + acc[4], sum(|c| c.0)); + assert_eq!(acc[1] + acc[5], sum(|c| c.1)); + assert_eq!(acc[2] + acc[6], sum(|c| c.2)); + assert_eq!(acc[3] + acc[7], calls.len() as u64); + // the calls that found nothing on one side, the others on the other + assert_eq!(acc[..4], [5_500, 68 << 20, 0, 2]); + assert_eq!(acc[4..], [9_700, 3 << 20, 38, 2]); + // a thread's calls go to its own look + watch_call(Duration::from_micros(3), 8192, 2); + std::thread::spawn(|| watch_call(Duration::from_micros(5), 4096, 0)).join().unwrap(); + assert_eq!(CALLS.with(|c| c.replace([0; 8])), [0, 0, 0, 0, 3_000, 8192, 2, 1]); + } + + #[test] + fn sums_from_threads_are_taken_once() { + static S: Sums<3> = Sums::new(); + std::thread::scope(|t| { + for k in 0..4u64 { + t.spawn(move || { + for _ in 0..1000 { + assert!(S.add(0, 1) >= 1); + S.add(2, k); + } + }); + } + }); + assert_eq!(S.take(), [4000, 0, 6000]); + assert_eq!(S.take(), [0, 0, 0]); + } + + #[test] + fn staleness_and_own_writes_are_summed() { + // (only `deep` runs add to these, and no test is: this one has them alone) + for stale in [true, false, true] { + walk_stale(stale); + } + walk_pass(Duration::from_millis(3)); + walk_pass(Duration::from_millis(7)); + assert_eq!(STALE.take(), [3, 2, 2, 10_000_000, 7_000_000]); + own_writes(40, 30, 28, 25); + own_writes(2, 0, 0, 0); + assert_eq!(OWN.take(), [2, 42, 30, 28, 25]); + } +} diff --git a/crates/xcl/src/hle/d3d12x/lut3d.rs b/crates/xcl/src/hle/d3d12x/lut3d.rs new file mode 100644 index 0000000000..6f969c56b6 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/lut3d.rs @@ -0,0 +1,427 @@ +//! `XCL_DUMP_TARGETS` (`targets`): 3D textures – a title's colour-grading lookup tables are – +//! followed through XCL. With the switch on, a line when one is made (whichever creation path: +//! `lut` names it from then on), when XCL sees it written (a copy into it, a render target view +//! of it made, drawn into or cleared, an unordered access view of it made – what a shader writes +//! through one is not seen –, an upload from the title's memory, WriteToSubresource) and when a +//! shader resource view of it goes into a console descriptor slot (its T# index there is what a +//! translated shader takes from `ResourceDescriptorHeap`). At a dumped frame each live one of at +//! most 64 on every side is read back in the state the title's submitted work left it in (its +//! transitions, as `title_textures` notes them, applied at each submit): the texels of its 8 +//! corners and centre and each channel's least and greatest over mip 0, and its first, middle +//! and last depth slices as `lut_xx_f_slice.bmp` (channels clamped to +//! 0..1, alpha left out). One whose state is not known (copied into from COMMON: promoted to +//! COPY_DEST, which a texture does not decay from) is logged as not read back. +//! Textures are kept by address (not AddRef'd) and forgotten at their last Release. + +use std::collections::BTreeMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// sides of a texture read back at a dump, at most; and how many are read back +const SIDE_MOST: u64 = 64; +const DUMPED_MOST: usize = 256; +/// lines of writes logged per texture (then every power of two) +const WRITES_LOGGED: u64 = 12; + +pub fn on() -> bool { + super::targets::enabled() +} + +/// Whether `created` is to be told of a resource made (`on`, or `XCL_CAPTURE_FRAME`). +pub fn created_on() -> bool { + on() || super::capture::enabled() +} + +struct Vol { + n: u64, + /// the state the title's submitted work leaves it in: one for all subresources, or one each + states: Vec, + /// copied into while in COMMON with no transition after: implicitly COPY_DEST + promoted: bool, + writes: u64, +} + +static VOLS: Mutex> = Mutex::new(BTreeMap::new()); +static NEXT: AtomicU64 = AtomicU64::new(0); +/// PC list → the transitions of 3D textures it recorded since it was made or reset +static NOTES: Mutex>> = Mutex::new(BTreeMap::new()); + +unsafe fn desc_of(res: usize) -> Option { + let p = res as *mut c_void; + ID3D12Resource::from_raw_borrowed(&p).map(|r| r.GetDesc()) +} + +/// Texture `res` was made by `how` (from the console description `console`, at the title's +/// address `va`, kept in step with that memory or not) in `state`: noted if it is a 3D one. +pub unsafe fn created(how: &str, res: *mut c_void, console: Option<&[u8; 0x38]>, va: Option, kept: bool, state: u32) { + super::capture::created(how, res, console, va, kept); + if !on() || res.is_null() { + return; + } + let Some(d) = desc_of(res as usize).filter(|d| d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) else { return }; + let u = |x: &[u8; 0x38], o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); + let console_text = console.map_or(String::new(), |x| format!(" (console format {}, console flags {:#x}, layout {:#x})", u(x, 0x20), u(x, 0x30), u(x, 0x2C))); + let flags = d.Flags.0; + let (n, known) = { + let mut g = VOLS.lock().unwrap(); + match g.get(&(res as usize)) { + Some(v) => (v.n, true), + None => { + let n = NEXT.fetch_add(1, Ordering::Relaxed); + g.insert(res as usize, Vol { n, states: vec![D3D12_RESOURCE_STATES(state as i32)], promoted: false, writes: 0 }); + (n, false) + } + } + }; + let at = va.map_or(String::new(), |a| format!(", the title's memory at {a:#x}")); + match known { + true => crate::xlog_info!("D3D12.X: 3D texture lut{n} {res:p} is also {how}{console_text}: {}{at}", if kept { "kept in step with the title's memory" } else { "not kept in step with the title's memory" }), + false => crate::xlog_info!( + "D3D12.X: 3D texture lut{n} {res:p} made by {how}: {}x{}x{}, {} mips, PC format {}{console_text}, flags {flags:#x} (render target {}, unordered access {}), {}{at}, state {state:#x}", + d.Width, + d.Height, + d.DepthOrArraySize, + d.MipLevels, + d.Format.0, + flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0 != 0, + flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0, + if kept { "kept in step with the title's memory (uploaded from it)" } else { "not kept in step with the title's memory (its contents are the GPU's)" } + ), + } +} + +/// The PC texture went for good. +pub fn forget(res: usize) { + if on() { + VOLS.lock().unwrap().remove(&res); + } +} + +/// `res` (any resource) is written by `what` (`copy`: a copy, which promotes a texture in COMMON +/// to COPY_DEST): logged if it is a 3D texture (the first `WRITES_LOGGED` times, then every +/// power of two). +pub fn wrote(res: usize, copy: bool, what: impl FnOnce() -> String) { + if !on() || res == 0 { + return; + } + let (n, k) = { + let mut g = VOLS.lock().unwrap(); + let Some(v) = g.get_mut(&res) else { return }; + v.writes += 1; + if copy && v.states.len() == 1 && v.states[0] == D3D12_RESOURCE_STATE_COMMON { + v.promoted = true; + } + (v.n, v.writes) + }; + if k <= WRITES_LOGGED || k.is_power_of_two() { + crate::xlog_info!("D3D12.X: 3D texture lut{n} {res:#x} written (#{k}): {}", what()); + } +} + +/// A shader resource view `v` (None: the default one) of `res` went into console slot `cpu`, T# +/// index `index`. +pub fn viewed(res: usize, rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>, index: u32, cpu: u64) { + if !on() { + return; + } + if rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D { + return slot_reused(index, cpu, res, || format!("a view of {res:#x} (dimension {}, {}x{}, format {})", rd.Dimension.0, rd.Width, rd.Height, rd.Format.0)); + } + let Some(n) = VOLS.lock().unwrap().get(&res).map(|v| v.n) else { return }; + INDICES.lock().unwrap().insert(index, n); + let view = match v { + // SAFETY: the union member the view dimension names + Some(v) if v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE3D => unsafe { + let t = v.Anonymous.Texture3D; + format!("view format {}, mips {} (+{}), min LOD clamp {}, component mapping {:#x}", v.Format.0, t.MostDetailedMip, t.MipLevels as i32, t.ResourceMinLODClamp, v.Shader4ComponentMapping) + }, + Some(v) => format!("view dimension {} (not 3D), format {}", v.ViewDimension.0, v.Format.0), + None => format!("the default view (format {}, all {} mips)", rd.Format.0, rd.MipLevels), + }; + crate::xlog_info!("D3D12.X: 3D texture lut{n} {res:#x}: shader resource view in console slot {cpu:#x} (T# index {index}): {view}"); +} + +/// T# indices that hold a shader resource view of a 3D texture → its number +static INDICES: Mutex> = Mutex::new(BTreeMap::new()); + +/// Console slot `cpu` (T# index `index`) gets `what`, not a view of a 3D texture: logged when it +/// held one – a T# the title copied out of the slot before now names `what` on the PC, where the +/// console's copy still names the 3D texture's memory. +pub fn slot_reused(index: u32, cpu: u64, res: usize, what: impl FnOnce() -> String) { + if !on() { + return; + } + let same = |n: u64| VOLS.lock().unwrap().get(&res).is_some_and(|v| v.n == n); + let Some(n) = INDICES.lock().unwrap().get(&index).copied().filter(|&n| !same(n)) else { return }; + INDICES.lock().unwrap().remove(&index); + crate::xlog_info!("D3D12.X: 3D texture lut{n}: console slot {cpu:#x} (T# index {index}), which held a view of it, now holds {}", what()); +} + +/// The title recorded `transitions` (resource, subresource, state after) on PC list `list`. +pub fn note_transitions(list: usize, transitions: &[(usize, u32, D3D12_RESOURCE_STATES)]) { + if !on() || transitions.is_empty() { + return; + } + let ours: Vec<_> = { + let g = VOLS.lock().unwrap(); + transitions.iter().filter(|t| g.contains_key(&t.0)).copied().collect() + }; + if !ours.is_empty() { + NOTES.lock().unwrap().entry(list).or_default().extend(ours); + } +} + +/// PC list `list` records anew. +pub fn list_reset(list: usize) { + if on() { + NOTES.lock().unwrap().remove(&list); + } +} + +/// PC lists `lists` were submitted in this order: their transitions apply. +pub fn submitted(lists: &[*mut c_void]) { + if !on() { + return; + } + let notes: Vec<_> = { + let g = NOTES.lock().unwrap(); + if g.is_empty() { return } + lists.iter().filter_map(|&l| g.get(&(l as usize))).flatten().copied().collect() + }; + if notes.is_empty() { + return; + } + let mut g = VOLS.lock().unwrap(); + for (res, sub, after) in notes { + if let Some(v) = g.get_mut(&res) { + let mips = unsafe { desc_of(res) }.map_or(1, |d| d.MipLevels.max(1) as usize); + super::title_textures::apply_transition(&mut v.states, mips, sub, after); + v.promoted = false; + } + } +} + +/// The 3D textures to read back at this dump: (tag, texture, its desc, the state subresource 0 +/// is in); the others are logged with why not. +pub unsafe fn to_dump() -> Vec<(String, ID3D12Resource, D3D12_RESOURCE_DESC, D3D12_RESOURCE_STATES)> { + let g = VOLS.lock().unwrap(); + crate::xlog_info!("D3D12.X: 3D texture dump: {} 3D textures live", g.len()); + let mut out = Vec::new(); + for (&res, v) in g.iter() { + let p = res as *mut c_void; + let Some(r) = ID3D12Resource::from_raw_borrowed(&p) else { continue }; + let d = r.GetDesc(); + let why = if d.Width > SIDE_MOST || d.Height as u64 > SIDE_MOST || d.DepthOrArraySize as u64 > SIDE_MOST { + Some("larger than 64 on a side".to_string()) + } else if texel_floats(d.Format, &[0; 16]).is_none() { + Some(format!("format {} is not decoded here", d.Format.0)) + } else if v.promoted { + Some("its state is not known (copied into from COMMON, so in COPY_DEST)".into()) + } else if out.len() >= DUMPED_MOST { + Some(format!("past the {DUMPED_MOST} read back")) + } else { + None + }; + let state = v.states[0]; + match why { + Some(w) => crate::xlog_info!("D3D12.X: 3D texture dump: lut{} {res:#x} {}x{}x{} format {} (state {:#x}): not read back – {w}", v.n, d.Width, d.Height, d.DepthOrArraySize, d.Format.0, state.0), + None => out.push((format!("lut{}_{}x{}x{}_f{}", v.n, d.Width, d.Height, d.DepthOrArraySize, d.Format.0), r.clone(), d, state)), + } + } + out +} + +/// Whether a copy from a texture in `state` needs a transition to COPY_SOURCE first (COMMON is +/// promoted to it implicitly; a read state that has COPY_SOURCE in it is one already). +pub fn needs_transition(state: D3D12_RESOURCE_STATES) -> bool { + state != D3D12_RESOURCE_STATE_COMMON && state.0 & D3D12_RESOURCE_STATE_COPY_SOURCE.0 == 0 +} + +/// A texel of `format` (its first `targets::texel_bytes` bytes of `t`) as four floats, as the +/// texture stores it (sRGB not linearised; missing channels 0, missing alpha 1). None: a format +/// not decoded here (block-compressed ones among them). +pub fn texel_floats(format: DXGI_FORMAT, t: &[u8]) -> Option<[f32; 4]> { + use super::present::{half_float, small_float}; + if t.len() < super::targets::texel_bytes(format) { + return None; + } + let u16_at = |i: usize| u16::from_le_bytes([t[i], t[i + 1]]); + let u32_at = |i: usize| u32::from_le_bytes([t[i], t[i + 1], t[i + 2], t[i + 3]]); + let h = |i: usize| half_float(u16_at(i)); + let f = |i: usize| f32::from_bits(u32_at(i)); + let un8 = |i: usize| t[i] as f32 / 255.0; + let un16 = |i: usize| u16_at(i) as f32 / 65535.0; + Some(match format { + DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_R8G8B8A8_UNORM_SRGB | DXGI_FORMAT_R8G8B8A8_TYPELESS => [un8(0), un8(1), un8(2), un8(3)], + DXGI_FORMAT_B8G8R8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM_SRGB | DXGI_FORMAT_B8G8R8A8_TYPELESS => [un8(2), un8(1), un8(0), un8(3)], + DXGI_FORMAT_B8G8R8X8_UNORM | DXGI_FORMAT_B8G8R8X8_UNORM_SRGB => [un8(2), un8(1), un8(0), 1.0], + DXGI_FORMAT_R8G8B8A8_SNORM => { + let s = |i: usize| (t[i] as i8 as f32 / 127.0).max(-1.0); + [s(0), s(1), s(2), s(3)] + } + DXGI_FORMAT_R10G10B10A2_UNORM | DXGI_FORMAT_R10G10B10A2_TYPELESS => { + let v = u32_at(0); + [(v & 0x3FF) as f32 / 1023.0, (v >> 10 & 0x3FF) as f32 / 1023.0, (v >> 20 & 0x3FF) as f32 / 1023.0, (v >> 30) as f32 / 3.0] + } + DXGI_FORMAT_R11G11B10_FLOAT => { + let v = u32_at(0); + [small_float(v & 0x7FF, 6), small_float(v >> 11 & 0x7FF, 6), small_float(v >> 22, 5), 1.0] + } + DXGI_FORMAT_R9G9B9E5_SHAREDEXP => { + let v = u32_at(0); + let scale = 2f32.powi((v >> 27) as i32 - 15 - 9); + [(v & 0x1FF) as f32 * scale, (v >> 9 & 0x1FF) as f32 * scale, (v >> 18 & 0x1FF) as f32 * scale, 1.0] + } + DXGI_FORMAT_R16G16B16A16_FLOAT | DXGI_FORMAT_R16G16B16A16_TYPELESS => [h(0), h(2), h(4), h(6)], + DXGI_FORMAT_R16G16B16A16_UNORM => [un16(0), un16(2), un16(4), un16(6)], + DXGI_FORMAT_R32G32B32A32_FLOAT | DXGI_FORMAT_R32G32B32A32_TYPELESS => [f(0), f(4), f(8), f(12)], + DXGI_FORMAT_R32G32_FLOAT => [f(0), f(4), 0.0, 1.0], + DXGI_FORMAT_R16G16_FLOAT => [h(0), h(2), 0.0, 1.0], + DXGI_FORMAT_R16G16_UNORM => [un16(0), un16(2), 0.0, 1.0], + DXGI_FORMAT_R8G8_UNORM => [un8(0), un8(1), 0.0, 1.0], + DXGI_FORMAT_R32_FLOAT => [f(0), 0.0, 0.0, 1.0], + DXGI_FORMAT_R16_FLOAT => [h(0), 0.0, 0.0, 1.0], + DXGI_FORMAT_R16_UNORM => [un16(0), 0.0, 0.0, 1.0], + DXGI_FORMAT_R8_UNORM => [un8(0), 0.0, 0.0, 1.0], + _ => return None, + }) +} + +/// The 8 corners of a `w` × `h` × `d` volume and its centre, in that order (x fastest). +fn probe_points(w: usize, h: usize, d: usize) -> [(usize, usize, usize); 9] { + let (x, y, z) = (w.max(1) - 1, h.max(1) - 1, d.max(1) - 1); + [(0, 0, 0), (x, 0, 0), (0, y, 0), (x, y, 0), (0, 0, z), (x, 0, z), (0, y, z), (x, y, z), (w / 2, h / 2, d / 2)] +} + +/// Byte offset of texel (x, y, z) in a footprint of `h` rows of `pitch` bytes per depth slice. +fn texel_offset(x: usize, y: usize, z: usize, h: usize, pitch: usize, bytes: usize) -> usize { + (z * h + y) * pitch + x * bytes +} + +/// Least and greatest of each channel over `texels`. +fn channel_range(texels: impl Iterator) -> ([f32; 4], [f32; 4]) { + let (mut lo, mut hi) = ([f32::INFINITY; 4], [f32::NEG_INFINITY; 4]); + for t in texels { + for c in 0..4 { + lo[c] = lo[c].min(t[c]); + hi[c] = hi[c].max(t[c]); + } + } + (lo, hi) +} + +fn text(t: [f32; 4]) -> String { + format!("({:.4}, {:.4}, {:.4}, {:.4})", t[0], t[1], t[2], t[3]) +} + +/// A 24-bit BMP of `w` × `h` colours (rows top first). +fn bmp(w: usize, h: usize, rgb: &[[u8; 3]]) -> Vec { + let row = (w * 3).div_ceil(4) * 4; + let size = (54 + row * h) as u32; + let mut b = Vec::with_capacity(size as usize); + b.extend_from_slice(b"BM"); + for v in [size, 0, 54, 40, w as u32, h as u32] { + b.extend_from_slice(&v.to_le_bytes()); + } + b.extend_from_slice(&1u16.to_le_bytes()); + b.extend_from_slice(&24u16.to_le_bytes()); + b.extend_from_slice(&[0; 24]); + for y in (0..h).rev() { + let start = b.len(); + for c in &rgb[y * w..(y + 1) * w] { + b.extend_from_slice(&[c[2], c[1], c[0]]); + } + b.resize(start + row, 0); + } + b +} + +/// A dump `tag` (`to_dump`) read back into `rb` at `fp` (mip 0, all its depth slices): its texel +/// values logged and three depth slices written as pictures. +pub unsafe fn log_values(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, tag: &str) { + let mut p: *mut c_void = std::ptr::null_mut(); + if rb.Map(0, None, Some(&mut p)).is_err() || p.is_null() { + return; + } + let f = &fp.Footprint; + let (w, h, d, pitch) = (f.Width as usize, f.Height as usize, f.Depth as usize, f.RowPitch as usize); + let bytes = super::targets::texel_bytes(f.Format); + let len = (rb.GetDesc().Width as usize).saturating_sub(fp.Offset as usize); + let data = std::slice::from_raw_parts((p as *const u8).add(fp.Offset as usize), len); + let at = |x: usize, y: usize, z: usize| data.get(texel_offset(x, y, z, h, pitch, bytes)..).and_then(|t| texel_floats(f.Format, t)); + let points: Vec = probe_points(w, h, d).iter().map(|&(x, y, z)| format!("({x},{y},{z})={}", at(x, y, z).map_or("?".into(), text))).collect(); + let (lo, hi) = channel_range((0..d).flat_map(|z| (0..h).flat_map(move |y| (0..w).map(move |x| (x, y, z)))).filter_map(|(x, y, z)| at(x, y, z))); + crate::xlog_info!("D3D12.X: 3D texture dump: {tag}: corners and centre (x,y,z)=(r,g,b,a): {}", points.join(" ")); + crate::xlog_info!("D3D12.X: 3D texture dump: {tag}: over mip 0, least {} greatest {}", text(lo), text(hi)); + let dir = crate::state::boot().map(|b| b.logs_dir()); + let mut slices = vec![0, d / 2, d.max(1) - 1]; + slices.dedup(); + for k in slices { + let rgb: Vec<[u8; 3]> = (0..h) + .flat_map(|y| (0..w).map(move |x| (x, y))) + .map(|(x, y)| at(x, y, k).map_or([0; 3], |t| [0, 1, 2].map(|c| if t[c].is_nan() { 255 } else { (t[c].clamp(0.0, 1.0) * 255.0).round() as u8 }))) + .collect(); + if let Some(dir) = &dir { + let path = dir.join(format!("{tag}_slice{k}.bmp")); + let _ = std::fs::write(&path, bmp(w, h, &rgb)); + crate::xlog_info!("D3D12.X: 3D texture dump: {tag}: depth slice {k} written to {}", path.display()); + } + } + rb.Unmap(0, None); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Texels of the formats a lookup table has, as the floats a shader would read. + #[test] + fn lut_texels_decode_to_floats() { + assert_eq!(texel_floats(DXGI_FORMAT_R8G8B8A8_UNORM, &[0, 255, 51, 255]), Some([0.0, 1.0, 0.2, 1.0])); + assert_eq!(texel_floats(DXGI_FORMAT_B8G8R8A8_UNORM, &[0, 255, 51, 255]), Some([0.2, 1.0, 0.0, 1.0])); + // R10G10B10A2: r 1023 in the low bits, g 0, b 0, a 3 + assert_eq!(texel_floats(DXGI_FORMAT_R10G10B10A2_UNORM, &(0x3FFu32 | 3 << 30).to_le_bytes()), Some([1.0, 0.0, 0.0, 1.0])); + // R11G11B10: 1.0 = exponent 15, no mantissa, in each of r (bits 0-10) and b (22-31) + let one11 = 15u32 << 6; + let one10 = 15u32 << 5; + assert_eq!(texel_floats(DXGI_FORMAT_R11G11B10_FLOAT, &(one11 | one10 << 22).to_le_bytes()), Some([1.0, 0.0, 1.0, 1.0])); + // half floats 1.0, 0.5, 0, -2 + let hs: Vec = [0x3C00u16, 0x3800, 0, 0xC000].iter().flat_map(|v| v.to_le_bytes()).collect(); + assert_eq!(texel_floats(DXGI_FORMAT_R16G16B16A16_FLOAT, &hs), Some([1.0, 0.5, 0.0, -2.0])); + let fs: Vec = [0.25f32, 1.0, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()).collect(); + assert_eq!(texel_floats(DXGI_FORMAT_R32G32B32A32_FLOAT, &fs), Some([0.25, 1.0, 0.0, 1.0])); + // R9G9B9E5: mantissa 256 with exponent 16: 256 * 2^(16 - 24) = 1.0 for r + assert_eq!(texel_floats(DXGI_FORMAT_R9G9B9E5_SHAREDEXP, &(256u32 | 16 << 27).to_le_bytes()), Some([1.0, 0.0, 0.0, 1.0])); + assert_eq!(texel_floats(DXGI_FORMAT_BC1_UNORM, &[0; 16]), None); + assert_eq!(texel_floats(DXGI_FORMAT_R16G16B16A16_FLOAT, &[0; 4]), None, "too few bytes"); + } + + /// The corners and centre of a volume, where a texel lies in a footprint, and the channels' + /// ranges; which states a copy needs a transition from. + #[test] + fn lut_probes_and_ranges() { + let p = probe_points(32, 16, 8); + assert_eq!(p[0], (0, 0, 0)); + assert_eq!(p[7], (31, 15, 7)); + assert_eq!(p[6], (0, 15, 7)); + assert_eq!(p[8], (16, 8, 4)); + assert_eq!(probe_points(1, 1, 1), [(0, 0, 0); 9]); + // 32 wide RGBA16F: 256-byte rows, 16 rows a slice + assert_eq!(texel_offset(3, 2, 1, 16, 256, 8), (16 + 2) * 256 + 24); + let (lo, hi) = channel_range([[0.0, 1.0, 1.0, 1.0], [0.5, 0.25, 1.0, 1.0]].into_iter()); + assert_eq!((lo, hi), ([0.0, 0.25, 1.0, 1.0], [0.5, 1.0, 1.0, 1.0])); + assert!(!needs_transition(D3D12_RESOURCE_STATE_COMMON)); + assert!(!needs_transition(D3D12_RESOURCE_STATE_GENERIC_READ)); + assert!(needs_transition(D3D12_RESOURCE_STATES(0xC0))); + assert!(needs_transition(D3D12_RESOURCE_STATE_UNORDERED_ACCESS)); + // a 2 x 1 picture: a row padded to 8 bytes, bottom row first + let b = bmp(2, 1, &[[1, 2, 3], [4, 5, 6]]); + assert_eq!(b.len(), 54 + 8); + assert_eq!(&b[54..], &[3, 2, 1, 6, 5, 4, 0, 0]); + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 60c0daf9f9..2c1daeb7a3 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -13,34 +13,54 @@ mod alloc_pool; pub use alloc_pool::AllocatorSubmitStats; mod build_queue; pub mod bind; +mod bvh_want; +mod capture; pub mod console_heap; pub mod console_list; +pub mod clamp; +mod depth_uav; pub mod device_x; pub mod dxgi_device; mod cpu_writes; pub mod dred; mod fence_x; +pub mod file_reads; pub mod frame; pub(crate) mod gfx_records; +mod gpu_profile; +mod gpu_times; pub mod guard; +mod indirect_guard; mod late_release; pub mod layout; pub mod list_x; +mod look_stats; +mod lut3d; pub mod memory_report; pub mod null; +mod placements; pub mod present; pub mod pso_async; mod queue_submit; mod pso_manifest; pub mod real; +mod scatter; mod shader_cache_session; +mod sharded; +mod small_tex; pub mod sparse; mod standin; +mod targets; +mod watch; pub mod title_list; +mod submit_cost; +mod texture_upload; pub mod title_textures; +pub mod view_want; mod uma_driver; mod used_journal; pub mod vram; +mod worker_pool; use std::ffi::c_void; use std::sync::OnceLock; diff --git a/crates/xcl/src/hle/d3d12x/placements.rs b/crates/xcl/src/hle/d3d12x/placements.rs new file mode 100644 index 0000000000..696e9dcfe5 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/placements.rs @@ -0,0 +1,781 @@ +//! The live placements of the title's textures on video memory shared by address (`vram`): each +//! PC texture, the title pages it has (`vram::owned_pages`: tile i on the page at `start + i * +//! 64 KiB`), its kind and when it came. Two textures on the same pages share video memory as on +//! the console – what one is written with, the other shows. +//! +//! `XCL_PLACE_CHECK=1` logs placements over the pages of a live texture (the first 32 in full) +//! and counts them every 2 s, by how their pages lie and by kind. +//! +//! A placement over other pages of a live target supersedes it (`supersedes`; `XCL_PLACE_RETIRE=0` +//! turns it off): what is uploaded into or drawn to the newer one then no longer shows in the +//! older one's tiles. Its tiles leave the shared pages once the queues are past the work submitted +//! before (`late_release::hold_unmap`), and come back when the title uses it again (a barrier or a +//! copy of it: `note_use`) or releases the newer ones over it while it still holds it. + +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::Mutex; +use std::time::Instant; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::{ID3D12Resource, D3D12_RESOURCE_DESC}; + +/// What the GPU does with a placed texture. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Kind { + /// a render target, depth buffer or UAV texture (`vram::gpu_owned`) + Target, + /// sampled: kept in step with the title's memory (`title_textures`) + Sampled, +} + +impl Kind { + fn word(self) -> &'static str { + match self { + Kind::Target => "target", + Kind::Sampled => "sampled", + } + } +} + +/// Where a placement's video memory is: the title's pages of a device, or an arena (`vram`). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Backing { + Pages(usize), + Arena(u64), +} + +/// The PC description of a placed texture, for the log. +#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] +pub(super) struct Desc { + pub width: u64, + pub height: u32, + pub depth: u16, + pub mips: u16, + pub format: i32, + pub flags: i32, +} + +impl Desc { + pub(super) fn of(d: &D3D12_RESOURCE_DESC) -> Desc { + Desc { width: d.Width, height: d.Height, depth: d.DepthOrArraySize, mips: d.MipLevels, format: d.Format.0, flags: d.Flags.0 } + } +} + +impl std::fmt::Display for Desc { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}x{}x{} format {} flags {:#x} {} mips", self.width, self.height, self.depth, self.format, self.flags, self.mips) + } +} + +#[derive(Clone, Debug)] +struct Placement { + /// the title address it was placed at (`vram::canonical_va`) + va: usize, + /// its title pages `[start, end)` (none of its own: `start == end`) + start: usize, + end: usize, + backing: Backing, + kind: Kind, + seq: u64, + at: Instant, + desc: Desc, + /// the title released it: it goes on the PC once the GPU is past it (`late_release`) + released: bool, + /// false: superseded, its tiles off the shared pages (or about to be) + mapped: bool, + /// the newer placements it is superseded by + under: Vec, + /// the older ones it supersedes + over: Vec, +} + +/// How a newer placement's pages lie to an older one's. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Overlap { + /// the same pages: one memory under two descriptions + Same, + /// all its pages are the older one's + Inside, + /// all the older one's pages are its + Around, + /// some of each one's pages are the other's + Partial, +} + +impl Overlap { + fn words(self) -> &'static str { + match self { + Overlap::Same => "on the same pages as", + Overlap::Inside => "inside", + Overlap::Around => "around", + Overlap::Partial => "partly over", + } + } +} + +/// How placement `new`'s pages lie to `old`'s (None: they share no video memory). Placements at +/// one address share their tiles past their own pages too (`vram::Pages::extra_pages`). +fn overlap(new: &Placement, old: &Placement) -> Option { + if new.backing != old.backing { + return None; + } + let shared = new.start < old.end && old.start < new.end; + if !shared && new.va != old.va { + return None; + } + Some(if (new.start, new.end) == (old.start, old.end) { + Overlap::Same + } else if old.start <= new.start && new.end <= old.end { + Overlap::Inside + } else if new.start <= old.start && old.end <= new.end { + Overlap::Around + } else { + Overlap::Partial + }) +} + +/// Whether a newer placement lying `overlap` to an older one supersedes it: a target the title +/// still holds, mapped, on the title's pages (an arena has no tiles to unmap), and on other pages +/// than the newer one (the same pages are one memory under two descriptions, shared as on the +/// console). An older sampled texture is retired by `title_textures` (under a sampled one: +/// `Table::insert`; under a target: `retire_overlapping`). +pub(super) fn supersedes(overlap: Overlap, old_kind: Kind, old_backing: Backing, old_released: bool, old_mapped: bool) -> bool { + overlap != Overlap::Same && old_kind == Kind::Target && matches!(old_backing, Backing::Pages(_)) && !old_released && old_mapped +} + +/// A placement over the pages of an older live one. +#[derive(Clone, Debug)] +pub(super) struct Case { + pub old: usize, + pub overlap: Overlap, + /// (the newer one's, the older one's) + pub kinds: (Kind, Kind), + /// placements between them + pub ago: u64, + pub ms: u64, + /// the older one was released by the title and is not gone on the PC yet + pub released: bool, + pub old_desc: Desc, + /// the older one's (address, first page, end of its pages) + pub old_range: (usize, usize, usize), + pub old_seq: u64, + /// the newer one supersedes it + pub retired: bool, +} + +/// the placements are found by the 2 MiB blocks of the title's addresses they cover +const BLOCK_SHIFT: usize = 21; + +#[derive(Default)] +struct Registry { + live: HashMap, + /// block → the placements over it + blocks: BTreeMap>, + seq: u64, + /// the superseded ones the title holds (`SUPERSEDED`) + unmapped: usize, +} + +/// What a placement found (`Registry::place`). +#[derive(Default)] +struct Placed { + seq: u64, + /// with `look`: the older ones on its video memory, oldest first + cases: Vec, + /// the older ones it supersedes + victims: Vec, + /// ones to map again (`Registry::release`) + remap: Vec, +} + +impl Registry { + /// The blocks of `p`'s pages and of its address. + fn blocks_of(p: &Placement) -> std::ops::RangeInclusive { + let last = if p.end > p.start { p.end - 1 } else { p.start }; + (p.va.min(p.start) >> BLOCK_SHIFT)..=(last.max(p.va) >> BLOCK_SHIFT) + } + + /// The live placements but `p` itself that share video memory with `p`. + fn over(&self, res: usize, p: &Placement) -> Vec<(usize, Overlap)> { + let mut out: Vec<(usize, Overlap)> = Vec::new(); + for b in Self::blocks_of(p) { + for &o in self.blocks.get(&b).into_iter().flatten() { + if o == res || out.iter().any(|&(k, _)| k == o) { + continue; + } + if let Some(ov) = self.live.get(&o).and_then(|old| overlap(p, old)) { + out.push((o, ov)); + } + } + } + out + } + + /// Texture `res` placed; with `look`, the older live ones it shares video memory with, and + /// with `retire` the ones it supersedes (`supersedes`). + #[allow(clippy::too_many_arguments)] + fn place(&mut self, res: usize, va: usize, (start, end): (usize, usize), backing: Backing, kind: Kind, desc: Desc, now: Instant, look: bool, retire: bool) -> Placed { + // (an object's address again: the one before went without a word) + let remap = self.remove(res).unwrap_or_default(); + self.seq += 1; + let mut p = Placement { va, start, end: end.max(start), backing, kind, seq: self.seq, at: now, desc, released: false, mapped: true, under: Vec::new(), over: Vec::new() }; + let found = if look || retire { self.over(res, &p) } else { Vec::new() }; + let mut out = Placed { seq: self.seq, remap, ..Default::default() }; + for &(o, overlap) in &found { + let Some(old) = self.live.get_mut(&o) else { continue }; + let retired = retire && supersedes(overlap, old.kind, old.backing, old.released, old.mapped); + if look { + out.cases.push(Case { + old: o, + overlap, + kinds: (kind, old.kind), + ago: p.seq - old.seq, + ms: now.saturating_duration_since(old.at).as_millis() as u64, + released: old.released, + old_desc: old.desc, + old_range: (old.va, old.start, old.end), + old_seq: old.seq, + retired, + }); + } + if retired { + old.mapped = false; + old.under.push(res); + p.over.push(o); + self.unmapped += 1; + out.victims.push(o); + } + } + out.cases.sort_by_key(|c| c.old_seq); + out.victims.sort_by_key(|o| self.live.get(o).map_or(0, |q| q.seq)); + for b in Self::blocks_of(&p) { + self.blocks.entry(b).or_default().push(res); + } + self.live.insert(res, p); + out + } + + /// The title released `res`; it stays until it is gone on the PC (`remove`). Returns the older + /// ones it superseded that are to be mapped again: the title holds them, and no other newer one + /// it holds lies over other pages of them (those supersede them from now on). + fn release(&mut self, res: usize) -> Vec { + let Some(p) = self.live.get_mut(&res).filter(|p| !p.released) else { return Vec::new() }; + p.released = true; + if !p.mapped { + // (its tiles go with it: `vram::forget`) + self.unmapped -= 1; + } + let (over, under) = (std::mem::take(&mut p.over), std::mem::take(&mut p.under)); + for n in under { + if let Some(q) = self.live.get_mut(&n) { + q.over.retain(|&r| r != res); + } + } + let mut remap = Vec::new(); + for o in over { + let Some(old) = self.live.get_mut(&o) else { continue }; + old.under.retain(|&r| r != res); + if !old.under.is_empty() || old.released || old.mapped { + continue; + } + let old = old.clone(); + let newer: Vec = self + .over(o, &old) + .into_iter() + .filter(|&(n, ov)| ov != Overlap::Same && self.live.get(&n).is_some_and(|q| q.seq > old.seq && !q.released)) + .map(|(n, _)| n) + .collect(); + for n in &newer { + if let Some(q) = self.live.get_mut(n) { + q.over.push(o); + } + } + if let Some(old) = self.live.get_mut(&o) { + if newer.is_empty() { + old.mapped = true; + self.unmapped -= 1; + remap.push(o); + } else { + old.under = newer; + } + } + } + remap + } + + /// `res` is gone on the PC (None: it was not here); what to map again, as `release`. + fn remove(&mut self, res: usize) -> Option> { + let remap = self.release(res); + let p = self.live.remove(&res)?; + for b in Self::blocks_of(&p) { + if let Some(v) = self.blocks.get_mut(&b) { + v.retain(|&r| r != res); + if v.is_empty() { + self.blocks.remove(&b); + } + } + } + Some(remap) + } + + /// The title uses superseded `res` again: it is mapped again (the title shares the memory, as + /// the console lets it). Returns the newer ones it was superseded by (none: it was not). + fn use_again(&mut self, res: usize) -> Vec { + let Some(p) = self.live.get_mut(&res).filter(|p| !p.mapped && !p.released) else { return Vec::new() }; + p.mapped = true; + self.unmapped -= 1; + let under = std::mem::take(&mut p.under); + for n in &under { + if let Some(q) = self.live.get_mut(n) { + q.over.retain(|&r| r != res); + } + } + under + } + + /// Whether `res` is superseded (its tiles are to leave the shared pages). + fn superseded(&self, res: usize) -> bool { + self.live.get(&res).is_some_and(|p| !p.mapped && !p.released) + } +} + +static REGISTRY: Mutex> = Mutex::new(None); + +/// `XCL_PLACE_CHECK=1`: placements over the pages of live ones logged and counted. +pub(super) fn check() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var("XCL_PLACE_CHECK").is_ok_and(|v| v.trim() == "1"); + if on { + crate::xlog_info!("D3D12.X: XCL_PLACE_CHECK=1 - placements over the pages of live textures are logged (the first 32) and counted every 2 s"); + } + on + }) +} + +/// `XCL_PLACE_RETIRE` (on; `=0` off): a placement over other pages of a live target supersedes it. +pub(super) fn retire() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = !std::env::var("XCL_PLACE_RETIRE").is_ok_and(|v| v.trim() == "0"); + if !on { + crate::xlog_info!("D3D12.X: XCL_PLACE_RETIRE=0 - a target stays on the pages of a newer placement over it"); + } + on + }) +} + +/// superseded placements the title holds (`Registry::unmapped`): with none, `note_use` takes no lock +static SUPERSEDED: AtomicUsize = AtomicUsize::new(0); + +/// The counts of the 2 s line: [made, aliases at the same range, over released ones not gone +/// yet, partial (tt, st, ts, ss), one inside the other (tt, st, ts, ss), aliases of a sampled +/// texture over a target, older ones superseded, their tiles taken off the shared pages, +/// superseded ones used again] – tt: a target over a target, st: a sampled texture over a +/// target, ... +static COUNTS: [AtomicU64; 15] = [const { AtomicU64::new(0) }; 15]; +static LAST_LINE: Mutex> = Mutex::new(None); + +/// The kinds' place in `COUNTS`' groups of four. +fn kinds_index((new, old): (Kind, Kind)) -> usize { + (new == Kind::Sampled) as usize + 2 * (old == Kind::Sampled) as usize +} + +/// The 2 s line of `counts` (`COUNTS`). +fn counts_line(c: &[u64; 15]) -> String { + let p = c[3] + c[4] + c[5] + c[6]; + let i = c[7] + c[8] + c[9] + c[10]; + format!( + "D3D12.X: placements (2 s): {} made, {} aliases at the same range ({} sampled over a target), {p} partial overlaps (tt/st/ts/ss {}/{}/{}/{}), {i} one inside the other (tt/st/ts/ss {}/{}/{}/{}), {} over ones the title released (not gone yet); {} older ones superseded, {} retired (off the shared pages), {} used again", + c[0], c[1], c[11], c[3], c[4], c[5], c[6], c[7], c[8], c[9], c[10], c[2], c[12], c[13], c[14] + ) +} + +/// The full line of a case (the first 32). +fn case_line(res: usize, seq: u64, kind: Kind, desc: &Desc, (va, start, end): (usize, usize, usize), c: &Case) -> String { + format!( + "D3D12.X: placement #{seq} ({} {desc}, object {res:#x}) at {va:#x}, pages {start:#x}..{end:#x}, is {} #{} ({} {}, object {:#x}) at {:#x}, pages {:#x}..{:#x}, placed {} placements / {} ms before{}{}", + kind.word(), + c.overlap.words(), + c.old_seq, + c.kinds.1.word(), + c.old_desc, + c.old, + c.old_range.0, + c.old_range.1, + c.old_range.2, + c.ago, + c.ms, + if c.released { ", released by the title (not gone yet)" } else { "" }, + if c.retired { "; it supersedes it" } else { "" } + ) +} + +/// The cases of a placement into `COUNTS`, the first 32 logged; the 2 s line when it is due. +fn note(res: usize, seq: u64, kind: Kind, desc: &Desc, range: (usize, usize, usize), cases: &[Case]) { + static LOGGED: AtomicU64 = AtomicU64::new(0); + COUNTS[0].fetch_add(1, Ordering::Relaxed); + for c in cases { + let k = match c.overlap { + Overlap::Same => 1, + Overlap::Partial => 3 + kinds_index(c.kinds), + Overlap::Inside | Overlap::Around => 7 + kinds_index(c.kinds), + }; + COUNTS[k].fetch_add(1, Ordering::Relaxed); + if c.overlap == Overlap::Same && c.kinds == (Kind::Sampled, Kind::Target) { + COUNTS[11].fetch_add(1, Ordering::Relaxed); + } + if c.released { + COUNTS[2].fetch_add(1, Ordering::Relaxed); + } + if c.retired { + COUNTS[12].fetch_add(1, Ordering::Relaxed); + } + // (an alias in full only of another kind: a sampled one is uploaded over what the GPU wrote) + if (c.overlap != Overlap::Same || c.kinds.0 != c.kinds.1) && LOGGED.fetch_add(1, Ordering::Relaxed) < 32 { + crate::xlog_info!("{}", case_line(res, seq, kind, desc, range, c)); + } + } + let now = Instant::now(); + let due = { + let mut last = LAST_LINE.lock().unwrap(); + let due = last.is_some_and(|t| now.duration_since(t).as_secs() >= 2); + if due || last.is_none() { + *last = Some(now); + } + due + }; + if due { + let c: [u64; 15] = std::array::from_fn(|k| COUNTS[k].swap(0, Ordering::Relaxed)); + crate::xlog_info!("{}", counts_line(&c)); + } +} + +/// A reference of XCL's own to placement `raw`, one the title holds (its release takes the +/// registry's lock first: `released`). Dropped outside that lock: it may be the last one. +unsafe fn resource(raw: usize) -> Option { + let p = raw as *mut c_void; + ID3D12Resource::from_raw_borrowed(&p).cloned() +} + +/// The superseded ones of `remap` go back on the shared pages (`vram::remap_if_unmapped`), under +/// the registry's lock: a deferred unmap (`unmap_if_superseded`) is before or after it. Returns +/// the references taken, to drop outside the lock. +unsafe fn map_again(remap: &[usize]) -> Vec { + let held: Vec = remap.iter().filter_map(|&o| resource(o)).collect(); + for r in &held { + super::vram::remap_if_unmapped(r); + } + held +} + +/// Texture `res` placed at title address `va` on `pages` (`[start, end)`: its own title pages), +/// its tiles mapped. Returns the older targets it supersedes: their tiles are to leave the shared +/// pages once the queues are past the work submitted before (`late_release::hold_unmap`). +pub(super) fn placed(res: usize, va: usize, pages: (usize, usize), backing: Backing, kind: Kind, desc: &D3D12_RESOURCE_DESC) -> Vec { + let (look, retire) = (check(), retire()); + let desc = Desc::of(desc); + let (out, victims, held) = { + let mut g = REGISTRY.lock().unwrap(); + let r = g.get_or_insert_with(Registry::default); + let out = r.place(res, va, pages, backing, kind, desc, Instant::now(), look, retire); + SUPERSEDED.store(r.unmapped, Ordering::Relaxed); + let victims: Vec = out.victims.iter().filter_map(|&o| unsafe { resource(o) }).collect(); + let held = unsafe { map_again(&out.remap) }; + (out, victims, held) + }; + drop(held); + if look { + note(res, out.seq, kind, &desc, (va, pages.0, pages.1.max(pages.0)), &out.cases); + } + victims +} + +/// What `f` does to the registry, and the ones it says to map again mapped again. +fn settle(f: impl FnOnce(&mut Registry) -> Vec) { + let held = { + let mut g = REGISTRY.lock().unwrap(); + let Some(r) = g.as_mut() else { return }; + let remap = f(r); + SUPERSEDED.store(r.unmapped, Ordering::Relaxed); + unsafe { map_again(&remap) } + }; + drop(held); +} + +/// The title released placed texture `res` (`vram::forget`, after its pages went idle): the +/// older targets only it superseded go back on the shared pages. +pub(super) fn released(res: usize) { + settle(|r| r.release(res)); +} + +/// Resource `res` is gone on the PC (or goes now). +pub(super) fn gone(res: usize) { + settle(|r| r.remove(res).unwrap_or_default()); +} + +/// A superseded target's tiles leave the shared pages (`late_release::hold_unmap`, the queues +/// past the work submitted before) – unless the title used it again in the meantime, released +/// it, or released the newer ones over it. +pub(super) unsafe fn unmap_if_superseded(res: &ID3D12Resource) { + let g = REGISTRY.lock().unwrap(); + if g.as_ref().is_some_and(|r| r.superseded(res.as_raw() as usize)) { + super::vram::unmap_superseded_target(res); + COUNTS[13].fetch_add(1, Ordering::Relaxed); + } +} + +/// The title uses `res` (a barrier, a copy): a superseded target goes back on the shared pages – +/// on the console the title may use both over one memory when it knows they share it. Logged +/// once for each pair (the first 64). The work recorded now waits for the mapping +/// (`vram::before_execute` at its submit). +pub(super) fn note_use(res: usize) { + if res == 0 || SUPERSEDED.load(Ordering::Relaxed) == 0 { + return; + } + static LOGGED: Mutex>> = Mutex::new(None); + let held = { + let mut g = REGISTRY.lock().unwrap(); + let Some(r) = g.as_mut() else { return }; + let under = r.use_again(res); + SUPERSEDED.store(r.unmapped, Ordering::Relaxed); + if under.is_empty() { + return; + } + COUNTS[14].fetch_add(1, Ordering::Relaxed); + if let Some(old) = r.live.get(&res) { + for n in &under { + let Some(new) = r.live.get(n) else { continue }; + let mut seen = LOGGED.lock().unwrap(); + let seen = seen.get_or_insert_with(Default::default); + if seen.len() < 64 && seen.insert((old.seq, new.seq)) { + crate::xlog_info!( + "D3D12.X: a superseded texture is used again: #{} ({} {}, object {res:#x}) at {:#x}, pages {:#x}..{:#x}, under #{} ({} {}, object {n:#x}) at {:#x}, pages {:#x}..{:#x}, placed {} placements later; it goes back on the shared pages", + old.seq, old.kind.word(), old.desc, old.va, old.start, old.end, new.seq, new.kind.word(), new.desc, new.va, new.start, new.end, new.seq - old.seq + ); + } + } + } + unsafe { map_again(&[res]) } + }; + drop(held); +} + +#[cfg(test)] +mod tests { + use super::*; + + const K64: usize = 0x1_0000; + const MIB: usize = 1 << 20; + + /// A placement looked at, not retiring: (its sequence number, its cases). + fn place(r: &mut Registry, res: usize, va: usize, pages: (usize, usize), kind: Kind) -> (u64, Vec) { + on(r, res, va, pages, Backing::Pages(1), kind) + } + + fn on(r: &mut Registry, res: usize, va: usize, pages: (usize, usize), backing: Backing, kind: Kind) -> (u64, Vec) { + let p = r.place(res, va, pages, backing, kind, Desc::default(), Instant::now(), true, false); + (p.seq, p.cases) + } + + /// A placement retiring, not looked at: (the ones it supersedes, the ones to map again). + fn retiring(r: &mut Registry, res: usize, at: usize, len: usize, kind: Kind) -> (Vec, Vec) { + let p = r.place(res, at, (at, at + len), Backing::Pages(1), kind, Desc::default(), Instant::now(), false, true); + assert!(p.cases.is_empty(), "not looked at"); + (p.victims, p.remap) + } + + /// The superseded ones the title holds, as the registry counts them and as they are. + fn superseded(r: &Registry) -> Vec { + let mut v: Vec = r.live.keys().copied().filter(|&k| r.superseded(k)).collect(); + v.sort_unstable(); + assert_eq!(v.len(), r.unmapped); + v + } + + fn overlaps(cases: &[Case]) -> Vec<(usize, Overlap)> { + cases.iter().map(|c| (c.old, c.overlap)).collect() + } + + /// Placements are classified by how their pages lie to the live ones'. + #[test] + fn a_placement_is_classified_by_its_pages() { + let mut r = Registry::default(); + let x = 0x40_0000_0000usize; + // a 14.4 MiB target, then: the same pages, an R8 target inside it, one partly over its end, + // one around all of it, one past it + assert!(place(&mut r, 1, x, (x, x + 0xe7_0000), Kind::Target).1.is_empty()); + assert_eq!(overlaps(&place(&mut r, 2, x, (x, x + 0xe7_0000), Kind::Target).1), [(1, Overlap::Same)]); + let (_, c) = place(&mut r, 3, x + 0xba_0000, (x + 0xba_0000, x + 0xe4_0000), Kind::Target); + assert_eq!(overlaps(&c), [(1, Overlap::Inside), (2, Overlap::Inside)]); + let (_, c) = place(&mut r, 4, x + 0xe0_0000, (x + 0xe0_0000, x + 0x120_0000), Kind::Sampled); + assert_eq!(overlaps(&c), [(1, Overlap::Partial), (2, Overlap::Partial), (3, Overlap::Partial)]); + assert_eq!(c[0].kinds, (Kind::Sampled, Kind::Target)); + let (_, c) = place(&mut r, 5, x - K64, (x - K64, x + 0x200_0000), Kind::Sampled); + assert_eq!(overlaps(&c), [(1, Overlap::Around), (2, Overlap::Around), (3, Overlap::Around), (4, Overlap::Around)]); + assert!(place(&mut r, 6, x + 0x200_0000, (x + 0x200_0000, x + 0x210_0000), Kind::Sampled).1.is_empty()); + } + + /// Ranges that only touch share nothing; nor do placements on other video memory. + #[test] + fn neighbours_and_other_memory_share_nothing() { + let mut r = Registry::default(); + let x = 0x10_0000_0000usize; + place(&mut r, 1, x, (x, x + 4 * MIB), Kind::Target); + assert!(place(&mut r, 2, x + 4 * MIB, (x + 4 * MIB, x + 8 * MIB), Kind::Target).1.is_empty()); + assert!(place(&mut r, 3, x - MIB, (x - MIB, x), Kind::Sampled).1.is_empty()); + // (another device's pages, an arena) + assert!(on(&mut r, 4, x, (x, x + 4 * MIB), Backing::Pages(2), Kind::Target).1.is_empty()); + assert!(on(&mut r, 5, x, (x, x + 4 * MIB), Backing::Arena(7), Kind::Target).1.is_empty()); + let (_, c) = on(&mut r, 6, x + MIB, (x + MIB, x + 2 * MIB), Backing::Arena(7), Kind::Target); + assert_eq!(overlaps(&c), [(5, Overlap::Inside)]); + } + + /// A texture at a 4 KiB-aligned address with no page of its own (`vram::owned_pages`) shares + /// tiles only with one at the same address. + #[test] + fn textures_without_pages_of_their_own_share_by_address() { + let mut r = Registry::default(); + let x = 0x20_0000_0000usize + 0x1000; + let first = x.next_multiple_of(K64); + place(&mut r, 1, x, (first, first), Kind::Sampled); + assert!(place(&mut r, 2, x + 0x2000, (first, first), Kind::Sampled).1.is_empty(), "another address: other tiles"); + assert_eq!(overlaps(&place(&mut r, 3, x, (first, first), Kind::Sampled).1), [(1, Overlap::Same)]); + // (one with pages from the next 64 KiB on) + assert_eq!(overlaps(&place(&mut r, 4, x, (first, first + K64), Kind::Target).1), [(1, Overlap::Around), (3, Overlap::Around)]); + } + + /// A placement over 2 MiB blocks is found from each of them, and once. + #[test] + fn a_large_placement_is_found_once_from_every_block() { + let mut r = Registry::default(); + let x = 0x30_0000_0000usize; + place(&mut r, 1, x, (x, x + 64 * MIB), Kind::Target); + for at in [x, x + 31 * MIB, x + 64 * MIB - K64] { + let (_, c) = place(&mut r, 100 + at, at, (at, at + K64), Kind::Sampled); + assert_eq!(overlaps(&c), [(1, Overlap::Inside)], "at {at:#x}"); + r.remove(100 + at); + } + } + + /// Sequence numbers and ages count placements; a released one is found until it is gone, and + /// an object's address placed again is a new placement. + #[test] + fn released_ones_stay_until_gone_and_sequence_numbers_count_placements() { + let mut r = Registry::default(); + let x = 0x50_0000_0000usize; + let (s1, _) = place(&mut r, 1, x, (x, x + 2 * MIB), Kind::Target); + place(&mut r, 2, x + 8 * MIB, (x + 8 * MIB, x + 9 * MIB), Kind::Target); + assert!(r.release(1).is_empty()); + let (s3, c) = place(&mut r, 3, x + MIB, (x + MIB, x + 3 * MIB), Kind::Sampled); + assert_eq!((s3 - s1, c.len(), c[0].ago, c[0].old_seq, c[0].released), (2, 1, 2, s1, true)); + assert!(r.remove(1).is_some() && r.remove(1).is_none()); + assert!(place(&mut r, 4, x, (x, x + MIB), Kind::Target).1.is_empty(), "1 is gone, 3 starts where 4 ends"); + // (the address of object 4 again, elsewhere: the old placement is not found) + let (_, c) = place(&mut r, 4, x + 8 * MIB, (x + 8 * MIB, x + 9 * MIB), Kind::Target); + assert_eq!(overlaps(&c), [(2, Overlap::Same)]); + assert!(place(&mut r, 5, x, (x, x + K64), Kind::Target).1.is_empty(), "object 4 was moved, object 3 starts past it"); + assert!(r.blocks.values().flatten().all(|res| r.live.contains_key(res))); + } + + /// The 2 s line's counts by kind: the newer one's first. + #[test] + fn the_counts_line_names_the_kinds_newer_first() { + assert_eq!(kinds_index((Kind::Target, Kind::Target)), 0); + assert_eq!(kinds_index((Kind::Sampled, Kind::Target)), 1); + assert_eq!(kinds_index((Kind::Target, Kind::Sampled)), 2); + assert_eq!(kinds_index((Kind::Sampled, Kind::Sampled)), 3); + let line = counts_line(&[9, 2, 1, 1, 2, 0, 0, 0, 0, 3, 0, 1, 4, 3, 1]); + assert!(line.starts_with("D3D12.X: placements (2 s): 9 made, 2 aliases at the same range (1 sampled over a target), 3 partial overlaps (tt/st/ts/ss 1/2/0/0), 3 one inside the other (tt/st/ts/ss 0/0/3/0)"), "{line}"); + assert!(line.ends_with("; 4 older ones superseded, 3 retired (off the shared pages), 1 used again"), "{line}"); + } + + /// Only a target the title holds, still mapped, on the title's pages, and on other pages than + /// the newer one is superseded. + #[test] + fn only_a_held_mapped_target_on_other_pages_is_superseded() { + let pages = Backing::Pages(1); + for o in [Overlap::Inside, Overlap::Around, Overlap::Partial] { + assert!(supersedes(o, Kind::Target, pages, false, true), "{o:?}"); + } + assert!(!supersedes(Overlap::Same, Kind::Target, pages, false, true), "an alias stays shared"); + assert!(!supersedes(Overlap::Partial, Kind::Sampled, pages, false, true), "title_textures retires sampled ones"); + assert!(!supersedes(Overlap::Partial, Kind::Target, Backing::Arena(3), false, true), "no tiles in an arena"); + assert!(!supersedes(Overlap::Partial, Kind::Target, pages, true, true), "released"); + assert!(!supersedes(Overlap::Partial, Kind::Target, pages, false, false), "superseded already"); + } + + /// A sampled texture over part of a target supersedes it; the target is mapped again when the + /// newer one is released while the title holds it. An alias and an older sampled one are not. + #[test] + fn a_placement_over_other_pages_of_a_target_supersedes_it_until_released() { + let mut r = Registry::default(); + let x = 0x60_0000_0000usize; + assert_eq!(retiring(&mut r, 1, x, 0xe7_0000, Kind::Target), (vec![], vec![])); + assert_eq!(retiring(&mut r, 2, x, 0xe7_0000, Kind::Target), (vec![], vec![]), "the same pages: an alias"); + assert_eq!(retiring(&mut r, 3, x + 16 * MIB, MIB, Kind::Sampled), (vec![], vec![])); + assert_eq!(retiring(&mut r, 4, x + 0xe0_0000, 2 * MIB, Kind::Sampled), (vec![1, 2], vec![]), "over both aliases' ends"); + assert_eq!(superseded(&r), [1, 2]); + assert!(r.use_again(3).is_empty(), "never superseded"); + assert_eq!(retiring(&mut r, 5, x + 16 * MIB + K64, K64, Kind::Target), (vec![], vec![]), "over a sampled one: title_textures"); + let mut back = r.release(4); + back.sort_unstable(); + assert_eq!(back, [1, 2]); + assert!(superseded(&r).is_empty()); + assert!(r.release(4).is_empty(), "once"); + } + + /// A placement over several targets supersedes each; with one of them released by the title + /// first, only the others are mapped again. + #[test] + fn a_placement_over_several_targets_supersedes_each() { + let mut r = Registry::default(); + let x = 0x70_0000_0000usize; + for k in 0..3 { + retiring(&mut r, 1 + k, x + k * 4 * MIB, 4 * MIB, Kind::Target); + } + assert_eq!(retiring(&mut r, 9, x + MIB, 10 * MIB, Kind::Target).0, [1, 2, 3], "partly, around, partly"); + assert!(r.release(2).is_empty(), "the older one released: nothing to map again"); + assert_eq!(superseded(&r), [1, 3]); + assert_eq!(r.remove(9), Some(vec![1, 3])); + assert!(superseded(&r).is_empty()); + assert!(r.live[&1].over.is_empty() && r.live[&1].under.is_empty()); + } + + /// When the newer one goes while a still newer one the title holds lies over other pages of + /// the old one, that one supersedes it from then on. + #[test] + fn the_next_newer_one_keeps_a_target_superseded() { + let mut r = Registry::default(); + let x = 0x80_0000_0000usize; + retiring(&mut r, 1, x, 8 * MIB, Kind::Target); + assert_eq!(retiring(&mut r, 2, x, 2 * MIB, Kind::Sampled).0, [1]); + assert_eq!(retiring(&mut r, 3, x + 6 * MIB, 4 * MIB, Kind::Sampled).0, Vec::::new(), "superseded already"); + assert!(r.release(2).is_empty(), "3 still lies over it"); + assert_eq!(superseded(&r), [1]); + assert_eq!(r.live[&1].under, [3]); + assert_eq!(r.release(3), [1]); + assert!(superseded(&r).is_empty()); + } + + /// A superseded target the title uses again goes back on the shared pages, and the newer + /// one's release then has nothing to map again. + #[test] + fn a_superseded_target_used_again_is_mapped_again() { + let mut r = Registry::default(); + let x = 0x90_0000_0000usize; + retiring(&mut r, 1, x, 4 * MIB, Kind::Target); + assert_eq!(retiring(&mut r, 2, x + 3 * MIB, 4 * MIB, Kind::Target).0, [1]); + assert_eq!(r.use_again(1), [2]); + assert!(superseded(&r).is_empty()); + assert!(r.use_again(1).is_empty(), "once"); + assert!(r.release(2).is_empty()); + // (superseded again by a later placement; then the title releases the old one) + assert_eq!(retiring(&mut r, 3, x + MIB, MIB, Kind::Sampled).0, [1]); + assert!(r.release(1).is_empty() && superseded(&r).is_empty()); + assert!(r.use_again(1).is_empty(), "released"); + assert!(r.remove(3).unwrap().is_empty()); + } +} diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 999fc00a56..d0941c4ea6 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -52,6 +52,8 @@ static PRESENTX_LOCK: Mutex<()> = Mutex::new(()); /// command queue #30 PresentX(planeCount, planes, parameters): plane 0's first resource is /// the frame; S_OK always (a console present does not fail for the title). pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, planes: *const u8, _params: *const u8) -> i32 { + // (`XCL_LOOK_STATS=2`: a frame's time on the thread that submits, added up) + let _cost = super::look_stats::deep().then(|| crate::hle::api_cost::time(crate::hle::api_cost::Call::Present)); if plane_count == 0 || planes.is_null() || !crate::gpu::shader::readable(planes as usize, 0x18) { return 0; } @@ -115,6 +117,9 @@ fn source_uv_rect(rect: Option<[i32; 4]>, w: u32, h: u32) -> [f32; 4] { unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u8) { let frames = BOUNDARIES.fetch_add(1, Ordering::Relaxed) + 1; + super::targets::frame_end(); + super::gpu_times::present(frames); + super::bvh_want::frame(); if frames % 300 == 0 { // the title's frame rate, for comparing runs (every 300 frames) static LAST: Mutex> = Mutex::new(None); @@ -138,6 +143,9 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u } } let extracted = extract_planes(plane_count, planes); + if super::capture::enabled() { + super::capture::present(queue as usize, &extracted.iter().map(|e| e.0).collect::>(), frames); + } if extracted.is_empty() || !enabled() { return; } @@ -252,6 +260,15 @@ pub fn rtv_resource(handle: usize) -> Option { RTVS.lock().unwrap().as_ref()?.get(&handle).copied() } +/// The resource `r` while a view still names it (AddRef'd), for `XCL_DUMP_TARGETS`. +pub(super) unsafe fn view_resource(r: usize) -> Option { + let g = RTVS.lock().unwrap(); + if !g.as_ref()?.values().any(|&v| v == r) { + return None; + } + ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).cloned() +} + /// The resource bound as render target 0 on `list` (`XCL_TRACE_FRAME`). pub fn rt0_resource(list: usize) -> Option { let h = *LISTS.lock().unwrap().as_ref()?.get(&list)?; @@ -645,6 +662,11 @@ pub(super) unsafe fn retire_released_queue(raw: usize) { static EXECUTES: AtomicU64 = AtomicU64::new(0); +/// XCL is presenting on this thread (its own copy of the frame is being submitted). +pub(super) fn presenting() -> bool { + IN_PRESENT.with(|c| c.get()) +} + /// (PresentX calls, ExecuteCommandLists calls) so far pub fn activity() -> (u64, u64) { (PRESENTS.load(Ordering::Relaxed), EXECUTES.load(Ordering::Relaxed)) @@ -690,6 +712,7 @@ pub fn on_queue_console_method(_info: &StubInfo, _caller: usize) { } BOUNDARIES.fetch_add(1, Ordering::Relaxed); LAST_BOUNDARY_MS.store(now_ms(), Ordering::Relaxed); + let _cost = super::look_stats::deep().then(|| crate::hle::api_cost::time(crate::hle::api_cost::Call::Present)); unsafe { present_now(Duration::from_millis(4), None) }; } @@ -1268,13 +1291,17 @@ unsafe impl Send for Presenter {} static PRESENTER: Mutex> = Mutex::new(None); unsafe fn transition(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + transition_sub(res, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after) +} + +unsafe fn transition_sub(res: &ID3D12Resource, sub: u32, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(res), - Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + Subresource: sub, StateBefore: before, StateAfter: after, }), @@ -1429,7 +1456,11 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, return; // swap chain is bound to the first queue we presented from } // rotate to the oldest in-flight allocator slot and wait only for its fence (frame N-2) - if let Err(e) = prepare_pipelined_slot(p, is_frame) { + let waited = { + let _cost = super::look_stats::deep().then(|| crate::hle::api_cost::time(crate::hle::api_cost::Call::PresentCopyWait)); + prepare_pipelined_slot(p, is_frame) + }; + if let Err(e) = waited { p.disabled = matches!(&e, FenceError::Removed(_)); if !matches!(&e, FenceError::Timeout(_)) { crate::xlog_error!("present: previous copy: {e}"); @@ -1446,8 +1477,44 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, if p.alloc.Reset().is_err() || p.list.Reset(&p.alloc, None).is_err() { return; } - let due = frame_dump_due(); + // `XCL_DUMP_TARGETS`: a busy frame's render targets go with its picture (copied in the + // state the title left them, as `XCL_TRACE_FRAME`'s; its frame dump is also the + // `last_frame_dump` of the report) + let targets = super::targets::take_pending(); + let dumping_targets = targets.is_some(); + let due = frame_dump_due() || dumping_targets; let mut dumps = Vec::new(); + for (tag, res, d) in targets.map_or(Vec::new(), |f| super::targets::to_dump(PRESENTS.load(Ordering::Relaxed), &f)) { + if let Some((buffer, footprint)) = readback_copy(&p.list, &res, &d) { + dumps.push(FrameDump { _source: res, buffer, footprint, format: d.Format, tag }); + } + } + // and what each depth UAV twin holds (`depth_uav`; it rests in UNORDERED_ACCESS) + if dumping_targets { + for (tag, twin) in super::depth_uav::twins_to_dump() { + let d = twin.GetDesc(); + p.list.ResourceBarrier(&[transition(&twin, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let copied = readback_copy(&p.list, &twin, &d); + p.list.ResourceBarrier(&[transition(&twin, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + if let Some((buffer, footprint)) = copied { + dumps.push(FrameDump { _source: twin, buffer, footprint, format: d.Format, tag }); + } + } + // and the small 3D textures (`lut3d`), from the state the title's work left them in + for (tag, tex, d, state) in super::lut3d::to_dump() { + let moved = super::lut3d::needs_transition(state); + if moved { + p.list.ResourceBarrier(&[transition_sub(&tex, 0, state, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + } + let copied = readback_copy(&p.list, &tex, &d); + if moved { + p.list.ResourceBarrier(&[transition_sub(&tex, 0, D3D12_RESOURCE_STATE_COPY_SOURCE, state)]); + } + if let Some((buffer, footprint)) = copied { + dumps.push(FrameDump { _source: tex, buffer, footprint, format: d.Format, tag }); + } + } + } let mut composited = false; if resolved.len() > 1 { if p.compositor.is_none() { @@ -1523,12 +1590,11 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, if due && trace_frame() { let busiest = busiest_rt(); let followed = FOLLOWED.lock().unwrap(); + // (a followed target is an address too: taken only while an RTV still holds it) let targets = busiest .into_iter() - .chain(followed.iter().copied()) - .filter_map(|r| { - let rr = r as *mut c_void; - let res = ID3D12Resource::from_raw_borrowed(&rr)?.clone(); + .chain(followed.iter().filter_map(|&r| view_resource(r))) + .filter_map(|res| { let d = res.GetDesc(); if d.SampleDesc.Count > 1 { return None; @@ -1558,8 +1624,12 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, crate::xlog_error!("present: submit copy: {e}"); return; } + if dumping_targets { + super::targets::submitted(); + } let presented = { let _stall = crate::stall::span(crate::stall::StallKind::Present); + let _in_driver = super::watch::in_driver(super::watch::Call::Present); sc.Present(0, DXGI_PRESENT(0)).ok() }; if let Err(e) = presented { @@ -1573,6 +1643,17 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, match fence::wait(&p.fence, p.value, &p.dev, Some(p.event), 2000) { Ok(()) => { for dump in p.dumps.drain(..) { + if dump.tag.starts_with("twin") { + super::depth_uav::log_values(&dump.buffer, &dump.footprint, &dump.tag); + continue; + } + if dump.tag.starts_with("lut") { + super::lut3d::log_values(&dump.buffer, &dump.footprint, &dump.tag); + continue; + } + if dump.tag.starts_with("target") { + super::targets::log_census(&dump.buffer, &dump.footprint, &dump.tag); + } write_frame(&dump.buffer, &dump.footprint, dump.format, &dump.tag); } mark_pipe_drained(p); @@ -1580,7 +1661,13 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, } Err(e) => { p.disabled = matches!(&e, FenceError::Removed(_)); - crate::xlog_error!("present: frame dump copy: {e}"); + // (a copy queued behind the title's work is no stopped GPU: not the fence's + // text, which a watchdog reads as one; its buffers stay on the ring slot) + if let FenceError::Timeout(ms) = e { + crate::xlog_warn!("present: frame dump copy: not finished after {ms} ms – this dump is skipped"); + } else { + crate::xlog_error!("present: frame dump copy: {e}"); + } if p.disabled { return; } @@ -1683,6 +1770,56 @@ fn rgb(format: DXGI_FORMAT, t: u32) -> Option<[u8; 3]> { }) } +/// A texel of `format` (its bytes: `targets::texel_bytes` of them) as a colour to look at, for +/// the formats `rgb` does not take: a frame's HDR and data targets (`XCL_DUMP_TARGETS`). A +/// float channel is tone-mapped as the HDR formats are, its sign dropped (a normal, a motion +/// vector); an integer target shows its low bytes. A flat picture over a scene that was drawn +/// could not be followed through these: they were written black, "format not decoded". +fn texel_rgb(format: DXGI_FORMAT, t: &[u8]) -> Option<[u8; 3]> { + let u16_at = |i: usize| u16::from_le_bytes([t[i], t[i + 1]]); + let u32_at = |i: usize| u32::from_le_bytes([t[i], t[i + 1], t[i + 2], t[i + 3]]); + // (NaN and infinities: white, so that they show) + let tm = |v: f32| if v.is_finite() { ((v.abs() / (1.0 + v.abs())).sqrt() * 255.0) as u8 } else { 255 }; + let half = |i: usize| half_float(u16_at(i)); + let float = |i: usize| f32::from_bits(u32_at(i)); + if t.len() < super::targets::texel_bytes(format) { + return None; + } + Some(match format { + DXGI_FORMAT_R16G16B16A16_FLOAT | DXGI_FORMAT_R16G16B16A16_TYPELESS => [tm(half(0)), tm(half(2)), tm(half(4))], + DXGI_FORMAT_R16G16B16A16_UNORM => [t[1], t[3], t[5]], + DXGI_FORMAT_R32G32B32A32_FLOAT | DXGI_FORMAT_R32G32B32A32_TYPELESS => [tm(float(0)), tm(float(4)), tm(float(8))], + DXGI_FORMAT_R16G16_FLOAT | DXGI_FORMAT_R16G16_TYPELESS => [tm(half(0)), tm(half(2)), 0], + DXGI_FORMAT_R16G16_UNORM => [t[1], t[3], 0], + DXGI_FORMAT_R32G32_FLOAT => [tm(float(0)), tm(float(4)), 0], + DXGI_FORMAT_R32G32_UINT => [t[0], t[4], t[1]], + DXGI_FORMAT_R32_FLOAT | DXGI_FORMAT_D32_FLOAT | DXGI_FORMAT_R32_TYPELESS => [tm(float(0)); 3], + DXGI_FORMAT_R32_UINT => [t[0], t[1], t[2]], + DXGI_FORMAT_R16_FLOAT | DXGI_FORMAT_R16_TYPELESS => [tm(half(0)); 3], + DXGI_FORMAT_R16_UNORM | DXGI_FORMAT_D16_UNORM => [t[1]; 3], + DXGI_FORMAT_R16_UINT => [t[0], t[1], 0], + DXGI_FORMAT_R8G8_UNORM | DXGI_FORMAT_R8G8_TYPELESS => [t[0], t[1], 0], + DXGI_FORMAT_R8_UNORM | DXGI_FORMAT_A8_UNORM | DXGI_FORMAT_R8_TYPELESS => [t[0]; 3], + DXGI_FORMAT_R8_UINT => [t[0].wrapping_mul(37), t[0].wrapping_mul(91), t[0].wrapping_mul(151)], + DXGI_FORMAT_R8G8B8A8_TYPELESS => [t[0], t[1], t[2]], + DXGI_FORMAT_B8G8R8A8_TYPELESS => [t[2], t[1], t[0]], + DXGI_FORMAT_R10G10B10A2_TYPELESS => return rgb(DXGI_FORMAT_R10G10B10A2_UNORM, u32_at(0)), + _ if t.len() >= 4 => return rgb(format, u32_at(0)), + _ => return None, + }) +} + +/// An IEEE half float. +pub(super) fn half_float(h: u16) -> f32 { + let (sign, e, m) = (if h >> 15 != 0 { -1.0f32 } else { 1.0 }, (h >> 10 & 31) as i32, (h & 0x3FF) as f32 / 1024.0); + sign * match e { + 0 => m * 2f32.powi(-14), + 31 if m == 0.0 => f32::INFINITY, + 31 => f32::NAN, + _ => (1.0 + m) * 2f32.powi(e - 15), + } +} + /// the largest render target the draws `XCL_TRACE_SHADERS` picked drew into (AddRef'd): the /// one the `XCL_TRACE_FRAME` dumps show instead of the busiest static WATCHED_RT: Mutex> = Mutex::new(None); @@ -1724,17 +1861,23 @@ pub unsafe fn watch_rt(rt: usize) { } /// the single-sampled resource bound as a render target most often (`XCL_TRACE_FRAME`; a -/// multisampled one cannot be copied to a buffer – the present list would not close) -fn busiest_rt() -> Option { +/// multisampled one cannot be copied to a buffer – the present list would not close). +/// +/// `USES` and the watched target are addresses, not references. A target is taken only while an +/// RTV still names it, which holds it (`view_resource`): a retail title's world releases +/// transient targets all the time, and GetDesc on one of those addresses ended the process (an +/// access violation under `present_now`, in every trace run that also dumped frames or targets). +unsafe fn busiest_rt() -> Option { if let Some(r) = *WATCHED_RT.lock().unwrap() { - return Some(r); + return view_resource(r); } - let single = |r: usize| unsafe { ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).is_some_and(|x| x.GetDesc().SampleDesc.Count <= 1) }; - USES.lock().unwrap().as_ref()?.iter().filter(|(&r, u)| u[USE_RT] > 0 && single(r)).max_by_key(|(_, u)| u[USE_RT]).map(|(&r, _)| r) + let mut bound: Vec<(usize, u64)> = USES.lock().unwrap().as_ref()?.iter().filter(|(_, u)| u[USE_RT] > 0).map(|(&r, u)| (r, u[USE_RT])).collect(); + bound.sort_by_key(|&(_, binds)| std::cmp::Reverse(binds)); + bound.into_iter().find_map(|(r, _)| view_resource(r).filter(|x| x.GetDesc().SampleDesc.Count <= 1)) } /// an 11- / 10-bit unsigned float (5-bit exponent) -> f32 -fn small_float(v: u32, mantissa_bits: u32) -> f32 { +pub(super) fn small_float(v: u32, mantissa_bits: u32) -> f32 { let (e, m) = (v >> mantissa_bits, v & ((1 << mantissa_bits) - 1)); let m = m as f32 / (1u32 << mantissa_bits) as f32; match e { @@ -1767,12 +1910,18 @@ unsafe fn write_frame(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRI } let (mut lit, mut decoded) = (0usize, true); let mut raw: HashMap = HashMap::new(); + // (a texel of 1, 2, 8 or 16 bytes is read at its own size: read as 4 bytes at a 4-byte + // stride, an HDR target showed every other half texel and a one-byte one ran past its row) + let bytes = super::targets::texel_bytes(format); for y in (0..oh).rev() { let start = bmp.len(); for x in 0..ow { - let t = ((p as *const u8).add(fp.Offset as usize + step * y * pitch + 4 * step * x) as *const u32).read_unaligned(); + let texel = std::slice::from_raw_parts((p as *const u8).add(fp.Offset as usize + step * y * pitch + bytes * step * x), bytes); + let mut first = [0u8; 4]; + first[..bytes.min(4)].copy_from_slice(&texel[..bytes.min(4)]); + let t = u32::from_le_bytes(first); *raw.entry(t).or_default() += 1; - let c = rgb(format, t).unwrap_or_else(|| { + let c = texel_rgb(format, texel).unwrap_or_else(|| { decoded = false; [0; 3] }); @@ -1938,6 +2087,31 @@ mod tests { assert_eq!(compiling_text("t", (3, 4), (0, 0, 0), 0, 1), "t | compiling shaders: DXC 3 running, 4 done | driver 0 building, 0 done, 1 failed"); } + #[test] + fn dumped_texels_of_hdr_and_data_formats_have_a_colour() { + assert_eq!(half_float(0x3C00), 1.0); + assert_eq!(half_float(0xC000), -2.0); + assert_eq!(half_float(0x0000), 0.0); + assert!(half_float(0x0001) > 0.0 && half_float(0x0001) < 1e-6, "a denormal"); + assert!(half_float(0x7C00).is_infinite() && half_float(0x7E00).is_nan()); + // RGBA16F (1, 0, 4, 1): tone-mapped x / (1 + x), square root + let hdr: Vec = [0x3C00u16, 0, 0x4400, 0x3C00].iter().flat_map(|h| h.to_le_bytes()).collect(); + assert_eq!(texel_rgb(DXGI_FORMAT_R16G16B16A16_FLOAT, &hdr), Some([180, 0, 228])); + // a NaN shows (white), a negative value by its size + let odd: Vec = [0x7E00u16, 0xBC00, 0, 0].iter().flat_map(|h| h.to_le_bytes()).collect(); + assert_eq!(texel_rgb(DXGI_FORMAT_R16G16B16A16_FLOAT, &odd), Some([255, 180, 0])); + assert_eq!(texel_rgb(DXGI_FORMAT_R8_UNORM, &[200]), Some([200; 3])); + assert_eq!(texel_rgb(DXGI_FORMAT_R32_UINT, &[1, 2, 3, 4]), Some([1, 2, 3])); + assert_eq!(texel_rgb(DXGI_FORMAT_R16G16_UNORM, &[0, 10, 0, 20]), Some([10, 20, 0])); + assert_eq!(texel_rgb(DXGI_FORMAT_R32_FLOAT, &1.0f32.to_le_bytes()), Some([180; 3])); + // the formats `rgb` knows go through it + assert_eq!(texel_rgb(DXGI_FORMAT_R8G8B8A8_UNORM, &[1, 2, 3, 4]), Some([1, 2, 3])); + assert_eq!(texel_rgb(DXGI_FORMAT_B8G8R8A8_UNORM, &[1, 2, 3, 4]), Some([3, 2, 1])); + // fewer bytes than the format's texel: no colour (and no read past them) + assert_eq!(texel_rgb(DXGI_FORMAT_R16G16B16A16_FLOAT, &hdr[..4]), None); + assert_eq!(texel_rgb(DXGI_FORMAT_BC1_UNORM, &[0; 4]), None, "a format with no texels of its own"); + } + #[test] fn present_ring_overlaps_previous_frame_and_drains_cleanly() { let mut ring = PresentRing::new(PRESENT_SLOTS); @@ -2143,7 +2317,10 @@ mod frame_dump_tests { write_frame(&buffer, &fp, fp.Footprint.Format, "frame"); let bright = last_frame_dump().unwrap(); assert_eq!(bright.non_dark_samples, Some(bright.sampled_pixels)); - write_frame(&buffer, &fp, DXGI_FORMAT_R32_FLOAT, "frame"); + // (a format no dump decodes, at the footprint's 4 bytes a texel: shared-exponent + // RGB is no render target's) + assert_eq!(texel_rgb(DXGI_FORMAT_R9G9B9E5_SHAREDEXP, &[31, 0, 0, 255]), None); + write_frame(&buffer, &fp, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, "frame"); let json = serde_json::to_value(last_frame_dump().unwrap()).unwrap(); assert!(json["non_dark_samples"].is_null(), "undecoded is different from dark"); } diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs index 725f5c593e..909a22fd4d 100644 --- a/crates/xcl/src/hle/d3d12x/present/preparation.rs +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -43,13 +43,25 @@ pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { std::env::remove_var("XCL_PREPARATION_MENU"); let root = &boot.game_root; let corpus = root.join(".xcl/pso-corpus").try_exists().map_err(|e| e.to_string())?; - if !corpus && std::env::var("XCL_PREPARE").is_ok_and(|v| v.trim() == "0") { return Ok(()); } + // `XCL_PREPARE=0`: the title starts at once and builds what it uses as it goes (it stands + // still for those builds): for a look at a change without the wait + if !corpus && std::env::var("XCL_PREPARE").is_ok_and(|v| v.trim() == "0") { + crate::xlog_info!("Shader preparation left out (XCL_PREPARE=0): the title builds what it uses as it goes"); + return Ok(()); + } let history = crate::hle::d3d12x::gfx_records::path().try_exists().map_err(|e| e.to_string())?; if !corpus && !history && (boot.config.graphics.eq_ignore_ascii_case("null") || (!root.join("shaders.rpf").try_exists().map_err(|e| e.to_string())? && !root.join("shaders").is_dir())) { return Ok(()); } - let progress = Arc::new(LaunchPreparation { adapter: boot.config.d3d12_adapter.clone(), ..Default::default() }); + // (the shader records earlier runs of the title used go first and alone: the rest are built + // when the title asks for them; `XCL_PREPARE_ALL=1` prepares every record) + let only = Some(crate::hle::d3d12x::pso_async::earlier_used_shaders()) + .filter(|used| !used.is_empty() && !std::env::var("XCL_PREPARE_ALL").is_ok_and(|v| v.trim() == "1")); + if let Some(used) = &only { + crate::xlog_info!("Shader preparation: only the {} shaders earlier runs used (XCL_PREPARE_ALL=1: every record)", used.len()); + } + let progress = Arc::new(LaunchPreparation { adapter: boot.config.d3d12_adapter.clone(), only, ..Default::default() }); let hwnd = if super::enabled() { *SCREEN.lock().unwrap() = Some(Screen { progress: progress.clone(), start: Instant::now(), clock: StallClock::default(), ready: false }); ACTIVE.store(true, Ordering::Release); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index ad583c6be1..df9fabd0da 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -3,8 +3,15 @@ //! it loads. When a pipeline's DXIL is not in the disk cache yet, the title gets a stand-in //! pipeline (shaders that draw nothing) at once and the real one is built on a worker; binding //! (`SetPipelineState`, console list replay, the two-pass lookups) uses the real one as soon -//! as it is there. A graphics pipeline draws nothing until then; a compute pipeline is waited -//! for where it is used, a `Dispatch` at its submit (a skipped dispatch would corrupt what it computes). +//! as it is there. A lazy pipeline (`lazy`) is built at its first use or ahead of it: those +//! of earlier runs in their order (`used::rank`), every other one at the lowest priority +//! (`Backlog`). A draw or dispatch with a pipeline still being built waits for it +//! (`resolve_wait`) where it is used, a `Dispatch` at its submit (`waits_for`, +//! `need_by_submit`): a dispatch until it is built (a skipped one corrupts what it computes) +//! unless `XCL_CS_PSO_WAIT_MS` limits that, a draw only while its thread has waited less than +//! `XCL_GFX_PSO_WAIT_MS` in the last second when that is set (`gfx_wait_left`) – then it and +//! the later draws of that pipeline draw nothing until it is built. An ExecuteIndirect whose +//! pipeline is still being built after that is skipped. //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. use std::collections::{HashMap, HashSet}; @@ -176,6 +183,21 @@ struct Build { by_submit: AtomicBool, demand: Mutex, queued: Mutex>, + /// a compute pipeline's console program (`fnv64` of its CS, as in the `[SHADER]` and driver + /// compile lines); 0 = not known + record: u64, + /// made by a lazy submit (the pipeline line counts these) + lazy: bool, + /// one of its stand-ins was used (`Pending::note_use_at` sets it; `build_is_ahead`, the line) + used: AtomicBool, + /// a bind waited for it past its budget, or binds go on without it (`build_is_late`) + late: AtomicBool, + /// its build gave the driver a huge program (`note_huge`) + huge: AtomicBool, + /// a wait for it passed 1 s and was logged (once a build) + warned: AtomicBool, + /// its translation and DXC compile on their own, until the backlog runs them (`Warm`) + warm: Mutex>, } const EVICTION_CANDIDATE_CAPACITY: usize = 1024; @@ -279,9 +301,15 @@ fn eviction_candidates() -> &'static EvictionCandidateQueue { CANDIDATES.get_or_init(EvictionCandidateQueue::new) } -/// The preload worker building this pipeline. +/// Who waits for the pipeline, and the preload worker building it. #[derive(Default)] struct Demand { + /// binds waiting for it: a wait that ran out of its budget leaves (`Build::unwant`), one + /// that saw the build end stays counted. `Build::wanted` is `waiters != 0`. + waiters: u32, + /// a submit counts among `waiters` before it gets to it (`want`, `need_by_submit`; left with + /// the wait for it) + ahead: bool, /// thread id of the preload worker (lowest priority) building it, 0 = none preload_thread: u32, } @@ -295,6 +323,18 @@ thread_local! { static NORMAL_WORKER: std::cell::Cell = const { std::cell::Cell::new(false) }; } +thread_local! { + /// when the build this thread runs (`run_build`) started + static JOB_START: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// the build this thread runs gave the driver a huge program (`note_huge`) + static JOB_HUGE: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// a backlog worker's build: whether it came from `Backlog::compute`; None once another + /// worker took this one's place (`build_parks`) + static PRELOAD_STEP: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// explicit late-build override for off-pool workers (e.g. `dispatch_chain`'s `xcl-pso-whole`) + static JOB_LATE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + /// This thread is a worker and one of the title's threads waits for what it is building: the /// build must not stand back for the title's sake (`real::big_compile_turn`). pub(super) fn build_is_wanted() -> bool { @@ -312,6 +352,62 @@ pub fn wanted_here() -> crate::gpu::recomp::dxc::Wanted { Box::new(move || own) } +/// The time since the build this thread runs started (None: it runs none): the driver compile +/// log says where a slow pipeline's time went before the driver got it. +pub(super) fn job_elapsed() -> Option { + JOB_START.with(|s| s.get()).map(|t| t.elapsed()) +} + +/// The build this thread runs gives the driver a huge program (`real::huge_pso_bytes`). +pub(super) fn note_huge() { + JOB_HUGE.with(|h| h.set(true)); +} + +/// This thread is a worker building a pipeline a bind waited for and went on without +/// (`resolve_within`), or a background `xcl-pso-whole` worker (`with_late_build`): nobody waits +/// for it now, but the title's draws or dispatches with it are left out until it is built +/// (`real::huge_compile_turn`). +pub(super) fn build_is_late() -> bool { + JOB_LATE.with(|l| l.get()) + || BUILDING.with(|b| b.borrow().as_ref().is_some_and(|build| build.late.load(Ordering::Acquire))) +} + +/// Run `f` with `build_is_late() == true` on the current thread, restoring the previous state on +/// return or unwind. +pub(super) fn with_late_build(f: impl FnOnce() -> R) -> R { + struct Reset(bool); + impl Drop for Reset { + fn drop(&mut self) { + JOB_LATE.with(|l| l.set(self.0)); + } + } + let prev = JOB_LATE.with(|l| l.replace(true)); + let _reset = Reset(prev); + f() +} + +/// This thread is a preload or backlog worker building a pipeline nobody has used yet: its huge +/// driver compile gives its turn to any other (`real::big_compile_turn`). +pub(super) fn build_is_ahead() -> bool { + BUILDING.with(|b| b.borrow().as_ref().is_some_and(|build| { + !build.used.load(Ordering::Relaxed) && build.demand.lock().unwrap().preload_thread != 0 + })) +} + +/// The build ahead on this thread waits for its pipeline's first use before its driver compile +/// (`real::huge_compile_turn`: no giant one is made ahead), which may never come. On a backlog +/// worker another worker starts in its place and the lane of new compute pipelines goes to the +/// next one (`Backlog::built`), so the backlog does not stand still behind it; this thread ends +/// after the build. (A normal worker's wait has main's `parked_for_big_compile` instead; on a +/// `xcl-pso-pre-*` worker this does nothing.) +pub(super) fn build_parks() { + let Some(new_compute) = PRELOAD_STEP.with(|s| s.take()) else { return }; + let Some(q) = preload_backlog() else { return }; + q.list.lock().unwrap().built(new_compute); + q.cv.notify_one(); + spawn_backlog_worker(q); +} + struct RunningBuild<'a> { build: &'a Build, preload: bool, @@ -377,11 +473,24 @@ fn run_build(build: &Arc, job: Job) { } let real = { let _running = RunningBuild { build, preload }; - run_job(job) + run_timed_job(build, job) }; complete(build, real); } +/// `run_job` for `build`: when it started and whether its program was huge are noted for the logs +/// (`job_elapsed`, `note_huge`; the pipeline line counts huge lazy builds). +fn run_timed_job(build: &Build, job: Job) -> usize { + JOB_START.with(|s| s.set(Some(std::time::Instant::now()))); + JOB_HUGE.with(|h| h.set(false)); + let real = run_job(job); + JOB_START.with(|s| s.set(None)); + if JOB_HUGE.with(|h| h.replace(false)) { + build.huge.store(true, Ordering::Relaxed); + } + real +} + impl Build { fn is_evictable(&self) -> bool { self.kind == PipelineKind::Compute } @@ -430,9 +539,25 @@ impl Build { by_submit: AtomicBool::new(false), demand: Default::default(), queued: Mutex::new(None), + record: 0, + lazy: false, + used: AtomicBool::new(false), + late: AtomicBool::new(false), + huge: AtomicBool::new(false), + warned: AtomicBool::new(false), + warm: Mutex::new(None), } } + /// What the submit that made the build knows of it: made by a lazy submit, the compute + /// pipeline's console program (`record`, 0: not known) and its translation ahead (`warm`). + fn with_submit(mut self, lazy: bool, record: u64, warm: Option) -> Self { + self.lazy = lazy; + self.record = record; + self.warm = Mutex::new(warm); + self + } + fn note_queued(&self) { if self.tracked.load(Ordering::Acquire) { // Publish the count before ACTIVE: completion may run as soon as the queue accepts @@ -476,27 +601,85 @@ impl Build { /// One of the title's threads waits or a recorded submit will wait for it: the worker /// building it goes on now, at a normal priority. fn want(&self) { - use windows_sys::Win32::Foundation::CloseHandle; - use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_PRIORITY_NORMAL, THREAD_SET_LIMITED_INFORMATION}; - let newly_wanted = !self.wanted.swap(true, Ordering::AcqRel); + self.add_waiter(&mut self.demand.lock().unwrap()); + self.wanted_now(); + } + + /// What a new waiter starts besides its count (not under the `demand` lock: `promote` takes + /// the queue's). + fn wanted_now(&self) { let _ = start_normal_workers(); self.promote(Priority::Foreground); - if newly_wanted { - let d = self.demand.lock().unwrap(); - if d.preload_thread == 0 { - return; - } - unsafe { - let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, d.preload_thread); - if !h.is_null() { - SetThreadPriority(h, THREAD_PRIORITY_NORMAL); - CloseHandle(h); - } + } + + /// (under the `demand` lock) + fn add_waiter(&self, d: &mut Demand) { + d.waiters += 1; + if d.waiters == 1 { + self.wanted.store(true, Ordering::Release); + Self::set_priority(d, windows_sys::Win32::System::Threading::THREAD_PRIORITY_NORMAL); + } + } + + /// A bind that waited for it ran out of its budget and goes on without it: when nobody else + /// waits, the build is no longer wanted – back at the lowest priority on a preload worker and + /// behind the huge-pipeline gate as an unwanted one (`real::big_compile_turn`): it waits for + /// free commit and for the unwanted slots, where a wanted build skips the commit wait and has + /// more slots, and many of those at once ran the process out of commit. (A job already + /// promoted to `Foreground` keeps its place in the queue.) + fn unwant(&self) { + let mut d = self.demand.lock().unwrap(); + d.waiters = d.waiters.saturating_sub(1); + if d.waiters == 0 { + self.wanted.store(false, Ordering::Release); + Self::set_priority(&d, windows_sys::Win32::System::Threading::THREAD_PRIORITY_LOWEST); + } + } + + /// The wait that ran out of its budget was the one a submit had counted ahead (`want`): that + /// one leaves too. + fn unwant_ahead(&self) { + let ahead = std::mem::take(&mut self.demand.lock().unwrap().ahead); + if ahead { + self.unwant(); + } + } + + /// The preload worker building it, if one does, at `priority` (under the `demand` lock: the + /// worker does not end its build meanwhile). + fn set_priority(d: &Demand, priority: windows_sys::Win32::System::Threading::THREAD_PRIORITY) { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_SET_LIMITED_INFORMATION}; + if d.preload_thread == 0 { + return; + } + unsafe { + let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, d.preload_thread); + if !h.is_null() { + SetThreadPriority(h, priority); + CloseHandle(h); } } } } +impl Build { + fn is_compute(&self) -> bool { + matches!(self.kind, PipelineKind::Compute | PipelineKind::ConsoleListCompute) + } + + /// Nobody has taken it yet: not sent to the workers (a bind wants it: they build it), not + /// released, not being built. + fn unclaimed(&self) -> bool { + !self.sent.load(Ordering::Acquire) && self.untaken() + } + + /// Not released and not being built (sent or not). + fn untaken(&self) -> bool { + !self.orphan.load(Ordering::Acquire) && self.job.lock().unwrap().is_some() + } +} + fn mark_queued(state: &AtomicU8) -> bool { state.compare_exchange(QUEUE_IDLE, QUEUE_ACTIVE, Ordering::AcqRel, Ordering::Acquire).is_ok() } @@ -511,6 +694,7 @@ impl Pending { } fn note_use_at(&self, frame: u64) { + self.build.used.store(true, Ordering::Relaxed); if super::memory_report::enabled() || self.build.recipe.is_some() { let _writer = self.build.eviction_timestamp_writer(); self.build.last_use_frame.fetch_max(frame, Ordering::Relaxed); @@ -2794,12 +2978,22 @@ fn forget_in_flight(build: &Arc) { IN_FLIGHT.remove_exact(key, &build, || COALESCING.finished(1)); } -/// The build is done (`real`: its pipeline, 0 = failed). fn complete(build: &Arc, real: usize) { + // (its translation ahead is of no use now: what it holds goes) + drop(build.warm.lock().unwrap().take()); if real == 0 { FAILED.fetch_add(1, Ordering::Relaxed); } else { BUILT.fetch_add(1, Ordering::Relaxed); + if build.lazy { + LAZY_BUILT.fetch_add(1, Ordering::Relaxed); + if !build.used.load(Ordering::Relaxed) { + LAZY_AHEAD.fetch_add(1, Ordering::Relaxed); + } + if build.huge.load(Ordering::Relaxed) { + LAZY_HUGE.fetch_add(1, Ordering::Relaxed); + } + } let _writer = build.eviction_timestamp_writer(); build.completed_frame.store(super::present::presents(), Ordering::Relaxed); } @@ -2984,10 +3178,200 @@ fn rebuild_reserved_pinned( } static BUILT: AtomicUsize = AtomicUsize::new(0); static FAILED: AtomicUsize = AtomicUsize::new(0); +static LAZY_MADE: AtomicUsize = AtomicUsize::new(0); +static LAZY_GRAPHICS: AtomicUsize = AtomicUsize::new(0); +static LAZY_BUILT: AtomicUsize = AtomicUsize::new(0); +static LAZY_AHEAD: AtomicUsize = AtomicUsize::new(0); +static LAZY_HUGE: AtomicUsize = AtomicUsize::new(0); + +/// What the pipeline line (`stats_line`) shows. +#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)] +struct Stats { + made: usize, + graphics: usize, + built: usize, + ahead: usize, + huge: usize, + /// translated ahead (`Backlog`), still in the backlog + warmed: usize, + backlog: usize, + /// binds' waits for pipelines being built: (waits, µs) so far (`api_cost::Call::PipelineWait`) + waits: (u64, u64), +} + +fn stats() -> Stats { + let l = |a: &AtomicUsize| a.load(Ordering::Relaxed); + Stats { + made: l(&LAZY_MADE), + graphics: l(&LAZY_GRAPHICS), + built: l(&LAZY_BUILT), + ahead: l(&LAZY_AHEAD), + huge: l(&LAZY_HUGE), + warmed: l(&WARMED), + backlog: l(&BACKLOG), + waits: crate::hle::api_cost::totals()[crate::hle::api_cost::Call::PipelineWait as usize], + } +} + +/// The pipeline line for `now` when something changed since `last` (written 2 s before): how +/// many lazy pipelines the title made, how many are built and how many of those before their +/// first use (a bind did not wait for them), and how long binds stood still waiting for +/// pipelines in those 2 s (counted when a wait ends). +fn stats_line(now: &Stats, last: &Stats, huge_kb: usize) -> Option { + if now == last { + return None; + } + Some(format!( + "D3D12.X: lazy pipelines: {} made ({} graphics), {} built ({} before their first use, {} with {huge_kb} KB of DXIL or more), {} translated ahead, {} in the build-ahead backlog; binds waited {} ms for pipelines being built ({} waits in 2 s)", + now.made, + now.graphics, + now.built, + now.ahead, + now.huge, + now.warmed, + now.backlog, + (now.waits.1 - last.waits.1) / 1000, + now.waits.0 - last.waits.0, + )) +} + +/// The pipeline line every 2 s while it changes (`stats_line`), and the line of calls put off to +/// the submit (`put_off_line`). +fn start_stats() { + static STARTED: std::sync::Once = std::sync::Once::new(); + // (a test's pipelines are not the title's) + if cfg!(test) { + return; + } + STARTED.call_once(|| { + let _ = std::thread::Builder::new().name("xcl-pso-stats".into()).spawn(|| { + let mut last = Stats::default(); + let mut last_put_off = PutOffStats::default(); + loop { + std::thread::sleep(std::time::Duration::from_secs(2)); + let now = stats(); + if let Some(line) = stats_line(&now, &last, super::real::huge_pso_bytes() >> 10) { + crate::xlog_info!("{line}"); + } + last = now; + let now = put_off_stats(); + if let Some(line) = put_off_line(&now, &last_put_off) { + crate::xlog_info!("{line}"); + } + last_put_off = now; + } + }); + }); +} static QUEUED_BUILDS: AtomicUsize = AtomicUsize::new(0); /// binds waiting right now for a pipeline still being built (`title_held`) static HELD: AtomicUsize = AtomicUsize::new(0); +/// What became of a call put off to the submit (`list_x::defer`), for the line of them +/// (`put_off_line`). +#[derive(Clone, Copy)] +pub(super) enum PutOff { + /// put off: its list split around it + Deferred, + /// its pipeline would have been waited for, but the list could not be split (no room for + /// more segments, a predicated or bundle list, one that is no title list, `XCL_ALLOC_SWAP=0`): + /// waited in the call + Refused, + /// recorded at a submit with its pipeline built + Recorded, + /// recorded at a submit, but its pipeline's build failed or ran out of its budget: skipped + Skipped, + /// not recorded at the submit (no allocator of the list's own, its Reset failed) + Dropped, +} + +static PUT_OFF: [AtomicUsize; 5] = [const { AtomicUsize::new(0) }; 5]; +/// pipelines a put-off call needed (`need_by_submit`) +static NEEDED_MADE: AtomicUsize = AtomicUsize::new(0); +/// waits at a submit for the pipelines of its put-off calls: count, µs +static SUBMIT_WAITS: AtomicU64 = AtomicU64::new(0); +static SUBMIT_WAIT_US: AtomicU64 = AtomicU64::new(0); + +pub(super) fn note_put_off(what: PutOff) { + PUT_OFF[what as usize].fetch_add(1, Ordering::Relaxed); + start_stats(); +} + +thread_local! { + /// this thread records the put-off calls of a submit (`at_submit`) + static AT_SUBMIT: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// While it lives this thread records a submit's put-off calls: its waits for their pipelines +/// are the submit's (`put_off_line`). +pub(super) struct AtSubmit(bool); + +pub(super) fn at_submit() -> AtSubmit { + AtSubmit(AT_SUBMIT.with(|a| a.replace(true))) +} + +impl Drop for AtSubmit { + fn drop(&mut self) { + AT_SUBMIT.with(|a| a.set(self.0)); + } +} + +pub(super) fn is_at_submit() -> bool { + AT_SUBMIT.with(|a| a.get()) +} + +/// How many put-off calls came to `what` so far. +#[cfg(test)] +pub(super) fn put_off_count(what: PutOff) -> usize { + PUT_OFF[what as usize].load(Ordering::Relaxed) +} + +/// What the line of put-off calls (`put_off_line`) shows. +#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)] +struct PutOffStats { + /// by `PutOff` + calls: [usize; 5], + needed: usize, + /// waits at submits: (count, µs) + waits: (u64, u64), + /// the most segments a title list's recording had (`title_list::segments_peak`) + segments: usize, +} + +fn put_off_stats() -> PutOffStats { + PutOffStats { + calls: std::array::from_fn(|k| PUT_OFF[k].load(Ordering::Relaxed)), + needed: NEEDED_MADE.load(Ordering::Relaxed), + waits: (SUBMIT_WAITS.load(Ordering::Relaxed), SUBMIT_WAIT_US.load(Ordering::Relaxed)), + segments: super::title_list::segments_peak(), + } +} + +/// The line of calls put off to the submit for `now` when it changed since `last` (written 2 s +/// before) and some call was put off or would have been: how many, what became of them at the +/// submits, the pipelines they needed, and how long submits stood in their waits for them. +/// (A thread that waits never builds the pipeline itself here: a foreground worker does.) +fn put_off_line(now: &PutOffStats, last: &PutOffStats) -> Option { + let c = |k: PutOff| now.calls[k as usize]; + if now == last || c(PutOff::Deferred) + c(PutOff::Refused) == 0 { + return None; + } + Some(format!( + "D3D12.X: put-off dispatches: {} put off to the submit ({} in 2 s), {} waited in the call (no split); at submits {} recorded, {} skipped (build failed or late), {} dropped; {} pipelines needed by a submit; submits waited {} ms for them in 2 s ({} waits; {} ms so far); at most {} segments in a recording", + c(PutOff::Deferred), + c(PutOff::Deferred) - last.calls[PutOff::Deferred as usize], + c(PutOff::Refused), + c(PutOff::Recorded), + c(PutOff::Skipped), + c(PutOff::Dropped), + now.needed, + (now.waits.1 - last.waits.1) / 1000, + now.waits.0 - last.waits.0, + now.waits.1 / 1000, + now.segments, + )) +} + /// The PC calls of the title's threads (`pc_call`): the ones going on, and how long the ones /// that ended took since the last frame was shown. struct PcCalls { @@ -3591,6 +3975,9 @@ fn drop_unstarted_job(build: &Arc) { build.publish_completed(done); } drop(job); + // (its translation ahead is of no use either, as in `complete`: the backlog may hold + // the build a while yet) + drop(build.warm.lock().unwrap().take()); forget_in_flight(build); } } @@ -3822,11 +4209,7 @@ fn submit_job(q: &BuildQueue, build: &Arc, priority: Priority, preload: b let on_preload_worker = PRELOAD_WORKER.get(); let built = build_queued(&queued_build); if built && preload && on_preload_worker { - static DONE: AtomicUsize = AtomicUsize::new(0); - let n = DONE.fetch_add(1, Ordering::Relaxed) + 1; - if n.is_power_of_two() { - crate::xlog_info!("D3D12.X: {n} pipelines built ahead of their first use"); - } + note_built_ahead(); } queued_build.queued.lock().unwrap().take(); })) @@ -3894,8 +4277,17 @@ fn build_queued(build: &Arc) -> bool { } } +/// This thread is a preload or backlog worker whose build nobody waits for (yet). +fn build_is_backlog_only() -> bool { + BUILDING.with(|b| b.borrow().as_ref().is_some_and(|build| { + build.demand.lock().unwrap().preload_thread != 0 && !build.wanted.load(Ordering::Acquire) + })) +} + /// The caller also drains its batch. Multiple workers can therefore build /// different chains without ever waiting for a free worker to start a piece. +/// A preload or backlog worker's build nobody waits for keeps its pieces on its own thread: helpers +/// would go to the workers whose builds binds wait for, ahead of them. pub(super) fn build_pieces(jobs: Vec) -> Vec { let count = jobs.len(); let jobs = Arc::new(Mutex::new(jobs.into_iter().enumerate().collect::>())); @@ -3907,8 +4299,11 @@ pub(super) fn build_pieces(jobs: Vec) -> Vec { }; // the helpers build for this worker's pipeline: the title waiting for it waits for them too let parent = BUILDING.with(|b| b.borrow().clone()); - let _ = start_normal_workers(); - for _ in 1..count.min(crate::gpu::recomp::dxc::compile_threads()) { + let width = if build_is_backlog_only() { 1 } else { count.min(crate::gpu::recomp::dxc::compile_threads()) }; + if width > 1 { + let _ = start_normal_workers(); + } + for _ in 1..width { let (drain, parent) = (drain.clone(), parent.clone()); let _ = queue().submit(Priority::BoundSoon, Box::new(move || { let before = BUILDING.with(|b| b.replace(parent)); @@ -3944,9 +4339,8 @@ pub fn release(p: usize) { } } -/// `standin` went to the title; `job` builds the real pipeline on a worker. pub fn submit(standin: usize, compute: bool, job: Job) { - submit_eager(standin, compute, job, 0, None); + submit_eager_with(standin, compute, job, 0, None, 0); } pub(super) fn submit_eager( @@ -3955,9 +4349,21 @@ pub(super) fn submit_eager( job: Job, key: u64, compute_key: Option, +) { + submit_eager_with(standin, compute, job, key, compute_key, 0); +} + +/// `submit_eager`, with a compute pipeline's console program for the log (`record`; 0: not known). +pub(super) fn submit_eager_with( + standin: usize, + compute: bool, + job: Job, + key: u64, + compute_key: Option, + record: u64, ) { let key = if super::pso_manifest::enabled() { key } else { 0 }; - submit_as(standin, compute, job, None, true, key, compute_key); + submit_as(standin, compute, job, None, true, key, compute_key, None, record); } /// Lazy pipeline creation (`XCL_LAZY_PSO=0`: off): a title's pipelines with console shaders get @@ -3971,9 +4377,10 @@ pub fn lazy() -> bool { } /// `submit`, sent to the workers only on its first `resolve` (`lazy`) – or now, at a low -/// priority, when an earlier run used a pipeline of these shaders (`key`, 0 = none; `used`). +/// priority, when an earlier run used a pipeline of these shaders (`key`, 0 = none; `used`) – +/// and built ahead of it by the backlog when no run used them yet (`send_ahead`). pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) { - submit_lazy_keyed(standin, compute, job, key, None); + submit_lazy_keyed_with(standin, compute, job, key, None, None, 0); } pub(super) fn submit_lazy_keyed( @@ -3983,7 +4390,22 @@ pub(super) fn submit_lazy_keyed( key: u64, compute_key: Option, ) { - submit_as(standin, compute, job, None, false, key, compute_key); + submit_lazy_keyed_with(standin, compute, job, key, compute_key, None, 0); +} + +/// `submit_lazy_keyed`, with the pipeline's translation and DXC compile on their own (`warm`): the +/// backlog does that for every pipeline it holds before the driver builds any of them. `record`: +/// a compute pipeline's console program, for the log (0: not known). +pub(super) fn submit_lazy_keyed_with( + standin: usize, + compute: bool, + job: Job, + key: u64, + compute_key: Option, + warm: Option, + record: u64, +) { + submit_as(standin, compute, job, None, false, key, compute_key, warm, record); } pub(super) fn submit_recipe_keyed( @@ -3993,11 +4415,32 @@ pub(super) fn submit_recipe_keyed( send: bool, key: u64, compute_key: Option, +) { + submit_recipe_keyed_with(standin, compute, recipe, send, key, compute_key, None, 0); +} + +/// `submit_recipe_keyed` with a lazy pipeline's translation ahead (`warm`) and a compute +/// pipeline's console program (`record`), as `submit_lazy_keyed_with` has them. +#[allow(clippy::too_many_arguments)] +pub(super) fn submit_recipe_keyed_with( + standin: usize, + compute: bool, + recipe: Recipe, + send: bool, + key: u64, + compute_key: Option, + warm: Option, + record: u64, ) { let job = recipe.initial_job(); - submit_as(standin, compute, job, Some(recipe), send, key, compute_key); + submit_as(standin, compute, job, Some(recipe), send, key, compute_key, warm, record); } +/// A lazy pipeline's translation and DXC compile without the driver's: what makes the DXIL +/// caches (in memory and on disk) hold its shaders, so its build is the driver's compile only. +pub type Warm = Box; + +#[allow(clippy::too_many_arguments)] fn submit_as( standin: usize, compute: bool, @@ -4006,9 +4449,13 @@ fn submit_as( send: bool, key: u64, compute_key: Option, + warm: Option, + record: u64, ) { debug_assert!(compute || compute_key.is_none()); let kind = PipelineKind::submitted(compute, super::console_list::enabled()); + // (false: an earlier submit of the same compute build made it and decided where it goes) + let mut created = true; let build = if let Some(compute_key) = compute_key { let mut removed = None; let mut retired_build = None; @@ -4035,6 +4482,7 @@ fn submit_as( }); if let Some(build) = active { COALESCING.hit(); + created = false; build } else { // A dead, completed, or orphaned value is removed only when this exact key is @@ -4044,9 +4492,9 @@ fn submit_as( COALESCING.finished(1); } let compute_key = Arc::new(compute_key); - let build = Arc::new(Build::new_keyed_kind( - job, false, Some(compute_key.clone()), recipe, kind, - )); + let build = Arc::new( + Build::new_keyed_kind(job, false, Some(compute_key.clone()), recipe, kind).with_submit(!send, record, warm), + ); builds.insert(compute_key, Arc::downgrade(&build)); COALESCING.unique(); build @@ -4056,9 +4504,7 @@ fn submit_as( drop(retired_build); build } else { - Arc::new(Build::new_keyed_kind( - job, false, None, recipe, kind, - )) + Arc::new(Build::new_keyed_kind(job, false, None, recipe, kind).with_submit(!send, record, warm)) }; let p = Arc::new(Pending { build: build.clone(), @@ -4073,6 +4519,13 @@ fn submit_as( on_use: Default::default(), }); build.tracked.store(true, Ordering::Release); + if !send { + LAZY_MADE.fetch_add(1, Ordering::Relaxed); + if !compute { + LAZY_GRAPHICS.fetch_add(1, Ordering::Relaxed); + } + start_stats(); + } PENDING.insert(standin, p.clone()); static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { @@ -4082,6 +4535,10 @@ fn submit_as( schedule(&build, Priority::BoundSoon, false, None); } else if let Some(rank) = used::rank(key).filter(|_| preload_enabled()) { schedule(&build, Priority::Preload, true, Some(rank)); + } else if created && key != 0 { + // (shaders no earlier run used: the backlog builds it ahead of its first use, its + // translation first when it has one, as commit and `XCL_PSO_AHEAD` allow) + send_ahead(&build); } } @@ -4111,17 +4568,52 @@ pub(crate) fn shaders_of(key: u64, shaders: Vec) { used::parts(key, shaders); } +/// Whether the active console profile is Xbox Series S (`lockhart`): checks `state::boot()` +/// first (already folded with `xcl.toml` and `XCL_DEVICE_TYPE` in the host process), then falls +/// back to `XCL_DEVICE_TYPE` for standalone `xcl shaders --used-only` and preparation workers +/// where no boot record is loaded. +pub(crate) fn profile_is_series_s() -> bool { + profile_is_series_s_from( + crate::state::boot().map(|b| b.config.is_series_s()), + std::env::var("XCL_DEVICE_TYPE").ok().as_deref(), + ) +} + +fn profile_is_series_s_from(boot_series_s: Option, env_device_type: Option<&str>) -> bool { + if let Some(series_s) = boot_series_s { + return series_s; + } + env_device_type.and_then(crate::config::parse_device_type) == Some("lockhart") +} + +/// File name for a per-profile usage or replay manifest beside the DXIL cache: Series X +/// (`anaconda`, default) keeps `{stem}.{ext}` unchanged; Series S (`lockhart`) uses +/// `{stem}-lockhart.{ext}` so switching profiles does not cross-pollinate startup preparation +/// or runtime preload lists. +pub(crate) fn used_file_name(stem: &str, ext: &str, series_s: bool) -> String { + if series_s { format!("{stem}-lockhart.{ext}") } else { format!("{stem}.{ext}") } +} + +pub(crate) fn used_pipelines_name() -> String { + used_file_name("used-pipelines", "txt", profile_is_series_s()) +} + +pub(crate) fn used_shaders_name() -> String { + used_file_name("used-shaders", "txt", profile_is_series_s()) +} + /// The shaders of the pipelines earlier runs used, each by its own key (`used-shaders.txt` -/// beside the DXIL cache): what a title's shader preparation translates. Empty before a run -/// with this list has used a pipeline. +/// or `used-shaders-lockhart.txt` beside the DXIL cache): what a title's shader preparation +/// translates. Empty before a run with this list has used a pipeline. pub fn earlier_used_shaders() -> std::collections::HashSet { - used::parse(&std::fs::read_to_string(crate::gpu::recomp::dxc::cache_dir().join("used-shaders.txt")).unwrap_or_default()) + used::parse(&std::fs::read_to_string(crate::gpu::recomp::dxc::cache_dir().join(used_shaders_name())).unwrap_or_default()) } -/// The keys of the pipelines earlier runs used (`used-pipelines.txt` beside the DXIL cache): -/// what `xcl shaders --precompile --used-only` builds. +/// The keys of the pipelines earlier runs used (`used-pipelines.txt` or +/// `used-pipelines-lockhart.txt` beside the DXIL cache): what +/// `xcl shaders --precompile --used-only` builds. pub fn earlier_used_keys() -> std::collections::HashSet { - used::parse(&std::fs::read_to_string(crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt")).unwrap_or_default()) + used::parse(&std::fs::read_to_string(crate::gpu::recomp::dxc::cache_dir().join(used_pipelines_name())).unwrap_or_default()) } /// Ask the used-pipeline writer to finish without ever joining it unboundedly. @@ -4189,13 +4681,13 @@ mod used { shaders: Mutex::new((HashSet::new(), None)), }; } - let path = crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"); + let path = crate::gpu::recomp::dxc::cache_dir().join(super::used_pipelines_name()); let earlier = parse_ranked(&std::fs::read_to_string(&path).unwrap_or_default()); if !earlier.is_empty() { crate::xlog_info!("D3D12.X: the pipelines of {} shader sets an earlier run used are built ahead of their first use", earlier.len()); } let now = Journal::file(path.clone(), earlier.keys().copied().collect()); - let shaders_path = path.with_file_name("used-shaders.txt"); + let shaders_path = path.with_file_name(super::used_shaders_name()); let shaders = parse(&std::fs::read_to_string(&shaders_path).unwrap_or_default()); let shaders_file = std::fs::OpenOptions::new().create(true).append(true).open(&shaders_path).ok(); Used { @@ -4270,6 +4762,271 @@ fn preload_enabled() -> bool { *ENABLED.get_or_init(|| !std::env::var("XCL_PSO_PRELOAD").is_ok_and(|v| v.trim() == "0")) } +/// The workers that build lazy pipelines no earlier run used ahead of their first use +/// (`XCL_PSO_PRELOAD=0`: off, with main's ranked preload), in the order of `Backlog`, on threads +/// of their own (`xcl-pso-ahead-*`) beside main's preload band (`xcl-pso-pre-*`: the pipelines of +/// earlier runs, `used::rank`), at the lowest priority: a pipeline that is bound is not held up +/// by the ones made ahead (whoever takes `job` first builds it; a bind's wait raises the worker +/// building it), and the title's own threads are not either. +struct Preload { + list: Mutex, + cv: Condvar, +} + +/// The lazy pipelines no earlier run used, to build ahead of their first use, in this order: the +/// compute ones binds go on without (`spared`); the title's other compute pipelines; then its +/// graphics pipelines, first translated and compiled by DXC all of them (`Warm`: milliseconds to +/// seconds each, no driver memory kept, and the disk caches hold them for the next run), then +/// built by the driver one by one. (Those of earlier runs are main's ranked preload.) A retail +/// title made its ~2 700 pipelines in its first 6 s and bound some of them for the first time up +/// to 150 s later: each such bind waited 7 – 15 s for its pipeline, one after another, and no +/// frame came for 156 s. A compute pipeline is waited for at its first dispatch (or its +/// dispatches are skipped: `XCL_CS_PSO_WAIT_MS`), and one no earlier run used was built only +/// then: a retail title's thread spent 57 s in the driver on one. Those are built by one worker +/// at a time (`compute_out`): a title has ~1 600 of them, some a minute each in the driver, and +/// with every worker on them the graphics pipelines would wait for all of them and be built at +/// their first draws instead. A pipeline a bind wants is not taken from here (`unclaimed`): the +/// workers build it at once, and a huge driver compile ahead of its use gives its turn to any +/// other and takes no giant slot (`real::big_compile_turn`). +#[derive(Default)] +struct Backlog { + /// compute pipelines no earlier run used + compute: std::collections::VecDeque>, + /// a worker builds one of `compute` or `spared` (`next` hands out no other until `built`) + compute_out: bool, + /// compute pipelines binds go on without while they are built (`image_only`), sent here at + /// their first bind (`send_spared`): used, so built before `compute` and with no room or cap + spared: std::collections::VecDeque>, + warm: std::collections::VecDeque>, + cold: std::collections::VecDeque>, +} + +/// What a backlog worker does with a pipeline. +enum Step { + /// its build (`ahead`: of a pipeline nobody used yet – counts against `ahead_cap`; + /// `new_compute`: in the lane of `Backlog::compute`, `Backlog::built` after it) + Build { ahead: bool, new_compute: bool }, + /// its translation and DXC compile; then back to the backlog for its build + Warm(Warm), +} + +impl Backlog { + fn push(&mut self, build: Arc) { + if build.is_compute() { + self.compute.push_back(build); + } else if build.warm.lock().unwrap().is_some() { + self.warm.push_back(build); + } else { + self.cold.push_back(build); + } + } + + fn len(&self) -> usize { + self.compute.len() + self.spared.len() + self.warm.len() + self.cold.len() + } + + /// The next piece of work. `ahead`: pipelines nobody used yet may be worked on now + /// (`XCL_PSO_AHEAD`, free commit: `ahead_room`); `builds`: one more of them may be built by + /// the driver (`ahead_cap`). Without them those wait here. + fn next(&mut self, ahead: bool, builds: bool) -> Option<(Arc, Step)> { + // (`sent`: its copy in another lane is passed over there) + if !self.compute_out { + while let Some(build) = self.spared.pop_front() { + if build.untaken() { + self.compute_out = true; + return Some((build, Step::Build { ahead: false, new_compute: true })); + } + } + } + if ahead && builds && !self.compute_out { + while let Some(build) = self.compute.pop_front() { + if build.unclaimed() { + self.compute_out = true; + return Some((build, Step::Build { ahead: true, new_compute: true })); + } + } + } + if !ahead { + return None; + } + while let Some(build) = self.warm.pop_front() { + if !build.unclaimed() { + continue; + } + let warm = build.warm.lock().unwrap().take(); + match warm { + Some(w) => return Some((build, Step::Warm(w))), + None => self.cold.push_back(build), + } + } + if !builds { + return None; + } + while let Some(build) = self.cold.pop_front() { + if build.unclaimed() { + return Some((build, Step::Build { ahead: true, new_compute: false })); + } + } + None + } + + /// The build `next` handed out as `Step::Build` is over (built, or taken by a bind). + fn built(&mut self, new_compute: bool) { + if new_compute { + self.compute_out = false; + } + } +} + +/// Lazy pipelines no earlier run used that the driver builds ahead of their first use +/// (`XCL_PSO_AHEAD`, default 4096; 0: none, and none translated ahead either – only those of +/// earlier runs are built ahead then). Each pipeline built keeps ~400 KB in the driver whether +/// the title uses it or not: a retail game made ~51 000 and used few. +fn ahead_cap() -> usize { + static V: OnceLock = OnceLock::new(); + *V.get_or_init(|| ahead_cap_of(std::env::var("XCL_PSO_AHEAD").ok().as_deref())) +} + +fn ahead_cap_of(v: Option<&str>) -> usize { + v.and_then(|v| v.trim().parse::().ok()).unwrap_or(4096) +} + +/// Commit that must be free for building ahead pipelines no earlier run used: the 6 GB DXC's +/// compiles keep free for a running title (`dxc::wait_for_memory`) and 2 GB more. Below it they +/// wait in the backlog (pipelines of an earlier run are built as before). +const AHEAD_FREE: u64 = 8 << 30; + +fn ahead_room() -> bool { + ahead_cap() > 0 && super::real::big_compile_commit_free(AHEAD_FREE) +} + +/// pipelines no earlier run used: translated ahead, built ahead by the backlog (`ahead_cap`); +/// pipelines in the backlog +static WARMED: AtomicUsize = AtomicUsize::new(0); +static AHEAD_BUILDS: AtomicUsize = AtomicUsize::new(0); +static BACKLOG: AtomicUsize = AtomicUsize::new(0); + +/// One more pipeline built ahead of its first use (by the backlog, or main's ranked preload): +/// the log line at powers of two, one count for both. +fn note_built_ahead() { + static DONE: AtomicUsize = AtomicUsize::new(0); + let n = DONE.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + crate::xlog_info!("D3D12.X: {n} pipelines built ahead of their first use"); + } +} + +/// The backlog and its workers, started at the first use (None: `XCL_PSO_PRELOAD=0`). +fn preload_backlog() -> Option<&'static Preload> { + static Q: OnceLock> = OnceLock::new(); + static STARTED: std::sync::Once = std::sync::Once::new(); + let q = Q + .get_or_init(|| preload_enabled().then(|| Preload { list: Mutex::new(Backlog::default()), cv: Condvar::new() })) + .as_ref()?; + STARTED.call_once(|| { + let n = (crate::gpu::recomp::dxc::compile_threads() / 4).clamp(2, 4); + for _ in 0..n { + spawn_backlog_worker(q); + } + }); + Some(q) +} + +/// One more worker of the backlog (`preload_backlog`; `build_parks` starts one in a parked one's +/// place). It builds through `run_build` as a preload worker: a bind's wait raises it. +fn spawn_backlog_worker(q: &'static Preload) { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let k = NEXT.fetch_add(1, Ordering::Relaxed); + let _ = std::thread::Builder::new().name(format!("xcl-pso-ahead-{k}")).stack_size(64 << 20).spawn(move || { + unsafe { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); + } + PRELOAD_WORKER.set(true); + loop { + let (build, step) = { + let mut g = q.list.lock().unwrap(); + loop { + let next = g.next(ahead_room(), AHEAD_BUILDS.load(Ordering::Relaxed) < ahead_cap()); + BACKLOG.store(g.len(), Ordering::Relaxed); + if let Some(next) = next { + break next; + } + // (pipelines waiting for free commit are looked at again in a second) + g = q.cv.wait_timeout(g, std::time::Duration::from_secs(1)).unwrap().0; + } + }; + let (ahead, new_compute) = match step { + Step::Warm(warm) => { + // (a translation that panics loses its warm-up, not this worker) + if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(warm)) { + crate::xlog_error!("D3D12.X: panic while translating a pipeline ahead: {}", panic_message(payload.as_ref())); + } + WARMED.fetch_add(1, Ordering::Relaxed); + if build.unclaimed() { + q.list.lock().unwrap().cold.push_back(build); + } + continue; + } + Step::Build { ahead, new_compute } => (ahead, new_compute), + }; + // (released meanwhile: its job goes; None: a bind's worker took it and builds it) + let job = if build.orphan.load(Ordering::Acquire) { + drop_unstarted_job(&build); + None + } else { + build.job.lock().unwrap().take() + }; + if let Some(job) = job { + if ahead { + AHEAD_BUILDS.fetch_add(1, Ordering::Relaxed); + } + PRELOAD_STEP.with(|s| s.set(Some(new_compute))); + run_build(&build, job); + let parked = PRELOAD_STEP.with(|s| s.take()).is_none(); + note_built_ahead(); + // (its lane went back and another worker took its place: `build_parks`) + if parked { + return; + } + } + q.list.lock().unwrap().built(new_compute); + } + }); +} + +/// A lazy pipeline no earlier run used (called by `submit_as` for a Build it created, `key` != 0, +/// not known to `used::rank`): to the backlog, built ahead of its first use. Nothing with +/// `XCL_PSO_AHEAD=0` or without the backlog. +fn send_ahead(build: &Arc) { + if ahead_cap() == 0 { + return; + } + let Some(q) = preload_backlog() else { return }; + let mut b = q.list.lock().unwrap(); + b.push(build.clone()); + BACKLOG.store(b.len(), Ordering::Relaxed); + q.cv.notify_one(); +} + +/// The build of a pipeline binds do not wait for (`image_only`) goes to the backlog `q`, in the +/// lane of new compute pipelines (`Backlog::spared`: one at a time), not to the workers builds a +/// bind waits for go to: there each of them, unwanted, waited for the one unwanted slot of huge +/// driver compiles, and with more of them than workers a build a bind waited for stood in the +/// queue behind them. The caller has set `build.sent` (`resolve_spared`). Without the backlog +/// (`XCL_PSO_PRELOAD=0`): to those workers. +fn send_spared(build: &Arc, q: Option<&Preload>) { + let Some(q) = q else { + // (`schedule` sends only a build not sent yet) + build.sent.store(false, Ordering::Release); + schedule(build, Priority::BoundSoon, false, None); + return; + }; + let mut b = q.list.lock().unwrap(); + b.spared.push_back(build.clone()); + BACKLOG.store(b.len(), Ordering::Relaxed); + q.cv.notify_one(); +} #[cfg(test)] mod used_tests { use super::*; @@ -9306,7 +10063,8 @@ mod used_tests { } /// A lazy pipeline of shaders an earlier run used is built without a bind; another one is - /// built only at its first use, and that use is kept for the next run. + /// not kept as used until its first use (the backlog may build it ahead of that: `send_ahead`), + /// and that use is kept for the next run. #[test] fn a_pipeline_an_earlier_run_used_is_built_ahead_of_its_first_use() { let (known, unknown) = (0x7E57_7001usize, 0x7E57_7002usize); @@ -9320,8 +10078,7 @@ mod used_tests { } assert!(!is_pending(known), "built by the workers that build ahead, with no bind"); assert_eq!(resolve(known), 0x4321); - assert!(is_pending(unknown), "nobody used it and no earlier run did"); - assert!(!used::noted(unknown_key)); + assert!(!used::noted(unknown_key), "nobody used it and no earlier run did"); assert_eq!(resolve_wait(unknown), 0x4322); assert!(used::noted(unknown_key) && used::noted(known_key), "a first use is kept for the next run"); released(known); @@ -9515,6 +10272,389 @@ mod used_tests { calls.end(5, 9, t_stale); } + /// The pipeline line's counts: lazy pipelines made (graphics among them), built at their + /// first use or before it, with a huge program; a bind's wait is counted with its time, and + /// one under a second is not logged. + #[test] + fn lazy_pipelines_and_the_waits_for_them_are_counted() { + let before = stats(); + let (first_use, ahead) = (0x7E57_C001usize, 0x7E57_C002usize); + submit_lazy(first_use, true, Box::new(|| { + std::thread::sleep(std::time::Duration::from_millis(5)); + note_huge(); + 0x6161 + }), 0); + let key = 0x5EED_C002u64; + used::earlier_run_used(key); + submit_lazy(ahead, false, Box::new(|| 0x6262), key); + let start = std::time::Instant::now(); + while is_pending(ahead) && start.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(!is_pending(ahead), "built ahead with no bind"); + assert_eq!(resolve_wait_for(first_use, None), 0x6161); + assert!(!entry(first_use).unwrap().build.warned.load(Ordering::Relaxed), "a short wait is not logged"); + let after = stats(); + assert!(after.made >= before.made + 2 && after.graphics > before.graphics, "{before:?} → {after:?}"); + assert!(after.built >= before.built + 2 && after.ahead > before.ahead && after.huge > before.huge, "{before:?} → {after:?}"); + assert!(after.waits.0 > before.waits.0 && after.waits.1 >= before.waits.1 + 5000, "{before:?} → {after:?}"); + released(first_use); + released(ahead); + } + + /// The line is written when a count changed, with the waits of its 2 s only. + #[test] + fn the_pipeline_line_comes_when_a_count_changed() { + let last = Stats { made: 10, graphics: 8, built: 2, ahead: 1, huge: 0, warmed: 4, backlog: 6, waits: (3, 4_000_000) }; + assert_eq!(stats_line(&last, &last, 256), None); + let now = Stats { built: 3, waits: (5, 6_500_000), ..last }; + let line = stats_line(&now, &last, 256).unwrap(); + assert!(line.contains("10 made (8 graphics), 3 built (1 before their first use, 0 with 256 KB of DXIL or more), 4 translated ahead, 6 in the build-ahead backlog"), "{line}"); + assert!(line.contains("waited 2500 ms for pipelines being built (2 waits in 2 s)"), "{line}"); + } + + /// A compute pipeline sent to the workers when made (`XCL_LAZY_PSO=0`) carries its console + /// program as a lazy one does: a late one is logged by it (`resolve_within`). + #[test] + fn a_pipeline_sent_to_the_workers_when_made_carries_its_record() { + let standin = 0x7E57_C026usize; + let (go, finish) = mpsc::channel::<()>(); + submit_eager_with(standin, true, Box::new(move || { + let _ = finish.recv(); + 0x6A6A + }), 0, None, 0x5EED_C026); + assert_eq!(entry(standin).map(|p| p.build.record), Some(0x5EED_C026)); + go.send(()).unwrap(); + assert_eq!(resolve_wait_for(standin, None), 0x6A6A); + released(standin); + } + + /// A lazy graphics pipeline of shaders no run used yet is translated, then built, with no + /// bind – when commit is free. + #[test] + fn a_lazy_graphics_pipeline_is_translated_then_built_ahead_of_its_first_use() { + let standin = 0x7E57_C010usize; + let warmed = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let w = warmed.clone(); + let room = ahead_room(); + submit_lazy_keyed_with( + standin, + false, + Box::new(move || if w.load(Ordering::Acquire) { 0x6464 } else { 1 }), + 0x5EED_C010, + None, + Some(Box::new(move || warmed.store(true, Ordering::Release))), + 0, + ); + let start = std::time::Instant::now(); + let limit = std::time::Duration::from_secs(if room { 10 } else { 1 }); + while is_pending(standin) && start.elapsed() < limit { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + if room { + assert!(!is_pending(standin), "built with no bind"); + assert_eq!(resolve(standin), 0x6464, "translated before the driver built it"); + } else { + assert!(is_pending(standin), "short of commit: not built ahead"); + } + released(standin); + } + + /// A build's warm-up goes when the build is over or will not run (`complete`, + /// `drop_unstarted_job`): what the translation ahead holds is of no use then. + #[test] + fn a_finished_or_dropped_build_lets_its_warm_up_go() { + let built = Arc::new(Build::new(Box::new(|| 0), false).with_submit(true, 0, Some(Box::new(|| {}) as Warm))); + assert!(built.lazy && built.warm.lock().unwrap().is_some()); + complete(&built, 0); + assert!(built.warm.lock().unwrap().is_none(), "complete drops it"); + let dropped = Arc::new(Build::new(Box::new(|| 0), false).with_submit(true, 0x5EED_C027, Some(Box::new(|| {}) as Warm))); + assert_eq!(dropped.record, 0x5EED_C027); + drop_unstarted_job(&dropped); + assert!(dropped.warm.lock().unwrap().is_none(), "an unstarted job's goes with it"); + } + + /// A dispatch is put off to the submit only where it would wait now: not with a pipeline that + /// writes only images (its dispatches are left out while it is built) nor with one a bind + /// already waited for past its budget. A submit that says it will wait for a pipeline counts + /// once among its waiters however often it says so, and leaves when that wait runs out; a + /// late or spared pipeline it does not count at all. + #[test] + fn a_dispatch_is_put_off_only_where_it_would_wait() { + let (plain, spared) = (0x7E57_F001usize, 0x7E57_F002usize); + let (go, finish) = mpsc::channel::<()>(); + let finish = Arc::new(Mutex::new(finish)); + for standin in [plain, spared] { + let finish = finish.clone(); + submit_lazy(standin, true, Box::new(move || { + let _ = finish.lock().unwrap().recv_timeout(std::time::Duration::from_secs(10)); + 0x7171 + }), 0); + } + image_only(spared); + assert!(waits_for(plain)); + assert!(!waits_for(spared), "its dispatches are left out while it is built"); + let p = entry(plain).unwrap(); + want(plain); + want(plain); + assert_eq!(p.build.demand.lock().unwrap().waiters, 1, "a submit counts once"); + assert!(p.build.wanted.load(Ordering::Acquire)); + assert_eq!(resolve_within(&p, plain, std::time::Duration::from_millis(50)), plain); + assert_eq!(p.build.demand.lock().unwrap().waiters, 0, "the submit's count leaves with the wait that ran out"); + assert!(!p.build.wanted.load(Ordering::Acquire), "nobody waits: not wanted"); + assert!(!waits_for(plain), "late: binds go on without it"); + // a later submit that puts it off does not wait for it: it does not count + want(plain); + assert_eq!(p.build.demand.lock().unwrap().waiters, 0, "a late build stays unwanted"); + assert_eq!(resolve_within(&p, plain, std::time::Duration::from_millis(50)), plain); + assert_eq!(p.build.demand.lock().unwrap().waiters, 0); + // a submit counted before another thread's wait made it late leaves at its own + { + let mut d = p.build.demand.lock().unwrap(); + d.ahead = true; + p.build.add_waiter(&mut d); + } + assert_eq!(resolve_within(&p, plain, std::time::Duration::from_millis(50)), plain); + assert_eq!(p.build.demand.lock().unwrap().waiters, 0, "the submit's count leaves with its wait for a late build"); + want(spared); + assert_eq!(entry(spared).unwrap().build.demand.lock().unwrap().waiters, 0, "nobody waits for a spared build"); + drop(go); + let start = std::time::Instant::now(); + while (is_pending(plain) || is_pending(spared)) && start.elapsed() < std::time::Duration::from_secs(20) { + let _ = resolve(spared); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(!waits_for(plain) && !waits_for(spared), "built"); + let _ = released(plain); + let _ = released(spared); + } + + #[test] + fn the_put_off_line_says_what_became_of_the_put_off_dispatches() { + let last = PutOffStats::default(); + assert_eq!(put_off_line(&last, &last), None); + let idle = PutOffStats { needed: 5, ..last }; + assert_eq!(put_off_line(&idle, &last), None, "nothing put off: no line"); + let now = PutOffStats { calls: [12, 1, 9, 2, 1], needed: 7, waits: (6, 2_500_000), segments: 24 }; + let before = PutOffStats { calls: [4, 0, 4, 0, 0], waits: (2, 500_000), ..Default::default() }; + let line = put_off_line(&now, &before).unwrap(); + assert!(line.contains("12 put off to the submit (8 in 2 s), 1 waited in the call"), "{line}"); + assert!(line.contains("at submits 9 recorded, 2 skipped (build failed or late), 1 dropped"), "{line}"); + assert!(line.contains("7 pipelines needed by a submit;"), "{line}"); + assert!(line.contains("submits waited 2000 ms for them in 2 s (4 waits; 2500 ms so far)"), "{line}"); + assert!(line.contains("at most 24 segments in a recording"), "{line}"); + assert_eq!(put_off_line(&now, &now), None, "nothing changed: no line"); + } + + /// A wait that passes a second is noted on its pipeline (and logged once for it). + #[test] + fn a_wait_past_a_second_is_noted_on_its_pipeline() { + let standin = 0x7E57_C003usize; + submit(standin, false, Box::new(|| { + std::thread::sleep(std::time::Duration::from_millis(1100)); + 0x6363 + })); + let p = entry(standin).unwrap(); + assert_eq!(resolve_wait_for(standin, None), 0x6363); + assert!(p.build.warned.load(Ordering::Relaxed)); + released(standin); + } + + /// A build that takes 600 ms and gives `real`. + fn slow(real: usize) -> Job { + Box::new(move || { + std::thread::sleep(std::time::Duration::from_millis(600)); + real + }) + } + + /// The budget for graphics pipelines is a thread's for a second, not one for each pipeline: + /// once it is spent the next pipeline is not waited for at all, it comes back with time + /// (half of it in half a second) and never grows past itself. With a budget for each + /// pipeline a title's thread stood still that long for every one of hundreds of pipelines + /// it used for the first time. + #[test] + fn the_graphics_budget_is_a_threads_for_a_second() { + use std::time::{Duration, Instant}; + std::thread::spawn(|| { + let budget = Duration::from_millis(100); + let t0 = Instant::now(); + assert_eq!(gfx_wait_left(budget, t0), budget, "all of it at first"); + gfx_wait_spent(Duration::from_millis(100)); + assert_eq!(gfx_wait_left(budget, t0), Duration::ZERO, "spent: the next pipeline is not waited for"); + let half = gfx_wait_left(budget, t0 + Duration::from_millis(500)); + assert!((half.as_secs_f64() - 0.050).abs() < 0.001, "half a second later half of it is back: {half:?}"); + assert_eq!(gfx_wait_left(budget, t0 + Duration::from_secs(5)), budget, "never more than the budget"); + gfx_wait_spent(Duration::from_millis(30)); + let left = gfx_wait_left(budget, t0 + Duration::from_secs(5)); + assert!((left.as_secs_f64() - 0.070).abs() < 0.001, "what was waited is taken off: {left:?}"); + gfx_wait_spent(Duration::from_secs(9)); + assert_eq!(gfx_wait_left(budget, t0 + Duration::from_secs(5)), Duration::ZERO, "a long wait leaves nothing, not a debt"); + }) + .join() + .unwrap(); + } + + /// With a budget for graphics pipelines a draw waits no longer than it and later draws of + /// that pipeline do not wait; a dispatch waits for its compute pipeline however long it takes. + #[test] + fn only_a_graphics_pipeline_is_left_after_its_budget() { + use std::time::{Duration, Instant}; + let (gfx, cs) = (0x7E57_C020usize, 0x7E57_C021usize); + submit(gfx, false, slow(0x6565)); + submit(cs, true, slow(0x6666)); + let budget = Some(Duration::from_millis(30)); + let t = Instant::now(); + assert_eq!(resolve_wait_budgets(gfx, None, budget, None), gfx, "not built within the budget: the stand-in"); + assert!(t.elapsed() < Duration::from_millis(400), "waited {:?}", t.elapsed()); + let t = Instant::now(); + assert_eq!(resolve_wait_budgets(gfx, None, budget, None), gfx); + assert!(t.elapsed() < Duration::from_millis(20), "a late pipeline is not waited for again ({:?})", t.elapsed()); + assert_eq!(resolve_wait_budgets(cs, None, budget, None), 0x6666, "a compute pipeline is waited for"); + let start = Instant::now(); + while is_pending(gfx) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(resolve_wait_budgets(gfx, None, budget, None), 0x6565, "built by a worker"); + let all = Some(Duration::from_secs(5)); + assert_eq!(budget_for(true, all, budget, None), all, "XCL_PSO_WAIT_MS still holds for compute"); + assert_eq!(budget_for(false, all, None, None), all); + assert_eq!(budget_for(false, all, budget, None), budget); + assert_eq!(budget_of(None), None); + assert_eq!(budget_of(Some("0")), None, "0: wait until built"); + assert_eq!(budget_of(Some(" 250 ")), Some(Duration::from_millis(250))); + assert_eq!(budget_of(Some("soon")), None); + released(gfx); + released(cs); + } + + /// A build a bind gave up waiting for is no longer wanted (it goes back behind the gate of + /// huge driver compiles); it was wanted while the bind waited. + #[test] + fn a_build_is_no_longer_wanted_once_its_wait_ran_out() { + use std::time::{Duration, Instant}; + let standin = 0x7E57_C022usize; + let (started_tx, started) = mpsc::channel(); + submit(standin, false, Box::new(move || { + started_tx.send(()).unwrap(); + let until = |want: bool| { + let t = Instant::now(); + while build_is_wanted() != want && t.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(1)); + } + build_is_wanted() == want + }; + if until(true) && until(false) { 0x6767 } else { 1 } + })); + started.recv().unwrap(); + assert_eq!(resolve_wait_budgets(standin, None, Some(Duration::from_millis(300)), None), standin); + let start = Instant::now(); + while is_pending(standin) && start.elapsed() < Duration::from_secs(20) { + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(resolve(standin), 0x6767, "wanted while the bind waited, not after it gave up"); + released(standin); + } + + /// With a budget of compute pipelines (`XCL_CS_PSO_WAIT_MS`) a dispatch waits no longer than + /// it and later dispatches of that pipeline do not wait; the bind's thread does not build the + /// pipeline, a worker does – also a lazy one nobody sent to the workers yet. Without it a + /// compute pipeline is waited for as before. + #[test] + fn a_compute_pipeline_is_waited_for_no_longer_than_its_own_budget() { + use std::time::{Duration, Instant}; + let standin = 0x7E57_C023usize; + let (built_on, on) = mpsc::channel(); + let (go, finish) = mpsc::channel::<()>(); + submit_lazy(standin, true, Box::new(move || { + let _ = built_on.send(std::thread::current().id()); + let _ = finish.recv(); + 0x6868 + }), 0); + let cs = Some(Duration::from_millis(30)); + let t = Instant::now(); + assert_eq!(resolve_wait_budgets(standin, None, None, cs), standin, "not built within the budget: the stand-in"); + assert!(t.elapsed() < Duration::from_millis(400), "waited {:?}", t.elapsed()); + let builder = on.recv_timeout(Duration::from_secs(10)).expect("a worker builds it"); + assert_ne!(builder, std::thread::current().id(), "the bind's thread does not build it"); + let t = Instant::now(); + assert_eq!(resolve_wait_budgets(standin, None, None, cs), standin); + assert!(t.elapsed() < Duration::from_millis(20), "a late pipeline is not waited for again ({:?})", t.elapsed()); + go.send(()).unwrap(); + let start = Instant::now(); + while is_pending(standin) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(resolve_wait_budgets(standin, None, None, cs), 0x6868, "built by a worker"); + released(standin); + let (all, gfx) = (Some(Duration::from_secs(5)), Some(Duration::from_millis(100))); + assert_eq!(budget_for(true, None, None, None), None, "unset: a compute pipeline is waited for until it is built"); + assert_eq!(budget_for(true, None, gfx, None), None, "the graphics budget is not one of compute pipelines"); + assert_eq!(budget_for(true, all, gfx, None), all, "unset: XCL_PSO_WAIT_MS as before"); + assert_eq!(budget_for(true, all, gfx, cs), cs, "its own before XCL_PSO_WAIT_MS"); + assert_eq!(budget_for(true, None, None, cs), cs); + assert_eq!(budget_for(false, all, None, cs), all, "not one of graphics pipelines"); + assert_eq!(budget_for(false, None, gfx, cs), gfx); + assert_eq!(budget_for(false, None, None, cs), None); + } + + /// A late compute program is logged once, not once for each of its pipelines. + #[test] + fn a_late_compute_program_is_logged_once() { + assert!(first_late(0x5EED_C024)); + assert!(!first_late(0x5EED_C024), "another pipeline of the same program"); + assert!(first_late(0x5EED_C025)); + } + + /// `peek` names the real pipeline once built and, unlike `resolve`, neither notes a use nor + /// sends a lazy one to the workers. + #[test] + fn a_peek_changes_nothing() { + let standin = 0x7E57_C0DEusize; + let build = Arc::new(Build::new(Box::new(|| 0), false)); + let p = Arc::new(Pending { + build: build.clone(), + driver: AtomicUsize::new(0), + compute: false, + key: 0x5EED_C0DE, + manifest_recipe: AtomicU64::new(0), + track_used: true, + used: Default::default(), + late: Default::default(), + spared: Default::default(), + on_use: Default::default(), + }); + PENDING.insert(standin, p.clone()); + assert_eq!(peek(standin), standin, "not built"); + assert!(!build.sent.load(Ordering::Acquire) && !build.used.load(Ordering::Relaxed)); + build.real.store(0x6A6B, Ordering::Release); + assert_eq!(peek(standin), 0x6A6B); + assert_eq!(peek(0x7E57_C0DF), 0x7E57_C0DF, "not async"); + assert!(Arc::ptr_eq(&PENDING.remove(standin).unwrap(), &p)); + } + + #[test] + fn used_manifests_separate_series_s_from_series_x() { + assert_eq!(used_file_name("used-pipelines", "txt", false), "used-pipelines.txt"); + assert_eq!(used_file_name("used-shaders", "txt", false), "used-shaders.txt"); + assert_eq!(used_file_name("used-graphics-pipelines", "bin", false), "used-graphics-pipelines.bin"); + assert_eq!(used_file_name("used-pipelines", "txt", true), "used-pipelines-lockhart.txt"); + assert_eq!(used_file_name("used-shaders", "txt", true), "used-shaders-lockhart.txt"); + assert_eq!(used_file_name("used-graphics-pipelines", "bin", true), "used-graphics-pipelines-lockhart.bin"); + + // Host boot config takes precedence over environment variables. + assert!(profile_is_series_s_from(Some(true), Some("anaconda"))); + assert!(!profile_is_series_s_from(Some(false), Some("lockhart"))); + // Standalone CLI / preparation workers without a boot record fall back to XCL_DEVICE_TYPE. + for raw in ["lockhart", "Series S", "series_s", "xss", "S"] { + assert!(profile_is_series_s_from(None, Some(raw)), "{raw}"); + } + for raw in ["anaconda", "Series X", "xsx", "X", "", "unknown"] { + assert!(!profile_is_series_s_from(None, Some(raw)), "{raw}"); + } + assert!(!profile_is_series_s_from(None, None)); + } + #[test] fn released_queued_pipeline_drops_job_immediately_before_workers_drain() { let _sat = WORKER_SATURATION_LOCK.lock().unwrap_or_else(|e| e.into_inner()); @@ -9670,25 +10810,109 @@ fn resolve_pending(p: &Pending, pso: usize) -> usize { p.note_use(); match p.build.real.load(Ordering::Acquire) { 0 => { - // a lazy one is wanted now: to the workers + // a lazy one is wanted now: to the workers (one binds do not wait for to the + // backlog's lane, as `resolve_spared` sends it: a bind no longer waits for a compute + // pipeline, its dispatch does) let stand = p.stand(pso); - schedule(&p.build, Priority::BoundSoon, false, None); - p.build.promote(Priority::Foreground); + if p.spared.load(Ordering::Acquire) { + if !p.build.sent.swap(true, Ordering::AcqRel) { + send_spared(&p.build, preload_backlog()); + } + } else { + schedule(&p.build, Priority::BoundSoon, false, None); + p.build.promote(Priority::Foreground); + } stand } r => r, } } +/// `resolve` with no side effects (for a report): the real pipeline behind `pso` once built, +/// else `pso` itself – no use noted, nothing sent to the workers. +pub(super) fn peek(pso: usize) -> usize { + entry(pso).map(|p| p.build.real.load(Ordering::Acquire)).filter(|&r| r != 0).unwrap_or(pso) +} + /// `resolve`, waiting for a pipeline still being built on a foreground worker. pub fn resolve_wait(pso: usize) -> usize { - resolve_wait_for(pso, wait_budget()) + resolve_wait_budgets(pso, wait_budget(), gfx_wait_budget(), cs_wait_budget()) } /// The pipeline to bind and whether that exact choice was a stand-in for an unfinished build. /// The answer stays true if a successful build ends after this bind chose its stand-in. pub fn resolve_wait_bound(pso: usize) -> (usize, bool) { - resolve_wait_bound_for(pso, wait_budget()) + let Some(p) = entry(pso) else { return (pso, false) }; + let bound = resolve_wait_budgets(pso, wait_budget(), gfx_wait_budget(), cs_wait_budget()); + (bound, p.bound_unbuilt(pso, bound)) +} + +/// `resolve_wait_bound` with one `budget` for the pipeline (None: until it is built). +#[cfg(test)] +fn resolve_wait_bound_for(pso: usize, budget: Option) -> (usize, bool) { + let Some(p) = entry(pso) else { return (pso, false) }; + let bound = resolve_wait_for(pso, budget); + (bound, p.bound_unbuilt(pso, bound)) +} + +/// `resolve_wait` with the budget of every pipeline (`XCL_PSO_WAIT_MS`), the one of graphics +/// pipelines (`XCL_GFX_PSO_WAIT_MS`) and the one of compute pipelines (`XCL_CS_PSO_WAIT_MS`). +fn resolve_wait_budgets(pso: usize, all: Option, gfx: Option, cs: Option) -> usize { + let Some(compute) = entry(pso).map(|p| p.compute) else { return resolve_wait_for(pso, None) }; + match gfx.filter(|_| !compute) { + // the graphics budget is a thread's for a second, not one for each pipeline + Some(budget) => { + let start = std::time::Instant::now(); + let r = resolve_wait_for(pso, Some(gfx_wait_left(budget, start))); + gfx_wait_spent(start.elapsed()); + r + } + None => resolve_wait_for(pso, budget_for(compute, all, gfx, cs)), + } +} + +thread_local! { + /// What this thread may still wait for graphics pipelines (`gfx_wait_left`): the + /// milliseconds left, and when they were last counted. + static GFX_WAIT: std::cell::Cell<(f64, Option)> = const { std::cell::Cell::new((0.0, None)) }; +} + +/// How long this thread may wait for a graphics pipeline at `now`, with `budget` to spend in a +/// second: what is left of it (it fills again at `budget` a second, to `budget` at most). +/// +/// The budget is not one for each pipeline: the first frames of a title's world bind hundreds +/// of pipelines never used before, one draw after another on one thread. With 500 ms for each, +/// a retail title's thread stood still 500 ms more than 500 times in a row on a cold cache and +/// showed no frame for minutes, although every one of those pipelines was being built +/// meanwhile. With a share of the thread's time instead, the wait is spent on the first ones +/// (and on any that is built within milliseconds: a pipeline made from a kept blob), the +/// thread goes on, and the rest draw once they are built. +fn gfx_wait_left(budget: std::time::Duration, now: std::time::Instant) -> std::time::Duration { + GFX_WAIT.with(|w| { + let (left, at) = w.get(); + let full = budget.as_secs_f64() * 1000.0; + let left = match at { + None => full, + Some(at) => (left + now.saturating_duration_since(at).as_secs_f64() * full).min(full), + }; + w.set((left, Some(now))); + std::time::Duration::from_secs_f64(left / 1000.0) + }) +} + +/// This thread waited `waited` for a graphics pipeline (`gfx_wait_left`). +fn gfx_wait_spent(waited: std::time::Duration) { + GFX_WAIT.with(|w| { + let (left, at) = w.get(); + w.set(((left - waited.as_secs_f64() * 1000.0).max(0.0), at)); + }) +} + +/// How long a bind waits for a pipeline of this kind: a compute one by `cs` if there is one, else +/// by `all` (a skipped dispatch leaves out data for later work: `cs_wait_budget`), a graphics one +/// by `gfx` if there is one. +fn budget_for(compute: bool, all: Option, gfx: Option, cs: Option) -> Option { + if compute { cs.or(all) } else { gfx.or(all) } } /// `resolve_wait`, waiting at most `budget` (None: until the pipeline is built). @@ -9701,43 +10925,116 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { resolve_wait_pending(&p, pso, budget) } -fn resolve_wait_bound_for(pso: usize, budget: Option) -> (usize, bool) { - let Some(p) = entry(pso) else { return (pso, false) }; - p.note_use(); - let bound = resolve_wait_pending(&p, pso, budget); - (bound, p.bound_unbuilt(pso, bound)) -} - fn resolve_wait_pending(p: &Arc, pso: usize, budget: Option) -> usize { if let real @ 1.. = p.build.real.load(Ordering::Acquire) { return real; } - let bound = if p.spared.load(Ordering::Acquire) { - resolve_spared(p, pso) - } else { - // (the title's thread is held from here until the pipeline is built or the budget is over) - let waiting = !*p.build.done.lock().unwrap(); - let _held = waiting.then(Held::new); - let _stall = waiting.then(|| crate::stall::span(crate::stall::StallKind::PipelineWait)).flatten(); - if let Some(budget) = budget { - resolve_within(p, pso, budget) - } else { - // Mark it wanted before an unsent build is queued: the worker and its DXC/driver - // admission see demand from their first instruction. An already queued build is - // promoted by `want`. - p.build.want(); - schedule(&p.build, Priority::Foreground, false, None); - let mut done = p.build.done.lock().unwrap(); - while !*done { - done = p.build.cv.wait(done).unwrap(); + if p.spared.load(Ordering::Acquire) { + return resolve_spared(p, pso); + } + if let Some(budget) = budget { + return resolve_within(p, pso, budget); + } + if *p.build.done.lock().unwrap() { + return built_or(p, pso); + } + // (the title's thread is held from here until the pipeline is built) + let _stall = crate::stall::span(crate::stall::StallKind::PipelineWait); + let mut wait = Wait::new(p); + // Mark it wanted before an unsent build is queued: the worker and its DXC/driver + // admission see demand from their first instruction. An already queued build is + // promoted by `want`. + p.build.want(); + schedule(&p.build, Priority::Foreground, false, None); + wait.until_done(None); + built_or(p, pso) +} + +/// `p`'s real pipeline once built, else `pso` (its stand-in). +fn built_or(p: &Pending, pso: usize) -> usize { + match p.build.real.load(Ordering::Acquire) { + 0 => p.stand(pso), + r => r, + } +} + +/// A wait of one of the title's threads for a pipeline still being built: the title is held +/// (`title_held`), the time is counted (`api_cost::Call::PipelineWait`, the pipeline line), and +/// the first wait for a pipeline that passes 1 s is logged with the thread and the pipeline's +/// kind – a draw or dispatch of the title stands still meanwhile. +struct Wait<'a> { + p: &'a Pending, + start: std::time::Instant, + /// this wait logged that it passed 1 s + logged: bool, + _held: Held, + _cost: crate::hle::api_cost::Timer, +} + +/// A wait this long is logged (once a build). +const LONG_WAIT: std::time::Duration = std::time::Duration::from_secs(1); + +impl<'a> Wait<'a> { + fn new(p: &'a Pending) -> Wait<'a> { + Wait { p, start: std::time::Instant::now(), logged: false, _held: Held::new(), _cost: crate::hle::api_cost::time(crate::hle::api_cost::Call::PipelineWait) } + } + + fn kind(&self) -> &'static str { + if self.p.compute { "compute" } else { "graphics" } + } + + /// Until the pipeline is built (true) or `budget` from the start of the wait is over + /// (false; None: no budget). + fn until_done(&mut self, budget: Option) -> bool { + let build = &self.p.build; + loop { + let waited = self.start.elapsed(); + if waited >= LONG_WAIT && !build.warned.swap(true, Ordering::Relaxed) { + self.logged = true; + crate::xlog_warn!( + "D3D12.X: thread {} has waited {} ms for a {} pipeline still being built (its draw or dispatch stands still)", + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }, + waited.as_millis(), + self.kind() + ); + } + let mut step = budget.map(|b| b.saturating_sub(waited)); + if !build.warned.load(Ordering::Relaxed) { + let to_long = LONG_WAIT.saturating_sub(waited); + step = Some(step.map_or(to_long, |s| s.min(to_long))); + } + let done = build.done.lock().unwrap(); + let done = match step { + None => build.cv.wait_while(done, |d| !*d).unwrap(), + Some(s) => build.cv.wait_timeout_while(done, s, |d| !*d).unwrap().0, + }; + if *done { + return true; } - match p.build.real.load(Ordering::Acquire) { - 0 => p.stand(pso), - r => r, + drop(done); + if budget.is_some_and(|b| self.start.elapsed() >= b) { + return false; } } - }; - bound + } +} + +impl Drop for Wait<'_> { + fn drop(&mut self) { + let waited = self.start.elapsed(); + if is_at_submit() { + SUBMIT_WAITS.fetch_add(1, Ordering::Relaxed); + SUBMIT_WAIT_US.fetch_add(waited.as_micros() as u64, Ordering::Relaxed); + } + if self.logged || (waited >= LONG_WAIT && !self.p.build.warned.swap(true, Ordering::Relaxed)) { + crate::xlog_warn!( + "D3D12.X: thread {} waited {} ms for a {} pipeline being built", + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }, + waited.as_millis(), + self.kind() + ); + } + } } /// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; unset or 0: until @@ -9745,7 +11042,7 @@ fn resolve_wait_pending(p: &Arc, pso: usize, budget: Option Option { static B: OnceLock> = OnceLock::new(); - *B.get_or_init(|| std::env::var("XCL_PSO_WAIT_MS").ok().and_then(|v| v.trim().parse::().ok()).filter(|&ms| ms > 0).map(std::time::Duration::from_millis)) + *B.get_or_init(|| budget_of(std::env::var("XCL_PSO_WAIT_MS").ok().as_deref())) } /// Whether binds have an explicit time bound. A dispatch is then recorded immediately instead of @@ -9754,28 +11051,76 @@ pub(super) fn waits_bounded() -> bool { wait_budget().is_some() } +/// How long a thread's draws wait in a second for graphics pipelines still being built +/// (`XCL_GFX_PSO_WAIT_MS`; unset or 0: as `wait_budget`, for each pipeline; `gfx_wait_left` has +/// why it is a share of the thread's time). A draw past it goes on with the stand-in, which draws +/// nothing, and so do the later draws of that pipeline until it is built. On a retail title the +/// draws of its world waited 7 – 15 s each for pipelines built one after another: no frame for +/// 156 s. Off by default: on a cold cache a logo and UI text drawn once and kept were missing +/// when draws did not wait. +fn gfx_wait_budget() -> Option { + static B: OnceLock> = OnceLock::new(); + *B.get_or_init(|| budget_of(std::env::var("XCL_GFX_PSO_WAIT_MS").ok().as_deref())) +} + +/// How long a bind waits for a compute pipeline still being built (`XCL_CS_PSO_WAIT_MS`; unset +/// or 0: as `wait_budget`). The bind's thread never builds the pipeline itself: the build goes to +/// the workers (`resolve_within`; a huge driver compile also waits for free commit at the gate +/// once nobody waits), and past the budget the pipeline's dispatches are skipped until it is +/// built – what they compute is missing or old meanwhile, the counts of later ExecuteIndirects +/// among it (`indirect_guard` zeroes only counts out of range). A retail title's thread spent +/// 57 s in the driver's compiler on one program no earlier run had used, and another of its +/// threads waited for it all that time: no frame for 57 s. +fn cs_wait_budget() -> Option { + static B: OnceLock> = OnceLock::new(); + *B.get_or_init(|| budget_of(std::env::var("XCL_CS_PSO_WAIT_MS").ok().as_deref())) +} + +/// A compute pipeline's dispatches go on without it while it is built (`XCL_CS_PSO_WAIT_MS`): +/// what builds one on a title's thread hands it to a thread of its own instead +/// (`real::dispatch_chain::whole_ready`). +pub(super) fn cs_goes_on() -> bool { + cs_wait_budget().is_some() +} + +/// A budget in milliseconds from the environment (unset, 0 or not a number: none). +fn budget_of(v: Option<&str>) -> Option { + v.and_then(|v| v.trim().parse::().ok()).filter(|&ms| ms > 0).map(std::time::Duration::from_millis) +} + /// `resolve_wait` for at most `budget`: the build goes to the workers (not this thread), and a /// pipeline not built by then is `late` – it and later binds of it get the stand-in (their -/// dispatches are skipped) until a worker has built it. +/// draws and dispatches are skipped) until a worker has built it. Its build is no longer wanted +/// (`Build::unwant`), but it was used: it goes before the builds ahead of first use. fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> usize { - let built = |p: &Pending| match p.build.real.load(Ordering::Acquire) { - 0 => p.stand(pso), - r => r, - }; if *p.build.done.lock().unwrap() { - return built(p); + return built_or(p, pso); } schedule(&p.build, Priority::BoundSoon, false, None); if p.late.load(Ordering::Acquire) { + // (a submit that counted itself ahead, `want`, before another wait made it late: it + // waits no more either) + p.build.unwant_ahead(); return p.stand(pso); } + // (the title's thread is held from here until the pipeline is built or the budget is over) + let _stall = crate::stall::span(crate::stall::StallKind::PipelineWait); + let mut wait = Wait::new(p); p.build.want(); - let (done, _) = p.build.cv.wait_timeout_while(p.build.done.lock().unwrap(), budget, |d| !*d).unwrap(); - if *done { - return built(p); + if wait.until_done(Some(budget)) { + return built_or(p, pso); } - drop(done); + drop(wait); p.late.store(true, Ordering::Release); + p.build.late.store(true, Ordering::Release); + p.build.unwant(); + p.build.unwant_ahead(); + if p.compute && p.build.record != 0 && cs_wait_budget().is_some() { + if first_late(p.build.record) { + crate::xlog_warn!("D3D12.X: compute pipeline of record {:016x} not built after {} ms: its dispatches are skipped until it is", p.build.record, budget.as_millis()); + } + return p.stand(pso); + } static N: AtomicUsize = AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); if n < 16 || n.is_power_of_two() { @@ -9784,6 +11129,13 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> p.stand(pso) } +/// The first late compute pipeline of console program `record` (`resolve_within`): its line is +/// written once a program, which a title makes with several root signatures. +fn first_late(record: u64) -> bool { + static SEEN: Mutex>> = Mutex::new(None); + SEEN.lock().unwrap().get_or_insert_with(Default::default).insert(record) +} + /// `XCL_PSO_IMAGE_SKIP=1`: a bind does not wait for a big compute program that writes nothing /// but images (`gpu::effects::big_and_image_only`); its dispatches are left out until a worker /// has built it. Off by default: what such a program draws is missing for that long. @@ -9811,7 +11163,10 @@ pub fn image_only(standin: usize) { fn resolve_spared(p: &Arc, pso: usize) -> usize { match p.build.real.load(Ordering::Acquire) { 0 => { - schedule(&p.build, Priority::BoundSoon, false, None); + if !p.build.sent.swap(true, Ordering::AcqRel) { + send_spared(&p.build, preload_backlog()); + } + p.build.late.store(true, Ordering::Release); if !*p.build.done.lock().unwrap() && !p.late.swap(true, Ordering::AcqRel) { static N: AtomicUsize = AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); @@ -9830,7 +11185,7 @@ pub fn resolve_for_bind(pso: usize) -> usize { match entry(pso) { Some(p) if p.compute => { p.note_use(); - resolve_wait_pending(&p, pso, wait_budget()) + resolve_wait_pending(&p, pso, budget_for(true, wait_budget(), None, cs_wait_budget())) } Some(p) => resolve_pending(&p, pso), None => { @@ -11053,13 +12408,62 @@ pub fn released(pso: usize) -> usize { released } +/// Whether a draw or dispatch with `pso` now has the pipeline it stands for: not a stand-in, or +/// one whose build succeeded (`put_off_line`'s skipped ones are those that had not). +pub(super) fn has_real(pso: usize) -> bool { + entry(pso).is_none_or(|p| p.build.real.load(Ordering::Acquire) != 0) +} + /// `pso` is a stand-in whose real pipeline is still being built. pub fn is_pending(pso: usize) -> bool { entry(pso).is_some_and(|p| !*p.build.done.lock().unwrap()) } +/// `pso` is a stand-in whose real pipeline is being built or was built, and `resolved`, what a +/// `resolve_wait` gave for it, is the stand-in (`pso` itself, or the driver pipeline a shared +/// stand-in binds: `shared`): the bind has the stand-in, also when the build finished since (a +/// failed build's stand-in is what draws for good). (`Pending::bound_unbuilt`, as +/// `resolve_wait_bound` answers it.) +pub fn gave_standin(pso: usize, resolved: usize) -> bool { + entry(pso).is_some_and(|p| p.bound_unbuilt(pso, resolved)) +} + +/// Whether a dispatch with `pso` would wait for its build now (`resolve_wait`): a pipeline still +/// being built that binds do not go on without – not one whose dispatches are left out while it +/// is built (`image_only`) or that a bind already waited for past its budget (`late`). Those go +/// on as they did, in the call, and their builds keep their place (not before the workers' +/// queue: `need_by_submit`). +pub fn waits_for(pso: usize) -> bool { + entry(pso).is_some_and(|p| !p.spared.load(Ordering::Acquire) && !p.late.load(Ordering::Acquire) && !*p.build.done.lock().unwrap()) +} + +/// A submit is about to wait for `pso` (one of its next put-off calls): it counts among the +/// build's waiters (`Build::want`) once, however often the submit says so, and leaves with +/// the wait for it when that runs out of its budget (`resolve_within`). Not for a pipeline the +/// submit will not wait for (late, or spared): nothing would take that count back, and its build +/// would stay wanted – ahead of the commit gate – until it is built. +pub fn want(pso: usize) { + if let Some(p) = entry(pso) { + want_ahead(&p); + } +} + +/// (`want`) Whether this call counted the submit among the waiters. +fn want_ahead(p: &Pending) -> bool { + { + // (under the lock: a wait that makes it late takes `ahead` back after it, `resolve_within`) + let mut d = p.build.demand.lock().unwrap(); + if p.late.load(Ordering::Acquire) || p.spared.load(Ordering::Acquire) || std::mem::replace(&mut d.ahead, true) { + return false; + } + p.build.add_waiter(&mut d); + } + p.build.wanted_now(); + true +} + /// A call with `pso` was put off to the submit, which will wait for it: its shared build is -/// wanted from record time and goes before the workers' queue. +/// wanted from record time (counted once, as `want`) and goes before the workers' queue. pub fn need_by_submit(pso: usize) { let Some(p) = entry(pso) else { return }; need_pending_by_submit(&p); @@ -11069,14 +12473,364 @@ fn need_pending_by_submit(p: &Arc) { if p.build.by_submit.load(Ordering::Acquire) { return; } - p.build.want(); + want_ahead(p); schedule(&p.build, Priority::BoundSoon, false, None); // True means all record-time demand work above is complete. Concurrent first callers may // repeat the idempotent promotion/schedule, but no caller observes publication too early. - p.build.by_submit.store(true, Ordering::Release); + if !p.build.by_submit.swap(true, Ordering::AcqRel) { + NEEDED_MADE.fetch_add(1, Ordering::Relaxed); + } +} + +/// What stand-in `pso` is (being) built from, for a diagnostic line (`dred::mark_pipeline`: a +/// pipeline bound with no label of its own). None: not a stand-in. +pub fn describe(pso: usize) -> Option { + let p = entry(pso)?; + let state = if p.build.real.load(Ordering::Acquire) != 0 { "" } else { ", not built yet" }; + Some(match (p.compute, p.build.record) { + (true, 0) => format!("a compute pipeline {pso:#x}{state}"), + (true, record) => format!("cs {record:016x}{state}"), + (false, _) => format!("a graphics pipeline {pso:#x} (shaders {:016x}){state}", p.key), + }) } /// (built in the background, failed, still building) pub fn counts() -> (usize, usize, usize) { (BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), QUEUED_BUILDS.load(Ordering::Relaxed)) } + +#[cfg(test)] +mod backlog_tests { + use super::*; + + /// A graphics pipeline for the backlog (`warm`: with its translation on its own), never built; + /// `key` is its `record` (what `drain` returns). + fn pending(key: u64, warm: bool) -> Arc { + Arc::new(Build::new_keyed_kind(Box::new(|| 0), false, None, None, PipelineKind::Graphics) + .with_submit(true, key, warm.then(|| Box::new(|| {}) as Warm))) + } + + /// A compute pipeline for the backlog, never built. + fn pending_compute(key: u64) -> Arc { + Arc::new(Build::new_keyed_kind(Box::new(|| 0), false, None, None, PipelineKind::Compute) + .with_submit(true, key, None)) + } + + /// A backlog worker's build nobody waits for builds the pieces of its dispatch chain itself: + /// none of them goes to the workers whose builds binds wait for. + #[test] + fn a_build_ahead_keeps_its_pieces_on_its_own_thread() { + let p = pending_compute(0x5EED_C1A1); + p.demand.lock().unwrap().preload_thread = 1; + let before = BUILDING.with(|b| b.replace(Some(p.clone()))); + let here = std::thread::current().id(); + let jobs: Vec = (0..6) + .map(|_| { + Box::new(move || { + std::thread::sleep(std::time::Duration::from_millis(20)); + usize::from(std::thread::current().id() == here) + }) as Job + }) + .collect(); + let on_here = build_pieces(jobs); + BUILDING.with(|b| *b.borrow_mut() = before); + assert_eq!(on_here, vec![1; 6], "every piece on the backlog worker's thread"); + } + + /// A piece whose build panics fails (0), on the caller's thread or a helper's, and the + /// caller still gets every other piece. + #[test] + fn a_piece_that_panics_fails_and_the_others_are_built() { + let jobs: Vec = (0..8usize) + .map(|i| { + Box::new(move || { + std::thread::sleep(std::time::Duration::from_millis(10)); + if i % 2 == 1 { + panic!("piece {i}"); + } + i + 1 + }) as Job + }) + .collect(); + assert_eq!(build_pieces(jobs), [1, 0, 3, 0, 5, 0, 7, 0]); + } + + /// Work from the backlog as its workers do (a translated one goes back for its build): the + /// record and step of each piece, in order. + fn drain(b: &mut Backlog, ahead: bool, builds: bool) -> Vec<(u64, &'static str)> { + let mut done = Vec::new(); + while let Some((p, step)) = b.next(ahead, builds) { + match step { + Step::Warm(w) => { + w(); + done.push((p.record, "warm")); + b.cold.push_back(p); + } + Step::Build { ahead, new_compute } => { + p.job.lock().unwrap().take(); + done.push((p.record, if ahead { "build ahead" } else { "build" })); + b.built(new_compute); + } + } + } + done + } + + /// Every pipeline is translated before the driver builds any of them; one a bind wants is + /// left to the workers. + #[test] + fn the_backlog_translates_every_new_pipeline_before_building_it() { + let mut b = Backlog::default(); + let wanted = pending(4, true); + wanted.sent.store(true, Ordering::Release); + b.push(pending(2, true)); + b.push(wanted); + b.push(pending(5, false)); + b.push(pending(3, true)); + assert_eq!(drain(&mut b, true, true), [(2, "warm"), (3, "warm"), (5, "build ahead"), (2, "build ahead"), (3, "build ahead")]); + assert_eq!(b.len(), 0); + } + + /// Switched off or short of commit (`ahead` false), nothing is worked on; past the cap + /// (`builds` false) the pipelines are translated but not built. They wait. + #[test] + fn nothing_is_built_ahead_when_switched_off_or_short_of_commit() { + let mut b = Backlog::default(); + b.push(pending(1, true)); + b.push(pending(2, false)); + assert!(drain(&mut b, false, true).is_empty()); + assert_eq!(b.len(), 2, "they wait"); + assert_eq!(drain(&mut b, true, false), [(1, "warm")]); + assert_eq!(b.len(), 2); + assert_eq!(drain(&mut b, true, true), [(2, "build ahead"), (1, "build ahead")]); + assert_eq!(ahead_cap_of(None), 4096); + assert_eq!(ahead_cap_of(Some(" 0 ")), 0, "XCL_PSO_AHEAD=0: off"); + assert_eq!(ahead_cap_of(Some("100")), 100); + assert_eq!(ahead_cap_of(Some("lots")), 4096); + } + + /// Compute pipelines have a lane of their own, before the graphics ones; they are built only + /// with room (`ahead`) and under the cap (`builds`), and one a bind wants is left to the + /// workers. + #[test] + fn new_compute_pipelines_are_built_before_graphics_ones() { + let mut b = Backlog::default(); + let wanted = pending_compute(6); + wanted.sent.store(true, Ordering::Release); + b.push(pending(1, true)); + b.push(pending_compute(3)); + b.push(wanted); + b.push(pending_compute(5)); + assert_eq!(drain(&mut b, true, true), [(3, "build ahead"), (5, "build ahead"), (1, "warm"), (1, "build ahead")]); + assert_eq!(b.len(), 0); + b.push(pending_compute(3)); + b.push(pending(2, false)); + assert!(drain(&mut b, false, true).is_empty()); + assert_eq!(b.len(), 2, "short of commit: they wait"); + assert!(drain(&mut b, true, false).is_empty()); + assert_eq!(b.len(), 2, "past the cap: they wait"); + assert_eq!(drain(&mut b, true, true), [(3, "build ahead"), (2, "build ahead")]); + } + + /// While a worker builds a new compute pipeline, the other workers get the graphics ones, not + /// the next new compute one. + #[test] + fn one_worker_at_a_time_builds_new_compute_pipelines() { + let mut b = Backlog::default(); + b.push(pending_compute(3)); + b.push(pending_compute(4)); + b.push(pending(1, false)); + let take = |b: &mut Backlog| b.next(true, true).map(|(p, step)| (p.record, matches!(step, Step::Build { new_compute: true, .. }))); + assert_eq!(take(&mut b), Some((3, true))); + assert_eq!(take(&mut b), Some((1, false)), "a graphics one while the new compute one is built"); + assert_eq!(take(&mut b), None, "the next new compute one waits for the one being built"); + b.built(false); + assert_eq!(take(&mut b), None); + b.built(true); + assert_eq!(take(&mut b), Some((4, true))); + } + + /// A pipeline binds go on without (`image_only`) goes to the backlog at its first bind, not to + /// the workers builds a bind waits for go to, and is built in the lane of new compute ones: + /// before them and one at a time with them, also short of commit and past the cap. Its place + /// in a lane from when it was made is passed over. + #[test] + fn a_pipeline_binds_go_on_without_is_built_by_the_backlog_one_at_a_time() { + let q = Preload { list: Mutex::new(Backlog::default()), cv: Condvar::new() }; + let spared = pending_compute(7); + { + let mut b = q.list.lock().unwrap(); + b.push(pending_compute(3)); + b.push(spared.clone()); + b.push(pending(2, false)); + } + // (as `resolve_spared` does) + spared.sent.store(true, Ordering::Release); + send_spared(&spared, Some(&q)); + let mut b = q.list.lock().unwrap(); + let mut take = |ahead: bool| { + b.next(ahead, ahead).map(|(p, step)| { + p.job.lock().unwrap().take(); + let Step::Build { ahead, new_compute } = step else { panic!("{} was not built", p.record) }; + (p.record, ahead, new_compute) + }) + }; + assert_eq!(take(false), Some((7, false, true)), "short of commit and past the cap it is built, in the new compute lane"); + assert_eq!(take(true), Some((2, true, false)), "a graphics one while it is built"); + assert_eq!(take(true), None, "the next new compute one waits for it"); + b.built(true); + assert_eq!(b.next(true, true).map(|(p, _)| p.record), Some(3)); + b.built(true); + assert!(b.next(true, true).is_none(), "its place from when it was made is passed over"); + assert_eq!(b.len(), 0); + } + + /// Bound under a wait budget, a pipeline binds go on without is built by a backlog worker, + /// not by the workers builds a bind waits for go to. + #[test] + fn a_pipeline_binds_go_on_without_is_not_built_by_the_workers_binds_wait_for() { + if preload_backlog().is_none() { + crate::gpu::recomp::runner::skip_test("no backlog (XCL_PSO_PRELOAD=0)"); + return; + } + let standin = 0x7E57_B0A3usize; + let (tx, rx) = mpsc::channel(); + submit_lazy(standin, true, Box::new(move || { + let _ = tx.send(std::thread::current().name().map(str::to_owned)); + 0x5C5C + }), 0); + image_only(standin); + assert_eq!(resolve_wait_for(standin, Some(std::time::Duration::from_millis(30))), standin, "still being built: the stand-in"); + let on = rx.recv_timeout(std::time::Duration::from_secs(10)).expect("a worker builds it"); + assert!(on.as_deref().is_some_and(|n| n.starts_with("xcl-pso-ahead-")), "built on {on:?}"); + let start = std::time::Instant::now(); + while is_pending(standin) && start.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(resolve_wait_for(standin, None), 0x5C5C); + let _ = released(standin); + } + + /// A lazy compute pipeline of shaders no run used yet is built with no bind – when commit is + /// free. + #[test] + fn a_lazy_compute_pipeline_of_new_shaders_is_built_ahead_of_its_first_use() { + let standin = 0x7E57_C011usize; + let room = ahead_room() && preload_backlog().is_some(); + submit_lazy(standin, true, Box::new(|| 0x6969), 0x5EED_C011); + let start = std::time::Instant::now(); + let limit = std::time::Duration::from_secs(if room { 10 } else { 1 }); + while is_pending(standin) && start.elapsed() < limit { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + if room { + assert!(!is_pending(standin), "built with no bind"); + assert_eq!(resolve(standin), 0x6969); + } else { + assert!(is_pending(standin), "short of commit: not built ahead"); + } + released(standin); + } + + /// The names of the backlog's workers alive now (`spawn_backlog_worker`). + fn preload_workers() -> Vec { + use windows_sys::Win32::Foundation::{CloseHandle, LocalFree, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, Thread32First, Thread32Next, TH32CS_SNAPTHREAD, THREADENTRY32}; + use windows_sys::Win32::System::Threading::{GetCurrentProcessId, GetThreadDescription, OpenThread, THREAD_QUERY_LIMITED_INFORMATION}; + let mut names = Vec::new(); + unsafe { + let snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + assert_ne!(snap, INVALID_HANDLE_VALUE, "no thread snapshot"); + let mut te: THREADENTRY32 = std::mem::zeroed(); + te.dwSize = std::mem::size_of::() as u32; + let mut ok = Thread32First(snap, &mut te) != 0; + while ok { + let h = if te.th32OwnerProcessID == GetCurrentProcessId() { OpenThread(THREAD_QUERY_LIMITED_INFORMATION, 0, te.th32ThreadID) } else { std::ptr::null_mut() }; + if !h.is_null() { + let mut p: *mut u16 = std::ptr::null_mut(); + if GetThreadDescription(h, &mut p) >= 0 && !p.is_null() { + let n = (0..).take_while(|&i| *p.add(i) != 0).count(); + let name = String::from_utf16_lossy(std::slice::from_raw_parts(p, n)); + LocalFree(p.cast()); + if name.starts_with("xcl-pso-ahead-") { + names.push(name); + } + } + CloseHandle(h); + } + ok = Thread32Next(snap, &mut te) != 0; + } + CloseHandle(snap); + } + names + } + + /// A giant build ahead on a backlog worker waits for its pipeline's first use + /// (`real::huge_compile_turn`) and does not stop the lane of new compute pipelines meanwhile: + /// the next one is built while it waits, by the worker that took the waiting one's place + /// (`build_parks`). Once a bind waits for it, it gets the giant slot and is built; its thread + /// then ends without giving the lane back a second time (it holds another worker's build), and + /// as many workers are left as before. Without that a pipeline the title never uses held the + /// lane for good. + #[test] + fn a_parked_giant_build_ahead_leaves_the_lane_of_new_compute_pipelines_to_the_next() { + use std::time::{Duration, Instant}; + let until = |done: &dyn Fn() -> bool, limit: Duration| { + let start = Instant::now(); + while !done() && start.elapsed() < limit { + std::thread::sleep(Duration::from_millis(5)); + } + done() + }; + if preload_backlog().is_none() || !ahead_room() { + crate::gpu::recomp::runner::skip_test("no build ahead (XCL_PSO_PRELOAD=0, XCL_PSO_AHEAD=0 or short of commit)"); + return; + } + // (as `preload_backlog` starts them; a thread names itself once it runs) + let workers = (crate::gpu::recomp::dxc::compile_threads() / 4).clamp(2, 4); + assert!(until(&|| preload_workers().len() == workers, Duration::from_secs(10)), "the backlog's workers: {:?}", preload_workers()); + let (giant, next, holder, last) = (0x7E57_C030usize, 0x7E57_C031usize, 0x7E57_C032usize, 0x7E57_C033usize); + // the giant build: its worker's name, then its turn at the giant slot + let (on_tx, on) = mpsc::channel(); + let (through_tx, through) = mpsc::channel(); + submit_lazy(giant, true, Box::new(move || { + let _ = on_tx.send(std::thread::current().name().map(str::to_owned)); + let slot = super::super::real::huge_compile_turn(super::super::real::GIANT_DRIVER_COMPILE); + let _ = through_tx.send(()); + drop(slot); + 0x6B6B + }), 0x5EED_C030); + let parked = on.recv_timeout(Duration::from_secs(10)).expect("a backlog worker builds it ahead").unwrap_or_default(); + assert!(parked.starts_with("xcl-pso-ahead-"), "built on {parked:?}"); + submit_lazy(next, true, Box::new(|| 0x6C6C), 0x5EED_C031); + assert!(until(&|| !is_pending(next), Duration::from_secs(10)), "the next new compute pipeline is not built while the giant one waits"); + assert!(is_pending(giant), "nobody used the giant one: it is not built"); + assert!(through.try_recv().is_err(), "a giant build ahead took its turn"); + assert!(until(&|| preload_workers().len() == workers + 1, Duration::from_secs(10)), "another worker took the waiting one's place: {:?}", preload_workers()); + // a new compute build the lane holds when the giant build ends + let (held_tx, held) = mpsc::channel(); + let (go, finish) = mpsc::channel::<()>(); + submit_lazy(holder, true, Box::new(move || { + let _ = held_tx.send(()); + let _ = finish.recv_timeout(Duration::from_secs(20)); + 0x6D6D + }), 0x5EED_C032); + held.recv_timeout(Duration::from_secs(10)).expect("the lane's next build starts"); + assert_eq!(resolve_wait_for(giant, None), 0x6B6B, "wanted, the giant build is made"); + assert!(through.try_recv().is_ok(), "it went through the giant slot"); + assert!(until(&|| !preload_workers().contains(&parked), Duration::from_secs(10)), "the waiting worker's thread did not end"); + assert_eq!(preload_workers().len(), workers, "as many workers as before: {:?}", preload_workers()); + // the lane is still the holder's: the giant build's end did not give it back again + submit_lazy(last, true, Box::new(|| 0x6E6E), 0x5EED_C033); + std::thread::sleep(Duration::from_millis(300)); + assert!(is_pending(last), "a second new compute build went while one was out"); + go.send(()).unwrap(); + assert!(until(&|| !is_pending(last), Duration::from_secs(10)), "the lane went back after the holder's build"); + assert_eq!(resolve(next), 0x6C6C); + assert_eq!(resolve(holder), 0x6D6D); + assert_eq!(resolve(last), 0x6E6E); + for standin in [giant, next, holder, last] { + released(standin); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 47152fddc8..1c1c731864 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -32,6 +32,7 @@ use windows::Win32::Graphics::Dxgi::*; use windows_sys::core::GUID; use super::layout::{self, Iface}; +use super::sharded::Sharded; use crate::stubs; use crate::util::{HRESULT, E_INVALIDARG, E_NOINTERFACE, E_OUTOFMEMORY, S_FALSE, S_OK}; @@ -39,6 +40,16 @@ const DLL: &str = "d3d12_xs.dll"; const EXTRA_SLOTS: usize = 64; const MAX_SCAN: usize = 512; +/// Where `$method` is in the PC interface `$iface` and every later version of it, looked up once +/// (`slot_of` asks for an object's class, by name, under one lock: a title records thousands of +/// these calls a frame on many threads). +macro_rules! pc_slot { + ($iface:literal, $method:literal) => {{ + static SLOT: OnceLock = OnceLock::new(); + *SLOT.get_or_init(|| layout::find($iface).and_then(|i| layout::slot(i, $method)).expect("method in layout")) + }}; +} + #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] pub enum Kind { Device, @@ -219,6 +230,9 @@ static FALLBACK_PSO: AtomicU64 = AtomicU64::new(0); static FAILED_PSO: AtomicU64 = AtomicU64::new(0); static FALLBACK_RS: AtomicU64 = AtomicU64::new(0); static TRANSLATED_PSO: AtomicU64 = AtomicU64::new(0); +/// console MS containers moved from the AS slot and translated (logged sparsely: a title +/// creates tens of thousands of these pipelines during boot) +static AS_SLOT_MS: AtomicU64 = AtomicU64::new(0); static TRANSLATE_ERRORS: Mutex> = Mutex::new(Vec::new()); #[derive(Clone, Copy)] @@ -452,7 +466,21 @@ pub fn abi_root_signature() -> Option { /// lifetime. static UMA_BUFFER: Mutex> = Mutex::new(Vec::new()); /// the committed UMA windows opened as D3D12 heaps (indexed by window `k`; `None` for sparse windows) -static UMA_HEAPS: Mutex>> = Mutex::new(Vec::new()); +/// Window heaps for `CreatePlacedResource` inside coherent UMA windows: for each window `k`, +/// contiguous `(seg_offset, seg_len, heap_raw)` segments (1 entry for single-heap windows, N for +/// `XCL_UMA_DRIVER=mixed:...`). +static UMA_HEAPS: Mutex>> = Mutex::new(Vec::new()); + +fn uma_heap_for(k: usize, offset: usize, len: usize) -> Option<(usize, usize)> { + let g = UMA_HEAPS.lock().unwrap(); + let segs = g.get(k)?; + for &(seg_off, seg_len, heap_raw) in segs { + if offset >= seg_off && offset.saturating_add(len) <= seg_off.saturating_add(seg_len) { + return Some((heap_raw, offset - seg_off)); + } + } + None +} /// console buffers placed in unified memory: resource → (address, bytes) /// address, bytes, whether XCL allocated the memory (not: the title's own, CreatePlacedResourceX) type UmaBuffer = (usize, usize, bool); @@ -479,8 +507,43 @@ pub fn uma_window_vas() -> Vec { UMA_BUFFER.lock().map(|g| g.iter().map(|b| b.1).collect()).unwrap_or_default() } -/// The window buffer holding `len` bytes at UMA address `p`, and their offset in it. +/// the windows' addresses again, for what asks for every draw and dispatch (0: no such window); +/// one for each window of the widest layout (16: a GPU view at window 8 or past had no PC address) +static UMA_WINDOW_VAS: [AtomicU64; crate::gpu::uma::MAX_HEAP_WINDOWS] = [const { AtomicU64::new(0) }; crate::gpu::uma::MAX_HEAP_WINDOWS]; +/// how many there are +static UMA_WINDOWS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// `uma_window_vas()[k]`, without its lock. +pub(super) fn uma_window_va(k: usize) -> Option { + (k < UMA_WINDOWS.load(Ordering::Acquire)).then(|| UMA_WINDOW_VAS[k].load(Ordering::Relaxed)) +} + +fn set_uma_windows(bufs: Vec<(usize, u64)>) { + UMA_WINDOWS.store(0, Ordering::Release); + for (at, b) in UMA_WINDOW_VAS.iter().zip(&bufs) { + at.store(b.1, Ordering::Relaxed); + } + UMA_WINDOWS.store(bufs.len().min(UMA_WINDOW_VAS.len()), Ordering::Release); + *UMA_BUFFER.lock().unwrap() = bufs; +} + +/// The window buffer holding `len` bytes at UMA address `p`, and their offset in it. Not for a +/// view window: what the lists' memory operations write is read back to the CPU at its own +/// address (`sparse::readback_after_execute`), and a GPU view has no CPU memory there. pub(super) fn uma_window_buffer(p: usize, len: usize) -> Option<(usize, u64)> { + let u = crate::gpu::uma::get()?; + let k = u.window_of(p).filter(|&k| !u.is_view_window(k))?; + let (base, size) = u.window(k); + if p - base + len > size { + return None; + } + Some((UMA_BUFFER.lock().ok()?.get(k)?.0, (p - base) as u64)) +} + +/// `uma_window_buffer`, and a view window's buffer too: for a caller that hands the range to +/// the GPU only, or reads and writes it on the CPU at `view_want::cpu` of the address (the CPU +/// cannot touch a GPU view), and that has asked for its tiles (`view_want::want`). +pub(super) fn uma_window_buffer_gpu(p: usize, len: usize) -> Option<(usize, u64)> { let u = crate::gpu::uma::get()?; let k = u.window_of(p)?; let (base, size) = u.window(k); @@ -494,7 +557,7 @@ pub(super) fn uma_window_buffer(p: usize, len: usize) -> Option<(usize, u64)> { pub fn uma_va_of(p: usize) -> Option { let u = crate::gpu::uma::get()?; let k = u.window_of(p)?; - Some(*uma_window_vas().get(k)? + (p - u.window(k).0) as u64) + Some(uma_window_va(k)? + (p - u.window(k).0) as u64) } /// What the start-up check of the coherent UMA windows found (`check_uma_import`): empty – not @@ -580,52 +643,98 @@ unsafe fn check_uma_import(device: &ID3D12Device, u: &crate::gpu::uma::Uma, bufs Ok(format!("ok, {} window(s), {} µs", probes.len(), t0.elapsed().as_micros())) } +/// `XCL_UMA_SHADOW`: 1 = the committed windows get GPU copies without asking for a heap over +/// them (to try the path on a GPU that has `OpenExistingHeapFromAddress`), 0 = never. +fn shadow_choice() -> Option { + std::env::var("XCL_UMA_SHADOW").ok().map(|v| v != "0") +} + unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) { let Some(u) = crate::gpu::uma::get() else { *UMA_ERROR.lock().unwrap() = "no UMA region".into(); return; }; - let open = |k: usize| -> Result<(usize, u64, usize), String> { - let (base, size) = u.window(k); - if allow_driver_remap && super::uma_driver::wanted(device) { - match super::uma_driver::remake(device, base, size) { - Ok((heap, buf)) => { - u.set_driver_window(k); - return Ok(super::uma_driver::raw(heap, buf)); - } - Err(e) => crate::xlog_warn!("D3D12.X: coherent window {k} stays imported: {e}"), - } + let buffer = |size: usize, flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let open = |k: usize| -> Result, String> { + if shadow_choice() == Some(true) { + return Ok(None); } let dev3: ID3D12Device3 = device.cast().map_err(|e| format!("ID3D12Device3: {e}"))?; - let heap: ID3D12Heap = dev3.OpenExistingHeapFromAddress(base as *const c_void).map_err(|e| format!("OpenExistingHeapFromAddress (window {k}): {e}"))?; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: size as u64, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER, - ..Default::default() + match dev3.OpenExistingHeapFromAddress::(u.window(k).0 as *const c_void) { + Ok(heap) => Ok(Some(heap)), + Err(e) if e.code() == windows::Win32::Foundation::E_NOTIMPL && shadow_choice() != Some(false) => { + *UMA_ERROR.lock().unwrap() = format!("OpenExistingHeapFromAddress (window {k}): {e}"); + Ok(None) + } + Err(e) => Err(format!("OpenExistingHeapFromAddress (window {k}): {e}")), + } + }; + let shadow = |k: usize| -> Result { + let desc = D3D12_HEAP_DESC { + SizeInBytes: u.window(k).1 as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES, }; - let mut buf: Option = None; - device.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("CreatePlacedResource: {e}"))?; - let buf = buf.ok_or("CreatePlacedResource")?; - let va = buf.GetGPUVirtualAddress(); - Ok((buf.into_raw() as usize, va, heap.into_raw() as usize)) + let mut heap: Option = None; + super::title_textures::own_work(|| device.CreateHeap(&desc, &mut heap)).map_err(|e| format!("CreateHeap (window {k}, {} MB of video memory): {e}", u.window(k).1 >> 20))?; + heap.ok_or_else(|| "CreateHeap".to_string()) }; let n = u.shader_windows(); let mut bufs: Vec<(usize, u64)> = vec![(0, 0); n]; - let mut heaps: Vec> = vec![None; n]; + let mut heaps: Vec> = vec![Vec::new(); n]; + let mut shadows: Vec<(usize, ID3D12Resource)> = Vec::new(); for k in 0..n { if !u.is_committed_window(k) { continue; } - match open(k) { + // on NVIDIA the window becomes a driver CUSTOM write-back L0 heap at its own address: the + // GPU's loads and atomics on imported pages are an order of magnitude slower (`uma_driver`) + if allow_driver_remap && shadow_choice() != Some(true) && super::uma_driver::wanted(device) { + let (base, size) = u.window(k); + match super::uma_driver::remake_window(device, base, size, u.committed_window() == Some(k)) { + Ok(remade) => { + u.set_driver_window(k); + if let Some(segs) = remade.watched_regions { + crate::gpu::uma::set_driver_watch_segments(k, segs); + } + bufs[k] = (remade.buf_raw, remade.gpu_va); + heaps[k] = remade.heaps; + continue; + } + Err(e) => crate::xlog_warn!("D3D12.X: coherent window {k} stays imported: {e}"), + } + } + let made = open(k).and_then(|heap| { + let shadowed = heap.is_none(); + let heap = match heap { + Some(h) => h, + None => shadow(k)?, + }; + let flags = if shadowed { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER }; + let mut buf: Option = None; + device.CreatePlacedResource(&heap, 0, &buffer(u.window(k).1, flags), D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("CreatePlacedResource: {e}"))?; + let buf = buf.ok_or("CreatePlacedResource")?; + if shadowed { + shadows.push((k, buf.clone())); + } + let va = buf.GetGPUVirtualAddress(); + Ok((buf.into_raw() as usize, va, heap.into_raw() as usize)) + }); + match made { Ok((buf_raw, va, heap_raw)) => { bufs[k] = (buf_raw, va); - heaps[k] = Some(heap_raw); + heaps[k] = vec![(0, u.window(k).1, heap_raw)]; } Err(e) => { crate::xlog_warn!("D3D12.X: UMA not available to the GPU: {e}"); @@ -634,7 +743,9 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) { } } } - let check = if std::env::var("XCL_UMA_CHECK").is_ok_and(|v| v == "0") { + let check = if !shadows.is_empty() { + Ok("not run: the coherent window has a copy in video memory (no host-memory heaps on this D3D12)".into()) + } else if std::env::var("XCL_UMA_CHECK").is_ok_and(|v| v == "0") { Ok("off (XCL_UMA_CHECK=0)".into()) } else { check_uma_import(device, u, &bufs) @@ -658,6 +769,23 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) { w0_va ); *UMA_HEAPS.lock().unwrap() = heaps; + for (k, buf) in &shadows { + let (base, size) = u.window(*k); + u.set_shadowed(); + if super::sparse::shadow_window(device, base, size, buf) { + crate::xlog_warn!( + "D3D12.X: UMA window {k} is not shared with the GPU ({}) \u{2013} {} MB of video memory at VA {:#x} stand for it: CPU writes are uploaded before each submit, GPU writes read back on Map and after the lists' memory writes", + match shadow_choice() { + Some(true) => "XCL_UMA_SHADOW=1", + _ => "OpenExistingHeapFromAddress is not implemented", + }, + size >> 20, + bufs[*k].1 + ); + } else { + crate::xlog_warn!("D3D12.X: UMA window {k} is not shared with the GPU and its copy in video memory is not kept in step"); + } + } // shaders take the windows from the shared descriptor heap (`pso::heap_windows`) if n > 1 && crate::gpu::recomp::pso::heap_windows() { let views: Vec<(usize, usize)> = bufs.iter().enumerate().map(|(k, b)| (b.0, u.window(k).1)).collect(); @@ -665,7 +793,7 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) { crate::xlog_info!("D3D12.X: memory windows from the shared descriptor heap (no per-access switch)"); } } - *UMA_BUFFER.lock().unwrap() = bufs; + set_uma_windows(bufs); } pub fn stats() -> D3d12Stats { @@ -740,8 +868,10 @@ pub fn device_raw() -> *mut c_void { DEVICE.load(Ordering::Acquire) as *mut c_void } -/// The process's video memory on the device's adapter: (local, non-local) bytes in use. -pub fn video_memory() -> Option<(u64, u64)> { +/// The process's video memory on the device's adapter: (local, non-local) bytes in use, and +/// the local budget – what Windows lets the process have of the card now, with what the other +/// programs hold taken off. Past it Windows moves the process's memory off the card. +pub fn video_memory() -> Option<(u64, u64, u64)> { use windows::Win32::Graphics::Dxgi::*; let raw = device_raw(); let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }?; @@ -753,10 +883,15 @@ pub fn video_memory() -> Option<(u64, u64)> { let mut non_local = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); adapter.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut local).ok()?; adapter.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut non_local).ok()?; - Some((local.CurrentUsage, non_local.CurrentUsage)) + Some((local.CurrentUsage, non_local.CurrentUsage, local.Budget)) } } +/// How far `used` is past `budget` (bytes; None: within it, or no budget known). +pub fn over_video_budget(used: u64, budget: u64) -> Option { + (budget != 0 && used > budget).then(|| used - budget) +} + /// The device runs only 32-lane waves: wave64 compute, mesh and geometry programs need the /// split form (`Options::split_wave64`). Unknown device: assume so. fn wave32_only(device: *mut c_void) -> bool { @@ -789,10 +924,19 @@ pub fn init() -> Result { init_with_remap(false) } +/// `init`; `allow_driver_remap`: the coherent windows may be remade as driver heaps +/// (`uma_driver`), only for the backend made before the title's code runs (`backend_before_guest`). pub(super) fn init_with_remap(allow_driver_remap: bool) -> Result { + // one at a time: two threads that both found no device made one each and opened the memory + // windows for it, and GPU work on the one device with window addresses of the other hung the + // GPU (unit tests; a title comes in through `backend`, which asks once) + static ONE: Mutex<()> = Mutex::new(()); + let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); if !device_raw().is_null() { return Ok(ADAPTER.lock().map(|a| a.clone()).unwrap_or_default()); } + #[cfg(test)] + OPENED.fetch_add(1, Ordering::Relaxed); unsafe { let cfg = crate::state::config(); match crate::gpu::agility::state() { @@ -815,22 +959,8 @@ pub(super) fn init_with_remap(allow_driver_remap: bool) -> Result( - &CLSID_D3D12DeviceRemovedExtendedData, - ) { - Ok(d) => { - d.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); - d.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); - } - Err(e) => { - crate::xlog_warn!("D3D12: DRED requested but unavailable: {e}"); - } - } - } + // `XCL_DRED=1` (`create_device` does it too; this call only puts the log line before the device) + crate::gpu::agility::enable_dred_once(); let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| format!("DXGI: {e}"))?; let mut device: Option = None; let mut name = String::new(); @@ -876,6 +1006,11 @@ pub(super) fn init_with_remap(allow_driver_remap: bool) -> Result bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("XCL_DRED").is_some()) +} + +/// With `XCL_DRED`: a resource, heap or pipeline the PC device made gets a name that says what +/// it is, for what a device removal reports about an address (`log_device_removed` lists the +/// allocations at the faulting address and those freed there lately by name). Later, more +/// telling names replace it (a memory window's buffer, a title's buffer placed over tiles). +unsafe fn name_for_report(obj: *mut c_void, kind: Kind) { + let name = match kind { + Kind::Resource => { + let Some(r) = ID3D12Resource::from_raw_borrowed(&obj) else { return }; + let d = r.GetDesc(); + if d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + format!("buffer {:#x} B flags {:#x}", d.Width, d.Flags.0) + } else { + format!("texture dim {} {}x{}x{} mips {} format {} samples {} flags {:#x}", d.Dimension.0, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels, d.Format.0, d.SampleDesc.Count, d.Flags.0) + } + } + Kind::Heap => { + let Some(h) = ID3D12Heap::from_raw_borrowed(&obj) else { return }; + let d = h.GetDesc(); + format!("heap {:#x} B type {} flags {:#x}", d.SizeInBytes, d.Properties.Type.0, d.Flags.0) + } + Kind::PipelineState => "pipeline state".to_string(), + _ => return, + }; + if let Some(o) = ID3D12Object::from_raw_borrowed(&obj) { + let _ = o.SetName(&windows::core::HSTRING::from(name)); + } +} + +/// `Release` of the COM interface pointer `p`, called through the vtable `p` itself has. +unsafe fn release_through_its_own_vtable(p: *mut c_void) -> u32 { + let vt = *(p as *const *const usize); + let release: RefFn = std::mem::transmute(*vt.add(2)); + release(p) +} + unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { if let Some(c) = CLASSES.lock().unwrap().iter().find(|c| c.orig == orig && c.kind == kind) { return c.ext; @@ -1164,13 +1343,15 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { // most derived PC interface this object implements let chain = layout::chain(kind.base()); let qi: QiFn = std::mem::transmute(*ot); - let release: RefFn = std::mem::transmute(*ot.add(2)); let mut iface = *chain.last().expect("layout chain"); for i in &chain { let iid = layout::parse_guid(i.iid); let mut out = std::ptr::null_mut(); if qi(obj, &iid, &mut out) >= 0 && !out.is_null() { - release(out); + // (through the result's own vtable: under the debug layer QueryInterface gives + // another object than `obj`, and `obj`'s Release on it read a null pointer in + // D3D12Core 1.5 s into a retail title's start) + release_through_its_own_vtable(out); iface = i; break; } @@ -1263,6 +1444,13 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { v[1 + i] = super::guard::make_tracer(v[1 + i], name); } } + // XCL_TWO_PASS_BATCH=2: a title call on a list with deferred two-pass draws records them + // first, unless it is one that cannot change what they draw (`bind::before_list_call`) + if kind == Kind::CommandList && super::bind::two_pass_defer() { + for (i, e) in v.iter_mut().enumerate().skip(1) { + *e = super::guard::make_before(*e, (i - 1) as u64, super::bind::before_list_call); + } + } let leaked: &'static [usize] = Box::leak(v.into_boxed_slice()); let ext = leaked.as_ptr() as usize + 8; EXTS.lock().unwrap().get_or_insert_with(HashSet::new).insert(ext); @@ -1294,6 +1482,17 @@ fn console_remap(kind: Kind) -> Vec<(usize, usize)> { } } +/// The PC method a title call through console command list slot `slot` (the older layout) runs, +/// by name (`console_remap`); the console's own methods by slot. +pub(super) fn list_slot_name(slot: usize) -> String { + let pc = console_remap(Kind::CommandList).into_iter().find(|e| e.0 == slot).map(|e| e.1).or((slot < 60).then_some(slot)); + let iface = layout::chain(Kind::CommandList.base()).first().copied(); + match (pc, iface) { + (Some(p), Some(i)) if p < i.methods.len() => i.methods[p].to_string(), + _ => format!("console list method #{slot}"), + } +} + /// console D3D12_DESCRIPTOR_HEAP_TYPE also used for CBV / SRV / UAV heaps const XBOX_EXTRA_CBV_SRV_UAV: u32 = 4; @@ -1324,6 +1523,7 @@ fn console_extensions(kind: Kind) -> Option { /// * device #76: `CreateCommittedResource` (heap properties, flags, desc, state, clear value, /// riid, ppv) as on PC #27 (PC #76 = CreateCommittedResource3); the console resource desc /// carries more after the 52 PC bytes (amd_fidelityfx_upscaler_xbox.dll writes 3 at +52). +/// * descriptor heap #8 GetDesc: a console heap's description as the title made it. /// * descriptor heap #9 / #10: the heap start handles come back in rax on the console. /// * resource #11 GetGPUVirtualAddress: console buffers live in unified memory; their console /// address (= CPU address, low 32 bits = offset in `mem`) is what console code gets. @@ -1393,7 +1593,7 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (133, x::create_placed_resource_layout_x as usize), ] } - Kind::DescriptorHeap => vec![(9, heap_cpu_start_x as usize), (10, heap_gpu_start_x as usize)], + Kind::DescriptorHeap => vec![(8, heap_get_desc_x as usize), (9, heap_cpu_start_x as usize), (10, heap_gpu_start_x as usize)], Kind::Resource => vec![(11, res_gpu_va_x as usize)], Kind::Fence => vec![(12, super::fence_x::completed_value_address as usize)], // the title's calls from #14 on: Signal / Wait / … / SignalX / PresentX at the slots of @@ -1455,6 +1655,7 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (61, l::fill32_x as usize), (62, l::fill64_x as usize), (63, l::fill128_x as usize), + (67, l::flush_pipeline_x as usize), (68, l::set_depth_bounds_x as usize), (69, l::write32_bottom_x as usize), (70, l::write64_bottom_x as usize), @@ -1469,6 +1670,10 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (90, l::write32_bottom_of_shader_x as usize), (93, l::kickoff_x as usize), (94, l::set_depth_bias_x as usize), + (127, b::dispatch_mesh as usize), + // the newer layout's (called before anything tells the layouts apart) + (131, l::flush_cache_range_x as usize), + (132, l::flush_cache_range_x as usize), // console compute/BVH builder extensions (`XboxBvhBuilder.dll`) (146, l::uav_barrier_x as usize), (148, b::allocate_upload_memory as usize), @@ -1478,6 +1683,34 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { } } +/// The descriptions console CBV/SRV/UAV and sampler heaps were made with (heap object, the +/// title's D3D12_DESCRIPTOR_HEAP_DESC), until the heap is released. +static CONSOLE_HEAP_DESCS: Mutex> = Mutex::new(Vec::new()); + +/// The description console heap `obj` was made with (None: not a console heap). +fn console_heap_desc(obj: usize) -> Option<[u32; 4]> { + CONSOLE_HEAP_DESCS.lock().unwrap().iter().find(|e| e.0 == obj).map(|e| e.1) +} + +/// descriptor heap #8 GetDesc → D3D12_DESCRIPTOR_HEAP_DESC (16 bytes), returned through a hidden +/// pointer the C++ way (this, buffer) or the C way (buffer, this) (`this_first`). A console heap +/// answers what the title made it with, not the PC heap's description: that has twice the slots +/// of a view heap, 2 048 samplers in a shader-visible sampler heap (`console_heap::pc_samplers`) +/// and no shader-visible flag on a view heap in the shared heap. A title that sized its writes +/// from the PC count would make descriptors past its slots, where `console_heap::slot` finds +/// none and the PC method writes at the console address. +unsafe extern "system" fn heap_get_desc_x(a: *mut c_void, b: *mut c_void) -> *mut [u32; 4] { + let (this, ret) = if this_first(a, b) { (a, b as *mut [u32; 4]) } else { (b, a as *mut [u32; 4]) }; + if let Some(d) = console_heap_desc(this as usize) { + if !ret.is_null() { + ret.write_unaligned(d); + } + return ret; + } + let f: unsafe extern "system" fn(*mut c_void, *mut [u32; 4]) -> *mut [u32; 4] = std::mem::transmute(orig_fn(this, 8)); + f(this, ret) +} + /// descriptor heap #9 / #10 GetCPU / GetGPUDescriptorHandleForHeapStart: console code /// takes the handle in rax (only `this` passed); the PC methods return it through a hidden /// pointer @@ -1501,25 +1734,48 @@ unsafe extern "system" fn heap_gpu_start_x(this: *mut c_void) -> u64 { h } +/// The PC heap behind a console CBV/SRV/UAV or sampler heap of description `d` (PC type): views +/// an SRV / UAV pair per console slot (in the shared shader-visible heap, the title's own a +/// CPU-only mirror when `shared` – `console_heap`); samplers one per slot, a shader-visible heap +/// all a shader can index (`console_heap::pc_samplers`). +fn pc_descriptor_heap_desc(d: [u32; 4], shared: bool) -> [u32; 4] { + let sampler = d[0] == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32; + let visible = d[2] & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32 != 0; + let pc_n = if sampler { super::console_heap::pc_samplers(d[1], visible) } else { d[1].saturating_mul(2) }; + let flags = if shared { d[2] & !(D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32) } else { d[2] }; + [d[0], pc_n, flags, d[3]] +} + +/// Every sampler of the PC sampler heap `heap`, all it holds, made the zero sampler: an S# of +/// zeros – a slot nothing was written to – is a sampler on the console: point filtering, wrap, +/// mip 0 only. So a table entry the title left empty samples as there (an unwritten PC +/// descriptor is undefined), as does an index past the title's slots (`console_heap::pc_samplers`). +unsafe fn zero_samplers(dev: &ID3D12Device, heap: &ID3D12DescriptorHeap) { + let zero = super::console_heap::zero_sampler(); + let cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr as u64; + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as u64; + for k in 0..heap.GetDesc().NumDescriptors as u64 { + dev.CreateSampler(&zero, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + k * inc) as usize }); + } +} + unsafe extern "system" fn dev_create_descriptor_heap_x(this: *mut c_void, desc: *const [u32; 4], riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let mut d = if desc.is_null() { [u32::MAX; 4] } else { *desc }; + let title = d; d[0] = pc_heap_type(d[0]); let desc = if desc.is_null() { desc } else { &d as *const [u32; 4] }; let sampler = d[0] == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32; if d[0] != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32 && !sampler { return dev_create_descriptor_heap(this, desc as usize, riid, ppv); } - // views: an SRV / UAV pair per console slot (in the shared shader-visible heap, the - // title's own a CPU-only mirror – `console_heap`); samplers: one per slot - let pc_n = if sampler { d[1] } else { d[1].saturating_mul(2) }; let visible = d[2] & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32 != 0; let shared = match ID3D12Device::from_raw_borrowed(&this) { Some(dev) if !sampler && !desc.is_null() => super::console_heap::shared_heap(dev), Some(dev) if sampler && !desc.is_null() => super::console_heap::shared_sampler_heap(dev), _ => false, }; - let flags = if shared { d[2] & !(D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32) } else { d[2] }; - let pc = [d[0], pc_n, flags, d[3]]; + let pc = pc_descriptor_heap_desc(d, shared); + let flags = pc[2]; let hr = dev_create_descriptor_heap(this, pc.as_ptr() as usize, riid, ppv); if hr >= 0 { let raw = *ppv; @@ -1529,24 +1785,12 @@ unsafe extern "system" fn dev_create_descriptor_heap_x(this: *mut c_void, desc: let gpu = if flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32 != 0 { heap.GetGPUDescriptorHandleForHeapStart().ptr } else { 0 }; let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE(d[0] as i32)); if sampler { - // an S# of zeros – a slot nothing was written to – is a sampler on the console: point - // filtering, wrap, mip 0 only. Every PC slot starts as that one, so a table entry the - // title left empty samples as there (an unwritten PC descriptor is undefined). - let zero = D3D12_SAMPLER_DESC { - Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, - AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP, - AddressV: D3D12_TEXTURE_ADDRESS_MODE_WRAP, - AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP, - MipLODBias: 0.0, - MaxAnisotropy: 1, - ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, - BorderColor: [0.0; 4], - MinLOD: 0.0, - MaxLOD: 0.0, - }; - for k in 0..d[1] as u64 { - dev.CreateSampler(&zero, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + k * inc as u64) as usize }); - } + zero_samplers(dev, heap); + } + { + let mut descs = CONSOLE_HEAP_DESCS.lock().unwrap(); + descs.retain(|e| e.0 != raw as usize); + descs.push((raw as usize, title)); } if !super::console_heap::register(raw as usize, d[1], cpu, gpu, inc, sampler, shared, visible) { crate::xlog_warn!("console descriptor heap: no room in UMA for {} slots", d[1]); @@ -1604,7 +1848,7 @@ fn view_shape_desc( ) -> Option<(u32, crate::gpu::desc::ImageType, u32, u32, u32, u32, u32, u32)> { use crate::gpu::desc::ImageType as T; let f = if format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN { r.Format } else { format }; - let fmt = crate::gpu::desc::gfx10_format(f).unwrap_or(0); + let fmt = view_tsharp_format(f); let (w, h, d) = (r.Width as u32, r.Height, r.DepthOrArraySize as u32); let ty = view_dim_to_image_type(dim)?; let depth = match ty { @@ -1630,6 +1874,16 @@ fn view_shape_desc( Some((fmt, ty, w, h, depth, base_level, last_level, max_mip)) } +/// The GFX10 format in the T# of a view in PC format `f` (0, a float image, when the table has +/// none). The PC's stencil views (X32_TYPELESS_G8X24_UINT, X24_TYPELESS_G8_UINT) are not in the +/// table but are UINT views: they get 8_UINT, so that translated shaders load them as integers +/// (`img_cls`); a float load of a UINT view is undefined in D3D12. +fn view_tsharp_format(f: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT) -> u32 { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UINT, DXGI_FORMAT_X24_TYPELESS_G8_UINT, DXGI_FORMAT_X32_TYPELESS_G8X24_UINT}; + let f = if f == DXGI_FORMAT_X24_TYPELESS_G8_UINT || f == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT { DXGI_FORMAT_R8_UINT } else { f }; + crate::gpu::desc::gfx10_format(f).unwrap_or(0) +} + /// Build the XCL shader-ABI T# for an SRV, populating GFX10 `BASE_LEVEL` (`t[3][15:12]`), /// `LAST_LEVEL` (`t[3][19:16]`, or `log2(SampleDesc.Count)` for MSAA), and `MAX_MIP` (`t[5][7:4]`). fn srv_tsharp_from_desc(slot_index: u32, r: &D3D12_RESOURCE_DESC, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> Option<[u32; 8]> { @@ -1685,7 +1939,8 @@ fn resource_dim_to_view(r: &D3D12_RESOURCE_DESC) -> i32 { static NON_UMA_BUFFER_VIEWS: AtomicU64 = AtomicU64::new(0); /// V# of a buffer view (raw: 4-byte elements, num_records in bytes; structured / typed: -/// stride = element size, num_records in elements); empty when the buffer is not in UMA. +/// stride = element size, num_records in elements); empty when the buffer is not in UMA. A +/// buffer placed in a GPU view asks for the tiles of the range viewed (`view_want`). fn buffer_view(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool) -> [u32; 4] { let Some((at, bytes)) = console_buffer(res) else { note_buffer_view(); @@ -1703,6 +1958,7 @@ fn buffer_view(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_ let base = at as u64 + first * elem as u64; let room = (bytes as u64).saturating_sub(first * elem as u64); let records = if stride == 0 { (n as u64 * 4).min(room) } else { (n as u64).min(room / stride as u64) }; + super::view_want::want(super::view_want::Path::BufferView, base, if stride == 0 { records } else { records * stride as u64 }); crate::gpu::desc::buffer_words(base, stride, records as u32, fmt) } @@ -1768,6 +2024,27 @@ const COHERENT_CUSTOM_WB_MAX: usize = 16 << 20; /// arena pool) const COHERENT_FLOOR: usize = 16 << 20; +/// A block of `size` bytes from `u` that one heap holds (`heap_of(p)`). A block across two +/// segments of a mixed window has none: it is held while the next fit is tried (which then starts +/// past it), and given back either way. +fn alloc_in_one_heap(u: &crate::gpu::uma::Uma, size: usize, heap_of: impl Fn(usize) -> Option) -> Option<(usize, T)> { + let mut held = Vec::new(); + let found = loop { + let Some(p) = u.alloc(size, 0x1_0000).map(|a| a as usize) else { break None }; + if let Some(h) = heap_of(p) { + break Some((p, h)); + } + held.push(p); + if held.len() == 4 { + break None; + } + }; + for p in held { + u.free(p); + } + found +} + /// Whether a readback heap / buffer of `rounded` bytes may take coherent memory. The room /// committed textures leave (`COHERENT_KEPT`) is kept for these: with the textures at that /// limit (Unicorn Overlord's), a second 128 MB of headroom sent every readback buffer to the @@ -1823,12 +2100,18 @@ unsafe fn place_console_buffer_sparse(this: *mut c_void, d: &D3D12_RESOURCE_DESC None } +fn uma_shadowed() -> bool { + crate::gpu::uma::get().is_some_and(|u| u.shadowed()) +} + /// Sanitize a console buffer description and initial state for placement in a coherent /// cross-adapter UMA heap (`OpenExistingHeapFromAddress`). fn sanitize_coherent_buffer(desc: &D3D12_RESOURCE_DESC, state: usize, cross_adapter: bool) -> (D3D12_RESOURCE_DESC, u32) { let mut d = *desc; d.Flags = D3D12_RESOURCE_FLAGS(d.Flags.0 & 0xFF); - if cross_adapter { + // a shadowed window's heap is video memory, not a cross-adapter heap over process memory; + // nor is a driver heap (`uma_driver`) + if cross_adapter && !uma_shadowed() { d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; } d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; @@ -1860,17 +2143,16 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta return Some(hr); } } - let Some(p) = u.alloc(rounded, 0x1_0000).map(|a| a as usize) else { + let heap_of = |p: usize| u.window_of(p).and_then(|k| uma_heap_for(k, p - u.window(k).0, rounded).map(|h| (k, h))); + let Some((p, (k, (heap, heap_off)))) = alloc_in_one_heap(u, rounded, heap_of) else { if prefer_coherent && u.has_sparse() { return place_console_buffer_sparse(this, &d, bytes, st, readback_on_null_map, riid, ppv); } return None; }; // the heap from OpenExistingHeapFromAddress is cross-adapter: row-major + sanitized flags & state - let k = u.window_of(p)?; let (d, st) = sanitize_coherent_buffer(&d, state, !u.is_driver_window(k)); - let heap = (*UMA_HEAPS.lock().unwrap().get(k)?)?; - let hr = dev_create_placed_resource(this, heap, p - u.window(k).0, &d as *const _ as usize, st as usize, clear, riid, ppv); + let hr = dev_create_placed_resource(this, heap, heap_off, &d as *const _ as usize, st as usize, clear, riid, ppv); if hr < 0 || (*ppv).is_null() { u.free(p); static ONCE: AtomicU64 = AtomicU64::new(0); @@ -1880,6 +2162,10 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta return None; } UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); + // a readback buffer in a shadowed window: what the GPU copied into it is in video memory + if readback_on_null_map && u.shadowed() { + note_sparse_readback(*ppv as usize); + } // Map must hand out the same memory the shaders read (checked once) static CHECKED: AtomicU64 = AtomicU64::new(0); if CHECKED.fetch_add(1, Ordering::Relaxed) == 0 { @@ -1899,39 +2185,68 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta Some(hr) } +/// Where a buffer of `bytes` the title places at `va` goes in unified memory: (its window, whether +/// it lies over the window's tiles – a sparse window, or a view window holding a GPU view of the +/// title's memory – rather than in the window's heap). None: not in a window, or past its end. A +/// buffer in a GPU view may run on into the next view windows (the view is one range across them, +/// `sparse::place_buffer` maps the tiles of each); any other may not. +fn title_buffer_window(u: &crate::gpu::uma::Uma, va: usize, bytes: usize) -> Option<(usize, bool)> { + let k = u.window_of(va)?; + let (base, size) = u.window(k); + if bytes == 0 { + return None; + } + if u.is_view_window(k) { + let last = u.window_of(va.checked_add(bytes - 1)?)?; + return (k..=last).all(|j| u.is_view_window(j)).then_some((k, true)); + } + if va - base + bytes > size { + return None; + } + Some((k, u.is_sparse_window(k))) +} + /// A buffer the title places at its own address (CreatePlacedResourceX): at a placement /// boundary (64 KiB) in unified memory it is that memory, placed in the window's heap; the /// title's allocation stays the title's. pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: &[u8; 0x38], state: u32, clear: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { let u = crate::gpu::uma::get()?; - let k = u.window_of(va)?; - let (base, size) = u.window(k); let mut d: D3D12_RESOURCE_DESC = std::ptr::read_unaligned(desc.as_ptr() as *const D3D12_RESOURCE_DESC); let bytes = d.Width as usize; + let (k, tiles) = title_buffer_window(u, va, bytes)?; + let base = u.window(k).0; // a placed PC buffer starts at 64 KiB: one at another address starts below it and XCL adds // the difference where PC methods take an offset into it (`buffer_delta`) let start = va & !0xFFFF; let delta = va - start; - if bytes == 0 || va - base + bytes > size { - return None; - } - // the title's own memory (a sparse window): a resource over its video-memory tiles - if u.is_sparse(va) { - let (hr, delta) = super::sparse::place_buffer(this, va, &d, state, riid, ppv)?; + // the title's own memory (a sparse window), or a GPU view of it: a resource over the window's + // video-memory tiles (a GPU view's show its CPU view), so its GPU address is the title's and + // what reads it (indirect arguments, copies, vertex buffers) reads the title's bytes + if tiles { + let view = super::view_want::want(super::view_want::Path::PlacedBuffer, va as u64, bytes as u64); + let Some((hr, delta)) = super::sparse::place_buffer(this, va, &d, state, riid, ppv) else { + if view { + static ONCE: AtomicU64 = AtomicU64::new(0); + if ONCE.fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_warn!("D3D12.X: a buffer at GPU-view address {va:#x} ({bytes:#x} bytes) is not over its tiles – a resource of its own (the GPU does not see the title's bytes there)"); + } + } + return None; + }; UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false)); if delta != 0 { BUFFER_DELTA.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); } return Some(hr); } - let heap = (*UMA_HEAPS.lock().unwrap().get(k)?)?; - if !u.is_driver_window(k) { + let (heap, heap_off) = uma_heap_for(k, start - base, delta + bytes)?; + if !u.shadowed() && !u.is_driver_window(k) { d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; } d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Alignment = 0; d.Width = (delta + bytes) as u64; - let hr = dev_create_placed_resource(this, heap, start - base, &d as *const _ as usize, state as usize, clear as usize, riid, ppv); + let hr = dev_create_placed_resource(this, heap, heap_off, &d as *const _ as usize, state as usize, clear as usize, riid, ppv); if hr < 0 || (*ppv).is_null() { return None; } @@ -1994,15 +2309,19 @@ fn pc_mappable(props: Option) -> bool { /// the console gives; the CPU's writes there reach the texture (`title_textures`). unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_void, data: *mut *mut c_void) -> HRESULT { // a resource in unified memory: its console address (no PC mapping – the PC's would be - // the start of the PC resource, before the address for a buffer placed below it) + // the start of the PC resource, before the address for a buffer placed below it). One in a + // GPU view gives its GPU-view address too (the console's; the CPU cannot touch it there): + // what the GPU wrote in the range read lands in its CPU view (`sparse::readback_now` reads + // and writes a GPU view's tiles at their CPU view). if let Some((p, bytes)) = console_buffer(this as usize) { - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(p)) { + if crate::gpu::uma::get().is_some_and(|u| u.is_gpu_copy(p) || u.is_view(p)) { if !range.is_null() { let r = *(range as *const D3D12_RANGE); if r.End > r.Begin { let begin = r.Begin.min(bytes); let end = r.End.min(bytes); if end > begin { + super::view_want::want(super::view_want::Path::MapRead, (p + begin) as u64, (end - begin) as u64); super::sparse::readback_now(p + begin, end - begin); } } @@ -2019,7 +2338,7 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v // the PC's Map only on a resource it can map: on a reserved one or one without CPU pages it is // an invalid call (debug layer 824 / 822) that the runtime answers with E_INVALIDARG let hr = if pc_can_map(this) { - let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void, *mut *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot!(this, "Map"))); + let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void, *mut *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12Resource", "Map"))); f(this, sub, range, data) } else { E_INVALIDARG @@ -2050,7 +2369,7 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v /// Every console resource is CPU-visible memory, a PC texture only in a CPU-visible heap. unsafe extern "system" fn res_write_to_subresource(this: *mut c_void, sub: u32, dst_box: *const D3D12_BOX, data: *const c_void, row_pitch: u32, depth_pitch: u32) -> HRESULT { type F = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_BOX, *const c_void, u32, u32) -> HRESULT; - let f: F = std::mem::transmute(orig_fn(this, slot!(this, "WriteToSubresource"))); + let f: F = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12Resource", "WriteToSubresource"))); let hr = f(this, sub, dst_box, data, row_pitch, depth_pitch); static CALLS: AtomicU64 = AtomicU64::new(0); static FAILED: AtomicU64 = AtomicU64::new(0); @@ -2064,6 +2383,10 @@ unsafe extern "system" fn res_write_to_subresource(this: *mut c_void, sub: u32, hr as u32 ); } + super::lut3d::wrote(this as usize, false, || { + let b = dst_box.as_ref().map(|b| (b.left, b.top, b.front, b.right, b.bottom, b.back)); + format!("WriteToSubresource({sub}, box {b:?}, row pitch {row_pitch}, depth pitch {depth_pitch}) by the CPU → {:#x}", hr as u32) + }); hr } @@ -2087,7 +2410,7 @@ unsafe extern "system" fn res_unmap(this: *mut c_void, sub: u32, range: *const c if UNMAPPABLE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&(this as usize))) { return; } - let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void) = std::mem::transmute(orig_fn(this, slot!(this, "Unmap"))); + let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void) = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12Resource", "Unmap"))); f(this, sub, range) } @@ -2097,23 +2420,20 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { // object can die. This is not the descriptor-write gate: descriptor hooks keep that across // driver calls which may make a temporary, non-final Release here. let mut tracked_srv_lifetime = super::vram::lock_tracked_srv_lifetime(); - // The last reference: kept until the queues are past the work in flight (`late_release`). - // (Two last-but-one releases at once can miss each other here; the object then goes at - // once, as before.) - let mut held = false; - let n = if super::late_release::enabled() { - let add: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); - if add(this) == 2 { - f(this); - held = true; - 0 - } else { - f(this); - f(this) - } - } else { - f(this) - }; + let add: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); + // Whether this is the last reference shows in the count after an AddRef of our own and its + // Release: 1 is ours alone. Then what XCL keeps by the object's address goes while the object + // is alive – after it, another thread can make a resource at that address, and the removals + // would strip that one (its pinned tiles too: `sparse::forget_buffer`). The last reference + // is kept until the queues are past the work in flight (`late_release`); its tiles are + // unpinned and its views made null views when it really goes. + // (Two releases of the last two references at once can both see more than 1 here; the one + // whose Release ends the object cleans up after it, as before.) + add(this); + let last = f(this) == 1; + let held = last && super::late_release::enabled(); + let mut pinned = false; + let n = if last { 0 } else { f(this) }; if n == 0 { // Remove lease candidates while Release is still serialized, then leave the lifetime // gate before the independent sparse/page/arena cleanup locks below. Do not wait for the @@ -2124,6 +2444,10 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { this as usize, tracked_srv_lifetime.as_ref(), ); drop(tracked_srv_lifetime.take()); + // (a held one's views when `late_release` lets it go) + if !held { + resource_ending(this as usize); + } if let Some(s) = UNMAPPABLE.lock().unwrap().as_mut() { s.remove(&(this as usize)); } @@ -2139,10 +2463,25 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { if let Some(m) = TITLE_ADDRESS.lock().unwrap().as_mut() { m.remove(&(this as usize)); } - super::sparse::forget_buffer(this as usize); + // (a held placed buffer still maps its tiles: unpinned by `late_release` when it lets it go) + if !held { + super::sparse::forget_buffer(this as usize); + } super::vram::forget_resource_backing_after_release(this as usize); + // (a held one is gone when `late_release` lets it go) + if !held { + super::placements::gone(this as usize); + super::small_tex::gone(this as usize); + } + super::depth_uav::forget(this as usize); super::title_textures::forget(this as usize); + super::lut3d::forget(this as usize); let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); + // a buffer may be over a heap of pages that are freed next; a texture, and a buffer of XCL's + // in video memory (or over a GPU view's tiles), is not + let texture = held && ID3D12Resource::from_raw_borrowed(&this).is_some_and(|r| r.GetDesc().Dimension != D3D12_RESOURCE_DIMENSION_BUFFER); + let in_video_memory = gone.as_ref().is_some_and(|b| crate::gpu::uma::get().is_some_and(|u| u.shadowed() || u.is_sparse(b.0) || u.is_view(b.0))); + pinned = !texture && !in_video_memory; if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { if u.is_sparse(p) { super::sparse::free(p); @@ -2153,15 +2492,37 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { } drop(tracked_srv_lifetime.take()); if held { - super::late_release::hold(this as usize); + super::late_release::hold(this as usize, pinned); + } else if last { + // (`XCL_LATE_RELEASE=0`: it goes now) + f(this); } n } +/// The PC resource `res` is destroyed next (its last reference goes now): its views in the shared +/// view heap become null views first (`console_heap::resource_gone`), so that a T# the title +/// kept of it reads zeros instead of an unmapped address. Logged at the first 16 releases that +/// had any and at powers of two. +pub(super) fn resource_ending(res: usize) { + let n = super::console_heap::resource_gone(res); + if n == 0 { + return; + } + static RELEASES: AtomicU64 = AtomicU64::new(0); + static NULLED: AtomicU64 = AtomicU64::new(0); + let total = NULLED.fetch_add(n as u64, Ordering::Relaxed) + n as u64; + let k = RELEASES.fetch_add(1, Ordering::Relaxed) + 1; + if k <= 16 || k.is_power_of_two() { + crate::xlog_info!("D3D12.X: {total} descriptors of destroyed resources set to null views so far ({k} resources)"); + } +} + /// A stand-in that is no driver object (`standin`) was released for good. pub(super) fn standin_released(pso: usize) { forget_pso(pso); - super::pso_async::release(super::pso_async::released(pso)); + // (lists in flight may bind the real one: `late_release` lets it go, as `pso_release` does) + super::late_release::hold_pipeline(super::pso_async::released(pso)); } /// A stand-in pipeline released for good takes its background-built real pipeline with it. @@ -2180,7 +2541,8 @@ unsafe extern "system" fn pso_release(this: *mut c_void) -> u32 { super::pso_manifest::forget_ready_compute(pso, generation); } forget_pso(pso); - super::pso_async::release(super::pso_async::released(pso)); + // (lists in flight may bind the real one: `late_release` lets it go) + super::late_release::hold_pipeline(super::pso_async::released(pso)); } n } @@ -2188,10 +2550,10 @@ unsafe extern "system" fn pso_release(this: *mut c_void) -> u32 { /// A pipeline state is gone: drop what XCL keeps by its address (a later pipeline may get the /// same address and must not inherit its root signature or compute pass). /// compute pipelines that run a translated console shader -static TRANSLATED_COMPUTE: Mutex>> = Mutex::new(None); +static TRANSLATED_COMPUTE: Sharded<()> = Sharded::new(); /// graphics pipelines built from translated console shaders -static TRANSLATED_GRAPHICS: Mutex>> = Mutex::new(None); +static TRANSLATED_GRAPHICS: Sharded<()> = Sharded::new(); /// Whether `pso` is a graphics pipeline of translated console shaders. /// `XCL_TRACE_FRAME`: the console VS and PS (their dump names' hashes) of a translated PSO. @@ -2204,12 +2566,20 @@ pub fn pso_layout(pso: usize) -> Option { PSO_LAYOUTS.lock().unwrap().as_ref()?.get(&pso).cloned() } +/// `XCL_SKIP_CS=,` (diagnostic, with `XCL_GPU_PROFILE=1`, whose report names the +/// hashes): dispatches of these console compute programs are left out. +pub fn skip_named_cs(pso: usize) -> bool { + static LIST: std::sync::OnceLock> = std::sync::OnceLock::new(); + let list = LIST.get_or_init(|| std::env::var("XCL_SKIP_CS").map(|v| v.split(',').filter_map(|h| u64::from_str_radix(h.trim(), 16).ok()).collect()).unwrap_or_default()); + !list.is_empty() && pso_shaders(pso).is_some_and(|(h, _)| list.contains(&h)) +} + pub fn pso_shaders(pso: usize) -> Option<(u64, u64)> { PSO_SHADERS.lock().unwrap().as_ref()?.get(&pso).copied() } pub fn is_translated_graphics(pso: usize) -> bool { - pso != 0 && TRANSLATED_GRAPHICS.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) + pso != 0 && TRANSLATED_GRAPHICS.contains(pso) } /// graphics pipelines given the generated rect list GS (`rect_list_gs`) @@ -2232,7 +2602,7 @@ fn note_rect_list_gs(pso: usize, copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, rect /// Whether `pso` runs a translated console compute shader. pub fn is_translated_compute(pso: usize) -> bool { - pso != 0 && TRANSLATED_COMPUTE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) + pso != 0 && TRANSLATED_COMPUTE.contains(pso) } /// compute pipelines the title made from a console shader that runs untranslated: a background @@ -2261,7 +2631,7 @@ pub(super) fn register_console_compute_for_test(pso: usize) { #[cfg(test)] pub(super) fn register_translated_compute_for_test(pso: usize) { if pso != 0 { - TRANSLATED_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + TRANSLATED_COMPUTE.insert(pso, ()); } } @@ -2275,7 +2645,7 @@ pub(super) fn register_rect_list_gs_for_test(pso: usize) { #[cfg(test)] pub(super) fn register_translated_graphics_for_test(pso: usize) { if pso != 0 { - TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + TRANSLATED_GRAPHICS.insert(pso, ()); } } @@ -2287,27 +2657,20 @@ pub(super) fn forget_pso_for_test(pso: usize) { fn forget_pso(pso: usize) { super::dred::forget_pso(pso); dispatch_chain::forget(pso); - if let Some(s) = TRANSLATED_COMPUTE.lock().unwrap().as_mut() { - s.remove(&pso); - } + TRANSLATED_COMPUTE.remove(pso); if let Some(s) = CONSOLE_COMPUTE.lock().unwrap().as_mut() { s.remove(&pso); } - if let Some(s) = TRANSLATED_GRAPHICS.lock().unwrap().as_mut() { - s.remove(&pso); - } + TRANSLATED_GRAPHICS.remove(pso); if let Some(s) = RECT_LIST_GS.lock().unwrap().as_mut() { s.remove(&pso); } - if let Some(m) = PSO_RS.lock().unwrap().as_mut() { - m.remove(&pso); - } - if let Some(m) = PSO_USER_SGPRS.lock().unwrap().as_mut() { - m.remove(&pso); - } - if let Some(m) = PSO_DISPATCH_REMAP.lock().unwrap().as_mut() { + PSO_RS.remove(pso); + PSO_USER_SGPRS.remove(pso); + if let Some(m) = PSO_SHADERS.lock().unwrap().as_mut() { m.remove(&pso); } + PSO_DISPATCH_REMAP.remove(pso); remap_fallback::forget(pso); super::device_x::forget_base(pso); // the compute pass goes with the last user of its entry (`Drop for TwoPassPso`) @@ -2385,32 +2748,43 @@ fn note_buffer_view() { /// #17 CreateConstantBufferView: a V# of float4 rows at the buffer's console address /// (`desc::cbv_words`; unified memory, anything else gets an empty V#). No PC CBV: translated -/// shaders read buffers through `mem`. +/// shaders read buffers through `mem`. One in a GPU view of the title's memory asks for its +/// tiles (`view_want`). unsafe extern "system" fn dev_create_cbv_x(this: *mut c_void, desc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC, cpu: u64) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor); let Some(slot) = super::console_heap::slot(cpu).filter(|s| !s.sampler) else { let f: unsafe extern "system" fn(*mut c_void, *const D3D12_CONSTANT_BUFFER_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 17)); return f(this, desc, cpu); }; let _tracked_write_lock = super::vram::lock_tracked_srv_write(); let (va, size) = desc.as_ref().map_or((0, 0), |d| (d.BufferLocation, d.SizeInBytes)); - let in_uma = crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize)); - if !in_uma { + let words = cbv_at(crate::gpu::uma::get(), va, size).unwrap_or_else(|| { note_buffer_view(); - } - let (va, size) = if in_uma { (va, size) } else { (0, 0) }; + crate::gpu::desc::cbv_words(0, 0) + }); + super::view_want::want(super::view_want::Path::Cbv, va, size as u64); super::vram::clear_tracked_srv(&slot); - super::console_heap::write(&slot, &crate::gpu::desc::cbv_words(va, size)); + super::console_heap::write(&slot, &words); +} + +/// The V# of a constant buffer view of `size` bytes at `va`, when shaders reach it there: the +/// CPU's unified memory, or a view window (a GPU view of the title's memory: the CPU cannot touch +/// it, its tiles show the CPU view). None: anywhere else. +fn cbv_at(u: Option<&crate::gpu::uma::Uma>, va: u64, size: u32) -> Option<[u32; 4]> { + let u = u?; + (u.contains(va as usize) || u.is_view(va as usize)).then(|| crate::gpu::desc::cbv_words(va, size)) } /// #22 CreateSampler: the PC sampler at the slot's index, the S# in XCL ABI form (word 3 /// [11:0] = sampler heap index; the state lives in the PC sampler). pub(super) unsafe extern "system" fn dev_create_sampler_x(this: *mut c_void, desc: *const D3D12_SAMPLER_DESC, cpu: u64) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor); let f: unsafe extern "system" fn(*mut c_void, *const D3D12_SAMPLER_DESC, u64) = std::mem::transmute(orig_fn(this, 22)); let Some(slot) = super::console_heap::slot(cpu).filter(|s| s.sampler) else { return f(this, desc, cpu) }; f(this, desc, slot.pc_srv); - super::console_heap::publish(&slot, false); + super::console_heap::publish(&slot, false, 0); super::console_heap::write(&slot, &[0, 0, 0, slot.index & 0xFFF]); } @@ -2425,9 +2799,11 @@ unsafe fn copy_console_slots(this: *mut c_void, n: u32, dst: u64, src: u64, ty: let _tracked_write_lock = (!d0.sampler).then(super::vram::lock_tracked_srv_write).flatten(); let step = if d0.sampler { SAMPLER_SLOT } else { SLOT } as u64; let ty = pc_heap_type(ty); + // what the source views name, for the copies in the shared heap (`console_heap::resource_gone`) + let names: Vec<(usize, usize)> = if d0.sampler { Vec::new() } else { (0..n as u64).map(|k| slot(src + k * SLOT as u64).map_or((0, 0), |s| super::console_heap::names_of(&s))).collect() }; let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24)); f(this, if d0.sampler { n } else { 2 * n }, d0.pc_srv, s0.pc_srv, ty); - super::console_heap::publish_range(&d0, n); + super::console_heap::publish_range(&d0, n, &names); let mut tracked_copies = (!d0.sampler && super::vram::srv_tracking_enabled()).then(Vec::new); for k in 0..n as u64 { if let (Some(d), Some(s)) = (slot(dst + k * step), slot(src + k * step)) { @@ -2465,6 +2841,7 @@ fn note_mixed_copy() { /// #24 CopyDescriptorsSimple(n, dst, src, type) unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor); let ty = pc_heap_type(ty); note_copy_call("CopyDescriptorsSimple", n, dst, src); if copy_console_slots(this, n, dst, src, ty) { @@ -2474,6 +2851,9 @@ unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u3 note_mixed_copy(); return; } + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 { + super::depth_uav::dsvs_copied(this, n, dst, src); + } let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24)); f(this, n, dst, src, ty); } @@ -2482,6 +2862,7 @@ unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u3 #[allow(clippy::too_many_arguments)] unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dsts: *const u64, dsizes: *const u32, ns: u32, srcs: *const u64, ssizes: *const u32, ty: u32) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor); let ty = pc_heap_type(ty); note_copy_call("CopyDescriptors", nd, if dsts.is_null() { 0 } else { *dsts }, if srcs.is_null() { 0 } else { *srcs }); use super::console_heap::{slot, SAMPLER_SLOT, SLOT}; @@ -2491,6 +2872,9 @@ unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dst note_mixed_copy(); return; } + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 { + super::depth_uav::dsv_ranges_copied(this, nd, dsts, dsizes, ns, srcs, ssizes); + } type F = unsafe extern "system" fn(*mut c_void, u32, *const u64, *const u32, u32, *const u64, *const u32, u32); let f: F = std::mem::transmute(orig_fn(this, 23)); return f(this, nd, dsts, dsizes, ns, srcs, ssizes, ty); @@ -2536,13 +2920,23 @@ unsafe fn release_taking_first(this: *mut c_void, mut take: impl FnMut() -> T unsafe extern "system" fn heap_release(this: *mut c_void) -> u32 { let lifetime = super::console_heap::lock_lifetime(); if lifetime.is_none() { - return release_taking_first(this, || super::console_heap::take(this as usize), |h| h.into_iter().for_each(super::console_heap::free)); + return release_taking_first( + this, + || { + CONSOLE_HEAP_DESCS.lock().unwrap().retain(|e| e.0 != this as usize); + super::console_heap::take(this as usize) + }, + |h| h.into_iter().for_each(super::console_heap::free), + ); } let generation = lifetime.as_ref().and_then(|_| super::console_heap::generation(this as usize)); let mut taken = None; let n = release_taking_first( this, - || super::console_heap::take_after_release(this as usize, generation, lifetime.as_ref()), + || { + CONSOLE_HEAP_DESCS.lock().unwrap().retain(|e| e.0 != this as usize); + super::console_heap::take_after_release(this as usize, generation, lifetime.as_ref()) + }, |h| taken = h, ); drop(lifetime); @@ -2598,6 +2992,17 @@ unsafe extern "system" fn dev_create_uav_checked_x( cpu: u64, ) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor); + dev_create_uav_checked_inner(this, res, counter, desc, cpu); +} + +unsafe fn dev_create_uav_checked_inner( + this: *mut c_void, + res: *mut c_void, + counter: *mut c_void, + desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, + cpu: u64, +) { if let Some(r) = ID3D12Resource::from_raw_borrowed(&res) { let rd = r.GetDesc(); let is_tex = rd.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER; @@ -2643,6 +3048,7 @@ unsafe extern "system" fn dev_create_uav_checked_x( /// #21 CreateDepthStencilView: the console's view formats as the PC's (`pc_view_format`). unsafe extern "system" fn dev_create_dsv_x(this: *mut c_void, res: *mut c_void, desc: *const D3D12_DEPTH_STENCIL_VIEW_DESC, cpu: u64) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_DEPTH_STENCIL_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 21)); let mut copy = desc.as_ref().copied(); if let Some(c) = copy.as_mut() { @@ -2653,7 +3059,31 @@ unsafe extern "system" fn dev_create_dsv_x(this: *mut c_void, res: *mut c_void, if copy.is_none() { copy = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| default_dsv(&r.GetDesc())); } - f(this, res, copy.as_ref().map_or(desc, |c| c as *const _), cpu) + // `XCL_DUMP_TARGETS`: the depth buffer a DSV names, kept with the RTVs' resources (DSV + // and RTV handles are in different heaps) + if super::targets::enabled() { + super::present::note_rtv(cpu as usize, res); + } + if super::capture::enabled() { + super::capture::note_view(cpu as usize, res as usize, true, copy.as_ref().map(|c| (c as *const D3D12_DEPTH_STENCIL_VIEW_DESC as *const [u32; 6]).read_unaligned())); + } + // `XCL_TRACE_FRAME`: the first 64 DSVs of depth buffers at least 1920 wide (flags 1: read-only + // depth, 2: read-only stencil) + if super::present::trace_frame() { + if let Some(d) = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()).filter(|d| d.Width >= 1920 && d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0) { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 64 { + let (vf, flags) = copy.as_ref().map_or((0, 0), |c| (c.Format.0, c.Flags.0)); + // (the buffer's title address: two buffers at one address are one memory on + // the console – a D16 buffer over the depth plane of a D16S8 one) + let at = title_address(res as usize).or_else(|| super::title_textures::address(res as usize)).map_or(String::new(), |a| format!(", the buffer at {a:#x}")); + crate::xlog_info!("frame trace: CreateDepthStencilView {cpu:#x} → {res:p} {}x{} PC format {}, view format {vf}, flags {flags:#x}{at}", d.Width, d.Height, d.Format.0); + } + } + } + let flags = copy.as_ref().map_or(0, |c| c.Flags.0 as u32); + f(this, res, copy.as_ref().map_or(desc, |c| c as *const _), cpu); + super::depth_uav::note_dsv(cpu as usize, res as usize, flags); } /// The view a DSV without a description has, for a depth buffer `pc_resource_desc` made @@ -2733,8 +3163,25 @@ fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) Some(out) } +/// An empty acceleration structure of XCL's own in unified memory (`XCL_BVH_EMPTY`): a header +/// whose root is a box32 node with no child, so a traversal ends at the root. +fn empty_bvh() -> Option { + static AT: std::sync::OnceLock> = std::sync::OnceLock::new(); + *AT.get_or_init(|| { + let p = crate::gpu::uma::get()?.alloc(0x1_0000, 0x1_0000)?; + let data = crate::gpu::bvh::empty().data; + unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), p, data.len()) }; + Some(p as u64) + }) +} + unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, cpu: u64) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor); + dev_create_srv_inner(this, res, desc, cpu); +} + +unsafe fn dev_create_srv_inner(this: *mut c_void, res: *mut c_void, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, cpu: u64) { let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); let mut copy = desc.as_ref().copied(); if let Some(c) = copy.as_mut() { @@ -2760,11 +3207,34 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, // so write the RDNA2 BVH descriptor directly and skip forwarding the console VA to PC. if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE) { let va = v.Anonymous.RaytracingAccelerationStructure.Location; - let in_uma = va != 0 && crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize)); - if in_uma { + // in a GPU view: its tiles are asked for from the root's on (the size is not known; the + // build wrote the nodes through views that asked for theirs, and a buffer placed there + // has all its tiles) + let view = super::view_want::want(super::view_want::Path::Bvh, va, 0x1_0000); + let in_uma = va != 0 && (view || crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize))); + // `XCL_BVH_EMPTY=1` (a test): every acceleration structure is an empty one – the title's + // rays hit nothing. Tells what its ray tracing shaders do to the picture and the device. + static EMPTY: std::sync::OnceLock = std::sync::OnceLock::new(); + let empty = *EMPTY.get_or_init(|| { + let on = std::env::var("XCL_BVH_EMPTY").is_ok_and(|v| v.trim() == "1"); + if on { + crate::xlog_info!("D3D12.X: XCL_BVH_EMPTY: acceleration structures are given to the shaders as empty ones"); + } + on + }); + if in_uma && !empty { + // and what rays read past it: the rest of the top level, its bottom levels, the + // parent pointers (`bvh_want`; `XCL_BVH_WALK=0`: the 64 KiB above only) + super::bvh_want::view_made(va); let w = crate::gpu::desc::bvh_words(va, true); return super::console_heap::write(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]); } + // (an all-zero descriptor is no empty structure: the shader reads its root at 0x30 of + // window 0) + if let Some(at) = empty.then(empty_bvh).flatten() { + let w = crate::gpu::desc::bvh_words(at, true); + return super::console_heap::write(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]); + } static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { crate::xlog_warn!("D3D12.X: CreateShaderResourceView(RAYTRACING_ACCELERATION_STRUCTURE) at {va:#x} is not in unified memory – writing empty BVH descriptor"); @@ -2789,11 +3259,15 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, ..Default::default() }; f(this, std::ptr::null_mut(), &null_buf, slot.pc_srv); + super::console_heap::publish(&slot, false, 0); } else { f(this, res, desc, slot.pc_srv); + super::console_heap::publish(&slot, false, res as usize); } - super::console_heap::publish(&slot, false); super::console_heap::note_resource(&slot, res as usize); + if res.is_null() || desc.as_ref().is_some_and(|v| v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER) { + super::lut3d::slot_reused(slot.index, cpu, res as usize, || format!("a shader resource view of {res:p} (a buffer or none)")); + } if !res.is_null() && super::memory_report::enabled() { super::vram::note_srv(res as usize, desc.as_ref()); } @@ -2814,7 +3288,7 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, // so write a valid T# referencing `slot.index` with the view's format class and type. if let Some(v) = desc.as_ref() { if let Some(ty) = view_dim_to_image_type(v.ViewDimension.0) { - let fmt = crate::gpu::desc::gfx10_format(v.Format).unwrap_or(0); + let fmt = view_tsharp_format(v.Format); let depth = if ty == crate::gpu::desc::ImageType::Cube { 6 } else { 1 }; return super::console_heap::write(&slot, &crate::gpu::desc::xcl_image_for_view(slot.index, fmt, ty, 1, 1, depth, 1)); } @@ -2827,6 +3301,7 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); } let rdesc = r.GetDesc(); + super::lut3d::viewed(res as usize, &rdesc, desc.as_ref(), slot.index, cpu); match srv_tsharp_from_desc(slot.index, &rdesc, desc.as_ref()) { Some(t) => { super::console_heap::write(&slot, &t); @@ -2876,7 +3351,8 @@ unsafe fn resource_at(this: *mut c_void, desc: *const u8, va: u64) -> *mut c_voi return r as *mut c_void; } let mut r = std::ptr::null_mut(); - let hr = super::device_x::create_placed_resource_x(this, va, x.as_ptr(), 0, std::ptr::null(), &ID3D12Resource::IID as *const _ as *const GUID, &mut r); + // (in COMMON, not the state the title made the memory's buffer in: `depth_uav` keeps that) + let hr = super::depth_uav::by_address(|| super::device_x::create_placed_resource_x(this, va, x.as_ptr(), 0, std::ptr::null(), &ID3D12Resource::IID as *const _ as *const GUID, &mut r)); if hr < 0 || r.is_null() { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 8 { @@ -2898,15 +3374,19 @@ unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u let v = (view as *const D3D12_SHADER_RESOURCE_VIEW_DESC).read_unaligned(); if v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor); let Some(slot) = super::console_heap::slot(cpu) else { return }; let _tracked_write_lock = super::vram::lock_tracked_srv_write(); super::vram::clear_tracked_srv(&slot); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; - let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + let (words, at, len) = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + super::view_want::want(super::view_want::Path::ViewAt, at, len); return super::console_heap::write(&slot, &words); } - dev_create_srv_x(this, resource_at(this, rdesc, va), &v, cpu); + let r = resource_at(this, rdesc, va); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor); + dev_create_srv_inner(this, r, &v, cpu); } /// device #71: the same for an unordered access view ({ the PC's UAV desc; GPU address @0x28; @@ -2919,19 +3399,24 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u let v = (view as *const D3D12_UNORDERED_ACCESS_VIEW_DESC).read_unaligned(); let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); if v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER { + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor); let Some(slot) = super::console_heap::slot(cpu) else { return }; let _tracked_write_lock = super::vram::lock_tracked_srv_write(); super::vram::clear_tracked_srv(&slot); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; - let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + let (words, at, len) = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + super::view_want::want(super::view_want::Path::ViewAt, at, len); return super::console_heap::write(&slot, &words); } - dev_create_uav_x(this, resource_at(this, rdesc, va), std::ptr::null_mut(), &v, cpu); + let r = resource_at(this, rdesc, va); + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor); + dev_create_uav_x(this, r, std::ptr::null_mut(), &v, cpu); } -/// V# of `n` elements from element `first` of the buffer at `va`. -fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool) -> [u32; 4] { +/// V# of `n` elements from element `first` of the buffer at `va`, and the bytes it covers +/// (address, length): what a view in a GPU view asks the tiles of (`view_want`). +fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool) -> ([u32; 4], u64, u64) { let fmt = crate::gpu::desc::gfx10_format(format).unwrap_or(22); let (stride, elem) = match (raw, stride) { (true, _) => (0, 4), @@ -2942,7 +3427,9 @@ fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI (false, s) => (s, s), }; let records = if stride == 0 { n.saturating_mul(4) } else { n }; - crate::gpu::desc::buffer_words(va + first * elem as u64, stride, records, fmt) + let at = va + first * elem as u64; + let len = if stride == 0 { records as u64 } else { records as u64 * stride as u64 }; + (crate::gpu::desc::buffer_words(at, stride, records, fmt), at, len) } fn resolve_uav_array_size(array_size: u32, total_slices: u32, first_slice: u32) -> u32 { @@ -3131,12 +3618,20 @@ fn uav_companion_srv( } unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, counter: *mut c_void, desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, cpu: u64) { + let rd_opt = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()); + // a UAV of the stencil plane of a depth buffer with unordered access: a view of its twin + // (`depth_uav`), made the way a UAV of a texture with unordered access is + let null_why = match super::depth_uav::resolve_uav(this, res, rd_opt.as_ref(), desc.as_ref()) { + super::depth_uav::Resolve::Twin(twin, view) => return dev_create_uav_checked_inner(this, twin, std::ptr::null_mut(), &view, cpu), + super::depth_uav::Resolve::Null(why) => Some(why), + super::depth_uav::Resolve::NotOurs => None, + }; // the view's format as the PC's for the resource (B5G5R5A1 of a target made R8G8B8A8, // `device_x::pc_resource_desc`: an invalid call, the device removed) let mut copy = desc.as_ref().copied(); if let Some(c) = copy.as_mut() { - if let Some(r) = ID3D12Resource::from_raw_borrowed(&res) { - let rf = r.GetDesc().Format.0 as u32; + if let Some(rd) = rd_opt.as_ref() { + let rf = rd.Format.0 as u32; c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32) as i32); } else { c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_view_format(c.Format.0 as u32) as i32); @@ -3148,7 +3643,6 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, let desc = copy.as_ref().map_or(desc, |c| c as *const _); super::present::note_use(res as usize, super::present::USE_UAV); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 19)); - let rd_opt = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()); if super::present::trace_frame() { if rd_opt.is_some_and(|d| d.Width >= 1920 && d.Flags.0 & 1 != 0) { let s = super::console_heap::slot(cpu); @@ -3168,7 +3662,9 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, let pc_uav = |at: u64| { if no_uav { static N: AtomicU64 = AtomicU64::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { + if let Some(why) = null_why { + super::depth_uav::null_view(why); + } else if N.fetch_add(1, Ordering::Relaxed) < 4 { crate::xlog_warn!("D3D12.X: a UAV of a resource that cannot have one on the PC (a depth buffer) – a null view"); } f(this, std::ptr::null_mut(), std::ptr::null_mut(), &null_desc, at) @@ -3180,7 +3676,8 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, let _tracked_write_lock = super::vram::lock_tracked_srv_write(); super::vram::clear_tracked_srv(&slot); pc_uav(slot.pc_uav); - super::console_heap::publish(&slot, true); + super::lut3d::slot_reused(slot.index, cpu, res as usize, || format!("an unordered access view of {res:p} (its companion view)")); + super::console_heap::publish(&slot, true, if no_uav { 0 } else { res as usize }); super::console_heap::note_resource(&slot, res as usize); let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else { // A null image UAV was already created and published at `slot.index + 1`. Create a @@ -3191,9 +3688,9 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, if let Some(srv) = uav_companion_srv(None, Some(v), true) { let g: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); g(this, std::ptr::null_mut(), &srv, slot.pc_srv); - super::console_heap::publish(&slot, false); + super::console_heap::publish(&slot, false, 0); } - let fmt = crate::gpu::desc::gfx10_format(v.Format).unwrap_or(0); + let fmt = view_tsharp_format(v.Format); return super::console_heap::write(&slot, &crate::gpu::desc::xcl_image_for_view(slot.index, fmt, ty, 1, 1, 1, 1)); } } @@ -3221,6 +3718,10 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, } None => (rd.Format, resource_dim_to_view(&rd), rd.DepthOrArraySize as u32, 0), }; + super::lut3d::wrote(res as usize, false, || { + let first = desc.as_ref().filter(|v| v.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE3D).map_or(0, |v| v.Anonymous.Texture3D.FirstWSlice); + format!("an unordered access view made in console slot {cpu:#x} (T# index {}, the UAV at + 1): format {}, mip {mip}, depth slices {first} (+{})", slot.index, format.0, array as i32) + }); let Some((fmt, ty, w, h, d, _)) = view_shape(r, format, dim, array, 1) else { note_buffer_view(); return super::console_heap::write(&slot, &[0; 8]); @@ -3232,7 +3733,7 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, let srv_res = if deny_srv { std::ptr::null_mut() } else { res }; let g: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); g(this, srv_res, &srv, slot.pc_srv); - super::console_heap::publish(&slot, false); + super::console_heap::publish(&slot, false, srv_res as usize); } let (w, h) = ((w >> mip).max(1), (h >> mip).max(1)); let d = if dim == 8 { (d >> mip).max(1) } else { d }; @@ -3347,6 +3848,10 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro super::device_x::pc_initial_state_for_desc(orig_flags, pc_flags, state as u32) }); let hr = dev_create_committed_resource(this, props, flags, desc, st as usize, clear, riid, ppv); + if hr >= 0 && pc_full.is_some() && !ppv.is_null() && !(*ppv).is_null() { + super::depth_uav::note_created(*ppv, &(console_desc as *const [u8; 0x38]).read_unaligned(), None, st); + super::lut3d::created("CreateCommittedResource (a PC resource: not in the title's memory)", *ppv, Some(&(console_desc as *const [u8; 0x38]).read_unaligned()), None, false, st); + } if hr < 0 { let pw = |o: usize| if props == 0 { 0 } else { *((props + o) as *const u32) }; crate::xlog_warn!( @@ -3483,7 +3988,11 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { Kind::PipelineState => v.push(("Release", pso_release as usize)), Kind::DescriptorHeap => v.push(("Release", heap_release as usize)), Kind::Heap => v.push(("Release", mem_heap_release as usize)), - Kind::Fence => v.extend_from_slice(&[("GetCompletedValue", fence_completed as usize), ("Signal", fence_signal as usize)]), + Kind::Fence => v.extend_from_slice(&[ + ("Signal", fence_signal as usize), + ("GetCompletedValue", fence_get_completed_value as usize), + ("SetEventOnCompletion", fence_set_event_on_completion as usize), + ]), _ => {} } v @@ -3537,13 +4046,27 @@ macro_rules! as_usize { unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailListLifecycle); let poisoned = super::list_x::recording_poisoned(this as usize); + let _t = crate::hle::api_cost::time_if( + super::look_stats::deep() && !super::title_textures::is_own_work() && !super::present::presenting(), + crate::hle::api_cost::Call::ListLifecycle, + ); + super::bind::flush_two_pass(this, super::bind::RunEnd::Close); super::list_x::before_close(this); + super::gpu_times::before_close(this); let ext = *(this as *const usize); - let f: RefFn = std::mem::transmute(orig_fn(this, slot!(this, "Close"))); + let f: RefFn = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "Close"))); let hr = f(this) as HRESULT; preserve_vtable(this, ext); + if hr >= 0 + && !super::title_textures::is_own_work() + && !super::present::presenting() + && super::title_list::wrapper_of(this).is_none() + && !super::console_list::is_backing(this) + { + super::title_textures::note_list_closed(this as usize); + } if hr < 0 { - let ty: RefFn = std::mem::transmute(orig_fn(this, slot_of(this, "GetType"))); + let ty: RefFn = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "GetType"))); crate::xlog_warn!("D3D12.X: command list {this:p} (type {}) Close → {:#x}", ty(this), hr as u32); } if poisoned { @@ -3565,14 +4088,21 @@ pub(super) fn submission_rejected_for_test(lists: &[*mut c_void]) -> bool { /// Reset (PC path): re-adopt the runtime's new open-state vtable if Reset replaced it. unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, initial_state: *mut c_void) -> HRESULT { let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailListLifecycle); + let _t = crate::hle::api_cost::time_if( + super::look_stats::deep() && !super::title_textures::is_own_work() && !super::present::presenting(), + crate::hle::api_cost::Call::ListLifecycle, + ); let ext = *(this as *const usize); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> HRESULT = - std::mem::transmute(orig_fn(this, slot!(this, "Reset"))); + std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "Reset"))); let prepared = super::bind::PreparedNativePipeline::new(initial_state as usize); let resolved = prepared.raw(); let hr = f(this, allocator, resolved as *mut c_void); preserve_vtable(this, ext); if hr >= 0 { + if !super::title_textures::is_own_work() && !super::present::presenting() { + super::title_textures::forget_list_closed(this as usize); + } super::list_x::on_pc_reset(this); prepared.record_generation(this as usize); super::dred::reset(this); @@ -3744,7 +4274,7 @@ macro_rules! creator { crate::xlog_info!("D3D12.X: {} for interface {asked} (not on the PC) – made as {}", $method, super::layout::guid_string(&iid)); } } - if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && !is_own_object($kind) { adopt(*ppv, $kind); if $kind == Kind::CommandQueue { super::queue_submit::created(*ppv as usize); @@ -3755,6 +4285,12 @@ macro_rules! creator { }; } +/// XCL's own lists, allocators, buffers and fences (made in `title_textures::own_work`) stay the +/// PC's: the title never sees them, and what a hook does for a title's object is paid on its submit. +fn is_own_object(kind: Kind) -> bool { + matches!(kind, Kind::CommandList | Kind::CommandAllocator | Kind::Resource | Kind::Fence) && super::title_textures::is_own_work() +} + creator!(dev_create_command_queue, "CreateCommandQueue", Kind::CommandQueue, [a1]); creator!(dev_create_command_queue1, "CreateCommandQueue1", Kind::CommandQueue, [a1, a2]); creator!(dev_create_command_allocator, "CreateCommandAllocator", Kind::CommandAllocator, [a1]); @@ -3827,6 +4363,16 @@ pub(super) const PC_RESOURCE_STATES: u32 = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | /// buffers-only heap) is made the PC's way (`device_x::pc_resource_desc`, the console's state /// bits dropped). Logged with the console's values. pub(super) unsafe extern "system" fn dev_create_placed_resource_x(this: *mut c_void, heap: usize, offset: usize, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let hr = placed_in_heap_x(this, heap, offset, desc, state, clear, riid, ppv); + if hr >= 0 && super::lut3d::created_on() && !ppv.is_null() && desc != 0 && crate::gpu::shader::readable(desc, 0x38) { + let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); + super::lut3d::created(&format!("CreatePlacedResource (heap {heap:#x} at {offset:#x}: the PC's memory, not kept in step)"), *ppv, Some(&x), None, false, state as u32 & PC_RESOURCE_STATES); + } + hr +} + +#[allow(clippy::too_many_arguments)] +unsafe fn placed_in_heap_x(this: *mut c_void, heap: usize, offset: usize, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { // the clear value in the PC's format of the resource (D3D12 wants the two to match) let mut clear_buf = [0u8; 24]; let clear = super::device_x::pc_clear(clear as *const c_void, &mut clear_buf) as usize; @@ -3838,7 +4384,7 @@ pub(super) unsafe extern "system" fn dev_create_placed_resource_x(this: *mut c_v let d = super::device_x::pc_resource_desc(&x); let st = state as u32 & PC_RESOURCE_STATES; if let Some(hr) = place_at_title_address(this, block + offset, &d, st, clear as *const c_void, riid, ppv) { - if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && cpu_readback && crate::gpu::uma::get().is_some_and(|u| u.is_sparse(block + offset)) { + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && cpu_readback && crate::gpu::uma::get().is_some_and(|u| u.is_gpu_copy(block + offset)) { let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); if st == D3D12_RESOURCE_STATE_COPY_DEST.0 as u32 && (flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 as u32) == 0 { note_sparse_readback(*ppv as usize); @@ -3887,7 +4433,11 @@ pub(super) unsafe extern "system" fn dev_create_placed_resource_x(this: *mut c_v u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u(0x20), u(0x2C), u(0x30) ); } - hr3.unwrap_or(hr2) + let hr = hr3.unwrap_or(hr2); + if hr >= 0 && is_texture && !ppv.is_null() && !(*ppv).is_null() { + super::depth_uav::note_created(*ppv, &x, None, st); + } + hr } /// A texture the title placed in a heap by the console's size (`get_resource_allocation_info_x` @@ -3917,10 +4467,15 @@ unsafe fn own_memory_if_larger_on_the_pc(this: *mut c_void, heap: usize, offset: let mut clear_buf = [0u8; 24]; let clear = super::device_x::pc_clear_for_desc(clear as *const c_void, u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()), &mut clear_buf) as usize; let mut hr = dev_create_committed_resource(this, &h.Properties as *const _ as usize, 0, d.as_ptr() as usize, st as usize, clear, riid, ppv); + let mut made_in = st; if hr < 0 && st != 0 { // as in the past-the-end fallback: a state the PC refuses for this desc (e.g. UAV // without the UAV flag) – COMMON rather than falling back to the overlapping placement hr = dev_create_committed_resource(this, &h.Properties as *const _ as usize, 0, d.as_ptr() as usize, 0, clear, riid, ppv); + made_in = 0; + } + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + super::depth_uav::note_created(*ppv, &x, None, made_in); } static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 8 { @@ -3991,12 +4546,21 @@ unsafe fn is_reserved(res: *mut c_void) -> bool { /// CreateReservedResource pub(super) unsafe extern "system" fn dev_create_reserved_resource(this: *mut c_void, a1: usize, a2: usize, a3: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - note_reserved(pc_create_reserved_resource(this, a1, a2, a3, riid, ppv), ppv) + reserved_3d(note_reserved(pc_create_reserved_resource(this, a1, a2, a3, riid, ppv), ppv), ppv, a2) } /// CreateReservedResource1 pub(super) unsafe extern "system" fn dev_create_reserved_resource1(this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - note_reserved(pc_create_reserved_resource1(this, a1, a2, a3, a4, riid, ppv), ppv) + reserved_3d(note_reserved(pc_create_reserved_resource1(this, a1, a2, a3, a4, riid, ppv), ppv), ppv, a2) +} + +/// `XCL_DUMP_TARGETS`: a reserved 3D texture (XCL's own for a placed one too: that placement's +/// line follows) +unsafe fn reserved_3d(hr: HRESULT, ppv: *mut *mut c_void, state: usize) -> HRESULT { + if hr >= 0 && super::lut3d::created_on() && !ppv.is_null() { + super::lut3d::created("CreateReservedResource (tiles mapped by whoever made it)", *ppv, None, None, false, state as u32); + } + hr } creator!(dev_create_heap_pc, "CreateHeap", Kind::Heap, [a1]); @@ -4327,7 +4891,7 @@ fn dummy_mesh() -> Option<&'static (Vec, Vec)> { .as_ref() } -fn compile(src: &str, target: &str) -> Vec { +pub(super) fn compile(src: &str, target: &str) -> Vec { unsafe { let mut blob = None; let t = format!("{target}\0"); @@ -4517,13 +5081,8 @@ fn with_switch_fallback(mut build: impl FnMut() -> R) -> R { if !HEAP_WINDOW_OOM.with(|o| o.replace(false)) { return r; } - if crate::gpu::uma::get().is_some_and(|u| u.shader_windows() > crate::gpu::uma::MAX_WINDOWS) { - static WARNED: std::sync::Once = std::sync::Once::new(); - WARNED.call_once(|| { - crate::xlog_warn!("D3D12.X: the driver refused an expanded-window pipeline; switch-form retry requires XCL_UMA_WINDOWS=4"); - }); - return r; - } + // (with more than 4 windows too: the switch form reaches windows 0..3 through the root UAVs, + // `pso::mem_windows`; addresses in the other windows read 0 in that pipeline only) let n = SWITCH_FORM_RETRIES.fetch_add(1, Ordering::Relaxed); if n < 5 || n % 100 == 0 { crate::xlog_warn!("D3D12.X: the driver ran out of memory on a pipeline with heap windows – building it in the switch form ({} so far)", n + 1); @@ -4572,17 +5131,17 @@ unsafe fn shader_bytes<'a>(b: &D3D12_SHADER_BYTECODE) -> Option<&'a [u8]> { /// Root signature of every pipeline built from translated console shaders (static samplers /// make it per pipeline): the draw binds it instead of the title's. -static PSO_RS: Mutex>> = Mutex::new(None); +static PSO_RS: Sharded = Sharded::new(); fn note_pso_rs(pso: *mut c_void, rs: *mut c_void) { if !pso.is_null() { - PSO_RS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso as usize, rs as usize); + PSO_RS.insert(pso as usize, rs as usize); } } /// user SGPRs and the console's `numthreads` of the console CS of a translated compute pipeline -static PSO_USER_SGPRS: Mutex>> = Mutex::new(None); -static PSO_DISPATCH_REMAP: Mutex>> = Mutex::new(None); +static PSO_USER_SGPRS: Sharded<(u32, [u32; 3])> = Sharded::new(); +static PSO_DISPATCH_REMAP: Sharded<(u32, u32)> = Sharded::new(); /// How many user SGPRs the console compute shader of a translated pipeline has (None: not /// known). What is above the driver's four holds root arguments (`console_list::inline_for`). @@ -4592,7 +5151,7 @@ pub fn pso_user_sgprs(pso: usize) -> Option { } pub(super) fn pso_user_sgprs_exact(pso: usize) -> Option { - PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).map(|e| e.0) + PSO_USER_SGPRS.get(pso).map(|e| e.0) } /// The console's group shape (`numthreads`) of a translated compute pipeline (None: not known). @@ -4602,22 +5161,22 @@ pub fn pso_threads(pso: usize) -> Option<[u32; 3]> { } pub(super) fn pso_threads_exact(pso: usize) -> Option<[u32; 3]> { - PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).map(|e| e.1) + PSO_USER_SGPRS.get(pso).map(|e| e.1) } /// (tests) A translated compute pipeline with this console group shape. #[cfg(test)] pub(crate) fn register_threads_for_test(pso: usize, threads: [u32; 3]) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, (0, threads)); + PSO_USER_SGPRS.insert(pso, (0, threads)); } #[cfg(test)] pub(super) fn register_compute_metadata_for_test( pso: usize, user_sgprs: u32, threads: [u32; 3], remap: (u32, u32), root: usize, ) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, (user_sgprs, threads)); - PSO_DISPATCH_REMAP.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, remap); - PSO_RS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, root); + PSO_USER_SGPRS.insert(pso, (user_sgprs, threads)); + PSO_DISPATCH_REMAP.insert(pso, remap); + PSO_RS.insert(pso, root); } pub fn pso_dispatch_remap(pso: usize) -> Option<(u32, u32)> { @@ -4626,19 +5185,17 @@ pub fn pso_dispatch_remap(pso: usize) -> Option<(u32, u32)> { } pub(super) fn pso_dispatch_remap_exact(pso: usize) -> Option<(u32, u32)> { - PSO_DISPATCH_REMAP.lock().unwrap().as_ref()?.get(&pso).copied() + PSO_DISPATCH_REMAP.get(pso) } fn note_pso_dispatch_remap(pso: *mut c_void, remap: Option<(u32, u32)>) { if pso.is_null() { return; } - let mut guard = PSO_DISPATCH_REMAP.lock().unwrap(); - let map = guard.get_or_insert_with(HashMap::new); if let Some(remap) = remap { - map.insert(pso as usize, remap); + PSO_DISPATCH_REMAP.insert(pso as usize, remap); } else { - map.remove(&(pso as usize)); + PSO_DISPATCH_REMAP.remove(pso as usize); } } @@ -4649,7 +5206,7 @@ pub fn pso_root_signature(pso: usize) -> Option { } pub(super) fn pso_root_signature_exact(pso: usize) -> Option { - PSO_RS.lock().unwrap().as_ref()?.get(&pso).copied() + PSO_RS.get(pso) } /// ABI root signatures with static samplers, by device and sampler set (owned here, never released). @@ -4721,11 +5278,33 @@ unsafe fn abi_rs_raw(this: *mut c_void) -> Option<*mut c_void> { /// for one of the `XCL_HUGE_PSO_CONCURRENCY` slots. NVIDIA's compiler (nvgpucomp64) takes /// minutes and ~1 GB for a 1 – 2 MB program; ~20 of them at once (one per worker) were slower /// in total than 1 – 2 at a time. Small programs (ms each) never wait. -fn huge_pso_bytes() -> usize { +pub(super) fn huge_pso_bytes() -> usize { static V: std::sync::OnceLock = std::sync::OnceLock::new(); *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_BYTES").ok().as_deref(), 256 << 10, 1, usize::MAX)) } +/// `XCL_SKIP_CS_KB=`: the DXIL size in bytes from which a compute program gets no pipeline +/// (a diagnostic); None: not set, 0 or not a number. +fn skip_cs_bytes() -> Option { + static V: std::sync::OnceLock> = std::sync::OnceLock::new(); + *V.get_or_init(|| skip_cs_bytes_of(std::env::var("XCL_SKIP_CS_KB").ok().as_deref())) +} + +fn skip_cs_bytes_of(v: Option<&str>) -> Option { + v.and_then(|v| v.trim().parse::().ok()).filter(|&kb| kb > 0).map(|kb| kb.saturating_mul(1024)) +} + +#[cfg(test)] +mod skip_cs_tests { + #[test] + fn the_skip_size_is_in_kib_and_off_unless_a_positive_number() { + assert_eq!(super::skip_cs_bytes_of(Some(" 400 ")), Some(400 << 10)); + assert_eq!(super::skip_cs_bytes_of(Some("0")), None); + assert_eq!(super::skip_cs_bytes_of(Some("big")), None); + assert_eq!(super::skip_cs_bytes_of(None), None); + } +} + /// Huge driver compiles at once on the workers (default 1, `XCL_HUGE_PSO_CONCURRENCY`). fn huge_pso_concurrency() -> usize { static V: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -4757,9 +5336,22 @@ struct Slots { cv: std::sync::Condvar, most: usize, wanted_most: usize, + /// compiles that are not built ahead of their first use waiting for a slot (`big_compile_turn`) + urgent: AtomicUsize, + /// a build ahead of its pipeline's first use may take a slot (`big_compile_turn`) + ahead: bool, } impl Slots { + const fn new(most: usize, wanted_most: usize) -> Slots { + Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most, wanted_most, urgent: AtomicUsize::new(0), ahead: true } + } + + /// `new` for a lane whose slots no build ahead of its pipeline's first use takes. + const fn closed_to_ahead(most: usize, wanted_most: usize) -> Slots { + Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most, wanted_most, urgent: AtomicUsize::new(0), ahead: false } + } + fn most(&self) -> usize { if self.most == 0 { huge_pso_concurrency() } else { self.most } } @@ -4769,7 +5361,7 @@ impl Slots { } } -struct SlotGuard(&'static Slots); +pub(super) struct SlotGuard(&'static Slots); impl Drop for SlotGuard { fn drop(&mut self) { @@ -4778,26 +5370,27 @@ impl Drop for SlotGuard { } } -static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 0, wanted_most: 0 }; +static BIG_COMPILES: Slots = Slots::new(0, 0); const AMD_MEDIUM_COMPUTE: usize = 128 << 10; const MEDIUM_COMPUTE_END: usize = 256 << 10; static MEDIUM_COMPILES: LazyLock = LazyLock::new(|| { let (default_most, default_wanted_most) = medium_pso_defaults(total_physical_ram()); let most = env_count(std::env::var("XCL_MEDIUM_PSO_CONCURRENCY").ok().as_deref(), default_most, 1, 64); - Slots { - n: Mutex::new(0), - cv: std::sync::Condvar::new(), + Slots::new( most, - wanted_most: env_count( + env_count( std::env::var("XCL_MEDIUM_PSO_WANTED_CONCURRENCY").ok().as_deref(), default_wanted_most.max(most), most, 64, ), - } + ) }); -const GIANT_DRIVER_COMPILE: usize = 4 << 20; -static GIANT_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 1 }; +pub(super) const GIANT_DRIVER_COMPILE: usize = 4 << 20; +/// One giant driver compile at a time, a wanted one too, and none of a pipeline nobody has used +/// yet: such a compile takes minutes, and one made ahead of its use held the only slot while a +/// bind waited for another giant one. +static GIANT_COMPILES: Slots = Slots::closed_to_ahead(1, 1); fn compile_slots(bytes: usize) -> &'static Slots { if bytes >= GIANT_DRIVER_COMPILE { &GIANT_COMPILES } else { &BIG_COMPILES } @@ -4825,8 +5418,10 @@ fn medium_compute_compile(kind: &str, bytes: usize, huge_bytes: usize, vendor: u } /// A driver compile of `bytes` of DXIL through `build`: a huge one on an `xcl-pso*` worker -/// waits for its slot first (`big_compile_turn`; not a title thread's, nor one the title waits -/// for). Logs its time, size and whether it was gated. +/// waits for its slot first (`big_compile_turn`; not a title thread's; one the title waits for +/// does not wait for free commit and may take one of `Slots::wanted_most`). Logs its time, size +/// and whether it was gated. (Every pipeline path passes its record +/// to `driver_compile_identified` now; the gate's tests use this form.) #[cfg(test)] fn driver_compile(kind: &str, bytes: usize, gate: bool, build: impl FnOnce() -> R) -> R { driver_compile_identified(kind, bytes, gate, None, false, build).0 @@ -4851,20 +5446,33 @@ fn driver_compile_identified(kind: &str, bytes: usize, gate: bool, record: Op let gate_stall = gated.then(|| crate::stall::span(crate::stall::StallKind::DriverCompileGate)).flatten(); let _slot = gated.then(|| { let _waiting = DRIVER_BUILDS.waiting(); - let slots = if medium { &*MEDIUM_COMPILES } else { compile_slots(bytes) }; - big_compile_turn(slots, || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted) + if medium { + big_compile_turn( + &MEDIUM_COMPILES, + || big_compile_commit_free(big_compile_headroom(bytes)), + super::pso_async::build_is_wanted, + super::pso_async::build_is_ahead, + ) + } else { + huge_compile_turn(bytes) + } }); drop(gate_stall); let waited = waited.elapsed(); static SEQUENCE: AtomicU64 = AtomicU64::new(0); let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1; let log = pso_trace() || bytes >= huge_bytes || medium; + if bytes >= huge_bytes { + super::pso_async::note_huge(); + } if log { let record = record.map_or_else( || if cached { ", driver blob supplied".to_string() } else { String::new() }, |hash| format!(", record {hash:016x}, driver blob {}", if cached { "supplied" } else { "absent" }), ); - crate::xlog_info!("D3D12.X: driver compile start #{sequence}: {kind} PSO, {bytes} B DXIL{record}"); + let stages = if kind.starts_with("graphics") { GRAPHICS_STAGES.with(|s| s.get()) } else { None }; + let before = stages.map_or_else(String::new, |(vs, ps)| stage_note(super::pso_async::job_elapsed(), vs, ps, waited)); + crate::xlog_info!("D3D12.X: driver compile start #{sequence}: {kind} PSO, {bytes} B DXIL{record}{before}"); } let started = std::time::Instant::now(); let _blob = BlobSupplied::set(cached); @@ -4888,6 +5496,26 @@ fn driver_compile_identified(kind: &str, bytes: usize, gate: bool, record: Op (r, took) } +thread_local! { + /// The translation and DXC compile of the VS and the PS of the graphics pipeline this + /// thread builds (`translated_graphics_pso_once`), for the driver compile log. + static GRAPHICS_STAGES: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Where a graphics pipeline's time went before the driver's compile (`job`: since its build +/// started on a worker, None elsewhere): the VS's and the PS's translation and DXC compile +/// (waits of DXC for memory included), the wait for the huge-pipeline gate (slot and commit), +/// and the rest (root signature, driver blob lookup). Measured on a retail title: 4 – 7 s for +/// a 300 – 480 KB stage, one after the other, before 3 – 8 s in the driver. +fn stage_note(job: Option, vs: std::time::Duration, ps: std::time::Duration, waited: std::time::Duration) -> String { + let ms = |d: std::time::Duration| d.as_millis(); + let stages = format!("VS {} ms, PS {} ms, gate {} ms", ms(vs), ms(ps), ms(waited)); + match job { + Some(job) => format!("; {} ms since its build started: {stages}, other {} ms", ms(job), ms(job.saturating_sub(vs + ps + waited))), + None => format!("; {stages}"), + } +} + /// How a logged driver compile went through the huge-pipeline gate. fn gate_note(huge_size: bool, gated: bool, waited: std::time::Duration) -> String { match (huge_size, gated) { @@ -4909,27 +5537,65 @@ fn gate_compute_driver_compile(has_cached_blob: bool) -> bool { /// waits for the pipeline (`wanted`), it bypasses the commit wait and can use up to /// `slots.wanted_most()` (default 2 for `>= 256 KB`, 1 for `>= 4 MiB` giant shaders) so a wanted /// build is not stuck behind 1 background build while a burst of lazy binds still cannot spike -/// driver compiler commit into OOM. -fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wanted: impl Fn() -> bool) -> SlotGuard { +/// driver compiler commit into OOM. A build ahead of the pipeline's first use (`ahead`, +/// `pso_async::Backlog`) takes a free slot only when no other build waits for one: one a bind +/// waits for, or waited for and gave up on (`XCL_GFX_PSO_WAIT_MS`), goes first. In a lane closed +/// to builds ahead (`Slots::ahead`: giant compiles) it takes no slot at all and waits until its +/// pipeline is used: a slot is never given back before the compile ends, so a giant compile +/// nobody wants made a bind wait minutes for another one. +fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wanted: impl Fn() -> bool, ahead: impl Fn() -> bool) -> SlotGuard { const LOOK: std::time::Duration = std::time::Duration::from_millis(50); let mut n = slots.n.lock().unwrap(); + // (counted in `urgent` while it waits) + let mut queued = false; let mut parked = None; - loop { + let guard = loop { let is_wanted = wanted(); let cap = if is_wanted { slots.wanted_most() } else { slots.most() }; - if *n < cap && (is_wanted || commit_free()) { + let ahead = !is_wanted && ahead(); + let open = slots.ahead || !ahead; + if open && *n < cap && (is_wanted || commit_free()) && !(ahead && slots.urgent.load(Ordering::Acquire) > 0) { *n += 1; - return SlotGuard(slots); + break SlotGuard(slots); + } + if !ahead && !queued { + queued = true; + slots.urgent.fetch_add(1, Ordering::AcqRel); } if parked.is_none() { parked = Some(super::pso_async::parked_for_big_compile()); } n = slots.cv.wait_timeout(n, LOOK).unwrap().0; + }; + if queued { + slots.urgent.fetch_sub(1, Ordering::AcqRel); } + guard } -/// Commit headroom a big driver compile waits for: 3 GB for the class that starts at -/// `huge_pso_bytes()` (each takes ~1.5 GB in the driver), and ~512× the DXIL size above 6 MiB +/// `big_compile_turn` of a huge driver compile of `bytes` on a worker. A build ahead of its +/// pipeline's first use in a lane closed to it waits there until the pipeline is used; on a +/// backlog worker another worker takes its place meanwhile (`pso_async::build_parks`). +pub(super) fn huge_compile_turn(bytes: usize) -> SlotGuard { + let slots = compile_slots(bytes); + if !slots.ahead && super::pso_async::build_is_ahead() { + super::pso_async::build_parks(); + } + big_compile_turn(slots, || big_compile_commit_free(headroom_for(bytes, super::pso_async::build_is_late())), super::pso_async::build_is_wanted, super::pso_async::build_is_ahead) +} + +/// The commit headroom a huge compile of `bytes` waits for (`big_compile_headroom`), halved for +/// one whose pipeline the title already uses and draws without (`late`): with a wait budget no +/// build stays wanted, and on a machine short of commit every one of them then stood at the gate +/// for the full headroom while the frames that needed them were left out (33 builds held, one for +/// 129 s, with 4.5 GB of commit free and 44,596 draws skipped meanwhile). +fn headroom_for(bytes: usize, late: bool) -> u64 { + let full = big_compile_headroom(bytes); + if late { full / 2 } else { full } +} + +/// Commit headroom a big driver compile waits for: 3 GB for the class that starts at +/// `huge_pso_bytes()` (each takes ~1.5 GB in the driver), and ~512× the DXIL size above 6 MiB /// of it — the driver's compile of a 29.8 MB program grew past 14 GB free before it was stopped /// (#1269), and programs of ~1 MB took several GB each on an 8 GB card (same issue). The floor /// leaves every program up to 6 MiB of DXIL waiting for exactly what it waited for before. @@ -4938,7 +5604,7 @@ fn big_compile_headroom(dxil_len: usize) -> u64 { } /// That much commit is free (true when that is not known). -fn big_compile_commit_free(need: u64) -> bool { +pub(super) fn big_compile_commit_free(need: u64) -> bool { use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; m.dwLength = std::mem::size_of::() as u32; @@ -4951,18 +5617,30 @@ mod big_compile_tests { use std::sync::atomic::AtomicBool; use std::time::{Duration, Instant}; + #[test] + fn a_late_build_waits_for_half_the_headroom() { + let bytes = huge_pso_bytes(); + assert_eq!(headroom_for(bytes, false), big_compile_headroom(bytes)); + assert_eq!(headroom_for(bytes, true), big_compile_headroom(bytes) / 2); + // (the class's floor: 3 GB, 1.5 GB for a late one - what one such compile takes) + assert_eq!(headroom_for(1 << 20, false), 3 << 30); + assert_eq!(headroom_for(1 << 20, true), 3 << 29); + // a giant program keeps a headroom that grows with it + assert_eq!(headroom_for(32 << 20, true), (32u64 << 20) * 256); + } + #[test] fn wanted_builds_bypass_commit_and_unwanted_slot_but_respect_hard_cap() { - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 2 }; - let held = big_compile_turn(&S, || true, || false); + static S: Slots = Slots::new(1, 2); + let held = big_compile_turn(&S, || true, || false, || false); assert_eq!(*S.n.lock().unwrap(), 1); // Unwanted slot is full, but a wanted build immediately takes the 2nd (wanted) slot and // bypasses the commit-free check. - let held_wanted = big_compile_turn(&S, || false, || true); + let held_wanted = big_compile_turn(&S, || false, || true, || false); assert_eq!(*S.n.lock().unwrap(), 2); // A 3rd wanted build MUST wait while both slots are occupied (hard cap = 2). let t = std::thread::spawn(|| { - let _g = big_compile_turn(&S, || false, || true); + let _g = big_compile_turn(&S, || false, || true, || false); }); std::thread::sleep(Duration::from_millis(120)); assert!(!t.is_finished(), "3rd concurrent wanted huge compile must wait for hard cap"); @@ -4975,7 +5653,7 @@ mod big_compile_tests { static WANTED2: AtomicBool = AtomicBool::new(false); let t0 = Instant::now(); let t = std::thread::spawn(|| { - let _g = big_compile_turn(&S, || false, || WANTED2.load(Ordering::Acquire)); + let _g = big_compile_turn(&S, || false, || WANTED2.load(Ordering::Acquire), || false); }); std::thread::sleep(Duration::from_millis(120)); assert!(!t.is_finished(), "no commit free: unwanted build waits"); @@ -4991,16 +5669,16 @@ mod big_compile_tests { // Mirrors GIANT_COMPILES (`most == 1, wanted_most == 1`) under low commit (< 3 GiB): // an unwanted compile waiting on commit headroom must never hold the slot and deadlock a // wanted compile. - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 1 }; + static S: Slots = Slots::new(1, 1); static FREE: AtomicBool = AtomicBool::new(false); let bg = std::thread::spawn(|| { - let _g = big_compile_turn(&S, || FREE.load(Ordering::Acquire), || false); + let _g = big_compile_turn(&S, || FREE.load(Ordering::Acquire), || false, || false); }); std::thread::sleep(Duration::from_millis(120)); assert!(!bg.is_finished(), "unwanted compile waits for commit"); assert_eq!(*S.n.lock().unwrap(), 0, "unwanted compile must not hold slot while commit-blocked"); let t0 = Instant::now(); - let wanted = big_compile_turn(&S, || false, || true); + let wanted = big_compile_turn(&S, || false, || true, || false); assert!(t0.elapsed() < Duration::from_secs(1), "wanted compile must acquire slot immediately"); assert_eq!(*S.n.lock().unwrap(), 1); drop(wanted); @@ -5012,13 +5690,13 @@ mod big_compile_tests { #[test] fn wanted_burst_is_hard_capped_to_wanted_most() { use std::sync::atomic::AtomicUsize; - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 2 }; + static S: Slots = Slots::new(1, 2); static IN: AtomicUsize = AtomicUsize::new(0); static PEAK: AtomicUsize = AtomicUsize::new(0); let t: Vec<_> = (0..12) .map(|_| { std::thread::spawn(|| { - let _g = big_compile_turn(&S, || false, || true); + let _g = big_compile_turn(&S, || false, || true, || false); let now = IN.fetch_add(1, Ordering::SeqCst) + 1; PEAK.fetch_max(now, Ordering::SeqCst); std::thread::sleep(Duration::from_millis(15)); @@ -5049,6 +5727,68 @@ mod big_compile_tests { assert!(gate_note(true, false, ms).contains("ungated here")); } + /// A build ahead of its pipeline's first use takes a free slot when nobody else waits for + /// one, and gives its turn to a build that is not ahead (one a bind gave up waiting for). + #[test] + fn a_build_ahead_gives_its_turn_to_any_other() { + static S: Slots = Slots::new(1, 1); + static ORDER: Mutex> = Mutex::new(Vec::new()); + // a free slot and nobody waiting: at once + drop(big_compile_turn(&S, || true, || false, || true)); + let held = big_compile_turn(&S, || true, || false, || false); + let other = std::thread::spawn(|| { + let g = big_compile_turn(&S, || true, || false, || false); + ORDER.lock().unwrap().push("other"); + std::thread::sleep(Duration::from_millis(50)); + drop(g); + }); + std::thread::sleep(Duration::from_millis(120)); + let ahead = std::thread::spawn(|| { + let g = big_compile_turn(&S, || true, || false, || true); + ORDER.lock().unwrap().push("ahead"); + drop(g); + }); + std::thread::sleep(Duration::from_millis(120)); + assert!(!other.is_finished() && !ahead.is_finished(), "the slot is taken: both wait"); + drop(held); + other.join().unwrap(); + ahead.join().unwrap(); + assert_eq!(*ORDER.lock().unwrap(), ["other", "ahead"]); + assert_eq!((*S.n.lock().unwrap(), S.urgent.load(Ordering::Acquire)), (0, 0)); + } + + /// In the lane of giant compiles (`most == 1, wanted_most == 1`) a build ahead of its + /// pipeline's first use takes no slot, not even a free one, so a wanted giant build goes at + /// once instead of waiting for its whole compile; once its pipeline is used it takes its turn. + #[test] + fn a_build_ahead_takes_no_giant_slot_until_its_pipeline_is_used() { + assert!(!GIANT_COMPILES.ahead && BIG_COMPILES.ahead, "only the giant lane is closed to builds ahead"); + static S: Slots = Slots::closed_to_ahead(1, 1); + static USED: AtomicBool = AtomicBool::new(false); + let ahead = std::thread::spawn(|| { + let _g = big_compile_turn(&S, || true, || false, || !USED.load(Ordering::Acquire)); + }); + std::thread::sleep(Duration::from_millis(120)); + assert!(!ahead.is_finished(), "a build ahead waits although the slot is free"); + assert_eq!(*S.n.lock().unwrap(), 0, "a build ahead must not hold the giant slot"); + let t0 = Instant::now(); + let wanted = big_compile_turn(&S, || false, || true, || false); + assert!(t0.elapsed() < Duration::from_secs(1), "a wanted giant build must take the slot at once"); + USED.store(true, Ordering::Release); + std::thread::sleep(Duration::from_millis(120)); + assert!(!ahead.is_finished(), "used now, it waits for the slot the wanted build holds"); + drop(wanted); + ahead.join().unwrap(); + assert_eq!((*S.n.lock().unwrap(), S.urgent.load(Ordering::Acquire)), (0, 0)); + } + + #[test] + fn a_graphics_compile_log_says_where_the_time_went_before_it() { + let s = Duration::from_secs; + assert_eq!(stage_note(Some(s(10)), s(4), s(3), s(1)), "; 10000 ms since its build started: VS 4000 ms, PS 3000 ms, gate 1000 ms, other 2000 ms"); + assert_eq!(stage_note(None, s(4), s(3), s(0)), "; VS 4000 ms, PS 3000 ms, gate 0 ms"); + } + #[test] fn driver_builds_count_while_running_and_once_done() { let b = DriverBuilds::new(); @@ -5125,7 +5865,7 @@ mod big_compile_tests { #[test] fn the_concurrency_limit_holds_and_all_finish() { use std::sync::atomic::AtomicUsize; - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 2, wanted_most: 2 }; + static S: Slots = Slots::new(2, 2); static IN: AtomicUsize = AtomicUsize::new(0); static PEAK: AtomicUsize = AtomicUsize::new(0); // the two holders of the slots meet here: both are inside at once, deterministically @@ -5133,7 +5873,7 @@ mod big_compile_tests { let t: Vec<_> = (0..8) .map(|_| { std::thread::spawn(|| { - let _g = big_compile_turn(&S, || true, || false); + let _g = big_compile_turn(&S, || true, || false, || false); let now = IN.fetch_add(1, Ordering::SeqCst) + 1; PEAK.fetch_max(now, Ordering::SeqCst); BOTH.wait(); @@ -5154,8 +5894,8 @@ mod big_compile_tests { // every slot taken: a small compile on a worker, and a huge one on an unnamed (title) // thread, both go on at once // (both lanes: a huge compile of any size would block on a gate it should bypass) - let mut held: Vec<_> = (0..huge_pso_concurrency()).map(|_| big_compile_turn(&BIG_COMPILES, || true, || false)).collect(); - held.push(big_compile_turn(&GIANT_COMPILES, || true, || false)); + let mut held: Vec<_> = (0..huge_pso_concurrency()).map(|_| big_compile_turn(&BIG_COMPILES, || true, || false, || false)).collect(); + held.push(big_compile_turn(&GIANT_COMPILES, || true, || false, || false)); let small = std::thread::Builder::new() .name("xcl-pso-test".into()) .spawn(|| driver_compile("test", huge_pso_bytes() - 1, true, || 7)) @@ -5182,10 +5922,10 @@ mod big_compile_tests { #[test] fn unwanted_builds_go_one_at_a_time_when_the_commit_is_there() { - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 2 }; - let first = big_compile_turn(&S, || true, || false); + static S: Slots = Slots::new(1, 2); + let first = big_compile_turn(&S, || true, || false, || false); let t = std::thread::spawn(|| { - let _g = big_compile_turn(&S, || true, || false); + let _g = big_compile_turn(&S, || true, || false, || false); }); std::thread::sleep(Duration::from_millis(120)); assert!(!t.is_finished(), "one at a time"); @@ -5221,6 +5961,18 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } }; let dxil = compiled.dxil; + // `XCL_SKIP_CS_KB=` (a diagnostic): a program with n KiB of DXIL or more gets no pipeline + // and its dispatches are skipped. The biggest programs are most of the driver code a retail + // title's world has in use at once, and an NVIDIA driver removes the device when that passes + // 512 MiB (xcl-dev/xcl#2403): without them a run lives long enough to look at the rest. + if skip_cs_bytes().is_some_and(|n| dxil.len() >= n) { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_warn!("D3D12.X: XCL_SKIP_CS_KB: a compute program of {} KiB of DXIL (record {:016x}) gets no pipeline, its dispatches are skipped ({n} so far)", dxil.len() >> 10, crate::gpu::shader::fnv64(cs)); + } + return Some(Err(())); + } // a big program: the driver's compile takes it seconds to a minute (a retail game's 1 MB // ray-tracing resolve programs ~30 s each, ~600 of them): built in the background like one // whose DXIL is missing – the title's loading does not wait for it, its first bind does @@ -5240,9 +5992,13 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const note_pso_rs(*ppv, rs as *mut c_void); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); if let Some(i) = crate::gpu::recomp::pso::compute_interface(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (i.user_sgprs, i.threads)); + PSO_USER_SGPRS.insert(*ppv as usize, (i.user_sgprs, i.threads)); } note_translated_compute(0, ppv); + PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (record, 0)); + if super::gpu_profile::on() || super::gpu_times::enabled() { + super::gpu_profile::note_compute(record, cs, dxil.len(), wave32_only(this)); + } TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); return Some(Ok(0)); } @@ -5277,12 +6033,16 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); if let Some(i) = crate::gpu::recomp::pso::compute_interface(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (i.user_sgprs, i.threads)); + PSO_USER_SGPRS.insert(*ppv as usize, (i.user_sgprs, i.threads)); } note_pso_dispatch_remap(*ppv, compiled.dispatch_remap); remap_fallback::note(*ppv as usize, this, f, rs as usize, &compiled.samplers, d.Flags, d.NodeMask, record, cs, wave32_only(this), crate::gpu::recomp::pso::mem_windows(), compiled.dispatch_remap.is_some()); note_translated_compute(hr, ppv); + PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (record, 0)); + if super::gpu_profile::on() || super::gpu_times::enabled() { + super::gpu_profile::note_compute(record, cs, dxil.len(), wave32_only(this)); + } crate::xlog_info!( "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", dxil.len(), @@ -5467,8 +6227,8 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL } let reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; if hr >= 0 && !reused { - keep_driver_blob(&COMPUTE_BLOBS, COMPUTE_BLOBS_MAX, key, dxil.len(), disk.as_deref(), persist_took, - || read_pso_cached_blob(*ppv)); + keep_driver_blob_at(&COMPUTE_BLOBS, COMPUTE_BLOBS_MAX, key, dxil.len(), disk.as_deref(), persist_took, + driver_cache::compute_keep_threshold(), || read_pso_cached_blob(*ppv)); } else if reused && from_disk { COMPUTE_BLOBS.admit(key, cached.as_ref().unwrap().clone(), COMPUTE_BLOBS_MAX); driver_cache::note(true, loaded.take()); @@ -5482,11 +6242,14 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL /// run still goes through the driver's compiler. On an NVIDIA GPU that is 5 – 27 s for each of /// a retail title's larger compute programs when its world loads: the title dispatches without /// them meanwhile and is ended before all are built, so the next run starts the same compiles -/// again. A blob whose build took `KEEP` or longer is written under the hash of its DXIL and -/// its flags (`\driver\`) and read when a later run has none in memory; the +/// again. A blob whose build took `KEEP` (a compute pipeline's: `COMPUTE_KEEP`) or longer is +/// written under the hash of its DXIL and its flags (`\driver\`) and read when a +/// later run has none in memory; the /// driver refuses the blob of another driver, adapter or root signature (the file is dropped -/// and the program compiled as before). Off by default on AMD; `XCL_PSO_DISK_CACHE=1` forces -/// it on, and `XCL_PSO_DISK_CACHE=0` turns it off everywhere. +/// and the program compiled as before). A translated graphics pipeline's blob goes under +/// `graphics_file_hash`, the passes of a two-pass one under `TwoPassBlob`'s names. +/// Off by default on AMD; `XCL_PSO_DISK_CACHE=1` forces it on, and `XCL_PSO_DISK_CACHE=0` +/// turns it off everywhere. pub(crate) mod driver_cache { use crate::gpu::recomp::pso::StaticSampler; use std::io::Read; @@ -5498,6 +6261,10 @@ pub(crate) mod driver_cache { /// builds shorter than this are not worth a file const KEEP: std::time::Duration = std::time::Duration::from_millis(250); + /// … of a compute pipeline: one not kept is compiled again in every run, at its first bind, + /// often on one of the title's threads (a retail title's thread spent 228 ms on a 4 KB + /// program that no file was kept for) + const COMPUTE_KEEP: std::time::Duration = std::time::Duration::from_millis(20); static HITS: AtomicU64 = AtomicU64::new(0); static STALE: AtomicU64 = AtomicU64::new(0); static STORED: AtomicU64 = AtomicU64::new(0); @@ -5646,6 +6413,42 @@ pub(crate) mod driver_cache { enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(graphics_name(hash, bytes))) } + /// The layout of `graphics_file_hash`'s input: a change names every graphics file anew. + const GRAPHICS_FILE_SCHEMA: u32 = 2; + + /// The hash a translated graphics pipeline's file is named after: its key in memory + /// (`graphics_blob_key`: the description's state, the DXIL of each stage, the static samplers) + /// with the adapter and driver it is made on (`driver_identity`) and the memory windows of its + /// root signature (`pso::mem_windows`), which the description does not hold. A file named + /// after the description alone was the blob of whichever adapter wrote it last. + pub fn graphics_file_hash(key: (u64, usize), driver: u64, windows: u32) -> u64 { + let mut b = Vec::with_capacity(32); + b.extend_from_slice(&GRAPHICS_FILE_SCHEMA.to_le_bytes()); + b.extend_from_slice(&key.0.to_le_bytes()); + b.extend_from_slice(&(key.1 as u64).to_le_bytes()); + b.extend_from_slice(&driver.to_le_bytes()); + b.extend_from_slice(&windows.to_le_bytes()); + crate::gpu::shader::fnv64(&b) + } + + /// Builds shorter than this keep no file (`KEEP`; `XCL_PSO_DISK_CACHE_MIN_MS` to choose). + pub(super) fn keep_threshold() -> std::time::Duration { + static MIN: std::sync::OnceLock = std::sync::OnceLock::new(); + *MIN.get_or_init(|| keep_threshold_of(std::env::var("XCL_PSO_DISK_CACHE_MIN_MS").ok().as_deref(), KEEP)) + } + + /// Compute builds shorter than this keep no file (`COMPUTE_KEEP`; `XCL_PSO_DISK_CACHE_MIN_MS` + /// to choose, as for the others). + pub(super) fn compute_keep_threshold() -> std::time::Duration { + static MIN: std::sync::OnceLock = std::sync::OnceLock::new(); + *MIN.get_or_init(|| keep_threshold_of(std::env::var("XCL_PSO_DISK_CACHE_MIN_MS").ok().as_deref(), COMPUTE_KEEP)) + } + + /// A threshold in milliseconds from the environment (unset or not a number: `default`). + fn keep_threshold_of(v: Option<&str>, default: std::time::Duration) -> std::time::Duration { + v.and_then(|v| v.trim().parse().ok()).map_or(default, std::time::Duration::from_millis) + } + /// Bytes read from one exact cache-file generation. Keeping its handle open lets a later /// refusal dispose that file object without touching a replacement at the same pathname. pub struct LoadedBlob { @@ -5789,18 +6592,22 @@ pub(crate) mod driver_cache { ok } - pub(super) fn worth_keeping(took: std::time::Duration) -> bool { - took >= KEEP || keep_fixtures() + /// A build that took `took` keeps its blob when `min` or longer (`keep_threshold`, + /// `compute_keep_threshold`; tests can ask for every one). + pub(super) fn worth_keeping(took: std::time::Duration, min: std::time::Duration) -> bool { + took >= min || keep_fixtures() } /// Exclusive publication turn for one pathname within this process. Different in-memory /// identities can share a disk key (notably compute root-signature pointers), so reserve the - /// pathname before capturing bytes as well as reserving the in-memory key. + /// pathname before capturing bytes as well as reserving the in-memory key. A build shorter + /// than `min` gets no turn (`keep_threshold`, `compute_keep_threshold`; zero for a + /// preparation worker). pub(super) struct KeepTurn(PathBuf, std::time::Duration); impl KeepTurn { - pub(super) fn new(p: &Path, took: std::time::Duration) -> Option { - if !worth_keeping(took) { + pub(super) fn new(p: &Path, took: std::time::Duration, min: std::time::Duration) -> Option { + if !worth_keeping(took, min) { return None; } let mut active = ACTIVE_KEEPS.lock().unwrap(); @@ -5828,10 +6635,10 @@ pub(crate) mod driver_cache { } } - /// Keep `blob`, of a build that took `took`, for the next run. + /// Keep `blob`, of a compute build that took `took`, for the next run. #[cfg(test)] pub fn keep(p: &Path, blob: &[u8], took: std::time::Duration) -> bool { - if let Some(turn) = KeepTurn::new(p, took) { + if let Some(turn) = KeepTurn::new(p, took, compute_keep_threshold()) { turn.store(blob) } else { false @@ -5979,6 +6786,20 @@ pub(crate) mod driver_cache { assert!(name_for(&[0u8; 0x1234], 2, true).ends_with("-1234-2.chain.pso")); } + /// A graphics pipeline's file follows its description's key, the adapter and driver and + /// the window count, and the same inputs name the same file in every run (a fixed hash, + /// none seeded per process). + #[test] + fn a_graphics_file_follows_its_key_adapter_driver_and_windows() { + let (key, driver) = ((0x0123_4567_89ab_cdef, 0x4_0000), 0x10de_2b85); + let h = graphics_file_hash(key, driver, 16); + assert_eq!(h, 0x366d_c4de_0ace_48bd, "the hash of a run before"); + assert_ne!(h, graphics_file_hash((key.0 ^ 1, key.1), driver, 16), "another description or DXIL"); + assert_ne!(h, graphics_file_hash((key.0, key.1 + 1), driver, 16), "another DXIL size"); + assert_ne!(h, graphics_file_hash(key, driver + 1, 16), "another adapter or driver"); + assert_ne!(h, graphics_file_hash(key, driver, 4), "another window count"); + } + #[test] fn static_sampler_root_signatures_have_distinct_compatible_names() { let wrap = ([0, 0, 0, 0], false); @@ -6117,6 +6938,23 @@ pub(crate) mod driver_cache { assert_eq!(std::fs::read(&target).unwrap(), b"not the cache entry"); } + /// A compute build of 20 ms or more keeps its file (it was 250 ms, as for the others, and + /// `XCL_PSO_DISK_CACHE_MIN_MS` did not reach it); the switch chooses for both. + #[test] + fn a_compute_build_of_a_tenth_of_a_second_keeps_its_file() { + let ms = std::time::Duration::from_millis; + assert_eq!(keep_threshold_of(None, COMPUTE_KEEP), ms(20)); + assert_eq!(keep_threshold_of(None, KEEP), ms(250), "the others' as before"); + assert_eq!(keep_threshold_of(Some(" 100 "), COMPUTE_KEEP), ms(100)); + assert_eq!(keep_threshold_of(Some("0"), KEEP), ms(0)); + assert_eq!(keep_threshold_of(Some("soon"), COMPUTE_KEEP), ms(20)); + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-compute-{}", std::process::id())); + let _directory = Directory(dir.clone()); + let p = dir.join("driver").join(name(b"small program", 0)); + keep(&p, &[4, 5, 6], ms(100)); + assert_eq!(load_bytes(&p).as_deref(), Some(&[4u8, 5, 6][..]), "a 100 ms compute build is kept"); + } + #[test] fn an_overlapping_writer_cannot_modify_the_published_blob() { use std::io::Write; @@ -6259,11 +7097,13 @@ impl DriverBlobs { } } -/// The driver's compiled form of translated compute programs (`GetCachedBlob`), -/// by (DXIL hash, root signature, flags), up to `COMPUTE_BLOBS_MAX` bytes in all. +/// The driver's compiled form of translated compute programs (`GetCachedBlob`), keyed by +/// (identity hash, root signature, domain or compute flags), up to `COMPUTE_BLOBS_MAX` bytes +/// across ordinary compute and both two-pass PSOs. static COMPUTE_BLOBS: DriverBlobs<(u64, usize, i32)> = DriverBlobs::new(); const COMPUTE_BLOBS_MAX: usize = 512 << 20; -/// smaller programs compile in milliseconds: not kept +/// smaller programs mostly compile in milliseconds: not kept in memory (a slow build only on +/// disk: `keep_driver_blob_at`) const COMPUTE_BLOB_MIN_DXIL: usize = 16 << 10; #[cfg_attr(not(test), allow(dead_code))] @@ -6361,10 +7201,11 @@ mod compute_blob_tests { *total += 3; } assert_eq!(super::compute_blob(key).as_deref().map(|v| v.len()), Some(3)); - let before = super::COMPUTE_BLOBS.blobs.lock().unwrap().as_ref().unwrap().1; super::forget_compute_blob(key); - assert!(super::compute_blob(key).is_none()); - assert_eq!(super::COMPUTE_BLOBS.blobs.lock().unwrap().as_ref().unwrap().1, before - 3); + let guard = super::COMPUTE_BLOBS.blobs.lock().unwrap(); + let (map, total) = guard.as_ref().unwrap(); + assert!(!map.contains_key(&key)); + assert_eq!(*total, map.values().map(|blob| blob.len()).sum::()); } #[test] @@ -6429,6 +7270,28 @@ mod compute_blob_tests { cache.finish(11, None, 32, false); } + /// A small program's slow build keeps its blob on disk (not in memory: `COMPUTE_BLOB_MIN_DXIL`); + /// its quick build keeps none. A small program without its file is compiled again in every + /// run, at its first bind (a retail title's thread spent 228 ms in the driver on one of 4 KB). + #[test] + fn a_small_programs_slow_build_keeps_its_blob_on_disk() { + let ms = std::time::Duration::from_millis; + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-small-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let (slow, quick) = (dir.join("small-slow.pso"), dir.join("small-quick.pso")); + let cache = super::DriverBlobs::new(); + let kept = super::keep_driver_blob_at(&cache, 1 << 20, 1u64, 4392, Some(&slow), ms(228), ms(20), || Some(b"small".to_vec())); + assert_eq!(kept.as_deref().map(Vec::as_slice), Some(b"small".as_slice())); + assert_eq!(std::fs::read(&slow).ok().as_deref(), Some(b"small".as_slice()), "228 ms for 4 KB of DXIL: kept on disk"); + if !super::driver_cache::keep_fixtures() { + assert!(cache.get(1).is_none(), "and not in memory"); + super::keep_driver_blob_at(&cache, 1 << 20, 2u64, 4392, Some(&quick), ms(5), ms(20), || panic!("a quick small build keeps nothing")); + assert!(!quick.exists()); + } + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn active_builder_wins_over_disk_admission() { let cache = super::DriverBlobs::new(); @@ -6467,25 +7330,47 @@ unsafe fn read_pso_cached_blob(pso: *mut c_void) -> Option> { } /// Offer the exact result and duration of one successful build to the bounded RAM cache and, -/// when slow, the disk cache. One same-key owner captures and publishes at a time: another -/// completed builder cannot charge its duration to these bytes or overwrite them afterward. +/// when slow (`driver_cache::keep_threshold`), the disk cache. One same-key owner captures and +/// publishes at a time: another completed builder cannot charge its duration to these bytes or +/// overwrite them afterward. The captured blob comes back (for `warm_replay::accepted`). fn keep_driver_blob( cache: &DriverBlobs, limit: usize, key: K, dxil_len: usize, disk: Option<&std::path::Path>, took: std::time::Duration, read: impl FnOnce() -> Option>, -) { - if (dxil_len < COMPUTE_BLOB_MIN_DXIL && !driver_cache::keep_fixtures()) || !cache.reserve(key) { - return; +) -> Option>> { + keep_driver_blob_at(cache, limit, key, dxil_len, disk, took, driver_cache::keep_threshold(), read) +} + +/// `keep_driver_blob` with a disk threshold of `min` (a compute pipeline's: +/// `driver_cache::compute_keep_threshold`). A program under `COMPUTE_BLOB_MIN_DXIL` keeps no blob +/// in memory, but its slow build still keeps one on disk: a small program without its file is +/// compiled again in every run, at its first bind (a retail title's thread spent 228 ms in the +/// driver on one of 4 KB). A preparation worker (`PREPARING`) builds each pipeline once, for the +/// disk: every blob is kept there whatever its size and time, none in memory. +#[allow(clippy::too_many_arguments)] +fn keep_driver_blob_at( + cache: &DriverBlobs, limit: usize, key: K, dxil_len: usize, + disk: Option<&std::path::Path>, took: std::time::Duration, min: std::time::Duration, + read: impl FnOnce() -> Option>, +) -> Option>> { + let preparing = PREPARING.load(Ordering::Relaxed); + let min = if preparing { std::time::Duration::ZERO } else { min }; + let memory = !preparing && (dxil_len >= COMPUTE_BLOB_MIN_DXIL || driver_cache::keep_fixtures()); + let to_disk = disk.is_some() && driver_cache::worth_keeping(took, min); + if !(memory || to_disk) || !cache.reserve(key) { + return None; } - let keep_turn = disk.and_then(|path| driver_cache::KeepTurn::new(path, took)); + let keep_turn = disk.filter(|_| to_disk).and_then(|path| driver_cache::KeepTurn::new(path, took, min)); let Some(bytes) = read().filter(|bytes| !bytes.is_empty()) else { cache.finish(key, None, limit, false); - return; + return None; }; let blob = std::sync::Arc::new(bytes); // Publish to disk before exposing the blob through RAM: a concurrent consumer cannot reject // this generation while its staging file is being renamed into place. let persisted = keep_turn.as_ref().is_some_and(|turn| turn.store(&blob)); - cache.finish(key, Some(blob), limit, persisted); + // (a blob for the disk only still releases the key, and marks it persisted when written) + cache.finish(key, memory.then(|| blob.clone()), limit, persisted); + Some(blob) } /// The driver's compiled form of translated graphics pipelines (`GetCachedBlob`), @@ -6831,6 +7716,42 @@ mod graphics_blob_tests { assert!(!copy.GS.pShaderBytecode.is_null()); } + /// Where the description's parts are (shaders, input layout, semantic names, root signature, + /// a cached blob) never enters the key, only what is there. + #[test] + fn graphics_blob_key_reads_no_pointer() { + let names = [std::ffi::CString::new("TEXCOORD").unwrap(), std::ffi::CString::new("TEXCOORD").unwrap()]; + let elem = |n: &std::ffi::CStr| D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(n.as_ptr() as *const u8), + SemanticIndex: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT, + ..Default::default() + }; + let layouts = [[elem(&names[0])], [elem(&names[1])]]; + let (vs, ps) = ([b"vs-a".to_vec(), b"vs-a".to_vec()], [b"ps-a".to_vec(), b"ps-a".to_vec()]); + let blob = [7u8; 8]; + let desc = |k: usize| { + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + // (never dereferenced: the root signature is not read) + d.pRootSignature = unsafe { std::mem::transmute::>>(0x1000 * (k + 1)) }; + d.VS = bytecode(&vs[k]); + d.PS = bytecode(&ps[k]); + d.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: layouts[k].as_ptr(), NumElements: 1 }; + if k == 1 { + d.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: blob.as_ptr().cast(), CachedBlobSizeInBytes: blob.len() }; + } + d.NumRenderTargets = 1; + d.SampleDesc.Count = 1; + d + }; + let (a, b) = (desc(0), desc(1)); + assert_ne!(a.VS.pShaderBytecode, b.VS.pShaderBytecode); + assert_ne!(a.InputLayout.pInputElementDescs, b.InputLayout.pInputElementDescs); + unsafe { + assert_eq!(graphics_blob_key(&a, &vs[0], Some(&ps[0]), None, &[]), graphics_blob_key(&b, &vs[1], Some(&ps[1]), None, &[])); + } + } + #[test] fn native_stream_drops_stale_cache_before_rect_gs_fallback() { let mut with_gs = StreamOut::default(); @@ -6970,6 +7891,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const // picks; RDNA2 does for pixel shaders): the lanes 32..63 it reads come from `upper_lanes` // (split_wave64) let split = graphics_wave32(this); + let vs_started = std::time::Instant::now(); let vs_c = match console_to_dxil_for(vs, Stage::Vertex, 0, split) { Ok(b) => b, Err(e) => { @@ -6979,6 +7901,8 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const }; let mut samplers = vs_c.samplers; let vs_dxil = vs_c.dxil; + let ps_started = std::time::Instant::now(); + let vs_took = ps_started - vs_started; let ps_dxil = match shader_bytes(&d.PS) { Some(p) if is_console(p) => match console_to_dxil_for(p, Stage::Pixel, samplers.len() as u32, split) { Ok(b) => { @@ -6993,6 +7917,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const Some(p) => Some(p.to_vec()), None => None, }; + let ps_took = ps_started.elapsed(); let rs = abi_rs_for(this, &samplers)?; let mut copy: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::ptr::read(d); copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); @@ -7033,7 +7958,10 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const crate::shaders::pipeline_library::load_graphics(&library_name, ©) }; let mut cached = (cacheable && library_pso.is_none()).then(|| graphics_blob(gkey)).flatten(); - let disk = cacheable.then(|| driver_cache::graphics_path(disk_key.0, disk_key.1)).flatten(); + // (no file without the adapter's identity: it could be another adapter's; the root + // signature's memory windows are not in the description) + let disk = cacheable.then(|| driver_identity(this)).flatten().and_then(|id| driver_cache::graphics_path( + driver_cache::graphics_file_hash(disk_key, id, crate::gpu::recomp::pso::mem_windows()), disk_key.1)); let from_disk = cacheable && library_pso.is_none() && cached.is_none(); let mut loaded = None; if from_disk { @@ -7041,6 +7969,8 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); } let rejected_generation = cached.clone(); + // (for the driver compile log of this pipeline only) + GRAPHICS_STAGES.with(|s| s.set(Some((vs_took, ps_took)))); let build = if let Some(pso) = library_pso { *ppv = pso.into_raw(); GraphicsPsoBuild { hr: S_OK, built_in_driver: std::time::Duration::ZERO, reused: false, cache_eligible: false } @@ -7064,6 +7994,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const finish_pso(this, create, &desc as *const _ as _, riid, ppv) } else { finish_pso(this, f, c as *const _ as *const c_void, riid, ppv) }, ) }; + GRAPHICS_STAGES.with(|s| s.set(None)); let hr = build.hr; if build.reused { if let Some(blob) = cached.as_ref() { @@ -7071,9 +8002,9 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const } } if cacheable && build.cache_eligible { - keep_driver_blob(&GRAPHICS_BLOBS, GRAPHICS_BLOBS_MAX, gkey, bytes, disk.as_deref(), build.built_in_driver, - || read_pso_cached_blob(*ppv)); - if let (Some(p), Some(b)) = (disk.as_deref(), graphics_blob(gkey)) { + let kept = keep_driver_blob(&GRAPHICS_BLOBS, GRAPHICS_BLOBS_MAX, gkey, bytes, disk.as_deref(), build.built_in_driver, + || read_pso_cached_blob(*ppv)).or_else(|| graphics_blob(gkey)); + if let (Some(p), Some(b)) = (disk.as_deref(), kept) { crate::shaders::warm_replay::accepted(Some(p), &b); } } else if build.reused && from_disk { @@ -7102,8 +8033,12 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", shader_bytes(&d.PS))]); - TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + TRANSLATED_GRAPHICS.insert(*ppv as usize, ()); note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); + if (super::gpu_profile::on() || super::gpu_times::enabled()) && !super::present::trace_frame() { + let ps = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); + PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps)); + } if super::present::trace_frame() { let ps = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps)); @@ -7119,7 +8054,13 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const }; PSO_LAYOUTS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, elems.join(", ")); static N: AtomicU64 = AtomicU64::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 400 { + // (with `XCL_TRACE_FORMATS`, only pipelines that draw into a target of those formats: a + // title's menus make the first 400 long before the ones looked for) + let formats = super::bind::trace_formats(); + let wanted = formats.is_empty() + || d.RTVFormats[..d.NumRenderTargets.min(8) as usize].iter().any(|f| formats.contains(&f.0)) + || super::bind::trace_dsv_formats().contains(&d.DSVFormat.0); + if wanted && N.fetch_add(1, Ordering::Relaxed) < 1500 { let b = &d.BlendState.RenderTarget[0]; let z = &d.DepthStencilState; crate::xlog_info!( @@ -7181,14 +8122,20 @@ enum OwnedDesc { unsafe impl Send for OwnedDesc {} // Every pointer in an `OwnedDesc` refers to immutable backing storage owned by the same value. -// The translated builders only read it, so one retained recipe may safely be shared. +// The translated builders only read it, so one retained recipe, or a build and its translation +// ahead (`warm_graphics`), may safely share it. unsafe impl Sync for OwnedDesc {} /// A hash of a pipeline's shaders in their order (never 0): what `pso_async` knows a used /// pipeline by in the next run. /// `shaders_key` of the one shader `blob`. pub(crate) fn shader_key(blob: &[u8]) -> u64 { - ((0xcbf2_9ce4_8422_2325u64 ^ crate::gpu::shader::fnv64(blob)).wrapping_mul(0x0000_0100_0000_01b3)) | 1 + shader_key_of_hash(crate::gpu::shader::fnv64(blob)) +} + +/// `shader_key` of the shader whose dump hash (`fnv64`) is `hash`. +pub(crate) fn shader_key_of_hash(hash: u64) -> u64 { + ((0xcbf2_9ce4_8422_2325u64 ^ hash).wrapping_mul(0x0000_0100_0000_01b3)) | 1 } pub(crate) fn shaders_key>(blobs: &[T]) -> u64 { @@ -7527,6 +8474,11 @@ unsafe fn go_background( let (key, parts) = owned.shaders_key(); // (a graphics pipeline used in this run is built before the next starts: `gfx_records`) let described = if super::pso_async::lazy() { owned.record(key, &parts) } else { None }; + // (a compute pipeline's console program, as `translated_compute_pso` names it in the log) + let record = match &owned { + OwnedDesc::Compute(_, blobs) => blobs.first().map_or(0, |cs| crate::gpu::shader::fnv64(cs)), + _ => 0, + }; let build_key = match &owned { OwnedDesc::Compute(desc, shaders) => shaders.first().map(|shader| { compute_build_key::ComputeBuildKey::capture(this as usize, desc, shader.clone(), wave32_only(this)) @@ -7536,19 +8488,25 @@ unsafe fn go_background( // a big compute program that writes nothing but images: binds can go on without it let image_only = compute && super::pso_async::image_skip() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); let lazy = super::pso_async::lazy(); + let owned = std::sync::Arc::new(owned); + // (only a lazy pipeline is warmed: the backlog translates what it holds before the driver builds) + let warm: Option = (lazy && matches!(*owned, OwnedDesc::Graphics(..))).then(|| { + let owned = owned.clone(); + Box::new(move || unsafe { warm_graphics(dev, &owned) }) as super::pso_async::Warm + }); if super::pso_async::rebuild_recipes_enabled() { let recipe_dev = RecipeDev(ID3D12Device::from_raw_borrowed(&this)?.clone(), f); let recipe = super::pso_async::Recipe::new(move || { let dev = Dev(recipe_dev.0.as_raw() as usize, recipe_dev.1); run_owned_build(dev, &owned, build) }); - super::pso_async::submit_recipe_keyed(*ppv as usize, compute, recipe, !lazy, if lazy { key } else { 0 }, build_key); + super::pso_async::submit_recipe_keyed_with(*ppv as usize, compute, recipe, !lazy, if lazy { key } else { 0 }, build_key, warm, record); } else { let job: super::pso_async::Job = Box::new(move || run_owned_build(dev, &owned, build)); if lazy { - super::pso_async::submit_lazy_keyed(*ppv as usize, compute, job, key, build_key); + super::pso_async::submit_lazy_keyed_with(*ppv as usize, compute, job, key, build_key, warm, record); } else { - super::pso_async::submit_eager(*ppv as usize, compute, job, key, build_key); + super::pso_async::submit_eager_with(*ppv as usize, compute, job, key, build_key, record); } } if lazy { @@ -7565,6 +8523,25 @@ unsafe fn go_background( Some(hr) } +/// The translation and DXC compile of a graphics pipeline's console VS and PS as +/// `translated_graphics_pso_once` makes them, without the driver's compile: its later build +/// finds them in the shader caches (`pso_async::Warm`). Errors are left to that build to note. +unsafe fn warm_graphics(dev: Dev, d: &OwnedDesc) { + use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; + let OwnedDesc::Graphics(desc, ..) = d else { return }; + let this = dev.0 as *mut c_void; + let Some(vs) = shader_bytes(&desc.VS).filter(|v| is_console(v)) else { return }; + // (with HS / DS or a console GS it takes another path) + if shader_bytes(&desc.HS).is_some() || shader_bytes(&desc.DS).is_some() || shader_bytes(&desc.GS).is_some_and(|g| is_console(g)) { + return; + } + let split = graphics_wave32(this); + let Ok(vs_c) = console_to_dxil_for(vs, Stage::Vertex, 0, split) else { return }; + if let Some(ps) = shader_bytes(&desc.PS).filter(|p| is_console(p)) { + let _ = console_to_dxil_for(ps, Stage::Pixel, vs_c.samplers.len() as u32, split); + } +} + fn run_owned_build(dev: Dev, owned: &OwnedDesc, build: unsafe fn(Dev, &OwnedDesc, *mut *mut c_void) -> bool) -> usize { let mut out: *mut c_void = std::ptr::null_mut(); if unsafe { build(dev, owned, &mut out) } && !out.is_null() { out as usize } else { 0 } @@ -7621,7 +8598,23 @@ unsafe fn build_stream(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { } pub(super) unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - graphics_pso(this, desc, riid, ppv, false, true) + let _cost = crate::hle::api_cost::time(crate::hle::api_cost::Call::Pipeline); + let hr = graphics_pso(this, desc, riid, ppv, false, true); + note_pipeline_for_dump(this, desc, ppv, hr); + hr +} + +/// `XCL_DUMP_TARGETS`: pipeline `*ppv` was made from the graphics desc `desc` – its shaders, +/// blend state and formats, for the pipelines a dumped target lists (`targets::note_pipeline`). +unsafe fn note_pipeline_for_dump(this: *mut c_void, desc: *const c_void, ppv: *mut *mut c_void, hr: HRESULT) { + if !(super::targets::enabled() || super::capture::enabled()) || hr < 0 || ppv.is_null() || (*ppv).is_null() || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return; + } + let d = &*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); + // (in `own_graphics`' order: the set's key is the one `pso_async` and `used-pipelines.txt` know) + let stages: Vec<(&'static str, &[u8])> = [("vs", &d.VS), ("ps", &d.PS), ("ds", &d.DS), ("hs", &d.HS), ("gs", &d.GS)].into_iter().filter_map(|(s, b)| shader_bytes(b).map(|b| (s, b))).collect(); + super::targets::note_pipeline(*ppv as usize, &stages, &d.BlendState.RenderTarget[0], &d.RTVFormats[..d.NumRenderTargets.min(8) as usize], graphics_wave32(this)); + super::capture::note_graphics(*ppv as usize, d, &stages, graphics_wave32(this)); } /// `dev_create_graphics_pso`; `stream`: the desc is a pipeline stream's (`stream_pipeline`). @@ -7667,11 +8660,25 @@ unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID unsafe fn note_translated_compute(hr: HRESULT, ppv: *mut *mut c_void) { if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { - TRANSLATED_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + TRANSLATED_COMPUTE.insert(*ppv as usize, ()); } } unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let hr = compute_pso(this, desc, riid, ppv); + // `XCL_DUMP_TARGETS`: its CS, for the compute pipelines a dumped frame lists; + // `XCL_CAPTURE_FRAME`: its shader, for a captured frame's pipelines + if (super::targets::enabled() || super::capture::enabled()) && hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + if let Some(cs) = shader_bytes(&(*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC)).CS) { + super::targets::note_pipeline(*ppv as usize, &[("cs", cs)], &D3D12_RENDER_TARGET_BLEND_DESC::default(), &[], wave32_only(this)); + super::capture::note_compute(*ppv as usize, cs); + } + } + hr +} + +unsafe fn compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let _cost = crate::hle::api_cost::time(crate::hle::api_cost::Call::Pipeline); super::null::capture_compute_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); let (mut console, missed) = if super::pso_async::enabled() { attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) } else { (translated_compute_pso(this, f, desc, riid, ppv), false) }; @@ -7701,7 +8708,9 @@ unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const // a console shader the recompiler could not take must not reach the driver: AMD's shader // compiler crashes on the stripped DXIL (NOBC bitcode) instead of rejecting it let hr = if console.is_some() { E_INVALIDARG } else { finish_pso(this, f, desc, riid, ppv) }; - if hr >= 0 || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + // (a program of XCL's own that the driver refuses is not one that does nothing: its user has + // another way) + if hr >= 0 || super::title_textures::is_own_work() || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return hr; } let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC); @@ -7741,8 +8750,9 @@ pub struct TwoPassPso { impl Drop for TwoPassPso { fn drop(&mut self) { - // the compute pipeline state is XCL's (the root signatures are cached or the title's) - super::pso_async::release(self.compute); + // the compute pipeline state is XCL's (the root signatures are cached or the title's); + // lists in flight may bind it: `late_release` lets it go once the queues are past them + super::late_release::hold_pipeline(self.compute); } } @@ -7750,11 +8760,13 @@ static TWO_PASS: Mutex>>> = Mut /// The compute pass of a pipeline state XCL built from console MS / GS code. pub fn two_pass_of(pso: usize) -> Option> { - let pso = super::pso_async::resolve(pso); - two_pass_of_exact(pso) + two_pass_of_exact(super::pso_async::resolve(pso)) } -pub(super) fn two_pass_of_exact(pso: usize) -> Option> { +/// `two_pass_of` of exactly `pso`, not resolved again: a draw that resolved its pipeline once +/// (`pso_async::resolve_wait`) records its passes with what that gave. (Resolved again, a build +/// that finished in between gave the two-pass entry while the draw held the stand-in.) +pub fn two_pass_of_exact(pso: usize) -> Option> { TWO_PASS.lock().unwrap().as_ref()?.get(&pso).cloned() } @@ -8129,21 +9141,15 @@ fn passthrough_mesh_stream_accepts_a_triangle_driver_blob() { } } -#[allow(dead_code)] // Two-pass identities are consumed by the next stacked cache stage. mod two_pass_identity; - -/// The console PS of a two-pass pipeline (a PC PS passes as it is). -/// The PS of a two-pass pipeline (DXIL, static samplers – a PC PS passes as it is). -fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool) -> Result<(Option>, Vec), String> { - use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; - match ps { - Some(p) if is_console(p) => console_to_dxil_for(p, Stage::Pixel, 0, split_wave64).map(|c| (Some(c.dxil), c.samplers)).map_err(|e| format!("PS: {e}")), - Some(p) => Ok((Some(p.to_vec()), Vec::new())), - None => Ok((None, Vec::new())), - } -} - -fn two_pass_driver_id(device: *mut c_void) -> Option { +use two_pass_identity::Fnv64; + +/// The adapter of `device` and its driver (vendor, device, subsystem, revision, user-mode +/// driver version), for the names of the driver blobs kept on disk: the driver refuses another +/// one's blob (it is compiled again), and two adapters sharing the cache (a GPU and the +/// software one) would take turns overwriting each other's files. None: not known (no blob of +/// its pipelines is kept on disk). +fn driver_identity(device: *mut c_void) -> Option { use windows::Win32::Graphics::Dxgi::*; let dev = unsafe { ID3D12Device::from_raw_borrowed(&device) }?; let luid = unsafe { dev.GetAdapterLuid() }; @@ -8155,7 +9161,7 @@ fn two_pass_driver_id(device: *mut c_void) -> Option { let adapter: IDXGIAdapter = factory.EnumAdapterByLuid(luid).ok()?; let desc = adapter.GetDesc().ok()?; let version = adapter.CheckInterfaceSupport(&IDXGIDevice::IID).ok()?; - let mut h = two_pass_identity::Fnv64::new(); + let mut h = Fnv64::new(); h.u32(desc.VendorId); h.u32(desc.DeviceId); h.u32(desc.SubSysId); @@ -8165,8 +9171,19 @@ fn two_pass_driver_id(device: *mut c_void) -> Option { }) } +/// The console PS of a two-pass pipeline (a PC PS passes as it is). +/// The PS of a two-pass pipeline (DXIL, static samplers – a PC PS passes as it is). +fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool) -> Result<(Option>, Vec), String> { + use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; + match ps { + Some(p) if is_console(p) => console_to_dxil_for(p, Stage::Pixel, 0, split_wave64).map(|c| (Some(c.dxil), c.samplers)).map_err(|e| format!("PS: {e}")), + Some(p) => Ok((Some(p.to_vec()), Vec::new())), + None => Ok((None, Vec::new())), + } +} + pub(crate) fn preparation_driver_identity(dev: &ID3D12Device) -> Option { - two_pass_driver_id(dev.as_raw()) + driver_identity(dev.as_raw()) } /// Create the mesh pipeline (RS and shaders already in the stream) and its compute pass. @@ -8178,7 +9195,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: *ppv = std::ptr::null_mut(); let Some(rs) = abi_rs_for(this, &tp.samplers) else { return E_INVALIDARG }; let mesh_bytes = stream.shader_bytes(); - let disk_key = (mesh_bytes != 0).then(|| two_pass_driver_id(this)).flatten().and_then(|driver| { + let disk_key = (mesh_bytes != 0).then(|| driver_identity(this)).flatten().and_then(|driver| { two_pass_identity::two_pass_stream_key(&stream.0, ps_samplers, driver, crate::gpu::recomp::pso::mem_windows()) }); let gkey = disk_key.map(|(hash, bytes)| (hash, bytes, mesh_rs as usize)); @@ -8207,8 +9224,16 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: if gate && slot.is_none() { let waited = std::time::Instant::now(); let gate_stall = crate::stall::span(crate::stall::StallKind::DriverCompileGate); - let slots = if medium { &*MEDIUM_COMPILES } else { compile_slots(bytes) }; - slot = Some(big_compile_turn(slots, || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)); + slot = Some(if medium { + big_compile_turn( + &MEDIUM_COMPILES, + || big_compile_commit_free(big_compile_headroom(bytes)), + super::pso_async::build_is_wanted, + super::pso_async::build_is_ahead, + ) + } else { + huge_compile_turn(bytes) + }); drop(gate_stall); crate::xlog_info!("D3D12.X: two-pass {kind} PSO ({bytes} B DXIL) gated, waited {} ms", waited.elapsed().as_millis()); } @@ -8267,9 +9292,9 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: driver_cache::note(true, gloaded.take()); } } else { - keep_driver_blob(&GRAPHICS_BLOBS, GRAPHICS_BLOBS_MAX, key, mesh_bytes, gdisk.as_deref(), gin_driver, - || read_pso_cached_blob(mesh_pso.as_raw())); - if let (Some(path), Some(blob)) = (gdisk.as_deref(), graphics_blob(key)) { + let kept = keep_driver_blob(&GRAPHICS_BLOBS, GRAPHICS_BLOBS_MAX, key, mesh_bytes, gdisk.as_deref(), gin_driver, + || read_pso_cached_blob(mesh_pso.as_raw())).or_else(|| graphics_blob(key)); + if let (Some(path), Some(blob)) = (gdisk.as_deref(), kept) { crate::shaders::warm_replay::accepted(Some(path), &blob); } } @@ -8333,9 +9358,9 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: } } if hc >= 0 && !creused && !compute.is_null() { - keep_driver_blob(&COMPUTE_BLOBS, COMPUTE_BLOBS_MAX, ckey, tp.cs.len(), cdisk.as_deref(), cpersist_took, - || read_pso_cached_blob(compute)); - if let (Some(p), Some(b)) = (cdisk.as_deref(), compute_blob(ckey)) { + let kept = keep_driver_blob_at(&COMPUTE_BLOBS, COMPUTE_BLOBS_MAX, ckey, tp.cs.len(), cdisk.as_deref(), cpersist_took, + driver_cache::compute_keep_threshold(), || read_pso_cached_blob(compute)).or_else(|| compute_blob(ckey)); + if let (Some(p), Some(b)) = (cdisk.as_deref(), kept) { crate::shaders::warm_replay::accepted(Some(p), &b); } } else if creused && cfrom_disk { @@ -8375,12 +9400,184 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: note_pso_rs(mesh_pso, mesh_rs); TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); - if n < 5 || n % 1000 == 0 { - crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (compute {} B + mesh {} B DXIL)", tp.cs.len(), tp.ms.len()); + if n < 5 || n % 1000 == 0 || pso_trace() { + crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (compute {} B + mesh {} B DXIL; blobs reused: compute {creused}, mesh {greused})", tp.cs.len(), tp.ms.len()); } hr } +/// The mesh and amplification shaders of a stream, as XCL translates them: a console MS +/// container in the AS slot with no MS subobject (a retail game's minimap pipelines) is the +/// mesh shader it says it is. It used to be refused – translated, the title rendered nothing +/// from then on, which was the translated mesh shaders failing their output budget (ms_6_6), +/// not the slot. With the chunk budget fixed they translate and the title keeps rendering. +/// Returns (MS to translate, AS left): the moved shader is not an AS any more. +fn mesh_shader_slots<'a>(ms_slot: Option<&'a [u8]>, as_slot: Option<&'a [u8]>) -> (Option<&'a [u8]>, Option<&'a [u8]>) { + use crate::gpu::recomp::pso::is_console; + match (ms_slot, as_slot) { + (None, Some(a)) if is_console(a) && crate::gpu::xbox::parse(a).is_some_and(|sh| sh.stage == "MS") => (Some(a), None), + (ms, a) => (ms, a), + } +} + +#[cfg(test)] +mod mesh_slot_tests { + use super::{console_ms_in_as_slot, fallback_stream, mesh_shader_slots}; + use crate::gpu::xbox::tests::{sample, fssm, CODE}; + + /// A stream subobject: its type, then the payload at 4 (align 4) or 8 (align 8). + fn sub(ty: u32, payload: &[u8]) -> Vec { + let (_, palign) = super::super::null::subobject_payload(ty).unwrap(); + let poff = if palign == 8 { 8 } else { 4 }; + let mut b = vec![0u8; (poff + payload.len() + 7) & !7]; + b[..4].copy_from_slice(&ty.to_le_bytes()); + b[poff..poff + payload.len()].copy_from_slice(payload); + b + } + + fn bytecode(s: &[u8]) -> Vec { + let mut b = Vec::new(); + b.extend_from_slice(&(s.as_ptr() as u64).to_le_bytes()); + b.extend_from_slice(&(s.len() as u64).to_le_bytes()); + b + } + + /// The stream the retail title's AS-slot MS pipelines have: a console MS container in the + /// AS subobject, no MS subobject, a PS and the graphics state (`mesh_shader_slots` moves it). + fn as_slot_ms_stream(ms: &[u8], ps: &[u8]) -> Vec { + let mut s = sub(0, &0u64.to_le_bytes()); // ROOT_SIGNATURE: null + s.extend_from_slice(&sub(24, &bytecode(ms))); + s.extend_from_slice(&sub(2, &bytecode(ps))); + s.extend_from_slice(&sub(8, &vec![0u8; 328])); // BLEND + s.extend_from_slice(&sub(9, &u32::MAX.to_le_bytes())); // SAMPLE_MASK + s.extend_from_slice(&sub(10, &vec![0u8; 44])); // RASTERIZER + s.extend_from_slice(&sub(11, &vec![0u8; 52])); // DEPTH_STENCIL + s.extend_from_slice(&sub(15, &vec![0u8; 36])); // RENDER_TARGET_FORMATS + s.extend_from_slice(&sub(17, &[1, 0, 0, 0, 0, 0, 0, 0])); // SAMPLE_DESC + s + } + + /// `XCL_DUMP_TARGETS` notes a mesh pipeline's console MS (also from the AS slot) and its PS, + /// render target 0's blend and the formats; a stream with a PC mesh shader is not noted. + #[test] + fn a_dumped_target_knows_the_shaders_of_a_console_mesh_pipeline() { + let ms = sample(13, &[fssm(&CODE, &[(8, 13)])]); + let ps = b"DXBC-a-pixel-shader".to_vec(); + // D3D12_RT_FORMAT_ARRAY: RTFormats[8], then NumRenderTargets; two targets, + // R8G8B8A8_UNORM_SRGB (29) and R10G10B10A2_UNORM (24) + let mut formats = vec![0u8; 36]; + formats[..4].copy_from_slice(&29u32.to_le_bytes()); + formats[4..8].copy_from_slice(&24u32.to_le_bytes()); + formats[32..36].copy_from_slice(&2u32.to_le_bytes()); + let mut stream = sub(0, &0u64.to_le_bytes()); // ROOT_SIGNATURE: null + stream.extend_from_slice(&sub(24, &bytecode(&ms))); // the MS in the AS slot + stream.extend_from_slice(&sub(2, &bytecode(&ps))); + stream.extend_from_slice(&sub(8, &vec![0u8; 328])); // BLEND + stream.extend_from_slice(&sub(15, &formats)); + let subs = super::stream_subobjects(&stream).unwrap(); + let m = unsafe { super::mesh_stream_for_dump(&subs) }.expect("a console mesh pipeline is noted"); + assert_eq!(m.stages.iter().map(|s| s.0).collect::>(), ["ms", "ps"]); + assert_eq!(m.stages[0].1, ms.as_slice(), "the MS, moved out of the AS slot"); + assert_eq!(m.stages[1].1, ps.as_slice()); + assert_eq!(m.formats.iter().map(|f| f.0).collect::>(), [29, 24]); + // a PC mesh shader (not a console container) is left to the PC paths + let pc = b"DXBC-a-pc-mesh-shader".to_vec(); + let stream = as_slot_ms_stream(&pc, &ps); + assert!(unsafe { super::mesh_stream_for_dump(&super::stream_subobjects(&stream).unwrap()) }.is_none()); + } + + /// The stand-in for a console MS alone in the AS slot is a mesh pipeline: the subobject is + /// retyped to MS with the dummy MS (as `translated_mesh_stream` reads the title's stream), + /// the PS is the dummy PS. Left an empty AS and a PS, the stream had neither an MS nor a VS + /// and the driver refused it (E_INVALIDARG, NishantParajuli's and Chrysana's runs). + #[test] + fn the_stand_in_of_a_moved_ms_is_a_mesh_pipeline() { + let ms = sample(13, &[fssm(&CODE, &[(8, 13)])]); + let ps = b"DXBC-a-pixel-shader".to_vec(); + let stream = as_slot_ms_stream(&ms, &ps); + let desc = [stream.len(), stream.as_ptr() as usize]; + let subs = super::stream_subobjects(&stream).unwrap(); + assert!(unsafe { console_ms_in_as_slot(&subs) }); + let (buf, _) = unsafe { fallback_stream(desc.as_ptr() as *const u8) }.expect("a stand-in stream"); + let out = super::stream_subobjects(&buf).unwrap(); + assert!(!out.iter().any(|s| s.0 == 24), "no AS subobject left"); + let m = out.iter().find(|s| s.0 == 25).expect("an MS subobject"); + let dm = super::dummy_mesh().expect("DXC for the stand-in shaders"); + let got = unsafe { super::payload_shader(m.1) }.unwrap(); + assert_eq!(got, dm.0.as_slice(), "the dummy MS"); + let p = out.iter().find(|s| s.0 == 2).unwrap(); + assert_eq!(unsafe { super::payload_shader(p.1) }.unwrap(), dm.1.as_slice(), "the dummy PS"); + // a real AS with no MS is not moved, and its stand-in keeps the AS slot empty + let as_ = sample(14, &[fssm(&CODE, &[(8, 14)])]); + let stream = as_slot_ms_stream(&as_, &ps); + let desc = [stream.len(), stream.as_ptr() as usize]; + assert!(!unsafe { console_ms_in_as_slot(&super::stream_subobjects(&stream).unwrap()) }); + let (buf, _) = unsafe { fallback_stream(desc.as_ptr() as *const u8) }.unwrap(); + let out = super::stream_subobjects(&buf).unwrap(); + assert!(out.iter().any(|s| s.0 == 24) && !out.iter().any(|s| s.0 == 25)); + } + + /// The stand-in's target formats are the PC's, as the real pipeline's: the console's + /// D16_UNORM_S8_UINT (118) is D24_UNORM_S8_UINT (45) and a B4G4R4A4 target (115) is + /// R8G8B8A8 (28). With the console's the driver refuses the stand-in (the title's depth-only + /// mesh pipelines; NishantParajuli's follow-up, reproduced natively by thehollowedone). + #[test] + fn the_stand_in_of_a_stream_has_the_pcs_target_formats() { + let mut s = sub(15, &{ + let mut p = Vec::new(); + for f in [115u32, 28, 0, 0, 0, 0, 0, 0, 2] { + p.extend_from_slice(&f.to_le_bytes()); + } + p + }); + s.extend_from_slice(&sub(16, &118u32.to_le_bytes())); + let desc = [s.len(), s.as_ptr() as usize]; + let (out, _) = unsafe { fallback_stream(desc.as_ptr() as *const u8) }.expect("a stand-in stream"); + let subs = super::stream_subobjects(&out).unwrap(); + let word = |p: &[u8], k: usize| u32::from_le_bytes(p[4 * k..4 * k + 4].try_into().unwrap()); + assert_eq!((subs[0].0, word(subs[0].1, 0), word(subs[0].1, 1), word(subs[0].1, 8)), (15, 28, 28, 2)); + assert_eq!((subs[1].0, word(subs[1].1, 0)), (16, 45)); + } + + /// A console MS container alone in the AS slot becomes the MS; a real AS (console or PC), + /// an MS already present, or a PC shader in the AS slot are left as they are. + #[test] + fn a_console_ms_in_the_as_slot_is_the_mesh_shader() { + let ms = sample(13, &[fssm(&CODE, &[(8, 13)])]); + let as_ = sample(14, &[fssm(&CODE, &[(8, 14)])]); + let pc = b"DXBC-not-a-console-container".to_vec(); + // MS in the AS slot, no MS: moved, and not an AS any more + let (m, a) = mesh_shader_slots(None, Some(&ms)); + assert!(m.is_some_and(|m| std::ptr::eq(m, ms.as_slice())) && a.is_none()); + // an MS present: both slots untouched, whatever the AS holds + let (m, a) = mesh_shader_slots(Some(&ms), Some(&as_)); + assert!(m.is_some_and(|m| std::ptr::eq(m, ms.as_slice())) && a.is_some_and(|a| std::ptr::eq(a, as_.as_slice()))); + // a console AS (not an MS) stays in the AS slot + let (m, a) = mesh_shader_slots(None, Some(&as_)); + assert!(m.is_none() && a.is_some_and(|a| std::ptr::eq(a, as_.as_slice()))); + // a PC shader in the AS slot stays too + let (m, a) = mesh_shader_slots(None, Some(&pc)); + assert!(m.is_none() && a.is_some()); + // nothing: nothing + assert!(mesh_shader_slots(None, None) == (None, None)); + } + + /// The cached-only attempt defers a moved MS like a console compute pipeline: `defer` + /// marks the attempt missed, so `dev_create_pipeline_state` takes the background path + /// (stand-in now, translation on the worker / first bind) instead of translating on the + /// title's thread – tens of thousands of these pipelines during boot delayed the intro + /// by seconds on NVIDIA and past a minute on AMD wave64. Outside the attempt (the + /// worker's build) nothing is deferred. + #[test] + fn a_moved_ms_defers_in_the_attempt_only() { + let (_, missed) = crate::gpu::recomp::dxc::cached_only(|| { + assert!(crate::gpu::recomp::dxc::defer(), "inside the attempt: deferred"); + }); + assert!(missed, "the attempt is missed: the caller takes the background path"); + assert!(!crate::gpu::recomp::dxc::defer(), "outside: the build translates"); + } +} + /// CreatePipelineState with a console MS: Some(hr) when it was a console mesh pipeline /// (translated, or E_INVALIDARG – console bytecode must not reach the driver). unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { @@ -8399,17 +9596,11 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri let subs = stream_subobjects(std::slice::from_raw_parts(base as *const u8, size))?; let as_slot = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS.0 as u32).and_then(|s| payload_shader(s.1)); let ms_slot = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32).and_then(|s| payload_shader(s.1)); - // A console MS container in the AS slot and no MS subobject (a retail game's minimap - // pipelines): refused. Translated as the mesh shader they are, the title rendered nothing - // from then on (a black screen every run); refused, it goes on to its menus. What it - // expects of them is not known yet. - if let (None, Some(a)) = (ms_slot, as_slot) { - if is_console(a) && crate::gpu::xbox::parse(a).is_some_and(|sh| sh.stage == "MS") { - note_translation_error(format!("mesh pipeline with its MS {:016x} in the AS slot – refused", crate::gpu::shader::fnv64(a))); - return Some(E_INVALIDARG); - } - } - let ms = ms_slot?; + // a console MS in the AS slot with no MS subobject: moved, and translated when first + // bound (below), not on the title's thread for each of tens of thousands + let moved = ms_slot.is_none(); + let (ms, as_slot) = mesh_shader_slots(ms_slot, as_slot); + let Some(ms) = ms else { return None }; if !is_console(ms) { return None; } @@ -8422,10 +9613,20 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri )); return Some(E_INVALIDARG); } - // made when first bound (`pso_async::lazy`): not even translated now + // made when first bound (`pso_async::lazy`): not even translated now. A moved MS too: the + // title creates tens of thousands of these during boot and uses few; translating each on + // the calling thread delayed the intro by seconds (NVIDIA) or past a minute (AMD wave64, + // the split path). The attempt defers, `go_background` hands the title a stand-in and the + // worker (or the bind) runs this path again outside cached-only. if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { return None; } + if moved { + let n = AS_SLOT_MS.fetch_add(1, Ordering::Relaxed); + if n < 5 || n % 1000 == 0 { + crate::xlog_info!("D3D12.X: mesh pipeline with its MS {:016x} in the AS slot – translated as MS (#{})", crate::gpu::shader::fnv64(ms), n + 1); + } + } let ps = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32).and_then(|s| payload_shader(s.1)); let console_ps = ps; let (tp, (ps, ps_samplers)) = match (console_mesh(ms, ps, wave32_only(this)), two_pass_ps(ps, graphics_wave32(this))) { @@ -8485,6 +9686,9 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri let hr = finish_two_pass(this, &out, tp, rs, &ps_samplers, node_mask, "MS", riid, ppv); if hr >= 0 { super::dred::label(*ppv as usize, &[("ms", Some(ms)), ("ps", console_ps)]); + if super::gpu_times::enabled() { + PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(ms), console_ps.map_or(0, crate::gpu::shader::fnv64))); + } } Some(hr) } @@ -8560,10 +9764,20 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE let hr = finish_two_pass(this, &out, tp, rs, &ps_samplers, d.NodeMask, "GS", riid, ppv); if hr >= 0 { super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("gs", Some(gs)), ("ps", shader_bytes(&d.PS))]); + if super::gpu_times::enabled() { + PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(gs), shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64))); + } } hr } +/// A console MS container in the stream's AS subobject and no MS subobject (`mesh_shader_slots`). +unsafe fn console_ms_in_as_slot(subs: &[(u32, &[u8])]) -> bool { + let shader = |ty: i32| subs.iter().find(|s| s.0 == ty as u32).and_then(|s| payload_shader(s.1)); + shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0).is_none() + && shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS.0).is_some_and(|a| crate::gpu::recomp::pso::is_console(a) && crate::gpu::xbox::parse(a).is_some_and(|sh| sh.stage == "MS")) +} + /// Rewrite a pipeline state stream with stand-in shaders. None if not possible. unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { let size = *(desc as *const usize); @@ -8573,12 +9787,17 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { } let mut buf = std::slice::from_raw_parts(base as *const u8, size).to_vec(); let d = dummy(); + // A console MS alone in the AS slot is the stream's mesh shader (`mesh_shader_slots`), so its + // stand-in is a mesh pipeline too, with the dummy MS in that subobject as an MS. Left an AS + // without a shader, the stream had a PS and neither an MS nor a VS: the driver refused it + // (E_INVALIDARG) and every such pipeline was built in the title's call (NishantParajuli). + let ms_in_as = stream_subobjects(&buf).is_some_and(|subs| console_ms_in_as_slot(&subs)); let (mesh, rt_count, rt_formats) = { - let mut mesh = false; + let mut mesh = ms_in_as; let mut rt_count = 0u32; let mut rt_formats = [windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(0); 8]; if let Some(subs) = stream_subobjects(&buf) { - mesh = subs.iter().any(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32); + mesh = mesh || subs.iter().any(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32); if let Some((_, p)) = subs.iter().find(|(ty, p)| *ty == 15 && p.len() >= 36) { for k in 0..8 { let f = super::device_x::pc_target_format(u32::from_le_bytes(p[4 * k..4 * k + 4].try_into().unwrap())); @@ -8610,6 +9829,10 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { 1 => put(&mut buf, &d.vs), 2 => put(&mut buf, dm.map_or(&d.ps[..], |m| &m.1[..])), 6 => put(&mut buf, &d.cs), + 24 if ms_in_as => { + buf[off..off + 4].copy_from_slice(&(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32).to_le_bytes()); + put(&mut buf, &dm?.0) + } 3 | 4 | 5 | 24 => put(&mut buf, &[]), 25 => put(&mut buf, &dm?.0), 8 if psize >= std::mem::size_of::() => { @@ -8618,6 +9841,10 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { let bytes = std::slice::from_raw_parts(&blend as *const D3D12_BLEND_DESC as *const u8, std::mem::size_of::()); buf[at..at + bytes.len()].copy_from_slice(bytes); } + // RENDER_TARGET_FORMATS, DEPTH_STENCIL_FORMAT: the console's formats as the PC's, as + // the real pipeline gets them (`translated_mesh_stream`) – with a console-only one + // (a retail game's depth-only mesh pipelines: D16_UNORM_S8_UINT) the driver refuses + // the stand-in (E_INVALIDARG) and the pipeline is built in the title's call 15 if psize >= 32 => { for k in 0..8 { let f = super::device_x::pc_target_format(u32::from_le_bytes(buf[at + 4 * k..at + 4 * k + 4].try_into().unwrap())); @@ -8948,6 +10175,86 @@ mod pso_blend_and_tsharp_tests { let img_arr = crate::gpu::desc::image(&srv_tsharp_from_desc(11, &msaa_arr, Some(&msaa_arr_srv)).unwrap()).unwrap(); assert_eq!((img_arr.ty, img_arr.depth, img_arr.base_level, img_arr.last_level), (crate::gpu::desc::ImageType::D2MsaaArray, 4, 0, 2)); } + + /// A stencil view is a UINT view: its T# has a uint format, so translated shaders load it as + /// integers (`img_cls`: the buffer-format table's numeric type 4); the depth view stays float. + #[test] + fn srv_tsharp_of_a_stencil_view_has_a_uint_format() { + let class = |fmt: u32| (crate::gpu::recomp::emit::buf_format_info(fmt as usize) >> 3) & 7; + for (resource, stencil, depth) in [ + (DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_X24_TYPELESS_G8_UINT, DXGI_FORMAT_R24_UNORM_X8_TYPELESS), + (DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_X32_TYPELESS_G8X24_UINT, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS), + ] { + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 2560, + Height: 1440, + DepthOrArraySize: 1, + MipLevels: 1, + Format: resource, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let view = |format, plane| D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, PlaneSlice: plane, ResourceMinLODClamp: 0.0 }, + }, + }; + let s = crate::gpu::desc::image(&srv_tsharp_from_desc(5, &rd, Some(&view(stencil, 1))).unwrap()).unwrap(); + assert_eq!((s.format, class(s.format)), (5, 4), "stencil view {stencil:?}: T# format 8_UINT, uint class"); + assert_eq!((s.width, s.height), (2560, 1440)); + let d = crate::gpu::desc::image(&srv_tsharp_from_desc(6, &rd, Some(&view(depth, 0))).unwrap()).unwrap(); + assert_ne!(class(d.format), 4, "depth view {depth:?} stays a float image"); + } + } + + /// A translated `image_load` of a stencil view (the T# `srv_tsharp_from_desc` writes for it) + /// gives the stencil values: in the second component, as the PC view has them. + #[test] + fn gpu_image_load_of_a_stencil_view_gives_the_stencil() { + use crate::gpu::recomp::runner::{self, KernelState, TestTexture, TexDim}; + use crate::gpu::rdna2::encode; + match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), + } + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R24G8_TYPELESS, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let view = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_X24_TYPELESS_G8_UINT, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, PlaneSlice: 1, ResourceMinLODClamp: 0.0 } }, + }; + // the runner's SRV of texture 0 is at heap index 0 + let t = srv_tsharp_from_desc(0, &rd, Some(&view)).unwrap(); + let mut code = encode("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("DMASK", 0x2), ("DIM", 1), ("UNORM", 1)], None).unwrap(); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let mut st = KernelState::default(); + st.sgpr[16..24].copy_from_slice(&t); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = (l % 8) as u32; + r[1] = (l / 8) as u32; + } + let stencil: Vec = (0..64).map(|k| 0x40 + k as u8).collect(); + let tex = [TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_X24_TYPELESS_G8_UINT, width: 8, height: 8, depth: 1, texel_bytes: 1, data: stencil, uav: false }]; + let r = runner::run_code_with(&code, &st, &[], &tex, &[]).unwrap(); + let bad: Vec = (0..64).filter(|&l| r.vgpr[l][10] != 0x40 + l as u32).map(|l| format!("lane {l}: {:#x}", r.vgpr[l][10])).collect(); + assert!(bad.is_empty(), "image_load of a stencil view (want 0x40 + lane):\n{}", bad.join("\n")); + } } enum StreamPipeline { @@ -9348,7 +10655,7 @@ unsafe fn translated_graphics_stream_once(this: *mut c_void, desc: *const c_void if !ppv.is_null() && !(*ppv).is_null() { note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", console_ps)]); - TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + TRANSLATED_GRAPHICS.insert(*ppv as usize, ()); if build.used_rect_gs { RECT_LIST_GS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); } } if n < 5 || n % 1000 == 0 { crate::xlog_info!("D3D12.X: graphics stream PSO from translated console shaders (#{})", n + 1); } @@ -9386,6 +10693,66 @@ fn subobjects_have_unreadable_shader(subs: &[(u32, &[u8])]) -> bool { } pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let hr = pipeline_state(this, desc, riid, ppv); + // `XCL_CAPTURE_FRAME`: a stream the graphics and compute paths did not note (mesh) + if super::capture::enabled() && hr >= 0 && !ppv.is_null() { + super::capture::note_stream(*ppv as usize); + } + note_mesh_stream_for_dump(desc, ppv, hr); + hr +} + +/// `XCL_DUMP_TARGETS`: a pipeline stream with a console mesh shader (`translated_mesh_stream`) +/// is noted with its MS and PS, render target 0's blend and the formats, as a graphics desc is +/// (`note_pipeline_for_dump`): without it a dumped target drawn by mesh pipelines lists them as +/// "not known" and their pixel shaders are not written. +unsafe fn note_mesh_stream_for_dump(desc: *const c_void, ppv: *mut *mut c_void, hr: HRESULT) { + if !super::targets::enabled() || hr < 0 || ppv.is_null() || (*ppv).is_null() || !crate::gpu::shader::readable(desc as usize, 16) { + return; + } + let (size, base) = (*(desc as *const usize), *((desc as usize + 8) as *const usize)); + if !crate::gpu::shader::readable(base, size) { + return; + } + let subs = known_subobjects(std::slice::from_raw_parts(base as *const u8, size)); + if let Some(m) = mesh_stream_for_dump(&subs) { + super::targets::note_pipeline(*ppv as usize, &m.stages, &m.blend, &m.formats, false); + } +} + +/// What `note_mesh_stream_for_dump` notes of a stream's subobjects: its MS (also from the AS +/// slot, `mesh_shader_slots`) and PS if the MS is a console one, render target 0's blend and +/// the render target formats. +struct MeshStreamForDump<'a> { + stages: Vec<(&'static str, &'a [u8])>, + blend: D3D12_RENDER_TARGET_BLEND_DESC, + formats: Vec, +} + +unsafe fn mesh_stream_for_dump<'a>(subs: &[(u32, &'a [u8])]) -> Option> { + let shader = |ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE| subs.iter().find(|s| s.0 == ty.0 as u32).and_then(|s| payload_shader(s.1)); + let (ms, _) = mesh_shader_slots(shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS), shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS)); + let ms = ms.filter(|ms| crate::gpu::recomp::pso::is_console(ms))?; + let mut stages = vec![("ms", ms)]; + if let Some(ps) = shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS) { + stages.push(("ps", ps)); + } + let payload = |ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE| subs.iter().find(|s| s.0 == ty.0 as u32).map(|s| s.1); + let blend = payload(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND) + .filter(|p| p.len() >= std::mem::size_of::()) + .map(|p| std::ptr::read_unaligned(p.as_ptr() as *const D3D12_BLEND_DESC).RenderTarget[0]) + .unwrap_or_default(); + let formats = payload(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS) + .filter(|p| p.len() >= std::mem::size_of::()) + .map(|p| { + let rt = std::ptr::read_unaligned(p.as_ptr() as *const D3D12_RT_FORMAT_ARRAY); + rt.RTFormats[..rt.NumRenderTargets.min(8) as usize].to_vec() + }) + .unwrap_or_default(); + Some(MeshStreamForDump { stages, blend, formats }) +} + +unsafe fn pipeline_state(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { super::null::capture_stream_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_mesh_stream(this, desc, riid, ppv)) } else { (translated_mesh_stream(this, desc, riid, ppv), false) }; @@ -9400,7 +10767,12 @@ pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void return hr; } match stream_pipeline(desc) { - StreamPipeline::Graphics(d, cacheable) => return graphics_pso(this, &*d as *const _ as *const c_void, riid, ppv, true, cacheable), + StreamPipeline::Graphics(d, cacheable) => { + let g = &*d as *const _ as *const c_void; + let hr = graphics_pso(this, g, riid, ppv, true, cacheable); + note_pipeline_for_dump(this, g, ppv, hr); + return hr; + } StreamPipeline::GraphicsStream => { let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_graphics_stream(this, desc, riid, ppv)) } else { (translated_graphics_stream(this, desc, riid, ppv), false) }; if missed { @@ -9444,7 +10816,7 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 let iid = pc_iid(Kind::RootSignature); hr = f(this, mask, blob, len, &iid, ppv); } - if hr < 0 { + if hr < 0 && !super::title_textures::is_own_work() { // console root signature rejected → empty one so the title keeps going let desc = D3D12_ROOT_SIGNATURE_DESC { Flags: D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, ..Default::default() }; let mut ser = None; @@ -9477,6 +10849,10 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, desc: *const c_void, handle: usize) { let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailViewDescriptor); + let _t = crate::hle::api_cost::time_if( + super::look_stats::deep() && !super::title_textures::is_own_work() && !super::present::presenting(), + crate::hle::api_cost::Call::ViewDescriptor, + ); type F = unsafe extern "system" fn(*mut c_void, *mut c_void, *const c_void, usize); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateRenderTargetView"))); // a view in a console-only format, or of a target made R8G8B8A8 (`device_x::pc_resource_desc`) @@ -9488,6 +10864,13 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de let desc = copy.as_ref().map_or(desc, |c| c as *const _ as *const c_void); f(this, res, desc, handle); super::present::note_rtv(handle, res); + if super::capture::enabled() { + super::capture::note_view(handle, res as usize, false, (!desc.is_null()).then(|| (desc as *const [u32; 6]).read_unaligned())); + } + super::lut3d::wrote(res as usize, false, || { + let v = copy.filter(|c| c.ViewDimension == D3D12_RTV_DIMENSION_TEXTURE3D).map(|c| (c.Format.0, c.Anonymous.Texture3D)); + format!("a render target view made ({handle:#x}): {}", v.map_or("the default view".into(), |(f, t)| format!("format {f}, mip {}, depth slices {} (+{})", t.MipSlice, t.FirstWSlice, t.WSize as i32))) + }); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 12 { @@ -9500,8 +10883,13 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de /// ClearRenderTargetView: as on the PC (`XCL_TRACE_FRAME`: the colours logged) unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *const [f32; 4], n: u32, rects: *const c_void) { let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailCopy); + let _t = crate::hle::api_cost::time_if( + super::look_stats::deep() && !super::title_textures::is_own_work() && !super::present::presenting(), + crate::hle::api_cost::Call::ListCopy, + ); type F = unsafe extern "system" fn(*mut c_void, usize, *const [f32; 4], u32, *const c_void); - let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ClearRenderTargetView"))); + let f: F = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "ClearRenderTargetView"))); + let _c = super::capture::op(this, || Some(super::capture::clear("rtv", rtv as u64, None, color.as_ref().map_or([0; 4], |c| c.map(f32::to_bits)), 0, n))); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 16 { @@ -9511,15 +10899,25 @@ unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *co super::present::note_use(r, super::present::USE_CLEAR); } } + if super::lut3d::on() { + if let Some(r) = super::present::rtv_resource(rtv) { + super::lut3d::wrote(r, false, || format!("ClearRenderTargetView {rtv:#x} to {:?}, {n} rects", color.as_ref())); + } + } f(this, rtv, color, n, rects) } unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rtvs: *const usize, single: i32, dsv: *const usize) { let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailBind); + let _t = crate::hle::api_cost::time_if( + super::look_stats::deep() && !super::title_textures::is_own_work() && !super::present::presenting(), + crate::hle::api_cost::Call::BindState, + ); type F = unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize); - let f: F = std::mem::transmute(orig_fn(this, slot!(this, "OMSetRenderTargets"))); + let f: F = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "OMSetRenderTargets"))); f(this, n, rtvs, single, dsv); super::list_x::note_render_targets(this, n, rtvs, single, dsv); + let _ = super::capture::op(this, || Some(super::capture::targets_op(this))); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 12 { @@ -9586,14 +10984,14 @@ unsafe extern "system" fn cl_clear_state(this: *mut c_void, pso: *mut c_void) { unsafe extern "system" fn cl_draw_instanced(this: *mut c_void, vcount: u32, icount: u32, sv: u32, si: u32) { super::list_x::prepare_draw(this); type F = unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32); - let f: F = std::mem::transmute(orig_fn(this, slot!(this, "DrawInstanced"))); + let f: F = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "DrawInstanced"))); f(this, vcount, icount, sv, si); } unsafe extern "system" fn cl_draw_indexed_instanced(this: *mut c_void, icount: u32, inst: u32, si: u32, bv: i32, sinst: u32) { super::list_x::prepare_draw(this); type F = unsafe extern "system" fn(*mut c_void, u32, u32, u32, i32, u32); - let f: F = std::mem::transmute(orig_fn(this, slot!(this, "DrawIndexedInstanced"))); + let f: F = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "DrawIndexedInstanced"))); f(this, icount, inst, si, bv, sinst); } @@ -9609,7 +11007,7 @@ unsafe extern "system" fn cl_execute_indirect( ) { super::list_x::prepare_draw(this); type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut c_void, u64, *mut c_void, u64); - let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ExecuteIndirect"))); + let f: F = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "ExecuteIndirect"))); f(this, sig, max_count, arg_buf, arg_off, cnt_buf, cnt_off); } @@ -9696,6 +11094,10 @@ pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailListLifecycle); + let _t = crate::hle::api_cost::time_if( + super::look_stats::deep() && !super::title_textures::is_own_work() && !super::present::presenting(), + crate::hle::api_cost::Call::ListLifecycle, + ); // Lists may still hold recordings on it that the title submits again (`alloc_pool`). UMA // follows each native backing and is released only when reset_pc_allocator resets that one. match super::alloc_pool::title_reset(this) { @@ -9742,8 +11144,21 @@ static QUEUE_OLDER: AtomicBool = AtomicBool::new(false); /// command list slots of the newer layout → the older layout's slot of the same method /// (`DispatchMesh` sits at newer #129 after #126 RSSetShadingRate, #127 RSSetShadingRateImage, -/// and #128 Scarlett-only shading-rate/color struct; older #127, two slots before as the others). -const NEWER_LIST_SLOTS: [(usize, usize); 22] = [(61, 59), (62, 60), (63, 61), (64, 62), (65, 63), (70, 68), (71, 69), (72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (129, 127), (139, 10)]; +/// and #128 Scarlett-only shading-rate/color struct: the older layout's #124 … #127, two slots +/// on as the other methods are). +const NEWER_LIST_SLOTS: [(usize, usize); 23] = [(61, 59), (62, 60), (63, 61), (64, 62), (65, 63), (69, 67), (70, 68), (71, 69), (72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (129, 127), (139, 10)]; + +pub(super) unsafe fn list_device(list: *mut c_void) -> Option { + type F = unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(list, 7)); + let iid = pc_iid(Kind::Device); + let mut raw: *mut c_void = std::ptr::null_mut(); + if f(list, &iid, &mut raw) >= 0 && !raw.is_null() { + Some(ID3D12Device::from_raw(raw)) + } else { + None + } +} /// The title called device method `slot`, which only runtimes with the newer layouts have (a retail game /// records its first lists before any queue call could tell). @@ -9791,6 +11206,8 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a }; super::list_x::break_cycles_before_title_signal(this as usize, a1, a2 as u64); super::title_textures::tie_downloads(a1 as *mut c_void, a2 as u64, downloads); + // (work that waits for it may use memory committed since it was submitted) + super::sparse::send_pending(); let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(PC_SIGNAL)); let hr = f(this, a1, a2); if hr >= 0 { @@ -9845,6 +11262,7 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a f(this, a1) } 23 => q_signal_x(this, a1 as *mut c_void, a2 as u64, a3 as u32) as u32 as usize, + 29 if crate::hle::kernelx::mirrors::page_mappings() => q_copy_page_mappings(a1 as u32, a2, a3, a4 as u32) as u32 as usize, 30 => super::present::present_x(this, a1 as u32, a2 as *const u8, a3 as *const u8) as u32 as usize, // the newer layout's #35: ExecuteCommandListsX(count, lists, a value, flags) – a retail // game submits all its command lists this way (flags 3; 0 for the one it recorded at @@ -9891,6 +11309,59 @@ macro_rules! queue_slots { } queue_slots!(14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35); +/// The calls of the queue's page-mapping method recorded so far and what they did, summed, and +/// when their line was logged last. +static PAGE_MAPPINGS: Mutex<(u64, crate::hle::kernelx::mirrors::Mapped, Option)> = + Mutex::new((0, crate::hle::kernelx::mirrors::Mapped { mapped: 0, unmapped: 0, empty: 0, elsewhere: 0 }, None)); + +/// What the queue's page mappings did so far: `n` calls with the totals `t`, the last one's +/// pool, then the view pages that followed their physical page (`moved`), the textures read +/// again for a mapping changed under them (`reread`), the pages of their uploads by where they +/// were read (`pages`: `title_textures::page_counts`) and the GPU-view tiles linked again +/// (`tiles`: `sparse::page_tiles`). +fn page_mapping_line(n: u64, t: crate::hle::kernelx::mirrors::Mapped, pool: usize, pool_pages: u32, moved: u64, reread: u64, pages: [u64; 4], tiles: [u64; 2]) -> String { + let [a, b, c, z] = pages; + format!( + "D3D12.X: queue CopyPageMappingsBatchX: {n} calls; GPU-view pages so far: {} mapped, {} unmapped, {} named a pool page with no page mapped there, {} elsewhere ignored (pool {pool:#x}, {pool_pages} pages of 64 KiB); {moved} moved with their physical page; textures: {reread} read again for a mapping changed under them, pages of their uploads: {a} where the mapping put the page, {b} at the CPU view's same offset, {c} at that offset never mapped, {z} unmapped; tiles: {} shown anew, {} followed their page", + t.mapped, t.unmapped, t.empty, t.elsewhere, tiles[0], tiles[1] + ) +} + +/// command queue #29 (#31 in the newer layout) `CopyPageMappingsBatchX(count, batches, pool, +/// pool pages, flags)`: the title maps pages of its memory into GPU views – a retail game the +/// pages its texture streaming fills into the GPU views its textures are in. Each GPU-view page +/// it names shows the physical page mapped at its pool page from here on +/// (`kernelx::mirrors::apply_batches`); as a stub every mapping was dropped and the view showed +/// its CPU view (#1031). S_OK always, as the stub (what the title does with it is not known); +/// the fifth argument does not reach `queue_dispatch`. +unsafe fn q_copy_page_mappings(count: u32, batches: usize, pool: usize, pool_pages: u32) -> HRESULT { + match crate::hle::kernelx::mirrors::apply_batches(count, batches, pool, pool_pages) { + Some(d) => { + let mut t = PAGE_MAPPINGS.lock().unwrap_or_else(|e| e.into_inner()); + t.0 += 1; + t.1.mapped += d.mapped; + t.1.unmapped += d.unmapped; + t.1.empty += d.empty; + t.1.elsewhere += d.elsewhere; + // at the first call, at powers of two and when 10 s have passed since the last line + let now = std::time::Instant::now(); + if t.0 == 1 || t.0.is_power_of_two() || t.2.map_or(true, |l| now.duration_since(l).as_secs() >= 10) { + t.2 = Some(now); + let (n, total) = (t.0, t.1); + drop(t); + use crate::hle::kernelx::mirrors; + let line = page_mapping_line(n, total, pool, pool_pages, mirrors::moved_pages(), super::title_textures::rereads(), super::title_textures::page_counts(), super::sparse::page_tiles()); + crate::xlog_info!("{line}"); + } + } + None => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: queue CopyPageMappingsBatchX({count}, {batches:#x}, {pool:#x}, {pool_pages}): a batch or range is unreadable or leaves the pool – the call is ignored")); + } + } + S_OK +} + /// command queue #23 SignalX(fence, value, flush flags): Signal with the console's cache flush /// options – the PC's Signal makes the queue's writes visible itself. (A stub that signalled /// nothing left Fortnite's render fences pending: its render thread waited, textures were @@ -9914,6 +11385,8 @@ unsafe fn q_signal_x_serialized(this: *mut c_void, fence: *mut c_void, value: u6 let downloads = super::title_textures::submit_prepared_downloads(this, prepared)?; super::list_x::break_cycles_before_title_signal(this as usize, fence as usize, value); super::title_textures::tie_downloads(fence, value, downloads); + // (work that waits for it may use memory committed since it was submitted) + super::sparse::send_pending(); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, PC_SIGNAL)); let hr = f(this, fence, value); if hr >= 0 { @@ -9923,14 +11396,105 @@ unsafe fn q_signal_x_serialized(this: *mut c_void, fence: *mut c_void, value: u6 Ok(hr) } -/// Fence::Signal (CPU) -unsafe extern "system" fn fence_completed(this: *mut c_void) -> u64 { - let f: unsafe extern "system" fn(*mut c_void) -> u64 = std::mem::transmute(orig_fn(this, slot_of(this, "GetCompletedValue"))); - super::title_textures::safe_fence_value(this as usize, f(this)) +/// GetCompletedValue of `fence` as the PC has it, without what the hook below does for the title +/// on the way (it lands copies back, which takes the sparse state's lock): for XCL's own queries, +/// the ones made with that lock held above all. With the hook, each such query stood ~2 ms +/// trying for the lock its own thread held, and a pass over the pending copies took seconds +/// with every submitting thread behind it. +pub(super) unsafe fn fence_completed(fence: &ID3D12Fence) -> u64 { + const PC_GET_COMPLETED_VALUE: usize = 8; + let p = fence.as_raw(); + // (a fence XCL holds a reference to: no need to ask Windows whether it can be read, as + // `is_adopted` does) + let f: unsafe extern "system" fn(*mut c_void) -> u64 = if is_ext(vt(p) as usize) { + std::mem::transmute(orig_fn(p, PC_GET_COMPLETED_VALUE)) + } else { + std::mem::transmute(*vt(p).add(PC_GET_COMPLETED_VALUE)) + }; + f(p) +} + +/// Fence::GetCompletedValue. What the title's lists wrote into its sparse memory comes back +/// asynchronously (`sparse::readback_after_execute`): the copies back the value covers land first. +unsafe extern "system" fn fence_get_completed_value(this: *mut c_void) -> u64 { + let f: unsafe extern "system" fn(*mut c_void) -> u64 = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12Fence", "GetCompletedValue"))); + let v = f(this); + super::sparse::settle_readbacks_try(); + super::title_textures::safe_fence_value(this as usize, v) +} + +/// A `fence_set_event_on_completion` wait: the title's event, XCL's own event the fence sets, and +/// the thread-pool wait on it (0 until registered) +struct FenceWait { + own: *mut c_void, + title: *mut c_void, + wait: AtomicUsize, +} + +unsafe extern "system" fn fence_wait_fired(ctx: *mut c_void, _timed_out: bool) { + use windows_sys::Win32::System::Threading::{SetEvent, UnregisterWaitEx}; + let w = ctx as *mut FenceWait; + super::sparse::settle_readbacks_try(); + SetEvent((*w).title); + let mut wh = (*w).wait.load(Ordering::Acquire); + while wh == 0 { + std::hint::spin_loop(); + wh = (*w).wait.load(Ordering::Acquire); + } + // no completion event: the registration goes once this callback returns + UnregisterWaitEx(wh as *mut c_void, std::ptr::null_mut()); + windows_sys::Win32::Foundation::CloseHandle((*w).own); + drop(Box::from_raw(w)); +} + +/// Fence::SetEventOnCompletion. Once copies back land asynchronously, the title's event is set +/// after the fence is reached and the copies back it covers landed: the fence sets an event of +/// XCL's own, and a thread-pool wait on that settles them and sets the title's. A null event +/// (a blocking wait) settles them after it. +unsafe extern "system" fn fence_set_event_on_completion(this: *mut c_void, value: u64, event: *mut c_void) -> HRESULT { + use windows_sys::Win32::System::Threading::{CreateEventW, RegisterWaitForSingleObject, UnregisterWaitEx, INFINITE, WT_EXECUTEONLYONCE}; + let f: unsafe extern "system" fn(*mut c_void, u64, *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12Fence", "SetEventOnCompletion"))); + if event.is_null() || !super::sparse::readbacks_async() { + let hr = { + let _t = crate::hle::api_cost::time_if( + event.is_null() && super::look_stats::deep() && !super::title_textures::is_own_work() && !super::present::presenting(), + crate::hle::api_cost::Call::FenceWait, + ); + f(this, value, event) + }; + if event.is_null() { + super::sparse::settle_readbacks_try(); + } + return hr; + } + let own = CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()); + if own.is_null() { + return f(this, value, event); + } + let w = Box::into_raw(Box::new(FenceWait { own, title: event, wait: AtomicUsize::new(0) })); + let mut wh = std::ptr::null_mut(); + if RegisterWaitForSingleObject(&mut wh, own, Some(fence_wait_fired), w as *const c_void, INFINITE, WT_EXECUTEONLYONCE) == 0 { + windows_sys::Win32::Foundation::CloseHandle(own); + drop(Box::from_raw(w)); + return f(this, value, event); + } + (*w).wait.store(wh as usize, Ordering::Release); + let hr = f(this, value, own); + if hr < 0 { + // the event will not be set: take the wait back (waiting for a running callback) + if UnregisterWaitEx(wh, windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE) != 0 { + windows_sys::Win32::Foundation::CloseHandle(own); + drop(Box::from_raw(w)); + } + } + hr } +/// Fence::Signal (CPU) unsafe extern "system" fn fence_signal(this: *mut c_void, value: u64) -> HRESULT { - let f: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, slot!(this, "Signal"))); + let f: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12Fence", "Signal"))); + // (work that waits for it may use memory committed since it was submitted) + super::sparse::send_pending(); let hr = f(this, value); super::fence_x::note_cpu_signal(this as usize); hr @@ -9938,7 +11502,7 @@ unsafe extern "system" fn fence_signal(this: *mut c_void, value: u64) -> HRESULT unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lists: *const *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); - let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ExecuteCommandLists"))); + let f: F = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12CommandQueue", "ExecuteCommandLists"))); // Internal XCL submits (`sparse` uploads/readbacks, `title_textures` uploads, tile zeroing) // run inside `own_work()` — sometimes while holding internal locks (`sparse::STATE`, // `vram::PAGES`). Forwarding them through the native slot, in the queue's ordered turn, skips @@ -9949,12 +11513,18 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis stop_if_device_removed(); return; } + super::capture::submit(this, std::slice::from_raw_parts(lists, n as usize)); crate::stall::note_submitter(); // from here to the end: XCL's uploads and tile mappings before the lists, then the driver's // own work in the submission. Where that takes long, it is not the title's time // (`pso_async::title_held`) let _in_pc = super::pso_async::pc_call(); + // (not while a stop for a driver error is being handled: `watch`) + super::watch::wait_while_held(); + let submit_t0 = std::time::Instant::now(); let mut preparation_stall = crate::stall::span(crate::stall::StallKind::SubmitPreparation); + // (the dispatches title lists put off to the submit are recorded in the loop below, before + // `prepare_title_submission`: the GPU-view tiles they ask for are mapped by its refresh) let title_lists = std::slice::from_raw_parts(lists, n as usize); // console-shaped lists run as the PC lists they were translated into (split title lists expand // into all of their recorded PC segments in exact chronological order) @@ -9977,8 +11547,11 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis return; } // textures in title memory the CPU wrote since: uploaded again first - prepare_title_submission(this); + prepare_title_submission(this, title_lists); super::list_x::note_queue_for_lists(this as usize, &mapped); + super::gpu_profile::note_queue(this); + let t_exec = std::time::Instant::now(); + super::submit_cost::call(t_exec - submit_t0); let plan = super::list_x::submission_plan(&mapped); drop(preparation_stall); let mut chunks = 0usize; @@ -9996,35 +11569,55 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis chunk.has_native_generations(), chunk.native_generations(), || { - let _ = super::alloc_pool::note_resubmits(this, lists); + // a list still on the GPU from its previous submit: that one first (the PC does + // not take a list again before then) + let t = std::time::Instant::now(); + if super::alloc_pool::note_resubmits(this, lists) > 0 { + super::alloc_pool::wait_for_previous_submits(lists); + } + super::submit_cost::previous(t.elapsed()); }, || { - let started = gpu_timing_on().then(std::time::Instant::now); - f(this, lists.len() as u32, lists.as_ptr()); - if let Some(started) = started { - note_submission_timing(started.elapsed(), lists.len(), this); + let started = std::time::Instant::now(); + { + let _in_driver = super::watch::in_driver(super::watch::Call::Execute); + f(this, lists.len() as u32, lists.as_ptr()); + } + let took = started.elapsed(); + super::submit_cost::driver(took); + if gpu_timing_on() { + note_submission_timing(took, lists.len(), this); } }, ) { return (false, None); } + super::gpu_times::executed(this, lists); chunks += 1; submitted.extend_from_slice(lists); super::list_x::copy_scratch_submitted(this, lists); - (true, chunk.submit_effects(this)) + let effects = chunk.submit_effects(this); + super::list_x::note_submitted(this); + (true, effects) }) }); + let t_end = std::time::Instant::now(); + super::submit_cost::exec(t_end - t_exec); super::alloc_pool::note_execute_call(chunks); super::present::note_execute(this, &submitted); stop_if_device_removed(); + super::submit_cost::end(t_end.elapsed()); + super::submit_cost::done(submit_t0); } /// Complete correctness-critical uploads before any native title list executes. The D3D12 /// submission API is void, so returning after preparation failure would silently lose the -/// title's exact submission; an unorderable failure must end the title instead. -pub(super) unsafe fn prepare_title_submission(queue: *mut c_void) { +/// title's exact submission; an unorderable failure must end the title instead. `lists`: the +/// title's own list pointers of this submission (`title_textures::refresh_for` leaves the look +/// for CPU writes out when they were all closed before the last one began). +pub(super) unsafe fn prepare_title_submission(queue: *mut c_void, lists: &[*mut c_void]) { use super::sparse::PreparationOutcome; - let outcome = super::title_textures::refresh(queue); + let outcome = super::title_textures::refresh_for(queue, lists); if outcome == PreparationOutcome::Ready { return; } @@ -10110,6 +11703,127 @@ unsafe fn report_dred_lists(head: *const D3D12_AUTO_BREADCRUMB_NODE, mut report: } } +/// devices opened (one a process) +#[cfg(test)] +static OPENED: AtomicUsize = AtomicUsize::new(0); + +#[cfg(test)] +mod init_tests { + use super::*; + + /// Threads that ask at once share one device (each had made one and opened the memory windows + /// for it: GPU work on the one with the other's window addresses hung the GPU). + #[test] + fn threads_that_ask_at_once_get_one_device() { + let all = std::sync::Barrier::new(4); + std::thread::scope(|s| { + for _ in 0..4 { + s.spawn(|| { + all.wait(); + let _ = init(); + }); + } + }); + assert!(OPENED.load(Ordering::Relaxed) <= 1, "{} devices were opened", OPENED.load(Ordering::Relaxed)); + } + + /// Each window of the widest layout keeps its GPU address for `uma_window_va`: with 8 places, + /// windows 8..15 had none, and their addresses went to the PC as they were. + #[test] + fn every_window_of_sixteen_has_a_place_for_its_gpu_address() { + assert_eq!(UMA_WINDOW_VAS.len(), crate::gpu::uma::MAX_HEAP_WINDOWS); + } +} + +#[cfg(test)] +mod release_tests { + use super::*; + + /// The last Release of a resource drops what XCL keeps by its address while the object is + /// still alive: once it is gone, another thread can make a resource at that address, whose + /// entries the removals would strip. (Run in a process of its own with `XCL_LATE_RELEASE=0`, + /// where the Release in `res_release` is the one that ends the object; with late releases on, + /// `late_release` ends it later.) + #[test] + fn the_last_release_drops_entries_before_the_object_goes() { + const CHILD: &str = "XCL_TEST_LAST_RELEASE_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::real::release_tests::the_last_release_drops_entries_before_the_object_goes", "--nocapture"]) + .env(CHILD, "1") + .env("XCL_LATE_RELEASE", "0") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + assert!(!super::super::late_release::enabled()); + #[repr(C)] + struct Fake { + vt: *const usize, + refs: AtomicUsize, + } + // whether the entry was still there when the count reached 0 + static ENTRY_AT_END: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(-1); + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + (*(this as *const Fake)).refs.fetch_add(1, Ordering::SeqCst) as u32 + 1 + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let n = (*(this as *const Fake)).refs.fetch_sub(1, Ordering::SeqCst) as u32 - 1; + if n == 0 { + ENTRY_AT_END.store(buffer_delta(this as usize) as i32, Ordering::SeqCst); + } + n + } + let mut orig = [0usize; 12]; + orig[1] = add_ref as usize; + orig[2] = release as usize; + let mut ext = vec![0usize; 13]; + ext[0] = orig.as_ptr() as usize; + ext[1..].copy_from_slice(&orig); + let fake = Box::new(Fake { vt: unsafe { ext.as_ptr().add(1) }, refs: AtomicUsize::new(2) }); + let this = &*fake as *const Fake as *mut c_void; + BUFFER_DELTA.lock().unwrap().get_or_insert_with(HashMap::new).insert(this as usize, 0x40); + unsafe { + assert_eq!(res_release(this), 1, "not the last"); + assert_eq!(buffer_delta(this as usize), 0x40, "kept while another reference is held"); + assert_eq!(res_release(this), 0); + } + assert_eq!(fake.refs.load(Ordering::SeqCst), 0); + assert_eq!(ENTRY_AT_END.load(Ordering::SeqCst), 0, "the entry went before the object"); + } +} + +#[cfg(test)] +mod own_program_tests { + use super::*; + + /// A program the driver refuses: a title's becomes one that does nothing, so the title goes on; + /// XCL's own gets the refusal (its user has another way). + #[test] + fn a_refused_program_of_xcls_own_is_refused() { + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + unsafe { + let raw = device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw).unwrap(); + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).unwrap(); + let ser = ser.unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())).unwrap(); + let no_program = [0x5Au8; 64]; + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&rs), CS: bytecode(&no_program), ..Default::default() }; + let made = super::super::title_textures::own_work(|| dev.CreateComputePipelineState::(&desc).is_ok()); + assert!(!made, "XCL's own program that is none was taken"); + let made = super::super::title_textures::own_work(|| dev.CreateRootSignature::(0, &no_program).is_ok()); + assert!(!made, "XCL's own root signature that is none was taken"); + assert!(dev.CreateComputePipelineState::(&desc).is_ok(), "a title's gets a stand-in"); + } + } +} + #[cfg(test)] mod submission_timing_tests { use super::*; @@ -10221,6 +11935,14 @@ mod submission_timing_tests { mod dred_tests { use super::*; + #[test] + fn video_memory_is_over_its_budget_only_past_a_known_one() { + assert_eq!(over_video_budget(30 << 30, 28 << 30), Some(2 << 30)); + assert_eq!(over_video_budget(28 << 30, 28 << 30), None); + assert_eq!(over_video_budget(1 << 30, 28 << 30), None); + assert_eq!(over_video_budget(30 << 30, 0), None, "no budget known (the query failed)"); + } + #[test] fn a_late_partially_executed_list_is_reported_before_unstarted_lists() { let progress = [0u32, 1, 2]; @@ -10261,6 +11983,12 @@ pub fn log_device_removed() { crate::xlog_error!("system commit at the removal: {} of {} MB ({} MB left)", commit >> 20, limit >> 20, limit.saturating_sub(commit) >> 20); } unsafe { + // (DRED 1.2: 3 hung, 6 fault, 7 page fault; 0 when the removal did not come from work + // the GPU was doing – then there is no page fault and there are no breadcrumbs either) + match dev.cast::() { + Ok(d) => crate::xlog_error!("DRED device state: {}", d.GetDeviceState().0), + Err(e) => crate::xlog_error!("DRED device state: not available ({:#x})", e.code().0 as u32), + } let Ok(dred) = dev.cast::() else { return }; if let Ok(pf) = dred.GetPageFaultAllocationOutput() { let names = |mut n: *const D3D12_DRED_ALLOCATION_NODE| { @@ -10277,7 +12005,13 @@ pub fn log_device_removed() { let window = uma_window_vas().iter().position(|&w| va >= w && va < w + 0x1_0000_0000).map(|k| format!(" = window {k} + {:#x}", va - uma_window_vas()[k])).unwrap_or_default(); crate::xlog_error!("DRED page fault at GPU VA {va:#x}{window}; allocations there: [{}]; recently freed: [{}]", names(pf.pHeadExistingAllocationNode), names(pf.pHeadRecentFreedAllocationNode)); } - if let Ok(bc) = dred.GetAutoBreadcrumbsOutput() { + let breadcrumbs = dred.GetAutoBreadcrumbsOutput(); + match &breadcrumbs { + Err(e) => crate::xlog_error!("DRED: no breadcrumbs ({:#x})", e.code().0 as u32), + Ok(bc) if bc.pHeadAutoBreadcrumbNode.is_null() => crate::xlog_error!("DRED: no breadcrumbs (no list was in flight)"), + Ok(_) => {} + } + if let Ok(bc) = breadcrumbs { report_dred_lists(bc.pHeadAutoBreadcrumbNode, |node, done| { let count = node.BreadcrumbCount as usize; let ops: Vec = (done.saturating_sub(3)..(done + 3).min(count)).map(|i| format!("{}{}", if i == done { ">" } else { "" }, (*node.pCommandHistory.add(i)).0)).collect(); @@ -10291,6 +12025,17 @@ pub fn log_device_removed() { bound += &format!("; bound after it: {}", after.iter().take(4).cloned().collect::>().join(", ")); } crate::xlog_error!("DRED: list {:p} on queue {:p}: {done} of {count} operations done, around: {}{bound}", list, node.pCommandQueue.as_ref().map_or(std::ptr::null_mut(), |q| q.as_raw()), ops.join(" ")); + // a list the GPU was in: what it ran last and all it had left (at most 160 + // operations), by name – the one that faulted is among those not done + if done != 0 { + let to = (done + 160).min(count); + crate::xlog_error!( + "DRED: … that list, before: {}; not done: {}{}", + super::dred::ops(key, &history, done.saturating_sub(16), done), + super::dred::ops(key, &history, done, to), + if to < count { format!(" … {} more", count - to) } else { String::new() } + ); + } }); } } @@ -10304,6 +12049,7 @@ pub fn stop_if_device_removed() { let Some(dev) = (unsafe { ID3D12Device::from_raw_borrowed(&raw) }) else { return }; if let Err(e) = unsafe { dev.GetDeviceRemovedReason() } { log_device_removed(); + super::watch::report("the device was removed"); let msg = format!("the D3D12 device was removed ({:#x}: {}) – the title is stopped", e.code().0 as u32, e.message()); crate::xlog_error!("{msg}"); crate::report::write_final(Some(msg)); @@ -10482,6 +12228,171 @@ mod this_first_tests { } } +#[cfg(test)] +mod descriptor_heap_tests { + use super::*; + + /// A device on the software adapter, adopted as a title's is. + fn warp_device() -> Option { + let mut dev: Option = None; + unsafe { + let warp = CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()).ok()?; + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).ok()?; + adopt(dev.as_ref()?.as_raw(), Kind::Device); + } + dev + } + + /// A shader-visible console sampler heap of 128 slots (a retail title's) made through device + /// #14: its PC heap holds a sampler at every index a translated shader forms (S# word 3 & + /// 0x7FF), and each of them, 128 to 2047 too, is the zero sampler slot 0 is. On WARP. + #[test] + fn a_shader_visible_sampler_heap_has_the_zero_sampler_at_every_index() { + let Some(dev) = warp_device() else { return crate::gpu::recomp::runner::skip_test("no WARP device") }; + let title = [D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32, 128, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32, 0]; + let riid = &ID3D12DescriptorHeap::IID as *const windows::core::GUID as *const GUID; + unsafe { + let mut p = std::ptr::null_mut(); + let hr = dev_create_descriptor_heap_x(dev.as_raw(), &title, riid, &mut p); + assert!(hr >= 0 && !p.is_null(), "{hr:#x}"); + let heap = ID3D12DescriptorHeap::from_raw(p); + assert_eq!(heap.GetDesc().NumDescriptors, 2048, "the PC heap"); + let start = heap.GetCPUDescriptorHandleForHeapStart().ptr; + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize; + let at = |k: usize| std::slice::from_raw_parts((start + k * inc) as *const u8, inc); + assert!(at(0).iter().any(|&b| b != 0), "the zero sampler is not zero bytes on WARP"); + for k in 1..2048 { + assert_eq!(at(k), at(0), "PC sampler {k}"); + } + } + } + + /// Descriptor heap #8 GetDesc of a console heap, called the C++ way and the C way, answers + /// what the title made it with: a shader-visible sampler heap of 128 made through device #14 + /// (its PC heap holds 2 048), and a view heap of 64 slots of the console type 4 (its PC heap: + /// 128 descriptors of type 0). Another heap answers the PC description, XCL's own call the PC + /// one always, and a released heap is forgotten. On WARP. + #[test] + fn a_console_heap_describes_itself_as_the_title_made_it() { + assert!(console_slots(Kind::DescriptorHeap).contains(&(8, heap_get_desc_x as usize)), "the title's #8"); + let Some(dev) = warp_device() else { return crate::gpu::recomp::runner::skip_test("no WARP device") }; + let get = |a: *mut c_void, b: *mut c_void| unsafe { heap_get_desc_x(a, b) }; + // (the C++ way, the C way), each with the pointer it returned + let both = |p: *mut c_void| { + let (mut x, mut y) = ([0u32; 4], [0u32; 4]); + let (px, py) = (x.as_mut_ptr() as *mut c_void, y.as_mut_ptr() as *mut c_void); + assert_eq!(get(p, px) as *mut c_void, px); + assert_eq!(get(py, p) as *mut c_void, py); + (x, y) + }; + let sampler = [D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32, 128, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32, 0]; + let riid = &ID3D12DescriptorHeap::IID as *const windows::core::GUID as *const GUID; + unsafe { + let mut p = std::ptr::null_mut(); + let hr = dev_create_descriptor_heap_x(dev.as_raw(), &sampler, riid, &mut p); + assert!(hr >= 0 && !p.is_null(), "{hr:#x}"); + let heap = ID3D12DescriptorHeap::from_raw(p); + assert_eq!(both(p), (sampler, sampler), "the sampler heap"); + assert_eq!(heap.GetDesc().NumDescriptors, 2048, "XCL's own call"); + drop(heap); + assert!(console_heap_desc(p as usize).is_none(), "released"); + + // a view heap made the PC way, then known as a console heap + let pc = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 128, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0 }; + let heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&pc).expect("a view heap"); + let p = heap.as_raw(); + assert!(is_adopted(p)); + let d = heap.GetDesc(); + let own = [d.Type.0 as u32, d.NumDescriptors, d.Flags.0 as u32, d.NodeMask]; + assert_eq!(own[..3], [0, 128, 0]); + assert_eq!(both(p), (own, own), "not a console heap: the PC description"); + let view = [XBOX_EXTRA_CBV_SRV_UAV, 64, 0, 0]; + CONSOLE_HEAP_DESCS.lock().unwrap().push((p as usize, view)); + assert_eq!(both(p), (view, view), "the view heap"); + assert_eq!(heap.GetDesc().NumDescriptors, 128, "XCL's own call"); + drop(heap); + assert!(console_heap_desc(p as usize).is_none(), "released"); + } + } + + /// A view of a texture in a CPU-only console heap, the texture destroyed (its view in the + /// shared heap made the null view), then the slot copied into a shader-visible heap, as from + /// a stale material table: the title's own heap still holds the destroyed texture's view, but + /// the copy in the shared heap is the null view and is recorded so (`console_heap::GONE`), as + /// is a copy of that copy. On WARP, in a process of its own (the shared heap is the process's). + #[test] + fn a_copy_of_a_destroyed_resources_view_is_the_null_view() { + const CHILD: &str = "XCL_TEST_GONE_VIEW_COPY_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::real::descriptor_heap_tests::a_copy_of_a_destroyed_resources_view_is_the_null_view", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + use super::super::console_heap::{in_global, names_of, slot, start, GONE, SLOT}; + let Some(dev) = warp_device() else { return crate::gpu::recomp::runner::skip_test("no WARP device") }; + if crate::gpu::uma::get().is_none() { + return crate::gpu::recomp::runner::skip_test("no UMA"); + } + let riid = &ID3D12DescriptorHeap::IID as *const windows::core::GUID as *const GUID; + unsafe { + let heap = |flags: D3D12_DESCRIPTOR_HEAP_FLAGS| { + let d = [D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32, 4, flags.0 as u32, 0]; + let mut p = std::ptr::null_mut(); + let hr = dev_create_descriptor_heap_x(dev.as_raw(), &d, riid, &mut p); + assert!(hr >= 0 && !p.is_null(), "{hr:#x}"); + ID3D12DescriptorHeap::from_raw(p) + }; + let (cpu_only, visible) = (heap(D3D12_DESCRIPTOR_HEAP_FLAG_NONE), heap(D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)); + assert!(in_global(cpu_only.as_raw() as usize) && in_global(visible.as_raw() as usize), "both heaps in the shared heap"); + // slot 0 of the CPU-only heap, slots 0 and 1 of the shader-visible one + let (a, b) = (start(cpu_only.as_raw() as usize).unwrap(), start(visible.as_raw() as usize).unwrap()); + let c = b + SLOT as u64; + let props = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 4, + Height: 4, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + let mut tex: Option = None; + dev.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut tex).expect("a texture"); + let tex = tex.unwrap(); + let view = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: desc.Format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() } }, + }; + dev_create_srv_x(dev.as_raw(), tex.as_raw(), &view, a); + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let bytes = |at: u64| std::slice::from_raw_parts(at as *const u8, inc).to_vec(); + let (sa, sb, sc) = (slot(a).unwrap(), slot(b).unwrap(), slot(c).unwrap()); + let texture_view = bytes(sa.pc_srv); + assert_eq!(bytes(sa.shared_srv), texture_view, "the view in the shared heap"); + assert_eq!(names_of(&sa).0, tex.as_raw() as usize); + resource_ending(tex.as_raw() as usize); + let null = bytes(sa.shared_srv); + assert_ne!(null, texture_view, "the texture's view in the shared heap is the null view now"); + assert_eq!(names_of(&sa).0, GONE); + assert_eq!(bytes(sa.pc_srv), texture_view, "the title's heap keeps the destroyed texture's view"); + dev_copy_descriptors_simple_x(dev.as_raw(), 1, b, a, XBOX_EXTRA_CBV_SRV_UAV); + assert_eq!(bytes(sb.pc_srv), texture_view, "the title's heap: a copy of what it held"); + assert_eq!(bytes(sb.shared_srv), null, "the copy in the shared heap: the null view"); + assert_eq!(names_of(&sb).0, GONE, "recorded as a destroyed resource's null view"); + dev_copy_descriptors_simple_x(dev.as_raw(), 1, c, b, XBOX_EXTRA_CBV_SRV_UAV); + assert_eq!((bytes(sc.shared_srv), names_of(&sc).0), (null, GONE), "a copy of the copy"); + } + } +} + #[cfg(test)] mod cache_report_tests { use super::*; @@ -10847,10 +12758,64 @@ mod queue_tests { } } + /// The queue's page-mapping method records the pages of a GPU view it names and returns + /// S_OK; a call it refuses records nothing and returns S_OK too. XCL_PAGE_MAPPINGS=0, and + /// only that, turns it off. + #[test] + fn the_queue_page_mapping_method_records_and_can_be_switched_off() { + use crate::hle::kernelx::mirrors::{self, Shows, PAGE}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + assert!(mirrors::page_mappings_on(None) && mirrors::page_mappings_on(Some("1"))); + assert!(!mirrors::page_mappings_on(Some("0"))); + unsafe { + // a pair of views of a size of the test's own (no other test's views pair with these) + let size = 197 * PAGE; + let cpu = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE, PAGE_READWRITE) as usize; + let gpu = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE, PAGE_READWRITE) as usize; + assert!(cpu != 0 && gpu != 0); + mirrors::reserved(cpu, size, 0x2040_2000, 0x04); + assert!(mirrors::reserved(gpu, size, 0x2040_2000, 0x801)); + // (no page of the title is mapped in this pool: a pool page named shows nothing) + let pool = cpu + 100 * PAGE; + let calls = mirrors::calls(); + // pool page 0 at view page 1, view page 2 unmapped (batch: destination, ranges, pointer) + let ranges: [[u32; 3]; 2] = [[0, 0, 1], [2, 0, 1]]; + let batch = [(gpu + PAGE) as u64, 2, ranges.as_ptr() as u64]; + assert_eq!(q_copy_page_mappings(1, batch.as_ptr() as usize, pool, 4), S_OK); + assert!(mirrors::calls() > calls, "the call is recorded"); + assert_eq!(mirrors::shows(gpu), Shows::Same(cpu), "a page not named shows its CPU view"); + assert_eq!(mirrors::shows(gpu + PAGE + 0x10), Shows::Nothing); + assert_eq!(mirrors::shows(gpu + 2 * PAGE), Shows::Nothing); + // a range of an unknown kind after a good one: nothing of the call is recorded + let ranges: [[u32; 3]; 2] = [[2, 0, 1], [7, 0, 1]]; + let batch = [(gpu + 3 * PAGE) as u64, 2, ranges.as_ptr() as u64]; + assert_eq!(q_copy_page_mappings(1, batch.as_ptr() as usize, pool, 4), S_OK); + assert_eq!(mirrors::shows(gpu + 3 * PAGE), Shows::Same(cpu + 3 * PAGE), "a refused call changes nothing"); + mirrors::released(cpu); + assert_eq!(mirrors::shows(gpu + PAGE), Shows::NoView); + VirtualFree(cpu as *mut c_void, 0, MEM_RELEASE); + VirtualFree(gpu as *mut c_void, 0, MEM_RELEASE); + } + } + + /// The line of the queue's page mappings says each count in its place. + #[test] + fn the_page_mapping_line() { + let t = crate::hle::kernelx::mirrors::Mapped { mapped: 30, unmapped: 4, empty: 0, elsewhere: 2 }; + assert_eq!( + page_mapping_line(8, t, 0x7200_0000_0000, 99776, 5, 6, [7, 8, 9, 10], [11, 12]), + "D3D12.X: queue CopyPageMappingsBatchX: 8 calls; GPU-view pages so far: 30 mapped, 4 unmapped, 0 named a pool page with no page mapped there, 2 elsewhere ignored (pool 0x720000000000, 99776 pages of 64 KiB); 5 moved with their physical page; textures: 6 read again for a mapping changed under them, pages of their uploads: 7 where the mapping put the page, 8 at the CPU view's same offset, 9 at that offset never mapped, 10 unmapped; tiles: 11 shown anew, 12 followed their page" + ); + } + + /// The newer layout's DispatchMesh (#129) is the older layout's #127, where the two-pass + /// DispatchMesh is hooked; #128 is another method. #[test] fn newer_layout_maps_dispatch_mesh_to_slot_129_not_128() { assert!(NEWER_LIST_SLOTS.contains(&(129, 127)), "DispatchMesh must map to newer slot #129"); assert!(!NEWER_LIST_SLOTS.iter().any(|&(newer, _)| newer == 128), "newer slot #128 must not map to DispatchMesh"); + let handler = console_slots(Kind::CommandList).into_iter().find(|e| e.0 == 127).map(|e| e.1); + assert_eq!(handler, Some(super::super::bind::dispatch_mesh as usize), "the older slot runs DispatchMesh"); } #[test] @@ -11144,6 +13109,91 @@ mod console_format_query_tests { } } +#[cfg(test)] +mod gpu_view_tests { + use super::*; + use crate::gpu::uma::{Uma, MAX_HEAP_WINDOWS, VIEW_WINDOWS, WINDOW}; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_UNKNOWN}; + + /// The 16-window layout of its own (the process's `uma::get()` is whatever the environment + /// chose) and a GPU view of `bytes` in its view windows. + fn sixteen_with_view(bytes: usize) -> (Uma, usize) { + let u = Uma::for_runtime_windows(16 << 20, 512 << 20, MAX_HEAP_WINDOWS).expect("16-window aperture"); + let g = u.view_reserve(bytes).expect("a GPU view"); + (u, g) + } + + /// A buffer view by address (device #70 / #71) covers exactly its elements: from element + /// `first` on, `n` of them – 4-byte words of a raw view, `stride` bytes of a structured one, + /// the format's bytes of a typed one. That range, no more, is what asks for a GPU view's tiles. + #[test] + fn a_view_by_address_covers_its_elements() { + let va = 0x7_0000_1000u64; + let (w, at, len) = buffer_words_at(va, DXGI_FORMAT_R32_TYPELESS, 3, 10, 0, true); + assert_eq!((at, len), (va + 12, 40), "raw: 4-byte words"); + assert_eq!((w[0], w[1] & 0xFFFF, w[2]), ((va + 12) as u32, ((va + 12) >> 32) as u32, 40)); + let (w, at, len) = buffer_words_at(va, DXGI_FORMAT_UNKNOWN, 2, 5, 24, false); + assert_eq!((at, len), (va + 48, 120), "structured: 24-byte elements"); + assert_eq!((w[0], w[1] >> 16, w[2]), ((va + 48) as u32, 24, 5)); + let (w, at, len) = buffer_words_at(va, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 4, 0, false); + assert_eq!((at, len), (va + 16, 64), "typed: the format's 16 bytes"); + assert_eq!((w[0], w[1] >> 16, w[2]), ((va + 16) as u32, 16, 4)); + let (_, at, len) = buffer_words_at(va, DXGI_FORMAT_R32_TYPELESS, 0, 0, 0, true); + assert_eq!((at, len), (va, 0), "an empty view asks for nothing"); + } + + /// A constant buffer view in a GPU view carries its address: shaders read the view window + /// there (its tiles show the CPU view). It was left empty: the address is no CPU memory. + #[test] + fn a_constant_buffer_view_in_a_gpu_view_carries_its_address() { + let (u, g) = sixteen_with_view(1 << 20); + let va = (g + 0x2_0100) as u64; + let w = cbv_at(Some(&u), va, 256).expect("a CBV in a GPU view reaches the shaders"); + assert_eq!(w, crate::gpu::desc::cbv_words(va, 256)); + assert_eq!((w[0], w[1] & 0xFFFF, w[2]), (va as u32, (va >> 32) as u32, 16), "the address and 16 float4 rows"); + // the CPU's unified memory as before; past the view windows, and without unified memory, + // nothing + let sparse = (u.base() + 0x10_0000) as u64; + assert_eq!(cbv_at(Some(&u), sparse, 64), Some(crate::gpu::desc::cbv_words(sparse, 64))); + let first_view = (0..MAX_HEAP_WINDOWS).find(|&k| u.is_view_window(k)).unwrap(); + let after = (u.base() + (first_view + VIEW_WINDOWS) * WINDOW + 0x100) as u64; + assert_eq!(cbv_at(Some(&u), after, 64), None, "an empty window"); + assert_eq!(cbv_at(None, va, 256), None); + // the 4-window layout has no view windows: the same address is nothing there + let four = Uma::for_runtime(16 << 20).expect("4-window aperture"); + assert_eq!(cbv_at(Some(&four), va, 256), None); + assert_eq!(u.view_release(g), Some(1 << 20)); + } + + /// A buffer the title places in a GPU view goes over the view window's tiles, as one in a + /// sparse window does, and may run on into the next view window (the view is one range across + /// them); not into a window that is no view. It became a resource of its own that stayed zero. + #[test] + fn a_buffer_placed_in_a_gpu_view_goes_over_its_tiles() { + let (u, g) = sixteen_with_view(2 * WINDOW); + let k = u.window_of(g).unwrap(); + assert!(u.is_view_window(k) && u.is_view_window(k + 1)); + assert_eq!(title_buffer_window(&u, g + 0x3_0000, 0x1000), Some((k, true))); + assert_eq!(title_buffer_window(&u, g + WINDOW - 0x1_0000, 0x2_0000), Some((k, true)), "across two view windows"); + assert_eq!(title_buffer_window(&u, g + WINDOW + 0x10, 0x100), Some((k + 1, true))); + assert_eq!(title_buffer_window(&u, g, 0), None, "no bytes"); + // the last view window runs into an empty one + let last = (0..MAX_HEAP_WINDOWS).rfind(|&j| u.is_view_window(j)).unwrap(); + let end = u.base() + (last + 1) * WINDOW; + assert!(!u.is_view_window(last + 1)); + assert_eq!(title_buffer_window(&u, end - 0x1_0000, 0x2_0000), None, "past the view windows"); + // sparse and coherent windows as before: whole in their window + assert_eq!(title_buffer_window(&u, u.base() + 0x1_0000, 0x100), Some((0, true))); + assert_eq!(title_buffer_window(&u, u.base() + WINDOW - 0x1_0000, 0x2_0000), None, "across a sparse window's end"); + let coh = u.committed_window().unwrap(); + let (c, c_len) = u.window(coh); + assert_eq!(title_buffer_window(&u, c + 0x1_0000, 0x100), Some((coh, false))); + assert_eq!(title_buffer_window(&u, c + c_len - 0x100, 0x200), None); + assert_eq!(title_buffer_window(&u, end + 0x1_0000, 0x100), None, "an empty window"); + assert_eq!(u.view_release(g), Some(2 * WINDOW)); + } +} + #[cfg(test)] mod map_tests { use super::*; @@ -11637,16 +13687,25 @@ mod mesh_stream_tests { panic!("CreateComputePipelineState must not be called when mesh PSO out-pointer is null"); } + /// (`driver_identity` asks the device for its adapter: no adapter has LUID 0, so no identity) + unsafe extern "system" fn fake_adapter_luid(_: *mut c_void, luid: *mut windows::Win32::Foundation::LUID) { + *luid = Default::default(); + } + #[test] fn finish_two_pass_rejects_null_mesh_out_pointer() { let iface = layout::find("ID3D12Device2").expect("ID3D12Device2 layout"); let pso_slot = layout::slot(iface, "CreatePipelineState").expect("CreatePipelineState slot"); let cs_slot = layout::slot(iface, "CreateComputePipelineState").expect("CreateComputePipelineState slot"); + let luid_slot = layout::slot(iface, "GetAdapterLuid").expect("GetAdapterLuid slot"); let mut pc = vec![0usize; iface.methods.len()]; pc[pso_slot] = fake_create_pso_null_ok as usize; pc[cs_slot] = fake_create_compute_unexpected as usize; - let ext_buf = [pc.as_ptr() as usize, 0]; + // the object's own table (after the PC table's address): what a direct COM call reads + let mut ext_buf = vec![0usize; 1 + iface.methods.len()]; + ext_buf[0] = pc.as_ptr() as usize; + ext_buf[1 + luid_slot] = fake_adapter_luid as usize; let ext_vtbl = ext_buf.as_ptr() as usize + std::mem::size_of::(); let mut fake_dev = [ext_vtbl]; let this = fake_dev.as_mut_ptr() as *mut c_void; @@ -12238,6 +14297,392 @@ void main() { } } +#[cfg(test)] +mod depth_uav_twin_tests { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::*; + + /// Runs the test `name` of this module again in a child process with `XCL_DEPTH_UAV_TWIN=1` + /// and unified memory (the shared heap and the switch are the process's). True: this is the + /// child, which does the work. + fn in_child(name: &str) -> bool { + const CHILD: &str = "XCL_TEST_DEPTH_UAV_TWIN_CHILD"; + if std::env::var_os(CHILD).is_some() { + return true; + } + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &format!("hle::d3d12x::real::depth_uav_twin_tests::{name}"), "--nocapture"]) + .env(CHILD, "1") + .env("XCL_DEPTH_UAV_TWIN", "1") + .env("XCL_UMA_MB", "64") + .env("XCL_COHERENT_MB", "64") + .output() + .unwrap(); + assert!( + output.status.success(), + "child failed ({:?}):\nstdout:\n{}\nstderr:\n{}", + output.status, + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + print!("{}", String::from_utf8_lossy(&output.stdout)); + // a skip in the child is a skip of this test: its line goes where the suite's skips go + use std::io::Write; + for l in String::from_utf8_lossy(&output.stderr).lines().filter(|l| l.starts_with("SKIPPED")) { + let _ = writeln!(std::io::stderr(), "{l}"); + } + false + } + + /// An adopted WARP device with a DIRECT queue, allocator and list of the PC's, a DSV heap of + /// the PC's, a console view heap of 4 slots (in the shared heap), and a 16x16 console + /// D24_UNORM_S8_UINT with ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS made through + /// CreateCommittedResource, with a DSV. None: skipped. + struct Fixture { + dev: ID3D12Device, + queue: ID3D12CommandQueue, + _alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + dsv_heap: ID3D12DescriptorHeap, + dsv: u64, + heap: ID3D12DescriptorHeap, + base: u64, + depth: ID3D12Resource, + } + + impl Fixture { + unsafe fn new() -> Option { + use super::super::{console_heap, depth_uav}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + if crate::gpu::uma::get().is_none() { + crate::gpu::recomp::runner::skip_test("no unified memory"); + return None; + } + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no WARP device"); + return None; + }; + let Ok(warp) = factory.EnumWarpAdapter::() else { + crate::gpu::recomp::runner::skip_test("no WARP device"); + return None; + }; + let mut dev: Option = None; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no WARP device"); + return None; + } + let dev = dev.unwrap(); + // the DSV heap and the list are the PC's; then the device as a title's + let dsv_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, NumDescriptors: 1, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0 }) + .unwrap(); + let dsv = dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr as u64; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let d = dev.as_raw(); + adopt(d, Kind::Device); + + // a console view heap of 4 slots (in the shared heap) + let mut heap_raw = std::ptr::null_mut(); + let hr = dev_create_descriptor_heap_x(d, &[0, 4, 1, 0],&ID3D12DescriptorHeap::IID as *const _ as *const GUID, &mut heap_raw); + assert!(hr >= 0 && !heap_raw.is_null(), "console view heap: {hr:#x}"); + let heap = ID3D12DescriptorHeap::from_raw(heap_raw); + let base = console_heap::start(heap_raw as usize).expect("console heap start"); + + let console = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 16, + Height: 16, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_D24_UNORM_S8_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let props = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut raw = std::ptr::null_mut(); + let hr = dev_create_committed_resource_x( + d, + &props as *const _ as usize, + 0, + &console as *const _ as usize, + D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as usize, + 0, + &ID3D12Resource::IID as *const _ as *const GUID, + &mut raw, + ); + assert!(hr >= 0 && !raw.is_null(), "the depth buffer: {hr:#x}"); + let depth = ID3D12Resource::from_raw(raw); + assert!(depth_uav::kept(raw as usize), "the buffer is kept"); + + dev_create_dsv_x( + d, + raw, + &D3D12_DEPTH_STENCIL_VIEW_DESC { Format: DXGI_FORMAT_D24_UNORM_S8_UINT, ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, ..Default::default() }, + dsv, + ); + Some(Fixture { dev, queue, _alloc: alloc, list, dsv_heap, dsv, heap, base, depth }) + } + } + + fn uav(format: DXGI_FORMAT, plane: u32) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: format, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: plane } }, + } + } + + /// A stencil UAV of a console depth buffer with unordered access, made through the device + /// calls (`XCL_DEPTH_UAV_TWIN=1`, the shared view heap): the slot's UAV and its companion SRV + /// name the buffer's R8 twin and the T# reads as 8-bit uint; a depth UAV stays a null view + /// with its reason; the DSV is known; the twin goes with the buffer. On WARP, in a child + /// process. + #[test] + fn gpu_a_stencil_uav_of_a_console_depth_buffer_is_a_view_of_its_twin() { + if !in_child("gpu_a_stencil_uav_of_a_console_depth_buffer_is_a_view_of_its_twin") { + return; + } + use super::super::{console_heap, depth_uav}; + unsafe { + let Some(f) = Fixture::new() else { return }; + let base = f.base; + let slot_cpu = |k: u64| base + k * console_heap::SLOT as u64; + let Fixture { dev, dsv_heap, dsv, heap, depth, .. } = f; + let (d, raw) = (dev.as_raw(), depth.as_raw()); + assert_eq!(depth_uav::dsv_names(dsv as usize), Some(raw as usize), "the DSV is known"); + + let (made, alive, redirected, _) = depth_uav::counts(); + dev_create_uav_checked_x(d, raw, std::ptr::null_mut(), &uav(DXGI_FORMAT_X24_TYPELESS_G8_UINT, 1), slot_cpu(0)); + dev_create_uav_checked_x(d, raw, std::ptr::null_mut(), &uav(DXGI_FORMAT_R24_UNORM_X8_TYPELESS, 0), slot_cpu(1)); + // a second stencil UAV takes the same twin + dev_create_uav_checked_x(d, raw, std::ptr::null_mut(), &uav(DXGI_FORMAT_R8_UINT, 0), slot_cpu(2)); + let (made2, alive2, redirected2, nulls) = depth_uav::counts(); + assert_eq!((made2 - made, alive2 - alive, redirected2 - redirected), (1, 1, 2), "one twin, two views of it"); + assert_eq!(nulls, ["its depth plane has no twin yet"], "the depth view is a null view, with its reason"); + + let twin = depth_uav::twin_of(raw as usize).expect("a stencil twin"); + let t = ID3D12Resource::from_raw_borrowed(&(twin as *mut c_void)).unwrap().GetDesc(); + assert_eq!((t.Format, t.Width, t.Height, t.DepthOrArraySize, t.MipLevels), (DXGI_FORMAT_R8_TYPELESS, 16, 16, 1, 1)); + assert!(t.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0); + assert_eq!(title_address(twin), None, "the twin is no title memory"); + for k in [0, 2] { + let s = console_heap::slot(slot_cpu(k)).unwrap(); + assert_ne!(s.shared_srv, 0, "slot {k} is in the shared heap"); + assert_eq!(console_heap::names_of(&s), (twin, twin), "slot {k}: SRV and UAV of the twin"); + let mut w = [0u32; 8]; + std::ptr::copy_nonoverlapping(slot_cpu(k) as *const u32, w.as_mut_ptr(), 8); + assert_eq!((w[0], (w[1] >> 20) & 0x1FF), (s.index, 5), "slot {k}: the T# of an R8_UINT image"); + } + let s = console_heap::slot(slot_cpu(1)).unwrap(); + assert_eq!(console_heap::names_of(&s).1, 0, "the depth plane's UAV is a null view"); + + drop(heap); + drop(depth); + assert!(!depth_uav::kept(raw as usize), "the buffer is forgotten at its last release"); + assert_eq!(depth_uav::counts().1, alive, "the twin goes with the buffer's Cell"); + drop(dsv_heap); + } + } + + /// A console depth buffer the title places at an address in unified memory + /// (CreatePlacedResourceX) and a stencil UAV of that memory made by address (device #71, on + /// XCL's own object there): the buffer is kept under its title address with the state it was + /// made in, and the view by address is a view of that buffer's twin. On WARP, in a child + /// process. + #[test] + fn gpu_a_stencil_uav_by_address_is_a_view_of_the_placed_buffers_twin() { + if !in_child("gpu_a_stencil_uav_by_address_is_a_view_of_the_placed_buffers_twin") { + return; + } + use super::super::{console_heap, depth_uav, device_x, vram}; + unsafe { + let Some(f) = Fixture::new() else { return }; + let d = f.dev.as_raw(); + let Some(va) = crate::gpu::uma::get().and_then(|u| u.alloc(1 << 20, 0x1_0000)) else { + crate::gpu::recomp::runner::skip_test("no unified memory for the buffer"); + return; + }; + let va = va as u64; + let console = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 16, + Height: 16, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_D24_UNORM_S8_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let rdesc = &console as *const _ as *const u8; + let mut raw = std::ptr::null_mut(); + let hr = device_x::create_placed_resource_x( + d, + va, + rdesc, + D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as u32, + std::ptr::null(), + &ID3D12Resource::IID as *const _ as *const GUID, + &mut raw, + ); + assert!(hr >= 0 && !raw.is_null(), "the placed depth buffer: {hr:#x}"); + let _placed = ID3D12Resource::from_raw(raw); + let at = vram::canonical_va(va as usize); + assert_eq!(depth_uav::made_in(raw as usize), Some((Some(D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as u32), Some(at))), "kept under its title address, made in DEPTH_WRITE"); + + // #71: { the PC's UAV desc; the GPU address @0x28 } + let mut view = [0u64; 8]; + std::ptr::write_unaligned(view.as_mut_ptr() as *mut D3D12_UNORDERED_ACCESS_VIEW_DESC, uav(DXGI_FORMAT_X24_TYPELESS_G8_UINT, 1)); + view[5] = va; + dev_create_uav_at_x(d, rdesc, view.as_ptr() as *const u8, f.base); + let twin = depth_uav::twin_of(raw as usize).expect("the placed buffer has a stencil twin"); + let s = console_heap::slot(f.base).unwrap(); + assert_eq!(console_heap::names_of(&s), (twin, twin), "the view by address names the placed buffer's twin"); + assert_eq!(depth_uav::made_in(raw as usize).unwrap().0, Some(D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as u32), "the view's own object (made in COMMON) does not change the buffer's state"); + } + } + + /// ClearUnorderedAccessViewUint of console code with the console handles of a stencil UAV + /// and the depth buffer as its resource: the PC clear goes to the twin the slot's view names, + /// and the twin reads back the value. On WARP, in a child process. + #[test] + fn gpu_clear_uav_of_a_stencil_uav_clears_the_twin() { + if !in_child("gpu_clear_uav_of_a_stencil_uav_clears_the_twin") { + return; + } + use super::super::{console_heap, depth_uav, list_x}; + unsafe { + let Some(f) = Fixture::new() else { return }; + let (d, raw) = (f.dev.as_raw(), f.depth.as_raw()); + let slot = f.base; + dev_create_uav_checked_x(d, raw, std::ptr::null_mut(), &uav(DXGI_FORMAT_X24_TYPELESS_G8_UINT, 1), slot); + let twin = depth_uav::twin_of(raw as usize).expect("a stencil twin"); + let twin = ID3D12Resource::from_raw_borrowed(&(twin as *mut c_void)).unwrap().clone(); + + // the title's call (#53) with the shared heap bound, on a stand-in of the list whose + // PC ClearUnorderedAccessViewUint (#49) notes the resource it is given and goes on to + // the list's own: what the PC call gets, not only what XCL counted + static PC_CLEAR: AtomicUsize = AtomicUsize::new(0); + static LIST: AtomicUsize = AtomicUsize::new(0); + static GOT: AtomicUsize = AtomicUsize::new(0); + type ClearUint = unsafe extern "system" fn(*mut c_void, u64, u64, usize, *const u32, u32, *const c_void); + unsafe extern "system" fn noting(_this: *mut c_void, gpu: u64, cpu: u64, res: usize, values: *const u32, n: u32, rects: *const c_void) { + GOT.store(res, Ordering::Relaxed); + let pc: ClearUint = std::mem::transmute(PC_CLEAR.load(Ordering::Relaxed)); + pc(LIST.load(Ordering::Relaxed) as *mut c_void, gpu, cpu, res, values, n, rects) + } + let l = &f.list; + l.SetDescriptorHeaps(&[console_heap::global_heap()]); + let lraw = l.as_raw(); + LIST.store(lraw as usize, Ordering::Relaxed); + PC_CLEAR.store(*(*(lraw as *const *const usize)).add(49), Ordering::Relaxed); + let mut pc_vt = [0usize; 64]; + pc_vt[49] = noting as usize; + // (`orig_fn` reads the PC table at -1 of the object's table) + let ext_vt = [pc_vt.as_ptr() as usize, 0]; + let stand_in = [ext_vt.as_ptr().add(1)]; + let (done, not_done) = depth_uav::clears(); + list_x::clear_uav_uint_x(stand_in.as_ptr() as *mut c_void, slot, slot, raw as usize, [0x5Au32; 4].as_ptr(), 0, std::ptr::null()); + let (done2, not_done2) = depth_uav::clears(); + assert_eq!((done2 - done, not_done2 - not_done), (1, 0), "the clear went to the twin"); + assert_eq!(GOT.load(Ordering::Relaxed), twin.as_raw() as usize, "the PC clear gets the twin as its resource, not the depth buffer"); + // a depth-plane UAV of the buffer is a null view: its clear is not done, nothing reaches the PC + let depth_slot = slot + console_heap::SLOT as u64; + dev_create_uav_checked_x(d, raw, std::ptr::null_mut(), &uav(DXGI_FORMAT_R24_UNORM_X8_TYPELESS, 0), depth_slot); + GOT.store(0, Ordering::Relaxed); + list_x::clear_uav_uint_x(stand_in.as_ptr() as *mut c_void, depth_slot, depth_slot, raw as usize, [0x11u32; 4].as_ptr(), 0, std::ptr::null()); + let (done3, not_done3) = depth_uav::clears(); + assert_eq!((done3 - done2, not_done3 - not_done2, GOT.load(Ordering::Relaxed)), (0, 1, 0), "a clear through the null view is not done"); + + // the twin to a readback buffer + let td = twin.GetDesc(); + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0u64; + f.dev.GetCopyableFootprints(&td, 0, 1, 0, Some(&mut fp), None, None, Some(&mut total)); + let mut rb: Option = None; + f.dev + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: total, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut rb, + ) + .expect("readback buffer"); + let rb = rb.unwrap(); + let b = [D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(twin.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + StateAfter: D3D12_RESOURCE_STATE_COPY_SOURCE, + }), + }, + }]; + l.ResourceBarrier(&b); + for b in b { + let tr = std::mem::ManuallyDrop::into_inner(b.Anonymous.Transition); + let _ = std::mem::ManuallyDrop::into_inner(tr.pResource); + } + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&twin), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + l.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + l.Close().expect("close list"); + f.queue.ExecuteCommandLists(&[Some(l.cast().unwrap())]); + let fence: ID3D12Fence = f.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + f.queue.Signal(&fence, 1).expect("signal"); + crate::gpu::fence::wait(&fence, 1, &f.dev, None, 5000).expect("the clear and the copy complete"); + + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).expect("map readback"); + let pitch = fp.Footprint.RowPitch as usize; + let rows: Vec> = (0..16).map(|y| std::slice::from_raw_parts((p as *const u8).add(fp.Offset as usize + y * pitch), 16).to_vec()).collect(); + rb.Unmap(0, None); + assert!(rows.iter().all(|r| r.iter().all(|&v| v == 0x5A)), "the twin was not cleared: {:x?}", &rows[0]); + } + } +} + +#[cfg(test)] +mod uma_heap_tests { + use super::*; + + /// A console buffer whose first fit crosses two segments of a mixed window goes to the next + /// fit, and the crossing block is given back (it stayed charged to the window). + #[test] + fn a_block_across_two_segments_is_given_back_and_the_next_fit_used() { + let u = crate::gpu::uma::Uma::with_windows(1, 4 << 20).expect("one UMA window"); + let (w0, _) = u.window(0); + let first = u.alloc(960 << 10, 0x1_0000).expect("first block") as usize; + assert_eq!(first, w0); + let used = u.used(); + let boundary = w0 + (1 << 20); + let heap_of = |p: usize| (p + (128 << 10) <= boundary || p >= boundary).then_some(()); + let (p, ()) = alloc_in_one_heap(&u, 128 << 10, heap_of).expect("a block in one segment"); + assert_eq!(p, w0 + (1088 << 10)); + assert_eq!(u.used(), used + (128 << 10)); + assert_eq!(u.alloc(64 << 10, 0x1_0000).map(|a| a as usize), Some(w0 + (960 << 10))); + assert!(alloc_in_one_heap(&u, 64 << 10, |_| None::<()>).is_none()); + assert_eq!(u.used(), used + (192 << 10)); + } +} + #[cfg(test)] mod list_release_tests { use super::*; diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 690f9e7dfc..ed17b4df3a 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -73,7 +73,13 @@ pub(crate) fn flush_indirect_used(timeout: std::time::Duration) { } } +/// (only when a count changed since the last line: called every 10 s in every run) pub(crate) fn log_counts() { + static LAST: Mutex<[u64; 7]> = Mutex::new([0; 7]); + let now = [&PROGRAMS, &PIECES, &DISPATCHES, &SLABS, &LIVE, &PEAK, &WANTED].map(|c| c.load(Ordering::Relaxed)); + if std::mem::replace(&mut *LAST.lock().unwrap(), now) == now { + return; + } let mib = |a: &AtomicU64| a.load(Ordering::Relaxed) >> 20; crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued in {} slabs; scratch {} MiB (most {}, largest dispatch {} in one slab)", PROGRAMS.load(Ordering::Relaxed), PIECES.load(Ordering::Relaxed), DISPATCHES.load(Ordering::Relaxed), SLABS.load(Ordering::Relaxed), @@ -103,8 +109,22 @@ impl PipelineBuilder { unsafe fn pipeline(&self, dxil: &[u8], iid: &GUID) -> Result { let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: self.node, Flags: self.flags, ..Default::default() }; let mut raw = std::ptr::null_mut(); - let (hr, _, _) = compute_container(self.device.as_raw(), self.create, &desc, self.signature.as_raw(), + let (hr, in_driver, _) = compute_container(self.device.as_raw(), self.create, &desc, self.signature.as_raw(), dxil, &self.samplers, self.record, iid, &mut raw, self.mode); + // (as `translated_compute_pso_once` logs a huge whole program the driver refuses) + if hr < 0 && dxil.len() >= huge_pso_bytes() { + let root = match self.mode { + ComputeBuild::IndirectChain => driver_cache::ChainRoot::IndirectCbv, + _ => driver_cache::ChainRoot::DirectConstants, + }; + crate::xlog_warn!( + "D3D12.X: the driver refused a dispatch chain's compute PSO of record {:016x} ({} B DXIL, driver cache {}) with {hr:#x} after {} ms in the driver", + self.record, + dxil.len(), + driver_cache::name_for_chain_root_node(dxil, self.flags.0, root, &self.samplers, self.node), + in_driver.as_millis() + ); + } if hr >= 0 && !raw.is_null() { Ok(ID3D12PipelineState::from_raw(raw)) } else { Err(hr) } } } @@ -161,6 +181,8 @@ struct Chain { plan: Weak, indirect: IndirectBuild, indirect_noted: AtomicBool, + /// a thread of its own builds the whole form (`whole_ready`) + whole_sent: AtomicBool, } struct IndirectChain { @@ -189,14 +211,81 @@ impl IndirectBuild { } } +/// A chain for the thread that builds its whole form (D3D12 objects are free-threaded). +struct ChainRef(Arc); +unsafe impl Send for ChainRef {} + impl Chain { - unsafe fn whole(&self) -> Result { - self.whole - .get_or_build(std::time::Instant::now(), || self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState))) - .map_err(|hr| if hr == crate::util::E_OUTOFMEMORY { "whole compute pipeline: out of memory".into() } else { format!("whole compute pipeline ({hr:#x})") }) + /// Build the whole form (or take the one built). `on_title_thread` is true only when a title + /// thread is synchronously blocked waiting for this compile (registers a long PC call). + unsafe fn whole(&self, on_title_thread: bool) -> Result { + let result = match self.whole.ready() { + Some(result) => result, + None => { + // (only when a title thread is held while this compile lasts, as in any other long PC call) + let _call = on_title_thread.then(super::super::pso_async::pc_call); + self.whole.get_or_build(std::time::Instant::now(), || self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState))) + } + }; + result.map_err(|hr| if hr == crate::util::E_OUTOFMEMORY { "whole compute pipeline: out of memory".into() } else { format!("whole compute pipeline ({hr:#x})") }) } } +type WholeJob = Box; + +/// Single persistent worker (`xcl-pso-whole`, 64 MiB stack) for building split programs' whole +/// forms off the title thread. A single worker avoids spawning an unbounded number of 64 MiB-stack +/// OS threads behind `real::huge_compile_turn` (which already serializes late giant compiles), and +/// runs each job under `pso_async::with_late_build` so it gets half commit headroom. Each job is +/// wrapped in `catch_unwind` so a panic cannot kill the worker and strand queued chains. +fn whole_worker() -> Option<&'static std::sync::mpsc::Sender> { + static TX: OnceLock>> = OnceLock::new(); + TX.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::channel::(); + std::thread::Builder::new() + .name("xcl-pso-whole".into()) + .stack_size(64 << 20) + .spawn(move || { + while let Ok(job) = rx.recv() { + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + super::super::pso_async::with_late_build(job); + })) + .is_err() + { + crate::xlog_warn!("D3D12.X: whole split-PSO worker caught a panic; continuing queued builds"); + } + } + }) + .ok() + .map(|_| tx) + }) + .as_ref() +} + +/// Clears `whole_sent` if a queued whole-form job panics or is dropped before completing normally. +struct WholeSentGuard { + job: ChainRef, + finished: bool, +} + +impl WholeSentGuard { + fn finish(mut self) { + self.finished = true; + } +} + +impl Drop for WholeSentGuard { + fn drop(&mut self) { + if !self.finished && self.job.0.whole.ready().is_none() { + self.job.0.whole_sent.store(false, Ordering::Release); + } + } +} + +fn enqueue_whole(job: WholeJob) -> bool { + whole_worker().is_some_and(|tx| tx.send(job).is_ok()) +} + static CHAINS: LazyLock>>> = LazyLock::new(Default::default); /// Shared for the process lifetime so chains with a common piece also share its driver blob. static SIGNATURES: LazyLock), ID3D12RootSignature>>> = LazyLock::new(Default::default); @@ -344,7 +433,7 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let first = pieces.next()?; let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group, whole_code: whole.to_vec(), whole: WholeBuild::new(), plan: Arc::downgrade(&plan), - indirect: IndirectBuild::new(), indirect_noted: AtomicBool::new(false) }); + indirect: IndirectBuild::new(), indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(false) }); retain_indirect_plan(plan.clone()); // Initialize the journal on this preparation worker, never on the first recording call. let _ = indirect_used(); @@ -365,7 +454,54 @@ pub(super) fn forget(pso: usize) { pub(in crate::hle::d3d12x) unsafe fn whole(pso: usize) -> Result, String> { let chain = CHAINS.lock().unwrap().get(&pso).cloned(); - chain.map(|c| c.whole()).transpose() + chain.map(|c| c.whole(true)).transpose() +} + +/// The whole form of a split program for an indirect dispatch, which runs no chain (its group +/// counts are the GPU's). +pub(in crate::hle::d3d12x) enum Whole { + /// no split program: the pipeline as it is + Plain, + Ready(ID3D12PipelineState), + /// still being built on the `xcl-pso-whole` worker: this dispatch goes without it + Late, +} + +/// `whole` where a compute pipeline's dispatches go on without it while it is built +/// (`pso_async::cs_goes_on`): the whole form, the largest program the driver compiles, is queued +/// onto the single `xcl-pso-whole` worker, once, and until it is there its dispatches are left out +/// as those of any late compute pipeline. Built in the call, a retail title's render thread stood +/// in the driver's compiler for it (1.1 MB of DXIL) and every other thread that dispatched it +/// stood behind its build: no frame for over two minutes after its first world frame. +pub(in crate::hle::d3d12x) unsafe fn whole_ready(pso: usize) -> Result { + let chain = CHAINS.lock().unwrap().get(&pso).cloned(); + let Some(chain) = chain else { return Ok(Whole::Plain) }; + if chain.whole.ready().is_some() { + return chain.whole(false).map(Whole::Ready); + } + if !super::super::pso_async::cs_goes_on() { + return chain.whole(true).map(Whole::Ready); + } + if !chain.whole_sent.swap(true, Ordering::AcqRel) { + let guard = WholeSentGuard { job: ChainRef(chain.clone()), finished: false }; + let queued = enqueue_whole(Box::new(move || { + match unsafe { guard.job.0.whole(false) } { + Ok(_) => guard.finish(), + // out of memory (`WholeBuild`): no result is kept, and the guard lets a later + // dispatch queue it again after `WHOLE_RETRY` + Err(_) if guard.job.0.whole.ready().is_none() => drop(guard), + Err(e) => { + crate::xlog_warn!("D3D12.X: the whole form of a split compute program was not built ({e}): its indirect dispatches stay left out"); + guard.finish(); + } + } + })); + if !queued { + chain.whole_sent.store(false, Ordering::Release); + return chain.whole(true).map(Whole::Ready); + } + } + Ok(Whole::Late) } struct Scratch { @@ -545,7 +681,7 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch( let most = scratch.as_ref().map_or(1, |(s, _)| (s.bytes / group).max(1)); let slabs = pso::dispatch_slabs(grid, most); let Some((scratch, used)) = scratch else { - let whole = chain.whole()?; + let whole = chain.whole(true)?; super::bind_pipeline_exact(list.as_raw(), original, whole.as_raw() as usize); list.Dispatch(x, y, z); return Ok(()); @@ -850,7 +986,7 @@ mod tests { indirect_build.result.set(Ok(indirect)).unwrap_or_else(|_| unreachable!()); CHAINS.lock().unwrap().insert(key, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, whole_code: Vec::new(), whole, plan: Arc::downgrade(&plan), indirect: indirect_build, - indirect_noted: AtomicBool::new(false) })); + indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(false) })); let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); @@ -885,4 +1021,105 @@ mod tests { assert_eq!(deterministic.get_or_build(at, || Err(compile)), Err(crate::util::E_INVALIDARG)); assert_eq!(deterministic.get_or_build(at + WHOLE_RETRY, || Ok(8)), Err(crate::util::E_INVALIDARG)); } + + #[test] + fn whole_worker_runs_all_jobs_on_one_late_thread() { + use std::collections::HashSet; + use std::sync::{mpsc, Arc, Mutex}; + use std::thread::ThreadId; + + assert!(!super::super::super::pso_async::build_is_late()); + let seen = Arc::new(Mutex::new(Vec::<(ThreadId, Option, bool)>::new())); + let (done_tx, done_rx) = mpsc::channel(); + const N: usize = 16; + for _ in 0..N { + let seen = seen.clone(); + let done_tx = done_tx.clone(); + assert!(super::enqueue_whole(Box::new(move || { + let id = std::thread::current().id(); + let name = std::thread::current().name().map(str::to_string); + let late = super::super::super::pso_async::build_is_late(); + seen.lock().unwrap().push((id, name, late)); + let _ = done_tx.send(()); + }))); + } + for _ in 0..N { + done_rx.recv_timeout(std::time::Duration::from_secs(5)).expect("whole worker job finished"); + } + let rows = seen.lock().unwrap(); + assert_eq!(rows.len(), N); + let threads: HashSet = rows.iter().map(|(id, _, _)| *id).collect(); + assert_eq!(threads.len(), 1, "expected all whole-PSO jobs to run on a single worker thread"); + assert!(rows.iter().all(|(_, name, late)| name.as_deref() == Some("xcl-pso-whole") && *late)); + } + + #[test] + fn with_late_build_resets_after_return_and_panic() { + use super::super::super::pso_async::{build_is_late, with_late_build}; + + assert!(!build_is_late()); + let inside = with_late_build(build_is_late); + assert!(inside); + assert!(!build_is_late()); + + let panicked = std::panic::catch_unwind(|| { + with_late_build(|| { + assert!(build_is_late()); + panic!("unwind check"); + }); + }); + assert!(panicked.is_err()); + assert!(!build_is_late()); + } + + #[test] + fn whole_worker_survives_a_panicking_job_and_runs_queued_work() { + use std::sync::{mpsc, Arc}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::time::Duration; + + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let (done2_tx, done2_rx) = mpsc::channel(); + let (done3_tx, done3_rx) = mpsc::channel(); + + // Simulate a pending flag cleared by a Drop guard if the first job panics. + struct FlagGuard(Arc, bool); + impl Drop for FlagGuard { + fn drop(&mut self) { + if !self.1 { + self.0.store(false, Ordering::Release); + } + } + } + let sent1 = Arc::new(AtomicBool::new(true)); + let guard1 = FlagGuard(sent1.clone(), false); + + assert!(super::enqueue_whole(Box::new(move || { + let _g = guard1; + let _ = entered_tx.send(std::thread::current().id()); + let _ = release_rx.recv(); + panic!("injected whole-PSO worker panic"); + }))); + let worker_tid = entered_rx.recv_timeout(Duration::from_secs(5)).expect("job 1 entered worker"); + + // Queue job 2 while job 1 is still active on the worker, then let job 1 panic. + assert!(super::enqueue_whole(Box::new(move || { + let late = super::super::super::pso_async::build_is_late(); + let _ = done2_tx.send((std::thread::current().id(), late)); + }))); + let _ = release_tx.send(()); + + let (tid2, late2) = done2_rx.recv_timeout(Duration::from_secs(5)).expect("job 2 ran after job 1 panicked"); + assert_eq!(tid2, worker_tid, "job 2 should run on the same surviving worker"); + assert!(late2, "late-build flag should still be active for job 2"); + assert!(!sent1.load(Ordering::Acquire), "panicking job's pending flag should be cleared on unwind"); + + // A third job submitted after the panic is also accepted and executed. + assert!(super::enqueue_whole(Box::new(move || { + let _ = done3_tx.send(std::thread::current().id()); + }))); + let tid3 = done3_rx.recv_timeout(Duration::from_secs(5)).expect("job 3 ran after panic"); + assert_eq!(tid3, worker_tid); + } } diff --git a/crates/xcl/src/hle/d3d12x/scatter.rs b/crates/xcl/src/hle/d3d12x/scatter.rs new file mode 100644 index 0000000000..c36f734716 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/scatter.rs @@ -0,0 +1,204 @@ +//! Many small pieces of the title's memory into a window in one dispatch. +//! +//! Between two submits a title writes thousands of scattered bits of its memory (constants, +//! instances, argument buffers): a retail title's world changed ~2 000 runs of 64-byte chunks a +//! submit, ~240 bytes each. A CopyBufferRegion apiece is 0.33 µs in the driver however little it +//! copies – 25 ms of every frame there. Here the runs' bytes go into the staging ring one after +//! another as before, with a table of where each chunk belongs in front of them, and one compute +//! dispatch puts all of them in their places. + +use std::ffi::c_void; +use std::mem::transmute_copy; +use std::sync::{Arc, Mutex, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; + +/// bytes of a chunk: what a thread copies +pub(super) const CHUNK: usize = 64; +/// threads of a group, and the most chunks one dispatch takes (65 535 groups of them are the limit) +const GROUP: usize = 64; +pub(super) const MAX_CHUNKS: usize = 65_535 * GROUP; + +/// (the destinations are within 1 GiB of the address bound: `upload_dirty` cuts the runs there) +const PROGRAM: &str = r#" +cbuffer C : register(b0) { uint chunks; }; +// where each chunk goes, and the chunks, one after another +ByteAddressBuffer places : register(t0); +ByteAddressBuffer bytes : register(t1); +RWByteAddressBuffer window : register(u0); +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + uint i = id.x; + [branch] if (i < chunks) { + uint to = places.Load(i * 4u); + uint from = i * 64u; + window.Store4(to, bytes.Load4(from)); + window.Store4(to + 16u, bytes.Load4(from + 16u)); + window.Store4(to + 32u, bytes.Load4(from + 32u)); + window.Store4(to + 48u, bytes.Load4(from + 48u)); + } +} +"#; + +pub(super) struct Scatter { + rs: ID3D12RootSignature, + pso: ID3D12PipelineState, +} + +// SAFETY: D3D12 objects are free-threaded +unsafe impl Send for Scatter {} +unsafe impl Sync for Scatter {} + +/// `XCL_SPARSE_SCATTER=0`: every run goes up with a copy of its own. +pub(super) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SPARSE_SCATTER").map_or(true, |v| v.trim() != "0")) +} + +/// The pass on `dev`, made on first use (None: it cannot be made there, logged once). +pub(super) unsafe fn of(dev: &ID3D12Device) -> Option> { + static MADE: Mutex>)>> = Mutex::new(None); + let key = dev.as_raw() as usize; + let mut g = MADE.lock().unwrap(); + if let Some((d, s)) = g.as_ref().filter(|(d, _)| *d == key) { + let _ = d; + return s.clone(); + } + // (its own work: the driver's answers as they are, see `dev_create_compute_pso`) + let made = match super::title_textures::own_work(|| Scatter::new(dev)) { + Ok(s) => Some(Arc::new(s)), + Err(e) => { + crate::xlog_warn!("sparse windows: small uploads go up with a copy each ({e})"); + None + } + }; + *g = Some((key, made.clone())); + made +} + +impl Scatter { + unsafe fn new(dev: &ID3D12Device) -> Result { + let cs = super::real::compile(PROGRAM, "cs_5_0"); + if cs.is_empty() { + return Err("its program does not compile".into()); + } + let root = |ty, anonymous| D3D12_ROOT_PARAMETER { ParameterType: ty, Anonymous: anonymous, ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL }; + let view = |ty, k| root(ty, D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: k, RegisterSpace: 0 } }); + let params = [ + root(D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 1 } }), + view(D3D12_ROOT_PARAMETER_TYPE_SRV, 0), + view(D3D12_ROOT_PARAMETER_TYPE_SRV, 1), + view(D3D12_ROOT_PARAMETER_TYPE_UAV, 0), + ]; + let desc = D3D12_ROOT_SIGNATURE_DESC { NumParameters: params.len() as u32, pParameters: params.as_ptr(), ..Default::default() }; + let mut blob: Option = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).map_err(|e| format!("root signature: {e}"))?; + let blob = blob.ok_or("root signature")?; + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())).map_err(|e| format!("CreateRootSignature: {e}"))?; + let code = D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }; + let pso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: code, ..Default::default() }) + .map_err(|e| format!("CreateComputePipelineState: {e}"))?; + Ok(Scatter { rs, pso }) + } + + /// The bytes a dispatch of `chunks` chunks takes in the ring: the table, then the chunks (both + /// from a multiple of `CHUNK`). + pub fn bytes(chunks: usize) -> usize { + Self::data_at(chunks) + chunks * CHUNK + } + + /// Where the chunks begin behind their table. + pub fn data_at(chunks: usize) -> usize { + (chunks * 4).next_multiple_of(CHUNK) + } + + /// Bind the pass on `list`. + pub unsafe fn bind(&self, list: &ID3D12GraphicsCommandList) { + list.SetComputeRootSignature(&self.rs); + list.SetPipelineState(&self.pso); + } + + /// `chunks` chunks from `ring_va` (the table, then the chunks) to their places from `to_va` on + /// (bound: `bind`). + pub unsafe fn dispatch(&self, list: &ID3D12GraphicsCommandList, chunks: usize, ring_va: u64, to_va: u64) { + debug_assert!(chunks > 0 && chunks <= MAX_CHUNKS); + list.SetComputeRoot32BitConstant(0, chunks as u32, 0); + list.SetComputeRootShaderResourceView(1, ring_va); + list.SetComputeRootShaderResourceView(2, ring_va + Self::data_at(chunks) as u64); + list.SetComputeRootUnorderedAccessView(3, to_va); + list.Dispatch(chunks.div_ceil(GROUP) as u32, 1, 1); + } +} + +/// A piece of a window one dispatch fills: addresses within 1 GiB of `base`, and the runs in it. +#[derive(Debug, PartialEq, Eq)] +pub(super) struct Piece { + pub window: usize, + /// the address the piece's destinations count from + pub base: usize, + pub runs: std::ops::Range, + pub chunks: usize, +} + +/// Cut `runs` (address, bytes; whole chunks, in the order of their addresses) into pieces of one +/// window and `SPAN` bytes of it and of at most `most` chunks each. `window(a)`: the window `a` is +/// in, with its first address (None: the run is left out). +pub(super) fn pieces(runs: &[(usize, usize)], most: usize, window: impl Fn(usize) -> Option<(usize, usize)>) -> Vec { + /// (far under the 4 GiB a byte offset of a shader reaches) + const SPAN: usize = 1 << 30; + let mut out: Vec = Vec::new(); + for (k, &(a, n)) in runs.iter().enumerate() { + let Some((w, start)) = window(a) else { continue }; + let base = start + (a - start) / SPAN * SPAN; + let chunks = n / CHUNK; + match out.last_mut() { + Some(p) if p.window == w && p.base == base && p.runs.end == k && p.chunks + chunks <= most => { + p.runs.end = k + 1; + p.chunks += chunks; + } + _ => out.push(Piece { window: w, base, runs: k..k + 1, chunks }), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn runs_are_cut_by_window_by_span_and_by_size() { + const W: usize = 4 << 30; + let window = |a: usize| (a >= W && a < 4 * W).then(|| (a / W - 1, a / W * W)); + let runs = [ + (W, 64), + (W + 4096, 192), + // the last bytes of the first GiB, then the next one + (W + (1 << 30) - 64, 64), + (W + (1 << 30), 64), + // in no window + (5 * W, 64), + // another window + (2 * W + 128, 640), + (2 * W + 4096, 64), + ]; + let p = pieces(&runs, 1000, window); + assert_eq!( + p, + vec![ + Piece { window: 0, base: W, runs: 0..3, chunks: 1 + 3 + 1 }, + Piece { window: 0, base: W + (1 << 30), runs: 3..4, chunks: 1 }, + Piece { window: 1, base: 2 * W, runs: 5..7, chunks: 10 + 1 }, + ] + ); + // a run never falls in two pieces, and a piece holds `most` chunks at most + let p = pieces(&runs[..3], 4, window); + assert_eq!(p.iter().map(|p| (p.runs.clone(), p.chunks)).collect::>(), vec![(0..2, 4), (2..3, 1)]); + assert_eq!(pieces(&runs[..1], 4, |_| None), vec![]); + assert_eq!((Scatter::data_at(1), Scatter::data_at(16), Scatter::data_at(17)), (64, 64, 128)); + assert_eq!(Scatter::bytes(17), 128 + 17 * 64); + } +} diff --git a/crates/xcl/src/hle/d3d12x/sharded.rs b/crates/xcl/src/hle/d3d12x/sharded.rs new file mode 100644 index 0000000000..3d2a97e81e --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/sharded.rs @@ -0,0 +1,124 @@ +//! A map by the address of an object, in parts with a lock each. +//! +//! A title records its command lists on many threads at once, and each recorded call looks up what +//! XCL keeps of the list and of its pipeline. One lock for a whole map has those threads wait for +//! each other: with 8 of them recording, a dispatch took 5.7 µs instead of 0.6 µs. + +use std::collections::HashMap; +use std::hash::{BuildHasherDefault, Hasher}; +use std::sync::{Mutex, MutexGuard}; + +const SHARDS: usize = 64; + +/// Addresses are spread by `spread` already. +#[derive(Default)] +pub(super) struct Spread(u64); + +impl Hasher for Spread { + fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.0 = spread((self.0 ^ b as u64) as usize); + } + } + fn write_usize(&mut self, i: usize) { + self.0 = spread(i); + } + fn finish(&self) -> u64 { + self.0 + } +} + +/// Which of `n` parts an address is in. +pub(super) fn part(address: usize, n: usize) -> usize { + (spread(address) >> 40) as usize % n +} + +fn spread(address: usize) -> u64 { + let x = (address as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15); + x ^ (x >> 29) +} + +type Map = HashMap>; + +/// (a cache line each: threads at different objects do not write the same one) +#[repr(align(64))] +struct Shard(Mutex>>); + +pub(super) struct Sharded([Shard; SHARDS]); + +impl Sharded { + pub const fn new() -> Self { + Sharded([const { Shard(Mutex::new(None)) }; SHARDS]) + } + + fn shard(&self, key: usize) -> MutexGuard<'_, Option>> { + self.0[part(key, SHARDS)].0.lock().unwrap() + } + + pub fn insert(&self, key: usize, value: V) -> Option { + self.shard(key).get_or_insert_with(Default::default).insert(key, value) + } + + pub fn remove(&self, key: usize) -> Option { + self.shard(key).as_mut()?.remove(&key) + } + + pub fn contains(&self, key: usize) -> bool { + self.shard(key).as_ref().is_some_and(|m| m.contains_key(&key)) + } + + pub fn get(&self, key: usize) -> Option + where + V: Clone, + { + self.shard(key).as_ref()?.get(&key).cloned() + } + + /// `f` with the value of `key` (made when there is none), with its part's lock held: `f` looks + /// up nothing else here. + pub fn with(&self, key: usize, f: impl FnOnce(&mut V) -> R) -> R + where + V: Default, + { + f(self.shard(key).get_or_insert_with(Default::default).entry(key).or_default()) + } + + /// Every value, one part after another. + pub fn for_each(&self, mut f: impl FnMut(usize, &V)) { + for s in &self.0 { + if let Some(m) = s.0.lock().unwrap().as_ref() { + m.iter().for_each(|(&k, v)| f(k, v)); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn values_stay_with_their_keys() { + static M: Sharded = Sharded::new(); + // addresses as objects have them: 16 bytes to 64 KiB apart + let keys: Vec = (0..4000).map(|k| 0x7FF6_1234_0000 + k * [16, 0x330, 0x1_0000][k % 3] + k).collect(); + for (n, &k) in keys.iter().enumerate() { + assert_eq!(M.insert(k, n as u64), None); + } + for (n, &k) in keys.iter().enumerate() { + assert!(M.contains(k) && M.get(k) == Some(n as u64)); + assert_eq!(M.with(k, |v| std::mem::replace(v, *v + 1)), n as u64); + } + let mut seen = 0; + M.for_each(|_, _| seen += 1); + assert_eq!(seen, keys.len()); + // (no part has much more than its share) + let most = M.0.iter().map(|s| s.0.lock().unwrap().as_ref().map_or(0, |m| m.len())).max().unwrap(); + assert!(most < keys.len() / SHARDS * 3, "{most} of {} in one part", keys.len()); + for (n, &k) in keys.iter().enumerate() { + assert_eq!(M.remove(k), Some(n as u64 + 1)); + assert!(!M.contains(k) && M.remove(k).is_none()); + } + assert_eq!(M.with(5, |v| *v), 0, "made when there is none"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/small_tex.rs b/crates/xcl/src/hle/d3d12x/small_tex.rs new file mode 100644 index 0000000000..0a2ba2a855 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/small_tex.rs @@ -0,0 +1,247 @@ +//! Small sampled textures of the title that get no shared pages (`vram::place_pages` refuses them: +//! a 1D texture cannot be a reserved resource) on 4 KiB placements in heaps of XCL's own +//! (`XCL_SMALL_TEXTURES=1`), instead of a committed resource each: a committed resource takes at +//! least 64 KiB of video memory, and a title's thousands of tiny lookup textures (a few hundred +//! bytes each) took ~300 MiB that way. +//! +//! Only what the PC itself allows: no render target, depth or UAV flags, one sample, and +//! `GetResourceAllocationInfo` giving `D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT` (4 KiB) for the +//! description asking for it (its most detailed level fits in 64 KiB). Anything else, and a +//! texture the heaps here cannot take, is made committed as before. +//! +//! A texture's units are free again once its last reference goes (`gone`, where `late_release` +//! lets it go: the queues are past the work submitted before; with `XCL_LATE_RELEASE=0` nothing +//! is placed here). The heaps stay (4 MiB each). + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use crate::util::HRESULT; + +/// a placement unit: the small-resource alignment +const UNIT: u64 = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64; +/// one heap of XCL's own +const HEAP_BYTES: u64 = 4 << 20; +const UNITS: usize = (HEAP_BYTES / UNIT) as usize; + +/// Whether small sampled textures go on 4 KiB placements (`XCL_SMALL_TEXTURES=1`). +pub(super) fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SMALL_TEXTURES").is_ok_and(|v| v.trim() == "1")) +} + +/// The units of one heap: first fit of a run of `n`. +struct Units(Vec); + +impl Units { + fn new() -> Self { + Units(vec![false; UNITS]) + } + + fn take(&mut self, n: usize) -> Option { + let mut run = 0; + for i in 0..self.0.len() { + run = if self.0[i] { 0 } else { run + 1 }; + if run == n { + let first = i + 1 - n; + self.0[first..=i].iter_mut().for_each(|u| *u = true); + return Some(first); + } + } + None + } + + fn give(&mut self, first: usize, n: usize) { + self.0[first..first + n].iter_mut().for_each(|u| *u = false); + } +} + +struct Pool { + /// the device the heaps are of + dev: usize, + heaps: Vec<(ID3D12Heap, Units)>, + /// live texture → (heap, first unit, units) + live: HashMap, + units_live: usize, +} + +static POOL: Mutex> = Mutex::new(None); + +/// The units `desc` takes on a 4 KiB placement, or None when the PC does not place it so. +pub(super) unsafe fn units_for(dev: &ID3D12Device, desc: &D3D12_RESOURCE_DESC) -> Option { + let shut = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || desc.Dimension == D3D12_RESOURCE_DIMENSION_UNKNOWN || (desc.Flags & shut).0 != 0 || desc.SampleDesc.Count != 1 { + return None; + } + let mut small = *desc; + small.Alignment = UNIT; + let info = dev.GetResourceAllocationInfo(0, &[small]); + (info.Alignment == UNIT && info.SizeInBytes != u64::MAX && info.SizeInBytes > 0 && info.SizeInBytes <= D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64) + .then(|| info.SizeInBytes.div_ceil(UNIT) as usize) +} + +/// A sampled texture `desc` on a 4 KiB placement in a heap of XCL's own (device `this`), made as +/// `CreatePlacedResource` (adopted as any resource); None when it is not placed so (the caller makes +/// it committed). +pub(super) unsafe fn place(this: *mut c_void, desc: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option { + // (with `XCL_LATE_RELEASE=0` a texture's units would be free at the title's release, while an + // upload of XCL's into it can still be in flight: committed then) + if !enabled() { + return None; + } + if !super::late_release::enabled() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: XCL_SMALL_TEXTURES=1 does nothing with XCL_LATE_RELEASE=0: small textures stay committed")); + return None; + } + let dev = ID3D12Device::from_raw_borrowed(&this)?; + let n = units_for(dev, desc)?; + let mut small = *desc; + small.Alignment = UNIT; + // the units first (the heap stays while the pool does); the resource is made outside the lock + let (heap_raw, heap_index, first) = { + let mut g = POOL.lock().unwrap(); + let pool = g.get_or_insert_with(|| Pool { dev: this as usize, heaps: Vec::new(), live: HashMap::new(), units_live: 0 }); + if pool.dev != this as usize { + return None; + } + let found = pool.heaps.iter_mut().enumerate().find_map(|(k, (h, u))| u.take(n).map(|first| (h.as_raw() as usize, k, first))); + match found { + Some(f) => f, + None => { + let hd = D3D12_HEAP_DESC { + SizeInBytes: HEAP_BYTES, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut heap: Option = None; + if dev.CreateHeap(&hd, &mut heap).is_err() { + return None; + } + let heap = heap?; + let mut units = Units::new(); + let first = units.take(n)?; + let raw = heap.as_raw() as usize; + pool.heaps.push((heap, units)); + let k = pool.heaps.len(); + if k <= 4 || k.is_power_of_two() { + // (XCL asks no residency priority for these heaps or for a committed texture, + // with or without XCL_VRAM_HOT_PRIORITY) + crate::xlog_info!("D3D12.X: small textures: heap {k} of 4 MiB made, residency priority: default, no override (as for a committed texture)"); + } + (raw, k - 1, first) + } + } + }; + let hr = super::real::dev_create_placed_resource(this, heap_raw, first * UNIT as usize, &small as *const _ as usize, state as usize, clear as usize, riid, ppv); + let mut g = POOL.lock().unwrap(); + let pool = g.as_mut().unwrap(); + if hr < 0 || (*ppv).is_null() { + pool.heaps[heap_index].1.give(first, n); + static FAILED: AtomicU64 = AtomicU64::new(0); + if FAILED.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: a small texture's 4 KiB placement failed ({hr:#x}); it is made committed"); + } + return None; + } + pool.live.insert(*ppv as usize, (heap_index, first, n)); + pool.units_live += n; + static PLACED: AtomicU64 = AtomicU64::new(0); + let k = PLACED.fetch_add(1, Ordering::Relaxed) + 1; + if k.is_power_of_two() && k >= 64 { + crate::xlog_info!( + "D3D12.X: {k} small textures on 4 KiB placements so far; {} live in {} KiB of {} heaps of 4 MiB (committed: at least {} KiB)", + pool.live.len(), + pool.units_live * UNIT as usize >> 10, + pool.heaps.len(), + pool.live.len() * 64 + ); + } + Some(hr) +} + +/// The texture `res` is destroyed next: its units are free. +pub(super) fn gone(res: usize) { + if !enabled() { + return; + } + let mut g = POOL.lock().unwrap(); + if let Some(pool) = g.as_mut() { + if let Some((k, first, n)) = pool.live.remove(&res) { + pool.heaps[k].1.give(first, n); + pool.units_live -= n; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_SAMPLE_DESC}; + + /// Units go first fit and come back: a freed run is taken again, a run longer than any gap is not. + #[test] + fn units_are_taken_first_fit_and_given_back() { + let mut u = Units::new(); + assert_eq!(u.take(1), Some(0)); + assert_eq!(u.take(4), Some(1)); + assert_eq!(u.take(1), Some(5)); + u.give(1, 4); + assert_eq!(u.take(2), Some(1)); + assert_eq!(u.take(3), Some(6), "the 2-unit gap left at 3 is too small"); + assert_eq!(u.take(2), Some(3)); + let mut full = Units::new(); + assert_eq!(full.take(UNITS), Some(0)); + assert_eq!(full.take(1), None); + full.give(UNITS - 2, 2); + assert_eq!(full.take(3), None); + assert_eq!(full.take(2), Some(UNITS - 2)); + } + + fn tex(dim: D3D12_RESOURCE_DIMENSION, w: u64, h: u32, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: dim, + Alignment: 0, + Width: w, + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: flags, + } + } + + /// The PC's rules decide: a tiny 1D or 2D sampled texture is placed on 4 KiB, a render target + /// or a texture over 64 KiB is not, and a buffer is never. + #[test] + fn only_textures_the_pc_places_on_4_kib_are_taken() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + return crate::gpu::recomp::runner::skip_test("no D3D12 device"); + } + let dev = dev.unwrap(); + unsafe { + // 256 texels of RGBA8: 1 KiB of texels, on a 4 KiB placement of the driver's size (8 KiB + // on an RTX 5070 Ti with driver 610.74) + let n = units_for(&dev, &tex(D3D12_RESOURCE_DIMENSION_TEXTURE1D, 256, 1, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, D3D12_RESOURCE_FLAG_NONE)); + assert!(n.is_some_and(|n| (1..=16).contains(&n)), "{n:?}"); + // 64x64 RGBA8: 16 KiB + let n = units_for(&dev, &tex(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)); + assert!(n.is_some_and(|n| (4..=16).contains(&n)), "{n:?}"); + assert_eq!(units_for(&dev, &tex(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)), None); + assert_eq!(units_for(&dev, &tex(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 512, 512, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)), None); + let mut buf = tex(D3D12_RESOURCE_DIMENSION_BUFFER, 4096, 1, windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE); + buf.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + assert_eq!(units_for(&dev, &buf), None); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 15a13d80bf..cae13913f2 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -16,10 +16,10 @@ //! Buffers the title places there get reserved resources over the same tiles, so PC-side //! copies, views and barriers see the same memory. -use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; use std::ffi::c_void; use std::hash::{BuildHasherDefault, Hasher}; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicU8, Ordering}; use std::sync::{Arc, Mutex}; use windows::core::Interface; @@ -40,6 +40,12 @@ const POOL_TILES: u32 = 64; /// tiles decommitted while no title work was submitted that stay mapped (`State::parked`) before /// they are unmapped together: 256 MB of video memory const PARKED_MAX: usize = 4096; +/// tiles waiting for their mapping call (`State::pending`) before they are sent at once: 256 MB +const PENDING_MAX: usize = 4096; +/// a pool tile freed is not reused before this (`State::cooling`): work the title submitted +/// before its unmap may still read it on the title's queues, and the sparse queue that maps, +/// clears and fills it for its next address does not wait for those +const COOL: std::time::Duration = std::time::Duration::from_secs(2); /// bytes of the ring-buffered upload staging buffer const STAGING: usize = 64 << 20; /// alignment of sub-allocations inside the upload staging ring (write-combined cacheline) @@ -51,9 +57,15 @@ const ZERO_BUF: usize = 1 << 20; /// bytes of the GPU→CPU readback staging buffer const READBACK_STAGING: usize = 16 << 20; +/// changed runs of fewer bytes go up together in a compute dispatch (`scatter`) when there are +/// this many of them, of this many chunks at most (4 MiB, so the ring fills in pieces) +const SCATTER_RUN: usize = 4 << 10; +const SCATTER_FROM: usize = 16; +const SCATTER_CHUNKS: usize = 1 << 16; + const PAGE: usize = 0x1000; const PAGES_PER_TILE: usize = TILE / PAGE; -const CHUNK: usize = 64; +const CHUNK: usize = super::scatter::CHUNK; const CHUNKS: usize = PAGE / CHUNK; /// Fast non-cryptographic integer hasher for page/tile lookup maps on the hot submit path. @@ -87,6 +99,7 @@ impl Hasher for FxHasher { } type FxHashMap = HashMap>; +type FxHashSet = std::collections::HashSet>; struct TileEntry { pool: (u32, u32), @@ -96,12 +109,160 @@ struct TileEntry { not_rw: u16, /// per-4 KiB-page hashes of the 64-byte chunks last sent to the GPU (`None` = all zero) sent: [Option>; PAGES_PER_TILE], + /// 0: the bytes are at the tile's own address. Else the 64 KiB-aligned CPU address they are + /// read from and land at (a tile of a GPU view, `State::mirrors`); `holes` are then the + /// uncommitted pages there. The tile's own address is no CPU memory: the title reserved it + /// with no access, as the console's GPU-only view of the same pages + src: usize, + /// what the CPU memory of a tile over a CPU view is: new for each such entry (`next_gen`), and + /// again whenever a page of it becomes a hole. A copy back or an immediate recorded with + /// another lands nowhere: the memory it was for is gone (decommitted and committed again, or + /// another CPU view shown). 0: a tile of the window's own, whose memory is its address's + gen: u32, +} + +/// The mapped tiles of the windows' own (not GPU views), and how many of them hold video memory +/// no CPU write was ever sent to: every committed page still has no `sent` hashes. Such a tile +/// holds zeros unless the GPU wrote to it. +fn never_sent(mapped: &FxHashMap) -> (usize, usize) { + let (mut own, mut unsent) = (0, 0); + for e in mapped.values().filter(|e| e.src == 0 && e.pool != LAZY) { + own += 1; + if e.sent.iter().all(|p| p.is_none()) { + unsent += 1; + } + } + (own, unsent) +} + +/// `TileEntry::pool` of a tile the title committed that has no video memory yet +/// (`XCL_SPARSE_LAZY=1`): it gets a pool tile once the CPU's first bytes go up to it or a +/// placed buffer or a copy back names it (`State::materialize`). Until then the window reads +/// zeros there, as the title's freshly committed pages do. +const LAZY: (u32, u32) = (u32::MAX, u32::MAX); + +/// `XCL_SPARSE_LAZY=1`: pages a title commits in a sparse window get their video memory at +/// their first use, not at the commit. Off by default: a compute program that writes through a +/// window to memory no buffer was placed on would write nothing there. +fn lazy_commits() -> bool { + #[cfg(test)] + if let Some(on) = tests::LAZY_COMMITS_FOR_TEST.with(|c| c.get()) { + return on; + } + lazy_asked() && !LAZY_REFUSED.load(Ordering::Relaxed) +} + +/// `XCL_SPARSE_LAZY=1` was given +fn lazy_asked() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SPARSE_LAZY").is_ok_and(|v| v.trim() == "1")) +} + +/// `XCL_SPARSE_LAZY=1` on a device whose unmapped tiles do not read zeros (`null_tiles_read_zero`): +/// commits map at once, as without it +static LAZY_REFUSED: AtomicBool = AtomicBool::new(false); + +/// Whether a tile of a reserved buffer with no video memory reads zeros and takes writes that go +/// nowhere on `dev` (tiled resources tier 2). On tier 1 a touch of one is undefined. +unsafe fn null_tiles_read_zero(dev: &ID3D12Device) -> bool { + let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut o as *mut _ as *mut c_void, std::mem::size_of_val(&o) as u32).is_ok() && o.TiledResourcesTier.0 >= D3D12_TILED_RESOURCES_TIER_2.0 +} + +/// The parts of `runs` (address, bytes) that lie in tiles `keep` holds for, cut where a tile +/// ends; neighbours left together are one run. +fn runs_where(runs: &[(usize, usize)], mut keep: impl FnMut(usize) -> bool) -> Vec<(usize, usize)> { + let mut out: Vec<(usize, usize)> = Vec::new(); + for &(a, n) in runs { + let end = a.saturating_add(n); + let mut at = a; + while at < end { + let t = at & !(TILE - 1); + let stop = t.saturating_add(TILE).min(end); + if keep(t) { + push_run(&mut out, at, stop - at); + } + at = stop; + } + } + out +} + +/// the last `TileEntry::gen` given out +static TILE_GEN: AtomicU32 = AtomicU32::new(0); + +/// A `TileEntry::gen` for a tile over a CPU view (never 0) +fn next_gen() -> u32 { + TILE_GEN.fetch_add(1, Ordering::Relaxed) % u32::MAX + 1 } impl TileEntry { fn with_holes(pool: (u32, u32), holes: u16) -> Self { - Self { pool, holes, not_rw: 0, sent: std::array::from_fn(|_| None) } + Self { pool, holes, not_rw: 0, sent: std::array::from_fn(|_| None), src: 0, gen: 0 } + } + + /// The CPU address of the tile at `t` (this entry's tile) + #[inline] + fn cpu(&self, t: usize) -> usize { + if self.src == 0 { + t + } else { + self.src + } + } +} + +/// The hole masks (`query_tile_holes`) of the 64 KiB tiles `tiles` of the title's CPU memory, in +/// their order. A page in the working set is committed: one query asks that of all their pages. +/// The others go to VirtualQuery, once for each region it reports: it walks a region to its end, +/// so a call a tile over a long committed range grew with the square of the range. +unsafe fn source_holes(tiles: &[usize]) -> Vec { + use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + /// tiles a working-set query asks for + const BATCH: usize = 256; + let mut out = Vec::with_capacity(tiles.len()); + let mut ws: Vec = Vec::with_capacity(BATCH.min(tiles.len()) * PAGES_PER_TILE); + // the region the last VirtualQuery reported: [start, end), and whether its pages are accessible + let mut region = (0usize, 0usize, false); + for batch in tiles.chunks(BATCH) { + ws.clear(); + for &t in batch { + for i in 0..PAGES_PER_TILE { + ws.push(PSAPI_WORKING_SET_EX_INFORMATION { VirtualAddress: (t + i * PAGE) as *mut c_void, ..std::mem::zeroed() }); + } + } + let asked = K32QueryWorkingSetEx(GetCurrentProcess(), ws.as_mut_ptr() as *mut c_void, std::mem::size_of_val(&ws[..]) as u32) != 0; + for (j, &t) in batch.iter().enumerate() { + let mut holes = 0xFFFFu16; + for i in 0..PAGES_PER_TILE { + let pg = t + i * PAGE; + // PSAPI_WORKING_SET_EX_BLOCK: bit 0 Valid, bits 4-14 Win32Protection + let flags = ws[j * PAGES_PER_TILE + i].VirtualAttributes.Flags; + let protect = ((flags >> 4) & 0x7FF) as u32; + let mut accessible = asked && flags & 1 != 0 && protect != 0 && protect & (PAGE_NOACCESS | PAGE_GUARD) == 0; + if !accessible { + if !(region.0..region.1).contains(&pg) { + #[cfg(test)] + tests::VIRTUAL_QUERIES.with(|n| n.set(n.get() + 1)); + let mut mbi: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + region = if VirtualQuery(pg as *const c_void, &mut mbi, std::mem::size_of::()) == 0 || mbi.RegionSize == 0 { + (pg, pg + PAGE, false) + } else { + let ok = mbi.State == MEM_COMMIT && mbi.Protect != 0 && (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) == 0; + (pg, (mbi.BaseAddress as usize).saturating_add(mbi.RegionSize).max(pg + PAGE), ok) + }; + } + accessible = region.2; + } + if accessible { + holes &= !(1u16 << i); + } + } + out.push(holes); + } } + out } /// Query actual OS page commitment across the 64 KiB tile at `tile`. @@ -142,7 +303,7 @@ fn decommit_tiles( mapped: &mut FxHashMap, pinned: &FxHashMap<(u32, u32), u32>, free: &mut Vec<(u32, u32)>, - to_zero: &mut Vec<(usize, usize)>, + to_zero: &mut BTreeSet<(usize, usize)>, a: usize, n: usize, ) -> Vec { @@ -168,12 +329,15 @@ fn decommit_tiles( } p += PAGE; } + if newly_holed != 0 && entry.src != 0 { + entry.gen = next_gen(); + } if entry.holes == 0xFFFF { unmapped.push(t); } else if newly_holed != 0 { for idx in 0..PAGES_PER_TILE { if newly_holed & (1u16 << idx) != 0 { - to_zero.push((t + idx * PAGE, PAGE)); + to_zero.insert((t + idx * PAGE, PAGE)); } } } @@ -185,23 +349,381 @@ fn decommit_tiles( } for &t in &unmapped { if let Some(entry) = mapped.remove(&t) { - if !pinned.contains_key(&entry.pool) { + if entry.pool != LAZY && !pinned.contains_key(&entry.pool) { free.push(entry.pool); } } } - if !unmapped.is_empty() { - to_zero.retain(|&(za, _)| mapped.contains_key(&(za & !(TILE - 1)))); + // (their pieces only: going over all of them for each page decommitted while a title loads, + // with no submit to clear them, grew with the square of the pages) + for &t in &unmapped { + while let Some(&piece) = to_zero.range((t, 0)..(t + TILE, 0)).next() { + to_zero.remove(&piece); + } } unmapped } +/// The pieces to clear (`State::to_zero`) as runs: neighbours and pieces inside another together. +fn zero_runs(pieces: BTreeSet<(usize, usize)>) -> Vec<(usize, usize)> { + let mut out: Vec<(usize, usize)> = Vec::new(); + for (a, n) in pieces { + match out.last_mut() { + Some(l) if a <= l.0 + l.1 => l.1 = l.1.max(a + n - l.0), + _ => out.push((a, n)), + } + } + out +} + +/// Free pool tiles partitioned by pool heap so `reuse_tile` packs the fullest live heap that +/// still has a free tile instead of scattering allocations across nearly-empty pools that are +/// draining towards `State::retire_free_pools`. +#[derive(Default)] +struct FreePools { + by_heap: Vec>, + total: usize, +} + +impl FreePools { + fn new() -> Self { + Self::default() + } + + fn len(&self) -> usize { + self.total + } + + fn is_empty(&self) -> bool { + self.total == 0 + } + + fn heap_len(&self, h: usize) -> usize { + self.by_heap.get(h).map_or(0, Vec::len) + } + + fn has_empty_heap(&self) -> bool { + self.by_heap.iter().any(|tiles| tiles.len() >= POOL_TILES as usize) + } + + fn add_heap(&mut self, h: u32) { + let idx = h as usize; + if idx >= self.by_heap.len() { + self.by_heap.resize_with(idx + 1, Vec::new); + } + debug_assert!(self.by_heap[idx].is_empty()); + self.by_heap[idx] = (1..POOL_TILES).rev().collect(); + self.total += (POOL_TILES - 1) as usize; + } + + fn push(&mut self, (h, t): (u32, u32)) { + let idx = h as usize; + if idx >= self.by_heap.len() { + self.by_heap.resize_with(idx + 1, Vec::new); + } + self.by_heap[idx].push(t); + self.total += 1; + } + + fn clear_heap(&mut self, h: usize) { + if let Some(tiles) = self.by_heap.get_mut(h) { + self.total -= tiles.len(); + tiles.clear(); + tiles.shrink_to_fit(); + } + } + + /// Move every cooled tile (`>= COOL`) from `cooling` into its pool heap's free list. + fn drain_cooling(&mut self, cooling: &mut VecDeque<((u32, u32), std::time::Instant)>, now: std::time::Instant) { + while cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { + if let Some((tile, _)) = cooling.pop_front() { + self.push(tile); + } + } + } + + /// Take a tile from the fullest partially-used heap (`0 < len < POOL_TILES`, lowest heap index + /// on ties) so nearly-empty heaps stay untouched and retire; only take from an all-free heap + /// when no partially-used heap has a free tile. + fn pop_packed(&mut self) -> Option<(u32, u32)> { + if self.total == 0 { + return None; + } + let h = self + .by_heap + .iter() + .enumerate() + .filter(|(_, tiles)| !tiles.is_empty() && tiles.len() < POOL_TILES as usize) + .min_by_key(|(_, tiles)| tiles.len()) + .or_else(|| self.by_heap.iter().enumerate().find(|(_, tiles)| tiles.len() >= POOL_TILES as usize)) + .map(|(h, _)| h)?; + let t = self.by_heap[h].pop()?; + self.total -= 1; + Some((h as u32, t)) + } + + #[cfg(test)] + fn contains(&self, &(h, t): &(u32, u32)) -> bool { + self.by_heap.get(h as usize).is_some_and(|tiles| tiles.contains(&t)) + } + + #[cfg(test)] + fn clear(&mut self) { + for tiles in &mut self.by_heap { + tiles.clear(); + } + self.total = 0; + } + + #[cfg(test)] + fn has_pool(&self, h: u32) -> bool { + self.heap_len(h as usize) > 0 + } +} + +/// Whether the oldest tile of `cooling` was freed `COOL` ago or more at `now` +fn cooled(cooling: &VecDeque<((u32, u32), std::time::Instant)>, now: std::time::Instant) -> bool { + cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) +} + +/// The pool tile to use next (`State::take_tile`): drain cooled tiles into their pool heaps and +/// take from the fullest partially-used heap (or an all-free heap if none is partially used). +/// None: neither, though tiles freed less than `COOL` ago may be cooling. +fn reuse_tile(free: &mut FreePools, cooling: &mut VecDeque<((u32, u32), std::time::Instant)>, now: std::time::Instant) -> Option<(u32, u32)> { + free.drain_cooling(cooling, now); + free.pop_packed() +} + +/// The pool heaps (`pools` of them) all of whose tiles are in `free` or cooled in `cooling` at +/// `now` (`State::retire_free_pools`): a tile still cooling keeps its heap. +fn free_heaps(free: &FreePools, cooling: &VecDeque<((u32, u32), std::time::Instant)>, pools: usize, now: std::time::Instant) -> Vec { + let mut count = vec![0u32; pools]; + for (h, c) in count.iter_mut().enumerate() { + *c = free.heap_len(h) as u32; + } + for &((h, _), _) in cooling.iter().take_while(|&&(_, at)| now.duration_since(at) >= COOL) { + if let Some(c) = count.get_mut(h as usize) { + *c += 1; + } + } + (0..pools).filter(|&h| count[h] == POOL_TILES).collect() +} + +/// Whether a submit that freed no tile tries `State::retire_free_pools` at `now`: when a tile +/// of `cooling` cooled or a heap waits in `retired` (`waiting`), and `COOL` after the last try +/// (`tried`) at the earliest (a try counts the cooled tiles). +fn retire_due(cooling: &VecDeque<((u32, u32), std::time::Instant)>, waiting: bool, tried: std::time::Instant, now: std::time::Instant) -> bool { + (waiting || cooled(cooling, now)) && now.duration_since(tried) >= COOL +} + struct UploadSlot { alloc: ID3D12CommandAllocator, list: ID3D12GraphicsCommandList, fence_val: u64, } +/// A copy back on `State::rbq`: its list, its readback buffer, the `rb_fence` value it waits +/// for, the `rbq` fence value that marks it done, and the copies into the title's memory +/// (window address, offset in `buf`, bytes, `TileEntry::gen` of the address's tile then: +/// `State::copy_back`). +struct RbJob { + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + buf: ID3D12Resource, + ptr: *mut u8, + cap: usize, + rb_v: u64, + done_v: u64, + copies: Vec<(usize, usize, usize, u32)>, + /// the type of queue `list` is for (a copy back runs on the title's own queue) + ty: D3D12_COMMAND_LIST_TYPE, + /// the title queue's fences for it (`State::rb_queue_fences`): the first reaches `rb_v` when + /// the lists it follows are done, the second `done_v` when the copy is. None: `rb_fence` and + /// the readback queue's fence (the form before) + fences: Option<(ID3D12Fence, ID3D12Fence)>, + /// place among the submissions' jobs (`ReadbackQueue::job_seq`): copies and immediates land in it + seq: u64, +} + +// D3D12 objects and mapped readback staging pointers are free-threaded; mutated under mutexes. +unsafe impl Send for RbJob {} + +/// In an immediate's byte count: the cell is a counter that the title's queues write in turn, +/// with values that only rise as they are recorded. A list that runs late – a retail title's +/// compute jobs, tens of frames after their recording when its submits are slow – writes an +/// earlier value over a later one; the title's CPU waits for "at least" the later one, which +/// was reached. The CPU's view keeps the larger value. +pub(super) const IMM_KEEP_MAX: u8 = 0x80; + +/// Immediates the title's lists wrote into a window (`list_x::imm_by_cpu`): stored in the +/// title's memory once `fence` reaches `value` (the lists are done on the GPU). +struct ImmJob { + /// place among the copies back (`RbJob::seq`) + seq: u64, + fence: ID3D12Fence, + value: u64, + /// (address, value, bytes, `TileEntry::gen` of the address's tile then) + writes: Vec<(usize, u64, u8, u32)>, +} + +unsafe impl Send for ImmJob {} + +/// Async readback job queues and buffer pool under a pure leaf lock separate from `STATE`. +/// +/// Strict 2-level DAG lock order (mathematically deadlock-free): +/// - `STATE` -> `ReadbackQueue` (mark `submitting` on plan prep, pop finished jobs, return recycled +/// `RbJob`s up to cap 32) +/// - `RbSubmit` -> `ReadbackQueue` (pop pooled `RbJob`, push newly submitted jobs & clear `submitting`) +/// - `STATE` and `RbSubmit` never nest; `ReadbackQueue` is never held across GPU fence spins, +/// `Condvar` waits (released while waiting), D3D12 COM calls, or `RbJob` drops. +struct ReadbackQueue { + /// fallback fence signalled on title queues (when a job has `fences: None`) + rb_fence: ID3D12Fence, + /// fallback readback queue fence (when a job has `fences: None`) + rbq_done: Option, + /// submitted copies back, oldest first, and finished ones to reuse + rb_jobs: VecDeque, + rb_pool: Vec, + /// immediates of the title's submissions, oldest first, and the count that orders them + /// with `rb_jobs` + imm_jobs: VecDeque, + job_seq: u64, + /// count of async readback plans prepared under `STATE` whose jobs have not yet been + /// published (or cancelled on error) into `rb_jobs`/`imm_jobs` + submitting: usize, + /// count of finished jobs currently popped and being landed into CPU memory under `STATE` + /// (forces concurrent `settle_readbacks*` callers to synchronize on `STATE` before returning) + landing: usize, +} + +unsafe impl Send for ReadbackQueue {} + +impl ReadbackQueue { + fn new(rb_fence: ID3D12Fence, rbq_done: Option) -> Self { + Self { rb_fence, rbq_done, rb_jobs: VecDeque::new(), rb_pool: Vec::new(), imm_jobs: VecDeque::new(), job_seq: 0, submitting: 0, landing: 0 } + } +} + +impl Drop for ReadbackQueue { + fn drop(&mut self) { + let left = self.rb_jobs.len() + self.imm_jobs.len(); + if left > 0 { + RB_PENDING.fetch_sub(left, Ordering::Release); + } + } +} + +/// Shared `ReadbackQueue` plus a `Condvar` notified whenever an in-flight `prepare_after_execute` +/// plan finishes publishing or cancels, so settling callers observe the transition within their +/// existing wait budget without polling or holding `STATE`. +struct SharedReadbacks { + queue: Mutex, + published: std::sync::Condvar, +} + +impl SharedReadbacks { + fn new(rb_fence: ID3D12Fence, rbq_done: Option) -> Self { + Self { + queue: Mutex::new(ReadbackQueue::new(rb_fence, rbq_done)), + published: std::sync::Condvar::new(), + } + } + + fn lock(&self) -> std::sync::LockResult> { + self.queue.lock() + } +} + +/// Tracks one prepared `AsyncReadbackPlan` from `prepare_after_execute` (while `STATE` is still +/// held) until `submit_async_readback` either publishes its jobs or bails/drops. Holds a strong +/// `Arc` so `ReadbackQueue::drop` cannot run while a submission is in flight. +struct SubmittingGuard { + readbacks: Arc, + active: bool, +} + +impl SubmittingGuard { + fn begin(readbacks: &Arc) -> Self { + let mut rq = readbacks.lock().unwrap(); + rq.submitting += 1; + RB_PENDING.fetch_add(1, Ordering::Release); + Self { readbacks: Arc::clone(readbacks), active: true } + } + + /// Atomically replace the pending submission token with `added` queued jobs under `rq`. + fn finish(mut self, rq: &mut ReadbackQueue, added: usize) { + rq.submitting -= 1; + self.active = false; + if added > 1 { + RB_PENDING.fetch_add(added - 1, Ordering::Release); + } else if added == 0 { + RB_PENDING.fetch_sub(1, Ordering::Release); + } + } +} + +impl Drop for SubmittingGuard { + fn drop(&mut self) { + if self.active { + let mut rq = self.readbacks.lock().unwrap(); + rq.submitting -= 1; + RB_PENDING.fetch_sub(1, Ordering::Release); + drop(rq); + self.readbacks.published.notify_all(); + } + } +} + +/// Per-queue async readback submission state, locked outside `STATE` so `readback_after_execute` +/// records `CopyBufferRegion` / `pc_execute` / `Signal` without blocking `STATE`. +struct RbSubmit { + dev: ID3D12Device, + /// title queue -> the two fences it signals around a copy back, and the last value. One set + /// a queue: with one fence for all, a queue that got to its Signal first let the copies of a + /// queue still waiting run early + rb_queue_fences: FxHashMap, +} + +unsafe impl Send for RbSubmit {} + +impl RbSubmit { + fn new(dev: ID3D12Device) -> Self { + Self { dev, rb_queue_fences: FxHashMap::default() } + } +} + +enum ReadyJob { + Imm(ImmJob), + Rb(RbJob), +} + +struct RbChunk { + win: usize, + va: usize, + len: usize, + gen: u32, +} + +struct AsyncReadbackPlan { + rb_submit: Arc>, + readbacks: Arc, + windows: Vec<(usize, ID3D12Resource)>, + batches: Vec>, + imm: Vec<(usize, u64, u8, u32)>, + submitting: SubmittingGuard, +} + +/// How far `drain_readbacks` goes +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Drain { + /// only copies the GPU has finished + #[cfg(test)] + Finished, + /// also those whose title work is done (waiting for the copy itself): before a CPU read + /// the title made sure of, e.g. after its wait for the value a list wrote + TitleDone, +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum SubmitResult { Submitted, @@ -1906,6 +2428,8 @@ struct RetiredTiles { tiles: Vec<(u32, u32)>, /// Fence marks on `self.queue` and every known title queue (`None` = signal failed, keep held). marks: Option>, + /// when they were unmapped: they cool (`State::cooling`) from then on once the marks are reached + at: std::time::Instant, } struct State { @@ -1921,17 +2445,38 @@ struct State { value: u64, /// reusable auto-reset Win32 event for fence waits (no per-wait CreateEventW/CloseHandle) event: HANDLE, - /// fence signalled on title queues so `queue` waits before copying GPU writes back to CPU + /// fence signalled on title queues after their lists, so a copy back waits for them rb_fence: ID3D12Fence, rb_value: u64, + /// copies back after the title's submissions (`readback_after_execute`): on a queue of their + /// own (`rbq`, None: on `queue`, waited for on the CPU), landing in the title's memory once + /// done (`drain_readbacks`). The title's queues can wait for work the title submits after + /// this one, from the same thread: waiting here for its lists stopped that submission – and, + /// on `queue`, every upload behind it (`before_execute` waiting for ring room). + rbq: Option<(ID3D12CommandQueue, ID3D12Fence)>, + rbq_value: u64, + /// async readback job queues and reusable staging pool (leaf lock separate from `STATE`) + readbacks: Arc, + /// async readback recorder and per-queue fence map (locked outside `STATE`) + rb_submit: Arc>, /// (window start, reserved buffer) of each sparse window windows: Vec<(usize, ID3D12Resource)>, /// video-memory pool heaps (None: given back, its index free for the next one) pools: Vec>, - free: Vec<(u32, u32)>, + /// pool tiles to use, partitioned by heap (`FreePools`): those of a pool that were never used, + /// and cooled ones (`cooling`) + free: FreePools, + /// pool tiles freed (`flush_parked`, once `quarantined` lets them go, and `release_if_unused`), + /// oldest first, with when: used again `COOL` after that at the earliest (`take_tile`). + /// Before, a tile unmapped went to `free` and was the next one taken, mapped, cleared and + /// filled for another address on the sparse queue while title work submitted before the + /// unmap could still read it. + cooling: VecDeque<((u32, u32), std::time::Instant)>, /// pools all of whose tiles came free: released once the GPU is past `value` and a moment /// went by (titles' queues may still read what was mapped there) retired: Vec<(ID3D12Heap, u64, std::time::Instant)>, + /// when `retire_free_pools` last ran (`retire_due`) + retire_tried: std::time::Instant, /// tile address → pool tile + uncommitted page hole mask + per-page sent chunk hashes mapped: FxHashMap, /// pool tiles also used by placed buffers (not freed while they are) @@ -1943,15 +2488,28 @@ struct State { /// decommits and commits again thousands of tiles a second, and each `UpdateTileMappings` /// took ~0.15 ms.) parked: FxHashMap, - /// unmapped parked pool tiles awaiting `self.queue` and in-flight title queues before entering `free` + /// tile address → pool tile of decommitted tiles a placed buffer uses: they stay mapped in + /// their window until the buffer is gone. Memory committed there again is then the same for + /// the window (what shaders write) and the buffer (what an ExecuteIndirect or a copy of the + /// title reads); with a new tile in the window the buffer kept the old one, with old bytes + kept: FxHashMap, + /// tile addresses given a pool tile in `mapped` whose `UpdateTileMappings` has not been sent + /// yet: mapped together (`flush_pending`, one call per window) before the next title submit, + /// before XCL's own GPU work on the windows, or past `PENDING_MAX`. (A retail title starting + /// on a Series S profile maps 4.3 GB of physical pages in small pieces: one mapping call + /// each, ~0.4 ms, held its loading thread ~25 s and its stall watchdog ended it.) + pending: Vec, + /// placed buffers → the tiles they use (address, pool tile) + buffers: FxHashMap>, + /// unmapped parked pool tiles awaiting `self.queue` and in-flight title queues before they + /// cool (`cooling`) quarantined: VecDeque, - /// per-title-queue fences used to mark in-flight GPU work; raw keys are removed only by - /// exact-generation queue retirement before that queue's address can be reused + /// per-title-queue fences used to mark in-flight GPU work (`note_queue`, `quarantine_tiles_for`); + /// raw keys are removed only by exact-generation queue retirement (`forget_queue`) before that + /// queue's address can be reused queue_fences: FxHashMap, - /// placed buffers → the pool tiles they use - buffers: FxHashMap>, /// reused tiles / decommitted partial pages to clear: (address, bytes) - to_zero: Vec<(usize, usize)>, + to_zero: BTreeSet<(usize, usize)>, /// ring-buffered upload staging heap (`STAGING` bytes, persistently mapped) staging: Option<(ID3D12Resource, *mut u8)>, /// monotonic ring-buffer write/submitted/retired byte cursors @@ -1975,14 +2533,188 @@ struct State { rb_last_fence: u64, /// the fence value each title queue last waited for waited: FxHashMap, - /// `mapped` as sorted (start, end) runs (None: to be made again) - runs: Option>, + /// `mapped` as runs of neighbouring tiles (start -> end), kept with it: sorted out of all of + /// them again (a retail title has 150,000) for each look behind a commit + runs: BTreeMap, /// reusable buffer for dirty runs in `before_execute` (avoids per-submit heap alloc) scratch_runs: Vec<(usize, usize)>, + /// `XCL_LOOK_STATS=2`: the title's pages XCL wrote itself since the last look (copies back + /// landed, immediates stored; `OWN_PAGES_MAX` at most), for `look_stats::own_writes` + own_pages: Vec, + /// CPU tile → the window tiles over it (tiles of a GPU view, `map_mirror`), with video memory + /// or not: what the CPU writes there goes to each of them. Several can show one CPU tile + mirrors: FxHashMap>, + /// window tile → the CPU tile under it, for each tile in `mirrors` + mirror_src: FxHashMap, + /// the CPU tiles of `mirrors` as runs (start -> end): where a CPU write has to reach the GPU + /// too (`mapped_ranges`). Tiles over a CPU view are never in `runs`: their own addresses are + /// not the CPU's + src_runs: BTreeMap, + /// `src_runs` for the threads that decommit the title's CPU memory, and their decommits under + /// way (`SOURCES`; a test's state has one of its own) + sources: &'static Mutex, + /// window tiles given video memory over their CPU view since the last submit: all of their + /// committed pages go up with it (the CPU wrote them before the tile was there, and those + /// writes were taken by a look before) + fill: Vec, + /// window tiles asked for (`map_mirror`) and not handled yet + asks: Vec, + /// window tiles whose GPU-view page changed (`remapped`), linked again at the next submit + remaps: Vec, + /// window tiles linked over their CPU tiles (`mirror_src`) that wait for their video memory + /// and fill, oldest first (`fill_later`) + later: VecDeque<(usize, usize)>, + /// committed pages filled at a submit at most, for tiles given video memory there + /// (`XCL_MIRROR_FILL_MB`): the rest wait for the next + fill_pages: usize, + /// tiles over a CPU view with video memory now, and the most there may be (`XCL_MIRROR_MB`) + mirrored: usize, + mirror_cap: usize, + /// tiles over a CPU view left without video memory for `mirror_cap`, or as none was to be had: + /// given it once there is room (`retry_refused`), or once their CPU view is written + refused: FxHashSet, + /// when a tile over a CPU view last found no video memory (`take_tile`): for a moment the + /// others do not try to make a heap again (each tried, and logged it), and the refused ones + /// wait + no_memory: Option, + /// tiles listed with no video memory (`LAZY`) whose CPU bytes found none at an upload + /// (`upload_dirty`): all that is committed there goes up at a submit once there is some + starved: Vec, + counts: MirrorCounts, + diag: ViewDiag, + /// `XCL_VIEW_POISON`: the tile the windows' tiles without video memory show (`poison_windows`) + poison: Option, /// Dirty CPU pages whose write-watch bits were reset before an upload failed. retry_pages: Vec, } +/// The one 64 KiB of video memory the tiles of the windows without video memory of their own are +/// mapped to (`D3D12_TILE_RANGE_FLAG_REUSE_SINGLE_TILE`), a buffer placed over it, and the +/// pattern's upload copy it is filled from again (`refresh_poison`: what a shader wrote there +/// lands in the one tile). +struct Poison { + heap: ID3D12Heap, + buf: ID3D12Resource, + src: ID3D12Resource, + at: std::time::Instant, +} + +/// What the tiles over CPU views did, for the timing line +#[derive(Default, Debug)] +struct MirrorCounts { + /// the most tiles with video memory at once + peak: usize, + /// tiles filled whole from their CPU view, and the bytes of their committed pages + fills: u64, + fill_bytes: u64, + /// tiles refused for `mirror_cap` or for want of video memory (each once until it has some) + refused: u64, + /// tiles whose video memory went back (their CPU view decommitted, or the view gone) + given_back: u64, + /// pages that were not committed in a CPU view, written since and asked about again + rechecks: u64, +} + +/// Diagnostics of the GPU-view tiles, all off unless set: `XCL_VIEW_KEEP=1` (a tile over a CPU +/// view keeps its video memory once filled, within `mirror_cap`), `XCL_VIEW_POISON=1` (or a +/// 32-bit pattern, `0x…`: what a tile of the windows without video memory reads instead of zeros, +/// `State::poison_windows`) and `XCL_VIEW_STATS=1`. Any of them logs `view_stats_line` every 2 s. +struct ViewSwitches { + keep: bool, + poison: Option, + stats: bool, +} + +fn view_switches() -> &'static ViewSwitches { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + ON.get_or_init(|| { + let var = |k: &str| std::env::var(k).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty() && v != "0"); + let (keep, poison) = (var("XCL_VIEW_KEEP").is_some(), poison_pattern(var("XCL_VIEW_POISON").as_deref())); + ViewSwitches { keep, poison, stats: keep || poison.is_some() || var("XCL_VIEW_STATS").is_some() } + }) +} + +/// The poison pattern of `XCL_VIEW_POISON` (set, not "0"): a NaN as a float, a wild index or count +/// as an integer, or the pattern given in hex. +fn poison_pattern(v: Option<&str>) -> Option { + let v = v?; + match v.strip_prefix("0x").or_else(|| v.strip_prefix("0X")) { + Some(hex) => u32::from_str_radix(hex, 16).ok().filter(|&p| p != 0), + None => Some(0x7FC0_DEAD), + } +} + +/// Whether a tile over a CPU view whose video memory would go back keeps it mapped where it is +/// (`XCL_VIEW_KEEP`): while the tiles with video memory and kept, this one among them, are within +/// the cap. +fn keep_view_tile(keep: bool, held: usize, cap: usize) -> bool { + keep && held <= cap +} + +/// The bucket of a tile that got video memory again `submits` after it went: 0-1, 2-8, 9-64, more. +fn back_bucket(submits: u64) -> usize { + match submits { + 0..=1 => 0, + 2..=8 => 1, + 9..=64 => 2, + _ => 3, + } +} + +/// What the GPU-view diagnostics count (`ViewSwitches`; nothing while they are off but submits). +#[derive(Default, Debug)] +struct ViewDiag { + keep: bool, + stats: bool, + /// submits so far (`before_execute_on`) + submits: u64, + /// tiles kept mapped that would have gone back (`XCL_VIEW_KEEP`) + kept: u64, + /// tile given back or kept → the submit then, until it gets video memory again + left_at: FxHashMap, + /// tiles that got video memory again, by submits since they went (`back_bucket`), and the + /// bytes of their committed pages filled again + back: [u64; 4], + back_bytes: u64, + /// submits that left tiles asked for waiting (`later`, `asks`) for a later one + deferred: u64, +} + +/// Tiles of GPU views asked for (`map_mirror` queued them), while `ViewSwitches::stats`. +static VIEW_ASKED: AtomicU64 = AtomicU64::new(0); + +/// `view_stats`: [asked, filled, given back, kept, back 0-1, 2-8, 9-64, more, bytes back, submits, +/// deferred] so far, then [with video memory, kept mapped, waiting, refused] now. +const VS: usize = 15; +const VS_NOW: usize = 11; + +/// tiles over CPU views asked for taken in at a time, and refused ones tried again at a submit at +/// most (`State::map_mirrors`); the rest wait for the next one +const MIRROR_ASKS_MAX: usize = 4096; + +/// Committed pages of the CPU views filled into tiles given video memory at a submit at most +/// (`XCL_MIRROR_FILL_MB`, 256 MB by default; at least a page; with 16 MB a close-up's mesh +/// data was asked for at a submit and drawn with part of it still unfilled, as shards and +/// slabs on the heads of a title's characters): the fills are hashed and go +/// through the staging ring on the title's submitting thread, with the state's lock held. +fn fill_pages() -> usize { + static PAGES: std::sync::OnceLock = std::sync::OnceLock::new(); + *PAGES.get_or_init(|| { + let mb = std::env::var("XCL_MIRROR_FILL_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(256); + (mb.saturating_mul(1 << 20) / PAGE).max(1) + }) +} + +/// Video memory for tiles over CPU views at most, in tiles (`XCL_MIRROR_MB`, 4096 MB by default): +/// a GPU view covers the whole of a 24 GB CPU reservation, and the card is mostly in use already. +fn mirror_cap() -> usize { + static CAP: std::sync::OnceLock = std::sync::OnceLock::new(); + *CAP.get_or_init(|| { + let mb = std::env::var("XCL_MIRROR_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(4096); + mb.saturating_mul(1 << 20) / TILE + }) +} + impl Drop for State { fn drop(&mut self) { if !self.event.is_invalid() { @@ -2051,13 +2783,14 @@ fn push_run(out: &mut Vec<(usize, usize)>, addr: usize, len: usize) { /// cells a wait before the write watched), and its old hash still makes the next look upload the /// whole chunk, the GPU's bytes with the CPU's. The hash check and copy are not atomic against a /// concurrent CPU store: callers rely on the title's fence discipline to exclude stores to the -/// same bytes while its synchronous copy-back lands. -fn land_page(slot: &mut Option>, page: &mut [u8], at: usize, src: &[u8], gpu_written: bool) { +/// same bytes while its synchronous copy-back lands. Whether it wrote any (`State::own_pages`). +fn land_page(slot: &mut Option>, page: &mut [u8], at: usize, src: &[u8], gpu_written: bool) -> bool { debug_assert_eq!(page.len(), PAGE); debug_assert!(at + src.len() <= page.len()); let sent = slot.get_or_insert_with(|| Box::new(ZERO_HASHES)); let end = at + src.len(); let mut offset = at; + let mut wrote = false; while offset < end { let chunk = offset / CHUNK; let chunk_start = chunk * CHUNK; @@ -2066,11 +2799,28 @@ fn land_page(slot: &mut Option>, page: &mut [u8], at: usize, if chunk_hash(&page[chunk_start..chunk_start + CHUNK]) == sent[chunk] { page[offset..copy_end].copy_from_slice(&src[source..source + copy_end - offset]); sent[chunk] = chunk_hash(&page[chunk_start..chunk_start + CHUNK]); + wrote = true; } else if gpu_written { page[offset..copy_end].copy_from_slice(&src[source..source + copy_end - offset]); + wrote = true; } offset = copy_end; } + wrote +} + +/// `State::own_pages` keeps this many pages at most (a look's worth) +const OWN_PAGES_MAX: usize = 1 << 16; + +thread_local! { + /// `XCL_LOOK_STATS=2`: the next `before_execute` on this thread follows a look (`note_look`) + static LOOKED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// The submit about to call `before_execute` on this thread looked for CPU writes +/// (`XCL_LOOK_STATS=2`): XCL's own writes since the look before are counted against it. +pub(super) fn note_look() { + LOOKED.with(|l| l.set(true)); } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -2332,6 +3082,14 @@ static WAIT_GATES: Mutex>>> = Mutex::new(FxHashMa /// (a list's `Reset`, with `XCL_DRED=1` on every start): the two then waited for each other. static QUEUE: Mutex> = Mutex::new(None); +/// The active state's async readback queue, reachable without locking `STATE` (`settle_readbacks*`, +/// `start_readback_thread`). Only locked briefly to clone the `Arc` (never nested with other locks). +static READBACKS: Mutex>> = Mutex::new(None); + +fn readbacks_arc() -> Option> { + READBACKS.lock().unwrap().clone() +} + fn remove_queue_fence(fences: &mut FxHashMap, raw: usize) -> Option<(F, u64)> { fences.remove(&raw) } @@ -2343,30 +3101,41 @@ fn initial_quarantine_marks(own: (F, u64), retiring: &[(F, u64)], bloc /// Remove raw queue-address state before a retired queue's final owner is released. Retired tile /// batches own fence clones independently; the cached fence drops after unlocking. pub(super) fn forget_queue(id: super::present::QueueId) { - let gone = { + let (gone, rb_submit) = { let mut state = STATE.lock().unwrap(); - state.as_mut().and_then(|state| { - state.waited.remove(&id.raw()); - remove_queue_fence(&mut state.queue_fences, id.raw()) - }) + let _held = holding(Holder::Other); + match state.as_mut() { + Some(state) => { + state.waited.remove(&id.raw()); + (remove_queue_fence(&mut state.queue_fences, id.raw()), Some(Arc::clone(&state.rb_submit))) + } + None => (None, None), + } }; + // (the copy-back fences of the queue: `RbSubmit` never nests with `STATE`; a copy back still + // in flight keeps its own clones of them) + let rb_gone = rb_submit.and_then(|sub| sub.lock().unwrap().rb_queue_fences.remove(&id.raw())); let gate = WAIT_GATES.lock().unwrap().remove(&id.raw()); drop(gone); + drop(rb_gone); drop(gate); } /// (bytes of video memory in pool heaps, of those mapped) – `XCL_ACTIVITY` pub fn pool_bytes() -> (usize, usize) { let g = lock_state(); + let _held = holding(Holder::Other); let Some(s) = g.as_ref() else { return (0, 0) }; let pools = s.pools.iter().filter(|p| p.is_some()).count() * POOL_TILES as usize * TILE; - (pools, pools.saturating_sub(s.free.len() * TILE)) + let quarantined: usize = s.quarantined.iter().map(|b| b.tiles.len()).sum(); + (pools, pools.saturating_sub((s.free.len() + s.cooling.len() + quarantined) * TILE)) } /// Active pool bytes, occupied tile bytes, retired pool bytes, and committed CPU page bytes for /// `device`, from one state lock so a pool moving to the retired list cannot be counted twice. pub(super) fn memory_bytes_for(device: usize) -> (usize, usize, usize, usize) { let g = lock_state(); + let _held = holding(Holder::Other); let Some(s) = g.as_ref() else { return (0, 0, 0, 0) }; memory_byte_counts( device, @@ -2374,7 +3143,7 @@ pub(super) fn memory_bytes_for(device: usize) -> (usize, usize, usize, usize) { s.pools.iter().filter(|p| p.is_some()).count(), s.free.len(), s.retired.len(), - s.mapped.values().map(|e| e.holes), + s.mapped.values().filter(|e| e.src == 0).map(|e| e.holes), ) } @@ -2422,7 +3191,8 @@ fn page_span(a: usize, n: usize) -> (usize, usize) { (a & !(PAGE - 1), a.saturating_add(n).saturating_add(PAGE - 1) & !(PAGE - 1)) } -/// Add the pages `[a, b)` to `early`, merged with the ranges they overlap or touch. +/// Add the pages `[a, b)` to `early` (ranges as start -> end), merged with the ranges they overlap +/// or touch. fn early_add(early: &mut BTreeMap, mut a: usize, mut b: usize) { if a >= b { return; @@ -2487,14 +3257,150 @@ fn buffer_desc(bytes: u64) -> D3D12_RESOURCE_DESC { } } +unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) -> windows::core::Result { + if lazy_asked() && !null_tiles_read_zero(dev) && !LAZY_REFUSED.swap(true, Ordering::Relaxed) { + crate::xlog_warn!("sparse windows: XCL_SPARSE_LAZY=1 is left out - on this device a tile with no video memory does not read zeros (tiled resources tier under 2)"); + } + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None)?; + let rbq = (|| -> windows::core::Result<(ID3D12CommandQueue, ID3D12Fence)> { + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; + let _ = q.SetName(windows::core::w!("xcl sparse readback queue")); + Ok((q, dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?)) + })() + .ok(); + let mut slots = Vec::with_capacity(UPLOAD_SLOTS); + for _ in 0..UPLOAD_SLOTS { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)?; + list.Close()?; + let _ = list.SetName(windows::core::w!("xcl sparse upload list")); + let _ = alloc.SetName(windows::core::w!("xcl sparse upload allocator")); + slots.push(UploadSlot { alloc, list, fence_val: 0 }); + } + let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None)?; + rb_list.Close()?; + let _ = rb_list.SetName(windows::core::w!("xcl sparse readback list")); + let _ = rb_alloc.SetName(windows::core::w!("xcl sparse readback allocator")); + let _ = queue.SetName(windows::core::w!("xcl sparse queue")); + let readbacks = Arc::new(SharedReadbacks::new(rb_fence.clone(), rbq.as_ref().map(|(_, f)| f.clone()))); + let rb_submit = Arc::new(Mutex::new(RbSubmit::new(dev.clone()))); + let generation = NEXT_STATE_GENERATION.fetch_add(1, Ordering::Relaxed); + let fence_allocation = fence.as_raw() as usize as u64; + let coordination = SparseCoordination::new(generation, fence_allocation) + .expect("valid sparse state generation and fence identity"); + Ok(State { + generation, + mapping_epoch: 0, + coordination, + dev: dev.clone(), + queue, + fence, + value: 0, + event, + rb_fence, + rb_value: 0, + rbq, + rbq_value: 0, + readbacks, + rb_submit, + windows, + pools: Vec::new(), + free: FreePools::new(), + cooling: VecDeque::new(), + retired: Vec::new(), + retire_tried: std::time::Instant::now(), + mapped: FxHashMap::default(), + pinned: FxHashMap::default(), + parked: FxHashMap::default(), + kept: FxHashMap::default(), + pending: Vec::new(), + buffers: FxHashMap::default(), + quarantined: VecDeque::new(), + queue_fences: FxHashMap::default(), + to_zero: BTreeSet::new(), + staging: None, + ring_write: 0, + ring_submitted: 0, + ring_free: 0, + inflight: VecDeque::new(), + uploads_ordered: true, + zero_buf: None, + slots, + next_slot: 0, + readback: None, + rb_alloc, + rb_list, + rb_last_fence: 0, + waited: FxHashMap::default(), + runs: BTreeMap::new(), + scratch_runs: Vec::new(), + own_pages: Vec::new(), + mirrors: FxHashMap::default(), + mirror_src: FxHashMap::default(), + src_runs: BTreeMap::new(), + sources: &SOURCES, + fill: Vec::new(), + asks: Vec::new(), + remaps: Vec::new(), + later: VecDeque::new(), + fill_pages: fill_pages(), + mirrored: 0, + mirror_cap: mirror_cap(), + refused: FxHashSet::default(), + no_memory: None, + starved: Vec::new(), + counts: MirrorCounts::default(), + diag: ViewDiag { keep: view_switches().keep, stats: view_switches().stats, ..Default::default() }, + poison: None, + retry_pages: Vec::new(), + }) +} + +/// pool heap number of the tiles of a shadowed window: they are the window's own buffer, not +/// pool tiles (never mapped, freed or pinned) +const SHADOW_POOL: u32 = u32::MAX; + +/// A committed window the GPU could not open as a heap (`real::open_uma`): `buf` in video +/// memory stands for `[base, base + size)` and is kept in step like the tiles of a sparse +/// window -- the CPU's writes (write-watch, changed 64-byte chunks) go to it before each +/// ExecuteCommandLists, GPU writes come back on Map and after the lists' memory operations. +/// All of it counts as mapped from the start: the window is committed. False: no queue for +/// the copies (the buffer then never sees the CPU's writes). +pub unsafe fn shadow_window(dev: &ID3D12Device, base: usize, size: usize, buf: &ID3D12Resource) -> bool { + let mut g = STATE.lock().unwrap(); + if g.is_none() { + // no sparse window was made (`init`): the copies still need the queue and the lists + match new_state(dev, Vec::new()) { + Ok(s) => *g = Some(s), + Err(e) => { + crate::xlog_warn!("shadowed window at {base:#x}: {e}"); + return false; + } + } + } + let Some(s) = g.as_mut() else { return false }; + s.windows.push((base, buf.clone())); + for (i, t) in (base..base + size).step_by(TILE).enumerate() { + s.mapped.insert(t, TileEntry::with_holes((SHADOW_POOL, i as u32), 0)); + } + early_add(&mut s.runs, base, base + size.next_multiple_of(TILE)); + MAPPED_GEN.fetch_add(1, Ordering::Release); + true +} + /// The sparse windows' buffers on `dev`: `(window_index, buffer_raw, gpu_va)` for each -/// sparse window in `gpu::uma` (empty: no sparse windows). +/// sparse window in `gpu::uma` and each view window, made the same way (empty: no sparse +/// windows). Nothing of a view window is mapped here: its tiles get video memory when asked for. pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { let Some(u) = crate::gpu::uma::get() else { return Vec::new() }; let mut out = Vec::new(); let mut windows = Vec::new(); for k in 0..u.shader_windows() { - if !u.is_sparse_window(k) { + if !u.is_sparse_window(k) && !u.is_view_window(k) { continue; } let (base, size) = u.window(k); @@ -2504,80 +3410,35 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { return Vec::new(); } let Some(r) = r else { return Vec::new() }; + // (a name for what a device removal reports about an address, `real::log_device_removed`) + let _ = r.SetName(&windows::core::HSTRING::from(format!("xcl memory window {k}{}", if u.is_view_window(k) { " (GPU views)" } else { "" }))); out.push((k, r.clone().into_raw() as usize, r.GetGPUVirtualAddress())); windows.push((base, r)); } if out.is_empty() { return out; } - let made = (|| -> windows::core::Result { - let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; - let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; - let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None)?; - let mut slots = Vec::with_capacity(UPLOAD_SLOTS); - for _ in 0..UPLOAD_SLOTS { - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)?; - list.Close()?; - let _ = list.SetName(windows::core::w!("xcl sparse upload list")); - let _ = alloc.SetName(windows::core::w!("xcl sparse upload allocator")); - slots.push(UploadSlot { alloc, list, fence_val: 0 }); - } - let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None)?; - rb_list.Close()?; - let _ = rb_list.SetName(windows::core::w!("xcl sparse readback list")); - let _ = rb_alloc.SetName(windows::core::w!("xcl sparse readback allocator")); - let _ = queue.SetName(windows::core::w!("xcl sparse queue")); - let generation = NEXT_STATE_GENERATION.fetch_add(1, Ordering::Relaxed); - let fence_allocation = fence.as_raw() as usize as u64; - let coordination = SparseCoordination::new(generation, fence_allocation) - .expect("valid sparse state generation and fence identity"); - Ok(State { - generation, - mapping_epoch: 0, - coordination, - dev: dev.clone(), - queue, - fence, - value: 0, - event, - rb_fence, - rb_value: 0, - windows, - pools: Vec::new(), - free: Vec::new(), - retired: Vec::new(), - mapped: FxHashMap::default(), - pinned: FxHashMap::default(), - parked: FxHashMap::default(), - quarantined: VecDeque::new(), - queue_fences: FxHashMap::default(), - buffers: FxHashMap::default(), - to_zero: Vec::new(), - staging: None, - ring_write: 0, - ring_submitted: 0, - ring_free: 0, - inflight: VecDeque::new(), - uploads_ordered: true, - zero_buf: None, - slots, - next_slot: 0, - readback: None, - rb_alloc, - rb_list, - rb_last_fence: 0, - waited: FxHashMap::default(), - runs: None, - scratch_runs: Vec::new(), - retry_pages: Vec::new(), - }) - })(); + let made = new_state(dev, windows); match made { - Ok(s) => { - crate::xlog_info!("D3D12.X: {} sparse window(s) for the title's own memory (tiled buffers on video memory)", out.len()); + Ok(mut s) => { + let views = out.iter().filter(|w| u.is_view_window(w.0)).count(); + crate::xlog_info!("D3D12.X: {} sparse window(s) for the title's own memory and {views} for GPU views of it (tiled buffers on video memory)", out.len() - views); + let sw = view_switches(); + if let Some(pattern) = sw.poison { + s.poison_windows(pattern); + } + if sw.stats { + crate::xlog_info!( + "D3D12.X: GPU-view diagnostics: keep {}, poison {}, a line every 2 s", + if sw.keep { format!("on ({} tiles at most, XCL_MIRROR_MB)", s.mirror_cap) } else { "off".into() }, + match (sw.poison, s.poison.is_some()) { + (Some(p), true) => format!("{p:#010x}"), + (Some(_), false) => "failed (zeros)".into(), + (None, _) => "off".into(), + } + ); + start_view_stats(); + } // a state this replaces (the windows set up again) goes after the lock: the release of // its last buffers reaches `forget_buffer`, which takes the lock (#344) // (the queue first: `queue()` never answers with one older than the state's) @@ -2585,10 +3446,12 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { let _upload_lifetime = UPLOAD_STATE_LIFETIME.write().unwrap(); let _uploads = UPLOAD_GATE.lock().unwrap(); let old_queue = QUEUE.lock().unwrap().replace(s.queue.clone()); + let _old_rb = READBACKS.lock().unwrap().replace(Arc::clone(&s.readbacks)); let mut state = STATE.lock().unwrap(); let old = state.replace(s); let s = state.as_mut().unwrap(); for (a, b) in std::mem::take(&mut *EARLY.lock().unwrap()) { + super::title_textures::mark_hot(a, b - a); s.commit_range(a, b - a); } for (a, b) in std::mem::take(&mut *EARLY_NOT_RW.lock().unwrap()) { @@ -2622,6 +3485,7 @@ impl State { /// Capture every identity used by unlocked sparse planning while this State is authoritative. /// The returned value owns hashes and mapping metadata; it retains no title-memory borrow. + /// (A tile over a CPU view, `TileEntry::src`, is read at its CPU address: its own is no memory.) unsafe fn upload_page_observation(&self, page: usize) -> Option { let tile = page & !(TILE - 1); let entry = self.mapped.get(&tile)?; @@ -2633,7 +3497,7 @@ impl State { ZERO_HASHES } else { let mut bytes = [0u8; PAGE]; - if !crate::hle::dstorage::read_own(page, bytes.as_mut_ptr(), bytes.len()) { + if !crate::hle::dstorage::read_own(entry.cpu(tile) + index * PAGE, bytes.as_mut_ptr(), bytes.len()) { return None; } std::array::from_fn(|chunk| { @@ -2644,18 +3508,22 @@ impl State { Some(UploadPageObservation { page, pool: entry.pool, hole, sent, source }) } + /// A pool tile (true: used before, to be cleared). One freed less than `COOL` ago, or one + /// still `quarantined`, is not taken: a retired pool is taken back or a heap made instead. + /// (Parked tiles are not flushed for it: freed now, they would wait and cool all the same.) unsafe fn take_tile(&mut self) -> Option<((u32, u32), bool)> { - self.drain_quarantined(); - if self.free.is_empty() && self.flush_parked() { - self.drain_quarantined(); + #[cfg(test)] + if tests::NO_TILES.with(|c| c.get()) { + return None; } - if let Some(t) = self.free.pop() { + self.drain_quarantined(); + if let Some(t) = reuse_tile(&mut self.free, &mut self.cooling, std::time::Instant::now()) { return Some((t, true)); } // a pool retired a moment ago (its last tile came free) is taken back before a new // heap is made: freeing and allocating a tile in turn made a new pool each time, // up to 18 GB of retired heaps in 2 s (#913). Its tiles are reused as freed tiles are - // (zeroed), so this is no less safe than reusing a tile of a pool in use. + // (zeroed), and they all cooled before it was retired. if let Some((heap, _, _)) = self.retired.pop() { let h = self.add_pool(heap); return Some(((h, 0), true)); @@ -2666,12 +3534,16 @@ impl State { Alignment: 0, Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES, }; + // (a heap takes its time, with the state locked: what waits for its mapping goes first, a + // CPU signal that asks meanwhile gives up after 2 ms) + self.flush_pending(); let mut heap: Option = None; if let Err(e) = super::title_textures::own_work(|| self.dev.CreateHeap(&desc, &mut heap)) { crate::xlog_warn!("sparse windows: no video memory for more tiles ({e})"); return None; } let heap = heap?; + let _ = heap.SetName(windows::core::w!("xcl sparse tile pool")); let h = self.add_pool(heap); Some(((h, 0), false)) } @@ -2689,30 +3561,25 @@ impl State { self.pools.len() as u32 - 1 } }; - self.free.extend((1..POOL_TILES).rev().map(|t| (h, t))); + self.free.add_heap(h); h } - /// Pools whose every tile is free again go (their video memory – and as much of the - /// system's commit: a retail game's homes of physical pages left 0.75 GB of pools for - /// 0.29 GB of tiles in use). Call after their tiles are unmapped and signalled. + /// Pools whose every tile is free again (cooled, `COOL`) go (their video memory – and as much + /// of the system's commit: a retail game's homes of physical pages left 0.75 GB of pools for + /// 0.29 GB of tiles in use). Call after their tiles are unmapped and signalled. `done`: the + /// value the sparse queue's fence has reached (a retired heap goes once it is past its mark). fn retire_free_pools_with(&mut self, done: u64) { let now = std::time::Instant::now(); + self.retire_tried = now; self.retired.retain(|(_, v, at)| !(done >= *v && now.duration_since(*at).as_secs() >= 2)); - if self.free.len() < POOL_TILES as usize { - return; - } - let mut count = vec![0u32; self.pools.len()]; - for &(h, _) in &self.free { - count[h as usize] += 1; - } - // (a flag a pool: a title's world load frees hundreds of pools' worth of tiles at once) - let gone: Vec = (0..count.len()).map(|h| count[h] == POOL_TILES && self.pools[h].is_some()).collect(); - if !gone.contains(&true) { + self.free.drain_cooling(&mut self.cooling, now); + let gone: Vec = free_heaps(&self.free, &self.cooling, self.pools.len(), now).into_iter().filter(|&h| self.pools[h].is_some()).collect(); + if gone.is_empty() { return; } - self.free.retain(|&(h, _)| !gone[h as usize]); - for h in (0..gone.len()).filter(|&h| gone[h]) { + for h in gone { + self.free.clear_heap(h); if let Some(heap) = self.pools[h].take() { self.retired.push((heap, self.value, now)); } @@ -2720,7 +3587,7 @@ impl State { } fn retire_free_pools(&mut self) { - self.retire_free_pools_with(unsafe { self.fence.GetCompletedValue() }); + self.retire_free_pools_with(unsafe { super::real::fence_completed(&self.fence) }); } /// Map `tiles` (tile addresses) of `res` (starting at `res_base`) onto pool tiles, @@ -2730,9 +3597,11 @@ impl State { return; } let mut by_heap: FxHashMap> = FxHashMap::default(); + debug_assert!(tiles.iter().all(|t| t.1 != LAZY), "a tile with no video memory is mapped nowhere"); for &(a, (h, t)) in tiles { by_heap.entry(h).or_default().push((((a - res_base) / TILE) as u32, t)); } + count_tile_calls(res_base, false, by_heap.len(), tiles.len()); for (h, mut pairs) in by_heap { pairs.sort_unstable_by_key(|&(x, _)| x); let mut coords: Vec = Vec::with_capacity(pairs.len()); @@ -2784,6 +3653,8 @@ impl State { let mut regions: Vec = Vec::with_capacity(xs.len()); let mut flags: Vec = Vec::with_capacity(xs.len()); let mut counts: Vec = Vec::with_capacity(xs.len()); + // (`XCL_VIEW_POISON`: onto the poison tile, every tile of a run on its one tile) + let poison = self.poison.as_ref().map(|p| &p.heap); let mut i = 0; while i < xs.len() { let x0 = xs[i]; @@ -2793,45 +3664,201 @@ impl State { } coords.push(D3D12_TILED_RESOURCE_COORDINATE { X: x0, ..Default::default() }); regions.push(D3D12_TILE_REGION_SIZE { NumTiles: run, UseBox: false.into(), ..Default::default() }); - flags.push(D3D12_TILE_RANGE_FLAG_NULL); + flags.push(if poison.is_some() { D3D12_TILE_RANGE_FLAG_REUSE_SINGLE_TILE } else { D3D12_TILE_RANGE_FLAG_NULL }); counts.push(run); i += run as usize; } + let offsets = vec![0u32; if poison.is_some() { counts.len() } else { 0 }]; + count_tile_calls(res_base, true, 1, tiles.len()); self.queue.UpdateTileMappings( res, coords.len() as u32, Some(coords.as_ptr()), Some(regions.as_ptr()), - None, + poison, flags.len() as u32, Some(flags.as_ptr()), - None, + poison.map(|_| offsets.as_ptr()), Some(counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE, ); } + /// `XCL_VIEW_POISON`: every tile of `res` (`tiles` of them) onto the poison tile, before the + /// tiles with video memory are mapped over it. + unsafe fn poison_all(&self, res: &ID3D12Resource, tiles: u32) { + let Some(p) = &self.poison else { return }; + if tiles == 0 { + return; + } + let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let region = D3D12_TILE_REGION_SIZE { NumTiles: tiles, UseBox: false.into(), ..Default::default() }; + let (flag, off) = (D3D12_TILE_RANGE_FLAG_REUSE_SINGLE_TILE, 0u32); + self.queue.UpdateTileMappings(res, 1, Some(&coord), Some(®ion), &p.heap, 1, Some(&flag), Some(&off), Some(&tiles), D3D12_TILE_MAPPING_FLAG_NONE); + } + + /// `XCL_VIEW_POISON`: a tile of video memory filled with `pattern`, and every tile of the + /// windows mapped onto it (one call each, before any has video memory of its own); unmapped + /// tiles go back to it from here on (`unmap_tiles`), and a buffer placed in a window starts + /// on it (`place_buffer`). Many tiles of reserved buffers on one tile of a heap is what + /// `REUSE_SINGLE_TILE` is for. Logged and left off when the tile cannot be made. + unsafe fn poison_windows(&mut self, pattern: u32) { + let made = (|| -> windows::core::Result { + let desc = D3D12_HEAP_DESC { + SizeInBytes: TILE as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES, + }; + let mut heap: Option = None; + self.dev.CreateHeap(&desc, &mut heap)?; + let heap = heap.ok_or_else(|| windows::core::Error::from(windows::Win32::Foundation::E_FAIL))?; + let _ = heap.SetName(windows::core::w!("xcl poison tile")); + let mut d = buffer_desc(TILE as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + let mut buf: Option = None; + self.dev.CreatePlacedResource(&heap, 0, &d, D3D12_RESOURCE_STATE_COMMON, None, &mut buf)?; + let mut src: Option = None; + self.dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut src)?; + let (Some(buf), Some(src)) = (buf, src) else { return Err(windows::Win32::Foundation::E_FAIL.into()) }; + let mut p = std::ptr::null_mut(); + src.Map(0, None, Some(&mut p))?; + std::slice::from_raw_parts_mut(p as *mut u32, TILE / 4).fill(pattern); + src.Unmap(0, None); + Ok(Poison { heap, buf, src, at: std::time::Instant::now() }) + })(); + match made { + Ok(p) => self.poison = Some(p), + Err(e) => { + crate::xlog_warn!("XCL_VIEW_POISON: no poison tile ({e}) – tiles without video memory read zeros"); + return; + } + } + let windows: Vec = self.windows.iter().map(|w| w.1.clone()).collect(); + let mut tiles = 0u64; + for r in &windows { + let n = (r.GetDesc().Width as usize).div_ceil(TILE) as u32; + self.poison_all(r, n); + tiles += n as u64; + } + self.refresh_poison(); + crate::xlog_info!("XCL_VIEW_POISON: {tiles} tiles of {} window(s) show {pattern:#010x} where they have no video memory", windows.len()); + } + + /// The poison tile filled with its pattern again (at most once every 16 ms: at a submit), + /// on the sparse queue the title's queues wait for. + unsafe fn refresh_poison(&mut self) { + let Some((buf, src)) = self.poison.as_mut().map(|p| { + p.at = std::time::Instant::now(); + (p.buf.clone(), p.src.clone()) + }) else { + return; + }; + // (no slot free without a wait, or none could be reset: the pattern goes back at a later submit) + let BeginSlot::Ready(idx) = self.begin_slot() else { return }; + self.slots[idx].list.CopyBufferRegion(&buf, 0, &src, 0, TILE as u64); + let _ = self.submit_slot(idx); + } + + /// `ensure_mapped` for a commit with `lazy_commits`: the tiles of `[a, a + n)` are listed + /// (watched, scanned, their holes kept) with no video memory (`LAZY`). A tile still mapped + /// from before (parked, or kept for a buffer) is taken back as it is. + unsafe fn ensure_listed(&mut self, a: usize, n: usize) { + let end = a.saturating_add(n); + let mut t = a & !(TILE - 1); + let mut new = false; + while t < end { + if !self.mapped.contains_key(&t) && !self.mirror_src.contains_key(&t) && self.window_index(t).is_some() { + if self.parked.contains_key(&t) || self.kept.contains_key(&t) { + self.ensure_mapped(t, TILE, |_| (0xFFFF, 0)); + } else { + self.mapped.insert(t, TileEntry::with_holes(LAZY, 0xFFFF)); + early_add(&mut self.runs, t, t + TILE); + new = true; + } + } + match t.checked_add(TILE) { + Some(next) => t = next, + None => break, + } + } + if new { + MAPPED_GEN.fetch_add(1, Ordering::Release); + } + } + + /// The `LAZY` tiles of `[a, a + n)` get their video memory now (their mapping is pending, + /// as `ensure_mapped` leaves it): (the tiles that did, those left without). A tile used + /// before goes to `reused` as the run to clear, which the caller sees to before anything is + /// written there. A moment after no video memory was found (`no_memory`) only tiles at hand + /// are taken, as in `new_mirror`, but with `force` (a placed buffer maps its tiles once). + unsafe fn materialize(&mut self, a: usize, n: usize, force: bool, reused: &mut Vec<(usize, usize)>) -> (usize, usize) { + let end = a.saturating_add(n); + let mut t = a & !(TILE - 1); + let (mut got, mut left) = (0, 0); + while t < end { + if self.mapped.get(&t).is_some_and(|e| e.pool == LAZY) { + let at_hand = !self.free.is_empty() || cooled(&self.cooling, std::time::Instant::now()) || !self.retired.is_empty(); + let wait = left > 0 || (!force && self.short_of_memory() && !at_hand); + match if wait { None } else { self.take_tile() } { + Some((tile, used)) => { + if let Some(e) = self.mapped.get_mut(&t) { + e.pool = tile; + } + if used { + reused.push((t, TILE)); + } + self.pending.push(t); + got += 1; + } + None => { + if !wait { + self.no_memory = Some(std::time::Instant::now()); + } + left += 1; + } + } + } + match t.checked_add(TILE) { + Some(next) => t = next, + None => break, + } + } + (got, left) + } + + /// The title's lists about to be submitted write `ranges` on the GPU (`will_write`): their + /// tiles listed with no video memory get it, cleared at this submit before the lists run. + unsafe fn give_memory(&mut self, ranges: &[(usize, usize)]) { + let mut reused = Vec::new(); + for &(a, n) in ranges { + self.materialize(a, n, false, &mut reused); + } + self.to_zero.extend(reused); + } + /// tiles of `[a, a + n)` get video memory (mapped in their window); `initial_state` supplies - /// the initial `(holes, untrusted protection)` masks for each newly mapped 64 KiB tile. + /// the initial `(holes, untrusted protection)` masks for each newly mapped 64 KiB tile. Tiles + /// over a CPU view (`mirror_src`) are left to `new_mirror`. unsafe fn ensure_mapped(&mut self, a: usize, n: usize, mut initial_state: impl FnMut(usize) -> (u16, u16)) { if n == 0 { return; } let first = a & !(TILE - 1); let end = a.saturating_add(n); - let mut new: Vec<(usize, (u32, u32))> = Vec::new(); + let mut new = false; let mut unparked = false; let mut t = first; while t < end { - if !self.mapped.contains_key(&t) && self.window_index(t).is_some() { + if !self.mapped.contains_key(&t) && !self.mirror_src.contains_key(&t) && self.window_index(t).is_some() { // still mapped there: no new mapping, what it held is cleared - if let Some(tile) = self.parked.remove(&t) { + if let Some(tile) = self.parked.remove(&t).or_else(|| self.kept.remove(&t)) { let (holes, not_rw) = initial_state(t); let mut entry = TileEntry::with_holes(tile, holes); entry.not_rw = not_rw; self.mapped.insert(t, entry); - self.runs = None; - self.to_zero.push((t, TILE)); + early_add(&mut self.runs, t, t + TILE); + self.to_zero.insert((t, TILE)); unparked = true; } else { let Some((tile, reused)) = self.take_tile() else { break }; @@ -2839,11 +3866,12 @@ impl State { let mut entry = TileEntry::with_holes(tile, holes); entry.not_rw = not_rw; self.mapped.insert(t, entry); - self.runs = None; + early_add(&mut self.runs, t, t + TILE); if reused { - self.to_zero.push((t, TILE)); + self.to_zero.insert((t, TILE)); } - new.push((t, tile)); + self.pending.push(t); + new = true; } } match t.checked_add(TILE) { @@ -2851,22 +3879,43 @@ impl State { None => break, } } - if new.is_empty() { - if unparked { - MAPPED_GEN.fetch_add(1, Ordering::Release); - } + if new || unparked { + MAPPED_GEN.fetch_add(1, Ordering::Release); + } + if self.pending.len() >= PENDING_MAX { + self.flush_pending(); + } else if !self.pending.is_empty() { + pending_soon(); + } + } + + /// The pending tiles (`pending`) mapped onto their pool tiles, one call per window, then the + /// fence signalled (title queues wait for it in `before_execute`). An address decommitted + /// since has no `mapped` entry and is skipped; one committed again maps its current tile. One + /// decommitted and parked (or kept for a placed buffer) stays pending: its mapping was never + /// sent, and a commit that takes it back from there sends none. + unsafe fn flush_pending(&mut self) { + if self.pending.is_empty() { return; } - MAPPED_GEN.fetch_add(1, Ordering::Release); - // per window + let mut addrs = std::mem::take(&mut self.pending); + addrs.sort_unstable(); + addrs.dedup(); let mut by_window: FxHashMap> = FxHashMap::default(); - for x in new { - if let Some(wi) = self.window_index(x.0) { - by_window.entry(wi).or_default().push(x); + for t in addrs { + if let (Some(e), Some(wi)) = (self.mapped.get(&t).filter(|e| e.pool != LAZY), self.window_index(t)) { + by_window.entry(wi).or_default().push((t, e.pool)); + } else if self.parked.contains_key(&t) || self.kept.contains_key(&t) { + self.pending.push(t); } } + if by_window.is_empty() { + return; + } for (wi, tiles) in by_window { let (b, r) = (self.windows[wi].0, self.windows[wi].1.clone()); + TILE_WORK[0].fetch_add(tiles.len() as u64, Ordering::Relaxed); + TILE_WORK[1].fetch_add(1, Ordering::Relaxed); self.map_tiles(&r, b, &tiles); } self.signal(); @@ -2884,18 +3933,29 @@ impl State { } unsafe fn wait_for_ms(&self, target: u64, timeout_ms: u32) -> bool { - if target == 0 || self.fence.GetCompletedValue() >= target { + if target == 0 || super::real::fence_completed(&self.fence) >= target { return true; } - let _ = self.fence.SetEventOnCompletion(target, self.event); + // The event is one for all waits here, and a wait that gave up leaves its registration + // behind: that one sets the event later, and the next wait would return at once with the + // queue not there (10 such "after 5 s" lines within 100 ms in one run, each followed by a + // Reset of an allocator the GPU was still in). So: until the fence says so, or `timeout_ms`. + let t0 = std::time::Instant::now(); let wait_stall = crate::stall::span(crate::stall::StallKind::GpuWait); - windows::Win32::System::Threading::WaitForSingleObject(self.event, timeout_ms); - drop(wait_stall); - if self.fence.GetCompletedValue() < target { - crate::xlog_warn!("sparse: the queue has not reached fence value {target} after {timeout_ms} ms (at {})", self.fence.GetCompletedValue()); - return false; + loop { + let _ = self.fence.SetEventOnCompletion(target, self.event); + let left = (timeout_ms as u64).saturating_sub(t0.elapsed().as_millis() as u64).max(1) as u32; + windows::Win32::System::Threading::WaitForSingleObject(self.event, left); + if super::real::fence_completed(&self.fence) >= target { + return true; + } + if t0.elapsed().as_millis() >= timeout_ms as u128 { + break; + } } - true + drop(wait_stall); + crate::xlog_warn!("sparse: the queue has not reached fence value {target} after {timeout_ms} ms (at {})", super::real::fence_completed(&self.fence)); + false } #[inline] @@ -2903,7 +3963,7 @@ impl State { if self.inflight.is_empty() { return; } - let completed = self.fence.GetCompletedValue(); + let completed = super::real::fence_completed(&self.fence); while let Some(&(fv, end_pos)) = self.inflight.front() { if fv <= completed { self.ring_free = end_pos; @@ -2917,7 +3977,7 @@ impl State { /// Acquire the next upload command slot, or return a ticket to wait for without `STATE`. unsafe fn begin_slot(&mut self) -> BeginSlot { let next_slot = self.next_slot; - let completed = self.fence.GetCompletedValue(); + let completed = super::real::fence_completed(&self.fence); let mut waiting = None; let mut ready = None; for offset in 0..self.slots.len() { @@ -2982,6 +4042,8 @@ impl State { /// Close and submit upload slot `idx` asynchronously (NO CPU wait — callers order GPU work /// via `queue.Wait(&self.fence, self.value)`). unsafe fn submit_slot(&mut self, idx: usize) -> SubmitResult { + // the copies on `queue` see every tile mapped (`pending` goes first on the same queue) + self.flush_pending(); if self.slots[idx].list.Close().is_err() { return SubmitResult::NotSubmitted; } @@ -3101,6 +4163,38 @@ impl State { } } + /// Update `sent` hashes for all 64-byte chunks overlapping `[va, va + len)` so the CPU + /// copy-back we just wrote to `va` is not re-uploaded by the next `before_execute`. + unsafe fn sync_sent_range(&mut self, va: usize, len: usize) { + if len == 0 { + return; + } + let mut pg = va & !(PAGE - 1); + let end = va + len; + while pg < end { + let t = pg & !(TILE - 1); + let tile_end = (t + TILE).min(end); + if let Some(entry) = self.mapped.get_mut(&t) { + let cpu = entry.cpu(t); + let mut p = pg; + while p < tile_end { + let idx = (p - t) / PAGE; + if entry.holes & (1u16 << idx) == 0 { + let bytes = std::slice::from_raw_parts((cpu + (p - t)) as *const u8, PAGE); + let sent = entry.sent[idx].get_or_insert_with(|| Box::new(ZERO_HASHES)); + let lo = va.saturating_sub(p) / CHUNK; + let hi = (end.min(p + PAGE) - p).div_ceil(CHUNK).min(CHUNKS); + for k in lo..hi { + sent[k] = chunk_hash(&bytes[k * CHUNK..(k + 1) * CHUNK]); + } + } + p += PAGE; + } + } + pg = tile_end; + } + } + fn publish_hashes(&mut self, updates: &[HashUpdate]) { publish_hash_updates(&mut self.mapped, updates); } @@ -3129,15 +4223,209 @@ impl State { } } + /// Whether nobody wrote the 64-byte chunk holding `va` since it was last sent to the GPU (its + /// page has video memory and its hash is the one known). + unsafe fn chunk_clean(&self, va: usize) -> bool { + let pg = va & !(PAGE - 1); + let t = pg & !(TILE - 1); + let idx = (pg - t) / PAGE; + let Some(entry) = self.mapped.get(&t).filter(|e| e.pool != LAZY) else { return false }; + if entry.holes & (1u16 << idx) != 0 { + return false; + } + let page = std::slice::from_raw_parts((entry.cpu(t) + (pg - t)) as *const u8, PAGE); + let k = (va - pg) / CHUNK; + let h = chunk_hash(&page[k * CHUNK..(k + 1) * CHUNK]); + entry.sent[idx].as_deref().map_or(h == ZERO_HASH, |sent| h == sent[k]) + } + + /// `len` bytes from readback memory `p + off` into the title's `dst` (committed pages only, in + /// one tile), a window address: they land at its tile's CPU address, if the tile's memory is + /// what it was when the copy was recorded (`gen`, `TileEntry::gen`). One shown over another + /// CPU view since, or with a page decommitted (and maybe committed again), is left out: what + /// the GPU had there before is not that memory's. (A tile of the window's own lands as before.) + /// `gpu_written`: the bytes are what the GPU's commands wrote (`land_page`): they land in a + /// chunk the CPU changed too. + unsafe fn copy_back(&mut self, p: *mut u8, dst: usize, off: usize, len: usize, gen: u32, gpu_written: bool) { + let mut at = dst; + let mut src_off = off; + let end = dst + len; + while at < end { + let pg = at & !(PAGE - 1); + let t = pg & !(TILE - 1); + let idx = (pg - t) / PAGE; + let step = (pg + PAGE).min(end) - at; + // (a tile with no video memory holds nothing the GPU wrote) + if let Some(entry) = self.mapped.get_mut(&t).filter(|e| e.pool != LAZY) { + let here = entry.cpu(t); + if entry.holes & (1u16 << idx) == 0 && entry.gen == gen { + let page = std::slice::from_raw_parts_mut((here + (pg - t)) as *mut u8, PAGE); + let source = std::slice::from_raw_parts(p.add(src_off), step); + let wrote = land_page(&mut entry.sent[idx], page, at - pg, source, gpu_written); + if wrote && self.own_pages.len() < OWN_PAGES_MAX && super::look_stats::deep() { + self.own_pages.push(here + (pg - t)); + } + } + } + at += step; + src_off += step; + } + } + + /// An immediate the GPU wrote at `va` (`bytes`: 4 or 8), into the title's memory there (at the + /// tile's CPU address), if it is the memory it was when the immediate was recorded (`gen`, as + /// in `copy_back`) + unsafe fn store_imm(&mut self, va: usize, value: u64, bytes: u8, gen: u32) { + let pg = va & !(PAGE - 1); + let t = pg & !(TILE - 1); + let Some(cpu) = self.mapped.get(&t).filter(|e| e.holes & (1u16 << ((pg - t) / PAGE)) == 0 && e.gen == gen).map(|e| e.cpu(t) + (va - t)) else { return }; + // (a chunk the title's CPU wrote since it was last sent keeps its state: it goes up with the + // next look, with this value in it) + let clean = self.chunk_clean(va); + match bytes & 0x7f { + 4 => (*(cpu as *const std::sync::atomic::AtomicU32)).store(value as u32, Ordering::Release), + 8 if bytes & IMM_KEEP_MAX != 0 => { + if (*(cpu as *const AtomicU64)).fetch_max(value, Ordering::AcqRel) > value { + static LATE: AtomicU64 = AtomicU64::new(0); + let k = LATE.fetch_add(1, Ordering::Relaxed) + 1; + if k.is_power_of_two() { + crate::xlog_info!("sparse: {k} immediates so far left out – their cell is a counter that held a later value ({value:#x} for {va:#x})"); + } + return; + } + } + 8 => (*(cpu as *const AtomicU64)).store(value, Ordering::Release), + _ => return, + } + if self.own_pages.len() < OWN_PAGES_MAX && super::look_stats::deep() { + self.own_pages.push(cpu & !(PAGE - 1)); + } + if clean { + self.sync_sent_range(va, (bytes & 0x7f) as usize); + } + } + + /// A copy back's list and a readback buffer of at least `need` bytes (reused when one fits). + #[cfg(test)] + unsafe fn rb_job(&self, need: usize, ty: D3D12_COMMAND_LIST_TYPE) -> Option { + take_or_alloc_rb_job(&self.dev, &self.readbacks, need, ty) + } + + /// Pop every finished `imm_job` and `rb_job` from `self.readbacks` in strict ascending `seq` + /// order, land them into CPU memory under `&mut self` (`STATE`), recycle finished `RbJob`s up + /// to cap 32, and return any excess `RbJob`s so the caller drops them outside all locks. + unsafe fn land_finished_readbacks(&mut self) -> Vec { + let ready: Vec = { + let mut rq = self.readbacks.lock().unwrap(); + let rbq_done = rq.rbq_done.clone(); + let mut out = Vec::new(); + let mut i = 0; + let mut k = 0; + loop { + // the immediates of submissions before the next copy back first + while k < rq.imm_jobs.len() && rq.rb_jobs.get(i).is_none_or(|j| rq.imm_jobs[k].seq < j.seq) { + if super::real::fence_completed(&rq.imm_jobs[k].fence) < rq.imm_jobs[k].value { + k += 1; + continue; + } + let Some(job) = rq.imm_jobs.remove(k) else { break }; + out.push(ReadyJob::Imm(job)); + } + if i >= rq.rb_jobs.len() { + break; + } + let done = { + let j = &rq.rb_jobs[i]; + match (&j.fences, &rbq_done) { + (Some((_, b)), _) => super::real::fence_completed(b) >= j.done_v, + (None, Some(d)) => super::real::fence_completed(d) >= j.done_v, + (None, None) => false, + } + }; + if !done { + i += 1; + continue; + } + let Some(job) = rq.rb_jobs.remove(i) else { break }; + out.push(ReadyJob::Rb(job)); + } + if !out.is_empty() { + rq.landing += out.len(); + } + out + }; + if ready.is_empty() { + return Vec::new(); + } + let landed_n = ready.len(); + let mut recycled: Vec = Vec::new(); + for item in ready { + match item { + ReadyJob::Imm(job) => { + for &(va, value, bytes, gen) in &job.writes { + self.store_imm(va, value, bytes, gen); + } + RB_PENDING.fetch_sub(1, Ordering::Release); + } + ReadyJob::Rb(mut job) => { + let copies = std::mem::take(&mut job.copies); + for &(dst, off, len, gen) in &copies { + // (the lists' own GPU writes, `readback_after_execute`) + self.copy_back(job.ptr, dst, off, len, gen, true); + } + TILE_WORK[3].fetch_add(copies.iter().map(|c| c.2 as u64).sum(), Ordering::Relaxed); + RB_PENDING.fetch_sub(1, Ordering::Release); + job.copies = copies; + job.copies.clear(); + recycled.push(job); + } + } + } + let mut excess = Vec::new(); + { + let mut rq = self.readbacks.lock().unwrap(); + rq.landing -= landed_n; + for job in recycled { + // (a burst of copies back does not keep its buffers for good: each is up to 16 MiB of + // host memory; excess jobs drop outside all locks) + if rq.rb_pool.len() < 32 { + rq.rb_pool.push(job); + } else { + excess.push(job); + } + } + } + excess + } + + /// Land submitted copies back in the title's memory as far as `how` says (test helper on a + /// standalone `State` without global `STATE`). + #[cfg(test)] + unsafe fn drain_readbacks(&mut self, how: Drain) -> Vec { + self.drain_readbacks_spin(how, 2000) + } + + #[cfg(test)] + unsafe fn drain_readbacks_spin(&mut self, how: Drain, spin_us: u128) -> Vec { + if wait_and_check_ready(&self.readbacks, how, spin_us, None) != ReadyCheck::LandNow { + return Vec::new(); + } + self.land_finished_readbacks() + } + /// Copy `ranges` (address, bytes) from sparse VRAM back into the CPU view and refresh /// `sent` hashes. Caller has already ordered `self.queue` after any GPU writes if needed. /// `gpu_written`: the ranges are bytes the GPU's commands wrote (`land_page`). - unsafe fn readback_ranges(&mut self, ranges: &[(usize, usize)], gpu_written: bool) { - let Some((rb, p)) = self.readback_buf() else { return }; - let mut pending: Vec<(usize, usize, usize)> = Vec::new(); // (va, rb_off, chunk) + /// Returns any excess recycled `RbJob`s for the caller to drop outside `STATE`. + unsafe fn readback_ranges(&mut self, ranges: &[(usize, usize)], gpu_written: bool) -> Vec { + self.flush_pending(); + // copies back of earlier submissions first: their data is older than this one's + let excess = self.land_finished_readbacks(); + let Some((rb, p)) = self.readback_buf() else { return excess }; + let mut pending: Vec<(usize, usize, usize, u32)> = Vec::new(); // (va, rb_off, chunk, gen of its tile) let mut used = 0usize; let mut open = false; - let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize)>, used: &mut usize, p: *mut u8| -> bool { + let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize, u32)>, used: &mut usize, p: *mut u8| -> bool { if *open { *open = false; let Ok(()) = s.rb_list.Close() else { return false }; @@ -3154,26 +4442,8 @@ impl State { } s.reclaim_ring(); } - for &(dst, off, len) in pending.iter() { - // copy only committed (non-hole) bytes - let mut at = dst; - let mut src_off = off; - let end = dst + len; - while at < end { - let pg = at & !(PAGE - 1); - let t = pg & !(TILE - 1); - let idx = (pg - t) / PAGE; - let step = (pg + PAGE).min(end) - at; - if let Some(entry) = s.mapped.get_mut(&t) { - if entry.holes & (1u16 << idx) == 0 { - let page = std::slice::from_raw_parts_mut(pg as *mut u8, PAGE); - let source = std::slice::from_raw_parts(p.add(src_off), step); - land_page(&mut entry.sent[idx], page, at - pg, source, gpu_written); - } - } - at += step; - src_off += step; - } + for &(dst, off, len, gen) in pending.iter() { + s.copy_back(p, dst, off, len, gen, gpu_written); } pending.clear(); *used = 0; @@ -3190,25 +4460,27 @@ impl State { let Some(wi) = self.window_index(cur) else { break }; let b = self.windows[wi].0; let to_tile_end = (tile + TILE) - cur; - if !self.mapped.contains_key(&tile) { + // (a tile with no video memory has nothing to copy back: the GPU's writes there went + // nowhere, and a tile it got now would hold what another address left in it) + let Some(gen) = self.mapped.get(&tile).filter(|e| e.pool != LAZY).map(|e| e.gen) else { done += (n - done).min(to_tile_end); continue; - } + }; if used == READBACK_STAGING { if !flush_and_copy(self, &mut open, &mut pending, &mut used, p) { - return; + return excess; } } let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; let chunk = (n - done).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); if !open { if !self.wait_for(self.rb_last_fence) || self.rb_alloc.Reset().is_err() || self.rb_list.Reset(&self.rb_alloc, None).is_err() { - return; + return excess; } open = true; } self.rb_list.CopyBufferRegion(&rb, used as u64, &self.windows[wi].1, (cur - b) as u64, chunk as u64); - pending.push((cur, used, chunk)); + pending.push((cur, used, chunk, gen)); used += chunk; done += chunk; } @@ -3216,11 +4488,20 @@ impl State { if open { let _ = flush_and_copy(self, &mut open, &mut pending, &mut used, p); } + excess } /// Asynchronously zero `runs` (address, bytes) in sparse VRAM using the pre-zeroed `zero_buf` /// (zero staging ring bytes consumed, zero CPU stall). unsafe fn upload_zeros(&mut self, runs: &[(usize, usize)]) -> UploadStep { + // (a tile with no video memory reads zeros already; a run goes on into its neighbours) + let kept: Vec<(usize, usize)>; + let runs = if lazy_commits() { + kept = runs_where(runs, |t| self.mapped.get(&t).is_none_or(|e| e.pool != LAZY)); + &kept[..] + } else { + runs + }; if runs.is_empty() { return UploadStep::Done(PreparationOutcome::Ready); } @@ -3275,13 +4556,77 @@ impl State { if !self.uploads_ordered { return UploadStep::Done(PreparationOutcome::ExecutedUntracked); } + // the CPU's first bytes for a tile listed with no video memory: it gets it now, and its + // mapping is sent before the copies that fill it. One used before is cleared first, here + // and not at the next submit (`to_zero`), which would clear these bytes with it + let kept: Vec<(usize, usize)>; + let mut runs = runs; + if lazy_commits() { + let mut reused = Vec::new(); + let (mut got, mut left) = (0, 0); + for &(a, n) in runs { + let (g, l) = self.materialize(a, n, false, &mut reused); + got += g; + left += l; + } + if got > 0 { + self.flush_pending(); + match self.upload_zeros(&reused) { + UploadStep::Done(PreparationOutcome::Ready) => {} + step => { + // not cleared now: cleared before anything else at the next try + // (`to_zero`), and all of their bytes go up after that (no hashes known) + for &(t, n) in &reused { + self.clear_sent_range(t, n); + } + self.to_zero.extend(reused.iter().copied()); + return step; + } + } + } + // none to be had: the bytes are not sent, whatever the scan noted, and all of the tile + // goes up once there is some (`starved`) + if left > 0 { + let mut starved: Vec = Vec::new(); + kept = runs_where(runs, |t| { + let has = self.mapped.get(&t).is_none_or(|e| e.pool != LAZY); + if !has && starved.last() != Some(&t) { + starved.push(t); + } + has + }); + for &t in &starved { + self.clear_sent_range(t, TILE); + } + self.starved.extend(starved); + runs = &kept[..]; + if runs.is_empty() { + return UploadStep::Done(PreparationOutcome::Ready); + } + } + } let Some(p) = self.staging_ptr() else { return UploadStep::Done(PreparationOutcome::RetryRequired); }; + // the open upload: its slot, where its ring bytes start, and the hashes it publishes once + // submitted (`submit_upload`); a submitted one's vector is used again let mut batch: Option = None; let mut recycled_batch: Option = None; + // what the open upload's copies take (window address, CPU address, bytes): their chunks' + // hashes, published once it is submitted (`submit_upload`) + let mut staged: Vec<(usize, usize, usize)> = Vec::new(); let mut last_wi: Option = None; - for &(a, n) in runs { + // the copies into the ring (source address, ring offset, bytes), done before their slot is + // submitted, by the worker threads when there are many + let mut jobs: Vec<(usize, usize, usize)> = Vec::new(); + // the many small ones first, together (the windows the open slot's dispatches write are + // UAVs in it until their first copy) + let mut uavs: Vec = Vec::new(); + let single = match self.scatter_small(runs, p, &mut batch, &mut recycled_batch, &mut jobs, &mut staged, &mut uavs) { + Ok(single) => single, + Err(step) => return step, + }; + for &(a, n) in single.as_deref().unwrap_or(runs) { let mut done = 0usize; while done < n { let cur = a + done; @@ -3301,49 +4646,16 @@ impl State { }, }; let b = self.windows[wi].0; - let copy = prepare_dirty_copy( - cur, - n - done, - b, - crate::gpu::uma::WINDOW, - self.ring_write, - STAGING, - ); - if (copy.ring_start + copy.bytes as u64).saturating_sub(self.ring_free) > STAGING as u64 { - self.reclaim_ring(); - if (copy.ring_start + copy.bytes as u64).saturating_sub(self.ring_free) > STAGING as u64 { - if let Some(ready) = batch.take() { - match self.submit_dirty_batch(ready, true) { - Ok(recycled) => recycled_batch = Some(recycled), - Err(outcome) => return UploadStep::Done(outcome), - } - } - while (copy.ring_start + copy.bytes as u64).saturating_sub(self.ring_free) > STAGING as u64 { - let Some(&(fv, _)) = self.inflight.front() else { - crate::xlog_warn!("sparse: the staging ring is full without a retirement fence; the unsubmitted CPU writes will be retried"); - return UploadStep::Done(PreparationOutcome::RetryRequired); - }; - return UploadStep::Wait(self.wait_ticket( - fv, - WaitKind::Ring { - front: *self.inflight.front().unwrap(), - write: self.ring_write, - submitted: self.ring_submitted, - free: self.ring_free, - }, - )); - } - } - } - if batch.as_ref().is_some_and(|batch| batch.hash_plan_would_overflow(copy.bytes)) { - match self.submit_dirty_batch(batch.take().unwrap(), true) { - Ok(recycled) => recycled_batch = Some(recycled), - Err(outcome) => return UploadStep::Done(outcome), - } + let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; + let (src, len) = self.cpu_span(cur, (n - done).min(to_win_end)); + let copy = prepare_dirty_copy(cur, len, b, crate::gpu::uma::WINDOW, self.ring_write, STAGING); + if let Err(step) = self.ring_room(copy.ring_start + copy.bytes as u64, p, &mut batch, &mut recycled_batch, &mut jobs, &mut staged) { + return step; } let slot_idx = match batch.as_ref() { Some(batch) => batch.slot, None => { + uavs.clear(); let idx = match self.begin_slot() { BeginSlot::Ready(index) => index, BeginSlot::Wait(ticket) => return UploadStep::Wait(ticket), @@ -3356,11 +4668,12 @@ impl State { idx } }; - std::ptr::copy_nonoverlapping(cur as *const u8, p.add(copy.staging_offset), copy.bytes); - batch.as_mut().unwrap().append_hashes( - cur, - std::slice::from_raw_parts(p.add(copy.staging_offset), copy.bytes), - ); + if let Some(k) = uavs.iter().position(|&w| w == wi) { + uavs.swap_remove(k); + self.slots[slot_idx].list.ResourceBarrier(&[uav_to_copy(&self.windows[wi].1)]); + } + jobs.push((src, copy.staging_offset, copy.bytes)); + staged.push((cur, src, copy.bytes)); let staging_res = &self.staging.as_ref().unwrap().0; self.slots[slot_idx].list.CopyBufferRegion( &self.windows[wi].1, @@ -3374,12 +4687,199 @@ impl State { } } if let Some(batch) = batch { - if let Err(outcome) = self.submit_dirty_batch(batch, false) { + if let Err(outcome) = self.submit_upload(batch, &mut jobs, &mut staged, p, false) { return UploadStep::Done(outcome); } } UploadStep::Done(PreparationOutcome::Ready) } + + /// Room in the upload ring up to its position `end`: what the GPU is done with is taken back; + /// when that is not enough, the open upload (`batch`) is submitted (a submitted one's vector + /// goes to `recycled`). Still not enough: a ticket for the oldest upload in the ring, which the + /// caller waits for with the state's lock and the upload gate given up, then starts again. + unsafe fn ring_room( + &mut self, + end: u64, + p: *mut u8, + batch: &mut Option, + recycled: &mut Option, + jobs: &mut Vec<(usize, usize, usize)>, + staged: &mut Vec<(usize, usize, usize)>, + ) -> Result<(), UploadStep> { + if end.saturating_sub(self.ring_free) <= STAGING as u64 { + return Ok(()); + } + self.reclaim_ring(); + if end.saturating_sub(self.ring_free) <= STAGING as u64 { + return Ok(()); + } + if let Some(ready) = batch.take() { + match self.submit_upload(ready, jobs, staged, p, true) { + Ok(done) => *recycled = Some(done), + Err(outcome) => return Err(UploadStep::Done(outcome)), + } + if end.saturating_sub(self.ring_free) <= STAGING as u64 { + return Ok(()); + } + } + let Some(&front) = self.inflight.front() else { + crate::xlog_warn!("sparse: the staging ring is full without a retirement fence; the unsubmitted CPU writes will be retried"); + return Err(UploadStep::Done(PreparationOutcome::RetryRequired)); + }; + Err(UploadStep::Wait(self.wait_ticket( + front.0, + WaitKind::Ring { front, write: self.ring_write, submitted: self.ring_submitted, free: self.ring_free }, + ))) + } + + /// Submit the open upload `batch`: the hashes of the chunks its copies take (`staged`: window + /// address, CPU address, bytes), read from the title's memory before the copies into the ring + /// (`run_copies`; a CPU write in between leaves the chunk changed, and it goes up again), then + /// the submit. They become `sent` only once it has its fence (`submit_dirty_batch`). A copy's + /// partial chunks at either end get none: they stay changed and go up with the next look. + unsafe fn submit_upload( + &mut self, + mut batch: PreparedDirtyBatch, + jobs: &mut Vec<(usize, usize, usize)>, + staged: &mut Vec<(usize, usize, usize)>, + p: *mut u8, + reclaim: bool, + ) -> Result { + for (at, src, n) in staged.drain(..) { + let mut c = at.next_multiple_of(CHUNK); + let hi = (at + n) & !(CHUNK - 1); + while c < hi { + let bytes = std::slice::from_raw_parts((src + (c - at)) as *const u8, CHUNK); + batch.updates.push(HashUpdate { at: c, hash: chunk_hash(bytes) }); + c += CHUNK; + } + } + run_copies(jobs, p); + self.submit_dirty_batch(batch, reclaim) + } + + /// Where the CPU bytes of window addresses `[a, a + n)` are: (CPU address of `a`, bytes from + /// `a` that lie in one piece there). The piece ends where a tile's CPU address does not follow + /// the one before it: a GPU view shown over another part of its CPU view, or a tile of the + /// window's own next to one over a CPU view (whose own address the CPU cannot read). + fn cpu_span(&self, a: usize, n: usize) -> (usize, usize) { + if self.mirrors.is_empty() { + return (a, n); + } + let src = |t: usize| self.mapped.get(&t).map_or(t, |e| e.cpu(t)); + let t0 = a & !(TILE - 1); + let s0 = src(t0); + let mut end = (t0 + TILE).min(a + n); + while end < a + n && src(end) == s0 + (end - t0) { + end = (end + TILE).min(a + n); + } + (s0 + (a - t0), end - a) + } + + /// Record the small ones of `runs` as dispatches (`scatter`) that put many of them in their + /// places at once, in the open upload (`batch`, opened here if none is): the runs left for a + /// copy each (None: all of them). `uavs` are the windows the open slot's dispatches write. + /// Err: what the caller returns (a ticket to wait for, or the outcome of a failed submit). + #[allow(clippy::too_many_arguments)] + unsafe fn scatter_small( + &mut self, + runs: &[(usize, usize)], + p: *mut u8, + batch: &mut Option, + recycled: &mut Option, + jobs: &mut Vec<(usize, usize, usize)>, + staged: &mut Vec<(usize, usize, usize)>, + uavs: &mut Vec, + ) -> Result>, UploadStep> { + if runs.len() < SCATTER_FROM || !super::scatter::on() { + return Ok(None); + } + // (a run that ends in the next window is cut where the window ends, by the copies; one + // whose CPU bytes are not in one piece is cut where they break, by the copies too) + let small = |&(a, n): &(usize, usize)| n < SCATTER_RUN && a % CHUNK == 0 && n % CHUNK == 0 && self.window_index(a).is_some_and(|w| a + n <= self.windows[w].0 + crate::gpu::uma::WINDOW) && self.cpu_span(a, n).1 == n; + let (small, single): (Vec<_>, Vec<_>) = runs.iter().copied().partition(small); + if small.len() < SCATTER_FROM { + return Ok(None); + } + let Some(pass) = super::scatter::of(&self.dev) else { return Ok(None) }; + let Some(ring_va) = self.staging.as_ref().map(|s| s.0.GetGPUVirtualAddress()) else { return Ok(None) }; + let pieces = super::scatter::pieces(&small, SCATTER_CHUNKS, |a| self.window_index(a).map(|w| (w, self.windows[w].0))); + let mut bound = None; + for piece in &pieces { + // the table of the piece and its chunks in one part of the ring + let bytes = super::scatter::Scatter::bytes(piece.chunks); + let mut at = self.ring_write.next_multiple_of(RING_ALIGN as u64); + let to_end = STAGING - at as usize % STAGING; + if bytes > to_end { + at += to_end as u64; + } + self.ring_room(at + bytes as u64, p, batch, recycled, jobs, staged)?; + let slot_idx = match batch.as_ref() { + Some(open) => open.slot, + None => { + uavs.clear(); + let idx = match self.begin_slot() { + BeginSlot::Ready(index) => index, + BeginSlot::Wait(ticket) => return Err(UploadStep::Wait(ticket)), + BeginSlot::RetryRequired => return Err(UploadStep::Done(PreparationOutcome::RetryRequired)), + }; + *batch = Some(match recycled.take() { + Some(done) => done.reopen(idx, self.ring_write), + None => PreparedDirtyBatch::new(idx, self.ring_write), + }); + idx + } + }; + let list = self.slots[slot_idx].list.clone(); + if bound != Some((slot_idx, self.slots[slot_idx].fence_val)) { + bound = Some((slot_idx, self.slots[slot_idx].fence_val)); + pass.bind(&list); + } + let off = at as usize % STAGING; + let mut place = p.add(off) as *mut u32; + let mut data = off + super::scatter::Scatter::data_at(piece.chunks); + for &(a, n) in &small[piece.runs.clone()] { + for k in 0..n / CHUNK { + place.write((a - piece.base + k * CHUNK) as u32); + place = place.add(1); + } + let src = self.cpu_span(a, n).0; + jobs.push((src, data, n)); + staged.push((a, src, n)); + data += n; + } + let (base, buf) = &self.windows[piece.window]; + pass.dispatch(&list, piece.chunks, ring_va + off as u64, buf.GetGPUVirtualAddress() + (piece.base - base) as u64); + if !uavs.contains(&piece.window) { + uavs.push(piece.window); + } + self.ring_write = at + bytes as u64; + SCATTERED[0].fetch_add(1, Ordering::Relaxed); + } + SCATTERED[1].fetch_add(small.len() as u64, Ordering::Relaxed); + Ok(Some(single)) + } +} + +/// dispatches of `scatter_small` so far, and the runs in them +static SCATTERED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// `r`, written by a dispatch of the list, becomes the destination of a copy. +fn uav_to_copy(r: &ID3D12Resource) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // SAFETY: the list keeps no reference and the window outlives it + pResource: unsafe { std::mem::transmute_copy(r) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + StateAfter: D3D12_RESOURCE_STATE_COPY_DEST, + }), + }, + } } /// Allocate a zeroed, write-watched block in the sparse VRAM windows (never straddling a @@ -3432,111 +4932,592 @@ pub fn queue() -> Option { QUEUE.lock().unwrap().clone() } -pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usize, usize)]) { - if ranges.is_empty() { - return; +/// Pop a pooled `RbJob` of at least `need` bytes for `ty` under the leaf `readbacks` lock, or +/// allocate a new one on `dev` outside both `STATE` and `readbacks`. +unsafe fn take_or_alloc_rb_job(dev: &ID3D12Device, readbacks: &SharedReadbacks, need: usize, ty: D3D12_COMMAND_LIST_TYPE) -> Option { + { + let mut rq = readbacks.lock().unwrap(); + if let Some(i) = rq.rb_pool.iter().enumerate().filter(|(_, j)| j.cap >= need && j.ty == ty).min_by_key(|(_, j)| j.cap).map(|(i, _)| i) { + return Some(rq.rb_pool.swap_remove(i)); + } + } + let cap = need.max(64 << 10).next_power_of_two().min(READBACK_STAGING); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).ok()?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).ok()?; + list.Close().ok()?; + let _ = list.SetName(windows::core::w!("xcl sparse readback list")); + let mut d = buffer_desc(cap as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut r).ok()?; + let buf = r?; + let mut p: *mut c_void = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).ok()?; + Some(RbJob { alloc, list, buf, ptr: p as *mut u8, cap, rb_v: 0, done_v: 0, copies: Vec::new(), ty, fences: None, seq: 0 }) +} + +/// Whether `rq` holds at least one finished unpopped `ImmJob` or `RbJob`. +unsafe fn rq_has_unpopped_finished(rq: &ReadbackQueue) -> bool { + if rq.imm_jobs.iter().any(|j| super::real::fence_completed(&j.fence) >= j.value) { + return true; + } + rq.rb_jobs.iter().any(|j| { + let done_f = match (&j.fences, &rq.rbq_done) { + (Some((_, b)), _) => b, + (None, Some(d)) => d, + (None, None) => return false, + }; + super::real::fence_completed(done_f) >= j.done_v + }) +} + +/// Whether any finished unpopped readback job exists (used by the background thread so it skips +/// `STATE` whenever nothing is ready to land or another thread is already landing). +unsafe fn has_unpopped_finished_jobs(rb: &SharedReadbacks) -> bool { + let rq = rb.lock().unwrap(); + rq_has_unpopped_finished(&rq) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum ReadyCheck { + NothingReady, + LandNow, + TimedOut, +} + +/// Wait outside `STATE` and outside `READBACKS` for any already-prepared `prepare_after_execute` +/// plan (`rq.submitting > 0`) to publish or cancel within `deadline`, and then for any +/// `Drain::TitleDone` readback job whose title lists are already done on the GPU (up to `spin_us` +/// total across all such jobs). +/// +/// Returns `ReadyCheck::LandNow` iff at least one job is finished or currently being landed under +/// `STATE` (meaning the caller must acquire `STATE` to land or synchronize with an in-flight land), +/// `ReadyCheck::TimedOut` if `deadline` expired while a submission was still publishing, or +/// `ReadyCheck::NothingReady` if no work is ready to land. +unsafe fn wait_and_check_ready(rb: &SharedReadbacks, how: Drain, spin_us: u128, deadline: Option) -> ReadyCheck { + { + let mut rq = rb.lock().unwrap(); + while rq.submitting > 0 { + if let Some(dl) = deadline { + let Some(rem) = dl.checked_duration_since(std::time::Instant::now()) else { + return ReadyCheck::TimedOut; + }; + if rem.is_zero() { + return ReadyCheck::TimedOut; + } + let (g, res) = rb.published.wait_timeout(rq, rem).unwrap(); + rq = g; + if rq.submitting > 0 && res.timed_out() { + return ReadyCheck::TimedOut; + } + } else { + rq = rb.published.wait(rq).unwrap(); + } + } } - let measure = super::memory_report::enabled(); - let (mut uploads, timing) = UploadGateTiming::acquire(measure); - readback_after_execute_locked(queue, ranges); - let times = timing.finish(); - drop(uploads.take()); - if measure { - note_readback_gate(times); + if how == Drain::TitleDone && spin_us > 0 { + let to_wait: Vec<(ID3D12Fence, u64)> = { + let rq = rb.lock().unwrap(); + let mut out = Vec::new(); + for j in &rq.rb_jobs { + let (title_f, done_f, rb_v, done_v) = match (&j.fences, &rq.rbq_done) { + (Some((a, b)), _) => (a, b, j.rb_v, j.done_v), + (None, Some(d)) => (&rq.rb_fence, d, j.rb_v, j.done_v), + (None, None) => continue, + }; + if super::real::fence_completed(done_f) < done_v && super::real::fence_completed(title_f) >= rb_v { + out.push((done_f.clone(), done_v)); + } + } + out + }; + if !to_wait.is_empty() { + // Single total spin budget across all title-done copies, completely outside all locks. + let t0 = std::time::Instant::now(); + let mut timed_out = 0u64; + for (done_f, done_v) in &to_wait { + while super::real::fence_completed(done_f) < *done_v && t0.elapsed().as_micros() < spin_us { + std::thread::yield_now(); + } + if super::real::fence_completed(done_f) < *done_v { + timed_out += 1; + } + } + if timed_out > 0 { + static LATE: AtomicU64 = AtomicU64::new(0); + let prev = LATE.fetch_add(timed_out, Ordering::Relaxed); + for n in 1..=timed_out { + let k = prev + n; + if k.is_power_of_two() { + crate::xlog_warn!("sparse: {k} copies back so far not finished after the title's work they follow – left for later"); + } + } + } + } + } + let rq = rb.lock().unwrap(); + if rq.landing > 0 || rq_has_unpopped_finished(&rq) { + ReadyCheck::LandNow + } else { + ReadyCheck::NothingReady } } -unsafe fn readback_after_execute_locked(queue: &ID3D12CommandQueue, ranges: &[(usize, usize)]) { - let mut g = lock_state(); - let Some(s) = g.as_mut() else { return }; - let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); - if filtered.is_empty() { - return; +/// Record and submit async readback copies + fences on `queue` under `plan.rb_submit` (outside +/// `STATE`), then push the resulting `ImmJob` and `RbJob`s to `plan.readbacks` once both fences +/// have been signalled on `queue`. +unsafe fn submit_async_readback(queue: &ID3D12CommandQueue, plan: AsyncReadbackPlan) { + submit_async_readback_inner( + queue, + plan, + #[cfg(test)] + None, + ); +} + +#[cfg(test)] +type PublishHook<'a> = &'a dyn Fn(&ID3D12Fence, u64); + +unsafe fn submit_async_readback_inner( + queue: &ID3D12CommandQueue, + plan: AsyncReadbackPlan, + #[cfg(test)] before_publish: Option>, +) { + let AsyncReadbackPlan { rb_submit, readbacks, windows, batches, imm, submitting } = plan; + // Lock order: the queue's submit lease (`queue_submit::with`) first, then `rb_submit`. The + // signals and executes below take the lease again (`real::native_queue_signal`, `pc_execute`), + // which is re-entrant only for a thread that already holds it: every caller of + // `readback_after_execute` must run inside `queue`'s lease (list_x's submit effects and + // kickoff do), or one thread holds `rb_submit` waiting for the lease while the lease holder + // waits for `rb_submit`. + let mut sub = rb_submit.lock().unwrap(); + // on this queue: [the title's lists] Signal(first, v) [the copies] Signal(second, v) + let key = queue.as_raw() as usize; + if !sub.rb_queue_fences.contains_key(&key) { + let (Ok(a), Ok(b)) = (sub.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE), sub.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE)) else { + return; + }; + sub.rb_queue_fences.insert(key, (a, b, 0)); } - filtered.sort_unstable(); - let mut merged: Vec<(usize, usize)> = Vec::with_capacity(filtered.len()); - for (a, n) in filtered { - match merged.last_mut() { - Some(last) if a <= last.0.saturating_add(last.1) => { - let end = (last.0 + last.1).max(a + n); - last.1 = end - last.0; + let (fences, v) = { + let e = sub.rb_queue_fences.get_mut(&key).expect("fences"); + e.2 += 1; + ((e.0.clone(), e.1.clone()), e.2) + }; + let _ = super::real::native_queue_signal(queue, &fences.0, v); + + let mut submitted: Vec = Vec::with_capacity(batches.len()); + if !batches.is_empty() { + let ty = queue.GetDesc().Type; + for batch in batches { + let need = batch.iter().map(|c| c.len).sum::(); + let Some(mut job) = take_or_alloc_rb_job(&sub.dev, &readbacks, need, ty) else { + crate::xlog_warn!("sparse: no readback buffer for a copy back of {need} bytes – left out"); + // (the Signal after the loop still goes out: what was recorded for it stands) + break; + }; + let _ = job.alloc.Reset(); + let _ = job.list.Reset(&job.alloc, None); + let mut off = 0usize; + for c in batch { + let (base, ref res) = windows[c.win]; + job.list.CopyBufferRegion(&job.buf, off as u64, res, (c.va - base) as u64, c.len as u64); + job.copies.push((c.va, off, c.len, c.gen)); + off += c.len; } - _ => merged.push((a, n)), + // (the PC slot in the queue's ordered turn, `real::native_queue_execute`) + if job.list.Close().is_ok() { + if let Ok(list) = job.list.cast::() { + super::real::native_queue_execute(queue, &list); + } + } + job.rb_v = v; + job.done_v = v; + job.fences = Some(fences.clone()); + submitted.push(job); } + let _ = super::real::native_queue_signal(queue, &fences.1, v); + } + + #[cfg(test)] + if let Some(hook) = before_publish { + hook(&fences.0, v); } - s.rb_value += 1; - let v = s.rb_value; - if super::real::native_queue_signal(queue, &s.rb_fence, v).is_ok() { - let _ = super::real::native_queue_wait(&s.queue, &s.rb_fence, v); - super::list_x::note_internal_wait(s.queue.as_raw() as usize, "sparse readback behind a title queue", &s.rb_fence, v); + + let mut rq = readbacks.lock().unwrap(); + let mut added = 0usize; + if !imm.is_empty() { + rq.job_seq += 1; + let seq = rq.job_seq; + rq.imm_jobs.push_back(ImmJob { seq, fence: fences.0.clone(), value: v, writes: imm }); + added += 1; + } + for mut job in submitted { + rq.job_seq += 1; + job.seq = rq.job_seq; + rq.rb_jobs.push_back(job); + added += 1; } - // (the ranges are the lists' own GPU writes) - s.readback_ranges(&merged, true); + submitting.finish(&mut rq, added); + if added > 0 { + RB_ASYNC.store(true, Ordering::Relaxed); + } + drop(rq); + readbacks.published.notify_all(); } -/// Synchronize `[va, va + len)` in a sparse window for a CPU read (`ID3D12Resource::Map` with -/// a non-empty read range, or `Map(0, NULL)` on a sparse readback resource): flushes pending -/// tile clears and unsubmitted CPU-changed chunks first so CPU writes are preserved, then -/// copies the range back from VRAM into CPU memory. -pub unsafe fn readback_now(va: usize, len: usize) { - if len == 0 { +unsafe fn readback_after_execute_with(state_lock: &Mutex>, queue: &ID3D12CommandQueue, ranges: &[(usize, usize)], imms: &[(usize, u64, u8)]) { + if ranges.is_empty() && imms.is_empty() { return; } - let measure = super::memory_report::enabled(); - let _upload_lifetime = UPLOAD_STATE_LIFETIME.read().unwrap(); - let (mut uploads, mut timing) = UploadGateTiming::acquire(measure); - readback_now_locked(va, len, &mut uploads, &mut timing); - let times = timing.finish(); + let is_global = std::ptr::eq(state_lock, &STATE); + // (the `STATE` stage takes the upload gate first, as every uploader does: its rare synchronous + // copy back uses the upload ring; the recording of an async copy back goes on outside both) + let measure = is_global && super::memory_report::enabled(); + let (mut uploads, timing) = if is_global { + let (guard, timing) = UploadGateTiming::acquire(measure); + (guard, Some(timing)) + } else { + (None, None) + }; + let (plan, excess) = { + let t0 = (is_global && super::look_stats::deep()).then(std::time::Instant::now); + let mut g = if is_global { lock_for_submit() } else { state_lock.lock().unwrap() }; + let _held = is_global.then(|| holding(Holder::After)); + if let Some(t0) = t0 { + HELD.add(HELD_AFTER_WAIT, t0.elapsed().as_micros() as u64); + } + let Some(s) = g.as_mut() else { return }; + s.prepare_after_execute(queue, ranges, imms) + }; + let times = timing.map(UploadGateTiming::finish); drop(uploads.take()); - drop(_upload_lifetime); - if measure { + if let Some(times) = times.filter(|_| measure) { note_readback_gate(times); } + drop(excess); + if let Some(plan) = plan { + submit_async_readback(queue, plan); + if is_global { + start_readback_thread(); + } + } } -unsafe fn readback_now_locked( - va: usize, len: usize, uploads: &mut Option, timing: &mut UploadGateTiming, -) { - 'prepare: loop { - let mut g = lock_state(); - let Some(s) = g.as_mut() else { return }; - if s.window_index(va).is_none() { - return; +pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usize, usize)], imms: &[(usize, u64, u8)]) { + readback_after_execute_with(&STATE, queue, ranges, imms); +} + +/// The PC `ExecuteCommandLists` of `queue` for `list` (an adopted title queue's own method, +/// not XCL's hook: this is not a submit of the title's). +pub(super) unsafe fn pc_execute(queue: &ID3D12CommandQueue, list: &ID3D12GraphicsCommandList) { + type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + const SLOT: usize = 10; + let q = queue.as_raw(); + let f: ExecFn = if super::real::is_adopted(q) { std::mem::transmute(super::real::orig_fn(q, SLOT)) } else { std::mem::transmute(*(*(q as *const *const usize)).add(SLOT)) }; + let one = [list.as_raw()]; + // (main's ordered queue turn: re-entrant, so a caller already in it keeps it) + super::queue_submit::with(q as usize, || f(q, 1, one.as_ptr())); +} + +/// copies back submitted and not landed yet, and whether any ran on the readback queue +static RB_PENDING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static RB_ASYNC: AtomicBool = AtomicBool::new(false); + +/// Whether copies back land asynchronously (any ran on the readback queue so far) +pub fn readbacks_async() -> bool { + RB_ASYNC.load(Ordering::Relaxed) +} + +unsafe fn settle_readbacks_with(state_lock: &Mutex>, rb: &Arc, how: Drain, spin_us: u128, lock_ms: Option) -> bool { + let deadline = lock_ms.map(|ms| std::time::Instant::now() + std::time::Duration::from_millis(ms)); + match wait_and_check_ready(rb, how, spin_us, deadline) { + ReadyCheck::NothingReady => return true, + ReadyCheck::TimedOut => return false, + ReadyCheck::LandNow => {} } - let zeroed = std::mem::take(&mut s.to_zero); - if !zeroed.is_empty() { - for &(a, n) in &zeroed { - s.clear_sent_range(a, n); - } - match s.upload_zeros(&zeroed) { - UploadStep::Done(PreparationOutcome::Ready) => {} - UploadStep::Wait(ticket) => { - // Publish the clear retry journal before another uploader can take the gate. It - // may consume it while this thread waits; after reacquiring, restart from state. - s.to_zero.extend(zeroed); - drop(g); - if !timing.with_released(uploads, || wait_upload_released(ticket)) { return } - continue 'prepare; + let is_global = std::ptr::eq(state_lock, &STATE); + let excess = match deadline { + None => { + let mut g = state_lock.lock().unwrap(); + let _held = is_global.then(|| holding(Holder::Settle)); + if let Some(s) = g.as_mut().filter(|s| Arc::ptr_eq(&s.readbacks, rb)) { + s.land_finished_readbacks() + } else { + Vec::new() } - UploadStep::Done(_) => { - s.to_zero.extend(zeroed); - return; + } + Some(dl) => { + let rem = dl.saturating_duration_since(std::time::Instant::now()); + let Some(mut g) = try_lock_giving_way(state_lock, &SUBMITS_WAITING, rem, is_global && submit_lock_first()) else { + return false; + }; + let _held = is_global.then(|| holding(Holder::Settle)); + if let Some(s) = g.as_mut().filter(|s| Arc::ptr_eq(&s.readbacks, rb)) { + s.land_finished_readbacks() + } else { + Vec::new() } } + }; + drop(excess); + true +} + +/// Copies back that are done on the GPU, into the title's memory, and those whose title work +/// is done (waiting for the copy): before a CPU read of memory the title's lists wrote. +pub unsafe fn settle_readbacks() { + if RB_PENDING.load(Ordering::Acquire) == 0 { + return; } - // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` - let mut dirty_runs: Vec<(usize, usize)> = Vec::new(); - let mut pg = va & !(PAGE - 1); + let Some(rb) = readbacks_arc() else { return }; + let _ = settle_readbacks_with(&STATE, &rb, Drain::TitleDone, 2000, None); +} + +/// `settle_readbacks` from a fence observation: the state's lock is only tried (for ~5 ms), as +/// XCL may be waiting on a fence of its own with the lock held. +pub unsafe fn settle_readbacks_try() { + settle_readbacks_within(5); +} + +/// `settle_readbacks` with the state's lock waited for `ms` ms at most (false: it was not had: +/// what is pending stays pending). A copy back whose title work is done is waited for 0.3 ms +/// outside all locks; if no job finished yet, `STATE` is not locked at all. +pub unsafe fn settle_readbacks_within(ms: u64) -> bool { + if RB_PENDING.load(Ordering::Acquire) == 0 { + return true; + } + // (`XCL_LOOK_STATS=2`: the time a title's thread spends here when it looks at a fence) + let _cost = super::look_stats::deep().then(|| crate::hle::api_cost::time(crate::hle::api_cost::Call::FenceSettle)); + let Some(rb) = readbacks_arc() else { return true }; + settle_readbacks_with(&STATE, &rb, Drain::TitleDone, 300, Some(ms)) +} + +/// The thread that moves finished copies back into the title's memory, so it sees what its +/// lists wrote without submitting again (started with the first copy back). +fn start_readback_thread() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let _ = std::thread::Builder::new().name("xcl-sparse-readback".into()).spawn(|| loop { + std::thread::sleep(std::time::Duration::from_micros(500)); + if RB_PENDING.load(Ordering::Acquire) == 0 { + continue; + } + // (`XCL_SUBMIT_LOCK_FIRST=1`: a submit waits for the lock: not now) + if submit_lock_first() && SUBMITS_WAITING.load(Ordering::Acquire) > 0 { + continue; + } + let Some(rb) = readbacks_arc() else { continue }; + if unsafe { !has_unpopped_finished_jobs(&rb) } { + continue; + } + if submit_lock_first() && SUBMITS_WAITING.load(Ordering::Acquire) > 0 { + continue; + } + let excess = { + if let Ok(mut g) = STATE.try_lock() { + let _held = holding(Holder::ReadbackThread); + if let Some(s) = g.as_mut().filter(|s| Arc::ptr_eq(&s.readbacks, &rb)) { + unsafe { s.land_finished_readbacks() } + } else { + Vec::new() + } + } else { + Vec::new() + } + }; + drop(excess); + }); + }); +} + +impl State { + /// Snapshot mapped tiles and immediates under `&mut self` (`STATE`) for async readback, or + /// execute the rare synchronous `rbq.is_none()` fallback inline. + unsafe fn prepare_after_execute(&mut self, queue: &ID3D12CommandQueue, ranges: &[(usize, usize)], imms: &[(usize, u64, u8)]) -> (Option, Vec) { + let s = self; + let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); + // immediates: stored by XCL when the lists are done. One that another write of these + // lists overlaps, and all of them without a queue of the title's to order them on, + // come back with a copy like the rest. + let mut imm: Vec<(usize, u64, u8, u32)> = Vec::new(); + for &(a, v, n) in imms { + if s.window_index(a).is_none() { + continue; + } + let len = (n & 0x7f) as usize; + if s.rbq.is_none() || ranges.iter().any(|&(ra, rn)| a < ra + rn && ra < a + len) { + filtered.push((a, len)); + } else { + // (with the memory it is for, `TileEntry::gen`: no tile there yet counts as the + // window's own, as before) + imm.push((a, v, n, s.mapped.get(&(a & !(TILE - 1))).map_or(0, |e| e.gen))); + } + } + if filtered.is_empty() && imm.is_empty() { + return (None, Vec::new()); + } + filtered.sort_unstable(); + let mut merged: Vec<(usize, usize)> = Vec::with_capacity(filtered.len()); + for (a, n) in filtered { + match merged.last_mut() { + Some(last) if a <= last.0.saturating_add(last.1) => { + let end = (last.0 + last.1).max(a + n); + last.1 = end - last.0; + } + _ => merged.push((a, n)), + } + } + if s.rbq.is_some() { + let mut windows: Vec<(usize, ID3D12Resource)> = Vec::new(); + let mut win_slot: Vec = vec![usize::MAX; s.windows.len()]; + let mut batches: Vec> = Vec::new(); + let mut used = 0usize; + for &(a, n) in &merged { + let mut at = 0usize; + while at < n { + let cur = a + at; + let tile = cur & !(TILE - 1); + let Some(wi) = s.window_index(cur) else { break }; + let to_tile_end = (tile + TILE) - cur; + // (a tile with no video memory has nothing to copy back, like one not mapped) + let Some(gen) = s.mapped.get(&tile).filter(|e| e.pool != LAZY).map(|e| e.gen) else { + at += (n - at).min(to_tile_end); + continue; + }; + if batches.is_empty() || used == READBACK_STAGING { + batches.push(Vec::new()); + used = 0; + } + let lwi = if win_slot[wi] != usize::MAX { + win_slot[wi] + } else { + let idx = windows.len(); + windows.push((s.windows[wi].0, s.windows[wi].1.clone())); + win_slot[wi] = idx; + idx + }; + let to_win_end = (s.windows[wi].0 + crate::gpu::uma::WINDOW) - cur; + let chunk = (n - at).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); + batches.last_mut().expect("batch").push(RbChunk { win: lwi, va: cur, len: chunk, gen }); + used += chunk; + at += chunk; + } + } + if imm.is_empty() && batches.is_empty() { + return (None, Vec::new()); + } + let submitting = SubmittingGuard::begin(&s.readbacks); + return ( + Some(AsyncReadbackPlan { + rb_submit: Arc::clone(&s.rb_submit), + readbacks: Arc::clone(&s.readbacks), + windows, + batches, + imm, + submitting, + }), + Vec::new(), + ); + } + s.rb_value += 1; + let v = s.rb_value; + if super::real::native_queue_signal(queue, &s.rb_fence, v).is_ok() { + let _ = super::real::native_queue_wait(&s.queue, &s.rb_fence, v); + super::list_x::note_internal_wait(s.queue.as_raw() as usize, "sparse readback behind a title queue", &s.rb_fence, v); + } + // (the ranges are the lists' own GPU writes) + (None, s.readback_ranges(&merged, true)) + } + + /// `readback_after_execute` on a standalone `State` (tests only). + #[cfg(test)] + unsafe fn after_execute(&mut self, queue: &ID3D12CommandQueue, ranges: &[(usize, usize)], imms: &[(usize, u64, u8)]) { + let (plan, excess) = self.prepare_after_execute(queue, ranges, imms); + drop(excess); + if let Some(plan) = plan { + submit_async_readback(queue, plan); + } + } +} + +/// Synchronize `[va, va + len)` in a sparse window for a CPU read (`ID3D12Resource::Map` with +/// a non-empty read range, or `Map(0, NULL)` on a sparse readback resource): flushes pending +/// tile clears and unsubmitted CPU-changed chunks first so CPU writes are preserved, then +/// copies the range back from VRAM into CPU memory. +pub unsafe fn readback_now(va: usize, len: usize) { + if len == 0 { + return; + } + // (copies back already submitted land first, waited for outside all locks) + if RB_PENDING.load(Ordering::Acquire) != 0 { + if let Some(rb) = readbacks_arc() { + wait_and_check_ready(&rb, Drain::TitleDone, 2000, None); + } + } + let measure = super::memory_report::enabled(); + let _upload_lifetime = UPLOAD_STATE_LIFETIME.read().unwrap(); + let (mut uploads, mut timing) = UploadGateTiming::acquire(measure); + let excess = readback_now_locked(va, len, &mut uploads, &mut timing); + let times = timing.finish(); + drop(uploads.take()); + drop(_upload_lifetime); + // (recycled copy-back jobs past the pool's cap drop outside all locks) + drop(excess); + if measure { + note_readback_gate(times); + } +} + +/// `readback_now` with the upload gate held. Returns any excess recycled `RbJob`s for the caller +/// to drop outside `STATE`. +unsafe fn readback_now_locked( + va: usize, len: usize, uploads: &mut Option, timing: &mut UploadGateTiming, +) -> Vec { + 'prepare: loop { + let mut g = lock_state(); + let held = holding(Holder::CpuRead); + let Some(s) = g.as_mut() else { return Vec::new() }; + if s.window_index(va).is_none() { + return Vec::new(); + } + let zeroed = zero_runs(std::mem::take(&mut s.to_zero)); + if !zeroed.is_empty() { + for &(a, n) in &zeroed { + s.clear_sent_range(a, n); + } + match s.upload_zeros(&zeroed) { + UploadStep::Done(PreparationOutcome::Ready) => {} + UploadStep::Wait(ticket) => { + // Publish the clear retry journal before another uploader can take the gate. It + // may consume it while this thread waits; after reacquiring, restart from state. + rejournal_zeros(&mut s.to_zero, zeroed); + drop(held); + drop(g); + if !timing.with_released(uploads, || wait_upload_released(ticket)) { return Vec::new() } + continue 'prepare; + } + UploadStep::Done(_) => { + rejournal_zeros(&mut s.to_zero, zeroed); + return Vec::new(); + } + } + } + // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` (read at the + // tile's CPU address: a mirrored tile shows another CPU view) + let mut dirty_runs: Vec<(usize, usize)> = Vec::new(); + let mut pg = va & !(PAGE - 1); let end = va + len; while pg < end { let t = pg & !(TILE - 1); let tile_end = (t + TILE).min(end); if let Some(entry) = s.mapped.get_mut(&t) { + let cpu = entry.cpu(t); let mut p = pg; while p < tile_end { let idx = (p - t) / PAGE; if entry.holes & (1u16 << idx) == 0 { - let bytes = std::slice::from_raw_parts(p as *const u8, PAGE); + let bytes = std::slice::from_raw_parts((cpu + (p - t)) as *const u8, PAGE); scan_page(bytes, p, &entry.sent[idx], &mut dirty_runs); } p += PAGE; @@ -3550,18 +5531,110 @@ unsafe fn readback_now_locked( UploadStep::Wait(ticket) => { // Dirty bytes were only observed, not removed from a journal. Another uploader // may send them while this thread waits; restart and rescan current hashes. + drop(held); drop(g); - if !timing.with_released(uploads, || wait_upload_released(ticket)) { return } + if !timing.with_released(uploads, || wait_upload_released(ticket)) { return Vec::new() } continue 'prepare; } - UploadStep::Done(_) => return, + UploadStep::Done(_) => return Vec::new(), } } - s.readback_ranges(&[(va, len)], false); - return; + // (the range is what the CPU reads, not what the GPU wrote: a changed chunk keeps its bytes) + return s.readback_ranges(&[(va, len)], false); } } +/// Clears taken from `State::to_zero` that did not go out, back into it, a piece per tile (a +/// decommit removes the pieces of its tiles by their start: a run over several tiles would +/// outlive one of them). +fn rejournal_zeros(to_zero: &mut BTreeSet<(usize, usize)>, runs: Vec<(usize, usize)>) { + for (a, n) in runs { + let end = a + n; + let mut p = a; + while p < end { + let next = ((p & !(TILE - 1)) + TILE).min(end); + to_zero.insert((p, next - p)); + p = next; + } + } +} + +/// Submits waiting for the state's lock. A thread that takes it again and again – a title mapping +/// its memory a page at a time – can keep them out for seconds: the lock goes to the first to ask +/// once it is free, and the thread that just gave it up is back before a waiting one has woken (a +/// retail title's loading screen stood still for 8 s while another of its threads mapped 1.2 GB). +static SUBMITS_WAITING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// what a commit waits for them at most +const GIVE_WAY_US: u128 = 2000; + +/// `m` for a submit: the others let it in first (`lock_in_turn`). +fn lock_first<'a, T>(m: &'a Mutex, waiting: &std::sync::atomic::AtomicUsize) -> std::sync::MutexGuard<'a, T> { + waiting.fetch_add(1, Ordering::AcqRel); + let g = m.lock(); + waiting.fetch_sub(1, Ordering::AcqRel); + g.unwrap() +} + +/// Submits in `before_execute` waiting for the state's lock (they send the put-off mappings). +static FLUSHERS_WAITING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// `XCL_SUBMIT_LOCK_FIRST=1` (off unless set): a submit's other uses of the state's lock (its +/// after stage's copies back, its ranges' mapped tiles) are let in first like its `before_execute`, +/// and the threads that only try the lock in a loop (copies back settled at a fence look, the +/// readback thread, put-off mappings sent) do not try it while a submit waits. A retail title's +/// world: each submit waited ~2 ms for the lock while title threads looked at fences ~170 times a +/// second, each trying the lock for up to 5 ms; a thread that tries the lock as it is let go takes +/// it before the waiting submit has woken. +fn submit_lock_first() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SUBMIT_LOCK_FIRST").is_ok_and(|v| v.trim() == "1")) +} + +/// The state's lock for a submit's after stage and ranges: `lock_first` with +/// `XCL_SUBMIT_LOCK_FIRST=1`, else `lock_state` as before. +fn lock_for_submit() -> std::sync::MutexGuard<'static, Option> { + if !submit_lock_first() { + return lock_state(); + } + let mut g = lock_first(&STATE, &SUBMITS_WAITING); + forget_released(&mut g); + g +} + +/// `m` tried until it is had or `budget` has gone by (None). With `give_way`, it is not tried +/// while a submit waits for it (`waiting`); that time does not count against `budget`, up to +/// `budget` more (a caller that may not wait for the lock still gives up in the end). +fn try_lock_giving_way<'a, T>(m: &'a Mutex, waiting: &std::sync::atomic::AtomicUsize, budget: std::time::Duration, give_way: bool) -> Option> { + let t0 = std::time::Instant::now(); + let mut gave = std::time::Duration::ZERO; + loop { + if give_way && gave < budget && waiting.load(Ordering::Acquire) > 0 { + let t = std::time::Instant::now(); + std::thread::yield_now(); + gave += t.elapsed(); + continue; + } + if let Ok(g) = m.try_lock() { + return Some(g); + } + if t0.elapsed().saturating_sub(gave) >= budget { + return None; + } + std::thread::yield_now(); + } +} + +/// `m` once no submit waits for it (or `GIVE_WAY_US` have gone by). +fn lock_in_turn<'a, T>(m: &'a Mutex, waiting: &std::sync::atomic::AtomicUsize) -> std::sync::MutexGuard<'a, T> { + if waiting.load(Ordering::Acquire) > 0 { + let t0 = std::time::Instant::now(); + while waiting.load(Ordering::Acquire) > 0 && t0.elapsed().as_micros() < GIVE_WAY_US { + std::thread::yield_now(); + } + } + m.lock().unwrap() +} + /// The title committed `[a, a + n)` in a sparse window. The pages of tiles mapped for it that /// lie outside the range are not committed (holes); the range's pages are. pub unsafe fn committed(a: usize, n: usize) { @@ -3574,7 +5647,10 @@ pub unsafe fn committed_with_protection(a: usize, n: usize, writable: bool) { if n == 0 { return; } - let mut g = lock_state(); + super::title_textures::mark_hot(a, n); + let mut g = lock_in_turn(&STATE, &SUBMITS_WAITING); + let _held = holding(Holder::Commits); + forget_released(&mut g); let Some(s) = g.as_mut() else { let (start, end) = page_span(a, n); early_add(&mut EARLY.lock().unwrap(), start, end); @@ -3595,7 +5671,9 @@ pub unsafe fn decommitted(a: usize, n: usize) { if n == 0 { return; } - let mut g = lock_state(); + let mut g = lock_in_turn(&STATE, &SUBMITS_WAITING); + let _held = holding(Holder::Commits); + forget_released(&mut g); let Some(s) = g.as_mut() else { let (start, end) = page_span(a, n); early_remove(&mut EARLY.lock().unwrap(), start, end); @@ -3604,14 +5682,122 @@ pub unsafe fn decommitted(a: usize, n: usize) { s.decommit_range(a, n); } +/// `decommitted` around the caller's decommit `os` of `[a, a + n)` in a sparse window (its +/// VirtualFree, called with no lock of XCL's held; its result is returned): a CPU view there (a +/// title's reservation of 64 KiB pages that a GPU view shows) has its pages taken as holes by +/// submits until Windows is done, as `source_decommit` does outside the windows. For a release, +/// drop the pair and `forget_mirrors` inside `os`, after the VirtualFree. +pub unsafe fn decommit(a: usize, n: usize, os: impl FnOnce() -> R) -> R { + if n == 0 { + return os(); + } + let (span, _) = freeing_begins(&SOURCES, a, n); + decommitted(a, n); + let r = os(); + freeing_ends(&SOURCES, span); + r +} + +/// Tiles wait for their mapping call (`State::pending`; read without the lock). +static PENDING: AtomicBool = AtomicBool::new(false); +static PENDING_WAKE: (Mutex<()>, std::sync::Condvar) = (Mutex::new(()), std::sync::Condvar::new()); + +/// A tile's mapping was put off: sent by the thread started here in 2 ms, unless something sends +/// it before. Work already on the GPU can reach the memory without another submit (it waits for a +/// value the CPU writes). +fn pending_soon() { + if PENDING.swap(true, Ordering::AcqRel) { + return; + } + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let _ = std::thread::Builder::new().name("xcl-tile-maps".into()).spawn(|| loop { + { + let mut g = PENDING_WAKE.0.lock().unwrap_or_else(|e| e.into_inner()); + while !PENDING.load(Ordering::Acquire) { + g = PENDING_WAKE.1.wait(g).unwrap_or_else(|e| e.into_inner()); + } + } + std::thread::sleep(std::time::Duration::from_millis(2)); + if PENDING.load(Ordering::Acquire) { + send_pending(); + } + }); + }); + drop(PENDING_WAKE.0.lock().unwrap_or_else(|e| e.into_inner())); + PENDING_WAKE.1.notify_one(); +} + +/// The mappings put off go to the GPU now: the CPU is about to signal a fence, and work submitted +/// before the title committed the memory may run because of it. +pub fn send_pending() { + // (a signal under the state's lock must not wait for it; the thread sends them then) + let t0 = std::time::Instant::now(); + loop { + // (asked each time: another thread may be sending them, and has sent them when the flag goes) + if !PENDING.load(Ordering::Acquire) { + return; + } + // (`XCL_SUBMIT_LOCK_FIRST=1`: a submit that waits for the lock in `before_execute` sends + // them itself, `flush_pending`) + if submit_lock_first() && FLUSHERS_WAITING.load(Ordering::Acquire) > 0 { + if t0.elapsed().as_millis() >= 2 { + return; + } + std::thread::yield_now(); + continue; + } + match STATE.try_lock() { + Ok(mut g) => { + let _held = holding(Holder::TileMaps); + if let Some(s) = g.as_mut() { + unsafe { s.flush_pending() }; + } + PENDING.store(false, Ordering::Release); + return; + } + Err(std::sync::TryLockError::Poisoned(_)) => return PENDING.store(false, Ordering::Release), + Err(std::sync::TryLockError::WouldBlock) if t0.elapsed().as_millis() >= 2 => return, + Err(std::sync::TryLockError::WouldBlock) => std::thread::yield_now(), + } + } +} + impl State { /// `committed` with the state locked unsafe fn commit_range(&mut self, a: usize, n: usize) { self.commit_range_with_protection(a, n, true); } + /// `committed_with_protection` with the state locked: `writable` false marks the committed + /// pages read-only (`TileEntry::not_rw`) for `known_writable` unsafe fn commit_range_with_protection(&mut self, a: usize, n: usize, writable: bool) { - self.ensure_mapped(a, n, |_| (0xFFFF, 0)); + // a tile over a CPU view committed at its own address: its own memory from here on + if !self.mirror_src.is_empty() { + let mut t = a & !(TILE - 1); + while t < a.saturating_add(n) { + if self.unlink_mirror(t) { + if let Some(e) = self.mapped.get_mut(&t).filter(|e| e.src != 0) { + // (what it held was the CPU view's: cleared, and the pages committed here + // are no holes below) + *e = TileEntry::with_holes(e.pool, 0xFFFF); + self.to_zero.insert((t, TILE)); + self.mirrored -= 1; + early_add(&mut self.runs, t, t + TILE); + MAPPED_GEN.fetch_add(1, Ordering::Release); + } + } + match t.checked_add(TILE) { + Some(next) => t = next, + None => break, + } + } + } + if lazy_commits() { + self.ensure_listed(a, n); + } else { + self.ensure_mapped(a, n, |_| (0xFFFF, 0)); + } let mut pg = a & !(PAGE - 1); let end = a.saturating_add(n); while pg < end { @@ -3642,10 +5828,31 @@ impl State { /// them and frees their pool tiles) unsafe fn decommit_range(&mut self, a: usize, n: usize) { let mut pools: Vec<(usize, (u32, u32))> = Vec::new(); - let mut t = a & !(TILE - 1); let end = a.saturating_add(n); + // tiles over a CPU view go as a whole (their holes are the CPU view's pages, not these) + if !self.mirror_src.is_empty() { + let mut t = a & !(TILE - 1); + while t < end { + if self.mirror_src.contains_key(&t) { + self.drop_mirror(t); + } + match t.checked_add(TILE) { + Some(next) => t = next, + None => break, + } + } + if self.parked.len() >= PARKED_MAX && self.flush_parked() { + self.retire_free_pools(); + } + } + // a CPU view in a window (a title's reservation of 64 KiB pages a GPU view shows): the + // tiles over it have holes there too (below, only the entries of these addresses get them) + if !self.src_runs.is_empty() { + self.source_decommitted_in(a, n); + } + let mut t = a & !(TILE - 1); while t < end { - if let Some(e) = self.mapped.get(&t) { + if let Some(e) = self.mapped.get(&t).filter(|e| e.pool != LAZY) { pools.push((t, e.pool)); } match t.checked_add(TILE) { @@ -3658,8 +5865,8 @@ impl State { if tiles.is_empty() { return; } - self.runs = None; for &t in &tiles { + early_remove(&mut self.runs, t, t + TILE); if let Ok(i) = pools.binary_search_by_key(&t, |p| p.0) { self.parked.insert(t, pools[i].1); } @@ -3671,14 +5878,46 @@ impl State { } } - /// a pool tile no window maps, none is parked on and no buffer uses goes back to the free list - fn release_if_unused(&mut self, tile: (u32, u32)) { - if !self.pinned.contains_key(&tile) - && !self.mapped.values().any(|e| e.pool == tile) - && !self.parked.values().any(|&p| p == tile) + /// A pool tile a buffer used at `t` is freed (`cooling`), unless its window maps it, it + /// is parked there, it waits in `quarantined`, or another buffer uses it. Kept mapped for + /// the buffer: parked from here on. + fn release_if_unused(&mut self, t: usize, tile: (u32, u32)) { + if self.pinned.contains_key(&tile) { + return; + } + if self.kept.get(&t) == Some(&tile) { + self.kept.remove(&t); + self.parked.insert(t, tile); + return; + } + if self.mapped.get(&t).is_none_or(|e| e.pool != tile) + && self.parked.get(&t) != Some(&tile) && !self.quarantined.iter().any(|b| b.tiles.contains(&tile)) { - self.free.push(tile); + self.cooling.push_back((tile, std::time::Instant::now())); + } + } + + /// The fence `quarantine_tiles_for` signals on title queue `q` after its work, made now (once per + /// queue; a queue of another device, e.g. an isolated unit test's, is left out). Which queues + /// get a mark is `present`'s registry (`queue_completion_snapshot`), so a queue is never kept + /// alive here; `forget_queue` drops its entry when it goes. False: no fence could be made. + #[cfg(test)] + unsafe fn note_queue(&mut self, q: &ID3D12CommandQueue) -> bool { + let key = q.as_raw() as usize; + if key == self.queue.as_raw() as usize || self.queue_fences.contains_key(&key) { + return true; + } + let mut qdev: Option = None; + if q.GetDevice(&mut qdev).is_err() || qdev.as_ref().is_none_or(|d| d.as_raw() != self.dev.as_raw()) { + return true; + } + match self.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) { + Ok(fence) => { + self.queue_fences.insert(key, (fence, 0)); + true + } + Err(_) => false, } } @@ -3725,9 +5964,11 @@ impl State { break; } } - self.quarantined.push_back(RetiredTiles { tiles, marks: ok.then_some(marks) }); + self.quarantined.push_back(RetiredTiles { tiles, marks: ok.then_some(marks), at: std::time::Instant::now() }); } + /// The `quarantined` tiles the GPU is past (`completed` answers for a fence) go to `cooling` + /// (from when they were unmapped). unsafe fn drain_quarantined_with(&mut self, mut completed: impl FnMut(&ID3D12Fence) -> u64) -> bool { let mut freed = false; while let Some(front) = self.quarantined.front() { @@ -3736,9 +5977,10 @@ impl State { break; } let batch = self.quarantined.pop_front().unwrap(); + let at = batch.at; for tile in batch.tiles { if !self.pinned.contains_key(&tile) { - self.free.push(tile); + self.cooling.push_back((tile, at)); freed = true; } } @@ -3746,14 +5988,16 @@ impl State { freed } + /// `drain_quarantined_with` XCL's own query of the fences: the title's `GetCompletedValue` + /// hook takes the state's lock, which the caller holds. unsafe fn drain_quarantined(&mut self) -> bool { - self.drain_quarantined_with(|fence| fence.GetCompletedValue()) + self.drain_quarantined_with(|fence| super::real::fence_completed(fence)) } - /// The parked tiles unmapped from their windows (one call per window) and their unpinned - /// pool tiles quarantined behind `self.queue` and every known title queue's completion fence. - /// Pools left all free are not retired here: callers do that (`retire_free_pools`) unless - /// they take a tile right away. + /// The parked tiles unmapped from their windows (one call per window) and their pool tiles + /// (but those of placed buffers) quarantined behind `self.queue` and every known title + /// queue's completion fence, then freed to `cooling` (`drain_quarantined`). Pools left all + /// free are not retired here: callers do that (`retire_free_pools`). unsafe fn flush_parked(&mut self) -> bool { self.flush_parked_with(None) } @@ -3784,15 +6028,24 @@ impl State { let mut by_window: FxHashMap> = FxHashMap::default(); let mut tiles: Vec<(u32, u32)> = Vec::new(); for (t, tile) in std::mem::take(&mut self.parked) { + // (a placed buffer uses it) + if self.pinned.contains_key(&tile) { + self.kept.insert(t, tile); + continue; + } if let Some(wi) = self.window_index(t) { by_window.entry(wi).or_default().push(t); } - if !self.pinned.contains_key(&tile) { - tiles.push(tile); - } + tiles.push(tile); + } + if by_window.is_empty() { + // (nothing to unmap) + self.quarantine_tiles_for(tiles, queues, retiring, blocked); + return false; } for (wi, ts) in by_window { let (b, r) = (self.windows[wi].0, self.windows[wi].1.clone()); + TILE_WORK[2].fetch_add(ts.len() as u64, Ordering::Relaxed); self.unmap_tiles(&r, b, &ts); } self.mapping_epoch = self.mapping_epoch.wrapping_add(1); @@ -3811,7 +6064,8 @@ pub fn known_writable(p: usize, n: usize) -> bool { return false; } { - let state = STATE.lock().unwrap(); + let state = lock_in_turn(&STATE, &SUBMITS_WAITING); + let _held = holding(Holder::Other); let Some(state) = state.as_ref() else { return false }; if !recorded_committed(&state.mapped, p, end) { return false; @@ -3820,8 +6074,11 @@ pub fn known_writable(p: usize, n: usize) -> bool { resident_pages_writable(p, end) } -/// Every page touched by `[p, end)` has video-memory backing, is committed, and has not been -/// given a non-writable protection. Check one 64 KiB tile at a time while holding `STATE`. +/// Every page touched by `[p, end)` is recorded (a tile of the window's own, with video memory or +/// `LAZY`), is committed, and has not been given a non-writable protection. A tile over a CPU view +/// (`TileEntry::src`) is never: its own address is no CPU memory (the title reserved it with no +/// access) and its `holes` are the CPU view's pages. Check one 64 KiB tile at a time while +/// holding `STATE`. fn recorded_committed(mapped: &FxHashMap, p: usize, end: usize) -> bool { let mut tile = p & !(TILE - 1); while tile < end { @@ -3830,7 +6087,7 @@ fn recorded_committed(mapped: &FxHashMap, p: usize, end: usize let last = (tile_end - 1 - tile) / PAGE; let pages = last - first + 1; let mask = ((((1u32 << pages) - 1) << first) & u16::MAX as u32) as u16; - if !mapped.get(&tile).is_some_and(|entry| (entry.holes | entry.not_rw) & mask == 0) { + if !mapped.get(&tile).is_some_and(|entry| entry.src == 0 && (entry.holes | entry.not_rw) & mask == 0) { return false; } if tile_end <= tile { @@ -3846,7 +6103,8 @@ fn recorded_committed(mapped: &FxHashMap, p: usize, end: usize pub fn protection_changed(a: usize, n: usize, writable: bool) { let Some(end) = a.checked_add(n) else { return }; let Some(uma) = crate::gpu::uma::get() else { return }; - let mut state = STATE.lock().unwrap(); + let mut state = lock_in_turn(&STATE, &SUBMITS_WAITING); + let _held = holding(Holder::Commits); for k in 0..uma.shader_windows() { if !uma.is_sparse_window(k) { continue; @@ -3924,1988 +6182,4566 @@ fn resident_pages_writable(p: usize, end: usize) -> bool { true } -/// The sparse windows' tiles with video memory as sorted (start, end) runs: where a CPU write -/// has to reach the GPU. -pub fn mapped_ranges() -> Vec<(usize, usize)> { - let mut g = lock_state(); - let Some(s) = g.as_mut() else { return Vec::new() }; - if s.runs.is_none() { - let mut tiles: Vec = s.mapped.keys().copied().collect(); - tiles.sort_unstable(); - let mut runs: Vec<(usize, usize)> = Vec::new(); - for t in tiles { - match runs.last_mut() { - Some(last) if last.1 == t => last.1 = t + TILE, - _ => runs.push((t, t + TILE)), - } - } - s.runs = Some(runs); - } - s.runs.clone().unwrap_or_default() +/// Window tiles asked for by `map_mirror`: each is queued once, until it is forgotten +/// (`forget_mirrors`) or left out (`State::map_mirrors`). +static MIRROR_ASKED: super::sharded::Sharded<()> = super::sharded::Sharded::new(); +/// How often a tile left `MIRROR_ASKED` (a view that went, a tile given back with its source): +/// whoever remembers having asked (`view_want`'s threads) asks again. +static MIRROR_FORGOTTEN: AtomicU64 = AtomicU64::new(0); + +/// Counts up whenever a tile that was asked for may be asked for again (`map_mirror` would +/// queue it): a caller that keeps what it asked for forgets it when this changes. +pub fn mirror_asks_forgotten() -> u64 { + MIRROR_FORGOTTEN.load(Ordering::Acquire) } -const LOOK_FIELDS: usize = 37; -const ACTIVE_US: usize = 0; -const REFRESH_WAIT_US: usize = 1; -const WATCH_US: usize = 2; -const PAGES: usize = 3; -const LOOKS: usize = 4; -const WATCHED: usize = 5; -const RANGES: usize = 6; -const QUEUE_WAIT_US: usize = 7; -const MAINTENANCE_US: usize = 8; -const SCAN_US: usize = 9; -const UPLOAD_US: usize = 10; -const RUNS: usize = 11; -const TRANSFER_BYTES: usize = 12; -const UPLOAD_WAIT_US: usize = 13; -const SUBMIT_GATE_WAIT_US: usize = 14; -const SUBMIT_GATE_HOLD_US: usize = 15; -const READBACK_GATE_WAIT_US: usize = 16; -const READBACK_GATE_HOLD_US: usize = 17; -const READBACK_GATE_RELEASED_US: usize = 18; -const TEXTURE_SELECT_WAIT_US: usize = 19; -const TEXTURE_SELECT_HOLD_US: usize = 20; -const TEXTURES_VISITED: usize = 21; -const TEXTURE_DIRTY_TESTS: usize = 22; -const TEXTURE_MATCHES: usize = 23; -const TEXTURES_RETAINED: usize = 24; -const VRAM_GATE_WAIT_US: usize = 25; -const VRAM_DEVICE_US: usize = 26; -const VRAM_UNMAP_POLL_US: usize = 27; -const VRAM_STATE_US: usize = 28; -const VRAM_QUEUE_WAIT_US: usize = 29; -const VRAM_RETIREMENT_US: usize = 30; -const VRAM_DEVICE_CACHE_HITS: usize = 31; -const VRAM_DEVICE_QUERIES: usize = 32; -const VRAM_CALLS: usize = 33; -const VRAM_MAPPING_WAITS: usize = 34; -const VRAM_RECLAIM_PASSES: usize = 35; -const VRAM_RETIREMENT_PASSES: usize = 36; +/// Tile `t` is asked for no more. +fn forget_ask(t: usize) { + if MIRROR_ASKED.remove(t).is_some() { + MIRROR_FORGOTTEN.fetch_add(1, Ordering::Release); + #[cfg(test)] + tests::ASKS_FORGOTTEN.with(|n| n.set(n.get() + 1)); + } +} +/// The tiles asked for that no submit has taken yet. A lock of its own: `map_mirror` is called +/// while recording, on any thread, and never waits for `STATE`. +static MIRROR_ASKS: Mutex> = Mutex::new(Vec::new()); +static MIRROR_ASKING: AtomicBool = AtomicBool::new(false); -/// One complete `XCL_ACTIVITY` look. It is built without shared updates, then published once so -/// the reporting thread cannot split one look across adjacent intervals. -pub(super) struct LookSample([u64; LOOK_FIELDS]); +/// What a thread that decommits the title's CPU memory needs to know of the tiles over CPU views, +/// and what a submit needs to know of those decommits. A lock of its own, which takes no other: +/// a decommit asks it with no lock of the state's (most of them are of memory no tile shows, and +/// a title's loading threads decommit all the time), a submit with `STATE` held. +#[derive(Default)] +struct Sources { + /// `State::src_runs`, changed with it (`link_mirror`, `unlink_mirror`) + runs: BTreeMap, + /// the pages `[start, end)` of decommits under way (`source_decommit`): told, Windows not + /// done yet. A submit takes them as holes, whatever Windows says of them for now + freeing: Vec<(usize, usize)>, +} -impl Default for LookSample { - fn default() -> Self { - Self([0; LOOK_FIELDS]) +impl Sources { + /// Whether tiles show any of `[a, end)` + fn shows(&self, a: usize, end: usize) -> bool { + self.runs.range(..end).next_back().is_some_and(|(_, &e)| e > a) } } -impl LookSample { - pub(super) fn add(&mut self, field: usize, value: u64) { - self.0[field] = self.0[field].wrapping_add(value); - } +static SOURCES: Mutex = Mutex::new(Sources { runs: BTreeMap::new(), freeing: Vec::new() }); - pub(super) fn add_time(&mut self, field: usize, value: std::time::Duration) { - self.add(field, value.as_micros() as u64); +fn lock_sources(m: &Mutex) -> std::sync::MutexGuard<'_, Sources> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// A decommit of the pages of `[a, a + n)` begins: submits take them as holes until it ends +/// (`freeing_ends` with the span returned). True: tiles show some of them, and the state has to +/// be told before Windows frees them. Either a submit linked a tile there before this (and the +/// state is told), or it links it after and finds the pages here (in the one lock, in turn). +fn freeing_begins(m: &Mutex, a: usize, n: usize) -> ((usize, usize), bool) { + let span = page_span(a, n); + let mut l = lock_sources(m); + l.freeing.push(span); + (span, l.shows(span.0, span.1)) +} + +/// The decommit of `span` (`freeing_begins`) is done. +fn freeing_ends(m: &Mutex, span: (usize, usize)) { + let mut l = lock_sources(m); + if let Some(i) = l.freeing.iter().position(|&f| f == span) { + l.freeing.swap_remove(i); } } -/// Cumulative complete looks. Disabled title submission never locks or updates this mutex. -static LOOK: Mutex<[u64; LOOK_FIELDS]> = Mutex::new([0; LOOK_FIELDS]); +/// What window tile `g` shows (`tile_shows`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Under { + /// not in a GPU view + NoView, + /// nothing (zeros): unmapped by the queue's page mappings, no page behind it, or a page kept + /// where kernelx does not see the memory go (no tile may show it there) + Nothing, + /// the 64 KiB-aligned CPU tile: the CPU view's at the same offset, or where the page mapped + /// there is kept + Cpu(usize), +} -fn merge_look(total: &mut [u64; LOOK_FIELDS], sample: [u64; LOOK_FIELDS]) { - for (total, value) in total.iter_mut().zip(sample) { - *total = total.wrapping_add(value); +/// What window tile `g` of a GPU view shows (`kernelx::mirrors::shows`; locks of its own, which +/// take no other: it may be asked with `STATE` held). While nothing is mapped, the CPU view's tile +/// as before. +fn tile_shows(g: usize) -> Under { + use crate::hle::kernelx::mirrors::{shows, Shows}; + match shows(g) { + Shows::NoView => Under::NoView, + Shows::Same(c) => Under::Cpu(c & !(TILE - 1)), + Shows::Page { at, tile: true } => Under::Cpu(at & !(TILE - 1)), + Shows::Page { .. } | Shows::Nothing => Under::Nothing, } } -fn add_gate_times(sample: &mut [u64; LOOK_FIELDS], wait: usize, hold: usize, released: Option, times: UploadGateTimes) { - sample[wait] = sample[wait].wrapping_add(times.wait_us); - sample[hold] = sample[hold].wrapping_add(times.hold_us); - if let Some(released) = released { - sample[released] = sample[released].wrapping_add(times.released_us); +/// The 64 KiB-aligned CPU tile behind window tile `g` of a GPU view (`tile_shows`). +fn mirror_source_tile(g: usize) -> Option { + match tile_shows(g) { + Under::Cpu(c) => Some(c), + _ => None, } } -fn note_readback_gate(times: UploadGateTimes) { - let mut total = LOOK.lock().unwrap(); - add_gate_times( - &mut total, READBACK_GATE_WAIT_US, READBACK_GATE_HOLD_US, Some(READBACK_GATE_RELEASED_US), times, - ); +/// 64 KiB of XCL's own, reserved and never committed: the source of a tile that shows nothing but +/// keeps its video memory, as a placed buffer maps its tiles once (`buffer_tiles`, +/// `remap_mirrors`). Its pages are always holes: nothing scans it, and no copy back lands there. +fn no_source() -> usize { + static AT: std::sync::OnceLock = std::sync::OnceLock::new(); + *AT.get_or_init(|| { + use windows_sys::Win32::System::Memory::MEM_RESERVE; + unsafe { VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE, PAGE_NOACCESS) as usize } + }) } -pub(super) fn note_watch(sample: &mut LookSample, t: std::time::Duration, pages: usize, watched: usize, ranges: usize) { - sample.add_time(WATCH_US, t); - sample.add(PAGES, pages as u64); - sample.add(WATCHED, watched as u64); - sample.add(RANGES, ranges as u64); -} +/// Window tiles whose page the queue's page mappings changed (`remapped`), for the next submit to +/// link again (`State::remap_mirrors`). A lock of its own, as `MIRROR_ASKS`. +static REMAPS: Mutex> = Mutex::new(Vec::new()); +static REMAPPING: AtomicBool = AtomicBool::new(false); -pub(super) fn note_texture_selection( - sample: &mut LookSample, - wait: std::time::Duration, - hold: std::time::Duration, - visited: usize, - dirty_tests: usize, - matches: usize, - retained: usize, -) { - sample.add_time(TEXTURE_SELECT_WAIT_US, wait); - sample.add_time(TEXTURE_SELECT_HOLD_US, hold); - sample.add(TEXTURES_VISITED, visited as u64); - sample.add(TEXTURE_DIRTY_TESTS, dirty_tests as u64); - sample.add(TEXTURE_MATCHES, matches as u64); - sample.add(TEXTURES_RETAINED, retained as u64); +/// What the GPU-view tiles `tiles` show changed (`kernelx::mirrors`: a mapping, an unmap, a freed +/// page, a page that got or lost its place): those asked for (`map_mirror`) are linked again at +/// the next submit. Any thread; no state's lock. +pub fn remapped(tiles: &[usize]) { + let asked: Vec = tiles.iter().copied().filter(|&t| MIRROR_ASKED.contains(t)).collect(); + if asked.is_empty() { + return; + } + REMAPS.lock().unwrap().extend(asked); + REMAPPING.store(true, Ordering::Release); } -fn note_vram_before_execute(sample: &mut LookSample, timing: super::vram::BeforeExecuteTiming) { - sample.add_time(VRAM_GATE_WAIT_US, timing.gate_wait); - sample.add_time(VRAM_DEVICE_US, timing.device); - sample.add_time(VRAM_UNMAP_POLL_US, timing.unmap_poll); - sample.add_time(VRAM_STATE_US, timing.state); - sample.add_time(VRAM_QUEUE_WAIT_US, timing.queue_wait); - sample.add_time(VRAM_RETIREMENT_US, timing.retirement); - sample.add(VRAM_DEVICE_CACHE_HITS, timing.device_cache_hits as u64); - sample.add(VRAM_DEVICE_QUERIES, timing.device_queries as u64); - sample.add(VRAM_CALLS, timing.calls as u64); - sample.add(VRAM_MAPPING_WAITS, timing.mapping_waits as u64); - sample.add(VRAM_RECLAIM_PASSES, timing.reclaim_passes as u64); - sample.add(VRAM_RETIREMENT_PASSES, timing.retirement_passes as u64); +/// The tiles of `q` (`REMAPS`) join those waiting to be linked again (`State::remaps`). Past +/// `MIRROR_ASKS_MAX` the queue is sorted and each tile kept once: a page changed at every frame, +/// or by several calls, waits once, and the queue holds no more than the tiles asked for. +fn take_remaps(remaps: &mut Vec, q: &mut Vec) { + remaps.append(q); + if remaps.len() > MIRROR_ASKS_MAX { + remaps.sort_unstable(); + remaps.dedup(); + } } -pub(super) fn note_look(mut sample: LookSample, active: std::time::Duration, refresh_wait: std::time::Duration) { - if let Some(timing) = super::vram::take_before_execute_timing() { - note_vram_before_execute(&mut sample, timing); +/// The physical page the GPU-view tiles `tiles` show moved from `from` to `to` (both 64 KiB +/// aligned; `whole`: its bytes were copied there): the tiles linked over `from` follow it now, +/// with their video memory (`State::retarget`). Called on the moving thread (kernelx, AWAY held) +/// before the memory at `from` can go. The state's lock only when tiles show `from` (it gives way +/// to submits). +pub unsafe fn moved(tiles: &[usize], from: usize, to: usize, whole: bool) { + if tiles.is_empty() || from == 0 || to == 0 || !lock_sources(&SOURCES).shows(from, from + TILE) { + return; + } + let mut g = lock_in_turn(&STATE, &SUBMITS_WAITING); + let _held = holding(Holder::Sources); + forget_released(&mut g); + let Some(s) = g.as_mut() else { return }; + for &w in tiles { + s.retarget(w, from, to, whole); } - sample.add_time(ACTIVE_US, active); - sample.add_time(REFRESH_WAIT_US, refresh_wait); - sample.add(LOOKS, 1); - let mut total = LOOK.lock().unwrap(); - merge_look(&mut total, sample.0); } -pub fn look_counters() -> [u64; LOOK_FIELDS] { - *LOOK.lock().unwrap() +/// The GPU-view tiles linked again so far: [to show what the page mappings put there (or nothing), +/// that followed their page]. +static VIEW_TILES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// `VIEW_TILES` so far. +pub fn page_tiles() -> [u64; 2] { + std::array::from_fn(|k| VIEW_TILES[k].load(Ordering::Relaxed)) } -pub fn look_delta(now: [u64; LOOK_FIELDS], before: [u64; LOOK_FIELDS]) -> [u64; LOOK_FIELDS] { - std::array::from_fn(|i| now[i].wrapping_sub(before[i])) +/// The CPU tile a placed buffer's tile is linked over for what it shows: a tile that shows nothing +/// keeps its video memory over `no_source` (the buffer maps its tiles once). None: no view. +fn buffer_source(under: Under) -> Option { + match under { + Under::Cpu(c) => Some(c), + Under::Nothing => Some(no_source()).filter(|&n| n != 0), + Under::NoView => None, + } } -/// Active foreground elapsed time and serialization wait before title submits in one interval. -pub fn look_line(d: [u64; LOOK_FIELDS], secs: u64) -> String { - let [ - active, refresh_wait, watch, pages, looks, watched, ranges, queue_wait, maintenance, scan, upload, - runs, transfer_bytes, upload_wait, submit_gate_wait, submit_gate_hold, readback_gate_wait, - readback_gate_hold, readback_gate_released, texture_select_wait, texture_select_hold, - textures_visited, texture_dirty_tests, texture_matches, textures_retained, - vram_gate_wait, vram_device, vram_unmap_poll, vram_state, vram_queue_wait, vram_retirement, - vram_device_cache_hits, vram_device_queries, vram_calls, vram_mapping_waits, - vram_reclaim_passes, vram_retirement_passes, - ] = d; - let ms = |us: u64| us / 1000; - let sparse = queue_wait.saturating_add(maintenance).saturating_add(scan).saturating_add(upload).saturating_add(upload_wait); - let texture_select = texture_select_wait.saturating_add(texture_select_hold); - let vram = vram_gate_wait - .saturating_add(vram_device) - .saturating_add(vram_unmap_poll) - .saturating_add(vram_state) - .saturating_add(vram_queue_wait) - .saturating_add(vram_retirement); - format!( - "looks before submits ({secs} s): {looks} looks did {} ms active work ({:.1} % of the time) after {} ms waiting for the refresh turn: write-watch {} ms ({:.1} MB in {:.1} ranges/look, {pages} pages written); texture select wait/hold {}/{} ms ({textures_visited} visited, {texture_dirty_tests} dirty-tested, {texture_matches} matched, {textures_retained} retained); sparse queue wait/fence+state/scan/upload/ownership wait {}/{}/{}/{}/{} ms ({runs} runs, {:.1} MB zero/dirty bytes); VRAM gate/device/unmap poll/state/queue wait/retire {}/{}/{}/{}/{}/{} ms ({vram_calls} calls, {vram_device_cache_hits} device-cache hits, {vram_device_queries} GetDevice queries, {vram_mapping_waits} mapping waits, {vram_reclaim_passes} reclaim passes, {vram_retirement_passes} retirement passes); upload gate submit wait/hold {}/{} ms, readback wait/hold/released wait+reacquire {}/{}/{} ms; other active work {} ms", - ms(active), - active as f64 / (secs.max(1) * 10_000) as f64, - ms(refresh_wait), - ms(watch), - watched as f64 / looks.max(1) as f64 / (1 << 20) as f64, - ranges as f64 / looks.max(1) as f64, - ms(texture_select_wait), - ms(texture_select_hold), - ms(queue_wait), - ms(maintenance), - ms(scan), - ms(upload), - ms(upload_wait), - transfer_bytes as f64 / (1 << 20) as f64, - ms(vram_gate_wait), - ms(vram_device), - ms(vram_unmap_poll), - ms(vram_state), - ms(vram_queue_wait), - ms(vram_retirement), - ms(submit_gate_wait), - ms(submit_gate_hold), - ms(readback_gate_wait), - ms(readback_gate_hold), - ms(readback_gate_released), - ms(active.saturating_sub(watch.saturating_add(sparse).saturating_add(texture_select).saturating_add(vram))) - ) +/// The window tiles of `[va, va + len)` are to show the title's CPU view behind them (`va` in a +/// GPU view of its memory, `kernelx::mirrors`): video memory, filled from the CPU view and kept in +/// step with it, from the next submit on. Any thread; it waits for no submit (no `STATE`) and +/// asks Windows nothing. Tiles that are not in a sparse window or in a GPU view are left out +/// there. Returns how many of its tiles were queued now (the others were asked for before). +pub fn map_mirror(va: usize, len: usize) -> usize { + if len == 0 { + return 0; + } + let end = va.saturating_add(len); + let mut new: Vec = Vec::new(); + let mut t = va & !(TILE - 1); + while t < end { + if MIRROR_ASKED.insert(t, ()).is_none() { + new.push(t); + } + match t.checked_add(TILE) { + Some(next) => t = next, + None => break, + } + } + if new.is_empty() { + return 0; + } + let queued = new.len(); + if view_switches().stats { + VIEW_ASKED.fetch_add(queued as u64, Ordering::Relaxed); + } + MIRROR_ASKS.lock().unwrap().extend(new); + MIRROR_ASKING.store(true, Ordering::Release); + queued } -fn poll_unique(mut fences: Vec, key: impl Fn(&F) -> usize, mut completed: impl FnMut(&F) -> u64) -> Vec<(F, u64)> { - fences.sort_unstable_by_key(&key); - fences.dedup_by(|a, b| key(a) == key(b)); - fences.into_iter().map(|fence| { - let value = completed(&fence); - (fence, value) - }).collect() +/// The title's CPU memory `[a, a + n)` is decommitted by `os` (the caller's VirtualFree, called +/// with no lock of XCL's held; its result is returned): the tiles shown over it have holes +/// there first (`source_decommitted`), and while `os` runs a submit takes those pages as holes, +/// whatever Windows says of them. Told only before the decommit, a submit in between asked Windows +/// about a page written before, found it still committed, read it as Windows freed it, and left it +/// committed in its tile for good (a later copy back or immediate wrote to it). The state's lock +/// is taken only when tiles show some of the range. +pub unsafe fn source_decommit(a: usize, n: usize, os: impl FnOnce() -> R) -> R { + if n == 0 { + return os(); + } + let (span, shown) = freeing_begins(&SOURCES, a, n); + if shown { + source_decommitted(a, n); + } + let r = os(); + freeing_ends(&SOURCES, span); + r } -fn observed_completion(observed: &[(F, u64)], fence: &F, same: impl Fn(&F, &F) -> bool) -> u64 { - observed.iter().find_map(|(known, value)| same(known, fence).then_some(*value)).unwrap_or(0) +/// `source_decommit` for a release of the title's CPU memory `[a, a + n)` by `os`: after it the +/// tiles over it are forgotten as well (`forget_mirrors`: the address may be given out anew), +/// before the pages stop being holes for submits. Drop the pair (`kernelx::mirrors::released`) +/// before `os` returns, so that no tile is linked over the address after the forget. +pub unsafe fn source_release(a: usize, n: usize, os: impl FnOnce() -> R) -> R { + if n == 0 { + return os(); + } + let (span, shown) = freeing_begins(&SOURCES, a, n); + if shown { + source_decommitted(a, n); + } + let r = os(); + forget_mirrors(a, n); + freeing_ends(&SOURCES, span); + r } -fn reserve_queue_wait(waited: &mut FxHashMap, queue: usize, value: u64) -> bool { - if value == 0 || waited.get(&queue).copied().unwrap_or(0) >= value { - return false; +/// The part of `source_decommit` that tells the state: the tiles shown over the title's CPU +/// memory `[a, a + n)` have holes there, cleared on the GPU (`sent = None` says the GPU holds +/// zeros), and a tile with no committed page left gives its video memory back. A submit's scan +/// reads those pages with the state's lock held: after this it does not – unless it asks Windows +/// before the decommit lands, which only `source_decommit` rules out (call that). +pub unsafe fn source_decommitted(a: usize, n: usize) { + if n == 0 { + return; } - waited.insert(queue, value); - true + let (start, end) = page_span(a, n); + if !lock_sources(&SOURCES).shows(start, end) { + return; + } + let mut g = lock_in_turn(&STATE, &SUBMITS_WAITING); + let _held = holding(Holder::Sources); + forget_released(&mut g); + let Some(s) = g.as_mut() else { return }; + s.source_decommitted_in(a, n); } -fn retry_journal(outcome: PreparationOutcome, mut deferred: Vec, runs: &[(usize, usize)]) -> Vec { - if outcome != PreparationOutcome::Ready { - for &(a, n) in runs { - let mut pg = a & !(PAGE - 1); - let end = a.saturating_add(n); - while pg < end { - deferred.push(pg); - pg += PAGE; - } +/// `[a, a + n)` is no GPU view or CPU view any more (released, or the pair is gone): tiles in it, +/// or over CPU memory in it, show nothing from here on (their video memory goes back), and may be +/// asked for again (the addresses may be given out anew). Call it once the pair is dropped +/// (`kernelx::mirrors::released`): with no tile linked anywhere it takes no state's lock, and a +/// tile linked after that looks its pair up again (`State::take_asks`), so one of the two sees +/// the other. +pub fn forget_mirrors(a: usize, n: usize) { + if n == 0 { + return; + } + let end = a.saturating_add(n); + // (out of the queue before out of the set: an ask in between finds the tile still asked + // for, or stays queued, and the count after it has the thread ask again. The other way + // round, an ask in between went with the queue and left the tile asked for, never mapped) + MIRROR_ASKS.lock().unwrap().retain(|&t| !(t < end && t + TILE > a)); + #[cfg(test)] + if let Some(f) = tests::BETWEEN_FORGETS.with(|f| f.take()) { + f(); + } + let mut asked: Vec = Vec::new(); + MIRROR_ASKED.for_each(|t, _| { + if t < end && t + TILE > a { + asked.push(t); } + }); + for t in asked { + forget_ask(t); } - deferred.sort_unstable(); - deferred.dedup(); - deferred + if lock_sources(&SOURCES).runs.is_empty() { + return; + } + let mut g = lock_in_turn(&STATE, &SUBMITS_WAITING); + let _held = holding(Holder::Sources); + forget_released(&mut g); + let Some(s) = g.as_mut() else { return }; + unsafe { s.forget_mirrors_in(a, end) }; } -fn remember_metric_runs(seen: &mut BTreeMap, runs: &[(usize, usize)]) { - for &(a, n) in runs { - early_add(seen, a, a.saturating_add(n)); +/// The CPU address behind window address `va`, for what reads or writes the title's memory +/// there: `va` itself, unless it lies in a GPU view of the title's CPU memory, whose tiles show +/// their CPU view (`State::map_mirrors` takes them by the same rule), or where the page the +/// queue's page mappings put there is kept (wherever that is: the CPU reads and writes any). No +/// `STATE`. +pub fn cpu_of(va: usize) -> usize { + use crate::hle::kernelx::mirrors::{shows, Shows}; + match shows(va) { + Shows::Same(c) | Shows::Page { at: c, .. } => c, + Shows::NoView | Shows::Nothing => va, } } -fn note_transfer_metrics( - sample: Option<&mut LookSample>, seen: Option<&(BTreeMap, BTreeMap)>, -) { - let (Some(sample), Some((zero, dirty))) = (sample, seen) else { return }; - sample.add(RUNS, (zero.len() + dirty.len()) as u64); - let bytes = zero.iter().chain(dirty).fold(0usize, |sum, (&a, &b)| sum.saturating_add(b.saturating_sub(a))); - sample.add(TRANSFER_BYTES, bytes as u64); -} +impl State { + /// Window tile `w` shows CPU tile `c` (with video memory or not yet). + fn link_mirror(&mut self, w: usize, c: usize) { + self.mirror_src.insert(w, c); + let over = self.mirrors.entry(c).or_default(); + over.push(w); + if over.len() == 1 { + early_add(&mut self.src_runs, c, c + TILE); + // (before the CPU tile's pages are asked about: a decommit from here on tells) + early_add(&mut lock_sources(self.sources).runs, c, c + TILE); + MAPPED_GEN.fetch_add(1, Ordering::Release); + } + } + + /// Window tile `w` shows no CPU tile any more (its entry in `mapped`, if any, is the caller's), + /// and may be asked for again. False: it showed none. + fn unlink_mirror(&mut self, w: usize) -> bool { + let linked = self.unlink_kept(w); + if linked { + forget_ask(w); + } + linked + } + + /// `unlink_mirror`, the ask kept: `w` is linked again (`remap_mirrors`), or waits asked for + /// until its GPU-view page shows something. (Forgotten, every recording thread's memory of its + /// asks would empty at each such change, `view_want`.) + fn unlink_kept(&mut self, w: usize) -> bool { + let Some(c) = self.mirror_src.remove(&w) else { return false }; + if let Some(over) = self.mirrors.get_mut(&c) { + over.retain(|&x| x != w); + if over.is_empty() { + self.mirrors.remove(&c); + early_remove(&mut self.src_runs, c, c + TILE); + early_remove(&mut lock_sources(self.sources).runs, c, c + TILE); + MAPPED_GEN.fetch_add(1, Ordering::Release); + } + } + self.refused.remove(&w); + true + } -fn rollback_queue_wait(waited: &mut FxHashMap, queue: usize, value: u64, previous: Option) { - if waited.get(&queue) != Some(&value) { - return; + /// Window tile `w` shows its CPU tile no more: its video memory is parked (unmapped before the + /// next submit), and it may be asked for again. + fn drop_mirror(&mut self, w: usize) { + self.unlink_mirror(w); + self.park(w); } - match previous { - Some(previous) => { waited.insert(queue, previous); } - None => { waited.remove(&queue); } + + /// The video memory of window tile `w` over a CPU view is parked (unmapped before the next + /// submit, unless a placed buffer uses it, or it is taken back first: `new_mirror`). + fn park(&mut self, w: usize) { + if self.mapped.get(&w).is_some_and(|e| e.src != 0) { + let e = self.mapped.remove(&w).expect("a tile over a CPU view"); + while let Some(&piece) = self.to_zero.range((w, 0)..(w + TILE, 0)).next() { + self.to_zero.remove(&piece); + } + self.mirrored -= 1; + self.give_back(w, e.pool); + } } -} -/// Wait with both `STATE` and `UPLOAD_GATE` released. The caller's shared generation lease keeps -/// every old-state allocator, list, staging byte and destination alive. Only an exact ticket may -/// retire ring storage; a crossing uploader otherwise makes the caller rebuild from current state. -unsafe fn wait_upload_released(ticket: WaitTicket) -> bool { - loop { - match crate::gpu::fence::wait(&ticket.fence, ticket.target, &ticket.dev, None, 5000) { - Ok(()) => break, - Err(crate::gpu::fence::FenceError::Timeout(_)) => { - crate::xlog_warn!("sparse: upload retirement fence {} is still pending; STATE remains released", ticket.target); + /// The video memory `pool` of window tile `w` over a CPU view goes back (no longer counted in + /// `mirrored`): parked – or kept mapped there (`XCL_VIEW_KEEP`, `keep_view_tile`), to be taken + /// back as a parked tile is (`new_mirror`). + fn give_back(&mut self, w: usize, pool: (u32, u32)) { + if keep_view_tile(self.diag.keep, self.mirrored + 1 + self.kept.len(), self.mirror_cap) { + if self.diag.kept == 0 { + crate::xlog_info!("XCL_VIEW_KEEP: tiles over CPU views keep their video memory once filled ({} tiles at most)", self.mirror_cap); } - Err(e) => { - crate::xlog_warn!("sparse: upload retirement fence {} failed: {e}", ticket.target); + self.kept.insert(w, pool); + self.diag.kept += 1; + } else { + self.parked.insert(w, pool); + self.counts.given_back += 1; + } + if self.diag.stats { + // (a tile that never comes back is not kept for ever) + if self.diag.left_at.len() >= 1 << 20 { + self.diag.left_at.clear(); + } + self.diag.left_at.insert(w, self.diag.submits); + } + } + + /// Video memory for window tile `w` over CPU tile `src` (`holes`: its pages not committed + /// there): taken back from `parked` / `kept` (cleared; it is held already, so past + /// `mirror_cap` too: a kept tile refused stayed mapped there with old bytes), or a tile of a + /// pool (cleared when it was used before), mapped with the next flush; all of it goes up at + /// the next submit (`fill`). `force`: past `mirror_cap` too (it counts all the same), for a + /// placed buffer's tile: the buffer maps its tiles once, and video memory the window tile got + /// later would not be the buffer's. False: past `mirror_cap` (logged at powers of two) or no + /// video memory (now or a moment ago, `no_memory`): `w` is in `refused` then (counted once). + unsafe fn new_mirror(&mut self, w: usize, src: usize, holes: u16, force: bool) -> bool { + if let Some(tile) = self.parked.remove(&w).or_else(|| self.kept.remove(&w)) { + self.mapped.insert(w, TileEntry { src, gen: next_gen(), ..TileEntry::with_holes(tile, holes) }); + self.to_zero.insert((w, TILE)); + } else { + // (`XCL_VIEW_KEEP`: the tiles kept hold video memory too) + let held = self.mirrored + if self.diag.keep { self.kept.len() } else { 0 }; + let at_cap = !force && held >= self.mirror_cap; + if at_cap && self.diag.keep && !self.kept.is_empty() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("XCL_VIEW_KEEP: {} tiles kept and {} with video memory reach the cap of {} (XCL_MIRROR_MB) – tiles are refused from here on, and read zeros", self.kept.len(), self.mirrored, self.mirror_cap)); + } + // (a moment after a heap could not be made, only tiles at hand: parked ones and those + // still quarantined or cooling are not) + self.drain_quarantined(); + let at_hand = !self.free.is_empty() || cooled(&self.cooling, std::time::Instant::now()) || !self.retired.is_empty(); + let wait = at_cap || (!force && self.short_of_memory() && !at_hand); + let got = if wait { None } else { self.take_tile() }; + let Some((tile, reused)) = got else { + if !wait { + self.no_memory = Some(std::time::Instant::now()); + } + if self.refused.insert(w) { + self.counts.refused += 1; + let n = self.counts.refused; + if at_cap && n.is_power_of_two() { + crate::xlog_warn!("sparse: {n} GPU-view tiles left without video memory (XCL_MIRROR_MB) – the GPU reads zeros there"); + } + } return false; + }; + self.mapped.insert(w, TileEntry { src, gen: next_gen(), ..TileEntry::with_holes(tile, holes) }); + if reused { + self.to_zero.insert((w, TILE)); + } + self.pending.push(w); + } + self.refused.remove(&w); + self.fill.push(w); + self.mirrored += 1; + self.counts.peak = self.counts.peak.max(self.mirrored); + if self.diag.stats { + if let Some(at) = self.diag.left_at.remove(&w) { + self.diag.back[back_bucket(self.diag.submits - at)] += 1; + self.diag.back_bytes += ((PAGES_PER_TILE - holes.count_ones() as usize) * PAGE) as u64; } } + true } - let proceed = { - let mut g = lock_state(); - match g.as_mut() { - None => false, - Some(s) if s.generation != ticket.state_generation || s.fence.as_raw() != ticket.fence.as_raw() => { - // The caller's shared lifetime makes replacement impossible. Fail closed if a - // future teardown path violates that protocol. - false + + /// A tile over a CPU view found no video memory a moment ago (`no_memory`, 1 s) + fn short_of_memory(&self) -> bool { + self.no_memory.is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(1)) + } + + /// Tiles refused (`refused`) wait for video memory again (`later`) once there is room, as + /// many as there is room for and `MIRROR_ASKS_MAX` at most: what their CPU view held goes up + /// then (written once before, it may never be written again). One no longer linked or with + /// video memory leaves `refused`. + unsafe fn retry_refused(&mut self) { + if self.refused.is_empty() || self.mirrored >= self.mirror_cap || self.short_of_memory() { + return; + } + let room = (self.mirror_cap - self.mirrored).min(MIRROR_ASKS_MAX); + let mut take: Vec<(usize, usize)> = Vec::new(); + let mut gone: Vec = Vec::new(); + for &w in &self.refused { + if take.len() == room { + break; } - Some(s) if !s.uploads_ordered => false, - Some(s) => { - // Another uploader can retire/reuse this slot or ring range after the waited - // target completes. That invalidates exact ownership but not the completed fence; - // loop on current state. Reclaim only if neither it nor a remap crossed this ticket. - if s.wait_ticket_valid(&ticket) { - s.reclaim_ring(); + match self.mirror_src.get(&w) { + Some(&c) if !self.mapped.contains_key(&w) => take.push((w, c)), + _ => gone.push(w), + } + } + for w in gone { + self.refused.remove(&w); + } + // (in the order of their CPU tiles: a query for each region of them) + take.sort_unstable_by_key(|t| t.1); + self.later.extend(take); + } + + /// At the top of a submit: tiles shown over their CPU views get video memory and are filled + /// from them (`fill_later`), the committed pages of `fill_pages` at most (a burst of asks + /// hashed up to 256 MiB and pushed it through the staging ring with the state's lock held, + /// on the title's submitting thread). The tiles waiting from submits before go first, in + /// their order; then the tiles refused before, when there is room again (`retry_refused`); + /// then the tiles asked for since (`take_asks`). + unsafe fn map_mirrors(&mut self) { + let mut budget = self.fill_pages; + if self.later.is_empty() { + self.retry_refused(); + } + loop { + self.fill_later(&mut budget); + if budget == 0 || !self.later.is_empty() || self.asks.is_empty() { + return; + } + self.take_asks(); + } + } + + /// The tiles waiting in `later` (linked, oldest first) get video memory and are filled while + /// `budget` (committed pages) lasts; one whose CPU tile has no committed page leaves it (and + /// `refused`: a write there gives it video memory, `mirror_writes`). One refused for want of + /// room or video memory goes to `refused` (`new_mirror`). + unsafe fn fill_later(&mut self, budget: &mut usize) { + /// tiles asked about at a time + const BATCH: usize = 256; + while *budget > 0 && !self.later.is_empty() { + let batch: Vec<(usize, usize)> = self.later.iter().take(BATCH).copied().collect(); + let holes = self.holes_now(&batch.iter().map(|b| b.1).collect::>()); + let mut done = 0; + for (&(w, c), h) in batch.iter().zip(holes) { + if *budget == 0 { + break; + } + done += 1; + if self.mirror_src.get(&w) != Some(&c) || self.mapped.contains_key(&w) { + continue; + } + if h == 0xFFFF { + self.refused.remove(&w); + } else if self.new_mirror(w, c, h, false) { + *budget = budget.saturating_sub(PAGES_PER_TILE - h.count_ones() as usize); } - true + } + self.later.drain(..done); + if done < batch.len() { + return; } } - }; - drop(ticket); - proceed -} + } -/// Snapshot strong fence owners under `STATE`, then query them without it. A batch or a higher -/// mark added while polling is checked against the same observation; a new fence has no -/// observation and therefore remains quarantined. -unsafe fn poll_retirement_fences() -> Vec<(ID3D12Fence, u64)> { - let fences = { - let g = lock_state(); - let Some(s) = g.as_ref() else { return Vec::new() }; - std::iter::once(s.fence.clone()) - .chain(s.quarantined.iter().flat_map(|batch| batch.marks.iter().flatten().map(|(fence, _)| fence.clone()))) - .collect() - }; - poll_unique(fences, |fence| fence.as_raw() as usize, |fence| fence.GetCompletedValue()) -} + /// The tiles asked for (`asks`, `MIRROR_ASKS_MAX` at most at a time) linked over their CPU + /// views, to wait for their video memory in `later`: a tile of a sparse window in a GPU view + /// gets it unless its CPU tile has no committed page (it waits in `mirrors` for the CPU to + /// write there). Others are left out, and may be asked for again. + unsafe fn take_asks(&mut self) { + if self.asks.is_empty() { + return; + } + let n = self.asks.len().min(MIRROR_ASKS_MAX); + let mut asks: Vec = self.asks.drain(..n).collect(); + asks.sort_unstable(); + asks.dedup(); + let mut want: Vec<(usize, usize)> = Vec::new(); + for g in asks { + if self.mirror_src.contains_key(&g) { + continue; + } + let under = if !self.mapped.contains_key(&g) && self.window_index(g).is_some() { tile_shows(g) } else { Under::NoView }; + match under { + Under::Cpu(c) => want.push((g, c)), + // (it stays asked for: a page mapped there later links it, `remapped`) + Under::Nothing => {} + // (not counted: an address left out at every submit would empty every thread's + // memory of its asks at every submit; a pair made later changes the views) + Under::NoView => { + MIRROR_ASKED.remove(g); + } + } + } + if want.is_empty() { + return; + } + #[cfg(test)] + if let Some(f) = tests::BEFORE_LINK.with(|f| f.take()) { + f(); + } + // linked before their CPU tiles' pages are asked about (`holes_now`) + for &(g, c) in &want { + self.link_mirror(g, c); + } + // (a pair dropped since it was looked up: its `forget_mirrors` may have found nothing + // linked, and the CPU tile may be given out anew; a page mapped or unmapped there since: + // linked again, the ask kept) + want.retain_mut(|(g, c)| match tile_shows(*g) { + Under::Cpu(now) if now == *c => true, + Under::Cpu(now) => { + self.unlink_kept(*g); + self.link_mirror(*g, now); + *c = now; + true + } + Under::Nothing => { + self.unlink_kept(*g); + false + } + Under::NoView => !self.unlink_mirror(*g), + }); + self.later.extend(want); + } -/// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB -/// pages from the write-watch, sorted) and the reused tiles are copied asynchronously into video -/// memory, and `queue` GPU-waits for that and for new tile mappings. -pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize, mut look: Option<&mut LookSample>) -> PreparationOutcome { - if look.is_some() { - super::vram::begin_before_execute_timing(); + /// Window tile `w`, linked over `from`, follows its page to `to` (`moved`): the link moves. With + /// video memory and `whole` (the page's 64 KiB were copied to `to`) its entry keeps its pool + /// tile, gen and sent hashes – nothing is cleared or filled: the known write kernelx notes at + /// `to` has the next scan send what differs, and a copy back recorded before lands at `to`. + /// Not `whole` (a page never used, not committed at `to`): its video memory is parked and it + /// waits to be filled from `to` (`later`), as one with no video memory does. + fn retarget(&mut self, w: usize, from: usize, to: usize, whole: bool) { + if self.mirror_src.get(&w) != Some(&from) || from == to { + return; + } + self.unlink_kept(w); + self.link_mirror(w, to); + VIEW_TILES[1].fetch_add(1, Ordering::Relaxed); + match self.mapped.get_mut(&w).filter(|e| e.src == from) { + Some(e) if whole => { + e.src = to; + e.holes = 0; + } + Some(_) => { + self.park(w); + self.later.push_back((w, to)); + } + None => self.later.push_back((w, to)), + } } - let q = queue.as_raw() as usize; - let t0 = look.is_some().then(std::time::Instant::now); - let queue_gate = WAIT_GATES.lock().unwrap().entry(q).or_default().clone(); - let _queue_serial = queue_gate.lock().unwrap(); - let _upload_lifetime = UPLOAD_STATE_LIFETIME.read().unwrap(); - let (mut uploads, mut timing) = UploadGateTiming::acquire(look.is_some()); - let t_gated = t0.map(|_| std::time::Instant::now()); - if let (Some(sample), Some(t0), Some(t_gated)) = (look.as_deref_mut(), t0, t_gated) { - sample.add_time(QUEUE_WAIT_US, t_gated.duration_since(t0)); + + /// The tiles whose GPU-view page the queue's page mappings changed (`remaps`, from `remapped`; + /// `MIRROR_ASKS_MAX` at most a submit) are linked to what they show now: video memory over a + /// place is cleared and filled from its committed pages (`fill_later`, before the asks), one + /// that shows nothing is given back – but a placed buffer's, which keeps its video memory + /// cleared over `no_source` – and stays asked for. Called after the finished copies back land + /// (a copy back recorded for the old link finds a new gen) and before `map_mirrors`. + unsafe fn remap_mirrors(&mut self) { + if self.remaps.is_empty() { + return; + } + let n = self.remaps.len().min(MIRROR_ASKS_MAX); + let mut tiles: Vec = self.remaps.drain(..n).collect(); + tiles.sort_unstable(); + tiles.dedup(); + for g in tiles { + // (a tile of the window's own is not a view's) + if self.mapped.get(&g).is_some_and(|e| e.src == 0) { + continue; + } + let now = tile_shows(g); + let linked = self.mirror_src.get(&g).copied(); + match now { + Under::Cpu(c) if linked == Some(c) => continue, + Under::Nothing if linked.is_none_or(|l| l == no_source()) => continue, + _ => {} + } + let pinned = self.mapped.get(&g).is_some_and(|e| self.pinned.contains_key(&e.pool)); + self.unlink_kept(g); + self.park(g); + if pinned { + // (a kept tile must not keep the bytes it showed) + self.to_zero.insert((g, TILE)); + } + match now { + Under::Cpu(c) if self.window_index(g).is_some() => { + self.link_mirror(g, c); + // (it was shown: before the older asks) + self.later.push_front((g, c)); + VIEW_TILES[0].fetch_add(1, Ordering::Relaxed); + } + Under::Nothing => { + if pinned && no_source() != 0 { + self.link_mirror(g, no_source()); + self.new_mirror(g, no_source(), 0xFFFF, true); + } + VIEW_TILES[0].fetch_add(1, Ordering::Relaxed); + } + _ => forget_ask(g), + } + } } - let outcome = before_execute_locked(queue, dirty, page, q, t0, &mut look, &mut uploads, &mut timing); - let times = timing.finish(); - drop(uploads.take()); - if let Some(sample) = look.as_deref_mut() { - add_gate_times(&mut sample.0, SUBMIT_GATE_WAIT_US, SUBMIT_GATE_HOLD_US, None, times); + + /// The hole masks of CPU tiles `tiles` (`source_holes`), with the pages of decommits under way + /// as holes too (`Sources::freeing`): Windows has them still, and frees them while the submit + /// reads them. Asked once the tiles are linked (`link_mirror`): a decommit that begins after + /// this finds them and tells the state before Windows frees anything; one that began before + /// is in the list read here. + unsafe fn holes_now(&self, tiles: &[usize]) -> Vec { + let freeing = lock_sources(self.sources).freeing.clone(); + let mut holes = source_holes(tiles); + for &(a, end) in &freeing { + for (h, &t) in holes.iter_mut().zip(tiles) { + let (lo, hi) = (a.max(t), end.min(t + TILE)); + if lo < hi { + *h |= ((1u32 << ((hi - t) / PAGE)) - (1u32 << ((lo - t) / PAGE))) as u16; + } + } + } + holes } - outcome -} -unsafe fn before_execute_locked( - queue: &ID3D12CommandQueue, - dirty: &[usize], - page: usize, - q: usize, - t0: Option, - look: &mut Option<&mut LookSample>, - uploads: &mut Option, - timing: &mut UploadGateTiming, -) -> PreparationOutcome { - let mut metric_runs = look.is_some().then(|| (BTreeMap::new(), BTreeMap::new())); - 'prepare: loop { - let t_started = t0.map(|_| std::time::Instant::now()); - let observed = poll_retirement_fences(); - let mut g = lock_state(); - let Some(s) = g.as_mut() else { - if let (Some(sample), Some(t_started)) = (look.as_deref_mut(), t_started) { - sample.add_time(MAINTENANCE_US, t_started.elapsed()); + /// Before a submit, the CPU pages written (`dirty`, `page` bytes each) that tiles show: a tile + /// over one with no video memory gets it now (its CPU tile had no committed page, gave its + /// memory back, or was refused), and a written page that was a hole there is asked about + /// again: committed since (a page of the CPU view committed lazily, on its first write), it is + /// one no more. Every `mapped` insert of a submit is made here, before pointers into the + /// entries are taken. + unsafe fn mirror_writes(&mut self, dirty: &[usize], page: usize) { + if self.mirrors.is_empty() { + return; } - note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); - return PreparationOutcome::Ready; - }; - // Snapshot the exact-generation coordination owners while this State is authoritative. The - // Arc-backed ledgers may later be used after STATE is released without borrowing replacement - // state; this parity stage still leaves the legacy upload path authoritative. - let coordination = s.coordination.clone(); - // the title's work sees what was decommitted unmapped, as it was - let flushed = s.flush_parked_with(Some(queue)); - let drained = s.drain_quarantined_with(|fence| { - observed_completion(&observed, fence, |known, current| known.as_raw() == current.as_raw()) - }); - if flushed || drained { - let sparse_done = observed_completion(&observed, &s.fence, |known, current| known.as_raw() == current.as_raw()); - s.retire_free_pools_with(sparse_done); - } - let t_maintained = t0.map(|_| std::time::Instant::now()); - let zero_runs = std::mem::take(&mut s.to_zero); - for &(a, n) in &zero_runs { - s.clear_sent_range(a, n); - } - let mut dirty_runs = std::mem::take(&mut s.scratch_runs); - dirty_runs.clear(); - let mut deferred = Vec::new(); - let retry_pages = std::mem::take(&mut s.retry_pages); - let prior_retry = retry_pages.clone(); - if retry_pages.is_empty() { - let mut i = 0; - while i < dirty.len() { - let a = dirty[i]; - let mut n = page; - i += 1; - while i < dirty.len() && dirty[i] == a + n { - n += page; - i += 1; - } - let mut pg = a & !(PAGE - 1); - while pg < a + n { - let t = pg & !(TILE - 1); - if let Some(entry) = s.mapped.get_mut(&t) { - let idx = (pg - t) / PAGE; - if entry.holes & (1u16 << idx) == 0 { - let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); - scan_page(bytes, pg, &entry.sent[idx], &mut dirty_runs); + // CPU tiles written that tiles show, and the pages written there + let mut written: Vec<(usize, u16)> = Vec::new(); + for &a in dirty { + let mut x = a & !(PAGE - 1); + while x < a + page { + let t = x & !(TILE - 1); + if self.mirrors.contains_key(&t) { + let bit = 1u16 << ((x - t) / PAGE); + match written.last_mut() { + Some(l) if l.0 == t => l.1 |= bit, + _ => written.push((t, bit)), } } - pg += PAGE; + x += PAGE; } } - } else { - let mut pages = retry_pages; - pages.extend(dirty.iter().flat_map(|&a| (a..a.saturating_add(page)).step_by(PAGE))); - pages.sort_unstable(); - pages.dedup(); - for pg in pages { - let t = pg & !(TILE - 1); - let Some(entry) = s.mapped.get_mut(&t) else { - if prior_retry.binary_search(&pg).is_ok() { deferred.push(pg) } - continue; - }; - let idx = (pg - t) / PAGE; - if entry.holes & (1u16 << idx) != 0 { - if prior_retry.binary_search(&pg).is_ok() { deferred.push(pg) } - continue; + // (tile over it, CPU tile, holes written – None: the tile has no video memory) + let mut ask: Vec<(usize, usize, Option)> = Vec::new(); + // (a tile refused is not asked about while there is no room or memory for it: it would be + // refused again, and its CPU tile may be written at every submit) + let waiting = self.mirrored >= self.mirror_cap || self.short_of_memory(); + for &(t, bits) in &written { + for &w in &self.mirrors[&t] { + match self.mapped.get(&w) { + Some(e) if e.src == t => { + if e.holes & bits != 0 { + ask.push((w, t, Some(e.holes & bits))); + } + } + Some(_) => {} + None if waiting && self.refused.contains(&w) => {} + None => ask.push((w, t, None)), + } } - let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); - scan_page(bytes, pg, &entry.sent[idx], &mut dirty_runs); - } - } - let t_scanned = t0.map(|_| std::time::Instant::now()); - // Dual-journal exactly what the legacy attempt is about to consume. This sealed batch is a - // parity record only: the established upload path remains authoritative and retires it as - // obsolete after publishing its own retry state. - let legacy_batch = coordination - .seal_legacy(q as u64, &zero_runs, &prior_retry, &dirty_runs) - .ok() - .flatten(); - // Owned planning remains preparatory only. Capturing and revalidating source hashes both - // require title-memory reads; doing either under STATE would add lock hold time and an extra - // acquisition to the live uploader. Do not activate it until capture can be made genuinely - // lock-free and measured on a Windows title workload. - let state_generation = s.generation; - let mapping_epoch = s.mapping_epoch; - let mut legacy_parity = legacy_batch.map(|lease| LegacyParityUpload::Lease { - lease, state_generation, mapping_epoch, - }); - let mut g = g; - let Some(s) = g.as_mut() else { - note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); - return PreparationOutcome::Ready; - }; - if let Some(parity) = legacy_parity.as_ref() { - match parity.revalidate(s.generation, s.mapping_epoch, |page| s.upload_page_observation(page)) { - // "Ready" accepts only the legacy attempt. The parity lease stays pending until that - // authoritative path finishes; coordinated accept/publish remains a later activation. - LegacyParityRevalidation::Ready => {} - LegacyParityRevalidation::RestartForGeneration => { - drop(g); - let _ = legacy_parity.take().unwrap().retry(); - // The per-call budget is already consumed, so this rebuild cannot unlock again. - continue 'prepare; + } + if ask.is_empty() { + return; + } + let now = self.holes_now(&ask.iter().map(|a| a.1).collect::>()); + for (&(w, t, holes), h) in ask.iter().zip(now) { + match holes { + Some(bits) => { + self.counts.rechecks += bits.count_ones() as u64; + let committed = bits & !h; + if let Some(e) = self.mapped.get_mut(&w) { + e.holes &= !committed; + for i in 0..PAGES_PER_TILE { + if committed & (1u16 << i) != 0 { + e.sent[i] = None; + } + } + } + } + None if h != 0xFFFF && !self.mapped.contains_key(&w) => { + self.new_mirror(w, t, h, false); + } + None => {} } - LegacyParityRevalidation::RetryCurrentGeneration => { - s.to_zero.extend(zero_runs.iter().copied()); - s.retry_pages = retry_journal(PreparationOutcome::RetryRequired, deferred, &dirty_runs); - drop(g); - let _ = legacy_parity.take().unwrap().retry(); - // The per-call budget is already consumed, so this rebuild cannot unlock again. - continue 'prepare; + } + } + + /// The CPU tiles of `mirrors` that `[a, end)` touches (by `src_runs`). + fn src_tiles_in(&self, a: usize, end: usize) -> Vec { + let a0 = a & !(TILE - 1); + let mut out = Vec::new(); + let before = self.src_runs.range(..a0).next_back().map(|(&s, &e)| (s, e)); + for (s, e) in before.into_iter().chain(self.src_runs.range(a0..end).map(|(&s, &e)| (s, e))) { + let mut t = s.max(a0); + while t < e.min(end) { + out.push(t); + t += TILE; } } + out } - // Submit tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. - let mut outcome = PreparationOutcome::Ready; - let mut upload_wait = None; - if !zero_runs.is_empty() { - match s.upload_zeros(&zero_runs) { - UploadStep::Done(done) => outcome = done, - UploadStep::Wait(ticket) => { - outcome = PreparationOutcome::RetryRequired; - upload_wait = Some(ticket); + + /// `source_decommitted` with the state locked: the pieces of the tiles over `[a, a + n)` get + /// holes (`decommit_tiles`); a tile all holes is parked, and stays in `mirrors` (a commit and + /// write there gives it video memory again). + unsafe fn source_decommitted_in(&mut self, a: usize, n: usize) { + let end = a.saturating_add(n); + for t in self.src_tiles_in(a, end) { + let (lo, hi) = (a.max(t), end.min(t + TILE)); + let over = self.mirrors.get(&t).cloned().unwrap_or_default(); + for w in over { + let Some(pool) = self.mapped.get(&w).filter(|e| e.src == t).map(|e| e.pool) else { continue }; + if !decommit_tiles(&mut self.mapped, &self.pinned, &mut Vec::new(), &mut self.to_zero, w + (lo - t), hi - lo).is_empty() { + self.mirrored -= 1; + self.give_back(w, pool); + } } } - if outcome != PreparationOutcome::Ready { - s.to_zero.extend(zero_runs.iter().copied()); + if self.parked.len() >= PARKED_MAX && self.flush_parked() { + self.retire_free_pools(); } } - if outcome == PreparationOutcome::Ready && !dirty_runs.is_empty() { - match s.upload_dirty(&dirty_runs) { - UploadStep::Done(done) => outcome = done, - UploadStep::Wait(ticket) => { - outcome = PreparationOutcome::RetryRequired; - upload_wait = Some(ticket); + + /// `forget_mirrors` with the state locked (`[a, end)`) + unsafe fn forget_mirrors_in(&mut self, a: usize, end: usize) { + let touches = |x: usize| x < end && x + TILE > a; + let gone: Vec = self.mirror_src.iter().filter(|&(&w, &c)| touches(w) || touches(c)).map(|(&w, _)| w).collect(); + for w in gone { + self.drop_mirror(w); + } + self.asks.retain(|&w| { + let keep = !touches(w) && !mirror_source_tile(w).is_some_and(touches); + if !keep { + forget_ask(w); } + keep + }); + if self.parked.len() >= PARKED_MAX && self.flush_parked() { + self.retire_free_pools(); } } - s.retry_pages = retry_journal(outcome, deferred, &dirty_runs); - if let Some(parity) = legacy_parity { - let _ = parity.obsolete(); - } - if let Some((zero, dirty)) = metric_runs.as_mut() { - remember_metric_runs(zero, &zero_runs); - remember_metric_runs(dirty, &dirty_runs); - } - if let (Some(sample), Some(t_started), Some(t_maintained), Some(t_scanned)) = - (look.as_deref_mut(), t_started, t_maintained, t_scanned) - { - let t_uploaded = std::time::Instant::now(); - sample.add_time(MAINTENANCE_US, t_maintained.duration_since(t_started)); - sample.add_time(SCAN_US, t_scanned.duration_since(t_maintained)); - sample.add_time(UPLOAD_US, t_uploaded.duration_since(t_scanned)); - } - dirty_runs.clear(); - s.scratch_runs = dirty_runs; - if let Some(ticket) = upload_wait { - // `to_zero` and `retry_pages` were restored above before ownership is released. Another - // queue may consume either journal; reacquisition is included in UPLOAD_WAIT_US and the - // next iteration always rebuilds its plan from current state. - drop(g); - drop(observed); - let wait_started = t0.map(|_| std::time::Instant::now()); - if !timing.with_released(uploads, || wait_upload_released(ticket)) { - if let (Some(sample), Some(wait_started)) = (look.as_deref_mut(), wait_started) { - sample.add_time(UPLOAD_WAIT_US, wait_started.elapsed()); + + /// The tiles of a buffer placed at `[start, start + len)` (`place_buffer`, `start` a tile's), + /// with video memory where they can have it: a tile of a GPU view shows its CPU view + /// (`new_mirror`, with no committed page and past `mirror_cap` too: the buffer needs the tile, + /// and maps it once), the others are the + /// window's own, with the pages committed there. + unsafe fn buffer_tiles(&mut self, start: usize, len: usize) -> Vec<(usize, (u32, u32))> { + let end = start + len; + let mut over: Vec<(usize, usize)> = Vec::new(); + for t in (start..end).step_by(TILE) { + if self.mapped.contains_key(&t) || self.window_index(t).is_none() { + continue; + } + if let Some(c) = self.mirror_src.get(&t).copied().or_else(|| buffer_source(tile_shows(t))) { + over.push((t, c)); } - note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); - return PreparationOutcome::RetryRequired; } - if let (Some(sample), Some(wait_started)) = (look.as_deref_mut(), wait_started) { - sample.add_time(UPLOAD_WAIT_US, wait_started.elapsed()); + if !over.is_empty() { + // linked before their CPU tiles' pages are asked about (`holes_now`), and given up + // when their pair went meanwhile, linked again when their page changed (as in + // `take_asks`) + over.retain_mut(|(t, c)| { + if self.mirror_src.contains_key(t) { + return true; + } + self.link_mirror(*t, *c); + match buffer_source(tile_shows(*t)) { + Some(now) if now == *c => true, + Some(now) => { + self.unlink_kept(*t); + self.link_mirror(*t, now); + *c = now; + true + } + None => !self.unlink_mirror(*t), + } + }); + let holes = self.holes_now(&over.iter().map(|o| o.1).collect::>()); + for (&(t, c), h) in over.iter().zip(holes) { + self.new_mirror(t, c, h, true); + } } - continue 'prepare; - } - if outcome != PreparationOutcome::Ready { - drop(g); - drop(observed); - note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); - return outcome; + // tiles listed with no video memory get it for the buffer (before `ensure_mapped`, which + // sends what is pending or asks for it soon); one that finds none is left out + let mut reused = Vec::new(); + self.materialize(start, len, true, &mut reused); + self.to_zero.extend(reused); + self.ensure_mapped(start, len, |t| { + let holes = query_tile_holes(t); + (holes, !holes) + }); + (start..end).step_by(TILE).filter_map(|t| self.mapped.get(&t).filter(|e| e.pool != LAZY).map(|e| (t, e.pool))).collect() } - let value = s.value; - let previous = s.waited.get(&q).copied(); - let wait = reserve_queue_wait(&mut s.waited, q, value).then(|| (s.fence.clone(), value, previous)); - drop(g); - drop(observed); - if let Some((fence, value, previous)) = wait { - if super::real::native_queue_wait(queue, &fence, value).is_err() { - let mut g = lock_state(); - if let Some(s) = g.as_mut().filter(|s| s.fence.as_raw() == fence.as_raw() && s.waited.get(&q) == Some(&value)) { - rollback_queue_wait(&mut s.waited, q, value, previous); - } - note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); - return PreparationOutcome::RetryRequired; + + /// `mapped_ranges` of this state + fn watched_ranges(&self) -> Vec<(usize, usize)> { + let mut out: Vec<(usize, usize)> = self.runs.iter().chain(self.src_runs.iter()).map(|(&a, &b)| (a, b)).collect(); + if !self.src_runs.is_empty() { + out.sort_unstable(); } - super::list_x::note_internal_wait(q, "sparse uploads and tile mappings", &fence, value); + out } - note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); - return PreparationOutcome::Ready; +} + +/// The sparse windows' tiles listed (with video memory, or to get it at their first use, +/// `LAZY`) as sorted (start, end) runs, and the CPU memory +/// tiles of GPU views show (never the views' own addresses): where a CPU write has to reach the +/// GPU. +pub fn mapped_ranges() -> Vec<(usize, usize)> { + let t0 = super::look_stats::deep().then(std::time::Instant::now); + let g = lock_for_submit(); + let _held = holding(Holder::Ranges); + if let Some(t0) = t0 { + HELD.add(HELD_RANGES_WAIT, t0.elapsed().as_micros() as u64); } + let Some(s) = g.as_ref() else { return Vec::new() }; + s.watched_ranges() } -/// A buffer the title places at `va` in a sparse window (`bytes` long, `desc` the PC -/// description): a reserved resource over the window's tiles there, starting at the 64 KiB -/// below `va` (returned: its distance from there). -pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option<(crate::util::HRESULT, usize)> { - let _placement = PLACEMENT.lock().unwrap(); - place_buffer_in( - &STATE, - &FORGOTTEN, - va, - desc, - state, - |d| { - let hr = super::real::dev_create_reserved_resource(this, d as *const _ as usize, state as usize, 0, riid, ppv); - (hr >= 0 && !ppv.is_null() && !(*ppv).is_null()).then_some((hr, *ppv)) - }, - |raw| { - if !ppv.is_null() && *ppv == raw { - *ppv = std::ptr::null_mut(); - } - drop(ID3D12Resource::from_raw(raw)); - }, - ) +const LOOK_FIELDS: usize = 37; +const ACTIVE_US: usize = 0; +const REFRESH_WAIT_US: usize = 1; +const WATCH_US: usize = 2; +const PAGES: usize = 3; +const LOOKS: usize = 4; +const WATCHED: usize = 5; +const RANGES: usize = 6; +const QUEUE_WAIT_US: usize = 7; +const MAINTENANCE_US: usize = 8; +const SCAN_US: usize = 9; +const UPLOAD_US: usize = 10; +const RUNS: usize = 11; +const TRANSFER_BYTES: usize = 12; +const UPLOAD_WAIT_US: usize = 13; +const SUBMIT_GATE_WAIT_US: usize = 14; +const SUBMIT_GATE_HOLD_US: usize = 15; +const READBACK_GATE_WAIT_US: usize = 16; +const READBACK_GATE_HOLD_US: usize = 17; +const READBACK_GATE_RELEASED_US: usize = 18; +const TEXTURE_SELECT_WAIT_US: usize = 19; +const TEXTURE_SELECT_HOLD_US: usize = 20; +const TEXTURES_VISITED: usize = 21; +const TEXTURE_DIRTY_TESTS: usize = 22; +const TEXTURE_MATCHES: usize = 23; +const TEXTURES_RETAINED: usize = 24; +const VRAM_GATE_WAIT_US: usize = 25; +const VRAM_DEVICE_US: usize = 26; +const VRAM_UNMAP_POLL_US: usize = 27; +const VRAM_STATE_US: usize = 28; +const VRAM_QUEUE_WAIT_US: usize = 29; +const VRAM_RETIREMENT_US: usize = 30; +const VRAM_DEVICE_CACHE_HITS: usize = 31; +const VRAM_DEVICE_QUERIES: usize = 32; +const VRAM_CALLS: usize = 33; +const VRAM_MAPPING_WAITS: usize = 34; +const VRAM_RECLAIM_PASSES: usize = 35; +const VRAM_RETIREMENT_PASSES: usize = 36; + +/// time spent and pages found by the write-watch scans (`refresh_once`), for the timing line +static WATCH: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; +/// [lock wait, chunk scan, upload] in µs, runs uploaded +static PHASES: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +/// Microseconds so far in [looks for CPU writes, waits for the state lock, chunk scans, uploads]. +pub fn timing_totals() -> [u64; 4] { + [WATCH[0].load(Ordering::Relaxed), PHASES[0].load(Ordering::Relaxed), PHASES[1].load(Ordering::Relaxed), PHASES[2].load(Ordering::Relaxed)] } -unsafe fn place_buffer_in( - state_lock: &Mutex>, - forgotten: &Mutex>, - va: usize, - desc: &D3D12_RESOURCE_DESC, - state: u32, - create: impl FnOnce(&D3D12_RESOURCE_DESC) -> Option<(crate::util::HRESULT, *mut c_void)>, - on_abort: impl FnOnce(*mut c_void), -) -> Option<(crate::util::HRESULT, usize)> { - let start = va & !(TILE - 1); - let delta = va - start; - let bytes = desc.Width as usize; - if bytes == 0 { - return None; +pub fn note_watch(t: std::time::Duration, pages: usize) { + WATCH[0].fetch_add(t.as_micros() as u64, Ordering::Relaxed); + WATCH[1].fetch_add(pages as u64, Ordering::Relaxed); +} + +/// One complete `XCL_ACTIVITY` look. It is built without shared updates, then published once so +/// the reporting thread cannot split one look across adjacent intervals. +pub(super) struct LookSample([u64; LOOK_FIELDS]); + +impl Default for LookSample { + fn default() -> Self { + Self([0; LOOK_FIELDS]) } - let end = va.checked_add(bytes)?.checked_sub(1)?; - let generation = { - let g = lock_state_in(state_lock, forgotten); - let s = g.as_ref()?; - s.window_index(start)?; - s.window_index(end)?; - s.fence.clone() - }; - let mut d = *desc; - d.Width = (delta + bytes) as u64; - d.Alignment = 0; - d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - // Reserved buffers only accept NONE or ALLOW_UNORDERED_ACCESS (strip console flags and ALLOW_CROSS_ADAPTER). - d.Flags &= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - if state & (D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32 | D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32) != 0 { - d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; +} + +impl LookSample { + pub(super) fn add(&mut self, field: usize, value: u64) { + self.0[field] = self.0[field].wrapping_add(value); } - // Driver creation may call back into a release path which needs `STATE`. Revalidate the - // strongly owned fence generation before publishing the resulting resource. - let (hr, raw) = create(&d)?; - let mut g = lock_state_in(state_lock, forgotten); - let valid = g.as_ref().is_some_and(|s| { - s.fence.as_raw() == generation.as_raw() && s.window_index(start).is_some() && s.window_index(end).is_some() - }); - let Some(res) = valid.then(|| ID3D12Resource::from_raw_borrowed(&raw).cloned()).flatten() else { - drop(g); - drop(generation); - on_abort(raw); - return None; - }; - let s = g.as_mut().unwrap(); - // its tiles: the window's video memory at the same addresses; probe actual OS commitment - // so uncommitted pages (e.g. [start, va) or reserved tails) stay marked as holes - s.ensure_mapped(start, delta + bytes, |t| { - let holes = query_tile_holes(t); - (holes, !holes) - }); - s.mapping_epoch = s.mapping_epoch.wrapping_add(1); - let tiles: Vec<(usize, (u32, u32))> = (start..va + bytes).step_by(TILE).filter_map(|t| s.mapped.get(&t).map(|e| (t, e.pool))).collect(); - s.map_tiles(&res, start, &tiles); - if s.buffers.contains_key(&(raw as usize)) { - forget_in(s, raw as usize); + + pub(super) fn add_time(&mut self, field: usize, value: std::time::Duration) { + self.add(field, value.as_micros() as u64); } - for &(_, tile) in &tiles { - *s.pinned.entry(tile).or_default() += 1; +} + +/// Cumulative complete looks. Disabled title submission never locks or updates this mutex. +static LOOK: Mutex<[u64; LOOK_FIELDS]> = Mutex::new([0; LOOK_FIELDS]); + +fn merge_look(total: &mut [u64; LOOK_FIELDS], sample: [u64; LOOK_FIELDS]) { + for (total, value) in total.iter_mut().zip(sample) { + *total = total.wrapping_add(value); } - s.buffers.insert(raw as usize, tiles.iter().map(|x| x.1).collect()); - s.signal(); - drop(g); - drop(res); - drop(generation); - Some((hr, delta)) } -/// Placed buffers released while `STATE` was held, let go by the next `lock_state`. Held only -/// to push or take, never across a call out. -static FORGOTTEN: Mutex> = Mutex::new(Vec::new()); +fn add_gate_times(sample: &mut [u64; LOOK_FIELDS], wait: usize, hold: usize, released: Option, times: UploadGateTimes) { + sample[wait] = sample[wait].wrapping_add(times.wait_us); + sample[hold] = sample[hold].wrapping_add(times.hold_us); + if let Some(released) = released { + sample[released] = sample[released].wrapping_add(times.released_us); + } +} -/// `STATE`, with the buffers released while it was held let go first. -fn lock_state() -> std::sync::MutexGuard<'static, Option> { - lock_state_in(&STATE, &FORGOTTEN) +fn note_readback_gate(times: UploadGateTimes) { + let mut total = LOOK.lock().unwrap(); + add_gate_times( + &mut total, READBACK_GATE_WAIT_US, READBACK_GATE_HOLD_US, Some(READBACK_GATE_RELEASED_US), times, + ); } -fn lock_state_in<'a>(state: &'a Mutex>, forgotten: &Mutex>) -> std::sync::MutexGuard<'a, Option> { - let mut g = state.lock().unwrap(); - forget_released_in(&mut g, forgotten); - g +/// `XCL_ACTIVITY`: a look's write-watch time and sizes, into its sample (nv's `note_watch` feeds +/// `timing_totals`). +pub(super) fn note_watch_sample(sample: &mut LookSample, t: std::time::Duration, pages: usize, watched: usize, ranges: usize) { + sample.add_time(WATCH_US, t); + sample.add(PAGES, pages as u64); + sample.add(WATCHED, watched as u64); + sample.add(RANGES, ranges as u64); } -fn forget_released_in(g: &mut Option, forgotten: &Mutex>) { - let gone = std::mem::take(&mut *forgotten.lock().unwrap()); - let Some(s) = g.as_mut() else { return }; - for res in gone { - forget_in(s, res); +pub(super) fn note_texture_selection( + sample: &mut LookSample, + wait: std::time::Duration, + hold: std::time::Duration, + visited: usize, + dirty_tests: usize, + matches: usize, + retained: usize, +) { + sample.add_time(TEXTURE_SELECT_WAIT_US, wait); + sample.add_time(TEXTURE_SELECT_HOLD_US, hold); + sample.add(TEXTURES_VISITED, visited as u64); + sample.add(TEXTURE_DIRTY_TESTS, dirty_tests as u64); + sample.add(TEXTURE_MATCHES, matches as u64); + sample.add(TEXTURES_RETAINED, retained as u64); +} + +fn note_vram_before_execute(sample: &mut LookSample, timing: super::vram::BeforeExecuteTiming) { + sample.add_time(VRAM_GATE_WAIT_US, timing.gate_wait); + sample.add_time(VRAM_DEVICE_US, timing.device); + sample.add_time(VRAM_UNMAP_POLL_US, timing.unmap_poll); + sample.add_time(VRAM_STATE_US, timing.state); + sample.add_time(VRAM_QUEUE_WAIT_US, timing.queue_wait); + sample.add_time(VRAM_RETIREMENT_US, timing.retirement); + sample.add(VRAM_DEVICE_CACHE_HITS, timing.device_cache_hits as u64); + sample.add(VRAM_DEVICE_QUERIES, timing.device_queries as u64); + sample.add(VRAM_CALLS, timing.calls as u64); + sample.add(VRAM_MAPPING_WAITS, timing.mapping_waits as u64); + sample.add(VRAM_RECLAIM_PASSES, timing.reclaim_passes as u64); + sample.add(VRAM_RETIREMENT_PASSES, timing.retirement_passes as u64); +} + +/// `XCL_ACTIVITY`: one complete look, published (nv's `note_look` marks the look for +/// `XCL_LOOK_STATS=2`). +pub(super) fn note_look_sample(mut sample: LookSample, active: std::time::Duration, refresh_wait: std::time::Duration) { + if let Some(timing) = super::vram::take_before_execute_timing() { + note_vram_before_execute(&mut sample, timing); } + sample.add_time(ACTIVE_US, active); + sample.add_time(REFRESH_WAIT_US, refresh_wait); + sample.add(LOOKS, 1); + let mut total = LOOK.lock().unwrap(); + merge_look(&mut total, sample.0); } -/// A placed buffer is gone: its tiles are not pinned by it any more. This runs from the -/// resource's last Release, which D3D12 can make while it holds a lock of its own (in a title's -/// command list Reset), and `before_execute` calls D3D12 with `STATE` held: waiting for `STATE` -/// here deadlocked the two threads. So it does not wait: with `STATE` held, the holder's next -/// `lock_state` lets the buffer go. -pub fn forget_buffer(res: usize) { - forget_buffer_in(&STATE, &FORGOTTEN, res); +pub fn look_counters() -> [u64; LOOK_FIELDS] { + *LOOK.lock().unwrap() } -fn forget_buffer_in(state: &Mutex>, forgotten: &Mutex>, res: usize) { - forgotten.lock().unwrap().push(res); - match state.try_lock() { - Ok(mut g) => forget_released_in(&mut g, forgotten), - Err(std::sync::TryLockError::WouldBlock) => {} - Err(e) => panic!("sparse state: {e}"), +pub fn look_delta(now: [u64; LOOK_FIELDS], before: [u64; LOOK_FIELDS]) -> [u64; LOOK_FIELDS] { + std::array::from_fn(|i| now[i].wrapping_sub(before[i])) +} + +/// Active foreground elapsed time and serialization wait before title submits in one interval. +pub fn look_line(d: [u64; LOOK_FIELDS], secs: u64) -> String { + let [ + active, refresh_wait, watch, pages, looks, watched, ranges, queue_wait, maintenance, scan, upload, + runs, transfer_bytes, upload_wait, submit_gate_wait, submit_gate_hold, readback_gate_wait, + readback_gate_hold, readback_gate_released, texture_select_wait, texture_select_hold, + textures_visited, texture_dirty_tests, texture_matches, textures_retained, + vram_gate_wait, vram_device, vram_unmap_poll, vram_state, vram_queue_wait, vram_retirement, + vram_device_cache_hits, vram_device_queries, vram_calls, vram_mapping_waits, + vram_reclaim_passes, vram_retirement_passes, + ] = d; + let ms = |us: u64| us / 1000; + let sparse = queue_wait.saturating_add(maintenance).saturating_add(scan).saturating_add(upload).saturating_add(upload_wait); + let texture_select = texture_select_wait.saturating_add(texture_select_hold); + let vram = vram_gate_wait + .saturating_add(vram_device) + .saturating_add(vram_unmap_poll) + .saturating_add(vram_state) + .saturating_add(vram_queue_wait) + .saturating_add(vram_retirement); + format!( + "looks before submits ({secs} s): {looks} looks did {} ms active work ({:.1} % of the time) after {} ms waiting for the refresh turn: write-watch {} ms ({:.1} MB in {:.1} ranges/look, {pages} pages written); texture select wait/hold {}/{} ms ({textures_visited} visited, {texture_dirty_tests} dirty-tested, {texture_matches} matched, {textures_retained} retained); sparse queue wait/fence+state/scan/upload/ownership wait {}/{}/{}/{}/{} ms ({runs} runs, {:.1} MB zero/dirty bytes); VRAM gate/device/unmap poll/state/queue wait/retire {}/{}/{}/{}/{}/{} ms ({vram_calls} calls, {vram_device_cache_hits} device-cache hits, {vram_device_queries} GetDevice queries, {vram_mapping_waits} mapping waits, {vram_reclaim_passes} reclaim passes, {vram_retirement_passes} retirement passes); upload gate submit wait/hold {}/{} ms, readback wait/hold/released wait+reacquire {}/{}/{} ms; other active work {} ms", + ms(active), + active as f64 / (secs.max(1) * 10_000) as f64, + ms(refresh_wait), + ms(watch), + watched as f64 / looks.max(1) as f64 / (1 << 20) as f64, + ranges as f64 / looks.max(1) as f64, + ms(texture_select_wait), + ms(texture_select_hold), + ms(queue_wait), + ms(maintenance), + ms(scan), + ms(upload), + ms(upload_wait), + transfer_bytes as f64 / (1 << 20) as f64, + ms(vram_gate_wait), + ms(vram_device), + ms(vram_unmap_poll), + ms(vram_state), + ms(vram_queue_wait), + ms(vram_retirement), + ms(submit_gate_wait), + ms(submit_gate_hold), + ms(readback_gate_wait), + ms(readback_gate_hold), + ms(readback_gate_released), + ms(active.saturating_sub(watch.saturating_add(sparse).saturating_add(texture_select).saturating_add(vram))) + ) +} + +fn poll_unique(mut fences: Vec, key: impl Fn(&F) -> usize, mut completed: impl FnMut(&F) -> u64) -> Vec<(F, u64)> { + fences.sort_unstable_by_key(&key); + fences.dedup_by(|a, b| key(a) == key(b)); + fences.into_iter().map(|fence| { + let value = completed(&fence); + (fence, value) + }).collect() +} + +fn observed_completion(observed: &[(F, u64)], fence: &F, same: impl Fn(&F, &F) -> bool) -> u64 { + observed.iter().find_map(|(known, value)| same(known, fence).then_some(*value)).unwrap_or(0) +} + +fn reserve_queue_wait(waited: &mut FxHashMap, queue: usize, value: u64) -> bool { + if value == 0 || waited.get(&queue).copied().unwrap_or(0) >= value { + return false; } + waited.insert(queue, value); + true } -fn forget_in(s: &mut State, res: usize) { - let Some(tiles) = s.buffers.remove(&res) else { return }; - for tile in tiles { - if let Some(c) = s.pinned.get_mut(&tile) { - *c -= 1; - if *c == 0 { - s.pinned.remove(&tile); - s.release_if_unused(tile); +fn retry_journal(outcome: PreparationOutcome, mut deferred: Vec, runs: &[(usize, usize)]) -> Vec { + if outcome != PreparationOutcome::Ready { + for &(a, n) in runs { + let mut pg = a & !(PAGE - 1); + let end = a.saturating_add(n); + while pg < end { + deferred.push(pg); + pg += PAGE; } } } + deferred.sort_unstable(); + deferred.dedup(); + deferred } -#[cfg(test)] -mod tests { - use super::*; +fn remember_metric_runs(seen: &mut BTreeMap, runs: &[(usize, usize)]) { + for &(a, n) in runs { + early_add(seen, a, a.saturating_add(n)); + } +} - #[test] - fn activity_look_line_splits_foreground_costs() { - let line = look_line([ - 830_000, - 120_000, - 610_000, - 4_800, - 240, - 240 * 1_641 << 20, - 240 * 69, - 10_000, - 30_000, - 40_000, - 40_000, - 90, - 96 << 20, - 20_000, - 5_000, - 105_000, - 3_000, - 70_000, - 12_000, - 7_000, - 13_000, - 24_000, - 8_000, - 1_200, - 1_190, - 1_000, - 2_000, - 3_000, - 4_000, - 5_000, - 6_000, - 237, - 3, - 240, - 8, - 2, - 1, - ], 2); - assert!(line.contains("240 looks did 830 ms active work (41.5 % of the time) after 120 ms waiting"), "{line}"); - assert!(line.contains("write-watch 610 ms (1641.0 MB in 69.0 ranges/look, 4800 pages written)"), "{line}"); - assert!(line.contains("texture select wait/hold 7/13 ms (24000 visited, 8000 dirty-tested, 1200 matched, 1190 retained)"), "{line}"); - assert!(line.contains("sparse queue wait/fence+state/scan/upload/ownership wait 10/30/40/40/20 ms (90 runs, 96.0 MB zero/dirty bytes)"), "{line}"); - assert!(line.contains("VRAM gate/device/unmap poll/state/queue wait/retire 1/2/3/4/5/6 ms (240 calls, 237 device-cache hits, 3 GetDevice queries, 8 mapping waits, 2 reclaim passes, 1 retirement passes)"), "{line}"); - assert!(line.contains("upload gate submit wait/hold 5/105 ms, readback wait/hold/released wait+reacquire 3/70/12 ms; other active work 39 ms"), "{line}"); - let idle = look_line([0; LOOK_FIELDS], 2); - assert!(idle.contains("0 looks did 0 ms active work (0.0 % of the time) after 0 ms waiting"), "{idle}"); - assert!(idle.contains("0.0 MB in 0.0 ranges/look"), "{idle}"); +fn note_transfer_metrics( + sample: Option<&mut LookSample>, seen: Option<&(BTreeMap, BTreeMap)>, +) { + let (Some(sample), Some((zero, dirty))) = (sample, seen) else { return }; + sample.add(RUNS, (zero.len() + dirty.len()) as u64); + let bytes = zero.iter().chain(dirty).fold(0usize, |sum, (&a, &b)| sum.saturating_add(b.saturating_sub(a))); + sample.add(TRANSFER_BYTES, bytes as u64); +} + +fn rollback_queue_wait(waited: &mut FxHashMap, queue: usize, value: u64, previous: Option) { + if waited.get(&queue) != Some(&value) { + return; + } + match previous { + Some(previous) => { waited.insert(queue, previous); } + None => { waited.remove(&queue); } } +} - #[test] - fn activity_look_counter_delta_survives_wrap() { - assert_eq!(look_delta([0; LOOK_FIELDS], [u64::MAX; LOOK_FIELDS]), [1; LOOK_FIELDS]); +/// Wait with both `STATE` and `UPLOAD_GATE` released. The caller's shared generation lease keeps +/// every old-state allocator, list, staging byte and destination alive. Only an exact ticket may +/// retire ring storage; a crossing uploader otherwise makes the caller rebuild from current state. +unsafe fn wait_upload_released(ticket: WaitTicket) -> bool { + loop { + match crate::gpu::fence::wait(&ticket.fence, ticket.target, &ticket.dev, None, 5000) { + Ok(()) => break, + Err(crate::gpu::fence::FenceError::Timeout(_)) => { + crate::xlog_warn!("sparse: upload retirement fence {} is still pending; STATE remains released", ticket.target); + } + Err(e) => { + crate::xlog_warn!("sparse: upload retirement fence {} failed: {e}", ticket.target); + return false; + } + } } + let proceed = { + let mut g = lock_state(); + match g.as_mut() { + None => false, + Some(s) if s.generation != ticket.state_generation || s.fence.as_raw() != ticket.fence.as_raw() => { + // The caller's shared lifetime makes replacement impossible. Fail closed if a + // future teardown path violates that protocol. + false + } + Some(s) if !s.uploads_ordered => false, + Some(s) => { + // Another uploader can retire/reuse this slot or ring range after the waited + // target completes. That invalidates exact ownership but not the completed fence; + // loop on current state. Reclaim only if neither it nor a remap crossed this ticket. + if s.wait_ticket_valid(&ticket) { + s.reclaim_ring(); + } + true + } + } + }; + drop(ticket); + proceed +} - #[test] - fn texture_selection_metrics_keep_wait_hold_and_counts_distinct() { - let mut sample = LookSample::default(); - note_texture_selection( - &mut sample, - std::time::Duration::from_micros(7), - std::time::Duration::from_micros(13), - 101, - 79, - 11, - 10, - ); - assert_eq!(sample.0[TEXTURE_SELECT_WAIT_US..=TEXTURES_RETAINED], [7, 13, 101, 79, 11, 10]); +/// Snapshot strong fence owners under `STATE`, then query them without it. A batch or a higher +/// mark added while polling is checked against the same observation; a new fence has no +/// observation and therefore remains quarantined. +unsafe fn poll_retirement_fences() -> Vec<(ID3D12Fence, u64)> { + let fences = { + let g = lock_state(); + let Some(s) = g.as_ref() else { return Vec::new() }; + std::iter::once(s.fence.clone()) + .chain(s.quarantined.iter().flat_map(|batch| batch.marks.iter().flatten().map(|(fence, _)| fence.clone()))) + .collect() + }; + // (XCL's own query: not through the title's GetCompletedValue hook and its settle) + poll_unique(fences, |fence| fence.as_raw() as usize, |fence| super::real::fence_completed(fence)) +} + +/// One page to scan: the CPU address of its bytes, its address in its window, and the slot of its +/// hashes (disjoint for every page of one submit: the window pages are distinct and their tiles' +/// entries are only touched through these). +struct PageSlot { + cpu: usize, + win: usize, + slot: *mut Option>, +} + +/// Of the pages `found` (CPU addresses, sorted), how many slots of `pages` the scan went over and +/// how many of those it found unchanged: no run of `runs` (window addresses, sorted, as the scan +/// made them) in the slot's window page. +fn own_scanned(found: &[usize], pages: &[PageSlot], runs: &[(usize, usize)]) -> (usize, usize) { + if found.is_empty() { + return (0, 0); + } + let (mut scanned, mut unchanged) = (0, 0); + for p in pages.iter().filter(|p| found.binary_search(&p.cpu).is_ok()) { + scanned += 1; + let k = runs.partition_point(|r| r.0 + r.1 <= p.win); + if !runs.get(k).is_some_and(|r| r.0 < p.win + PAGE) { + unchanged += 1; + } + } + (scanned, unchanged) +} + +/// The pages of one submit, shared with the worker threads (`worker_pool`). +struct SharedPages<'a>(&'a [PageSlot]); +// SAFETY: the slots are disjoint, and the scan finishes before the state's lock is given up +unsafe impl Sync for SharedPages<'_> {} + +/// Scan `pages` (`scan_page` on each, the bytes at their CPU address); the changed runs go to +/// `out` as window addresses, in their order. How the work was shared with the workers, if it was. +unsafe fn scan_pages(pages: &[PageSlot], out: &mut Vec<(usize, usize)>) -> Option { + /// pages a worker takes at a time, and the number from which the work is shared + const PIECE: usize = 64; + const SHARE_FROM: usize = 256; + let scan = |p: &PageSlot, out: &mut Vec<(usize, usize)>| { + let bytes = std::slice::from_raw_parts(p.cpu as *const u8, PAGE); + scan_page(bytes, p.win, &mut *p.slot, out); + }; + if pages.len() < SHARE_FROM { + pages.iter().for_each(|p| scan(p, out)); + return None; + } + let pieces = pages.len().div_ceil(PIECE); + let outs: Vec>> = (0..pieces).map(|_| Mutex::new(Vec::new())).collect(); + let shared = SharedPages(pages); + let work = |k: usize| { + // (the whole struct, not its field: that is what is Sync) + let shared = &shared; + let mut mine = Vec::new(); + for p in &shared.0[k * PIECE..((k + 1) * PIECE).min(shared.0.len())] { + scan(p, &mut mine); + } + *outs[k].lock().unwrap_or_else(|e| e.into_inner()) = mine; + }; + let shares = super::worker_pool::run(pieces, &work); + for o in outs { + for (addr, len) in o.into_inner().unwrap_or_else(|e| e.into_inner()) { + push_run(out, addr, len); + } } + Some(shares) +} - #[test] - fn vram_metrics_keep_phases_and_counts_distinct() { - let mut sample = LookSample::default(); - note_vram_before_execute(&mut sample, super::super::vram::BeforeExecuteTiming { - gate_wait: std::time::Duration::from_micros(1), - device: std::time::Duration::from_micros(2), - unmap_poll: std::time::Duration::from_micros(3), - state: std::time::Duration::from_micros(4), - queue_wait: std::time::Duration::from_micros(5), - retirement: std::time::Duration::from_micros(6), - device_cache_hits: 7, - device_queries: 8, - calls: 9, - mapping_waits: 10, - reclaim_passes: 11, - retirement_passes: 12, +/// Copies from the title's memory into the staging ring: shared with the worker threads when +/// there are many bytes. +unsafe fn run_copies(jobs: &mut Vec<(usize, usize, usize)>, staging: *mut u8) { + const SHARE_FROM: usize = 512 << 10; + let total: usize = jobs.iter().map(|j| j.2).sum(); + if total < SHARE_FROM || jobs.len() < 2 { + for &(src, off, n) in jobs.iter() { + std::ptr::copy_nonoverlapping(src as *const u8, staging.add(off), n); + } + } else { + // pieces of about the same bytes, in the order of the jobs + let target = (total / 16).max(64 << 10); + let mut pieces: Vec<(usize, usize)> = Vec::new(); + let (mut from, mut bytes) = (0usize, 0usize); + for (k, j) in jobs.iter().enumerate() { + bytes += j.2; + if bytes >= target { + pieces.push((from, k + 1)); + from = k + 1; + bytes = 0; + } + } + if from < jobs.len() { + pieces.push((from, jobs.len())); + } + struct Staging(*mut u8); + // SAFETY: the copies go to disjoint pieces of the ring, all from the caller's job list + unsafe impl Sync for Staging {} + let st = Staging(staging); + let list: &[(usize, usize, usize)] = jobs; + super::worker_pool::run(pieces.len(), &|k| { + let st = &st; + for &(src, off, n) in &list[pieces[k].0..pieces[k].1] { + unsafe { std::ptr::copy_nonoverlapping(src as *const u8, st.0.add(off), n) }; + } }); - assert_eq!(sample.0[VRAM_GATE_WAIT_US..=VRAM_RETIREMENT_PASSES], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); - let line = look_line(sample.0, 2); - assert!(line.contains("9 calls, 7 device-cache hits, 8 GetDevice queries"), "{line}"); } + jobs.clear(); +} - #[test] - fn upload_gate_times_accumulate_into_distinct_submit_and_readback_fields() { - let mut sample = [0; LOOK_FIELDS]; - add_gate_times( - &mut sample, - SUBMIT_GATE_WAIT_US, - SUBMIT_GATE_HOLD_US, - None, - UploadGateTimes { wait_us: 11, hold_us: 22, released_us: 33 }, - ); - add_gate_times( - &mut sample, - READBACK_GATE_WAIT_US, - READBACK_GATE_HOLD_US, - Some(READBACK_GATE_RELEASED_US), - UploadGateTimes { wait_us: 44, hold_us: 55, released_us: 66 }, - ); - assert_eq!(sample[SUBMIT_GATE_WAIT_US], 11); - assert_eq!(sample[SUBMIT_GATE_HOLD_US], 22); - assert_eq!(sample[READBACK_GATE_WAIT_US], 44); - assert_eq!(sample[READBACK_GATE_HOLD_US], 55); - assert_eq!(sample[READBACK_GATE_RELEASED_US], 66); +/// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB +/// pages from the write-watch, sorted) and the reused tiles are copied asynchronously into video +/// memory, and `queue` GPU-waits for that and for new tile mappings. +/// What the title's lists being recorded will write on the GPU in the sparse windows (address, +/// bytes; `will_write`), taken by the next submit: with `lazy_commits` a tile there may have no +/// video memory yet, and the write would go nowhere. +static WRITE_ASKS: Mutex> = Mutex::new(Vec::new()); +static WRITE_ASKING: AtomicBool = AtomicBool::new(false); + +/// A list being recorded writes `[va, va + len)` on the GPU with a memory operation (an +/// immediate, a fill, a copy, a timestamp): with `lazy_commits`, its tiles get their video memory +/// at the next submit, which comes before the list's (`State::give_memory`). Never waits for the +/// state. +pub(super) fn will_write(va: usize, len: usize) { + if len == 0 || !lazy_commits() { + return; } - - #[test] - fn retried_upload_ranges_are_counted_once() { - let mut zero = BTreeMap::new(); - let mut dirty = BTreeMap::new(); - remember_metric_runs(&mut zero, &[(0x1000, 0x1000)]); - remember_metric_runs(&mut zero, &[(0x1000, 0x1000)]); - remember_metric_runs(&mut dirty, &[(0x4000, 0x1000)]); - remember_metric_runs(&mut dirty, &[(0x4000, 0x2000)]); - let mut sample = LookSample::default(); - note_transfer_metrics(Some(&mut sample), Some(&(zero, dirty))); - assert_eq!(sample.0[RUNS], 2); - assert_eq!(sample.0[TRANSFER_BYTES], 0x3000); + WRITE_ASKS.lock().unwrap_or_else(|e| e.into_inner()).push((va, len)); + WRITE_ASKING.store(true, Ordering::Release); +} + +/// microseconds in `before_execute`, the wait for the state's lock with it +static SUBMIT_US: AtomicU64 = AtomicU64::new(0); + +/// `XCL_LOOK_STATS=2`: the parts of what `submit_cost` calls "sparse lock" (`PHASES[0]`: the wait +/// for the state's lock and the work before the scan), in µs but where said: a long wait asks for +/// less work under the lock elsewhere, the parts for less of that work here. (The pages of the +/// tiles that came to show a CPU view are gathered after it: the scan split's gather.) +static LOCK_SPLIT: super::look_stats::Sums<11> = super::look_stats::Sums::new(); +const LS_SUBMITS: usize = 0; +/// `PHASES[0]` of these submits +const LS_ALL: usize = 1; +const LS_WAIT: usize = 2; +/// landing finished copies back, and their bytes +const LS_BACK: usize = 3; +const LS_BACK_BYTES: usize = 4; +/// the tiles over CPU views (`map_mirrors`, `mirror_writes`) +const LS_VIEWS: usize = 5; +/// `flush_pending`, its tiles and calls +const LS_MAP: usize = 6; +const LS_MAP_TILES: usize = 7; +const LS_MAP_CALLS: usize = 8; +/// `flush_parked` (with the pools it left free), its tiles +const LS_UNMAP: usize = 9; +const LS_UNMAP_TILES: usize = 10; + +/// so far: [tiles `flush_pending` mapped, its calls, tiles `flush_parked` unmapped, bytes of +/// copies back landed] (read under the state's lock, which all of them are done with) +static TILE_WORK: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +/// so far, always counted: the sparse queue's UpdateTileMappings calls and their tiles, [map +/// calls, tiles mapped, unmap calls, tiles unmapped] in the sparse windows, then the same in +/// the view windows (GPU views). A placed buffer's mapping counts with its window's. +static TILE_CALLS: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; + +/// `calls` UpdateTileMappings of `tiles` tiles of the resource at `base` (`TILE_CALLS`) +fn count_tile_calls(base: usize, unmap: bool, calls: usize, tiles: usize) { + let k = if super::view_want::is_view(base as u64) { 4 } else { 0 } + if unmap { 2 } else { 0 }; + TILE_CALLS[k].fetch_add(calls as u64, Ordering::Relaxed); + TILE_CALLS[k + 1].fetch_add(tiles as u64, Ordering::Relaxed); +} + +/// `TILE_CALLS` so far, for the periodic log line (`tile_calls_line`) +pub fn tile_calls() -> [u64; 8] { + std::array::from_fn(|k| TILE_CALLS[k].load(Ordering::Relaxed)) +} + +/// The tile mapping calls between two `tile_calls`, None when there were none. +pub fn tile_calls_line(now: &[u64; 8], before: &[u64; 8]) -> Option { + let d: [u64; 8] = std::array::from_fn(|k| now[k].saturating_sub(before[k])); + if d.iter().all(|&n| n == 0) { + return None; } + Some(format!( + "sparse windows {} calls mapping {} tiles, {} calls unmapping {} tiles; GPU views {} calls mapping {} tiles, {} calls unmapping {} tiles", + d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7] + )) +} - #[test] - fn activity_look_publishes_one_complete_sample() { - let mut total = [10; LOOK_FIELDS]; - let sample = std::array::from_fn(|i| i as u64); - merge_look(&mut total, sample); - assert_eq!(total, std::array::from_fn(|i| 10 + i as u64)); - merge_look(&mut total, std::array::from_fn(|i| u64::MAX - 9 - i as u64)); - assert_eq!(total, [0; LOOK_FIELDS]); +/// The GPU-view diagnostics' counts (`VS`), all zero but the asks before there is a state. +fn view_stats() -> [u64; VS] { + let mut x = [0u64; VS]; + x[0] = VIEW_ASKED.load(Ordering::Relaxed); + let g = lock_state(); + let _held = holding(Holder::Other); + let Some(s) = g.as_ref() else { return x }; + let d = &s.diag; + let rest = [s.counts.fills, s.counts.given_back, d.kept, d.back[0], d.back[1], d.back[2], d.back[3], d.back_bytes, d.submits, d.deferred]; + x[1..VS_NOW].copy_from_slice(&rest); + let now = [s.mirrored, s.kept.len(), s.later.len() + s.asks.len(), s.refused.len()]; + for (k, n) in now.into_iter().enumerate() { + x[VS_NOW + k] = n as u64; + } + x +} + +/// The GPU-view diagnostics' line between two `view_stats`, None when nothing was counted. +fn view_stats_line(now: &[u64; VS], before: &[u64; VS]) -> Option { + let d: [u64; VS_NOW] = std::array::from_fn(|k| now[k].saturating_sub(before[k])); + if d.iter().all(|&n| n == 0) { + return None; } + Some(format!( + "GPU-view tiles (2 s): {} asked for, {} filled, {} given back, {} kept; back after 0-1 / 2-8 / 9-64 / more submits: {} / {} / {} / {} ({:.1} MB filled again); {} of {} submits left asked tiles waiting; now {} with video memory, {} kept, {} waiting, {} refused", + d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], d[8] as f64 / (1 << 20) as f64, d[10], d[9], + now[VS_NOW], now[VS_NOW + 1], now[VS_NOW + 2], now[VS_NOW + 3] + )) +} + +/// `view_stats_line` every 2 s on a thread of its own (`ViewSwitches::stats`; once). +fn start_view_stats() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let _ = std::thread::Builder::new().name("xcl-view-stats".into()).spawn(|| { + let mut before = view_stats(); + loop { + std::thread::sleep(std::time::Duration::from_secs(2)); + let now = view_stats(); + if let Some(line) = view_stats_line(&now, &before) { + crate::xlog_info!("D3D12.X: {line}"); + } + before = now; + } + }); + }); +} - #[test] - fn writable_record_requires_every_touched_page_and_tracks_protection() { - let mut mapped = FxHashMap::default(); - let (t0, t1) = (0x10_0000usize, 0x11_0000usize); - mapped.insert(t0, TileEntry::with_holes((0, 1), 0)); - mapped.insert(t1, TileEntry::with_holes((0, 2), 1 << 2)); - - assert!(recorded_committed(&mapped, t0, t0 + TILE)); - assert!(recorded_committed(&mapped, t0 + 0x800, t1 + 2 * PAGE)); - assert!(!recorded_committed(&mapped, t1 + 2 * PAGE, t1 + 2 * PAGE + 1)); - assert!(!recorded_committed(&mapped, t1 + TILE - 8, t1 + TILE + 8)); - - mark_protection(&mut mapped, t0 + 5 * PAGE + 16, 8, false); - assert!(!recorded_committed(&mapped, t0 + 5 * PAGE, t0 + 5 * PAGE + 1)); - assert!(recorded_committed(&mapped, t0 + 6 * PAGE, t0 + TILE)); - mark_protection(&mut mapped, t0 + 5 * PAGE, PAGE, true); - assert!(recorded_committed(&mapped, t0, t0 + TILE)); - } +/// The sparse lock split line of `x` (`LOCK_SPLIT`'s sums), as averages a submit. +fn lock_split_line(x: &[u64; 11]) -> String { + let n = x[LS_SUBMITS].max(1) as f64; + let ms = |k: usize| x[k] as f64 / n / 1e3; + let parts = [LS_WAIT, LS_BACK, LS_VIEWS, LS_MAP, LS_UNMAP].iter().map(|&k| x[k]).sum::(); + format!( + "sparse lock split ({} submits): wait {:.3} ms, copies back {:.3} ms ({:.0} KB), GPU-view tiles {:.3} ms, mappings {:.3} ms ({:.1} tiles in {:.1} calls), unmappings {:.3} ms ({:.1} tiles), rest {:.3} ms a submit (of {:.3} ms)", + x[LS_SUBMITS], + ms(LS_WAIT), + ms(LS_BACK), + x[LS_BACK_BYTES] as f64 / n / 1024.0, + ms(LS_VIEWS), + ms(LS_MAP), + x[LS_MAP_TILES] as f64 / n, + x[LS_MAP_CALLS] as f64 / n, + ms(LS_UNMAP), + x[LS_UNMAP_TILES] as f64 / n, + x[LS_ALL].saturating_sub(parts) as f64 / n / 1e3, + ms(LS_ALL) + ) +} - #[test] - fn early_protection_ranges_merge_split_and_commit_clears_them() { - let base = 0x20_0000usize; - let mut protected = BTreeMap::new(); - early_protection(&mut protected, base + PAGE + 16, 8, false); - early_protection(&mut protected, base + 3 * PAGE, 3 * PAGE, false); - early_protection(&mut protected, base + 5 * PAGE, PAGE, true); - assert_eq!(protected.into_iter().collect::>(), [(base + PAGE, base + 2 * PAGE), (base + 3 * PAGE, base + 5 * PAGE)]); - - let mut protected = BTreeMap::from([(base, base + 4 * PAGE)]); - early_remove(&mut protected, base + PAGE, base + 3 * PAGE); - assert_eq!(protected.into_iter().collect::>(), [(base, base + PAGE), (base + 3 * PAGE, base + 4 * PAGE)]); +impl State { + /// `before_execute` with the state locked: everything up to the queue's wait. Returns the step + /// and excess recycled `RbJob`s to drop outside `STATE`. `observed`: the retirement fences' + /// values read before the lock (`poll_retirement_fences`). + #[allow(clippy::too_many_arguments)] + unsafe fn before_execute_on_with( + &mut self, + queue: &ID3D12CommandQueue, + dirty: &[usize], + page: usize, + observed: &[(ID3D12Fence, u64)], + mut look: Option<&mut LookSample>, + metric_runs: &mut Option<(BTreeMap, BTreeMap)>, + t_started: Option, + ) -> (SubmitStep, Vec) { + let t0 = std::time::Instant::now(); + let s = self; + let q = queue.as_raw() as usize; + // (`XCL_LOOK_STATS=2`: the time after each step, and the work counted so far) + let split = super::look_stats::deep(); + let stamp = || split.then(std::time::Instant::now); + let work0: [u64; 4] = std::array::from_fn(|k| if split { TILE_WORK[k].load(Ordering::Relaxed) } else { 0 }); + // XCL's own writes since the look before, and those of them this look found (before the + // copies back below land: those the next look finds) + let own = (split && LOOKED.with(|l| l.replace(false))).then(|| { + let mut own = std::mem::take(&mut s.own_pages); + own.sort_unstable(); + own.dedup(); + let found: Vec = own.iter().copied().filter(|p| dirty.binary_search(p).is_ok()).collect(); + (own.len(), found) + }); + // Snapshot the exact-generation coordination owners while this State is authoritative. The + // Arc-backed ledgers may later be used after STATE is released without borrowing replacement + // state; this parity stage still leaves the legacy upload path authoritative. + let coordination = s.coordination.clone(); + // (copies back done before the tiles change below: a page that stops being a hole there + // would take what the GPU had in it) + let excess = s.land_finished_readbacks(); + let t_back = stamp(); + // tiles whose page the queue's page mappings changed (after the copies back: one for the + // old link lands nowhere), tiles asked to show CPU views, and the CPU writes that change + // them: before the flushes below, so their mappings reach the title's work (a tile taken + // back from `parked` needs none) + s.remap_mirrors(); + s.map_mirrors(); + s.diag.submits += 1; + if s.diag.stats && !(s.later.is_empty() && s.asks.is_empty()) { + s.diag.deferred += 1; + } + s.mirror_writes(dirty, page); + let t_views = stamp(); + // the title's work sees what was committed mapped … + s.flush_pending(); + PENDING.store(false, Ordering::Release); + let t_map = stamp(); + // the title's work sees what was decommitted unmapped, as it was (quarantined behind this + // queue and the title queues `present` knows; pools whose last tiles cooled since go with + // no tile freed now too: those a flush frees wait for the GPU in `quarantined`, then still + // cool there: `retire_due` sees them) + let flushed = s.flush_parked_with(Some(queue)); + s.drain_quarantined_with(|fence| observed_completion(observed, fence, |known, current| known.as_raw() == current.as_raw())); + if flushed || retire_due(&s.cooling, !s.retired.is_empty() || s.free.has_empty_heap(), s.retire_tried, std::time::Instant::now()) { + let sparse_done = observed_completion(observed, &s.fence, |known, current| known.as_raw() == current.as_raw()); + s.retire_free_pools_with(sparse_done); + } + let t_locked = std::time::Instant::now(); + PHASES[0].fetch_add((t_locked - t0).as_micros() as u64, Ordering::Relaxed); + if let (Some(t_back), Some(t_views), Some(t_map)) = (t_back, t_views, t_map) { + let us = |a: std::time::Instant, b: std::time::Instant| (b - a).as_micros() as u64; + let work = |k: usize| TILE_WORK[k].load(Ordering::Relaxed) - work0[k]; + LOCK_SPLIT.add(LS_ALL, us(t0, t_locked)); + LOCK_SPLIT.add(LS_BACK, us(t0, t_back)); + LOCK_SPLIT.add(LS_BACK_BYTES, work(3)); + LOCK_SPLIT.add(LS_VIEWS, us(t_back, t_views)); + LOCK_SPLIT.add(LS_MAP, us(t_views, t_map)); + LOCK_SPLIT.add(LS_MAP_TILES, work(0)); + LOCK_SPLIT.add(LS_MAP_CALLS, work(1)); + LOCK_SPLIT.add(LS_UNMAP, us(t_map, t_locked)); + LOCK_SPLIT.add(LS_UNMAP_TILES, work(2)); + if LOCK_SPLIT.add(LS_SUBMITS, 1) >= 1024 { + let x = LOCK_SPLIT.take(); + crate::xlog_info!("D3D12.X: {}; {}", lock_split_line(&x), holders_line(&HELD.take(), x[LS_SUBMITS])); + } + } + let t_maintained = t_started.map(|_| t_locked); + let zero_runs = zero_runs(std::mem::take(&mut s.to_zero)); + for &(a, n) in &zero_runs { + s.clear_sent_range(a, n); + } + let mut dirty_runs = std::mem::take(&mut s.scratch_runs); + dirty_runs.clear(); + // pages an upload before could not send (`retry_pages`, window addresses): scanned again + // with this submit's; one that lost its video memory meanwhile stays journaled + let mut deferred = Vec::new(); + let retry_pages = std::mem::take(&mut s.retry_pages); + let mut pages: Vec = Vec::with_capacity(dirty.len() + retry_pages.len()); + // tiles that came to show a CPU view: all of it (what is committed there) + let mut fill = std::mem::take(&mut s.fill); + fill.sort_unstable(); + fill.dedup(); + for &w in &fill { + let Some(entry) = s.mapped.get_mut(&w).filter(|e| e.src != 0) else { continue }; + s.counts.fills += 1; + for idx in 0..PAGES_PER_TILE { + if entry.holes & (1u16 << idx) == 0 { + pages.push(PageSlot { cpu: entry.src + idx * PAGE, win: w + idx * PAGE, slot: &mut entry.sent[idx] }); + s.counts.fill_bytes += PAGE as u64; + } + } + } + // tiles whose bytes found no video memory at an upload: all that is committed there, once + // a moment went by since (the upload gives them their tile, or leaves them here again) + let mut again = false; + if !s.starved.is_empty() && !s.short_of_memory() { + let mut starved = std::mem::take(&mut s.starved); + starved.sort_unstable(); + starved.dedup(); + for &t in &starved { + let Some(entry) = s.mapped.get_mut(&t).filter(|e| e.src == 0) else { continue }; + again = true; + for idx in 0..PAGES_PER_TILE { + if entry.holes & (1u16 << idx) == 0 { + pages.push(PageSlot { cpu: t + idx * PAGE, win: t + idx * PAGE, slot: &mut entry.sent[idx] }); + } + } + } + } + let mut i = 0; + while i < dirty.len() { + let a = dirty[i]; + let mut n = page; + i += 1; + while i < dirty.len() && dirty[i] == a + n { + n += page; + i += 1; + } + // only what has video memory (committed tiles of a sparse window, and the tiles that + // show CPU memory written) + let mut x = a; + while x < a + n { + let t = x & !(TILE - 1); + let end = (t + TILE).min(a + n); + if let Some(entry) = s.mapped.get_mut(&t).filter(|e| e.src == 0) { + let mut pg = x & !(PAGE - 1); + while pg < end { + let idx = (pg - t) / PAGE; + if entry.holes & (1u16 << idx) == 0 { + pages.push(PageSlot { cpu: pg, win: pg, slot: &mut entry.sent[idx] }); + } + pg += PAGE; + } + } + if let Some(over) = s.mirrors.get(&t) { + for &w in over { + let Some(entry) = s.mapped.get_mut(&w).filter(|e| e.src == t) else { continue }; + let mut pg = x & !(PAGE - 1); + while pg < end { + let idx = (pg - t) / PAGE; + if entry.holes & (1u16 << idx) == 0 { + pages.push(PageSlot { cpu: pg, win: w + (pg - t), slot: &mut entry.sent[idx] }); + } + pg += PAGE; + } + } + } + x = end; + } + } + for &pg in &retry_pages { + let t = pg & !(TILE - 1); + let idx = (pg - t) / PAGE; + let Some(entry) = s.mapped.get_mut(&t).filter(|e| e.holes & (1u16 << idx) == 0) else { + deferred.push(pg); + continue; + }; + // (read at the tile's CPU address: a tile over a CPU view shows that view's bytes) + pages.push(PageSlot { cpu: entry.cpu(t) + (pg - t), win: pg, slot: &mut entry.sent[idx] }); + } + if !s.mirrors.is_empty() || again || !retry_pages.is_empty() { + // (in window order, for the runs; a page filled, written or retried is one slot, + // scanned once) + pages.sort_unstable_by_key(|p| p.win); + pages.dedup_by_key(|p| p.win); + } + fill.clear(); + s.fill = fill; + // (`XCL_LOOK_STATS=2`: the gather of the pages apart from their scan) + let t_gathered = super::look_stats::deep().then(std::time::Instant::now); + let shares = scan_pages(&pages, &mut dirty_runs); + let t_scan_end = std::time::Instant::now(); + super::look_stats::scan(pages.len(), &dirty_runs); + if let Some(t_gathered) = t_gathered { + super::look_stats::scan_split(t_gathered - t_locked, t_scan_end - t_gathered, shares); + } + if let Some((written, found)) = own { + let (scanned, unchanged) = own_scanned(&found, &pages, &dirty_runs); + super::look_stats::own_writes(written, found.len(), scanned, unchanged); + } + drop(pages); + PHASES[1].fetch_add((t_scan_end - t_locked).as_micros() as u64, Ordering::Relaxed); + PHASES[3].fetch_add((zero_runs.len() + dirty_runs.len()) as u64, Ordering::Relaxed); + let t_scanned = t_started.map(|_| t_scan_end); + // Dual-journal exactly what the legacy attempt is about to consume. This sealed batch is a + // parity record only: the established upload path remains authoritative and retires it as + // obsolete after publishing its own retry state. + let legacy_batch = coordination + .seal_legacy(q as u64, &zero_runs, &retry_pages, &dirty_runs) + .ok() + .flatten(); + // Owned planning remains preparatory only (main #2962): capturing and revalidating source + // hashes both require title-memory reads under STATE. Do not activate it until capture can + // be made genuinely lock-free and measured on a title workload. + let state_generation = s.generation; + let mapping_epoch = s.mapping_epoch; + let mut legacy_parity = legacy_batch.map(|lease| LegacyParityUpload::Lease { + lease, state_generation, mapping_epoch, + }); + if let Some(parity) = legacy_parity.as_ref() { + match parity.revalidate(s.generation, s.mapping_epoch, |page| s.upload_page_observation(page)) { + // "Ready" accepts only the legacy attempt. The parity lease stays pending until that + // authoritative path finishes; coordinated accept/publish remains a later activation. + LegacyParityRevalidation::Ready => {} + LegacyParityRevalidation::RestartForGeneration => { + let _ = legacy_parity.take().unwrap().retry(); + return (SubmitStep::Restart, excess); + } + LegacyParityRevalidation::RetryCurrentGeneration => { + rejournal_zeros(&mut s.to_zero, zero_runs); + s.retry_pages = retry_journal(PreparationOutcome::RetryRequired, deferred, &dirty_runs); + let _ = legacy_parity.take().unwrap().retry(); + return (SubmitStep::Restart, excess); + } + } + } + // Submit tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. + let mut outcome = PreparationOutcome::Ready; + let mut upload_wait = None; + if !zero_runs.is_empty() { + match s.upload_zeros(&zero_runs) { + UploadStep::Done(done) => outcome = done, + UploadStep::Wait(ticket) => { + outcome = PreparationOutcome::RetryRequired; + upload_wait = Some(ticket); + } + } + if outcome != PreparationOutcome::Ready { + rejournal_zeros(&mut s.to_zero, zero_runs.clone()); + } + } + if outcome == PreparationOutcome::Ready && !dirty_runs.is_empty() { + match s.upload_dirty(&dirty_runs) { + UploadStep::Done(done) => outcome = done, + UploadStep::Wait(ticket) => { + outcome = PreparationOutcome::RetryRequired; + upload_wait = Some(ticket); + } + } + } + if s.poison.as_ref().is_some_and(|p| p.at.elapsed() >= std::time::Duration::from_millis(16)) { + s.refresh_poison(); + } + PHASES[2].fetch_add(t_scan_end.elapsed().as_micros() as u64, Ordering::Relaxed); + { + static CALLS: AtomicU64 = AtomicU64::new(0); + static BYTES: AtomicU64 = AtomicU64::new(0); + let bytes: usize = zero_runs.iter().chain(dirty_runs.iter()).map(|r| r.1).sum(); + let n = CALLS.fetch_add(1, Ordering::Relaxed) + 1; + let b = BYTES.fetch_add(bytes as u64, Ordering::Relaxed) + bytes as u64; + let us = SUBMIT_US.fetch_add(t0.elapsed().as_micros() as u64, Ordering::Relaxed) + t0.elapsed().as_micros() as u64; + if n.is_power_of_two() && n >= 16 { + let listed = s.mapped.values().filter(|e| e.pool == LAZY).count(); + crate::xlog_info!("sparse windows: {n} submits, {} MB of CPU writes uploaded, {} ms spent, {} tiles mapped", b >> 20, us / 1000, s.mapped.len() - listed); + let (own, unsent) = never_sent(&s.mapped); + crate::xlog_info!("sparse windows: {unsent} of the windows' own {own} mapped tiles ({} of {} MB) never got a byte from the CPU (zeros, or what the GPU wrote); {listed} listed with no video memory (XCL_SPARSE_LAZY)", unsent * TILE >> 20, own * TILE >> 20); + let ms = |x: &AtomicU64| x.load(Ordering::Relaxed) / 1000; + let c = &s.counts; + crate::xlog_info!( + "sparse windows timing: write-watch {} ms ({} dirty pages), lock wait {} ms, chunk scan {} ms, upload {} ms ({} runs, {} of them in {} dispatches); GPU views: {} tiles with video memory ({} at most, cap {}), {} filled ({} MB), {} refused, {} given back, {} holes asked again", + ms(&WATCH[0]), + WATCH[1].load(Ordering::Relaxed), + ms(&PHASES[0]), + ms(&PHASES[1]), + ms(&PHASES[2]), + PHASES[3].load(Ordering::Relaxed), + SCATTERED[1].load(Ordering::Relaxed), + SCATTERED[0].load(Ordering::Relaxed), + s.mirrored, + c.peak, + s.mirror_cap, + c.fills, + c.fill_bytes >> 20, + c.refused, + c.given_back, + c.rechecks + ); + } + } + s.retry_pages = retry_journal(outcome, deferred, &dirty_runs); + if let Some(parity) = legacy_parity { + let _ = parity.obsolete(); + } + if let Some((zero, dirty)) = metric_runs.as_mut() { + remember_metric_runs(zero, &zero_runs); + remember_metric_runs(dirty, &dirty_runs); + } + if let (Some(sample), Some(t_started), Some(t_maintained), Some(t_scanned)) = + (look.as_deref_mut(), t_started, t_maintained, t_scanned) + { + let t_uploaded = std::time::Instant::now(); + sample.add_time(MAINTENANCE_US, t_maintained.duration_since(t_started)); + sample.add_time(SCAN_US, t_scanned.duration_since(t_maintained)); + sample.add_time(UPLOAD_US, t_uploaded.duration_since(t_scanned)); + } + dirty_runs.clear(); + s.scratch_runs = dirty_runs; + let step = match upload_wait { + Some(ticket) => SubmitStep::Wait(ticket), + None => SubmitStep::Done(outcome), + }; + (step, excess) } - #[test] - fn working_set_check_rejects_resident_read_only_pages_without_touching_cold_pages() { - use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE, PAGE_READONLY}; - unsafe { - let base = VirtualAlloc(std::ptr::null(), 3 * PAGE, MEM_RESERVE, PAGE_NOACCESS) as usize; - assert_ne!(base, 0); - assert!(!VirtualAlloc(base as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); - assert!(!VirtualAlloc((base + PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_READONLY).is_null()); - assert!(!VirtualAlloc((base + 2 * PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); - std::ptr::write_volatile(base as *mut u8, 1); - assert_eq!(std::ptr::read_volatile((base + PAGE) as *const u8), 0); - assert!(resident_pages_writable(base, base + PAGE)); - assert!(!resident_pages_writable(base + PAGE, base + 2 * PAGE)); - assert!(resident_pages_writable(base + 2 * PAGE, base + 3 * PAGE)); + /// The retirement fences' values now (`poll_retirement_fences` on a standalone `State`). + #[cfg(test)] + unsafe fn observe_retirement_fences(&self) -> Vec<(ID3D12Fence, u64)> { + let fences = std::iter::once(self.fence.clone()) + .chain(self.quarantined.iter().flat_map(|batch| batch.marks.iter().flatten().map(|(fence, _)| fence.clone()))) + .collect(); + poll_unique(fences, |fence| fence.as_raw() as usize, |fence| super::real::fence_completed(fence)) + } - let mut cold: windows_sys::Win32::System::ProcessStatus::PSAPI_WORKING_SET_EX_INFORMATION = std::mem::zeroed(); - cold.VirtualAddress = (base + 2 * PAGE) as *mut c_void; - assert_ne!( - windows_sys::Win32::System::ProcessStatus::K32QueryWorkingSetEx( - windows_sys::Win32::System::Threading::GetCurrentProcess(), - &mut cold as *mut _ as *mut c_void, - std::mem::size_of_val(&cold) as u32, - ), - 0 - ); - assert_eq!(cold.VirtualAttributes.Flags & 1, 0, "the metadata query paged memory in"); - assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + /// `before_execute` on a standalone `State` (tests): its steps under the caller's hold of the + /// state, a wait for the GPU where an upload needs one, then the queue's wait for the state's + /// fence. Returns excess recycled `RbJob`s. + #[cfg(test)] + unsafe fn before_execute_on(&mut self, queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) -> Vec { + let mut metric_runs = None; + let mut excess = Vec::new(); + loop { + let observed = self.observe_retirement_fences(); + let (step, more) = self.before_execute_on_with(queue, dirty, page, &observed, None, &mut metric_runs, None); + excess.extend(more); + match step { + SubmitStep::Restart => {} + SubmitStep::Wait(ticket) => { + if crate::gpu::fence::wait(&ticket.fence, ticket.target, &ticket.dev, None, 5000).is_err() { + return excess; + } + if self.wait_ticket_valid(&ticket) { + self.reclaim_ring(); + } + } + SubmitStep::Done(PreparationOutcome::Ready) => { + let q = queue.as_raw() as usize; + if reserve_queue_wait(&mut self.waited, q, self.value) { + let _ = super::real::native_queue_wait(queue, &self.fence, self.value); + super::list_x::note_internal_wait(q, "sparse uploads and tile mappings", &self.fence, self.value); + } + return excess; + } + SubmitStep::Done(_) => return excess, + } } } +} - #[test] - fn memory_counts_committed_pages_and_separates_devices_and_retired_pools() { - let holes = [0xFFFE, 0xFFF0].into_iter(); // one committed page, then four - let (pools, occupied, retired, committed) = memory_byte_counts(7, 7, 1, 60, 1, holes); - assert_eq!(pools, POOL_TILES as usize * TILE); - assert_eq!(occupied, 4 * TILE, "occupied video tiles are independent of CPU page commitment"); - assert_eq!(retired, POOL_TILES as usize * TILE, "the retired pool is not also active"); - assert_eq!(committed, 5 * PAGE, "holes in a 64 KiB tile do not consume CPU commit"); - assert_eq!(memory_byte_counts(8, 7, 1, 60, 1, [0].into_iter()), (0, 0, 0, 0)); +/// Before a title submit on `queue`: what the title committed and decommitted mapped and unmapped +/// on the GPU, the tiles over CPU views and what they show, and the CPU writes at `dirty` (pages +/// of `page` bytes, sorted) uploaded; the queue then waits for all of it. `look` +/// (`XCL_ACTIVITY`) gets the look's times. Not `Ready`: the submit must not go (main's +/// preparation outcome); the journals of what did not go out are kept for the next submit. +pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize, mut look: Option<&mut LookSample>) -> PreparationOutcome { + if look.is_some() { + super::vram::begin_before_execute_timing(); } - - /// `queue()` answers while the state's lock is held: a resource's last `Release` asks for - /// it (`late_release::drain_known`) from inside a D3D12 call that the lock's holder can be - /// waiting for (a list's `Reset` against an upload's allocator `Reset`, with `XCL_DRED=1`). - #[test] - fn the_queue_is_answered_while_the_state_is_locked() { - let held = STATE.lock().unwrap(); - let (tx, rx) = std::sync::mpsc::channel(); - let asked = std::thread::spawn(move || { - let _ = queue(); - let _ = tx.send(()); - }); - let answered = rx.recv_timeout(std::time::Duration::from_secs(5)).is_ok(); - drop(held); - asked.join().unwrap(); - assert!(answered, "queue() waited for the sparse state's lock"); + let t_entry = std::time::Instant::now(); + let q = queue.as_raw() as usize; + let t0 = look.is_some().then_some(t_entry); + let queue_gate = WAIT_GATES.lock().unwrap().entry(q).or_default().clone(); + let _queue_serial = queue_gate.lock().unwrap(); + let _upload_lifetime = UPLOAD_STATE_LIFETIME.read().unwrap(); + let (mut uploads, mut timing) = UploadGateTiming::acquire(look.is_some()); + let t_gated = t0.map(|_| std::time::Instant::now()); + if let (Some(sample), Some(t0), Some(t_gated)) = (look.as_deref_mut(), t0, t_gated) { + sample.add_time(QUEUE_WAIT_US, t_gated.duration_since(t0)); } - - #[test] - fn exact_retirement_forgets_cache_but_inflight_batch_keeps_its_fence() { - use std::sync::Arc; - let old = Arc::new(7u32); - let mut fences = FxHashMap::default(); - fences.insert(0xA, (old.clone(), 3)); - let batch_mark = fences[&0xA].0.clone(); - - assert!(fences.contains_key(&0xA), "marker failure must leave the cache pinned"); - let gone = remove_queue_fence(&mut fences, 0xA).expect("exact retirement callback"); - assert!(fences.is_empty() && Arc::ptr_eq(&gone.0, &batch_mark)); - drop(gone); - drop(old); - assert_eq!(Arc::strong_count(&batch_mark), 1, "cache removal invalidated an in-flight batch mark"); - - let replacement = Arc::new(9u32); - fences.insert(0xA, (replacement.clone(), 1)); - assert!(!Arc::ptr_eq(&batch_mark, &fences[&0xA].0), "reused raw address kept the retired generation's fence"); + let outcome = before_execute_locked(queue, dirty, page, q, t_entry, t0, &mut look, &mut uploads, &mut timing); + let times = timing.finish(); + drop(uploads.take()); + if let Some(sample) = look.as_deref_mut() { + add_gate_times(&mut sample.0, SUBMIT_GATE_WAIT_US, SUBMIT_GATE_HOLD_US, None, times); } + outcome +} - #[test] - fn retirement_fence_poll_is_unlocked_and_new_requirements_fail_closed() { - use std::sync::{atomic::{AtomicU64, AtomicUsize, Ordering}, Arc}; - let first = Arc::new(AtomicU64::new(1)); - let late = Arc::new(AtomicU64::new(9)); - let state = Mutex::new(vec![first.clone(), first.clone()]); - let polls = AtomicUsize::new(0); - - let snapshot = state.lock().unwrap().clone(); - let observed = poll_unique(snapshot, |fence| Arc::as_ptr(fence) as usize, |fence| { - assert!(state.try_lock().is_ok(), "completion polling held sparse state"); - state.lock().unwrap().push(late.clone()); - polls.fetch_add(1, Ordering::Relaxed); - fence.load(Ordering::Relaxed) - }); +/// What `State::before_execute_on_with` came to. +enum SubmitStep { + /// prepared (`Ready`), or the outcome the submit gets (the journals were put back) + Done(PreparationOutcome), + /// an upload slot or ring room the GPU still holds: waited for with the locks let go, then again + /// from the start (the journals were put back) + Wait(WaitTicket), + /// the state's generation changed under the parity record: again from the start + Restart, +} - assert_eq!(polls.load(Ordering::Relaxed), 1, "the same fence is queried once"); - assert_eq!(observed_completion(&observed, &first, Arc::ptr_eq), 1); - assert!(observed_completion(&observed, &first, Arc::ptr_eq) < 2, "a higher mark added during polling remains held"); - assert_eq!(observed_completion(&observed, &late, Arc::ptr_eq), 0, "a newly added fence remains held"); +#[allow(clippy::too_many_arguments)] +unsafe fn before_execute_locked( + queue: &ID3D12CommandQueue, + dirty: &[usize], + page: usize, + q: usize, + t_entry: std::time::Instant, + t0: Option, + look: &mut Option<&mut LookSample>, + uploads: &mut Option, + timing: &mut UploadGateTiming, +) -> PreparationOutcome { + let mut metric_runs = look.is_some().then(|| (BTreeMap::new(), BTreeMap::new())); + 'prepare: loop { + let t_started = t0.map(|_| std::time::Instant::now()); + let observed = poll_retirement_fences(); + let t_lock = std::time::Instant::now(); + // (who had the lock when this began to wait for it: `XCL_LOOK_STATS=2`) + let behind = (HOLDER.load(Ordering::Relaxed) as usize).min(HOLDERS - 1); + FLUSHERS_WAITING.fetch_add(1, Ordering::AcqRel); + let mut g = lock_first(&STATE, &SUBMITS_WAITING); + FLUSHERS_WAITING.fetch_sub(1, Ordering::AcqRel); + let held = holding(Holder::Submit); + let t_got = super::look_stats::deep().then(std::time::Instant::now); + forget_released(&mut g); + let Some(s) = g.as_mut() else { + if let (Some(sample), Some(t_started)) = (look.as_deref_mut(), t_started) { + sample.add_time(MAINTENANCE_US, t_started.elapsed()); + } + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); + return PreparationOutcome::Ready; + }; + if MIRROR_ASKING.swap(false, Ordering::AcqRel) { + s.asks.append(&mut MIRROR_ASKS.lock().unwrap()); + } + if REMAPPING.swap(false, Ordering::AcqRel) { + take_remaps(&mut s.remaps, &mut REMAPS.lock().unwrap()); + } + if WRITE_ASKING.swap(false, Ordering::AcqRel) { + let asks = std::mem::take(&mut *WRITE_ASKS.lock().unwrap_or_else(|e| e.into_inner())); + s.give_memory(&asks); + } + let waited = t_lock.elapsed().as_micros() as u64; + PHASES[0].fetch_add(waited, Ordering::Relaxed); + // (the gates before the lock count with it: all of `before_execute` is the submit's sparse time) + SUBMIT_US.fetch_add(waited + t_lock.duration_since(t_entry).as_micros() as u64, Ordering::Relaxed); + if let Some(t_got) = t_got { + LOCK_SPLIT.add(LS_WAIT, (t_got - t_lock).as_micros() as u64); + LOCK_SPLIT.add(LS_ALL, waited); + HELD.add(HOLDERS + behind, (t_got - t_lock).as_micros() as u64); + } + let (step, excess) = s.before_execute_on_with(queue, dirty, page, &observed, look.as_deref_mut(), &mut metric_runs, t_started); + let outcome = match step { + SubmitStep::Restart => { + drop(held); + drop(g); + drop(observed); + drop(excess); + continue 'prepare; + } + SubmitStep::Wait(ticket) => { + // `to_zero` and `retry_pages` were restored before ownership is released. Another + // queue may consume either journal; reacquisition is included in UPLOAD_WAIT_US and the + // next iteration always rebuilds its plan from current state. + drop(held); + drop(g); + drop(observed); + drop(excess); + let wait_started = t0.map(|_| std::time::Instant::now()); + if !timing.with_released(uploads, || wait_upload_released(ticket)) { + if let (Some(sample), Some(wait_started)) = (look.as_deref_mut(), wait_started) { + sample.add_time(UPLOAD_WAIT_US, wait_started.elapsed()); + } + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); + return PreparationOutcome::RetryRequired; + } + if let (Some(sample), Some(wait_started)) = (look.as_deref_mut(), wait_started) { + sample.add_time(UPLOAD_WAIT_US, wait_started.elapsed()); + } + continue 'prepare; + } + SubmitStep::Done(outcome) => outcome, + }; + if outcome != PreparationOutcome::Ready { + drop(held); + drop(g); + drop(observed); + drop(excess); + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); + return outcome; } - - #[test] - fn title_queue_wait_reservation_is_monotonic_and_per_queue() { - let mut waited = FxHashMap::default(); - assert!(!reserve_queue_wait(&mut waited, 1, 0)); - assert!(reserve_queue_wait(&mut waited, 1, 4)); - assert!(!reserve_queue_wait(&mut waited, 1, 4)); - assert!(!reserve_queue_wait(&mut waited, 1, 3)); - assert!(reserve_queue_wait(&mut waited, 2, 3)); - assert!(reserve_queue_wait(&mut waited, 1, 5)); - assert_eq!(waited, FxHashMap::from_iter([(1, 5), (2, 3)])); + // the queue waits for the uploads and tile mappings (outside the lock; given back if it fails) + let value = s.value; + let previous = s.waited.get(&q).copied(); + let wait = reserve_queue_wait(&mut s.waited, q, value).then(|| (s.fence.clone(), value, previous)); + drop(held); + drop(g); + drop(observed); + // (recycled copy-back jobs past the pool's cap drop outside all locks) + drop(excess); + if let Some((fence, value, previous)) = wait { + if super::real::native_queue_wait(queue, &fence, value).is_err() { + let mut g = lock_state(); + if let Some(s) = g.as_mut().filter(|s| s.fence.as_raw() == fence.as_raw() && s.waited.get(&q) == Some(&value)) { + rollback_queue_wait(&mut s.waited, q, value, previous); + } + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); + return PreparationOutcome::RetryRequired; + } + super::list_x::note_internal_wait(q, "sparse uploads and tile mappings", &fence, value); } - - #[test] - fn failed_write_watch_pages_survive_until_a_ready_retry() { - let runs = [(0x1040, PAGE), (0x2000, CHUNK)]; - assert_eq!(retry_journal(PreparationOutcome::RetryRequired, vec![], &runs), [0x1000, 0x2000]); - assert!(retry_journal(PreparationOutcome::Ready, vec![], &runs).is_empty()); - assert_eq!(retry_journal(PreparationOutcome::ExecutedUntracked, vec![0x3000], &runs), [0x1000, 0x2000, 0x3000]); + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); + return PreparationOutcome::Ready; } +} - #[test] - fn late_claim_completion_cannot_change_a_newer_owner() { - let mut ledger = WorkClaimLedger::new(11); - ledger.add_dirty_pages([0x8000]); - let old = ledger.claim(1).unwrap(); - assert_eq!(ledger.commit(old.token), WorkClaimResolution::Committed); +/// A buffer the title places at `va` in a sparse window (`bytes` long, `desc` the PC +/// description): a reserved resource over the window's tiles there, starting at the 64 KiB +/// below `va` (returned: its distance from there). +pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option<(crate::util::HRESULT, usize)> { + let _placement = PLACEMENT.lock().unwrap(); + place_buffer_in( + &STATE, + &FORGOTTEN, + va, + desc, + state, + |d| { + let hr = super::real::dev_create_reserved_resource(this, d as *const _ as usize, state as usize, 0, riid, ppv); + (hr >= 0 && !ppv.is_null() && !(*ppv).is_null()).then_some((hr, *ppv)) + }, + |raw| { + if !ppv.is_null() && *ppv == raw { + *ppv = std::ptr::null_mut(); + } + drop(ID3D12Resource::from_raw(raw)); + }, + ) +} - ledger.add_retry_pages([0x8000]); - let newer = ledger.claim(1).unwrap(); - assert_eq!(ledger.restore(old.token), WorkClaimResolution::AlreadyFinished); - assert_eq!(ledger.owners.get(&0x8000), Some(&newer.token.serial)); - assert_eq!(ledger.commit(newer.token), WorkClaimResolution::Committed); - assert!(ledger.available.is_empty()); +unsafe fn place_buffer_in( + state_lock: &Mutex>, + forgotten: &Mutex>, + va: usize, + desc: &D3D12_RESOURCE_DESC, + state: u32, + create: impl FnOnce(&D3D12_RESOURCE_DESC) -> Option<(crate::util::HRESULT, *mut c_void)>, + on_abort: impl FnOnce(*mut c_void), +) -> Option<(crate::util::HRESULT, usize)> { + let start = va & !(TILE - 1); + let delta = va - start; + let bytes = desc.Width as usize; + if bytes == 0 { + return None; + } + let end = va.checked_add(bytes)?.checked_sub(1)?; + let generation = { + let g = lock_state_in(state_lock, forgotten); + let _held = holding(Holder::Buffers); + let s = g.as_ref()?; + s.window_index(start)?; + s.window_index(end)?; + s.fence.clone() + }; + let mut d = *desc; + d.Width = (delta + bytes) as u64; + d.Alignment = 0; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + // Reserved buffers only accept NONE or ALLOW_UNORDERED_ACCESS (strip console flags and ALLOW_CROSS_ADAPTER). + d.Flags &= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if state & (D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32 | D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32) != 0 { + d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + } + // Driver creation may call back into a release path which needs `STATE`. Revalidate the + // strongly owned fence generation before publishing the resulting resource. + let (hr, raw) = create(&d)?; + let mut g = lock_state_in(state_lock, forgotten); + let valid = g.as_ref().is_some_and(|s| { + s.fence.as_raw() == generation.as_raw() && s.window_index(start).is_some() && s.window_index(end).is_some() + }); + let Some(res) = valid.then(|| ID3D12Resource::from_raw_borrowed(&raw).cloned()).flatten() else { + drop(g); + drop(generation); + on_abort(raw); + return None; + }; + let held = holding(Holder::Buffers); + let s = g.as_mut().unwrap(); + // (a name for what a device removal reports about an address, `real::log_device_removed`) + let _ = res.SetName(&windows::core::HSTRING::from(format!("title buffer over tiles at {va:#x} ({bytes:#x} bytes)"))); + // its tiles: the window's video memory at the same addresses; probe actual OS commitment + // so uncommitted pages (e.g. [start, va) or reserved tails) stay marked as holes (of the CPU + // view a tile of a GPU view shows) + let tiles = s.buffer_tiles(start, delta + bytes); + s.mapping_epoch = s.mapping_epoch.wrapping_add(1); + // (`XCL_VIEW_POISON`: its tiles without video memory show the poison tile as the window's do) + s.poison_all(&res, (delta + bytes).div_ceil(TILE) as u32); + s.map_tiles(&res, start, &tiles); + if s.buffers.contains_key(&(raw as usize)) { + forget_in(s, raw as usize); + } + for &(_, tile) in &tiles { + *s.pinned.entry(tile).or_default() += 1; } + s.buffers.insert(raw as usize, tiles); + s.signal(); + drop(held); + drop(g); + drop(res); + drop(generation); + Some((hr, delta)) +} - #[test] - fn foreground_queue_cannot_pass_or_steal_an_unreceipted_claim() { - let mut frontier = ClaimFrontier::new(23); - let planner = frontier.claim(100).unwrap(); - assert_eq!( - frontier.observe(23, planner.epoch, 200), - Ok(ClaimFrontierAction::TakeOver(planner)), - "another queue mistook pending planner work for an empty frontier", - ); +/// Placed buffers released while `STATE` was held, let go by the next `lock_state`. Held only +/// to push or take, never across a call out. +static FORGOTTEN: Mutex> = Mutex::new(Vec::new()); - let helper = frontier.take_over(planner, 200).unwrap(); - assert_eq!(frontier.accept(planner), Err(ClaimFrontierError::StaleToken)); - assert_eq!(frontier.receipt(planner, 7), Err(ClaimFrontierError::StaleToken)); - assert_eq!(frontier.consume_obsolete(planner), Err(ClaimFrontierError::StaleToken)); - assert_eq!(frontier.take_over(planner, 300), Err(ClaimFrontierError::StaleToken)); - assert_eq!(frontier.observe(23, helper.epoch, 200), Ok(ClaimFrontierAction::Progress(helper))); +/// `STATE`, with the buffers released while it was held let go first. +fn lock_state() -> std::sync::MutexGuard<'static, Option> { + lock_state_in(&STATE, &FORGOTTEN) +} - frontier.accept(helper).unwrap(); - assert_eq!(frontier.take_over(helper, 100), Err(ClaimFrontierError::WrongState)); - assert_eq!(frontier.consume_obsolete(helper), Err(ClaimFrontierError::WrongState)); - assert_eq!( - frontier.observe(23, helper.epoch, 100), - Ok(ClaimFrontierAction::WaitForReceipt(helper)), - "accepted GPU work was exposed for retry", - ); - frontier.receipt(helper, 7).unwrap(); - assert_eq!( - frontier.observe(23, helper.epoch, 100), - Ok(ClaimFrontierAction::Ready { through: helper.epoch, required_fence: Some(7) }), - ); +fn lock_state_in<'a>(state: &'a Mutex>, forgotten: &Mutex>) -> std::sync::MutexGuard<'a, Option> { + let mut g = state.lock().unwrap(); + forget_released_in(&mut g, forgotten); + g +} + +/// Who holds `STATE` (`HOLDER`): the time a submit waits for it is put down to the holder it found +/// there when it began to wait, and each holder's own time under it is summed (`XCL_LOOK_STATS=2`, +/// with the sparse lock split line). +#[derive(Clone, Copy)] +#[repr(u8)] +enum Holder { + Nobody = 0, + Submit, + After, + Ranges, + Settle, + ReadbackThread, + TileMaps, + Commits, + Sources, + Buffers, + CpuRead, + Other, +} +const HOLDERS: usize = 12; +const HOLDER_NAMES: [&str; HOLDERS] = [ + "nobody", + "submits", + "after stages", + "ranges", + "copies back settled", + "readback thread", + "put-off mappings", + "commits", + "GPU-view sources", + "placed buffers", + "CPU reads", + "other", +]; +static HOLDER: AtomicU8 = AtomicU8::new(0); +/// [µs each holder held the lock], [µs submits waited behind each], then the submit's other +/// waits for it: in its after stage, and for its ranges +static HELD: super::look_stats::Sums<{ 2 * HOLDERS + 2 }> = super::look_stats::Sums::new(); +const HELD_AFTER_WAIT: usize = 2 * HOLDERS; +const HELD_RANGES_WAIT: usize = 2 * HOLDERS + 1; + +/// `STATE` is held by its holder until this is dropped (declared after the guard: it goes first). +struct Holding(Holder, Option); + +fn holding(who: Holder) -> Holding { + HOLDER.store(who as u8, Ordering::Relaxed); + Holding(who, super::look_stats::deep().then(std::time::Instant::now)) +} + +impl Drop for Holding { + fn drop(&mut self) { + HOLDER.store(Holder::Nobody as u8, Ordering::Relaxed); + if let Some(t) = self.1 { + HELD.add(self.0 as usize, t.elapsed().as_micros() as u64); + } } +} - #[test] - fn receipts_and_obsolete_holes_advance_only_a_contiguous_frontier() { - let mut frontier = ClaimFrontier::new(29); - let first = frontier.claim(1).unwrap(); - let second = frontier.claim(2).unwrap(); - let hole = frontier.claim(3).unwrap(); - frontier.accept(first).unwrap(); - frontier.accept(second).unwrap(); - frontier.receipt(second, 11).unwrap(); - frontier.consume_obsolete(hole).unwrap(); +/// The holders part of the sparse lock split line (`HELD`'s sums over `submits`), in ms a submit: +/// who held the lock how long, and whom the submits' waits for it were behind. +fn holders_line(x: &[u64; 2 * HOLDERS + 2], submits: u64) -> String { + let n = submits.max(1) as f64; + let part = |from: usize| -> String { + let items: Vec = (0..HOLDERS).filter(|&k| x[from + k] > 0).map(|k| format!("{} {:.3}", HOLDER_NAMES[k], x[from + k] as f64 / n / 1e3)).collect(); + if items.is_empty() { "none".into() } else { items.join(", ") } + }; + format!( + "held by: {} ms a submit; waits behind: {} ms a submit; the submit's other waits for it: after stage {:.3}, ranges {:.3} ms a submit", + part(0), + part(HOLDERS), + x[HELD_AFTER_WAIT] as f64 / n / 1e3, + x[HELD_RANGES_WAIT] as f64 / n / 1e3 + ) +} - assert_eq!(frontier.retired_through, 0, "out-of-order terminal work crossed the first claim"); - assert_eq!( - frontier.observe(29, hole.epoch, 9), - Ok(ClaimFrontierAction::WaitForReceipt(first)), - ); - frontier.receipt(first, 8).unwrap(); - assert_eq!(frontier.retired_through, hole.epoch, "an obsolete hole left the frontier stuck"); - assert_eq!( - frontier.observe(29, hole.epoch, 9), - Ok(ClaimFrontierAction::Ready { through: hole.epoch, required_fence: Some(11) }), - ); - assert_eq!( - frontier.observe(29, first.epoch, 9), - Ok(ClaimFrontierAction::Ready { through: first.epoch, required_fence: Some(8) }), - "an older observer unnecessarily inherited a newer fence", - ); +/// `forget_released_in` for the global state (`FORGOTTEN`). +fn forget_released(g: &mut Option) { + forget_released_in(g, &FORGOTTEN); +} + +fn forget_released_in(g: &mut Option, forgotten: &Mutex>) { + let gone = std::mem::take(&mut *forgotten.lock().unwrap()); + let Some(s) = g.as_mut() else { return }; + for res in gone { + forget_in(s, res); } +} - #[test] - fn frontier_rejects_wrong_generations_unknown_epochs_and_invalid_receipts() { - let mut frontier = ClaimFrontier::new(31); - let token = frontier.claim(4).unwrap(); - assert_eq!(frontier.observe(30, token.epoch, 4), Err(ClaimFrontierError::StaleGeneration)); - assert_eq!(frontier.observe(31, token.epoch + 1, 4), Err(ClaimFrontierError::UnknownEpoch)); - assert_eq!(frontier.receipt(token, 1), Err(ClaimFrontierError::WrongState)); - frontier.accept(token).unwrap(); - assert_eq!(frontier.receipt(token, 0), Err(ClaimFrontierError::Fence)); - assert_eq!(frontier.observe(31, 0, 4), Ok(ClaimFrontierAction::Ready { through: 0, required_fence: None })); +/// A placed buffer is gone: its tiles are not pinned by it any more. This runs from the +/// resource's last Release, which D3D12 can make while it holds a lock of its own (in a title's +/// command list Reset), and `before_execute` calls D3D12 with `STATE` held: waiting for `STATE` +/// here deadlocked the two threads. So it does not wait: with `STATE` held, the holder's next +/// `lock_state` lets the buffer go. +pub fn forget_buffer(res: usize) { + forget_buffer_in(&STATE, &FORGOTTEN, res); +} - let stale_generation = ClaimFrontierToken { state_generation: 32, ..token }; - assert_eq!(frontier.receipt(stale_generation, 1), Err(ClaimFrontierError::StaleGeneration)); +fn forget_buffer_in(state: &Mutex>, forgotten: &Mutex>, res: usize) { + forgotten.lock().unwrap().push(res); + match state.try_lock() { + Ok(mut g) => { + let _held = std::ptr::eq(state, &STATE).then(|| holding(Holder::Other)); + forget_released_in(&mut g, forgotten) + } + Err(std::sync::TryLockError::WouldBlock) => {} + Err(e) => panic!("sparse state: {e}"), } +} - #[test] - fn frontier_epoch_and_lease_overflow_fail_without_partial_publication() { - let mut epoch = ClaimFrontier::new(37); - epoch.next_epoch = u64::MAX; - assert_eq!(epoch.claim(1), Err(ClaimFrontierError::Exhausted)); - assert!(epoch.records.is_empty()); +fn forget_in(s: &mut State, res: usize) { + let Some(tiles) = s.buffers.remove(&res) else { return }; + for (t, tile) in tiles { + if let Some(c) = s.pinned.get_mut(&tile) { + *c -= 1; + if *c == 0 { + s.pinned.remove(&tile); + s.release_if_unused(t, tile); + } + } + } +} - let mut lease = ClaimFrontier::new(41); - lease.next_lease = u64::MAX; - assert_eq!(lease.claim(1), Err(ClaimFrontierError::Exhausted)); - assert_eq!(lease.next_epoch, 0); - assert!(lease.records.is_empty()); +#[cfg(test)] +mod tests { + use super::*; - let mut takeover = ClaimFrontier::new(43); - let token = takeover.claim(1).unwrap(); - takeover.next_lease = u64::MAX; - assert_eq!(takeover.take_over(token, 2), Err(ClaimFrontierError::Exhausted)); - assert_eq!(takeover.observe(43, token.epoch, 1), Ok(ClaimFrontierAction::Progress(token))); + thread_local! { + /// The VirtualQuery calls `source_holes` made on this thread. + pub(super) static VIRTUAL_QUERIES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Run by `take_asks` on this thread between the look up of the asked tiles' pairs and + /// their link (once) + pub(super) static BEFORE_LINK: std::cell::Cell>> = const { std::cell::Cell::new(None) }; + /// Run by `forget_mirrors` on this thread between dropping the queued asks and the asked + /// set's tiles (once) + pub(super) static BETWEEN_FORGETS: std::cell::Cell>> = const { std::cell::Cell::new(None) }; + /// The asks `forget_ask` counted on this thread (`MIRROR_FORGOTTEN` is every test's) + pub(super) static ASKS_FORGOTTEN: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// `lazy_commits` for the test on this thread (`LazyCommits`; None: as the environment + /// says). A thread's own: the other tests' states run beside it in this process. + pub(super) static LAZY_COMMITS_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// `take_tile` finds no video memory on this thread + pub(super) static NO_TILES: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + /// The runs of the tiles mapped, made from all of them (but those over a CPU view: their + /// own addresses are no CPU memory). + fn runs_of(s: &State) -> BTreeMap { + let mut tiles: Vec = s.mapped.iter().filter(|(_, e)| e.src == 0).map(|(&t, _)| t).collect(); + tiles.sort_unstable(); + let mut runs: Vec<(usize, usize)> = Vec::new(); + for t in tiles { + match runs.last_mut() { + Some(last) if last.1 == t => last.1 = t + TILE, + _ => runs.push((t, t + TILE)), + } + } + runs.into_iter().collect() } + /// The tiles waiting to be linked again keep their order while few; past `MIRROR_ASKS_MAX` each + /// waits once, however often its page changed. #[test] - fn work_claim_ledger_merges_orders_and_restores_exact_out_of_order_work() { - let mut ledger = WorkClaimLedger::new(7); - ledger.add_zero_ranges(&[(0x3000, 2 * PAGE)]); - ledger.add_retry_pages([0x3001, 0x1000, 0x1000]); - ledger.add_dirty_pages([0x4000, 0x6001, 0x6000]); + fn a_tile_remapped_again_and_again_waits_once() { + let (mut remaps, mut q) = (Vec::new(), vec![3 * TILE, TILE, 3 * TILE]); + take_remaps(&mut remaps, &mut q); + assert!(q.is_empty()); + assert_eq!(remaps, vec![3 * TILE, TILE, 3 * TILE], "few: as they came"); + // the same 100 tiles changed at each of 100 submits, none taken meanwhile + for _ in 0..100 { + let mut q: Vec = (0..100).map(|k| k * TILE).collect(); + take_remaps(&mut remaps, &mut q); + assert!(remaps.len() <= MIRROR_ASKS_MAX + 100); + } + remaps.sort_unstable(); + remaps.dedup(); + assert_eq!(remaps, (0..100).map(|k| k * TILE).collect::>()); + } + + /// XCL's own writes in a look: a slot counts as scanned when its CPU page is one of them, and + /// as unchanged when no changed run lies in its window page (a GPU view's slot has its own). + #[test] + fn own_writes_scanned_and_found_unchanged() { + let slot = |cpu: usize, win: usize| PageSlot { cpu, win, slot: std::ptr::null_mut() }; + let (c, w) = (0x10_0000usize, 0x8000_0000usize); + // CPU pages 0..4, and page 1 shown again by a GPU view's tile at `w` + let pages = [slot(c, c), slot(c + PAGE, c + PAGE), slot(c + PAGE, w + PAGE), slot(c + 2 * PAGE, c + 2 * PAGE), slot(c + 3 * PAGE, c + 3 * PAGE)]; + // changed: a chunk of page 0, the end of page 1 (own address only), page 3 whole + let runs = [(c + 0x40, 0x40), (c + 2 * PAGE - CHUNK, CHUNK), (c + 3 * PAGE, PAGE)]; + // XCL wrote pages 1, 2 and 3 (and 9, which was not scanned) + let found = [c + PAGE, c + 2 * PAGE, c + 3 * PAGE, c + 9 * PAGE]; + assert_eq!(own_scanned(&found, &pages, &runs), (4, 2)); + assert_eq!(own_scanned(&[], &pages, &runs), (0, 0)); + assert_eq!(own_scanned(&found, &pages, &[]), (4, 4)); + } + + /// The sparse lock split: the parts and the rest are the whole, as averages a submit. + #[test] + fn the_sparse_lock_parts_and_rest_are_the_whole() { + let mut x = [0u64; 11]; + x[LS_SUBMITS] = 4; + x[LS_ALL] = 4_000; + x[LS_WAIT] = 1_000; + x[LS_BACK] = 400; + x[LS_BACK_BYTES] = 8 << 10; + x[LS_VIEWS] = 200; + x[LS_MAP] = 1_200; + x[LS_MAP_TILES] = 10; + x[LS_MAP_CALLS] = 2; + x[LS_UNMAP] = 800; + x[LS_UNMAP_TILES] = 6; + assert_eq!( + lock_split_line(&x), + "sparse lock split (4 submits): wait 0.250 ms, copies back 0.100 ms (2 KB), GPU-view tiles 0.050 ms, mappings 0.300 ms (2.5 tiles in 0.5 calls), unmappings 0.200 ms (1.5 tiles), rest 0.100 ms a submit (of 1.000 ms)" + ); + // (parts counted over a submit that ended after the sums were taken: no negative rest) + x[LS_ALL] = 0; + assert!(lock_split_line(&x).contains("rest 0.000 ms")); + assert!(lock_split_line(&[0; 11]).starts_with("sparse lock split (0 submits): wait 0.000 ms")); + } - let first = ledger.claim(2).unwrap(); - assert_eq!(first.pages.iter().map(|(page, reasons)| (*page, reasons.0)).collect::>(), [ - (0x1000, WorkReasons::RETRY.0), - (0x3000, WorkReasons::ZERO.0 | WorkReasons::RETRY.0), - ]); - let second = ledger.claim(8).unwrap(); - assert_eq!(second.pages.iter().map(|(page, reasons)| (*page, reasons.0)).collect::>(), [ - (0x4000, WorkReasons::ZERO.0 | WorkReasons::DIRTY.0), - (0x6000, WorkReasons::DIRTY.0), - ]); + /// The holders part of the line: only the holders with time, as averages a submit. + #[test] + fn the_holders_line_names_who_held_the_lock_and_whom_the_waits_were_behind() { + let mut x = [0u64; 2 * HOLDERS + 2]; + x[Holder::Submit as usize] = 4_000; + x[Holder::TileMaps as usize] = 800; + x[HOLDERS + Holder::Settle as usize] = 2_000; + x[HELD_AFTER_WAIT] = 400; + assert_eq!( + holders_line(&x, 4), + "held by: submits 1.000, put-off mappings 0.200 ms a submit; waits behind: copies back settled 0.500 ms a submit; the submit's other waits for it: after stage 0.100, ranges 0.000 ms a submit" + ); + assert!(holders_line(&[0; 2 * HOLDERS + 2], 0).starts_with("held by: none ms a submit; waits behind: none")); + } - ledger.add_dirty_pages([0x1000]); - assert!(ledger.claim(1).is_none(), "new work escaped an older owner of the same page"); - assert_eq!(ledger.cancel(second.token), WorkClaimResolution::Restored); - let out_of_order = ledger.claim(1).unwrap(); - assert_eq!(out_of_order.pages[0].0, 0x4000); - assert_eq!(ledger.commit(first.token), WorkClaimResolution::Committed); - let later = ledger.claim(1).unwrap(); - assert_eq!(later.pages, [(0x1000, WorkReasons::DIRTY)]); - assert_eq!(ledger.commit(later.token), WorkClaimResolution::Committed); - assert_eq!(ledger.cancel(out_of_order.token), WorkClaimResolution::Restored); - let restored = ledger.claim(8).unwrap(); - assert_eq!(restored.pages.iter().map(|(page, _)| *page).collect::>(), [0x4000, 0x6000]); + /// A device of the test's own (a software one without a GPU). + unsafe fn test_device() -> ID3D12Device { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let mut dev: Option = None; + if std::env::var_os("XCL_TEST_WARP").is_some() || D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + dev.expect("D3D12 device") } - #[test] - fn replaced_sparse_batch_handles_reject_stale_additions() { - let batches = SparseBatches::new(17); - let stale_clone = batches.clone(); - let current = batches.replace_generation(18).unwrap(); - assert!(!batches.add_dirty_pages([0xC000])); - assert!(!stale_clone.add_retry_pages([0xD000])); - assert!(matches!(batches.seal(1, 1), Err(SparseBatchError::StaleGeneration))); - assert!(matches!(stale_clone.replace_generation(19), Err(SparseBatchError::StaleGeneration))); - assert!(current.add_dirty_pages([0xB000])); - assert_eq!(current.seal(1, 1).unwrap().unwrap().pages()[0].0, 0xB000); + /// Whether `dev` is a software device (WARP, or the Microsoft Basic Render Driver CI runs on, + /// which is the default adapter there and need not carry DXGI_ADAPTER_FLAG_SOFTWARE). + unsafe fn software(dev: &ID3D12Device) -> bool { + use windows::Win32::Graphics::Dxgi::*; + let Ok(factory) = CreateDXGIFactory1::() else { return false }; + let adapter: windows::core::Result = factory.EnumAdapterByLuid(dev.GetAdapterLuid()); + adapter.and_then(|a| a.GetDesc1()).is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 || (d.VendorId, d.DeviceId) == (0x1414, 0x8c)) } + /// The small ones of an upload's runs go up in dispatches: each lands where it belongs (far + /// into the window too, next to runs that go up with a copy), and what lies between them keeps + /// what the GPU has there. #[test] - fn sparse_batch_takeover_revokes_without_restoring_or_duplicating_work() { - let batches = SparseBatches::new(47); - assert!(batches.add_dirty_pages([0x1_1000])); - let old = batches.seal(1, 1).unwrap().unwrap(); - let through = batches.through().unwrap(); - assert_eq!(old.pages()[0].0, 0x1_1000); - - let replacement = old.take_over(2).unwrap(); - assert!(matches!( - old.obsolete(), - Err(SparseBatchError::Frontier(ClaimFrontierError::StaleToken)), - )); - assert_eq!(replacement.pages()[0].0, 0x1_1000); - replacement.accept().unwrap().receipt(5).unwrap(); - assert_eq!( - batches.observe(through, 9), - Ok(ClaimFrontierAction::Ready { through, required_fence: Some(5) }), - "the revoked owner restored or duplicated its work", - ); - assert!(batches.seal(3, 1).unwrap().is_none()); + fn small_runs_go_up_in_dispatches_and_leave_what_lies_between() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + const SIZE: usize = 3 << 30; + unsafe { + let dev = test_device(); + // (the software device makes a reserved buffer of 3 GiB and is removed by the first copies + // into it, 0x887a0020 – and a process has one device an adapter: every test after it failed) + if software(&dev) { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let mut reserved: Option = None; + if dev.CreateReservedResource(&buffer_desc(SIZE as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved).is_err() { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let window = reserved.expect("reserved buffer"); + let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert!(base != 0 && base % TILE == 0); + let mut s = new_state(&dev, vec![(base, window.clone())]).expect("state"); + // (the 1 GiB a dispatch reaches from its base ends between the third and the fourth) + let tiles = [base, base + TILE, base + (1 << 30) - TILE, base + (1 << 30), base + SIZE - TILE]; + let mut seed = 0x1234_5678_9ABC_DEF1u64; + let mut random = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for &t in &tiles { + assert!(!VirtualAlloc(t as *const c_void, TILE, MEM_COMMIT, PAGE_READWRITE).is_null()); + s.commit_range(t, TILE); + for i in 0..TILE / 8 { + *(t as *mut u64).add(i) = random(); + } + } + // all of it goes up, then the CPU writes all of it again and only some runs go up + let all: Vec<(usize, usize)> = tiles.iter().map(|&t| (t, TILE)).collect(); + s.upload_dirty(&all); + let on_gpu: Vec> = tiles.iter().map(|&t| std::slice::from_raw_parts(t as *const u8, TILE).to_vec()).collect(); + let mut runs: Vec<(usize, usize)> = Vec::new(); + for &t in &tiles { + for i in 0..TILE / 8 { + *(t as *mut u64).add(i) = random(); + } + let mut o = 0; + loop { + o += CHUNK * (1 + random() as usize % 9); + let n = if random() % 23 == 0 { SCATTER_RUN + CHUNK * (random() as usize % 40) } else { CHUNK * (1 + random() as usize % 12) }; + if o + n > TILE { + break; + } + runs.push((t + o, n)); + o += n; + } + } + let small = runs.iter().filter(|r| r.1 < SCATTER_RUN).count() as u64; + let counts = || (SCATTERED[0].load(Ordering::Relaxed), SCATTERED[1].load(Ordering::Relaxed)); + let before = counts(); + s.upload_dirty(&runs); + let after = counts(); + assert!(small > 300 && runs.len() as u64 > small, "{small} small runs of {}", runs.len()); + assert!(after.0 - before.0 >= 3 && after.1 - before.1 >= small, "{} dispatches of {} runs", after.0 - before.0, after.1 - before.1); + + let mut d = buffer_desc((tiles.len() * TILE) as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + let mut back: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut back).expect("readback buffer"); + let back = back.expect("readback buffer"); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list"); + for (k, &t) in tiles.iter().enumerate() { + list.CopyBufferRegion(&back, (k * TILE) as u64, &window, (t - base) as u64, TILE as u64); + } + list.Close().expect("Close"); + s.queue.ExecuteCommandLists(&[Some(list.cast().expect("list"))]); + s.signal(); + s.wait_for(s.value); + let mut p = std::ptr::null_mut(); + back.Map(0, None, Some(&mut p)).expect("Map"); + for (k, &t) in tiles.iter().enumerate() { + let mut want = on_gpu[k].clone(); + for &(a, n) in runs.iter().filter(|r| r.0 >= t && r.0 < t + TILE) { + want[a - t..a - t + n].copy_from_slice(std::slice::from_raw_parts(a as *const u8, n)); + } + let got = std::slice::from_raw_parts((p as *const u8).add(k * TILE), TILE); + let wrong = (0..TILE / CHUNK).filter(|c| got[c * CHUNK..][..CHUNK] != want[c * CHUNK..][..CHUNK]).collect::>(); + assert!(wrong.is_empty(), "tile {k}: chunks {:?}… of {} are not what they should be", &wrong[..wrong.len().min(8)], TILE / CHUNK); + } + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } } + /// A copy back after a title submission does not wait for the title's queue: that queue can + /// be waiting for work the title submits next, from the thread that is in here. The copy + /// lands once the title's work is done (`drain_readbacks`). Before, the sparse queue + /// GPU-waited for the title's queue and this thread waited for the copy (5 s, then on). #[test] - fn dropped_pending_batch_remains_visible_for_foreground_takeover() { - let batches = SparseBatches::new(53); - assert!(batches.add_dirty_pages([0x2_1000])); - let abandoned = batches.seal(10, 1).unwrap().unwrap(); - let token = abandoned.token; - let through = batches.through().unwrap(); - drop(abandoned); - assert_eq!(batches.observe(through, 20), Ok(ClaimFrontierAction::TakeOver(token))); + fn a_copy_back_does_not_wait_for_the_title_queue() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.expect("D3D12 device"); + let base = VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert!(base != 0 && base % TILE == 0); + assert!(!VirtualAlloc(base as *const c_void, TILE, MEM_COMMIT, PAGE_READWRITE).is_null()); + let mut reserved: Option = None; + dev.CreateReservedResource(&buffer_desc(TILE as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved).expect("CreateReservedResource"); + let reserved = reserved.expect("reserved buffer"); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); + let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("rb_alloc"); + let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); + rb_list.Close().expect("rb_list close"); + let rbq_queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("readback queue"); + let rbq_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("readback fence"); - let foreground = batches.take_over(token, 20).unwrap(); - foreground.accept().unwrap().receipt(7).unwrap(); - assert_eq!( - batches.observe(through, 20), - Ok(ClaimFrontierAction::Ready { through, required_fence: Some(7) }), - ); + let rb_readbacks = Arc::new(SharedReadbacks::new(rb_fence.clone(), Some(rbq_fence.clone()))); + let rb_submit = Arc::new(Mutex::new(RbSubmit::new(dev.clone()))); + let mut s = State { + generation: 1, + mapping_epoch: 0, + coordination: SparseCoordination::new(1, 1).unwrap(), + dev: dev.clone(), + queue, + fence, + value: 0, + event, + rb_fence, + rb_value: 0, + rbq: Some((rbq_queue, rbq_fence)), + rbq_value: 0, + readbacks: rb_readbacks, + rb_submit, + windows: vec![(base, reserved.clone())], + pools: Vec::new(), + free: FreePools::new(), + cooling: VecDeque::new(), + retired: Vec::new(), + retire_tried: std::time::Instant::now(), + mapped: FxHashMap::default(), + pinned: FxHashMap::default(), + parked: FxHashMap::default(), + kept: FxHashMap::default(), + pending: Vec::new(), + quarantined: VecDeque::new(), + queue_fences: FxHashMap::default(), + buffers: FxHashMap::default(), + to_zero: BTreeSet::new(), + staging: None, + ring_write: 0, + ring_submitted: 0, + ring_free: 0, + inflight: VecDeque::new(), + uploads_ordered: true, + zero_buf: None, + slots: Vec::new(), + next_slot: 0, + readback: None, + rb_alloc, + rb_list, + rb_last_fence: 0, + waited: FxHashMap::default(), + runs: BTreeMap::new(), + scratch_runs: Vec::new(), + own_pages: Vec::new(), + mirrors: FxHashMap::default(), + mirror_src: FxHashMap::default(), + src_runs: BTreeMap::new(), + sources: &SOURCES, + fill: Vec::new(), + asks: Vec::new(), + remaps: Vec::new(), + later: VecDeque::new(), + fill_pages: fill_pages(), + mirrored: 0, + mirror_cap: mirror_cap(), + refused: FxHashSet::default(), + no_memory: None, + starved: Vec::new(), + counts: MirrorCounts::default(), + diag: ViewDiag::default(), + poison: None, + retry_pages: Vec::new(), + }; + s.commit_range(base, TILE); + assert!(s.mapped.contains_key(&base)); + // (as before the title's submit) + s.flush_pending(); + std::ptr::write_bytes(base as *mut u8, 0, 256); + + // the title's queue: blocked on a fence nothing has signalled yet, then a copy of + // 0..64 into the tile (a GPU write the title's next CPU read expects) + let title: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate"); + let mut up: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &{ let mut d = buffer_desc(256); d.Flags = D3D12_RESOURCE_FLAG_NONE; d }, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut up) + .expect("upload buffer"); + let up = up.expect("upload buffer"); + let mut p: *mut c_void = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).expect("Map"); + for i in 0..64u32 { + *(p as *mut u32).add(i as usize) = 0xC0DE_0000 | i; + } + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list"); + list.CopyBufferRegion(&reserved, 0, &up, 0, 256); + list.Close().expect("close"); + title.Wait(&s.fence, s.value).expect("wait for the tile mapping"); + title.Wait(&gate, 1).expect("wait for the gate"); + title.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + + let t0 = std::time::Instant::now(); + s.after_execute(&title, &[(base, 256)], &[]); + let took = t0.elapsed(); + assert!(took < std::time::Duration::from_secs(1), "the copy back waited {took:?} for the title's queue"); + s.drain_readbacks(Drain::Finished); + assert_eq!(*(base as *const u32), 0, "nothing lands before the title's work is done"); + + // the title's queue goes on: the copy back lands once it is done + gate.Signal(1).expect("gate signal"); + // as the title would: wait for its own work (here the fences its queue signals: the + // first once its lists are done, the second once the copy behind them is) + let t = std::time::Instant::now(); + loop { + s.drain_readbacks(Drain::TitleDone); + if *(base as *const u32) == 0xC0DE_0000 { + break; + } + assert!(t.elapsed() < std::time::Duration::from_secs(5), "the copy back did not land"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + for i in 0..64u32 { + assert_eq!(*(base as *const u32).add(i as usize), 0xC0DE_0000 | i, "dword {i} after the copy back"); + } + assert!(s.readbacks.lock().unwrap().rb_jobs.is_empty(), "the copy back was consumed"); + assert_eq!(s.readbacks.lock().unwrap().rb_pool.len(), 1, "its buffer is kept for the next one"); + drop(s); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } } #[test] - fn sparse_batch_producers_are_collected_before_locking() { - use std::sync::atomic::{AtomicBool, Ordering}; - let batches = SparseBatches::new(57); - let unlocked = AtomicBool::new(false); - let ledger = batches.ledger.clone(); - let pages = std::iter::once_with(|| { unlocked.store(ledger.try_lock().is_ok(), Ordering::Relaxed); 0x2_2001 }); - assert!(batches.add_dirty_pages(pages)); - assert!(unlocked.load(Ordering::Relaxed), "a producer iterator ran under the batch lock"); - assert_eq!(batches.seal(1, 1).unwrap().unwrap().pages()[0].0, 0x2_2000); + fn activity_look_line_splits_foreground_costs() { + let line = look_line([ + 830_000, + 120_000, + 610_000, + 4_800, + 240, + 240 * 1_641 << 20, + 240 * 69, + 10_000, + 30_000, + 40_000, + 40_000, + 90, + 96 << 20, + 20_000, + 5_000, + 105_000, + 3_000, + 70_000, + 12_000, + 7_000, + 13_000, + 24_000, + 8_000, + 1_200, + 1_190, + 1_000, + 2_000, + 3_000, + 4_000, + 5_000, + 6_000, + 237, + 3, + 240, + 8, + 2, + 1, + ], 2); + assert!(line.contains("240 looks did 830 ms active work (41.5 % of the time) after 120 ms waiting"), "{line}"); + assert!(line.contains("write-watch 610 ms (1641.0 MB in 69.0 ranges/look, 4800 pages written)"), "{line}"); + assert!(line.contains("texture select wait/hold 7/13 ms (24000 visited, 8000 dirty-tested, 1200 matched, 1190 retained)"), "{line}"); + assert!(line.contains("sparse queue wait/fence+state/scan/upload/ownership wait 10/30/40/40/20 ms (90 runs, 96.0 MB zero/dirty bytes)"), "{line}"); + assert!(line.contains("VRAM gate/device/unmap poll/state/queue wait/retire 1/2/3/4/5/6 ms (240 calls, 237 device-cache hits, 3 GetDevice queries, 8 mapping waits, 2 reclaim passes, 1 retirement passes)"), "{line}"); + assert!(line.contains("upload gate submit wait/hold 5/105 ms, readback wait/hold/released wait+reacquire 3/70/12 ms; other active work 39 ms"), "{line}"); + let idle = look_line([0; LOOK_FIELDS], 2); + assert!(idle.contains("0 looks did 0 ms active work (0.0 % of the time) after 0 ms waiting"), "{idle}"); + assert!(idle.contains("0.0 MB in 0.0 ranges/look"), "{idle}"); } #[test] - fn sparse_batch_ready_requires_new_reasons_to_be_sealed() { - let batches = SparseBatches::new(59); - assert!(batches.add_dirty_pages([0x3_1000])); - let first = batches.seal(1, 1).unwrap().unwrap(); - let first_epoch = batches.through().unwrap(); - assert!(batches.add_dirty_pages([0x3_1001])); - assert_eq!(batches.through(), Err(SparseBatchError::Unsealed)); - assert_eq!(batches.observe(first_epoch, 2), Err(SparseBatchError::Unsealed)); + fn activity_look_counter_delta_survives_wrap() { + assert_eq!(look_delta([0; LOOK_FIELDS], [u64::MAX; LOOK_FIELDS]), [1; LOOK_FIELDS]); + } - first.accept().unwrap().receipt(8).unwrap(); - assert_eq!(batches.through(), Err(SparseBatchError::Unsealed)); - let successor = batches.seal(2, 1).unwrap().unwrap(); - let through = batches.through().unwrap(); - assert!(through > first_epoch); - successor.obsolete().unwrap(); - assert_eq!( - batches.observe(through, 2), - Ok(ClaimFrontierAction::Ready { through, required_fence: Some(8) }), + #[test] + fn texture_selection_metrics_keep_wait_hold_and_counts_distinct() { + let mut sample = LookSample::default(); + note_texture_selection( + &mut sample, + std::time::Duration::from_micros(7), + std::time::Duration::from_micros(13), + 101, + 79, + 11, + 10, ); + assert_eq!(sample.0[TEXTURE_SELECT_WAIT_US..=TEXTURES_RETAINED], [7, 13, 101, 79, 11, 10]); } #[test] - fn sparse_batch_receipts_are_contiguous_and_acceptance_is_fail_closed() { - let batches = SparseBatches::new(61); - assert!(batches.add_dirty_pages([0x4_1000, 0x4_2000])); - let first = batches.seal(1, 1).unwrap().unwrap(); - let second = batches.seal(2, 1).unwrap().unwrap(); - let through = batches.through().unwrap(); - let first_token = first.token; - let first = first.accept().unwrap(); - let second = second.accept().unwrap(); - second.receipt(11).unwrap(); - assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::WaitForReceipt(first_token))); - first.receipt(8).unwrap(); - assert_eq!( - batches.observe(through, 3), - Ok(ClaimFrontierAction::Ready { through, required_fence: Some(11) }), - ); - - assert!(batches.add_dirty_pages([0x4_3000])); - let accepted = batches.seal(4, 1).unwrap().unwrap().accept().unwrap(); - let accepted_token = accepted.token.unwrap().0; - assert!(matches!( - batches.take_over(accepted_token, 5), - Err(SparseBatchError::Frontier(ClaimFrontierError::WrongState)), - )); - drop(accepted); - assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); - - let current = batches.replace_generation(62).unwrap(); - assert_eq!(batches.through(), Err(SparseBatchError::StaleGeneration)); - assert!(matches!(current.replace_generation(61), Err(SparseBatchError::StaleGeneration))); - assert!(matches!(current.take_over(accepted_token, 6), Err(SparseBatchError::StaleGeneration))); - assert!(current.add_dirty_pages([0x5_1000])); - let stale = current.seal(6, 1).unwrap().unwrap(); - let replacement = current.replace_generation(63).unwrap(); - assert_eq!(stale.obsolete(), Err(SparseBatchError::StaleGeneration)); - assert_eq!(replacement.through(), Ok(0)); - assert!(matches!(SparseBatches::new(u64::MAX).replace_generation(0), Err(SparseBatchError::StaleGeneration))); - } - - #[test] - fn live_sparse_coordination_owns_one_exact_generation() { - let coordination = SparseCoordination::new(101, 501).unwrap(); - { - let batches = coordination.batches.ledger.lock().unwrap(); - assert_eq!(batches.work.state_generation, 101); - assert_eq!(batches.fence, Some(SparseFenceIdentity { state_generation: 101, allocation: 501 })); - } - assert_eq!(coordination.waits.fence(), SparseFenceIdentity { state_generation: 101, allocation: 501 }); - let reservation = coordination.reservations.reserve(0, RING_ALIGN).unwrap(); - assert_eq!(reservation.token.unwrap().state_generation, 101); - assert!(SparseCoordination::new(0, 501).is_none()); - assert!(SparseCoordination::new(101, 0).is_none()); + fn vram_metrics_keep_phases_and_counts_distinct() { + let mut sample = LookSample::default(); + note_vram_before_execute(&mut sample, super::super::vram::BeforeExecuteTiming { + gate_wait: std::time::Duration::from_micros(1), + device: std::time::Duration::from_micros(2), + unmap_poll: std::time::Duration::from_micros(3), + state: std::time::Duration::from_micros(4), + queue_wait: std::time::Duration::from_micros(5), + retirement: std::time::Duration::from_micros(6), + device_cache_hits: 7, + device_queries: 8, + calls: 9, + mapping_waits: 10, + reclaim_passes: 11, + retirement_passes: 12, + }); + assert_eq!(sample.0[VRAM_GATE_WAIT_US..=VRAM_RETIREMENT_PASSES], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + let line = look_line(sample.0, 2); + assert!(line.contains("9 calls, 7 device-cache hits, 8 GetDevice queries"), "{line}"); } #[test] - fn legacy_sparse_attempt_is_mirrored_and_retired_as_one_exact_batch() { - let coordination = SparseCoordination::new(103, 503).unwrap(); - let snapshot = coordination.clone(); - assert!(Arc::ptr_eq(&coordination.batches.ledger, &snapshot.batches.ledger)); - - let batch = snapshot.seal_legacy( - 0xA, - &[(0x3000, 2 * PAGE)], - &[0x3001, 0x1000], - &[(0x4000 + CHUNK, CHUNK)], - ).unwrap().unwrap(); - assert_eq!(batch.token.state_generation, 103); - assert_eq!( - batch.pages().iter().map(|(page, reasons)| (*page, reasons.0)).collect::>(), - [ - (0x1000, WorkReasons::RETRY.0), - (0x3000, WorkReasons::ZERO.0 | WorkReasons::RETRY.0), - (0x4000, WorkReasons::ZERO.0 | WorkReasons::DIRTY.0), - ], + fn upload_gate_times_accumulate_into_distinct_submit_and_readback_fields() { + let mut sample = [0; LOOK_FIELDS]; + add_gate_times( + &mut sample, + SUBMIT_GATE_WAIT_US, + SUBMIT_GATE_HOLD_US, + None, + UploadGateTimes { wait_us: 11, hold_us: 22, released_us: 33 }, ); - let through = snapshot.batches.through().unwrap(); - batch.obsolete().unwrap(); - assert_eq!( - coordination.batches.observe(through, 0xB), - Ok(ClaimFrontierAction::Ready { through, required_fence: None }), - "the parity batch remained visible after the legacy path retired it", + add_gate_times( + &mut sample, + READBACK_GATE_WAIT_US, + READBACK_GATE_HOLD_US, + Some(READBACK_GATE_RELEASED_US), + UploadGateTimes { wait_us: 44, hold_us: 55, released_us: 66 }, ); - assert!(coordination.batches.seal(0xB, usize::MAX).unwrap().is_none()); + assert_eq!(sample[SUBMIT_GATE_WAIT_US], 11); + assert_eq!(sample[SUBMIT_GATE_HOLD_US], 22); + assert_eq!(sample[READBACK_GATE_WAIT_US], 44); + assert_eq!(sample[READBACK_GATE_HOLD_US], 55); + assert_eq!(sample[READBACK_GATE_RELEASED_US], 66); } - fn wait_ready(fence: SparseFenceIdentity, through: u64, value: Option) -> SparseReadyReceipt { - SparseReadyReceipt { state_generation: fence.state_generation, fence, through, required_fence: value } + #[test] + fn retried_upload_ranges_are_counted_once() { + let mut zero = BTreeMap::new(); + let mut dirty = BTreeMap::new(); + remember_metric_runs(&mut zero, &[(0x1000, 0x1000)]); + remember_metric_runs(&mut zero, &[(0x1000, 0x1000)]); + remember_metric_runs(&mut dirty, &[(0x4000, 0x1000)]); + remember_metric_runs(&mut dirty, &[(0x4000, 0x2000)]); + let mut sample = LookSample::default(); + note_transfer_metrics(Some(&mut sample), Some(&(zero, dirty))); + assert_eq!(sample.0[RUNS], 2); + assert_eq!(sample.0[TRANSFER_BYTES], 0x3000); } - fn wait_reservation(decision: ForegroundWaitDecision) -> ForegroundWaitReservation { - match decision { ForegroundWaitDecision::Reserve(reservation) => reservation, _ => panic!("wait not reserved") } + #[test] + fn activity_look_publishes_one_complete_sample() { + let mut total = [10; LOOK_FIELDS]; + let sample = std::array::from_fn(|i| i as u64); + merge_look(&mut total, sample); + assert_eq!(total, std::array::from_fn(|i| 10 + i as u64)); + merge_look(&mut total, std::array::from_fn(|i| u64::MAX - 9 - i as u64)); + assert_eq!(total, [0; LOOK_FIELDS]); } #[test] - fn foreground_wait_pairs_out_of_order_frontier_with_exact_fence() { - let batches = SparseBatches::with_fence(101, 501).unwrap(); - assert!(batches.add_dirty_pages([0x6_1000, 0x6_2000])); - let first = batches.seal(1, 1).unwrap().unwrap(); - let first_token = first.token; - let second = batches.seal(2, 1).unwrap().unwrap(); - let through = batches.through().unwrap(); - let first = first.accept().unwrap(); - second.accept().unwrap().receipt(11).unwrap(); - let waits = ForegroundWaits::new(101, 501).unwrap(); - let queue = waits.register_queue(0xA).unwrap(); - assert_eq!(waits.register_queue(0xA), Ok(queue)); - assert_eq!(batches.ready_receipt(through, 3), Err(ForegroundWaitError::NotReady)); - assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::WaitForReceipt(first_token))); - first.receipt(8).unwrap(); - - let ready = batches.ready_receipt(through, 3).unwrap(); - let wrong = SparseReadyReceipt { fence: SparseFenceIdentity { allocation: 502, ..ready.fence }, ..ready }; - assert!(matches!(waits.reserve(queue, wrong), Err(ForegroundWaitError::Fence))); - let reservation = wait_reservation(waits.reserve(queue, ready).unwrap()); - assert_eq!(reservation.arm().unwrap().publish(), Ok((through, 11))); - assert!(matches!(waits.reserve(queue, ready), Ok(ForegroundWaitDecision::Installed { through: t, value: 11 }) if t == through)); - assert!(matches!(waits.reserve(queue, wait_ready(waits.fence(), through + 1, None)), - Ok(ForegroundWaitDecision::NoWait { through: t }) if t == through + 1)); + fn writable_record_requires_every_touched_page_and_tracks_protection() { + let mut mapped = FxHashMap::default(); + let (t0, t1) = (0x10_0000usize, 0x11_0000usize); + mapped.insert(t0, TileEntry::with_holes((0, 1), 0)); + mapped.insert(t1, TileEntry::with_holes((0, 2), 1 << 2)); - let other = SparseBatches::with_fence(101, 502).unwrap(); - let other_waits = ForegroundWaits::new(101, 502).unwrap(); - let other_queue = other_waits.register_queue(0xE).unwrap(); - assert!(matches!(other.ready_receipt(through, 3), Err(ForegroundWaitError::Batch(_)))); - assert!(matches!(other_waits.reserve(other_queue, ready), Err(ForegroundWaitError::Fence))); + assert!(recorded_committed(&mapped, t0, t0 + TILE)); + assert!(recorded_committed(&mapped, t0 + 0x800, t1 + 2 * PAGE)); + assert!(!recorded_committed(&mapped, t1 + 2 * PAGE, t1 + 2 * PAGE + 1)); + assert!(!recorded_committed(&mapped, t1 + TILE - 8, t1 + TILE + 8)); - assert!(matches!(batches.replace_generation_with_fence(102, 501), Err(SparseBatchError::Fence))); - let stale = batches.clone(); - let batches = batches.replace_generation_with_fence(102, 503).unwrap(); - assert_eq!(batches.ledger.lock().unwrap().fence.unwrap().allocation, 503); - assert_eq!(stale.ready_receipt(through, 3), Err(ForegroundWaitError::Batch(SparseBatchError::StaleGeneration))) + mark_protection(&mut mapped, t0 + 5 * PAGE + 16, 8, false); + assert!(!recorded_committed(&mapped, t0 + 5 * PAGE, t0 + 5 * PAGE + 1)); + assert!(recorded_committed(&mapped, t0 + 6 * PAGE, t0 + TILE)); + mark_protection(&mut mapped, t0 + 5 * PAGE, PAGE, true); + assert!(recorded_committed(&mapped, t0, t0 + TILE)); } #[test] - fn foreground_wait_rollbacks_are_exact_and_queue_reuse_is_stale() { - let waits = ForegroundWaits::new(103, 601).unwrap(); - let fence = waits.fence(); - let queue = waits.register_queue(0xB).unwrap(); - let ready = wait_ready(fence, 1, Some(5)); - let abandoned = wait_reservation(waits.reserve(queue, ready).unwrap()); - let stale = abandoned.token.unwrap(); - assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Pending(token)) if token == stale)); - assert!(matches!(waits.reserve(queue, wait_ready(fence, 0, None)), Err(ForegroundWaitError::Pending(_)))); - drop(abandoned); + fn early_protection_ranges_merge_split_and_commit_clears_them() { + let base = 0x20_0000usize; + let mut protected = BTreeMap::new(); + early_protection(&mut protected, base + PAGE + 16, 8, false); + early_protection(&mut protected, base + 3 * PAGE, 3 * PAGE, false); + early_protection(&mut protected, base + 5 * PAGE, PAGE, true); + assert_eq!(protected.into_iter().collect::>(), [(base + PAGE, base + 2 * PAGE), (base + 3 * PAGE, base + 5 * PAGE)]); - let accepted = wait_reservation(waits.reserve(queue, wait_ready(fence, 2, Some(6))).unwrap()).arm().unwrap(); - let accepted_token = accepted.token.unwrap(); - accepted.rollback().unwrap(); - let newer = wait_reservation(waits.reserve(queue, wait_ready(fence, 3, Some(7))).unwrap()); - assert_eq!(waits.0.lock().unwrap().transition(accepted_token, ForegroundWaitState::Accepted, None), - Err(ForegroundWaitError::StaleToken)); - assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Pending(token)) if token == newer.token.unwrap())); - drop(newer); - waits.retire_queue(queue).unwrap(); - let replacement = waits.register_queue(0xB).unwrap(); - assert!(replacement.generation > queue.generation); - assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Queue))); - assert!(matches!(waits.reserve(replacement, ready), Ok(ForegroundWaitDecision::Reserve(_)))); + let mut protected = BTreeMap::from([(base, base + 4 * PAGE)]); + early_remove(&mut protected, base + PAGE, base + 3 * PAGE); + assert_eq!(protected.into_iter().collect::>(), [(base, base + PAGE), (base + 3 * PAGE, base + 4 * PAGE)]); } #[test] - fn foreground_wait_unpublished_acceptance_fails_closed() { - let waits = ForegroundWaits::new(107, 701).unwrap(); - let queue = waits.register_queue(0xC).unwrap(); - let ready = wait_ready(waits.fence(), 1, Some(9)); - let accepted = wait_reservation(waits.reserve(queue, ready).unwrap()).arm().unwrap(); - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { - let _accepted = accepted; - panic!("after native wait acceptance"); - })); - assert!(result.is_err()); - assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Uncertain))); - assert!(matches!(waits.reserve(queue, wait_ready(waits.fence(), 0, None)), Err(ForegroundWaitError::Uncertain))); + fn working_set_check_rejects_resident_read_only_pages_without_touching_cold_pages() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE, PAGE_READONLY}; + unsafe { + let base = VirtualAlloc(std::ptr::null(), 3 * PAGE, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert_ne!(base, 0); + assert!(!VirtualAlloc(base as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + assert!(!VirtualAlloc((base + PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_READONLY).is_null()); + assert!(!VirtualAlloc((base + 2 * PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + std::ptr::write_volatile(base as *mut u8, 1); + assert_eq!(std::ptr::read_volatile((base + PAGE) as *const u8), 0); + assert!(resident_pages_writable(base, base + PAGE)); + assert!(!resident_pages_writable(base + PAGE, base + 2 * PAGE)); + assert!(resident_pages_writable(base + 2 * PAGE, base + 3 * PAGE)); + + let mut cold: windows_sys::Win32::System::ProcessStatus::PSAPI_WORKING_SET_EX_INFORMATION = std::mem::zeroed(); + cold.VirtualAddress = (base + 2 * PAGE) as *mut c_void; + assert_ne!( + windows_sys::Win32::System::ProcessStatus::K32QueryWorkingSetEx( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + &mut cold as *mut _ as *mut c_void, + std::mem::size_of_val(&cold) as u32, + ), + 0 + ); + assert_eq!(cold.VirtualAttributes.Flags & 1, 0, "the metadata query paged memory in"); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } } #[test] - fn foreground_wait_generation_replacement_rejects_old_guards_and_fences() { - let waits = ForegroundWaits::new(109, 801).unwrap(); - let queue = waits.register_queue(0xD).unwrap(); - let old_fence = waits.fence(); - let old_ready = wait_ready(old_fence, 1, Some(3)); - let old = wait_reservation(waits.reserve(queue, old_ready).unwrap()); - waits.replace_generation(109, 110, 802).unwrap(); - drop(old); - assert!(matches!(waits.reserve(queue, old_ready), Err(ForegroundWaitError::StaleGeneration))); - assert_eq!(waits.replace_generation(110, 109, 803), Err(ForegroundWaitError::StaleGeneration)); - assert_eq!(waits.replace_generation(110, 111, 801), Err(ForegroundWaitError::Fence)); - let current = wait_ready(waits.fence(), 1, Some(4)); - assert!(matches!(waits.reserve(queue, current), Ok(ForegroundWaitDecision::Reserve(_)))); + fn memory_counts_committed_pages_and_separates_devices_and_retired_pools() { + let holes = [0xFFFE, 0xFFF0].into_iter(); // one committed page, then four + let (pools, occupied, retired, committed) = memory_byte_counts(7, 7, 1, 60, 1, holes); + assert_eq!(pools, POOL_TILES as usize * TILE); + assert_eq!(occupied, 4 * TILE, "occupied video tiles are independent of CPU page commitment"); + assert_eq!(retired, POOL_TILES as usize * TILE, "the retired pool is not also active"); + assert_eq!(committed, 5 * PAGE, "holes in a 64 KiB tile do not consume CPU commit"); + assert_eq!(memory_byte_counts(8, 7, 1, 60, 1, [0].into_iter()), (0, 0, 0, 0)); } - fn upload_observation(page: usize, pool: (u32, u32), source_word: u64) -> UploadPageObservation { - let mut source = ZERO_HASHES; - source[1] = source_word; - source[2] = source_word; - UploadPageObservation { page, pool, hole: false, sent: Some(ZERO_HASHES), source } + /// `queue()` answers while the state's lock is held: a resource's last `Release` asks for + /// it (`late_release::drain_known`) from inside a D3D12 call that the lock's holder can be + /// waiting for (a list's `Reset` against an upload's allocator `Reset`, with `XCL_DRED=1`). + #[test] + fn the_queue_is_answered_while_the_state_is_locked() { + let held = STATE.lock().unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + let asked = std::thread::spawn(move || { + let _ = queue(); + let _ = tx.send(()); + }); + let answered = rx.recv_timeout(std::time::Duration::from_secs(5)).is_ok(); + drop(held); + asked.join().unwrap(); + assert!(answered, "queue() waited for the sparse state's lock"); } - fn coordinated_upload_fixture( - owner: u64, - ) -> (SparseBatches, CoordinatedSparseUploadPlan, UploadPageObservation, ClaimFrontierToken) { - let batches = SparseBatches::new(71); - assert!(batches.add_dirty_pages([0x2_1000])); - let lease = batches.seal(owner, 1).unwrap().unwrap(); - let token = lease.token; - let observation = upload_observation(0x2_1000, (4, 9), 0xA5); - let plan = CoordinatedSparseUploadPlan::build(lease, 71, 7, |_| Some(observation.clone())).unwrap(); - (batches, plan, observation, token) + /// A submit gets the lock soon although another thread takes it again and again for 0.2 ms each. + #[test] + fn a_submit_is_let_in_before_the_commits() { + use std::sync::atomic::AtomicUsize; + let (m, waiting, stop) = (Mutex::new(0u64), AtomicUsize::new(0), AtomicBool::new(false)); + std::thread::scope(|s| { + s.spawn(|| { + while !stop.load(Ordering::Acquire) { + let mut g = lock_in_turn(&m, &waiting); + *g += 1; + let t = std::time::Instant::now(); + while t.elapsed().as_micros() < 200 { + std::hint::spin_loop(); + } + } + }); + while *m.lock().unwrap() == 0 { + std::thread::yield_now(); + } + let mut turns: Vec = Vec::new(); + for _ in 0..20 { + let before = *lock_first(&m, &waiting); + std::thread::sleep(std::time::Duration::from_millis(2)); + let after = *lock_first(&m, &waiting); + // (the turns the other thread had while this one slept and waited) + turns.push(after - before); + } + stop.store(true, Ordering::Release); + turns.sort_unstable(); + // 2 ms of sleep are 10 turns; without the rule a waiting thread stood behind hundreds + assert!(turns[10] < 60, "the other thread's turns before a submit had the lock: {turns:?}"); + }); + assert_eq!(waiting.load(Ordering::Acquire), 0); } - fn commit_coordinated( - plan: CoordinatedSparseUploadPlan, observation: &UploadPageObservation, - reservations: &UploadReservations, slot: usize, fence: u64, - ) -> Result> { - plan.commit_reserved( - 71, 7, |_| Some(observation.clone()), reservations, slot, 64, - |_, _| Ok(vec![0; 64]), |_, _| Ok(()), |_, _| {}, || Ok(fence), - ) + /// A thread that only tries the lock (a fence look settling copies back) does not take it while + /// a submit waits for it, when it gives way; without that it takes it at once. Its time giving + /// way does not count against its budget, but it does not give way for ever. + #[test] + fn a_thread_that_tries_the_lock_gives_way_to_a_waiting_submit() { + use std::sync::atomic::AtomicUsize; + use std::time::Duration; + let (m, waiting) = (Mutex::new(()), AtomicUsize::new(0)); + // nobody waits: had at once either way + assert!(try_lock_giving_way(&m, &waiting, Duration::from_millis(5), true).is_some()); + assert!(try_lock_giving_way(&m, &waiting, Duration::from_millis(5), false).is_some()); + // a submit waits for 8 ms: the lock, free all along, is not taken in the first 5 ms + waiting.store(1, Ordering::Release); + let t0 = std::time::Instant::now(); + let got = std::thread::scope(|s| { + s.spawn(|| { + std::thread::sleep(Duration::from_millis(8)); + waiting.store(0, Ordering::Release); + }); + try_lock_giving_way(&m, &waiting, Duration::from_millis(5), true).is_some() + }); + let took = t0.elapsed(); + assert!(got, "the lock was free once the submit was done"); + assert!(took >= Duration::from_millis(5), "taken after {took:?}, while the submit waited"); + // a submit that never stops waiting: it is given way to for the budget, then tried + waiting.store(1, Ordering::Release); + let t0 = std::time::Instant::now(); + assert!(try_lock_giving_way(&m, &waiting, Duration::from_millis(3), true).is_some()); + assert!(t0.elapsed() >= Duration::from_millis(3)); + assert!(try_lock_giving_way(&m, &waiting, Duration::from_millis(3), false).is_some()); + // held by another thread: given up after the budget (and the time given way) + let held = m.lock().unwrap(); + let t0 = std::time::Instant::now(); + let got = std::thread::scope(|s| s.spawn(|| try_lock_giving_way(&m, &waiting, Duration::from_millis(3), true).is_some()).join().unwrap()); + assert!(!got); + assert!(t0.elapsed() >= Duration::from_millis(6), "gave up after {:?}", t0.elapsed()); + drop(held); } + /// A mapping put off does not wait for the title's next submit: a CPU signal sends it, and + /// without one it goes a few milliseconds after the commit (work the title submitted before + /// may reach the memory once a value the CPU writes lets it run). #[test] - fn shared_upload_page_builder_preserves_intent_order_and_dirty_ranges() { - let claimed = [ - (0x1_1000, WorkReasons(WorkReasons::ZERO.0 | WorkReasons::DIRTY.0)), - (0x1_2000, WorkReasons::RETRY), - ]; - let first = upload_observation(0x1_1000, (2, 3), 0x91); - let second = upload_observation(0x1_2000, (2, 3), ZERO_HASH); - let pages = build_upload_pages(&claimed, |page| match page { - 0x1_1000 => Some(first.clone()), - 0x1_2000 => Some(second.clone()), - _ => None, - }).unwrap(); + fn a_mapping_put_off_is_sent_without_a_submit() { + if super::super::backend() != super::super::Backend::Real { + return; + } + unsafe { + let _ = super::super::real::device_raw(); + // (a device without sparse windows: commits wait for one, nothing is put off) + if STATE.lock().unwrap().is_none() { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let Some((at, len)) = alloc(64 * TILE, TILE) else { return }; + let put_off = || STATE.lock().unwrap().as_ref().is_some_and(|s| s.pending.iter().any(|t| (at..at + len).contains(t))); + let mapped = || STATE.lock().unwrap().as_ref().is_some_and(|s| (at..at + len).step_by(TILE).all(|t| s.mapped.contains_key(&t))); + send_pending(); + assert!(mapped() && !put_off(), "a CPU signal sends what is put off"); + decommitted(at, len); + VirtualFree(at as *mut c_void, len, MEM_DECOMMIT); + // (as a submit does: the tiles unmapped, so the next commit needs mappings again) + if let Some(s) = STATE.lock().unwrap().as_mut() { + s.flush_parked(); + } + assert!(!VirtualAlloc(at as *const c_void, len, MEM_COMMIT, PAGE_READWRITE).is_null()); + committed(at, len); + let t0 = std::time::Instant::now(); + while put_off() { + assert!(t0.elapsed().as_secs() < 5, "nothing sent the mappings"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(mapped()); + assert!(free(at)); + } + } - assert_eq!(pages.iter().map(|page| page.page).collect::>(), [0x1_1000, 0x1_2000]); - assert!(pages[0].zero && pages[0].dirty); - assert_eq!(pages[0].dirty_ranges, [(0x1_1000 + CHUNK, 2 * CHUNK)]); - assert!(!pages[1].zero && pages[1].dirty); - assert!(pages[1].dirty_ranges.is_empty(), "retry intent was lost when no chunks changed"); - assert!(build_upload_pages(&claimed, |page| { - (page == 0x1_1000).then(|| first.clone()) - }).is_none()); + #[test] + fn exact_retirement_forgets_cache_but_inflight_batch_keeps_its_fence() { + use std::sync::Arc; + let old = Arc::new(7u32); + let mut fences = FxHashMap::default(); + fences.insert(0xA, (old.clone(), 3)); + let batch_mark = fences[&0xA].0.clone(); + + assert!(fences.contains_key(&0xA), "marker failure must leave the cache pinned"); + let gone = remove_queue_fence(&mut fences, 0xA).expect("exact retirement callback"); + assert!(fences.is_empty() && Arc::ptr_eq(&gone.0, &batch_mark)); + drop(gone); + drop(old); + assert_eq!(Arc::strong_count(&batch_mark), 1, "cache removal invalidated an in-flight batch mark"); + + let replacement = Arc::new(9u32); + fences.insert(0xA, (replacement.clone(), 1)); + assert!(!Arc::ptr_eq(&batch_mark, &fences[&0xA].0), "reused raw address kept the retired generation's fence"); } #[test] - fn coordinated_plan_revalidates_every_sparse_page_identity() { - let (_, plan, observation, _) = coordinated_upload_fixture(1); - assert_eq!(plan.validate(72, 7, |_| Some(observation.clone())), Err(UploadPlanInvalid::StateGeneration)); - assert_eq!(plan.validate(71, 8, |_| Some(observation.clone())), Err(UploadPlanInvalid::MappingEpoch)); - assert_eq!(plan.validate(71, 7, |_| None), Err(UploadPlanInvalid::MissingPage)); + fn retirement_fence_poll_is_unlocked_and_new_requirements_fail_closed() { + use std::sync::{atomic::{AtomicU64, AtomicUsize, Ordering}, Arc}; + let first = Arc::new(AtomicU64::new(1)); + let late = Arc::new(AtomicU64::new(9)); + let state = Mutex::new(vec![first.clone(), first.clone()]); + let polls = AtomicUsize::new(0); - let mut remapped = observation.clone(); - remapped.page += TILE; - assert_eq!(plan.validate(71, 7, |_| Some(remapped.clone())), Err(UploadPlanInvalid::Mapping)); - let mut repooled = observation.clone(); - repooled.pool.1 += 1; - assert_eq!(plan.validate(71, 7, |_| Some(repooled.clone())), Err(UploadPlanInvalid::Mapping)); - let mut hole = observation.clone(); - hole.hole = true; - assert_eq!(plan.validate(71, 7, |_| Some(hole.clone())), Err(UploadPlanInvalid::Mapping)); - let mut resent = observation.clone(); - resent.sent.as_mut().unwrap()[3] ^= 1; - assert_eq!(plan.validate(71, 7, |_| Some(resent.clone())), Err(UploadPlanInvalid::SentHashes)); - let mut rewritten = observation.clone(); - rewritten.source[3] ^= 1; - assert_eq!(plan.validate(71, 7, |_| Some(rewritten.clone())), Err(UploadPlanInvalid::SourceHashes)); + let snapshot = state.lock().unwrap().clone(); + let observed = poll_unique(snapshot, |fence| Arc::as_ptr(fence) as usize, |fence| { + assert!(state.try_lock().is_ok(), "completion polling held sparse state"); + state.lock().unwrap().push(late.clone()); + polls.fetch_add(1, Ordering::Relaxed); + fence.load(Ordering::Relaxed) + }); + + assert_eq!(polls.load(Ordering::Relaxed), 1, "the same fence is queried once"); + assert_eq!(observed_completion(&observed, &first, Arc::ptr_eq), 1); + assert!(observed_completion(&observed, &first, Arc::ptr_eq) < 2, "a higher mark added during polling remains held"); + assert_eq!(observed_completion(&observed, &late, Arc::ptr_eq), 0, "a newly added fence remains held"); } #[test] - fn live_parity_snapshot_revalidates_concurrent_changes_and_retries() { - let batches = SparseBatches::new(73); - assert!(batches.add_dirty_pages([0x2_3000])); - let lease = batches.seal(3, 1).unwrap().unwrap(); - let token = lease.token; - let through = batches.through().unwrap(); - let observed = upload_observation(0x2_3000, (6, 11), 0xB7); - let mut captures = 0; - let snapshot = UploadPlanningSnapshot::capture(73, 9, lease.pages(), |_| { - captures += 1; - Some(observed.clone()) - }).unwrap(); - assert_eq!(captures, 1); + fn title_queue_wait_reservation_is_monotonic_and_per_queue() { + let mut waited = FxHashMap::default(); + assert!(!reserve_queue_wait(&mut waited, 1, 0)); + assert!(reserve_queue_wait(&mut waited, 1, 4)); + assert!(!reserve_queue_wait(&mut waited, 1, 4)); + assert!(!reserve_queue_wait(&mut waited, 1, 3)); + assert!(reserve_queue_wait(&mut waited, 2, 3)); + assert!(reserve_queue_wait(&mut waited, 1, 5)); + assert_eq!(waited, FxHashMap::from_iter([(1, 5), (2, 3)])); + } - // Construction consumes only the owned snapshot; no live State observation is available - // while this work runs outside its lock. - let plan = CoordinatedSparseUploadPlan::from_snapshot(lease, snapshot).unwrap(); - assert_eq!(plan.pages[0].source, observed.source); - assert_eq!(plan.validate(74, 9, |_| Some(observed.clone())), Err(UploadPlanInvalid::StateGeneration)); - assert_eq!(plan.validate(73, 10, |_| Some(observed.clone())), Err(UploadPlanInvalid::MappingEpoch)); - let mut rewritten = observed.clone(); - rewritten.source[5] ^= 1; - assert_eq!(plan.validate(73, 9, |_| Some(rewritten.clone())), Err(UploadPlanInvalid::SourceHashes)); - assert_eq!(plan.validate(73, 9, |_| Some(observed.clone())), Ok(())); + #[test] + fn failed_write_watch_pages_survive_until_a_ready_retry() { + let runs = [(0x1040, PAGE), (0x2000, CHUNK)]; + assert_eq!(retry_journal(PreparationOutcome::RetryRequired, vec![], &runs), [0x1000, 0x2000]); + assert!(retry_journal(PreparationOutcome::Ready, vec![], &runs).is_empty()); + assert_eq!(retry_journal(PreparationOutcome::ExecutedUntracked, vec![0x3000], &runs), [0x1000, 0x2000, 0x3000]); + } - let parity = LegacyParityUpload::Planned(plan); + #[test] + fn late_claim_completion_cannot_change_a_newer_owner() { + let mut ledger = WorkClaimLedger::new(11); + ledger.add_dirty_pages([0x8000]); + let old = ledger.claim(1).unwrap(); + assert_eq!(ledger.commit(old.token), WorkClaimResolution::Committed); + + ledger.add_retry_pages([0x8000]); + let newer = ledger.claim(1).unwrap(); + assert_eq!(ledger.restore(old.token), WorkClaimResolution::AlreadyFinished); + assert_eq!(ledger.owners.get(&0x8000), Some(&newer.token.serial)); + assert_eq!(ledger.commit(newer.token), WorkClaimResolution::Committed); + assert!(ledger.available.is_empty()); + } + + #[test] + fn foreground_queue_cannot_pass_or_steal_an_unreceipted_claim() { + let mut frontier = ClaimFrontier::new(23); + let planner = frontier.claim(100).unwrap(); assert_eq!( - parity.revalidate(74, 9, |_| Some(observed.clone())), - LegacyParityRevalidation::RestartForGeneration, + frontier.observe(23, planner.epoch, 200), + Ok(ClaimFrontierAction::TakeOver(planner)), + "another queue mistook pending planner work for an empty frontier", ); + + let helper = frontier.take_over(planner, 200).unwrap(); + assert_eq!(frontier.accept(planner), Err(ClaimFrontierError::StaleToken)); + assert_eq!(frontier.receipt(planner, 7), Err(ClaimFrontierError::StaleToken)); + assert_eq!(frontier.consume_obsolete(planner), Err(ClaimFrontierError::StaleToken)); + assert_eq!(frontier.take_over(planner, 300), Err(ClaimFrontierError::StaleToken)); + assert_eq!(frontier.observe(23, helper.epoch, 200), Ok(ClaimFrontierAction::Progress(helper))); + + frontier.accept(helper).unwrap(); + assert_eq!(frontier.take_over(helper, 100), Err(ClaimFrontierError::WrongState)); + assert_eq!(frontier.consume_obsolete(helper), Err(ClaimFrontierError::WrongState)); assert_eq!( - parity.revalidate(73, 10, |_| Some(observed.clone())), - LegacyParityRevalidation::RetryCurrentGeneration, + frontier.observe(23, helper.epoch, 100), + Ok(ClaimFrontierAction::WaitForReceipt(helper)), + "accepted GPU work was exposed for retry", ); + frontier.receipt(helper, 7).unwrap(); assert_eq!( - parity.revalidate(73, 9, |_| Some(rewritten.clone())), - LegacyParityRevalidation::RetryCurrentGeneration, + frontier.observe(23, helper.epoch, 100), + Ok(ClaimFrontierAction::Ready { through: helper.epoch, required_fence: Some(7) }), ); + } + + #[test] + fn receipts_and_obsolete_holes_advance_only_a_contiguous_frontier() { + let mut frontier = ClaimFrontier::new(29); + let first = frontier.claim(1).unwrap(); + let second = frontier.claim(2).unwrap(); + let hole = frontier.claim(3).unwrap(); + frontier.accept(first).unwrap(); + frontier.accept(second).unwrap(); + frontier.receipt(second, 11).unwrap(); + frontier.consume_obsolete(hole).unwrap(); + + assert_eq!(frontier.retired_through, 0, "out-of-order terminal work crossed the first claim"); assert_eq!( - parity.revalidate(73, 9, |_| Some(observed.clone())), - LegacyParityRevalidation::Ready, + frontier.observe(29, hole.epoch, 9), + Ok(ClaimFrontierAction::WaitForReceipt(first)), ); + frontier.receipt(first, 8).unwrap(); + assert_eq!(frontier.retired_through, hole.epoch, "an obsolete hole left the frontier stuck"); assert_eq!( - batches.observe(through, 4), - Ok(ClaimFrontierAction::TakeOver(token)), - "validation must not accept or publish the behavior-neutral parity lease", + frontier.observe(29, hole.epoch, 9), + Ok(ClaimFrontierAction::Ready { through: hole.epoch, required_fence: Some(11) }), ); - parity.retry().unwrap(); - let restored = batches.seal(4, 1).unwrap().expect( - "a stale unlocked plan did not restore its exact work for retry", + assert_eq!( + frontier.observe(29, first.epoch, 9), + Ok(ClaimFrontierAction::Ready { through: first.epoch, required_fence: Some(8) }), + "an older observer unnecessarily inherited a newer fence", ); - assert_eq!(restored.pages(), &[(0x2_3000, WorkReasons::DIRTY)]); - let fallback = LegacyParityUpload::Lease { - lease: restored, - state_generation: 73, - mapping_epoch: 9, - }; + } + + #[test] + fn frontier_rejects_wrong_generations_unknown_epochs_and_invalid_receipts() { + let mut frontier = ClaimFrontier::new(31); + let token = frontier.claim(4).unwrap(); + assert_eq!(frontier.observe(30, token.epoch, 4), Err(ClaimFrontierError::StaleGeneration)); + assert_eq!(frontier.observe(31, token.epoch + 1, 4), Err(ClaimFrontierError::UnknownEpoch)); + assert_eq!(frontier.receipt(token, 1), Err(ClaimFrontierError::WrongState)); + frontier.accept(token).unwrap(); + assert_eq!(frontier.receipt(token, 0), Err(ClaimFrontierError::Fence)); + assert_eq!(frontier.observe(31, 0, 4), Ok(ClaimFrontierAction::Ready { through: 0, required_fence: None })); + + let stale_generation = ClaimFrontierToken { state_generation: 32, ..token }; + assert_eq!(frontier.receipt(stale_generation, 1), Err(ClaimFrontierError::StaleGeneration)); + } + + #[test] + fn frontier_epoch_and_lease_overflow_fail_without_partial_publication() { + let mut epoch = ClaimFrontier::new(37); + epoch.next_epoch = u64::MAX; + assert_eq!(epoch.claim(1), Err(ClaimFrontierError::Exhausted)); + assert!(epoch.records.is_empty()); + + let mut lease = ClaimFrontier::new(41); + lease.next_lease = u64::MAX; + assert_eq!(lease.claim(1), Err(ClaimFrontierError::Exhausted)); + assert_eq!(lease.next_epoch, 0); + assert!(lease.records.is_empty()); + + let mut takeover = ClaimFrontier::new(43); + let token = takeover.claim(1).unwrap(); + takeover.next_lease = u64::MAX; + assert_eq!(takeover.take_over(token, 2), Err(ClaimFrontierError::Exhausted)); + assert_eq!(takeover.observe(43, token.epoch, 1), Ok(ClaimFrontierAction::Progress(token))); + } + + #[test] + fn work_claim_ledger_merges_orders_and_restores_exact_out_of_order_work() { + let mut ledger = WorkClaimLedger::new(7); + ledger.add_zero_ranges(&[(0x3000, 2 * PAGE)]); + ledger.add_retry_pages([0x3001, 0x1000, 0x1000]); + ledger.add_dirty_pages([0x4000, 0x6001, 0x6000]); + + let first = ledger.claim(2).unwrap(); + assert_eq!(first.pages.iter().map(|(page, reasons)| (*page, reasons.0)).collect::>(), [ + (0x1000, WorkReasons::RETRY.0), + (0x3000, WorkReasons::ZERO.0 | WorkReasons::RETRY.0), + ]); + let second = ledger.claim(8).unwrap(); + assert_eq!(second.pages.iter().map(|(page, reasons)| (*page, reasons.0)).collect::>(), [ + (0x4000, WorkReasons::ZERO.0 | WorkReasons::DIRTY.0), + (0x6000, WorkReasons::DIRTY.0), + ]); + + ledger.add_dirty_pages([0x1000]); + assert!(ledger.claim(1).is_none(), "new work escaped an older owner of the same page"); + assert_eq!(ledger.cancel(second.token), WorkClaimResolution::Restored); + let out_of_order = ledger.claim(1).unwrap(); + assert_eq!(out_of_order.pages[0].0, 0x4000); + assert_eq!(ledger.commit(first.token), WorkClaimResolution::Committed); + let later = ledger.claim(1).unwrap(); + assert_eq!(later.pages, [(0x1000, WorkReasons::DIRTY)]); + assert_eq!(ledger.commit(later.token), WorkClaimResolution::Committed); + assert_eq!(ledger.cancel(out_of_order.token), WorkClaimResolution::Restored); + let restored = ledger.claim(8).unwrap(); + assert_eq!(restored.pages.iter().map(|(page, _)| *page).collect::>(), [0x4000, 0x6000]); + } + + #[test] + fn replaced_sparse_batch_handles_reject_stale_additions() { + let batches = SparseBatches::new(17); + let stale_clone = batches.clone(); + let current = batches.replace_generation(18).unwrap(); + assert!(!batches.add_dirty_pages([0xC000])); + assert!(!stale_clone.add_retry_pages([0xD000])); + assert!(matches!(batches.seal(1, 1), Err(SparseBatchError::StaleGeneration))); + assert!(matches!(stale_clone.replace_generation(19), Err(SparseBatchError::StaleGeneration))); + assert!(current.add_dirty_pages([0xB000])); + assert_eq!(current.seal(1, 1).unwrap().unwrap().pages()[0].0, 0xB000); + } + + #[test] + fn sparse_batch_takeover_revokes_without_restoring_or_duplicating_work() { + let batches = SparseBatches::new(47); + assert!(batches.add_dirty_pages([0x1_1000])); + let old = batches.seal(1, 1).unwrap().unwrap(); + let through = batches.through().unwrap(); + assert_eq!(old.pages()[0].0, 0x1_1000); + + let replacement = old.take_over(2).unwrap(); + assert!(matches!( + old.obsolete(), + Err(SparseBatchError::Frontier(ClaimFrontierError::StaleToken)), + )); + assert_eq!(replacement.pages()[0].0, 0x1_1000); + replacement.accept().unwrap().receipt(5).unwrap(); assert_eq!( - fallback.revalidate(74, 9, |_| None), - LegacyParityRevalidation::RestartForGeneration, + batches.observe(through, 9), + Ok(ClaimFrontierAction::Ready { through, required_fence: Some(5) }), + "the revoked owner restored or duplicated its work", + ); + assert!(batches.seal(3, 1).unwrap().is_none()); + } + + #[test] + fn dropped_pending_batch_remains_visible_for_foreground_takeover() { + let batches = SparseBatches::new(53); + assert!(batches.add_dirty_pages([0x2_1000])); + let abandoned = batches.seal(10, 1).unwrap().unwrap(); + let token = abandoned.token; + let through = batches.through().unwrap(); + drop(abandoned); + assert_eq!(batches.observe(through, 20), Ok(ClaimFrontierAction::TakeOver(token))); + + let foreground = batches.take_over(token, 20).unwrap(); + foreground.accept().unwrap().receipt(7).unwrap(); + assert_eq!( + batches.observe(through, 20), + Ok(ClaimFrontierAction::Ready { through, required_fence: Some(7) }), ); + } + + #[test] + fn sparse_batch_producers_are_collected_before_locking() { + use std::sync::atomic::{AtomicBool, Ordering}; + let batches = SparseBatches::new(57); + let unlocked = AtomicBool::new(false); + let ledger = batches.ledger.clone(); + let pages = std::iter::once_with(|| { unlocked.store(ledger.try_lock().is_ok(), Ordering::Relaxed); 0x2_2001 }); + assert!(batches.add_dirty_pages(pages)); + assert!(unlocked.load(Ordering::Relaxed), "a producer iterator ran under the batch lock"); + assert_eq!(batches.seal(1, 1).unwrap().unwrap().pages()[0].0, 0x2_2000); + } + + #[test] + fn sparse_batch_ready_requires_new_reasons_to_be_sealed() { + let batches = SparseBatches::new(59); + assert!(batches.add_dirty_pages([0x3_1000])); + let first = batches.seal(1, 1).unwrap().unwrap(); + let first_epoch = batches.through().unwrap(); + assert!(batches.add_dirty_pages([0x3_1001])); + assert_eq!(batches.through(), Err(SparseBatchError::Unsealed)); + assert_eq!(batches.observe(first_epoch, 2), Err(SparseBatchError::Unsealed)); + + first.accept().unwrap().receipt(8).unwrap(); + assert_eq!(batches.through(), Err(SparseBatchError::Unsealed)); + let successor = batches.seal(2, 1).unwrap().unwrap(); + let through = batches.through().unwrap(); + assert!(through > first_epoch); + successor.obsolete().unwrap(); assert_eq!( - fallback.revalidate(73, 10, |_| None), - LegacyParityRevalidation::RetryCurrentGeneration, + batches.observe(through, 2), + Ok(ClaimFrontierAction::Ready { through, required_fence: Some(8) }), ); - fallback.retry().unwrap(); - let exact = batches.seal(5, 1).unwrap().unwrap(); - assert_eq!(exact.pages(), &[(0x2_3000, WorkReasons::DIRTY)]); - exact.obsolete().unwrap(); } #[test] - fn coordinated_preaccept_unwind_cancels_reservation_and_leaves_batch_visible() { - for panic_at in ["copy", "prepare"] { - let (batches, plan, observation, token) = coordinated_upload_fixture(1); - let reservations = UploadReservations::new(71, 1, 256, 64); - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let _ = plan.commit_reserved( - 71, 7, |_| Some(observation.clone()), &reservations, 0, 64, - |_, _| -> Result, ()> { - if panic_at == "copy" { panic!("copy panicked") } - Ok(vec![0; 64]) - }, - |_, _| -> Result<(), ()> { - if panic_at == "prepare" { panic!("prepare panicked") } - Ok(()) - }, - |_, _| {}, || Ok::<_, ()>(9), - ); - })); - assert!(result.is_err()); - assert_eq!(batches.observe(1, 9), Ok(ClaimFrontierAction::TakeOver(token))); - let ledger = reservations.0.lock().unwrap(); - assert!(!ledger.poisoned && ledger.records.is_empty()); - assert!(ledger.slots.iter().all(Option::is_none)); + fn sparse_batch_receipts_are_contiguous_and_acceptance_is_fail_closed() { + let batches = SparseBatches::new(61); + assert!(batches.add_dirty_pages([0x4_1000, 0x4_2000])); + let first = batches.seal(1, 1).unwrap().unwrap(); + let second = batches.seal(2, 1).unwrap().unwrap(); + let through = batches.through().unwrap(); + let first_token = first.token; + let first = first.accept().unwrap(); + let second = second.accept().unwrap(); + second.receipt(11).unwrap(); + assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::WaitForReceipt(first_token))); + first.receipt(8).unwrap(); + assert_eq!( + batches.observe(through, 3), + Ok(ClaimFrontierAction::Ready { through, required_fence: Some(11) }), + ); + + assert!(batches.add_dirty_pages([0x4_3000])); + let accepted = batches.seal(4, 1).unwrap().unwrap().accept().unwrap(); + let accepted_token = accepted.token.unwrap().0; + assert!(matches!( + batches.take_over(accepted_token, 5), + Err(SparseBatchError::Frontier(ClaimFrontierError::WrongState)), + )); + drop(accepted); + assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); + + let current = batches.replace_generation(62).unwrap(); + assert_eq!(batches.through(), Err(SparseBatchError::StaleGeneration)); + assert!(matches!(current.replace_generation(61), Err(SparseBatchError::StaleGeneration))); + assert!(matches!(current.take_over(accepted_token, 6), Err(SparseBatchError::StaleGeneration))); + assert!(current.add_dirty_pages([0x5_1000])); + let stale = current.seal(6, 1).unwrap().unwrap(); + let replacement = current.replace_generation(63).unwrap(); + assert_eq!(stale.obsolete(), Err(SparseBatchError::StaleGeneration)); + assert_eq!(replacement.through(), Ok(0)); + assert!(matches!(SparseBatches::new(u64::MAX).replace_generation(0), Err(SparseBatchError::StaleGeneration))); + } + + #[test] + fn live_sparse_coordination_owns_one_exact_generation() { + let coordination = SparseCoordination::new(101, 501).unwrap(); + { + let batches = coordination.batches.ledger.lock().unwrap(); + assert_eq!(batches.work.state_generation, 101); + assert_eq!(batches.fence, Some(SparseFenceIdentity { state_generation: 101, allocation: 501 })); + } + assert_eq!(coordination.waits.fence(), SparseFenceIdentity { state_generation: 101, allocation: 501 }); + let reservation = coordination.reservations.reserve(0, RING_ALIGN).unwrap(); + assert_eq!(reservation.token.unwrap().state_generation, 101); + assert!(SparseCoordination::new(0, 501).is_none()); + assert!(SparseCoordination::new(101, 0).is_none()); + } + + #[test] + fn legacy_sparse_attempt_is_mirrored_and_retired_as_one_exact_batch() { + let coordination = SparseCoordination::new(103, 503).unwrap(); + let snapshot = coordination.clone(); + assert!(Arc::ptr_eq(&coordination.batches.ledger, &snapshot.batches.ledger)); + + let batch = snapshot.seal_legacy( + 0xA, + &[(0x3000, 2 * PAGE)], + &[0x3001, 0x1000], + &[(0x4000 + CHUNK, CHUNK)], + ).unwrap().unwrap(); + assert_eq!(batch.token.state_generation, 103); + assert_eq!( + batch.pages().iter().map(|(page, reasons)| (*page, reasons.0)).collect::>(), + [ + (0x1000, WorkReasons::RETRY.0), + (0x3000, WorkReasons::ZERO.0 | WorkReasons::RETRY.0), + (0x4000, WorkReasons::ZERO.0 | WorkReasons::DIRTY.0), + ], + ); + let through = snapshot.batches.through().unwrap(); + batch.obsolete().unwrap(); + assert_eq!( + coordination.batches.observe(through, 0xB), + Ok(ClaimFrontierAction::Ready { through, required_fence: None }), + "the parity batch remained visible after the legacy path retired it", + ); + assert!(coordination.batches.seal(0xB, usize::MAX).unwrap().is_none()); + } + + fn wait_ready(fence: SparseFenceIdentity, through: u64, value: Option) -> SparseReadyReceipt { + SparseReadyReceipt { state_generation: fence.state_generation, fence, through, required_fence: value } + } + + fn wait_reservation(decision: ForegroundWaitDecision) -> ForegroundWaitReservation { + match decision { ForegroundWaitDecision::Reserve(reservation) => reservation, _ => panic!("wait not reserved") } + } + + #[test] + fn foreground_wait_pairs_out_of_order_frontier_with_exact_fence() { + let batches = SparseBatches::with_fence(101, 501).unwrap(); + assert!(batches.add_dirty_pages([0x6_1000, 0x6_2000])); + let first = batches.seal(1, 1).unwrap().unwrap(); + let first_token = first.token; + let second = batches.seal(2, 1).unwrap().unwrap(); + let through = batches.through().unwrap(); + let first = first.accept().unwrap(); + second.accept().unwrap().receipt(11).unwrap(); + let waits = ForegroundWaits::new(101, 501).unwrap(); + let queue = waits.register_queue(0xA).unwrap(); + assert_eq!(waits.register_queue(0xA), Ok(queue)); + assert_eq!(batches.ready_receipt(through, 3), Err(ForegroundWaitError::NotReady)); + assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::WaitForReceipt(first_token))); + first.receipt(8).unwrap(); + + let ready = batches.ready_receipt(through, 3).unwrap(); + let wrong = SparseReadyReceipt { fence: SparseFenceIdentity { allocation: 502, ..ready.fence }, ..ready }; + assert!(matches!(waits.reserve(queue, wrong), Err(ForegroundWaitError::Fence))); + let reservation = wait_reservation(waits.reserve(queue, ready).unwrap()); + assert_eq!(reservation.arm().unwrap().publish(), Ok((through, 11))); + assert!(matches!(waits.reserve(queue, ready), Ok(ForegroundWaitDecision::Installed { through: t, value: 11 }) if t == through)); + assert!(matches!(waits.reserve(queue, wait_ready(waits.fence(), through + 1, None)), + Ok(ForegroundWaitDecision::NoWait { through: t }) if t == through + 1)); + + let other = SparseBatches::with_fence(101, 502).unwrap(); + let other_waits = ForegroundWaits::new(101, 502).unwrap(); + let other_queue = other_waits.register_queue(0xE).unwrap(); + assert!(matches!(other.ready_receipt(through, 3), Err(ForegroundWaitError::Batch(_)))); + assert!(matches!(other_waits.reserve(other_queue, ready), Err(ForegroundWaitError::Fence))); + + assert!(matches!(batches.replace_generation_with_fence(102, 501), Err(SparseBatchError::Fence))); + let stale = batches.clone(); + let batches = batches.replace_generation_with_fence(102, 503).unwrap(); + assert_eq!(batches.ledger.lock().unwrap().fence.unwrap().allocation, 503); + assert_eq!(stale.ready_receipt(through, 3), Err(ForegroundWaitError::Batch(SparseBatchError::StaleGeneration))) + } + + #[test] + fn foreground_wait_rollbacks_are_exact_and_queue_reuse_is_stale() { + let waits = ForegroundWaits::new(103, 601).unwrap(); + let fence = waits.fence(); + let queue = waits.register_queue(0xB).unwrap(); + let ready = wait_ready(fence, 1, Some(5)); + let abandoned = wait_reservation(waits.reserve(queue, ready).unwrap()); + let stale = abandoned.token.unwrap(); + assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Pending(token)) if token == stale)); + assert!(matches!(waits.reserve(queue, wait_ready(fence, 0, None)), Err(ForegroundWaitError::Pending(_)))); + drop(abandoned); + + let accepted = wait_reservation(waits.reserve(queue, wait_ready(fence, 2, Some(6))).unwrap()).arm().unwrap(); + let accepted_token = accepted.token.unwrap(); + accepted.rollback().unwrap(); + let newer = wait_reservation(waits.reserve(queue, wait_ready(fence, 3, Some(7))).unwrap()); + assert_eq!(waits.0.lock().unwrap().transition(accepted_token, ForegroundWaitState::Accepted, None), + Err(ForegroundWaitError::StaleToken)); + assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Pending(token)) if token == newer.token.unwrap())); + drop(newer); + waits.retire_queue(queue).unwrap(); + let replacement = waits.register_queue(0xB).unwrap(); + assert!(replacement.generation > queue.generation); + assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Queue))); + assert!(matches!(waits.reserve(replacement, ready), Ok(ForegroundWaitDecision::Reserve(_)))); + } + + #[test] + fn foreground_wait_unpublished_acceptance_fails_closed() { + let waits = ForegroundWaits::new(107, 701).unwrap(); + let queue = waits.register_queue(0xC).unwrap(); + let ready = wait_ready(waits.fence(), 1, Some(9)); + let accepted = wait_reservation(waits.reserve(queue, ready).unwrap()).arm().unwrap(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + let _accepted = accepted; + panic!("after native wait acceptance"); + })); + assert!(result.is_err()); + assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Uncertain))); + assert!(matches!(waits.reserve(queue, wait_ready(waits.fence(), 0, None)), Err(ForegroundWaitError::Uncertain))); + } + + #[test] + fn foreground_wait_generation_replacement_rejects_old_guards_and_fences() { + let waits = ForegroundWaits::new(109, 801).unwrap(); + let queue = waits.register_queue(0xD).unwrap(); + let old_fence = waits.fence(); + let old_ready = wait_ready(old_fence, 1, Some(3)); + let old = wait_reservation(waits.reserve(queue, old_ready).unwrap()); + waits.replace_generation(109, 110, 802).unwrap(); + drop(old); + assert!(matches!(waits.reserve(queue, old_ready), Err(ForegroundWaitError::StaleGeneration))); + assert_eq!(waits.replace_generation(110, 109, 803), Err(ForegroundWaitError::StaleGeneration)); + assert_eq!(waits.replace_generation(110, 111, 801), Err(ForegroundWaitError::Fence)); + let current = wait_ready(waits.fence(), 1, Some(4)); + assert!(matches!(waits.reserve(queue, current), Ok(ForegroundWaitDecision::Reserve(_)))); + } + + fn upload_observation(page: usize, pool: (u32, u32), source_word: u64) -> UploadPageObservation { + let mut source = ZERO_HASHES; + source[1] = source_word; + source[2] = source_word; + UploadPageObservation { page, pool, hole: false, sent: Some(ZERO_HASHES), source } + } + + fn coordinated_upload_fixture( + owner: u64, + ) -> (SparseBatches, CoordinatedSparseUploadPlan, UploadPageObservation, ClaimFrontierToken) { + let batches = SparseBatches::new(71); + assert!(batches.add_dirty_pages([0x2_1000])); + let lease = batches.seal(owner, 1).unwrap().unwrap(); + let token = lease.token; + let observation = upload_observation(0x2_1000, (4, 9), 0xA5); + let plan = CoordinatedSparseUploadPlan::build(lease, 71, 7, |_| Some(observation.clone())).unwrap(); + (batches, plan, observation, token) + } + + fn commit_coordinated( + plan: CoordinatedSparseUploadPlan, observation: &UploadPageObservation, + reservations: &UploadReservations, slot: usize, fence: u64, + ) -> Result> { + plan.commit_reserved( + 71, 7, |_| Some(observation.clone()), reservations, slot, 64, + |_, _| Ok(vec![0; 64]), |_, _| Ok(()), |_, _| {}, || Ok(fence), + ) + } + + #[test] + fn shared_upload_page_builder_preserves_intent_order_and_dirty_ranges() { + let claimed = [ + (0x1_1000, WorkReasons(WorkReasons::ZERO.0 | WorkReasons::DIRTY.0)), + (0x1_2000, WorkReasons::RETRY), + ]; + let first = upload_observation(0x1_1000, (2, 3), 0x91); + let second = upload_observation(0x1_2000, (2, 3), ZERO_HASH); + let pages = build_upload_pages(&claimed, |page| match page { + 0x1_1000 => Some(first.clone()), + 0x1_2000 => Some(second.clone()), + _ => None, + }).unwrap(); + + assert_eq!(pages.iter().map(|page| page.page).collect::>(), [0x1_1000, 0x1_2000]); + assert!(pages[0].zero && pages[0].dirty); + assert_eq!(pages[0].dirty_ranges, [(0x1_1000 + CHUNK, 2 * CHUNK)]); + assert!(!pages[1].zero && pages[1].dirty); + assert!(pages[1].dirty_ranges.is_empty(), "retry intent was lost when no chunks changed"); + assert!(build_upload_pages(&claimed, |page| { + (page == 0x1_1000).then(|| first.clone()) + }).is_none()); + } + + #[test] + fn coordinated_plan_revalidates_every_sparse_page_identity() { + let (_, plan, observation, _) = coordinated_upload_fixture(1); + assert_eq!(plan.validate(72, 7, |_| Some(observation.clone())), Err(UploadPlanInvalid::StateGeneration)); + assert_eq!(plan.validate(71, 8, |_| Some(observation.clone())), Err(UploadPlanInvalid::MappingEpoch)); + assert_eq!(plan.validate(71, 7, |_| None), Err(UploadPlanInvalid::MissingPage)); + + let mut remapped = observation.clone(); + remapped.page += TILE; + assert_eq!(plan.validate(71, 7, |_| Some(remapped.clone())), Err(UploadPlanInvalid::Mapping)); + let mut repooled = observation.clone(); + repooled.pool.1 += 1; + assert_eq!(plan.validate(71, 7, |_| Some(repooled.clone())), Err(UploadPlanInvalid::Mapping)); + let mut hole = observation.clone(); + hole.hole = true; + assert_eq!(plan.validate(71, 7, |_| Some(hole.clone())), Err(UploadPlanInvalid::Mapping)); + let mut resent = observation.clone(); + resent.sent.as_mut().unwrap()[3] ^= 1; + assert_eq!(plan.validate(71, 7, |_| Some(resent.clone())), Err(UploadPlanInvalid::SentHashes)); + let mut rewritten = observation.clone(); + rewritten.source[3] ^= 1; + assert_eq!(plan.validate(71, 7, |_| Some(rewritten.clone())), Err(UploadPlanInvalid::SourceHashes)); + } + + #[test] + fn live_parity_snapshot_revalidates_concurrent_changes_and_retries() { + let batches = SparseBatches::new(73); + assert!(batches.add_dirty_pages([0x2_3000])); + let lease = batches.seal(3, 1).unwrap().unwrap(); + let token = lease.token; + let through = batches.through().unwrap(); + let observed = upload_observation(0x2_3000, (6, 11), 0xB7); + let mut captures = 0; + let snapshot = UploadPlanningSnapshot::capture(73, 9, lease.pages(), |_| { + captures += 1; + Some(observed.clone()) + }).unwrap(); + assert_eq!(captures, 1); + + // Construction consumes only the owned snapshot; no live State observation is available + // while this work runs outside its lock. + let plan = CoordinatedSparseUploadPlan::from_snapshot(lease, snapshot).unwrap(); + assert_eq!(plan.pages[0].source, observed.source); + assert_eq!(plan.validate(74, 9, |_| Some(observed.clone())), Err(UploadPlanInvalid::StateGeneration)); + assert_eq!(plan.validate(73, 10, |_| Some(observed.clone())), Err(UploadPlanInvalid::MappingEpoch)); + let mut rewritten = observed.clone(); + rewritten.source[5] ^= 1; + assert_eq!(plan.validate(73, 9, |_| Some(rewritten.clone())), Err(UploadPlanInvalid::SourceHashes)); + assert_eq!(plan.validate(73, 9, |_| Some(observed.clone())), Ok(())); + + let parity = LegacyParityUpload::Planned(plan); + assert_eq!( + parity.revalidate(74, 9, |_| Some(observed.clone())), + LegacyParityRevalidation::RestartForGeneration, + ); + assert_eq!( + parity.revalidate(73, 10, |_| Some(observed.clone())), + LegacyParityRevalidation::RetryCurrentGeneration, + ); + assert_eq!( + parity.revalidate(73, 9, |_| Some(rewritten.clone())), + LegacyParityRevalidation::RetryCurrentGeneration, + ); + assert_eq!( + parity.revalidate(73, 9, |_| Some(observed.clone())), + LegacyParityRevalidation::Ready, + ); + assert_eq!( + batches.observe(through, 4), + Ok(ClaimFrontierAction::TakeOver(token)), + "validation must not accept or publish the behavior-neutral parity lease", + ); + parity.retry().unwrap(); + let restored = batches.seal(4, 1).unwrap().expect( + "a stale unlocked plan did not restore its exact work for retry", + ); + assert_eq!(restored.pages(), &[(0x2_3000, WorkReasons::DIRTY)]); + let fallback = LegacyParityUpload::Lease { + lease: restored, + state_generation: 73, + mapping_epoch: 9, + }; + assert_eq!( + fallback.revalidate(74, 9, |_| None), + LegacyParityRevalidation::RestartForGeneration, + ); + assert_eq!( + fallback.revalidate(73, 10, |_| None), + LegacyParityRevalidation::RetryCurrentGeneration, + ); + fallback.retry().unwrap(); + let exact = batches.seal(5, 1).unwrap().unwrap(); + assert_eq!(exact.pages(), &[(0x2_3000, WorkReasons::DIRTY)]); + exact.obsolete().unwrap(); + } + + #[test] + fn coordinated_preaccept_unwind_cancels_reservation_and_leaves_batch_visible() { + for panic_at in ["copy", "prepare"] { + let (batches, plan, observation, token) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(71, 1, 256, 64); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = plan.commit_reserved( + 71, 7, |_| Some(observation.clone()), &reservations, 0, 64, + |_, _| -> Result, ()> { + if panic_at == "copy" { panic!("copy panicked") } + Ok(vec![0; 64]) + }, + |_, _| -> Result<(), ()> { + if panic_at == "prepare" { panic!("prepare panicked") } + Ok(()) + }, + |_, _| {}, || Ok::<_, ()>(9), + ); + })); + assert!(result.is_err()); + assert_eq!(batches.observe(1, 9), Ok(ClaimFrontierAction::TakeOver(token))); + let ledger = reservations.0.lock().unwrap(); + assert!(!ledger.poisoned && ledger.records.is_empty()); + assert!(ledger.slots.iter().all(Option::is_none)); + } + } + + #[test] + fn coordinated_commit_orders_callbacks_and_owns_copied_staging() { + let (_, plan, observation, _) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(71, 1, 256, 64); + let calls = std::cell::RefCell::new(Vec::new()); + let receipt = plan.commit_reserved( + 71, 7, |_| Some(observation.clone()), &reservations, 0, 4, + |range, pages| { + calls.borrow_mut().push("copy"); + assert_eq!(range, UploadRingRange { start: 0, end: 4 }); + assert_eq!(pages[0].page, observation.page); + Ok::<_, ()>(vec![1, 2, 3, 4]) + }, + |staging, _| { + calls.borrow_mut().push("prepare"); + assert_eq!(&*staging.bytes, &[1, 2, 3, 4]); + Ok::<_, ()>(()) + }, + |staging, _| { + calls.borrow_mut().push("execute"); + assert_eq!(&*staging.bytes, &[1, 2, 3, 4]); + }, + || { calls.borrow_mut().push("signal"); Ok::<_, ()>(9) }, + ).unwrap(); + assert_eq!(&*calls.borrow(), &["copy", "prepare", "execute", "signal"]); + assert_eq!(reservations.complete(receipt), Ok(4)); + } + + #[test] + fn coordinated_plan_preaccept_failures_stay_visible_and_takeover_revokes() { + for failure in ["validate", "reservation generation", "reserve", "copy", "size", "prepare"] { + let (batches, plan, observation, token) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(if failure == "reservation generation" { 72 } else { 71 }, 1, 256, 64); + let occupied = (failure == "reserve").then(|| reservations.reserve(0, 64).unwrap()); + let result = plan.commit_reserved( + if failure == "validate" { 72 } else { 71 }, 7, |_| Some(observation.clone()), + &reservations, 0, 64, + |_, _| if failure == "copy" { Err("copy") } else { Ok(vec![0; if failure == "size" { 63 } else { 64 }]) }, + |_, _| if failure == "prepare" { Err("prepare") } else { Ok(()) }, + |_, _| {}, || Ok::<_, &'static str>(9), + ); + let expected = match failure { + "validate" => matches!(result, Err(CoordinatedSparseUploadError::Invalid(UploadPlanInvalid::StateGeneration))), + "reservation generation" => matches!(result, Err(CoordinatedSparseUploadError::Reserve(UploadReservationError::StaleGeneration))), + "reserve" => matches!(result, Err(CoordinatedSparseUploadError::Reserve(UploadReservationError::SlotBusy))), + "copy" => matches!(result, Err(CoordinatedSparseUploadError::Copy("copy"))), + "size" => matches!(result, Err(CoordinatedSparseUploadError::StagingSize)), + _ => matches!(result, Err(CoordinatedSparseUploadError::Prepare("prepare"))), + }; + assert!(expected, "wrong {failure} boundary result"); + assert_eq!(batches.observe(1, 9), Ok(ClaimFrontierAction::TakeOver(token))); + assert!(!reservations.0.lock().unwrap().poisoned); + drop(occupied); + } + + let (batches, stale, observation, token) = coordinated_upload_fixture(1); + let replacement = batches.take_over(token, 2).unwrap(); + let result = commit_coordinated(stale, &observation, &UploadReservations::new(71, 1, 256, 64), 0, 9); + assert!(matches!(result, Err(CoordinatedSparseUploadError::Accept( + SparseBatchError::Frontier(ClaimFrontierError::StaleToken) + )))); + assert_eq!(replacement.pages()[0].0, 0x2_1000); + } + + #[test] + fn coordinated_submit_then_panic_poisons_both_generations() { + let (batches, plan, observation, _) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(71, 1, 256, 64); + let submitted = std::cell::Cell::new(false); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = plan.commit_reserved( + 71, 7, |_| Some(observation.clone()), &reservations, 0, 64, + |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), + |_, _| { submitted.set(true); panic!("execute panicked after submit") }, + || Ok::<_, ()>(9), + ); + })); + assert!(result.is_err() && submitted.get()); + assert!(reservations.0.lock().unwrap().poisoned); + assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); + + let (batches, plan, observation, _) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(71, 1, 256, 64); + let result = plan.commit_reserved( + 71, 7, |_| Some(observation.clone()), &reservations, 0, 64, + |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), |_, _| {}, || Err::("signal"), + ); + assert!(matches!(result, Err(CoordinatedSparseUploadError::Signal("signal")))); + assert!(reservations.0.lock().unwrap().poisoned); + assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); + + let (batches, plan, observation, _) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(71, 1, 256, 64); + assert!(matches!(commit_coordinated(plan, &observation, &reservations, 0, 0), + Err(CoordinatedSparseUploadError::PublishReservation(UploadReservationError::State)))); + assert!(reservations.0.lock().unwrap().poisoned); + assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); + } + + #[test] + fn coordinated_frontier_publication_failure_quarantines_submitted_reservation() { + let (batches, plan, _, _) = coordinated_upload_fixture(1); + let lease = plan.lease.unwrap(); + let batch = lease.accept().unwrap(); + let reservations = UploadReservations::new(71, 1, 256, 64); + let reservation = reservations.reserve(0, 64).unwrap(); + let mut accepted = AcceptedCoordinatedUpload::new(reservation, batch); + let receipt = accepted.reservation.take().unwrap().publish_after_accept(13).unwrap(); + accepted.batch_ledger.lock().unwrap().bindings.remove(&accepted.batch_token.epoch); + assert_eq!(accepted.batch.take().unwrap().receipt(13), Err(SparseBatchError::Corrupt)); + drop(accepted); + let ledger = reservations.0.lock().unwrap(); + assert!(ledger.poisoned); + assert_eq!(ledger.records[&receipt.token.serial].state, UploadReservationState::Poisoned); + drop(ledger); + let ledger = batches.ledger.lock().unwrap(); + assert!(ledger.poisoned && ledger.work.claims.is_empty() && ledger.work.owners.is_empty()); + assert!(ledger.bindings.is_empty()); + } + + #[test] + fn a_prior_poison_does_not_leave_later_accepted_work_owned() { + let batches = SparseBatches::new(71); + assert!(batches.add_dirty_pages([0x3_1000, 0x3_2000])); + let first = batches.seal(1, 1).unwrap().unwrap().accept().unwrap(); + let second = batches.seal(2, 1).unwrap().unwrap().accept().unwrap(); + let reservations = UploadReservations::new(71, 2, 256, 64); + let first = AcceptedCoordinatedUpload::new(reservations.reserve(0, 64).unwrap(), first); + let second = AcceptedCoordinatedUpload::new(reservations.reserve(1, 64).unwrap(), second); + drop(first); + assert!(matches!(second.publish(17), Err(CoordinatedPublishError::Batch(SparseBatchError::Poisoned)))); + let ledger = batches.ledger.lock().unwrap(); + assert!(ledger.poisoned && ledger.work.claims.is_empty() && ledger.work.owners.is_empty()); + assert!(ledger.bindings.is_empty()); + drop(ledger); + let reservations = reservations.0.lock().unwrap(); + assert!(reservations.poisoned && reservations.records.values().all(|r| r.state == UploadReservationState::Poisoned)); + } + + #[test] + fn coordinated_receipts_publish_exact_out_of_order_fence_prefix() { + let batches = SparseBatches::new(71); + assert!(batches.add_dirty_pages([0x2_1000, 0x2_2000])); + let observation = |page| upload_observation(page, (4, 9), 0xA5); + let first_lease = batches.seal(1, 1).unwrap().unwrap(); + let first_token = first_lease.token; + let second_lease = batches.seal(2, 1).unwrap().unwrap(); + let through = batches.through().unwrap(); + let first = CoordinatedSparseUploadPlan::build(first_lease, 71, 7, |page| Some(observation(page))).unwrap(); + let second = CoordinatedSparseUploadPlan::build(second_lease, 71, 7, |page| Some(observation(page))).unwrap(); + let reservations = UploadReservations::new(71, 2, 256, 64); + let second_receipt = commit_coordinated(second, &observation(0x2_2000), &reservations, 1, 11).unwrap(); + assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::TakeOver(first_token))); + let first_receipt = commit_coordinated(first, &observation(0x2_1000), &reservations, 0, 8).unwrap(); + assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::Ready { through, required_fence: Some(11) })); + assert_eq!(reservations.complete(first_receipt), Ok(0)); + assert_eq!(reservations.complete(second_receipt), Ok(128)); + } + + #[test] + fn upload_reservations_reclaim_only_a_contiguous_retired_prefix() { + let reservations = UploadReservations::new(41, 2, 256, 64); + let first = reservations.reserve(0, 80).unwrap(); + let second = reservations.reserve(1, 80).unwrap(); + assert_eq!(first.range(), UploadRingRange { start: 0, end: 80 }); + assert_eq!(second.range(), UploadRingRange { start: 128, end: 208 }); + let first = first.submit(5).unwrap(); + let second = second.submit(6).unwrap(); + + assert_eq!(reservations.complete(second), Ok(0), "later retirement crossed an older owner"); + assert!(matches!(reservations.reserve(1, 64), Err(UploadReservationError::Full))); + assert_eq!(reservations.complete(first), Ok(208)); + + let wrapped = reservations.reserve(1, 64).unwrap(); + assert_eq!(wrapped.range(), UploadRingRange { start: 256, end: 320 }); + assert_eq!(wrapped.submit(7).and_then(|receipt| reservations.complete(receipt)), Ok(320)); + } + + #[test] + fn an_empty_ring_discards_tail_padding_before_a_full_capacity_reservation() { + let reservations = UploadReservations::new(42, 1, 256, 64); + drop(reservations.reserve(0, 64).unwrap()); + { + let ledger = reservations.0.lock().unwrap(); + assert_eq!((ledger.cursor, ledger.reclaimed), (64, 64)); + } + + let full = reservations.reserve(0, 256).unwrap(); + assert_eq!(full.range(), UploadRingRange { start: 256, end: 512 }); + let ledger = reservations.0.lock().unwrap(); + assert_eq!((ledger.cursor, ledger.reclaimed), (512, 256)); + } + + #[test] + fn failed_empty_ring_reservation_does_not_publish_boundary_normalization() { + let mut ledger = UploadReservationLedger::new(42, 1, 256, 64); + let token = ledger.reserve(42, 0, 64).unwrap().0; + assert_eq!(ledger.cancel(token), Ok(64)); + ledger.next_serial = u64::MAX; + + assert!(matches!(ledger.reserve(42, 0, 256), Err(UploadReservationError::Exhausted))); + assert_eq!((ledger.cursor, ledger.reclaimed), (64, 64)); + assert_eq!(ledger.next_serial, u64::MAX); + assert!(ledger.order.is_empty()); + assert!(ledger.records.is_empty()); + assert!(ledger.slots[0].is_none()); + } + + #[test] + fn cancelling_an_older_reservation_never_rewinds_newer_ring_work() { + let reservations = UploadReservations::new(43, 3, 512, 64); + let first = reservations.reserve(0, 64).unwrap(); + let middle = reservations.reserve(1, 64).unwrap(); + let third = reservations.reserve(2, 64).unwrap(); + let middle_token = middle.token.unwrap(); + drop(middle); + assert_eq!(reservations.0.lock().unwrap().reclaimed, 0); + + let later = reservations.reserve(1, 64).unwrap(); + assert!(later.range().start >= third.range().end, "a cancellation rewound across newer work"); + drop(first); + assert_eq!(reservations.0.lock().unwrap().reclaimed, 128); + assert_eq!(reservations.0.lock().unwrap().cancel(middle_token), Err(UploadReservationError::Missing)); + + let third = third.submit(8).unwrap(); + assert_eq!(reservations.complete(UploadSubmissionReceipt { fence: 9, ..third }), Err(UploadReservationError::Fence)); + assert_eq!(reservations.complete(third), Ok(192)); + drop(later); + assert_eq!(reservations.0.lock().unwrap().reclaimed, 256); + } + + #[test] + fn dropped_reservation_cancels_exactly_it_and_signal_failure_poisons_reuse() { + let reservations = UploadReservations::new(47, 2, 256, 64); + let abandoned = reservations.reserve(0, 64).unwrap(); + let stale = abandoned.token.unwrap(); + drop(abandoned); + assert_eq!(reservations.0.lock().unwrap().reclaimed, 64); + assert_eq!(reservations.0.lock().unwrap().cancel(stale), Err(UploadReservationError::Missing)); + + let poisoned = reservations.reserve(0, 64).unwrap(); + poisoned.poison().unwrap(); + let ledger = reservations.0.lock().unwrap(); + assert!(ledger.poisoned); + assert_eq!(ledger.slots[0], Some(2), "poison released an allocator with untracked GPU work"); + drop(ledger); + assert!(matches!(reservations.reserve(1, 64), Err(UploadReservationError::Poisoned))); + } + + #[test] + fn upload_reservation_bounds_generation_and_monotonic_overflow_fail_closed() { + let mut ledger = UploadReservationLedger::new(53, 1, 256, 64); + assert!(matches!(ledger.reserve(52, 0, 64), Err(UploadReservationError::StaleGeneration))); + assert!(matches!(ledger.reserve(53, 1, 0), Err(UploadReservationError::Slot))); + assert!(matches!(ledger.reserve(53, 0, 0), Err(UploadReservationError::Empty))); + assert!(matches!(ledger.reserve(53, 0, 257), Err(UploadReservationError::TooLarge))); + + ledger.cursor = u64::MAX - 31; + assert!(matches!(ledger.reserve(53, 0, 64), Err(UploadReservationError::Exhausted))); + ledger.cursor = 0; + ledger.next_serial = u64::MAX; + assert!(matches!(ledger.reserve(53, 0, 64), Err(UploadReservationError::Exhausted))); + assert!(ledger.records.is_empty()); + assert!(ledger.order.is_empty()); + assert!(ledger.slots[0].is_none()); + } + + #[test] + fn a_failed_title_queue_wait_rolls_back_only_its_reservation() { + let mut waited = FxHashMap::from_iter([(1, 4), (2, 7)]); + assert!(reserve_queue_wait(&mut waited, 1, 5)); + rollback_queue_wait(&mut waited, 1, 5, Some(4)); + assert_eq!(waited, FxHashMap::from_iter([(1, 4), (2, 7)])); + rollback_queue_wait(&mut waited, 1, 9, None); + assert_eq!(waited.get(&1), Some(&4), "a stale failure changed a newer reservation"); + } + + #[test] + fn quarantine_uses_installed_retirement_marks_and_fails_closed_without_one() { + use std::sync::Arc; + let own = Arc::new(1u32); + let retired = Arc::new(2u32); + let marks = initial_quarantine_marks((own.clone(), 3), &[(retired.clone(), 4)], false).unwrap(); + assert_eq!(marks.iter().map(|(_, value)| *value).collect::>(), [3, 4]); + drop(retired); + assert_eq!(Arc::strong_count(&marks[1].0), 1, "batch did not own the retirement marker"); + assert!(initial_quarantine_marks((own, 3), &[(marks[1].0.clone(), 4)], true).is_none(), "Preparing/Failed reused tiles without a completion source"); + } + + /// A block freed on one thread while another allocates: its address goes back to the + /// windows only once it is decommitted (released first, the decommit came after another + /// thread had the same address again: that thread's writes faulted). + #[test] + fn a_freed_block_is_decommitted_before_its_address_is_reused() { + if crate::gpu::uma::get().is_none_or(|u| !u.has_sparse()) { + return; + } + let threads: Vec<_> = (0..4) + .map(|_| { + std::thread::spawn(|| unsafe { + for i in 0..2000u64 { + let Some((p, n)) = alloc(TILE, TILE) else { continue }; + std::ptr::write_volatile(p as *mut u64, i); + std::ptr::write_volatile((p + n - 8) as *mut u64, i); + assert_eq!(std::ptr::read_volatile(p as *const u64), i); + assert!(free(p)); + } + }) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + } + + /// `f` on another thread while this one holds the sparse state (as `before_execute` does + /// around its D3D12 calls, which can wait for that thread): did `f` finish without waiting + /// for the state? The thread runs before the state is taken, so its start is not timed. + fn returns_while_the_state_is_held(f: impl FnOnce() + Send + 'static) -> bool { + let (ready_tx, ready_rx) = std::sync::mpsc::channel(); + let (go_tx, go_rx) = std::sync::mpsc::channel::<()>(); + let (tx, rx) = std::sync::mpsc::channel(); + let t = std::thread::spawn(move || { + let _ = ready_tx.send(()); + let _ = go_rx.recv(); + f(); + let _ = tx.send(()); + }); + ready_rx.recv().unwrap(); + let held = STATE.lock().unwrap(); + go_tx.send(()).unwrap(); + let done = rx.recv_timeout(std::time::Duration::from_secs(5)); + drop(held); + let joined = t.join(); + assert!(joined.is_ok(), "the thread panicked: {joined:?}"); + done.is_ok() + } + + /// A placed buffer released while another thread holds the sparse state: the release does + /// not wait for the state, and the next `lock_state` lets the buffer go. + #[test] + fn a_buffer_released_while_the_state_is_held_does_not_wait_for_it() { + const RES: usize = 0x7ff0_dead_0000; + assert!(returns_while_the_state_is_held(|| forget_buffer(RES)), "forget_buffer waited for the sparse state's lock"); + drop(lock_state()); + assert!(!FORGOTTEN.lock().unwrap().contains(&RES)); + } + + + /// Freeing the last tile in use of a pool and taking a tile again takes the retired pool + /// back, not a new heap each time (#913: 288 pools of 64 MB, 18 GB asked of a 12 GB card). + #[test] + fn a_pool_retired_a_moment_ago_is_taken_back() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.expect("D3D12 device"); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); + let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("rb_alloc"); + let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); + rb_list.Close().expect("rb_list close"); + let readbacks = Arc::new(SharedReadbacks::new(rb_fence.clone(), None)); + let rb_submit = Arc::new(Mutex::new(RbSubmit::new(dev.clone()))); + let mut s = State { + generation: 1, + mapping_epoch: 0, + coordination: SparseCoordination::new(1, 1).unwrap(), + dev, + queue, + fence, + value: 0, + event, + rb_fence, + rb_value: 0, + rbq: None, + rbq_value: 0, + readbacks, + rb_submit, + windows: Vec::new(), + pools: Vec::new(), + free: FreePools::new(), + cooling: VecDeque::new(), + retired: Vec::new(), + retire_tried: std::time::Instant::now(), + parked: FxHashMap::default(), + kept: FxHashMap::default(), + pending: Vec::new(), + mapped: FxHashMap::default(), + pinned: FxHashMap::default(), + quarantined: VecDeque::new(), + queue_fences: FxHashMap::default(), + buffers: FxHashMap::default(), + to_zero: BTreeSet::new(), + staging: None, + ring_write: 0, + ring_submitted: 0, + ring_free: 0, + inflight: VecDeque::new(), + uploads_ordered: true, + zero_buf: None, + slots: Vec::new(), + next_slot: 0, + readback: None, + rb_alloc, + rb_list, + rb_last_fence: 0, + waited: FxHashMap::default(), + runs: BTreeMap::new(), + scratch_runs: Vec::new(), + own_pages: Vec::new(), + mirrors: FxHashMap::default(), + mirror_src: FxHashMap::default(), + src_runs: BTreeMap::new(), + sources: &SOURCES, + fill: Vec::new(), + asks: Vec::new(), + remaps: Vec::new(), + later: VecDeque::new(), + fill_pages: fill_pages(), + mirrored: 0, + mirror_cap: mirror_cap(), + refused: FxHashSet::default(), + no_memory: None, + starved: Vec::new(), + counts: MirrorCounts::default(), + diag: ViewDiag::default(), + poison: None, + retry_pages: Vec::new(), + }; + + let (first, reused) = s.take_tile().expect("a tile from a new pool"); + assert!(!reused, "a new pool's tile needs no clearing"); + s.free.push(first); + s.retire_free_pools(); + assert_eq!(s.retired.len(), 1, "an all-free pool is retired"); + for round in 0..8 { + let (tile, reused) = s.take_tile().expect("a tile"); + assert!(reused, "round {round}: a tile of a retired pool is cleared before use"); + s.free.push(tile); + s.retire_free_pools(); + assert_eq!(s.retired.len(), 1, "round {round}: the retired pool was taken back, not a new one made"); + assert_eq!(s.pools.iter().filter(|p| p.is_some()).count(), 0, "round {round}"); + } + } + } + + /// A title frees its tiles in runs spread over all its pools: the pools of the freed runs go + /// back. With pools of 64 MiB none of these did (every pool kept the tiles still in use). + #[test] + fn pools_of_freed_runs_go_back() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + // 192 MiB of tiles, taken in order as a title's first commits take them + const TILES: usize = 3072; + let tiles: Vec<(u32, u32)> = (0..TILES).map(|_| s.take_tile().expect("a tile").0).collect(); + let made = s.pools.iter().filter(|p| p.is_some()).count(); + assert_eq!(made * POOL_TILES as usize, TILES, "the tiles fill whole pools"); + // of every 64 MiB the title keeps the first 4 MiB and frees the rest + let (mut kept, mut freed) = (0, 0); + for (i, &t) in tiles.iter().enumerate() { + if i % 1024 < 64 { + kept += 1; + } else { + s.free.push(t); + freed += 1; + } + } + s.retire_free_pools(); + let left = s.pools.iter().filter(|p| p.is_some()).count() * POOL_TILES as usize; + assert_eq!(s.free.len() + s.retired.len() * POOL_TILES as usize, freed, "every freed tile is free or its pool retired"); + assert!(left <= kept * 2, "{left} tiles of video memory stay in pools for {kept} tiles in use ({} MiB for {} MiB)", left * TILE >> 20, kept * TILE >> 20); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn aligned_tile_addresses_spread_across_hash_buckets() { + use std::hash::BuildHasher; + + let hasher = BuildHasherDefault::::default(); + let mut used = [false; 256]; + for tile in 0..used.len() { + let address = (1usize << 32) + tile * TILE; + let bucket = hasher.hash_one(address) as usize & (used.len() - 1); + used[bucket] = true; } + let occupied = used.iter().filter(|&&bucket| bucket).count(); + assert!(occupied >= used.len() / 2, "256 aligned addresses used {occupied} buckets"); } + /// Only the 64-byte chunks the CPU changed are sent again – the rest of the page may hold + /// what the GPU wrote. #[test] - fn coordinated_commit_orders_callbacks_and_owns_copied_staging() { - let (_, plan, observation, _) = coordinated_upload_fixture(1); - let reservations = UploadReservations::new(71, 1, 256, 64); - let calls = std::cell::RefCell::new(Vec::new()); - let receipt = plan.commit_reserved( - 71, 7, |_| Some(observation.clone()), &reservations, 0, 4, - |range, pages| { - calls.borrow_mut().push("copy"); - assert_eq!(range, UploadRingRange { start: 0, end: 4 }); - assert_eq!(pages[0].page, observation.page); - Ok::<_, ()>(vec![1, 2, 3, 4]) - }, - |staging, _| { - calls.borrow_mut().push("prepare"); - assert_eq!(&*staging.bytes, &[1, 2, 3, 4]); - Ok::<_, ()>(()) - }, - |staging, _| { - calls.borrow_mut().push("execute"); - assert_eq!(&*staging.bytes, &[1, 2, 3, 4]); - }, - || { calls.borrow_mut().push("signal"); Ok::<_, ()>(9) }, - ).unwrap(); - assert_eq!(&*calls.borrow(), &["copy", "prepare", "execute", "signal"]); - assert_eq!(reservations.complete(receipt), Ok(4)); + fn only_changed_chunks_are_sent() { + let mut page = vec![0u8; PAGE]; + let mut sent = ZERO_HASHES; + assert!(changed_chunks(&page, &mut sent).is_empty(), "a zero page is what the GPU has"); + page[10] = 1; + page[200] = 2; + page[255] = 3; + page[4000] = 4; + assert_eq!(changed_chunks(&page, &mut sent), vec![(0, 64), (192, 64), (3968, 64)]); + assert!(changed_chunks(&page, &mut sent).is_empty(), "nothing changed since"); + page[256] = 5; // next to the chunk at 192: one run + page[200] = 9; + assert_eq!(changed_chunks(&page, &mut sent), vec![(192, 128)]); } #[test] - fn coordinated_plan_preaccept_failures_stay_visible_and_takeover_revokes() { - for failure in ["validate", "reservation generation", "reserve", "copy", "size", "prepare"] { - let (batches, plan, observation, token) = coordinated_upload_fixture(1); - let reservations = UploadReservations::new(if failure == "reservation generation" { 72 } else { 71 }, 1, 256, 64); - let occupied = (failure == "reserve").then(|| reservations.reserve(0, 64).unwrap()); - let result = plan.commit_reserved( - if failure == "validate" { 72 } else { 71 }, 7, |_| Some(observation.clone()), - &reservations, 0, 64, - |_, _| if failure == "copy" { Err("copy") } else { Ok(vec![0; if failure == "size" { 63 } else { 64 }]) }, - |_, _| if failure == "prepare" { Err("prepare") } else { Ok(()) }, - |_, _| {}, || Ok::<_, &'static str>(9), - ); - let expected = match failure { - "validate" => matches!(result, Err(CoordinatedSparseUploadError::Invalid(UploadPlanInvalid::StateGeneration))), - "reservation generation" => matches!(result, Err(CoordinatedSparseUploadError::Reserve(UploadReservationError::StaleGeneration))), - "reserve" => matches!(result, Err(CoordinatedSparseUploadError::Reserve(UploadReservationError::SlotBusy))), - "copy" => matches!(result, Err(CoordinatedSparseUploadError::Copy("copy"))), - "size" => matches!(result, Err(CoordinatedSparseUploadError::StagingSize)), - _ => matches!(result, Err(CoordinatedSparseUploadError::Prepare("prepare"))), - }; - assert!(expected, "wrong {failure} boundary result"); - assert_eq!(batches.observe(1, 9), Ok(ClaimFrontierAction::TakeOver(token))); - assert!(!reservations.0.lock().unwrap().poisoned); - drop(occupied); - } + fn clean_chunks_take_gpu_copy_back_bytes() { + let mut page = vec![0x11u8; PAGE]; + let mut sent = Box::new(ZERO_HASHES); + changed_chunks(&page, &mut sent); + let mut slot = Some(sent); + let gpu = vec![0x22u8; 2 * CHUNK]; - let (batches, stale, observation, token) = coordinated_upload_fixture(1); - let replacement = batches.take_over(token, 2).unwrap(); - let result = commit_coordinated(stale, &observation, &UploadReservations::new(71, 1, 256, 64), 0, 9); - assert!(matches!(result, Err(CoordinatedSparseUploadError::Accept( - SparseBatchError::Frontier(ClaimFrontierError::StaleToken) - )))); - assert_eq!(replacement.pages()[0].0, 0x2_1000); + land_page(&mut slot, &mut page, CHUNK, &gpu, false); + + assert!(page[..CHUNK].iter().all(|&byte| byte == 0x11)); + assert!(page[CHUNK..3 * CHUNK].iter().all(|&byte| byte == 0x22)); + assert!(changed_chunks(&page, slot.as_deref_mut().unwrap()).is_empty(), "landed bytes were left dirty"); } #[test] - fn coordinated_submit_then_panic_poisons_both_generations() { - let (batches, plan, observation, _) = coordinated_upload_fixture(1); - let reservations = UploadReservations::new(71, 1, 256, 64); - let submitted = std::cell::Cell::new(false); - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let _ = plan.commit_reserved( - 71, 7, |_| Some(observation.clone()), &reservations, 0, 64, - |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), - |_, _| { submitted.set(true); panic!("execute panicked after submit") }, - || Ok::<_, ()>(9), - ); - })); - assert!(result.is_err() && submitted.get()); - assert!(reservations.0.lock().unwrap().poisoned); - assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); + fn dirty_chunks_survive_gpu_copy_back_and_upload_next() { + let mut page = vec![0x11u8; PAGE]; + let mut sent = Box::new(ZERO_HASHES); + changed_chunks(&page, &mut sent); + let old_dirty_hash = sent[1]; + let mut slot = Some(sent); + page[CHUNK..2 * CHUNK].fill(0x33); + let gpu = vec![0x22u8; 2 * CHUNK]; - let (batches, plan, observation, _) = coordinated_upload_fixture(1); - let reservations = UploadReservations::new(71, 1, 256, 64); - let result = plan.commit_reserved( - 71, 7, |_| Some(observation.clone()), &reservations, 0, 64, - |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), |_, _| {}, || Err::("signal"), - ); - assert!(matches!(result, Err(CoordinatedSparseUploadError::Signal("signal")))); - assert!(reservations.0.lock().unwrap().poisoned); - assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); + land_page(&mut slot, &mut page, CHUNK, &gpu, false); - let (batches, plan, observation, _) = coordinated_upload_fixture(1); - let reservations = UploadReservations::new(71, 1, 256, 64); - assert!(matches!(commit_coordinated(plan, &observation, &reservations, 0, 0), - Err(CoordinatedSparseUploadError::PublishReservation(UploadReservationError::State)))); - assert!(reservations.0.lock().unwrap().poisoned); - assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); + assert!(page[CHUNK..2 * CHUNK].iter().all(|&byte| byte == 0x33), "copy-back overwrote newer CPU bytes"); + assert_eq!(slot.as_ref().unwrap()[1], old_dirty_hash, "dirty chunk lost its last-sent hash"); + assert!(page[2 * CHUNK..3 * CHUNK].iter().all(|&byte| byte == 0x22), "clean neighbour did not land"); + assert_eq!(changed_chunks(&page, slot.as_deref_mut().unwrap()), vec![(CHUNK, CHUNK)]); } + /// A wait's cells and the write after it share a chunk (#3093, the test title's Wait32 / Wait64 + /// at +0x300 / +0x308 and Write32 at +0x310): the CPU wrote the cells, so the chunk changed, + /// and the GPU's own write still lands; the chunk keeps its old hash and uploads next. #[test] - fn coordinated_frontier_publication_failure_quarantines_submitted_reservation() { - let (batches, plan, _, _) = coordinated_upload_fixture(1); - let lease = plan.lease.unwrap(); - let batch = lease.accept().unwrap(); - let reservations = UploadReservations::new(71, 1, 256, 64); - let reservation = reservations.reserve(0, 64).unwrap(); - let mut accepted = AcceptedCoordinatedUpload::new(reservation, batch); - let receipt = accepted.reservation.take().unwrap().publish_after_accept(13).unwrap(); - accepted.batch_ledger.lock().unwrap().bindings.remove(&accepted.batch_token.epoch); - assert_eq!(accepted.batch.take().unwrap().receipt(13), Err(SparseBatchError::Corrupt)); - drop(accepted); - let ledger = reservations.0.lock().unwrap(); - assert!(ledger.poisoned); - assert_eq!(ledger.records[&receipt.token.serial].state, UploadReservationState::Poisoned); - drop(ledger); - let ledger = batches.ledger.lock().unwrap(); - assert!(ledger.poisoned && ledger.work.claims.is_empty() && ledger.work.owners.is_empty()); - assert!(ledger.bindings.is_empty()); + fn gpu_written_bytes_land_in_a_chunk_the_cpu_changed() { + let mut page = vec![0u8; PAGE]; + let mut sent = Box::new(ZERO_HASHES); + changed_chunks(&page, &mut sent); + let old_hash = sent[0x300 / CHUNK]; + let mut slot = Some(sent); + page[0x300..0x304].copy_from_slice(&0xDEAD_00AAu32.to_le_bytes()); + page[0x308..0x310].copy_from_slice(&0x0000_0003_0000_0000u64.to_le_bytes()); + + land_page(&mut slot, &mut page, 0x310, &0x55AA_55AAu32.to_le_bytes(), true); + + assert_eq!(page[0x310..0x314], 0x55AA_55AAu32.to_le_bytes(), "the GPU's write was dropped"); + assert_eq!(page[0x300..0x304], 0xDEAD_00AAu32.to_le_bytes(), "the CPU's cells were overwritten"); + assert_eq!(page[0x308..0x310], 0x0000_0003_0000_0000u64.to_le_bytes()); + assert_eq!(slot.as_ref().unwrap()[0x300 / CHUNK], old_hash, "the changed chunk lost its last-sent hash"); + assert_eq!(changed_chunks(&page, slot.as_deref_mut().unwrap()), vec![(0x300, CHUNK)]); + } + + /// `scan_page` leaves published hashes unchanged, skips allocation for zero pages, and + /// coalesces adjacent dirty chunks. + #[test] + fn scan_page_plans_without_publishing_and_coalesces() { + let mut page = vec![0u8; PAGE]; + let slot: Option> = None; + let mut out = Vec::new(); + scan_page(&page, 0x1_0000, &slot, &mut out); + assert!(slot.is_none(), "all-zero page must not allocate hash box"); + assert!(out.is_empty()); + + page[PAGE - 64] = 0xAA; + scan_page(&page, 0x1_0000, &slot, &mut out); + assert!(slot.is_none(), "planning must not publish a last-sent hash"); + assert_eq!(out, vec![(0x1_0FC0, 64)]); + + // Adjacent chunk at the start of the next page coalesces into a single run. + let mut next = vec![0u8; PAGE]; + next[0] = 0xBB; + let next_slot: Option> = None; + scan_page(&next, 0x1_1000, &next_slot, &mut out); + assert_eq!(out, vec![(0x1_0FC0, 128)]); + } + + #[test] + fn hash_plan_is_published_only_when_applied() { + let base = 0x2_0000; + let mut mapped = FxHashMap::default(); + mapped.insert(base, TileEntry::with_holes((0, 0), 0)); + let mut prefix = Vec::new(); + append_hash_updates(base + CHUNK, &[1; CHUNK], &mut prefix); + let mut suffix = Vec::new(); + append_hash_updates(base + PAGE + 2 * CHUNK, &[2; CHUNK], &mut suffix); + assert!(mapped[&base].sent[0].is_none()); + assert!(mapped[&base].sent[1].is_none()); + publish_hash_updates(&mut mapped, &prefix); + assert_eq!(mapped[&base].sent[0].as_ref().unwrap()[1], chunk_hash(&[1; CHUNK])); + assert!(mapped[&base].sent[1].is_none(), "an unacknowledged suffix was published"); + publish_hash_updates(&mut mapped, &suffix); + assert_eq!(mapped[&base].sent[1].as_ref().unwrap()[2], chunk_hash(&[2; CHUNK])); } #[test] - fn a_prior_poison_does_not_leave_later_accepted_work_owned() { - let batches = SparseBatches::new(71); - assert!(batches.add_dirty_pages([0x3_1000, 0x3_2000])); - let first = batches.seal(1, 1).unwrap().unwrap().accept().unwrap(); - let second = batches.seal(2, 1).unwrap().unwrap().accept().unwrap(); - let reservations = UploadReservations::new(71, 2, 256, 64); - let first = AcceptedCoordinatedUpload::new(reservations.reserve(0, 64).unwrap(), first); - let second = AcceptedCoordinatedUpload::new(reservations.reserve(1, 64).unwrap(), second); - drop(first); - assert!(matches!(second.publish(17), Err(CoordinatedPublishError::Batch(SparseBatchError::Poisoned)))); - let ledger = batches.ledger.lock().unwrap(); - assert!(ledger.poisoned && ledger.work.claims.is_empty() && ledger.work.owners.is_empty()); - assert!(ledger.bindings.is_empty()); - drop(ledger); - let reservations = reservations.0.lock().unwrap(); - assert!(reservations.poisoned && reservations.records.values().all(|r| r.state == UploadReservationState::Poisoned)); + fn cpu_write_after_planning_is_dirty_after_receipt_publication() { + let base = 0x3_0000; + let mut mapped = FxHashMap::default(); + mapped.insert(base, TileEntry::with_holes((0, 0), 0)); + let mut page = vec![0u8; PAGE]; + page[0] = 1; + let staged = page[..CHUNK].to_vec(); + let mut planned = Vec::new(); + append_hash_updates(base, &staged, &mut planned); + page[0] = 2; + publish_hash_updates(&mut mapped, &planned); + + let mut runs = Vec::new(); + scan_page(&page, base, &mapped[&base].sent[0], &mut runs); + assert_eq!(runs, [(base, CHUNK)]); } #[test] - fn coordinated_receipts_publish_exact_out_of_order_fence_prefix() { - let batches = SparseBatches::new(71); - assert!(batches.add_dirty_pages([0x2_1000, 0x2_2000])); - let observation = |page| upload_observation(page, (4, 9), 0xA5); - let first_lease = batches.seal(1, 1).unwrap().unwrap(); - let first_token = first_lease.token; - let second_lease = batches.seal(2, 1).unwrap().unwrap(); - let through = batches.through().unwrap(); - let first = CoordinatedSparseUploadPlan::build(first_lease, 71, 7, |page| Some(observation(page))).unwrap(); - let second = CoordinatedSparseUploadPlan::build(second_lease, 71, 7, |page| Some(observation(page))).unwrap(); - let reservations = UploadReservations::new(71, 2, 256, 64); - let second_receipt = commit_coordinated(second, &observation(0x2_2000), &reservations, 1, 11).unwrap(); - assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::TakeOver(first_token))); - let first_receipt = commit_coordinated(first, &observation(0x2_1000), &reservations, 0, 8).unwrap(); - assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::Ready { through, required_fence: Some(11) })); - assert_eq!(reservations.complete(first_receipt), Ok(0)); - assert_eq!(reservations.complete(second_receipt), Ok(128)); + fn batch_hash_plan_is_bounded_by_staging() { + assert_eq!(MAX_BATCH_HASH_UPDATES, STAGING / CHUNK); + assert_eq!(MAX_BATCH_HASH_UPDATES * std::mem::size_of::(), STAGING / 4); + assert!(!batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES - 1, CHUNK)); + assert!(batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES, CHUNK)); + assert!(batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES / 2 + 1, STAGING / 2)); } #[test] - fn upload_reservations_reclaim_only_a_contiguous_retired_prefix() { - let reservations = UploadReservations::new(41, 2, 256, 64); - let first = reservations.reserve(0, 80).unwrap(); - let second = reservations.reserve(1, 80).unwrap(); - assert_eq!(first.range(), UploadRingRange { start: 0, end: 80 }); - assert_eq!(second.range(), UploadRingRange { start: 128, end: 208 }); - let first = first.submit(5).unwrap(); - let second = second.submit(6).unwrap(); - - assert_eq!(reservations.complete(second), Ok(0), "later retirement crossed an older owner"); - assert!(matches!(reservations.reserve(1, 64), Err(UploadReservationError::Full))); - assert_eq!(reservations.complete(first), Ok(208)); + fn prepared_dirty_batch_keeps_exact_hash_plan_and_rollback_point() { + let mut batch = PreparedDirtyBatch::new(3, 0x12_3400); + let bytes = [0xA5; 2 * CHUNK]; + batch.append_hashes(0x20_0000, &bytes); + assert_eq!(batch.slot, 3); + assert_eq!(batch.ring_start, 0x12_3400); + assert_eq!(batch.updates.len(), 2); + assert_eq!(batch.updates[0], HashUpdate { at: 0x20_0000, hash: chunk_hash(&bytes[..CHUNK]) }); + assert_eq!(batch.updates[1], HashUpdate { at: 0x20_0000 + CHUNK, hash: chunk_hash(&bytes[CHUNK..]) }); + assert!(!batch.hash_plan_would_overflow(CHUNK)); - let wrapped = reservations.reserve(1, 64).unwrap(); - assert_eq!(wrapped.range(), UploadRingRange { start: 256, end: 320 }); - assert_eq!(wrapped.submit(7).and_then(|receipt| reservations.complete(receipt)), Ok(320)); + let storage = batch.updates.as_ptr(); + let capacity = batch.updates.capacity(); + for index in 0..3 { + batch.clear_after_submit(); + batch = batch.reopen(4 + index, 0x20_0000 + index as u64 * PAGE as u64); + batch.append_hashes(0x30_0000, &bytes); + assert_eq!(batch.updates.as_ptr(), storage, "batch {index} replaced its hash-plan allocation"); + assert_eq!(batch.updates.capacity(), capacity); + } } #[test] - fn an_empty_ring_discards_tail_padding_before_a_full_capacity_reservation() { - let reservations = UploadReservations::new(42, 1, 256, 64); - drop(reservations.reserve(0, 64).unwrap()); - { - let ledger = reservations.0.lock().unwrap(); - assert_eq!((ledger.cursor, ledger.reclaimed), (64, 64)); - } + fn prepared_dirty_copy_splits_at_windows_and_ring_wrap() { + let window = 4 * PAGE; + let base = 0x10_0000; + let first = prepare_dirty_copy(base + window - CHUNK, 2 * CHUNK, base, window, 0, 8 * PAGE); + assert_eq!(first, PreparedDirtyCopy { + ring_start: 0, + staging_offset: 0, + window_offset: window - CHUNK, + bytes: CHUNK, + }); + let second = prepare_dirty_copy(base + window, CHUNK, base + window, window, CHUNK as u64, 8 * PAGE); + assert_eq!(second.window_offset, 0); + assert_eq!(second.bytes, CHUNK); - let full = reservations.reserve(0, 256).unwrap(); - assert_eq!(full.range(), UploadRingRange { start: 256, end: 512 }); - let ledger = reservations.0.lock().unwrap(); - assert_eq!((ledger.cursor, ledger.reclaimed), (512, 256)); + let cap = 8 * PAGE; + let wrapped = prepare_dirty_copy(base, PAGE, base, window, (cap - 512) as u64, cap); + assert_eq!(wrapped.ring_start, cap as u64); + assert_eq!(wrapped.staging_offset, 0); + assert_eq!(wrapped.bytes, PAGE); } + /// Ring-buffer planner keeps every chunk contiguous, 64-byte aligned, <= cap/2, and splits + /// cleanly across the end of the ring buffer without wrapping mid-copy. #[test] - fn failed_empty_ring_reservation_does_not_publish_boundary_normalization() { - let mut ledger = UploadReservationLedger::new(42, 1, 256, 64); - let token = ledger.reserve(42, 0, 64).unwrap().0; - assert_eq!(ledger.cancel(token), Ok(64)); - ledger.next_serial = u64::MAX; - - assert!(matches!(ledger.reserve(42, 0, 256), Err(UploadReservationError::Exhausted))); - assert_eq!((ledger.cursor, ledger.reclaimed), (64, 64)); - assert_eq!(ledger.next_serial, u64::MAX); - assert!(ledger.order.is_empty()); - assert!(ledger.records.is_empty()); - assert!(ledger.slots[0].is_none()); + fn ring_planner_handles_wrap_and_large_chunks() { + let cap = 64 << 20; + // Normal aligned chunk + let (a, n) = plan_ring_chunk(0, 4096, cap); + assert_eq!((a, n), (0, 4096)); + // Unaligned cursor aligns up to 64 + let (a, n) = plan_ring_chunk(17, 256, cap); + assert_eq!((a, n), (64, 256)); + // Oversized chunk capped at cap / 2 + let (a, n) = plan_ring_chunk(0, cap * 2, cap); + assert_eq!((a, n), (0, cap / 2)); + // Near end of ring with >= 4 KiB left: shrinks to fill tail + let near = (cap - 8192) as u64; + let (a, n) = plan_ring_chunk(near, 16384, cap); + assert_eq!((a, n), (near, 8192)); + assert_eq!((a as usize % cap) + n, cap); + // Tiny tail (< 4 KiB): wraps cleanly to 0 of next cycle + let tiny = (cap - 512) as u64; + let (a, n) = plan_ring_chunk(tiny, 4096, cap); + assert_eq!((a, n), (cap as u64, 4096)); + assert_eq!(a as usize % cap, 0); } + /// `query_tile_holes` marks reserved, free, and `PAGE_NOACCESS` pages as holes while clearing + /// bits only for committed, accessible 4 KiB pages. #[test] - fn cancelling_an_older_reservation_never_rewinds_newer_ring_work() { - let reservations = UploadReservations::new(43, 3, 512, 64); - let first = reservations.reserve(0, 64).unwrap(); - let middle = reservations.reserve(1, 64).unwrap(); - let third = reservations.reserve(2, 64).unwrap(); - let middle_token = middle.token.unwrap(); - drop(middle); - assert_eq!(reservations.0.lock().unwrap().reclaimed, 0); + fn query_tile_holes_detects_reserved_noaccess_and_committed_pages() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; - let later = reservations.reserve(1, 64).unwrap(); - assert!(later.range().start >= third.range().end, "a cancellation rewound across newer work"); - drop(first); - assert_eq!(reservations.0.lock().unwrap().reclaimed, 128); - assert_eq!(reservations.0.lock().unwrap().cancel(middle_token), Err(UploadReservationError::Missing)); + unsafe { + // SAFETY: Reserving 2 tiles (128 KiB) with VirtualAlloc returns a 64 KiB-aligned VA. + let base = VirtualAlloc(std::ptr::null(), 2 * TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert!(base != 0 && base % TILE == 0); - let third = third.submit(8).unwrap(); - assert_eq!(reservations.complete(UploadSubmissionReceipt { fence: 9, ..third }), Err(UploadReservationError::Fence)); - assert_eq!(reservations.complete(third), Ok(192)); - drop(later); - assert_eq!(reservations.0.lock().unwrap().reclaimed, 256); - } + // Initially every page in both reserved tiles is a hole. + assert_eq!(query_tile_holes(base), 0xFFFF); + assert_eq!(query_tile_holes(base + TILE), 0xFFFF); - #[test] - fn dropped_reservation_cancels_exactly_it_and_signal_failure_poisons_reuse() { - let reservations = UploadReservations::new(47, 2, 256, 64); - let abandoned = reservations.reserve(0, 64).unwrap(); - let stale = abandoned.token.unwrap(); - drop(abandoned); - assert_eq!(reservations.0.lock().unwrap().reclaimed, 64); - assert_eq!(reservations.0.lock().unwrap().cancel(stale), Err(UploadReservationError::Missing)); + // Commit pages 4..8 as PAGE_READWRITE and page 9 as PAGE_NOACCESS. + let p4 = VirtualAlloc((base + 4 * PAGE) as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE); + assert!(!p4.is_null()); + let p9 = VirtualAlloc((base + 9 * PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_NOACCESS); + assert!(!p9.is_null()); - let poisoned = reservations.reserve(0, 64).unwrap(); - poisoned.poison().unwrap(); - let ledger = reservations.0.lock().unwrap(); - assert!(ledger.poisoned); - assert_eq!(ledger.slots[0], Some(2), "poison released an allocator with untracked GPU work"); - drop(ledger); - assert!(matches!(reservations.reserve(1, 64), Err(UploadReservationError::Poisoned))); + // Only bits 4..8 are cleared; reserved [0..4), PAGE_NOACCESS [9], and reserved [10..16) remain holes. + assert_eq!(query_tile_holes(base), 0xFFFF & !(0b1111u16 << 4)); + assert_eq!(query_tile_holes(base + TILE), 0xFFFF); + + // Commit pages 0..4 and confirm bits 0..4 clear too. + let p0 = VirtualAlloc(base as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE); + assert!(!p0.is_null()); + assert_eq!(query_tile_holes(base), 0xFF00); + + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + // Released (MEM_FREE) memory reports all holes. + assert_eq!(query_tile_holes(base), 0xFFFF); + } } + /// Mapping tiles for a placed buffer over partially-committed/reserved memory must preserve + /// uncommitted hole bits so `readback_ranges` does not access-violate, + /// and later commits clear those hole bits so subsequent writes scan cleanly. #[test] - fn upload_reservation_bounds_generation_and_monotonic_overflow_fail_closed() { - let mut ledger = UploadReservationLedger::new(53, 1, 256, 64); - assert!(matches!(ledger.reserve(52, 0, 64), Err(UploadReservationError::StaleGeneration))); - assert!(matches!(ledger.reserve(53, 1, 0), Err(UploadReservationError::Slot))); - assert!(matches!(ledger.reserve(53, 0, 0), Err(UploadReservationError::Empty))); - assert!(matches!(ledger.reserve(53, 0, 257), Err(UploadReservationError::TooLarge))); + fn ensure_mapped_with_query_holes_skips_uncommitted_pages_on_readback() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.expect("D3D12 device"); + + // Reserve 2 tiles; commit only [base + 0x4000, base + 0x8000) to simulate a + // non-64KiB-aligned placed buffer with uncommitted prefix [base, base + 0x4000) and + // uncommitted second tile [base + TILE, base + 2*TILE). + let base = VirtualAlloc(std::ptr::null(), 2 * TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert!(base != 0 && base % TILE == 0); + assert!(!VirtualAlloc((base + 4 * PAGE) as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + + let mut reserved: Option = None; + dev.CreateReservedResource(&buffer_desc((2 * TILE) as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved) + .expect("CreateReservedResource"); + let reserved = reserved.expect("reserved buffer"); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); + let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("rb_alloc"); + let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); + rb_list.Close().expect("rb_list close"); - ledger.cursor = u64::MAX - 31; - assert!(matches!(ledger.reserve(53, 0, 64), Err(UploadReservationError::Exhausted))); - ledger.cursor = 0; - ledger.next_serial = u64::MAX; - assert!(matches!(ledger.reserve(53, 0, 64), Err(UploadReservationError::Exhausted))); - assert!(ledger.records.is_empty()); - assert!(ledger.order.is_empty()); - assert!(ledger.slots[0].is_none()); - } + let readbacks = Arc::new(SharedReadbacks::new(rb_fence.clone(), None)); + let rb_submit = Arc::new(Mutex::new(RbSubmit::new(dev.clone()))); + let mut s = State { + generation: 1, + mapping_epoch: 0, + coordination: SparseCoordination::new(1, 1).unwrap(), + dev, + queue, + fence, + value: 0, + event, + rb_fence, + rb_value: 0, + rbq: None, + rbq_value: 0, + readbacks, + rb_submit, + windows: vec![(base, reserved)], + pools: Vec::new(), + free: FreePools::new(), + cooling: VecDeque::new(), + retired: Vec::new(), + retire_tried: std::time::Instant::now(), + mapped: FxHashMap::default(), + pinned: FxHashMap::default(), + parked: FxHashMap::default(), + kept: FxHashMap::default(), + pending: Vec::new(), + quarantined: VecDeque::new(), + queue_fences: FxHashMap::default(), + buffers: FxHashMap::default(), + to_zero: BTreeSet::new(), + staging: None, + ring_write: 0, + ring_submitted: 0, + ring_free: 0, + inflight: VecDeque::new(), + uploads_ordered: true, + zero_buf: None, + slots: Vec::new(), + next_slot: 0, + readback: None, + rb_alloc, + rb_list, + rb_last_fence: 0, + waited: FxHashMap::default(), + runs: BTreeMap::new(), + scratch_runs: Vec::new(), + own_pages: Vec::new(), + mirrors: FxHashMap::default(), + mirror_src: FxHashMap::default(), + src_runs: BTreeMap::new(), + sources: &SOURCES, + fill: Vec::new(), + asks: Vec::new(), + remaps: Vec::new(), + later: VecDeque::new(), + fill_pages: fill_pages(), + mirrored: 0, + mirror_cap: mirror_cap(), + refused: FxHashSet::default(), + no_memory: None, + starved: Vec::new(), + counts: MirrorCounts::default(), + diag: ViewDiag::default(), + poison: None, + retry_pages: Vec::new(), + }; - #[test] - fn a_failed_title_queue_wait_rolls_back_only_its_reservation() { - let mut waited = FxHashMap::from_iter([(1, 4), (2, 7)]); - assert!(reserve_queue_wait(&mut waited, 1, 5)); - rollback_queue_wait(&mut waited, 1, 5, Some(4)); - assert_eq!(waited, FxHashMap::from_iter([(1, 4), (2, 7)])); - rollback_queue_wait(&mut waited, 1, 9, None); - assert_eq!(waited.get(&1), Some(&4), "a stale failure changed a newer reservation"); - } + // Mirrors `place_buffer`: map both tiles probing real OS page commitment. + s.ensure_mapped(base, 2 * TILE, |t| { + let holes = query_tile_holes(t); + (holes, !holes) + }); + assert_eq!(s.mapped[&base].holes, 0xFF0F, "uncommitted prefix and suffix pages must stay holes"); + assert_eq!(s.mapped[&(base + TILE)].holes, 0xFFFF, "fully reserved tile must have all 16 holes set"); - #[test] - fn quarantine_uses_installed_retirement_marks_and_fails_closed_without_one() { - use std::sync::Arc; - let own = Arc::new(1u32); - let retired = Arc::new(2u32); - let marks = initial_quarantine_marks((own.clone(), 3), &[(retired.clone(), 4)], false).unwrap(); - assert_eq!(marks.iter().map(|(_, value)| *value).collect::>(), [3, 4]); - drop(retired); - assert_eq!(Arc::strong_count(&marks[1].0), 1, "batch did not own the retirement marker"); - assert!(initial_quarantine_marks((own, 3), &[(marks[1].0.clone(), 4)], true).is_none(), "Preparing/Failed reused tiles without a completion source"); - } + // Reading back the full 2-tile span must not fault on uncommitted pages. + s.readback_ranges(&[(base, 2 * TILE)], false); - /// A block freed on one thread while another allocates: its address goes back to the - /// windows only once it is decommitted (released first, the decommit came after another - /// thread had the same address again: that thread's writes faulted). - #[test] - fn a_freed_block_is_decommitted_before_its_address_is_reused() { - if crate::gpu::uma::get().is_none_or(|u| !u.has_sparse()) { - return; - } - let threads: Vec<_> = (0..4) - .map(|_| { - std::thread::spawn(|| unsafe { - for i in 0..2000u64 { - let Some((p, n)) = alloc(TILE, TILE) else { continue }; - std::ptr::write_volatile(p as *mut u64, i); - std::ptr::write_volatile((p + n - 8) as *mut u64, i); - assert_eq!(std::ptr::read_volatile(p as *const u64), i); - assert!(free(p)); - } - }) - }) - .collect(); - for t in threads { - t.join().unwrap(); - } - } + // Now incrementally commit [base, base + 4*PAGE) and clear its hole bits (as `committed` does). + assert!(!VirtualAlloc(base as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + let entry = s.mapped.get_mut(&base).unwrap(); + for i in 0..4 { + entry.holes &= !(1u16 << i); + } + assert_eq!(entry.holes, 0xFF00); - /// `f` on another thread while this one holds the sparse state (as `before_execute` does - /// around its D3D12 calls, which can wait for that thread): did `f` finish without waiting - /// for the state? The thread runs before the state is taken, so its start is not timed. - fn returns_while_the_state_is_held(f: impl FnOnce() + Send + 'static) -> bool { - let (ready_tx, ready_rx) = std::sync::mpsc::channel(); - let (go_tx, go_rx) = std::sync::mpsc::channel::<()>(); - let (tx, rx) = std::sync::mpsc::channel(); - let t = std::thread::spawn(move || { - let _ = ready_tx.send(()); - let _ = go_rx.recv(); - f(); - let _ = tx.send(()); - }); - ready_rx.recv().unwrap(); - let held = STATE.lock().unwrap(); - go_tx.send(()).unwrap(); - let done = rx.recv_timeout(std::time::Duration::from_secs(5)); - drop(held); - let joined = t.join(); - assert!(joined.is_ok(), "the thread panicked: {joined:?}"); - done.is_ok() - } + // Writing to the newly committed page is detected by `scan_page`. + *(base as *mut u8) = 0x5A; + let mut dirty = Vec::new(); + let page0 = std::slice::from_raw_parts(base as *const u8, PAGE); + scan_page(page0, base, &entry.sent[0], &mut dirty); + assert_eq!(dirty, vec![(base, CHUNK)]); - /// A placed buffer released while another thread holds the sparse state: the release does - /// not wait for the state, and the next `lock_state` lets the buffer go. - #[test] - fn a_buffer_released_while_the_state_is_held_does_not_wait_for_it() { - const RES: usize = 0x7ff0_dead_0000; - assert!(returns_while_the_state_is_held(|| forget_buffer(RES)), "forget_buffer waited for the sparse state's lock"); - drop(lock_state()); - assert!(!FORGOTTEN.lock().unwrap().contains(&RES)); + s.wait_for(s.value); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } } - - /// Freeing the last tile in use of a pool and taking a tile again takes the retired pool - /// back, not a new heap each time (#913: 288 pools of 64 MB, 18 GB asked of a 12 GB card). + /// A tile decommitted and committed again before the next submit gets its pool tile back + /// with no new tile mapping (cleared instead). One that is not is unmapped and freed by + /// `flush_parked` (before a submit), or when the free list runs out; a placed buffer's + /// release does not free it while it is parked. #[test] - fn a_pool_retired_a_moment_ago_is_taken_back() { + fn a_tile_decommitted_and_committed_again_keeps_its_video_memory() { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::*; + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); let mut dev: Option = None; if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { - let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); } let dev = dev.expect("D3D12 device"); + let base = VirtualAlloc(std::ptr::null(), 2 * TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert!(base != 0 && base % TILE == 0); + let mut reserved: Option = None; + dev.CreateReservedResource(&buffer_desc((2 * TILE) as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved) + .expect("CreateReservedResource"); + let reserved = reserved.expect("reserved buffer"); let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); @@ -5913,6 +10749,9 @@ mod tests { let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("rb_alloc"); let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); rb_list.Close().expect("rb_list close"); + + let readbacks = Arc::new(SharedReadbacks::new(rb_fence.clone(), None)); + let rb_submit = Arc::new(Mutex::new(RbSubmit::new(dev.clone()))); let mut s = State { generation: 1, mapping_epoch: 0, @@ -5924,17 +10763,25 @@ mod tests { event, rb_fence, rb_value: 0, - windows: Vec::new(), + rbq: None, + rbq_value: 0, + readbacks, + rb_submit, + windows: vec![(base, reserved)], pools: Vec::new(), - free: Vec::new(), + free: FreePools::new(), + cooling: VecDeque::new(), retired: Vec::new(), - parked: FxHashMap::default(), + retire_tried: std::time::Instant::now(), mapped: FxHashMap::default(), pinned: FxHashMap::default(), + parked: FxHashMap::default(), + kept: FxHashMap::default(), + pending: Vec::new(), quarantined: VecDeque::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), - to_zero: Vec::new(), + to_zero: BTreeSet::new(), staging: None, ring_write: 0, ring_submitted: 0, @@ -5949,1160 +10796,2771 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), - runs: None, + runs: BTreeMap::new(), scratch_runs: Vec::new(), + own_pages: Vec::new(), + mirrors: FxHashMap::default(), + mirror_src: FxHashMap::default(), + src_runs: BTreeMap::new(), + sources: &SOURCES, + fill: Vec::new(), + asks: Vec::new(), + remaps: Vec::new(), + later: VecDeque::new(), + fill_pages: fill_pages(), + mirrored: 0, + mirror_cap: mirror_cap(), + refused: FxHashSet::default(), + no_memory: None, + starved: Vec::new(), + counts: MirrorCounts::default(), + diag: ViewDiag::default(), + poison: None, retry_pages: Vec::new(), }; - let (first, reused) = s.take_tile().expect("a tile from a new pool"); - assert!(!reused, "a new pool's tile needs no clearing"); - s.free.push(first); - s.retire_free_pools(); - assert_eq!(s.retired.len(), 1, "an all-free pool is retired"); - for round in 0..8 { - let (tile, reused) = s.take_tile().expect("a tile"); - assert!(reused, "round {round}: a tile of a retired pool is cleared before use"); - s.free.push(tile); - s.retire_free_pools(); - assert_eq!(s.retired.len(), 1, "round {round}: the retired pool was taken back, not a new one made"); - assert_eq!(s.pools.iter().filter(|p| p.is_some()).count(), 0, "round {round}"); + s.commit_range(base, TILE); + let tile = s.mapped[&base].pool; + assert_eq!(s.pending, vec![base], "a new tile's mapping waits for the next flush"); + assert_eq!(s.value, 0, "nothing sent yet"); + s.flush_pending(); + assert!(s.pending.is_empty()); + let v = s.value; + assert!(v > 0, "a new tile is mapped"); + mark_protection(&mut s.mapped, base + PAGE, PAGE, false); + assert_eq!(s.mapped[&base].not_rw, 1 << 1); + + // decommitted: parked, still mapped, nothing sent to the GPU + s.decommit_range(base, TILE); + assert!(!s.mapped.contains_key(&base)); + assert_eq!(s.parked.get(&base), Some(&tile)); + assert!(!s.free.contains(&tile)); + assert_eq!(s.value, v, "no tile mapping changed"); + s.release_if_unused(base, tile); + assert!(!s.free.contains(&tile) && s.cooling.is_empty(), "a parked tile is not free"); + + assert!(s.runs.is_empty() && runs_of(&s).is_empty()); + // committed again: the same tile, cleared, no new mapping + s.to_zero.clear(); + let gen = mapped_gen(); + s.commit_range(base, TILE); + assert_eq!(s.runs, BTreeMap::from([(base, base + TILE)])); + assert_eq!(s.mapped[&base].pool, tile); + assert_eq!(s.mapped[&base].holes, 0); + assert_eq!(s.mapped[&base].not_rw, 0, "recommitted pages use their commit protection"); + assert!(s.parked.is_empty()); + assert_eq!(s.to_zero, BTreeSet::from([(base, TILE)])); + assert_eq!(s.value, v, "no tile mapping changed"); + assert!(mapped_gen() > gen, "readers of `mapped` see it changed"); + mark_protection(&mut s.mapped, base + 2 * PAGE, PAGE, false); + s.decommit_range(base + 2 * PAGE, PAGE); + s.commit_range(base + 2 * PAGE, PAGE); + assert_eq!(s.mapped[&base].not_rw, 0, "a partially recommitted page is writable again"); + s.decommit_range(base + 3 * PAGE, PAGE); + s.commit_range_with_protection(base + 3 * PAGE, PAGE, false); + assert_eq!(s.mapped[&base].not_rw, 1 << 3, "commit and protection publish as one record update"); + s.commit_range(base + 3 * PAGE, PAGE); + + // decommitted and flushed (as before a submit): unmapped and quarantined until the + // unmap fence completes, then cooling, not free yet + s.decommit_range(base, TILE); + assert!(s.flush_parked()); + assert!(s.parked.is_empty()); + assert!(s.quarantined.iter().any(|b| b.tiles.contains(&tile))); + assert!(!s.cooling.iter().any(|c| c.0 == tile) && !s.free.contains(&tile)); + assert!(s.value > v, "the unmapping is sent"); + assert!(!s.flush_parked(), "nothing left to flush"); + s.wait_for(s.value); + assert!(s.drain_quarantined()); + assert!(s.cooling.iter().any(|c| c.0 == tile) && !s.free.contains(&tile)); + + // no free tile left: neither the parked tile (mapped at its address until the next + // flush) nor the one cooling is taken for the next commit, but a new pool's. Before, + // the parked one was unmapped and taken at once. + s.commit_range(base, TILE); + let parked = s.mapped[&base].pool; + assert_ne!(parked, tile, "the cooling tile is not taken"); + s.decommit_range(base, TILE); + s.free.clear(); + s.commit_range(base + TILE, TILE); + assert_eq!(s.parked.get(&base), Some(&parked), "still parked"); + let tile = s.mapped[&(base + TILE)].pool; + assert_ne!(tile.0, parked.0, "a tile of a new pool"); + assert!(!s.mapped.contains_key(&base)); + assert!(s.flush_parked()); + assert!(!s.cooling.iter().any(|c| c.0 == parked), "unmapped at the flush, quarantined"); + s.wait_for(s.value); + assert!(s.drain_quarantined()); + assert_eq!(s.cooling.back().map(|c| c.0), Some(parked), "unmapped at the flush, then cooling"); + + // a placed buffer uses the tile: the window keeps it when it is decommitted and + // flushed, memory committed there again is the buffer's, and it is free only once + // the buffer is gone and it was decommitted + *s.pinned.entry(tile).or_default() += 1; + let at = base + TILE; + assert!(s.pending.contains(&at), "its mapping is not sent yet"); + s.decommit_range(at, TILE); + assert!(!s.flush_parked(), "nothing to unmap"); + assert_eq!(s.kept.get(&at), Some(&tile)); + assert!(!s.free.contains(&tile)); + // kept before its mapping was sent: that stays pending, and the commit that takes the + // tile back sends it + let v = s.value; + s.flush_pending(); + assert_eq!((s.value, &s.pending), (v, &vec![at]), "no mapping of a kept tile"); + s.commit_range(at, TILE); + s.flush_pending(); + assert!(s.value > v && s.pending.is_empty(), "mapped with the commit"); + s.decommit_range(at, TILE); + assert!(!s.flush_parked(), "nothing to unmap"); + assert_eq!(s.kept.get(&at), Some(&tile)); + let v = s.value; + s.to_zero.clear(); + s.commit_range(at, TILE); + assert_eq!(s.mapped[&at].pool, tile, "the buffer's tile"); + assert_eq!(s.to_zero, BTreeSet::from([(at, TILE)])); + assert_eq!(s.value, v, "no tile mapping changed"); + s.decommit_range(at, TILE); + assert!(!s.flush_parked()); + s.pinned.remove(&tile); + s.release_if_unused(at, tile); + assert!(s.kept.is_empty() && !s.cooling.iter().any(|c| c.0 == tile)); + assert!(s.flush_parked()); + s.wait_for(s.value); + assert!(s.drain_quarantined()); + assert!(s.cooling.iter().any(|c| c.0 == tile) && !s.free.contains(&tile)); + + assert_eq!(s.runs, runs_of(&s)); + // committed and decommitted again before a flush: no mapping is sent for it + s.flush_pending(); + s.flush_parked(); + let v = s.value; + s.commit_range(base, TILE); + assert_eq!(s.pending, vec![base]); + s.decommit_range(base, TILE); + s.flush_pending(); // as for an upload or readback before the title's next submit + assert_eq!(s.value, v, "a tile gone before the flush is not mapped"); + assert_eq!(s.pending, vec![base], "parked, its mapping never sent: still pending"); + // taken back from `parked`: the flush now sends its mapping + s.commit_range(base, TILE); + s.flush_pending(); + assert!(s.pending.is_empty()); + assert!(s.value > v, "a tile parked before its mapping was sent is mapped"); + + // neighbours are one run, a tile taken out of it leaves the other + s.commit_range(base, 2 * TILE); + assert_eq!(s.runs, BTreeMap::from([(base, base + 2 * TILE)])); + s.decommit_range(base, TILE); + assert_eq!(s.runs, BTreeMap::from([(base + TILE, base + 2 * TILE)])); + s.decommit_range(base + TILE, PAGE); + assert_eq!(s.runs, runs_of(&s), "a tile with pages left stays"); + s.flush_pending(); + + s.wait_for(s.value); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + struct SignalOnDrop(ID3D12Fence, u64); + + impl Drop for SignalOnDrop { + fn drop(&mut self) { + unsafe { + let _ = self.0.Signal(self.1); } } } - /// A title frees its tiles in runs spread over all its pools: the pools of the freed runs go - /// back. With pools of 64 MiB none of these did (every pool kept the tiles still in use). + unsafe fn test_state_with_reserved(tiles: usize) -> (usize, State) { + use windows_sys::Win32::System::Memory::MEM_RESERVE; + + let dev = test_device(); + let base = VirtualAlloc(std::ptr::null(), tiles * TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert!(base != 0 && base % TILE == 0); + let mut reserved: Option = None; + dev.CreateReservedResource(&buffer_desc((tiles * TILE) as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved) + .expect("CreateReservedResource"); + let reserved = reserved.expect("reserved buffer"); + let s = new_state(&dev, vec![(base, reserved)]).expect("state"); + (base, s) + } + + unsafe fn add_upload_slot(s: &mut State, fence_val: u64, close: bool) { + let alloc = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("upload allocator"); + let list: ID3D12GraphicsCommandList = s.dev + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None) + .expect("upload list"); + if close { + list.Close().expect("upload list close"); + } + s.slots.push(UploadSlot { alloc, list, fence_val }); + } + #[test] - fn pools_of_freed_runs_go_back() { + fn begin_slot_skips_a_busy_head_for_a_ready_slot() { use windows_sys::Win32::System::Memory::MEM_RELEASE; unsafe { let (base, mut s) = test_state_with_reserved(1); - // 192 MiB of tiles, taken in order as a title's first commits take them - const TILES: usize = 3072; - let tiles: Vec<(u32, u32)> = (0..TILES).map(|_| s.take_tile().expect("a tile").0).collect(); - let made = s.pools.iter().filter(|p| p.is_some()).count(); - assert_eq!(made * POOL_TILES as usize, TILES, "the tiles fill whole pools"); - // of every 64 MiB the title keeps the first 4 MiB and frees the rest - let (mut kept, mut freed) = (0, 0); - for (i, &t) in tiles.iter().enumerate() { - if i % 1024 < 64 { - kept += 1; - } else { - s.free.push(t); - freed += 1; - } - } - s.retire_free_pools(); - let left = s.pools.iter().filter(|p| p.is_some()).count() * POOL_TILES as usize; - assert_eq!(s.free.len() + s.retired.len() * POOL_TILES as usize, freed, "every freed tile is free or its pool retired"); - assert!(left <= kept * 2, "{left} tiles of video memory stay in pools for {kept} tiles in use ({} MiB for {} MiB)", left * TILE >> 20, kept * TILE >> 20); + // (`new_state` makes `UPLOAD_SLOTS` ready slots: these tests lay out their own) + s.slots.clear(); + add_upload_slot(&mut s, 9, true); + add_upload_slot(&mut s, 0, true); + + assert!(matches!(s.begin_slot(), BeginSlot::Ready(1))); + assert_eq!(s.next_slot, 0); + s.slots[1].list.Close().expect("selected list close"); + drop(s); assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); } } #[test] - fn aligned_tile_addresses_spread_across_hash_buckets() { - use std::hash::BuildHasher; + fn begin_slot_waits_for_the_earliest_busy_slot_without_advancing() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; - let hasher = BuildHasherDefault::::default(); - let mut used = [false; 256]; - for tile in 0..used.len() { - let address = (1usize << 32) + tile * TILE; - let bucket = hasher.hash_one(address) as usize & (used.len() - 1); - used[bucket] = true; + unsafe { + let (base, mut s) = test_state_with_reserved(1); + // (`new_state` makes `UPLOAD_SLOTS` ready slots: these tests lay out their own) + s.slots.clear(); + add_upload_slot(&mut s, 9, true); + add_upload_slot(&mut s, 7, true); + add_upload_slot(&mut s, 8, true); + let ticket = match s.begin_slot() { + BeginSlot::Wait(ticket) => ticket, + _ => panic!("all busy slots did not return a retirement ticket"), + }; + + assert_eq!(s.next_slot, 0); + assert_eq!(ticket.target, 7); + assert!(matches!(ticket.kind, WaitKind::Slot { index: 1, next_slot: 0, fence: 7 })); + assert!(s.wait_ticket_owns_upload(&ticket)); + s.slots[1].fence_val = 10; + assert!(!s.wait_ticket_owns_upload(&ticket), "a changed selected slot accepted its old ticket"); + + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); } - let occupied = used.iter().filter(|&&bucket| bucket).count(); - assert!(occupied >= used.len() / 2, "256 aligned addresses used {occupied} buckets"); } - /// Only the 64-byte chunks the CPU changed are sent again – the rest of the page may hold - /// what the GPU wrote. #[test] - fn only_changed_chunks_are_sent() { - let mut page = vec![0u8; PAGE]; - let mut sent = ZERO_HASHES; - assert!(changed_chunks(&page, &mut sent).is_empty(), "a zero page is what the GPU has"); - page[10] = 1; - page[200] = 2; - page[255] = 3; - page[4000] = 4; - assert_eq!(changed_chunks(&page, &mut sent), vec![(0, 64), (192, 64), (3968, 64)]); - assert!(changed_chunks(&page, &mut sent).is_empty(), "nothing changed since"); - page[256] = 5; // next to the chunk at 192: one run - page[200] = 9; - assert_eq!(changed_chunks(&page, &mut sent), vec![(192, 128)]); + fn begin_slot_reset_failure_does_not_open_or_advance_a_slot() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + // (`new_state` makes `UPLOAD_SLOTS` ready slots: these tests lay out their own) + s.slots.clear(); + add_upload_slot(&mut s, 0, false); + + assert!(matches!(s.begin_slot(), BeginSlot::RetryRequired)); + assert_eq!(s.next_slot, 0); + + s.slots[0].list.Close().expect("failed selected list close"); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } } #[test] - fn clean_chunks_take_gpu_copy_back_bytes() { - let mut page = vec![0x11u8; PAGE]; - let mut sent = Box::new(ZERO_HASHES); - changed_chunks(&page, &mut sent); - let mut slot = Some(sent); - let gpu = vec![0x22u8; 2 * CHUNK]; + fn upload_wait_releases_and_reacquires_its_ownership_gate() { + let (acquired_tx, acquired_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let (mut guard, mut timing) = UploadGateTiming::acquire(false); + let worker = std::thread::spawn(move || { + let _crossing_uploader = UPLOAD_GATE.lock().unwrap(); + acquired_tx.send(()).unwrap(); + release_rx.recv().unwrap(); + }); + let released = timing.with_released(&mut guard, || { + let acquired = acquired_rx.recv_timeout(std::time::Duration::from_secs(1)).is_ok(); + release_tx.send(()).unwrap(); + worker.join().unwrap(); + acquired + }); + assert!(released, "another uploader could not cross the fence wait"); + assert!(UPLOAD_GATE.try_lock().is_err(), "the process upload gate was not reacquired"); + let times = timing.finish(); + assert_eq!((times.wait_us, times.hold_us, times.released_us), (0, 0, 0), "disabled timing read the clock"); + drop(guard); + } - land_page(&mut slot, &mut page, CHUNK, &gpu, false); + #[test] + fn replacement_waits_for_every_upload_generation_reader() { + let _placement = PLACEMENT.lock().unwrap(); + let lower_target = UPLOAD_STATE_LIFETIME.read().unwrap(); + let higher_target = UPLOAD_STATE_LIFETIME.read().unwrap(); + let (acquired_tx, acquired_rx) = std::sync::mpsc::channel(); + let replacement = std::thread::spawn(move || { + let _exclusive = UPLOAD_STATE_LIFETIME.write().unwrap(); + acquired_tx.send(()).unwrap(); + }); - assert!(page[..CHUNK].iter().all(|&byte| byte == 0x11)); - assert!(page[CHUNK..3 * CHUNK].iter().all(|&byte| byte == 0x22)); - assert!(changed_chunks(&page, slot.as_deref_mut().unwrap()).is_empty(), "landed bytes were left dirty"); + assert!(acquired_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err()); + drop(lower_target); + assert!(acquired_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err(), + "replacement passed the lower target while a higher upload was still in flight"); + drop(higher_target); + acquired_rx.recv_timeout(std::time::Duration::from_secs(1)).expect("replacement stayed blocked after every upload reader retired"); + replacement.join().unwrap(); } #[test] - fn dirty_chunks_survive_gpu_copy_back_and_upload_next() { - let mut page = vec![0x11u8; PAGE]; - let mut sent = Box::new(ZERO_HASHES); - changed_chunks(&page, &mut sent); - let old_dirty_hash = sent[1]; - let mut slot = Some(sent); - page[CHUNK..2 * CHUNK].fill(0x33); - let gpu = vec![0x22u8; 2 * CHUNK]; + fn a_stalled_upload_ring_yields_without_publishing_hashes() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; - land_page(&mut slot, &mut page, CHUNK, &gpu, false); + unsafe { + let (base, mut s) = test_state_with_reserved(1); + assert_eq!(VirtualAlloc(base as *mut c_void, TILE, MEM_COMMIT, PAGE_READWRITE) as usize, base); + std::ptr::write_bytes(base as *mut u8, 0x5a, PAGE); + s.commit_range(base, TILE); + s.wait_for(s.value); + let page = std::slice::from_raw_parts(base as *const u8, PAGE); + let mut sent = Box::new(ZERO_HASHES); + changed_chunks(page, &mut sent); + s.mapped.get_mut(&base).unwrap().sent[0] = Some(sent); + let before = *s.mapped[&base].sent[0].as_ref().unwrap().clone(); - assert!(page[CHUNK..2 * CHUNK].iter().all(|&byte| byte == 0x33), "copy-back overwrote newer CPU bytes"); - assert_eq!(slot.as_ref().unwrap()[1], old_dirty_hash, "dirty chunk lost its last-sent hash"); - assert!(page[2 * CHUNK..3 * CHUNK].iter().all(|&byte| byte == 0x22), "clean neighbour did not land"); - assert_eq!(changed_chunks(&page, slot.as_deref_mut().unwrap()), vec![(CHUNK, CHUNK)]); + s.ring_write = STAGING as u64; + s.ring_submitted = STAGING as u64; + s.ring_free = 0; + s.inflight.push_back((s.value + 1, STAGING as u64)); + let ticket = match s.upload_dirty_with_timeout(&[(base + CHUNK, 2 * CHUNK)], 20) { + UploadStep::Wait(ticket) => ticket, + UploadStep::Done(_) => panic!("a full ring did not return its retirement ticket"), + }; + assert_eq!(ticket.target, s.value + 1); + assert!(s.wait_ticket_valid(&ticket)); + s.mapping_epoch += 1; + assert!(!s.wait_ticket_valid(&ticket), "a remapped destination accepted an old upload ticket"); + assert!(s.wait_ticket_generation(&ticket), "a remap invalidated the live state generation"); + let after = s.mapped[&base].sent[0].as_ref().unwrap(); + assert_eq!(after.as_ref(), &before, "a failed upload changed the published hash state"); + + let alloc = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.Close().unwrap(); + // (only this busy slot: `new_state` made `UPLOAD_SLOTS` ready ones) + s.slots.clear(); + s.slots.push(UploadSlot { alloc, list, fence_val: s.value + 1 }); + s.next_slot = 0; + let before_slot = s.next_slot; + let ticket = match s.begin_slot() { + BeginSlot::Wait(ticket) => ticket, + _ => panic!("a busy slot did not return its retirement ticket"), + }; + assert_eq!(s.next_slot, before_slot, "a busy slot advanced before its fence completed"); + assert!(matches!(ticket.kind, WaitKind::Slot { index: 0, next_slot: 0, .. })); + assert!(s.wait_ticket_owns_upload(&ticket)); + s.slots[0].fence_val += 1; + assert!(!s.wait_ticket_owns_upload(&ticket), "a reused slot accepted its predecessor ticket"); + assert!(s.wait_ticket_generation(&ticket), "safe slot reuse invalidated the live generation"); + s.generation += 1; + assert!(!s.wait_ticket_owns_upload(&ticket), "a replacement state accepted an old upload ticket"); + s.uploads_ordered = false; + assert!(matches!( + s.upload_dirty_with_timeout(&[(base + CHUNK, CHUNK)], 20), + UploadStep::Done(PreparationOutcome::ExecutedUntracked) + )); + + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } } - /// A wait's cells and the write after it share a chunk (#3093, the test title's Wait32 / Wait64 - /// at +0x300 / +0x308 and Write32 at +0x310): the CPU wrote the cells, so the chunk changed, - /// and the GPU's own write still lands; the chunk keeps its old hash and uploads next. #[test] - fn gpu_written_bytes_land_in_a_chunk_the_cpu_changed() { - let mut page = vec![0u8; PAGE]; - let mut sent = Box::new(ZERO_HASHES); - changed_chunks(&page, &mut sent); - let old_hash = sent[0x300 / CHUNK]; - let mut slot = Some(sent); - page[0x300..0x304].copy_from_slice(&0xDEAD_00AAu32.to_le_bytes()); - page[0x308..0x310].copy_from_slice(&0x0000_0003_0000_0000u64.to_le_bytes()); + fn placement_create_is_unlocked_drains_releases_and_rejects_a_new_generation() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; - land_page(&mut slot, &mut page, 0x310, &0x55AA_55AAu32.to_le_bytes(), true); + unsafe { + let (base, mut s) = test_state_with_reserved(2); + assert_eq!(VirtualAlloc(base as *mut c_void, 2 * TILE, MEM_COMMIT, PAGE_READWRITE) as usize, base); + s.commit_range(base, 2 * TILE); + s.wait_for(s.value); + let old_tile = s.mapped[&base].pool; + let new_tile = s.mapped[&(base + TILE)].pool; - assert_eq!(page[0x310..0x314], 0x55AA_55AAu32.to_le_bytes(), "the GPU's write was dropped"); - assert_eq!(page[0x300..0x304], 0xDEAD_00AAu32.to_le_bytes(), "the CPU's cells were overwritten"); - assert_eq!(page[0x308..0x310], 0x0000_0003_0000_0000u64.to_le_bytes()); - assert_eq!(slot.as_ref().unwrap()[0x300 / CHUNK], old_hash, "the changed chunk lost its last-sent hash"); - assert_eq!(changed_chunks(&page, slot.as_deref_mut().unwrap()), vec![(0x300, CHUNK)]); - } + let mut placed: Option = None; + s.dev.CreateReservedResource(&buffer_desc(TILE as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut placed) + .expect("placed resource"); + let placed = placed.unwrap(); + let ptr = placed.as_raw() as usize; + s.buffers.insert(ptr, vec![(base, old_tile)]); + s.pinned.insert(old_tile, 1); - /// `scan_page` leaves published hashes unchanged, skips allocation for zero pages, and - /// coalesces adjacent dirty chunks. - #[test] - fn scan_page_plans_without_publishing_and_coalesces() { - let mut page = vec![0u8; PAGE]; - let slot: Option> = None; - let mut out = Vec::new(); - scan_page(&page, 0x1_0000, &slot, &mut out); - assert!(slot.is_none(), "all-zero page must not allocate hash box"); - assert!(out.is_empty()); + let state = Mutex::new(Some(s)); + let forgotten = Mutex::new(Vec::new()); + let desc = buffer_desc(TILE as u64); + let returned = placed.clone().into_raw(); + let mut unlocked = false; + let result = place_buffer_in( + &state, + &forgotten, + base + TILE, + &desc, + 0, + |_| { + unlocked = state.try_lock().is_ok(); + forget_buffer_in(&state, &forgotten, ptr); + forgotten.lock().unwrap().push(ptr); + Some((0, returned)) + }, + |_| panic!("same-generation placement aborted"), + ); + assert_eq!(result, Some((0, 0))); + assert!(unlocked, "resource creation held sparse STATE"); + { + let g = lock_state_in(&state, &forgotten); + let s = g.as_ref().unwrap(); + assert_eq!(s.buffers.get(&ptr), Some(&vec![(base + TILE, new_tile)])); + assert!(!s.pinned.contains_key(&old_tile)); + assert_eq!(s.pinned.get(&new_tile), Some(&1)); + } - page[PAGE - 64] = 0xAA; - scan_page(&page, 0x1_0000, &slot, &mut out); - assert!(slot.is_none(), "planning must not publish a last-sent hash"); - assert_eq!(out, vec![(0x1_0FC0, 64)]); + let original_fence = state.lock().unwrap().as_ref().unwrap().fence.clone(); + let replacement = state.lock().unwrap().as_ref().unwrap().dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let returned2 = placed.clone().into_raw(); + let mut aborted = false; + let result = place_buffer_in( + &state, + &forgotten, + base + TILE, + &desc, + 0, + |_| { + state.lock().unwrap().as_mut().unwrap().fence = replacement; + Some((0, returned2)) + }, + |raw| { + aborted = true; + drop(ID3D12Resource::from_raw(raw)); + }, + ); + assert!(result.is_none() && aborted, "a replacement state accepted the old generation's resource"); + state.lock().unwrap().as_mut().unwrap().fence = original_fence; - // Adjacent chunk at the start of the next page coalesces into a single run. - let mut next = vec![0u8; PAGE]; - next[0] = 0xBB; - let next_slot: Option> = None; - scan_page(&next, 0x1_1000, &next_slot, &mut out); - assert_eq!(out, vec![(0x1_0FC0, 128)]); + drop(ID3D12Resource::from_raw(returned)); + let s = state.lock().unwrap().take().unwrap(); + s.wait_for(s.value); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } } - #[test] - fn hash_plan_is_published_only_when_applied() { - let base = 0x2_0000; - let mut mapped = FxHashMap::default(); - mapped.insert(base, TileEntry::with_holes((0, 0), 0)); - let mut prefix = Vec::new(); - append_hash_updates(base + CHUNK, &[1; CHUNK], &mut prefix); - let mut suffix = Vec::new(); - append_hash_updates(base + PAGE + 2 * CHUNK, &[2; CHUNK], &mut suffix); - assert!(mapped[&base].sent[0].is_none()); - assert!(mapped[&base].sent[1].is_none()); - publish_hash_updates(&mut mapped, &prefix); - assert_eq!(mapped[&base].sent[0].as_ref().unwrap()[1], chunk_hash(&[1; CHUNK])); - assert!(mapped[&base].sent[1].is_none(), "an unacknowledged suffix was published"); - publish_hash_updates(&mut mapped, &suffix); - assert_eq!(mapped[&base].sent[1].as_ref().unwrap()[2], chunk_hash(&[2; CHUNK])); + /// `XCL_SPARSE_LAZY` on (or off) for this thread while it lives, and `take_tile` finding no + /// video memory while `no_tiles` is set. + struct Lazy; + impl Lazy { + fn on(on: bool) -> Lazy { + LAZY_COMMITS_FOR_TEST.with(|c| c.set(Some(on))); + Lazy + } + fn no_tiles(&self, none: bool) { + NO_TILES.with(|c| c.set(none)); + } } - - #[test] - fn cpu_write_after_planning_is_dirty_after_receipt_publication() { - let base = 0x3_0000; - let mut mapped = FxHashMap::default(); - mapped.insert(base, TileEntry::with_holes((0, 0), 0)); - let mut page = vec![0u8; PAGE]; - page[0] = 1; - let staged = page[..CHUNK].to_vec(); - let mut planned = Vec::new(); - append_hash_updates(base, &staged, &mut planned); - page[0] = 2; - publish_hash_updates(&mut mapped, &planned); - - let mut runs = Vec::new(); - scan_page(&page, base, &mapped[&base].sent[0], &mut runs); - assert_eq!(runs, [(base, CHUNK)]); + impl Drop for Lazy { + fn drop(&mut self) { + LAZY_COMMITS_FOR_TEST.with(|c| c.set(None)); + NO_TILES.with(|c| c.set(false)); + } } + /// A state of `tiles` tiles for the lazy tests, its window's CPU pages committed and the title's + /// queue. None: no GPU whose unmapped tiles read zeros (the lazy path is left out there). + unsafe fn lazy_state(tiles: usize) -> Option<(usize, State, ID3D12CommandQueue)> { + let dev = test_device(); + let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut o as *mut _ as *mut c_void, std::mem::size_of_val(&o) as u32).ok()?; + if software(&dev) || o.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0 { + return None; + } + let (base, s) = test_state_with_reserved(tiles); + assert!(!VirtualAlloc(base as *const c_void, tiles * TILE, MEM_COMMIT, PAGE_READWRITE).is_null()); + let queue: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).ok()?; + Some((base, s, queue)) + } + + /// `len` bytes of the window at `va` as the GPU has them, after what was sent to it. + unsafe fn window_bytes(s: &mut State, va: usize, len: usize) -> Vec { + let mut d = buffer_desc(len as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + let mut back: Option = None; + s.dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut back).expect("readback buffer"); + let back = back.expect("readback buffer"); + let (base, window) = (s.windows[0].0, s.windows[0].1.clone()); + let alloc: ID3D12CommandAllocator = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list"); + list.CopyBufferRegion(&back, 0, &window, (va - base) as u64, len as u64); + list.Close().expect("Close"); + s.flush_pending(); + s.queue.ExecuteCommandLists(&[Some(list.cast().expect("list"))]); + s.signal(); + s.wait_for(s.value); + let mut p = std::ptr::null_mut(); + back.Map(0, None, Some(&mut p)).expect("Map"); + let out = std::slice::from_raw_parts(p as *const u8, len).to_vec(); + back.Unmap(0, None); + out + } + + /// Tile `t`'s CPU pages written with bytes made from `seed`; its pages, for a submit's dirty list. + unsafe fn write_tile(t: usize, seed: u64) -> Vec { + let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + for i in 0..TILE / 8 { + *(t as *mut u64).add(i) = next(&mut x); + } + (t..t + TILE).step_by(PAGE).collect() + } + + /// With `XCL_SPARSE_LAZY` a committed tile gets no video memory until the CPU's first bytes + /// go up to it; they reach the GPU, and a later submit with nothing written leaves them there + /// (a tile cleared one submit after its bytes went up would read zeros). A tile never written + /// keeps none and reads zeros. #[test] - fn batch_hash_plan_is_bounded_by_staging() { - assert_eq!(MAX_BATCH_HASH_UPDATES, STAGING / CHUNK); - assert_eq!(MAX_BATCH_HASH_UPDATES * std::mem::size_of::(), STAGING / 4); - assert!(!batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES - 1, CHUNK)); - assert!(batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES, CHUNK)); - assert!(batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES / 2 + 1, STAGING / 2)); + fn a_lazy_tile_gets_memory_at_its_first_bytes_and_keeps_them() { + let lazy = Lazy::on(true); + unsafe { + let Some((base, mut s, queue)) = lazy_state(2) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") }; + s.commit_range(base, 2 * TILE); + assert_eq!(s.mapped[&base].pool, LAZY, "committed: listed with no video memory"); + assert_eq!(s.mapped[&(base + TILE)].pool, LAZY); + // a used pool tile on hand, so that its old bytes would show if it were not cleared + s.no_memory = None; + let dirty = write_tile(base, 7); + s.before_execute_on(&queue, &dirty, PAGE); + assert_ne!(s.mapped[&base].pool, LAZY, "its first bytes gave it a pool tile"); + assert_eq!(s.mapped[&(base + TILE)].pool, LAZY, "the tile never written has none"); + let cpu = std::slice::from_raw_parts(base as *const u8, TILE).to_vec(); + assert!(window_bytes(&mut s, base, TILE) == cpu, "the bytes reached the GPU"); + s.before_execute_on(&queue, &[], PAGE); + s.before_execute_on(&queue, &[], PAGE); + assert!(window_bytes(&mut s, base, TILE) == cpu, "and are still there two submits later"); + assert!(window_bytes(&mut s, base + TILE, TILE).iter().all(|&b| b == 0), "a tile with no memory reads zeros"); + } + drop(lazy); + } + + /// Bytes that found no video memory at an upload are owed and go up whole once there is some. + #[test] + fn bytes_that_found_no_memory_go_up_once_there_is_some() { + let lazy = Lazy::on(true); + unsafe { + let Some((base, mut s, queue)) = lazy_state(1) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") }; + s.commit_range(base, TILE); + let dirty = write_tile(base, 11); + lazy.no_tiles(true); + s.before_execute_on(&queue, &dirty, PAGE); + assert_eq!(s.mapped[&base].pool, LAZY, "no video memory to be had: still none"); + assert!(s.starved.contains(&base), "its bytes are owed"); + lazy.no_tiles(false); + s.no_memory = None; + s.before_execute_on(&queue, &[], PAGE); + assert_ne!(s.mapped[&base].pool, LAZY, "a submit with nothing written gives it its memory"); + let cpu = std::slice::from_raw_parts(base as *const u8, TILE).to_vec(); + assert!(window_bytes(&mut s, base, TILE) == cpu, "and all its bytes"); + } + drop(lazy); + } + + /// A memory write the title records on a list gives the tile its memory before the list runs + /// (`give_memory`); a placed buffer over a tile that finds none leaves it out of its mapping + /// instead of mapping pool tile u32::MAX. + #[test] + fn a_recorded_write_gives_memory_and_a_buffer_never_maps_the_sentinel() { + let lazy = Lazy::on(true); + unsafe { + let Some((base, mut s, _queue)) = lazy_state(2) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") }; + s.commit_range(base, 2 * TILE); + s.give_memory(&[(base + 8, 8)]); + assert_ne!(s.mapped[&base].pool, LAZY, "the recorded write's tile got memory"); + assert_eq!(s.mapped[&(base + TILE)].pool, LAZY, "the other did not"); + lazy.no_tiles(true); + let tiles = s.buffer_tiles(base, 2 * TILE); + assert!(tiles.iter().all(|&(_, tile)| tile != LAZY), "no tile of a buffer is the sentinel: {tiles:?}"); + assert!(tiles.iter().any(|&(t, _)| t == base), "the tile with memory is the buffer's"); + } + drop(lazy); } + /// Decommitting a tile with no video memory frees and parks nothing; committed again it is + /// listed again. With the switch off a commit maps at once, as before. #[test] - fn prepared_dirty_batch_keeps_exact_hash_plan_and_rollback_point() { - let mut batch = PreparedDirtyBatch::new(3, 0x12_3400); - let bytes = [0xA5; 2 * CHUNK]; - batch.append_hashes(0x20_0000, &bytes); - assert_eq!(batch.slot, 3); - assert_eq!(batch.ring_start, 0x12_3400); - assert_eq!(batch.updates.len(), 2); - assert_eq!(batch.updates[0], HashUpdate { at: 0x20_0000, hash: chunk_hash(&bytes[..CHUNK]) }); - assert_eq!(batch.updates[1], HashUpdate { at: 0x20_0000 + CHUNK, hash: chunk_hash(&bytes[CHUNK..]) }); - assert!(!batch.hash_plan_would_overflow(CHUNK)); - - let storage = batch.updates.as_ptr(); - let capacity = batch.updates.capacity(); - for index in 0..3 { - batch.clear_after_submit(); - batch = batch.reopen(4 + index, 0x20_0000 + index as u64 * PAGE as u64); - batch.append_hashes(0x30_0000, &bytes); - assert_eq!(batch.updates.as_ptr(), storage, "batch {index} replaced its hash-plan allocation"); - assert_eq!(batch.updates.capacity(), capacity); + fn a_lazy_tile_decommits_without_a_pool_tile_and_off_maps_at_commit() { + unsafe { + let lazy = Lazy::on(true); + let Some((base, mut s, _queue)) = lazy_state(1) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") }; + s.commit_range(base, TILE); + let (free, parked) = (s.free.len(), s.parked.len()); + s.decommit_range(base, TILE); + assert!(!s.mapped.contains_key(&base), "gone from the window"); + assert_eq!((s.free.len(), s.parked.len()), (free, parked), "no pool tile freed or parked"); + s.commit_range(base, TILE); + assert_eq!(s.mapped[&base].pool, LAZY, "listed again"); + drop(lazy); + let off = Lazy::on(false); + let Some((base2, mut s2, _q2)) = lazy_state(1) else { return }; + s2.commit_range(base2, TILE); + assert_ne!(s2.mapped[&base2].pool, LAZY, "off: mapped at the commit"); + drop(off); + } + } + + /// The tiles `flush_parked` quarantined, once the sparse queue and the title queues are past + /// them (`drain_quarantined`), waited for up to 5 s. + unsafe fn settle_quarantined(s: &mut State) { + s.wait_for(s.value); + let start = std::time::Instant::now(); + while !s.quarantined.is_empty() && start.elapsed() < std::time::Duration::from_secs(5) { + if !s.drain_quarantined() { + std::thread::sleep(std::time::Duration::from_millis(1)); + } } } + /// `flush_parked` must keep unmapped pool tiles out of `free` (and `take_tile` must not reuse + /// them) while the sparse queue's unmap fence is still in flight on the GPU. #[test] - fn prepared_dirty_copy_splits_at_windows_and_ring_wrap() { - let window = 4 * PAGE; - let base = 0x10_0000; - let first = prepare_dirty_copy(base + window - CHUNK, 2 * CHUNK, base, window, 0, 8 * PAGE); - assert_eq!(first, PreparedDirtyCopy { - ring_start: 0, - staging_offset: 0, - window_offset: window - CHUNK, - bytes: CHUNK, - }); - let second = prepare_dirty_copy(base + window, CHUNK, base + window, window, CHUNK as u64, 8 * PAGE); - assert_eq!(second.window_offset, 0); - assert_eq!(second.bytes, CHUNK); + fn flush_parked_does_not_free_or_reuse_tiles_while_unmap_is_in_flight() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; - let cap = 8 * PAGE; - let wrapped = prepare_dirty_copy(base, PAGE, base, window, (cap - 512) as u64, cap); - assert_eq!(wrapped.ring_start, cap as u64); - assert_eq!(wrapped.staging_offset, 0); - assert_eq!(wrapped.bytes, PAGE); - } + unsafe { + let (base, mut s) = test_state_with_reserved(2); + s.commit_range(base, TILE); + let tile = s.mapped[&base].pool; + s.wait_for(s.value); - /// Ring-buffer planner keeps every chunk contiguous, 64-byte aligned, <= cap/2, and splits - /// cleanly across the end of the ring buffer without wrapping mid-copy. - #[test] - fn ring_planner_handles_wrap_and_large_chunks() { - let cap = 64 << 20; - // Normal aligned chunk - let (a, n) = plan_ring_chunk(0, 4096, cap); - assert_eq!((a, n), (0, 4096)); - // Unaligned cursor aligns up to 64 - let (a, n) = plan_ring_chunk(17, 256, cap); - assert_eq!((a, n), (64, 256)); - // Oversized chunk capped at cap / 2 - let (a, n) = plan_ring_chunk(0, cap * 2, cap); - assert_eq!((a, n), (0, cap / 2)); - // Near end of ring with >= 4 KiB left: shrinks to fill tail - let near = (cap - 8192) as u64; - let (a, n) = plan_ring_chunk(near, 16384, cap); - assert_eq!((a, n), (near, 8192)); - assert_eq!((a as usize % cap) + n, cap); - // Tiny tail (< 4 KiB): wraps cleanly to 0 of next cycle - let tiny = (cap - 512) as u64; - let (a, n) = plan_ring_chunk(tiny, 4096, cap); - assert_eq!((a, n), (cap as u64, 4096)); - assert_eq!(a as usize % cap, 0); + let gate: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate fence"); + let _unblock = SignalOnDrop(gate.clone(), 1); + s.queue.Wait(&gate, 1).expect("gate sparse queue"); + + s.decommit_range(base, TILE); + s.free.clear(); + assert!(s.flush_parked()); + assert!( + !s.free.contains(&tile) && !s.cooling.iter().any(|c| c.0 == tile), + "unmapped tile must remain quarantined until unmap fence completes" + ); + + // While the unmap is still blocked on `gate`, committing another tile must not steal `tile`. + s.commit_range(base + TILE, TILE); + assert_ne!(s.mapped[&(base + TILE)].pool, tile, "in-flight unmapped tile must not be reused before GPU completion"); + + gate.Signal(1).expect("release sparse queue"); + s.wait_for(s.value); + assert!(s.drain_quarantined(), "completed unmap batch should drain after fence completion"); + assert!( + s.cooling.iter().any(|c| c.0 == tile) && !s.free.contains(&tile), + "unmapped tile must go on to cool (`cooling`) once unmap fence completes" + ); + drop(_unblock); + s.wait_for(s.value); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } } - /// `query_tile_holes` marks reserved, free, and `PAGE_NOACCESS` pages as holes while clearing - /// bits only for committed, accessible 4 KiB pages. + /// `flush_parked` must keep unmapped pool tiles quarantined until every active title queue has + /// finished its prior work, even after `s.queue` itself finishes unmapping. #[test] - fn query_tile_holes_detects_reserved_noaccess_and_committed_pages() { - use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + fn flush_parked_quarantines_tiles_until_title_queues_finish() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; unsafe { - // SAFETY: Reserving 2 tiles (128 KiB) with VirtualAlloc returns a 64 KiB-aligned VA. - let base = VirtualAlloc(std::ptr::null(), 2 * TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; - assert!(base != 0 && base % TILE == 0); + let (base, mut s) = test_state_with_reserved(2); + let title_q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + + s.commit_range(base, TILE); + let tile = s.mapped[&base].pool; + s.wait_for(s.value); - // Initially every page in both reserved tiles is a hole. - assert_eq!(query_tile_holes(base), 0xFFFF); - assert_eq!(query_tile_holes(base + TILE), 0xFFFF); + let title_gate: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("title gate fence"); + let _unblock = SignalOnDrop(title_gate.clone(), 1); + title_q.Wait(&title_gate, 1).expect("gate title queue"); - // Commit pages 4..8 as PAGE_READWRITE and page 9 as PAGE_NOACCESS. - let p4 = VirtualAlloc((base + 4 * PAGE) as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE); - assert!(!p4.is_null()); - let p9 = VirtualAlloc((base + 9 * PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_NOACCESS); - assert!(!p9.is_null()); + s.decommit_range(base, TILE); + s.free.clear(); + assert!(s.flush_parked_for(std::slice::from_ref(&title_q), &[], false)); - // Only bits 4..8 are cleared; reserved [0..4), PAGE_NOACCESS [9], and reserved [10..16) remain holes. - assert_eq!(query_tile_holes(base), 0xFFFF & !(0b1111u16 << 4)); - assert_eq!(query_tile_holes(base + TILE), 0xFFFF); + // Even after `s.queue` finishes `unmap_tiles`, `title_q` is still gated behind `title_gate`. + s.wait_for(s.value); + assert!(!s.drain_quarantined(), "tile must remain quarantined while title queue has work in flight"); + assert!(!s.free.contains(&tile) && !s.cooling.iter().any(|c| c.0 == tile)); - // Commit pages 0..4 and confirm bits 0..4 clear too. - let p0 = VirtualAlloc(base as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE); - assert!(!p0.is_null()); - assert_eq!(query_tile_holes(base), 0xFF00); + s.commit_range(base + TILE, TILE); + assert_ne!(s.mapped[&(base + TILE)].pool, tile, "must not reuse tile still in use by title queue"); + title_gate.Signal(1).expect("release title queue"); + let start = std::time::Instant::now(); + while !s.drain_quarantined() && start.elapsed() < std::time::Duration::from_secs(5) { + std::thread::sleep(std::time::Duration::from_millis(2)); + } + assert!( + s.cooling.iter().any(|c| c.0 == tile) && !s.free.contains(&tile), + "tile must go on to cool (`cooling`) after title queue completes" + ); + drop(_unblock); + s.wait_for(s.value); + drop(s); assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); - // Released (MEM_FREE) memory reports all holes. - assert_eq!(query_tile_holes(base), 0xFFFF); } } - /// Mapping tiles for a placed buffer over partially-committed/reserved memory must preserve - /// uncommitted hole bits so `readback_ranges` does not access-violate, - /// and later commits clear those hole bits so subsequent writes scan cleanly. + /// Sub-tile decommits (two 32 KiB halves, sixteen 4 KiB pages, or decommitting the last + /// remaining committed page) must unmap the tile and return unpinned pool tiles to `free` + /// once `holes` reaches `0xFFFF`, pruning stale `to_zero` entries for unmapped tiles. #[test] - fn ensure_mapped_with_query_holes_skips_uncommitted_pages_on_readback() { - use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; - use windows::Win32::Graphics::Dxgi::*; - use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + fn decommit_sub_tile_reclaims_pool_tile_when_all_pages_become_holes() { + let mut mapped: FxHashMap = FxHashMap::default(); + let mut pinned: FxHashMap<(u32, u32), u32> = FxHashMap::default(); + let mut free: Vec<(u32, u32)> = Vec::new(); + let mut to_zero: BTreeSet<(usize, usize)> = BTreeSet::new(); - unsafe { - let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); - let mut dev: Option = None; - if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { - let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); - D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); - } - let dev = dev.expect("D3D12 device"); + // 1. Two 32 KiB decommits across a full 64 KiB tile. + let t0 = 0x10_0000usize; + mapped.insert(t0, TileEntry::with_holes((0, 10), 0)); + assert!(decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t0, TILE / 2).is_empty()); + assert_eq!(mapped[&t0].holes, 0x00FF); + assert_eq!(to_zero.len(), 8); + assert!(free.is_empty()); - // Reserve 2 tiles; commit only [base + 0x4000, base + 0x8000) to simulate a - // non-64KiB-aligned placed buffer with uncommitted prefix [base, base + 0x4000) and - // uncommitted second tile [base + TILE, base + 2*TILE). - let base = VirtualAlloc(std::ptr::null(), 2 * TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; - assert!(base != 0 && base % TILE == 0); - assert!(!VirtualAlloc((base + 4 * PAGE) as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + let unmapped = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t0 + TILE / 2, TILE / 2); + assert_eq!(unmapped, vec![t0]); + assert!(!mapped.contains_key(&t0)); + assert_eq!(free, vec![(0, 10)]); + assert!(to_zero.is_empty(), "stale to_zero entries for the unmapped tile must be pruned"); - let mut reserved: Option = None; - dev.CreateReservedResource(&buffer_desc((2 * TILE) as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved) - .expect("CreateReservedResource"); - let reserved = reserved.expect("reserved buffer"); - let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); - let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); - let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); - let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("rb_alloc"); - let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); - rb_list.Close().expect("rb_list close"); + // 2. Sixteen individual 4 KiB decommits in reverse order. + let t1 = 0x20_0000usize; + free.clear(); + mapped.insert(t1, TileEntry::with_holes((0, 11), 0)); + for i in (1..PAGES_PER_TILE).rev() { + let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t1 + i * PAGE, PAGE); + assert!(u.is_empty(), "tile still has committed pages after step {i}"); + } + assert!(free.is_empty()); + let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t1, PAGE); + assert_eq!(u, vec![t1]); + assert!(!mapped.contains_key(&t1)); + assert_eq!(free, vec![(0, 11)]); + assert!(to_zero.is_empty()); - let mut s = State { - generation: 1, - mapping_epoch: 0, - coordination: SparseCoordination::new(1, 1).unwrap(), - dev, - queue, - fence, - value: 0, - event, - rb_fence, - rb_value: 0, - windows: vec![(base, reserved)], - pools: Vec::new(), - free: Vec::new(), - retired: Vec::new(), - mapped: FxHashMap::default(), - pinned: FxHashMap::default(), - parked: FxHashMap::default(), - quarantined: VecDeque::new(), - queue_fences: FxHashMap::default(), - buffers: FxHashMap::default(), - to_zero: Vec::new(), - staging: None, - ring_write: 0, - ring_submitted: 0, - ring_free: 0, - inflight: VecDeque::new(), - uploads_ordered: true, - zero_buf: None, - slots: Vec::new(), - next_slot: 0, - readback: None, - rb_alloc, - rb_list, - rb_last_fence: 0, - waited: FxHashMap::default(), - runs: None, - scratch_runs: Vec::new(), - retry_pages: Vec::new(), - }; + // 3. Pinned tile decommitted in two halves: unmapped from `mapped`, NOT returned to `free`. + let t2 = 0x30_0000usize; + free.clear(); + mapped.insert(t2, TileEntry::with_holes((0, 12), 0)); + pinned.insert((0, 12), 1); + assert!(decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t2, TILE / 2).is_empty()); + let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t2 + TILE / 2, TILE / 2); + assert_eq!(u, vec![t2]); + assert!(!mapped.contains_key(&t2)); + assert!(free.is_empty(), "pinned pool tile must not return to free list"); + assert!(to_zero.is_empty()); - // Mirrors `place_buffer`: map both tiles probing real OS page commitment. - s.ensure_mapped(base, 2 * TILE, |t| { - let holes = query_tile_holes(t); - (holes, !holes) - }); - assert_eq!(s.mapped[&base].holes, 0xFF0F, "uncommitted prefix and suffix pages must stay holes"); - assert_eq!(s.mapped[&(base + TILE)].holes, 0xFFFF, "fully reserved tile must have all 16 holes set"); + // 4. Single-committed-page tile decommit reclaims tile without dropping another tile's to_zero. + let t3 = 0x40_0000usize; + let t4 = 0x50_0000usize; + mapped.insert(t3, TileEntry::with_holes((0, 13), 0xFFFF & !(1u16 << 2))); + mapped.insert(t4, TileEntry::with_holes((0, 14), 0)); + assert!(decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t4, PAGE).is_empty()); + assert_eq!(to_zero, BTreeSet::from([(t4, PAGE)])); + let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t3 + 2 * PAGE, PAGE); + assert_eq!(u, vec![t3]); + assert_eq!(free, vec![(0, 13)]); + assert_eq!(to_zero, BTreeSet::from([(t4, PAGE)]), "unrelated mapped tile's to_zero must remain"); - // Reading back the full 2-tile span must not fault on uncommitted pages. - s.readback_ranges(&[(base, 2 * TILE)], false); + // 5. The pieces as runs: neighbours together, pieces inside a whole tile with it. + let t5 = 0x60_0000usize; + to_zero.extend([(t5, TILE), (t5 + 3 * PAGE, PAGE), (t5 + TILE, TILE), (t5 + 2 * TILE + PAGE, PAGE)]); + assert_eq!(zero_runs(to_zero), vec![(t4, PAGE), (t5, 2 * TILE), (t5 + 2 * TILE + PAGE, PAGE)]); + } - // Now incrementally commit [base, base + 4*PAGE) and clear its hole bits (as `committed` does). - assert!(!VirtualAlloc(base as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); - let entry = s.mapped.get_mut(&base).unwrap(); - for i in 0..4 { - entry.holes &= !(1u16 << i); - } - assert_eq!(entry.holes, 0xFF00); + /// The pages in `early`, checking that its ranges are page-aligned, not empty, disjoint and + /// merged (no two touch). + fn early_pages(early: &BTreeMap) -> std::collections::BTreeSet { + let mut last_end = None; + let mut pages = std::collections::BTreeSet::new(); + for (&a, &b) in early { + assert!(a % PAGE == 0 && b % PAGE == 0 && a < b, "range {a:#x}..{b:#x}"); + assert!(last_end.is_none_or(|e| e < a), "range {a:#x}..{b:#x} touches the one before"); + last_end = Some(b); + pages.extend((a..b).step_by(PAGE)); + } + pages + } - // Writing to the newly committed page is detected by `scan_page`. - *(base as *mut u8) = 0x5A; - let mut dirty = Vec::new(); - let page0 = std::slice::from_raw_parts(base as *const u8, PAGE); - scan_page(page0, base, &entry.sent[0], &mut dirty); - assert_eq!(dirty, vec![(base, CHUNK)]); + /// xorshift64*: the same sequence on every run + fn next(x: &mut u64) -> u64 { + *x ^= *x >> 12; + *x ^= *x << 25; + *x ^= *x >> 27; + x.wrapping_mul(0x2545_F491_4F6C_DD1D) + } - s.wait_for(s.value); - drop(s); - assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + /// Before the device exists, commits and decommits leave the pages a plain page set would + /// hold, with the live path's rule (a range counts every page it touches): random ranges, + /// unaligned too, over 300 pages. + #[test] + fn early_commits_are_the_pages_a_page_set_holds() { + let base = 0x4_2000_0000usize; + for seed in 1..=8u64 { + let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + let (mut early, mut model) = (BTreeMap::new(), std::collections::BTreeSet::new()); + for _ in 0..4000 { + let a = base + (next(&mut x) % (300 * PAGE as u64)) as usize; + let n = match next(&mut x) % 4 { + 0 => PAGE, + 1 => 1 + (next(&mut x) % 64) as usize, + _ => 1 + (next(&mut x) % (24 * PAGE as u64)) as usize, + }; + let (start, end) = page_span(a, n); + let pages = (start..end).step_by(PAGE); + if next(&mut x) % 3 == 0 { + early_remove(&mut early, start, end); + pages.for_each(|p| { + model.remove(&p); + }); + } else { + early_add(&mut early, start, end); + model.extend(pages); + } + assert_eq!(early_pages(&early), model, "seed {seed}"); + } + } + } + + /// The same pages as the list this replaced, for what that list handled exactly: one + /// entry per committed page (`XMemMapPhysicalPagesScatter`, `home_again`) and page-aligned + /// decommits of any length. + #[test] + fn early_commits_match_the_old_list_for_page_entries() { + let base = 0x4_2000_0000usize; + let mut x = 0x1234_5678_9ABC_DEF1u64; + let (mut early, mut old): (BTreeMap, Vec<(usize, usize)>) = (BTreeMap::new(), Vec::new()); + for _ in 0..20000 { + let a = base + (next(&mut x) % 512) as usize * PAGE; + if next(&mut x) % 2 == 0 { + old.push((a, PAGE)); + early_add(&mut early, a, a + PAGE); + } else { + let n = (1 + next(&mut x) % 8) as usize * PAGE; + old.retain(|&(y, m)| y + m <= a || y >= a + n); + early_remove(&mut early, a, a + n); + } } + let old_pages: std::collections::BTreeSet = old.iter().map(|&(y, _)| y).collect(); + assert_eq!(early_pages(&early), old_pages); } - /// A tile decommitted and committed again before the next submit gets its pool tile back - /// with no new tile mapping (cleared instead). One that is not is unmapped and freed by - /// `flush_parked` (before a submit), or when the free list runs out; a placed buffer's - /// release does not free it while it is parked. + /// A range committed in one call keeps its other pages when one page of it is decommitted + /// (`commit_homes` commits several pages, `move_home_away` gives one back). The list this + /// replaced dropped the whole entry, so `init` left those still-committed pages as holes. #[test] - fn a_tile_decommitted_and_committed_again_keeps_its_video_memory() { - use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; - use windows::Win32::Graphics::Dxgi::*; - use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + fn early_decommit_of_one_page_keeps_the_rest() { + let a = 0x4_2000_0000usize; + let mut early = BTreeMap::new(); + early_add(&mut early, a, a + 4 * TILE); + early_remove(&mut early, a + TILE, a + 2 * TILE); + assert_eq!(early.into_iter().collect::>(), vec![(a, a + TILE), (a + 2 * TILE, a + 4 * TILE)]); + } - unsafe { - let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); - let mut dev: Option = None; - if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { - let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); - D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + /// Time for n 64 KiB pages committed one at a time and decommitted one at a time in + /// reverse, before the device exists (`cargo test --release -p xcl --lib -- + /// --ignored --exact hle::d3d12x::sparse::tests::early_commit_timing --nocapture`, + /// `XCL_EARLY_PAGES=16384,32768`). Run it alone: a test that made the device keeps a state. + #[test] + #[ignore] + fn early_commit_timing() { + if STATE.lock().unwrap().is_some() { + return eprintln!("early_commit_timing: a sparse state exists – run it alone"); + } + let sizes: Vec = std::env::var("XCL_EARLY_PAGES").ok().map_or(vec![4096, 8192, 16384, 32768], |v| v.split(',').map(|s| s.trim().parse().unwrap()).collect()); + let base = 0x4_2000_0000usize; + for n in sizes { + let t = std::time::Instant::now(); + for i in 0..n { + unsafe { committed(base + i * TILE, TILE) }; } - let dev = dev.expect("D3D12 device"); - let base = VirtualAlloc(std::ptr::null(), 2 * TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; - assert!(base != 0 && base % TILE == 0); - let mut reserved: Option = None; - dev.CreateReservedResource(&buffer_desc((2 * TILE) as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved) - .expect("CreateReservedResource"); - let reserved = reserved.expect("reserved buffer"); - let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); - let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); - let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); - let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("rb_alloc"); - let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); - rb_list.Close().expect("rb_list close"); - - let mut s = State { - generation: 1, - mapping_epoch: 0, - coordination: SparseCoordination::new(1, 1).unwrap(), - dev, - queue, - fence, - value: 0, - event, - rb_fence, - rb_value: 0, - windows: vec![(base, reserved)], - pools: Vec::new(), - free: Vec::new(), - retired: Vec::new(), - mapped: FxHashMap::default(), - pinned: FxHashMap::default(), - parked: FxHashMap::default(), - quarantined: VecDeque::new(), - queue_fences: FxHashMap::default(), - buffers: FxHashMap::default(), - to_zero: Vec::new(), - staging: None, - ring_write: 0, - ring_submitted: 0, - ring_free: 0, - inflight: VecDeque::new(), - uploads_ordered: true, - zero_buf: None, - slots: Vec::new(), - next_slot: 0, - readback: None, - rb_alloc, - rb_list, - rb_last_fence: 0, - waited: FxHashMap::default(), - runs: None, - scratch_runs: Vec::new(), - retry_pages: Vec::new(), - }; + let commit = t.elapsed(); + let t = std::time::Instant::now(); + for i in (0..n).rev() { + unsafe { decommitted(base + i * TILE, TILE) }; + } + let decommit = t.elapsed(); + println!("early: {n} pages: commit {:.1} ms, decommit {:.1} ms", commit.as_secs_f64() * 1e3, decommit.as_secs_f64() * 1e3); + } + } - s.commit_range(base, TILE); - let tile = s.mapped[&base].pool; - let v = s.value; - assert!(v > 0, "a new tile is mapped"); - mark_protection(&mut s.mapped, base + PAGE, PAGE, false); - assert_eq!(s.mapped[&base].not_rw, 1 << 1); + /// A sparse window of the test's own over a GPU view, and the CPU view the view shows, paired + /// by `kernelx::mirrors` as a retail title's are (`tiles` tiles each, a size no other test + /// pairs: pairs are made by size). The window's address space (4 GiB, a window's) is reserved + /// with no access: a CPU touch of it faults the test. The CPU view is reserved, and committed + /// where the test says. The window's buffer has `tiles` tiles. + struct Views { + s: State, + dev: ID3D12Device, + buf: ID3D12Resource, + /// the title's queue its submits go to + title: ID3D12CommandQueue, + w: usize, + c: usize, + } + + impl Views { + /// None: the device has no reserved buffers + unsafe fn new(tiles: usize) -> Option { + use windows_sys::Win32::System::Memory::MEM_RESERVE; + let dev = test_device(); + let mut buf: Option = None; + dev.CreateReservedResource(&buffer_desc((tiles * TILE) as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut buf).ok()?; + let buf = buf?; + let w = VirtualAlloc(std::ptr::null(), crate::gpu::uma::WINDOW, MEM_RESERVE, PAGE_NOACCESS) as usize; + let c = VirtualAlloc(std::ptr::null(), tiles * TILE, MEM_RESERVE, PAGE_READWRITE) as usize; + assert!(w != 0 && c != 0 && w % TILE == 0 && c % TILE == 0); + crate::hle::kernelx::mirrors::reserved(c, tiles * TILE, 0x2040_2000, PAGE_READWRITE); + crate::hle::kernelx::mirrors::reserved(w, tiles * TILE, 0x2040_2000, 0x801); + assert_eq!(cpu_of(w + 0x1_2345), c + 0x1_2345, "the views are paired"); + let title: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + let mut s = new_state(&dev, vec![(w, buf.clone())]).expect("state"); + // (what its decommits are told of is the test's own) + s.sources = Box::leak(Box::default()); + Some(Views { s, dev, buf, title, w, c }) + } + + /// Commit tiles `k..k + n` of the CPU view. + unsafe fn commit(&self, k: usize, n: usize) { + assert!(!VirtualAlloc((self.c + k * TILE) as *const c_void, n * TILE, MEM_COMMIT, PAGE_READWRITE).is_null()); + } + + /// Write tiles `k..k + n` of the CPU view with bytes made from `seed`. + unsafe fn write(&self, k: usize, n: usize, seed: u64) { + let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + for i in 0..n * TILE / 8 { + *((self.c + k * TILE) as *mut u64).add(i) = next(&mut x); + } + } - // decommitted: parked, still mapped, nothing sent to the GPU - s.decommit_range(base, TILE); - assert!(!s.mapped.contains_key(&base)); - assert_eq!(s.parked.get(&base), Some(&tile)); - assert!(!s.free.contains(&tile)); - assert_eq!(s.value, v, "no tile mapping changed"); - s.release_if_unused(tile); - assert!(!s.free.contains(&tile), "a parked tile is not free"); + /// The bytes of tile `k` of the CPU view. + unsafe fn cpu_tile(&self, k: usize) -> Vec { + std::slice::from_raw_parts((self.c + k * TILE) as *const u8, TILE).to_vec() + } - // committed again: the same tile, cleared, no new mapping - s.to_zero.clear(); - let gen = mapped_gen(); - s.commit_range(base, TILE); - assert_eq!(s.mapped[&base].pool, tile); - assert_eq!(s.mapped[&base].holes, 0); - assert_eq!(s.mapped[&base].not_rw, 0, "recommitted pages use their commit protection"); - assert!(s.parked.is_empty()); - assert_eq!(s.to_zero, vec![(base, TILE)]); - assert_eq!(s.value, v, "no tile mapping changed"); - assert!(mapped_gen() > gen, "readers of `mapped` see it changed"); - mark_protection(&mut s.mapped, base + 2 * PAGE, PAGE, false); - s.decommit_range(base + 2 * PAGE, PAGE); - s.commit_range(base + 2 * PAGE, PAGE); - assert_eq!(s.mapped[&base].not_rw, 0, "a partially recommitted page is writable again"); - s.decommit_range(base + 3 * PAGE, PAGE); - s.commit_range_with_protection(base + 3 * PAGE, PAGE, false); - assert_eq!(s.mapped[&base].not_rw, 1 << 3, "commit and protection publish as one record update"); - s.commit_range(base + 3 * PAGE, PAGE); + /// Tiles `0..n` of the GPU view asked for (`map_mirror`), taken by the test's state as a + /// submit takes them (other tests' asks stay queued). + fn ask(&mut self, n: usize) { + let (lo, hi) = (self.w, self.w + n * TILE); + map_mirror(lo, hi - lo); + MIRROR_ASKS.lock().unwrap().retain(|&t| t < lo || t >= hi); + self.s.asks.extend((lo..hi).step_by(TILE)); + } - // decommitted and flushed (as before a submit): unmapped and free once unmap fence completes - s.decommit_range(base, TILE); - assert!(s.flush_parked()); - assert!(s.parked.is_empty()); - assert!(s.value > v, "the unmapping is sent"); - assert!(!s.flush_parked(), "nothing left to flush"); - s.wait_for(s.value); - assert!(s.drain_quarantined()); - assert!(s.free.contains(&tile)); + /// The tiles of `0..n` queued by `remapped`, taken by the test's state as a submit takes + /// them (other tests' stay queued). + fn take_remaps(&mut self, n: usize) { + let (lo, hi) = (self.w, self.w + n * TILE); + let mut q = REMAPS.lock().unwrap(); + self.s.remaps.extend(q.iter().copied().filter(|&t| t >= lo && t < hi)); + q.retain(|&t| t < lo || t >= hi); + } - // no free tile left: the parked one is flushed and reused once its unmap fence finishes - s.commit_range(base, TILE); - let tile = s.mapped[&base].pool; - s.decommit_range(base, TILE); - s.free.clear(); - assert!(s.flush_parked()); - s.wait_for(s.value); - s.commit_range(base + TILE, TILE); - assert!(s.parked.is_empty()); - assert_eq!(s.mapped[&(base + TILE)].pool, tile); - assert!(!s.mapped.contains_key(&base)); + /// A submit of the title, with the CPU pages `dirty` written since the last. + unsafe fn submit(&mut self, dirty: &[usize]) { + let title = self.title.clone(); + let _ = self.s.before_execute_on(&title, dirty, PAGE); + } - s.wait_for(s.value); - drop(s); - assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + /// `len` bytes at `off` of `res` as the GPU has them, after what was sent to it. + unsafe fn gpu_bytes(&mut self, res: &ID3D12Resource, off: usize, len: usize) -> Vec { + let mut d = buffer_desc(len as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + let mut back: Option = None; + self.dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut back).expect("readback buffer"); + let back = back.expect("readback buffer"); + let alloc: ID3D12CommandAllocator = self.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let list: ID3D12GraphicsCommandList = self.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list"); + list.CopyBufferRegion(&back, 0, res, off as u64, len as u64); + list.Close().expect("Close"); + self.s.flush_pending(); + self.s.queue.ExecuteCommandLists(&[Some(list.cast().expect("list"))]); + self.s.signal(); + self.s.wait_for(self.s.value); + let mut p = std::ptr::null_mut(); + back.Map(0, None, Some(&mut p)).expect("Map"); + let out = std::slice::from_raw_parts(p as *const u8, len).to_vec(); + back.Unmap(0, None); + out } } - struct SignalOnDrop(ID3D12Fence, u64); - - impl Drop for SignalOnDrop { + impl Drop for Views { fn drop(&mut self) { + use windows_sys::Win32::System::Memory::MEM_RELEASE; unsafe { - let _ = self.0.Signal(self.1); + self.s.wait_for(self.s.value); + crate::hle::kernelx::mirrors::released(self.c); + crate::hle::kernelx::mirrors::released(self.w); + VirtualFree(self.c as *mut c_void, 0, MEM_RELEASE); + VirtualFree(self.w as *mut c_void, 0, MEM_RELEASE); } } } - unsafe fn test_state_with_reserved(tiles: usize) -> (usize, State) { - use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; - use windows::Win32::Graphics::Dxgi::*; - use windows_sys::Win32::System::Memory::MEM_RESERVE; - - let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); - let mut dev: Option = None; - if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { - let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); - D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); - } - let dev = dev.expect("D3D12 device"); - let base = VirtualAlloc(std::ptr::null(), tiles * TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; - assert!(base != 0 && base % TILE == 0); - let mut reserved: Option = None; - dev.CreateReservedResource(&buffer_desc((tiles * TILE) as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved) - .expect("CreateReservedResource"); - let reserved = reserved.expect("reserved buffer"); - let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); - let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); - let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); - let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("rb_alloc"); - let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); - rb_list.Close().expect("rb_list close"); - - let s = State { - generation: 1, - mapping_epoch: 0, - coordination: SparseCoordination::new(1, 1).unwrap(), - dev, - queue, - fence, - value: 0, - event, - rb_fence, - rb_value: 0, - windows: vec![(base, reserved)], - pools: Vec::new(), - free: Vec::new(), - retired: Vec::new(), - mapped: FxHashMap::default(), - pinned: FxHashMap::default(), - parked: FxHashMap::default(), - quarantined: VecDeque::new(), - queue_fences: FxHashMap::default(), - buffers: FxHashMap::default(), - to_zero: Vec::new(), - staging: None, - ring_write: 0, - ring_submitted: 0, - ring_free: 0, - inflight: VecDeque::new(), - uploads_ordered: true, - zero_buf: None, - slots: Vec::new(), - next_slot: 0, - readback: None, - rb_alloc, - rb_list, - rb_last_fence: 0, - waited: FxHashMap::default(), - runs: None, - scratch_runs: Vec::new(), - retry_pages: Vec::new(), - }; - (base, s) - } - - unsafe fn add_upload_slot(s: &mut State, fence_val: u64, close: bool) { - let alloc = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("upload allocator"); - let list: ID3D12GraphicsCommandList = s.dev - .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None) - .expect("upload list"); - if close { - list.Close().expect("upload list close"); + /// The tiles of a GPU view are read and written at the CPU view they show, never at their own + /// addresses (reserved with no access, as the title's are: a touch faults): the uploads' + /// sources are in one piece only as far as the CPU view is, and immediates and copies back + /// land in the CPU view. Before, the scan and the copies read the window's own addresses. + #[test] + fn a_mirrored_tile_is_read_and_written_at_its_cpu_view() { + unsafe { + let Some(mut v) = Views::new(37) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 5); + v.write(0, 5, 1); + v.s.asks.extend((0..4).map(|k| w + k * TILE)); + v.s.map_mirrors(); + for k in 0..4 { + let e = &v.s.mapped[&(w + k * TILE)]; + assert_eq!((e.src, e.holes), (c + k * TILE, 0), "tile {k} shows its CPU tile"); + } + assert_eq!(v.s.mirrored, 4); + assert!(v.s.runs.is_empty() && runs_of(&v.s).is_empty(), "the view's own addresses are no CPU memory"); + // the CPU bytes of a run over the tiles are in one piece … + assert_eq!(v.s.cpu_span(w + 0x100, 3 * TILE), (c + 0x100, 3 * TILE)); + // … up to a tile shown over another part of the CPU view … + v.s.mapped.get_mut(&(w + 2 * TILE)).unwrap().src = c + 4 * TILE; + assert_eq!(v.s.cpu_span(w + 0x100, 3 * TILE), (c + 0x100, 2 * TILE - 0x100)); + assert_eq!(v.s.cpu_span(w + 2 * TILE + 0x40, 0x80), (c + 4 * TILE + 0x40, 0x80)); + v.s.mapped.get_mut(&(w + 2 * TILE)).unwrap().src = c + 2 * TILE; + // … or to one of the window's own (the one after the 4th has nothing: its address is + // its own) + assert_eq!(v.s.cpu_span(w + 3 * TILE, 2 * TILE), (c + 3 * TILE, TILE)); + + // filled whole from the CPU view at the next submit + v.submit(&[]); + assert!(v.s.fill.is_empty()); + assert!(v.s.mapped[&w].sent.iter().all(|p| p.is_some()), "every page written went up"); + // an immediate of the GPU lands in the CPU view, and stays sent + let gen = |s: &State, t: usize| s.mapped[&t].gen; + v.s.store_imm(w + 2 * TILE + 0x40, 0x1122_3344_5566_7788, 8, gen(&v.s, w + 2 * TILE)); + assert_eq!(*((c + 2 * TILE + 0x40) as *const u64), 0x1122_3344_5566_7788); + v.s.store_imm(w + 2 * TILE + 0x48, 0xAABB_CCDD, 4, gen(&v.s, w + 2 * TILE)); + assert_eq!(*((c + 2 * TILE + 0x48) as *const u32), 0xAABB_CCDD); + assert!(v.s.chunk_clean(w + 2 * TILE + 0x40), "what landed is what the GPU has: not sent again"); + // so does a copy back … + let back: Vec = (0..256u32).map(|i| i as u8 ^ 0x5A).collect(); + v.s.copy_back(back.as_ptr() as *mut u8, w + 3 * TILE + 0x200, 0, 256, gen(&v.s, w + 3 * TILE), true); + assert_eq!(std::slice::from_raw_parts((c + 3 * TILE + 0x200) as *const u8, 256), &back[..]); + // … but one recorded while the tile showed another part of the CPU view + let before = gen(&v.s, w + TILE); + v.s.drop_mirror(w + TILE); + v.s.link_mirror(w + TILE, c + 4 * TILE); + assert!(v.s.new_mirror(w + TILE, c + 4 * TILE, 0, false)); + let tile = v.cpu_tile(4); + v.s.copy_back(back.as_ptr() as *mut u8, w + TILE, 0, 256, before, true); + assert_eq!(v.cpu_tile(4), tile, "a copy back of what the tile showed before is left out"); + } + } + + /// What the title's CPU writes has to reach the tiles over it: the watched ranges are the CPU + /// tiles (one with no committed page yet too: a write there gives its tile video memory), + /// never the GPU view's own addresses. Forgotten, the tiles give their video memory back. + #[test] + fn the_watch_ranges_of_mirrored_tiles_are_their_cpu_views() { + unsafe { + let Some(mut v) = Views::new(41) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 2); + v.write(0, 2, 2); + v.s.asks.extend((0..3).map(|k| w + k * TILE)); + let gen = mapped_gen(); + v.s.map_mirrors(); + assert!(mapped_gen() > gen, "readers of the ranges see them changed"); + assert_eq!(v.s.watched_ranges(), vec![(c, c + 3 * TILE)]); + assert!(!v.s.mapped.contains_key(&(w + 2 * TILE)), "no committed page: no video memory yet"); + assert_eq!(v.s.mirrors[&(c + 2 * TILE)], vec![w + 2 * TILE]); + assert_eq!(v.s.mirrored, 2); + let gen = mapped_gen(); + v.s.forget_mirrors_in(c, c + 41 * TILE); + assert!(mapped_gen() > gen); + assert!(v.s.watched_ranges().is_empty() && v.s.mirrors.is_empty() && v.s.mirror_src.is_empty()); + assert_eq!(v.s.mirrored, 0); + assert!(v.s.parked.contains_key(&w) && v.s.parked.contains_key(&(w + TILE)), "their video memory goes back"); + v.submit(&[]); } - s.slots.push(UploadSlot { alloc, list, fence_val }); } + /// The CPU view decommitted under a tile (told before Windows does it): its pages are holes, + /// cleared on the GPU and not read again (a read would fault); a page written once committed + /// again is one no more (a lazily committed page of the view). A tile with no committed page + /// left gives its video memory back, and gets it again when its CPU tile is written. #[test] - fn begin_slot_skips_a_busy_head_for_a_ready_slot() { - use windows_sys::Win32::System::Memory::MEM_RELEASE; - + fn a_decommit_of_the_cpu_view_makes_holes_and_parks_the_tile() { unsafe { - let (base, mut s) = test_state_with_reserved(1); - add_upload_slot(&mut s, 9, true); - add_upload_slot(&mut s, 0, true); - - assert!(matches!(s.begin_slot(), BeginSlot::Ready(1))); - assert_eq!(s.next_slot, 0); - s.slots[1].list.Close().expect("selected list close"); - - drop(s); - assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + let Some(mut v) = Views::new(43) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 1); + v.write(0, 1, 3); + // the second tile: its first 8 pages committed, the rest not yet + assert!(!VirtualAlloc((c + TILE) as *const c_void, 8 * PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + std::ptr::write_bytes((c + TILE) as *mut u8, 0x3C, 8 * PAGE); + v.s.asks.extend([w, w + TILE]); + v.s.map_mirrors(); + assert_eq!(v.s.mapped[&(w + TILE)].holes, 0xFF00); + v.submit(&[]); + assert!(v.s.mapped[&w].sent[3].is_some()); + + v.s.source_decommitted_in(c + 3 * PAGE, PAGE); + assert_ne!(VirtualFree((c + 3 * PAGE) as *mut c_void, PAGE, MEM_DECOMMIT), 0); + assert_eq!(v.s.mapped[&w].holes, 1 << 3); + assert!(v.s.mapped[&w].sent[3].is_none(), "the GPU holds zeros there"); + assert!(v.s.to_zero.contains(&(w + 3 * PAGE, PAGE))); + // written before the decommit (the look reports it): asked again, still a hole, not read + v.submit(&[c + 3 * PAGE]); + assert_eq!((v.s.mapped[&w].holes, v.s.counts.rechecks), (1 << 3, 1)); + // a page of the second tile committed on its first write: no hole from that submit on + assert!(!VirtualAlloc((c + TILE + 9 * PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + *((c + TILE + 9 * PAGE + 0x80) as *mut u32) = 0x600D_F00D; + v.submit(&[c + TILE + 9 * PAGE]); + assert_eq!(v.s.mapped[&(w + TILE)].holes, 0xFF00 & !(1 << 9)); + assert!(v.s.mapped[&(w + TILE)].sent[9].is_some(), "and it went up"); + + // the first tile decommitted whole: parked, still wanted over its CPU tile + let pool = v.s.mapped[&w].pool; + v.s.source_decommitted_in(c, TILE); + assert_ne!(VirtualFree(c as *mut c_void, TILE, MEM_DECOMMIT), 0); + assert!(!v.s.mapped.contains_key(&w)); + assert_eq!(v.s.parked.get(&w), Some(&pool)); + assert_eq!((v.s.mirrored, v.s.counts.given_back), (1, 1)); + assert_eq!(v.s.mirrors[&c], vec![w]); + // committed and written again: back from parked, filled whole at the submit + v.commit(0, 1); + *((c + 5 * PAGE) as *mut u8) = 1; + v.s.mirror_writes(&[c + 5 * PAGE], PAGE); + assert_eq!((v.s.mapped[&w].pool, v.s.mapped[&w].holes), (pool, 0)); + assert!(v.s.fill.contains(&w) && v.s.to_zero.contains(&(w, TILE))); + assert_eq!(v.s.mirrored, 2); + v.submit(&[c + 5 * PAGE]); + assert!(v.s.fill.is_empty() && v.s.mapped[&w].sent[5].is_some()); + } + } + + /// `map_mirror` is called while the title records, on any thread: it does not wait for the + /// state (held by a submit around its D3D12 calls), and asks for each tile once. + #[test] + fn map_mirror_does_not_wait_for_the_state() { + // (an address nothing reserves: only the asking is looked at) + const AT: usize = 0x7ff3_0000_0000; + let asked = returns_while_the_state_is_held(|| { + assert_eq!(map_mirror(AT + 0x10, 2 * TILE), 3, "three tiles queued"); + assert_eq!(map_mirror(AT + TILE, 3 * TILE), 1, "the fourth alone is new"); + assert_eq!(map_mirror(AT + 0x20, 0x100), 0, "a range in tiles asked for queues none"); + // (with the state held no submit takes them) + let asks = MIRROR_ASKS.lock().unwrap(); + for k in 0..4 { + assert_eq!(asks.iter().filter(|&&t| t == AT + k * TILE).count(), 1, "tile {k} is asked for once"); + } + }); + assert!(asked, "map_mirror waited for the sparse state's lock"); + // (other tests forget tiles too: the count only goes up) + let before = mirror_asks_forgotten(); + forget_mirrors(AT, 4 * TILE); + assert!(!MIRROR_ASKED.contains(AT) && !MIRROR_ASKS.lock().unwrap().contains(&AT), "forgotten tiles may be asked for again"); + assert!(mirror_asks_forgotten() >= before + 4, "whoever remembers having asked for them is told"); + } + + /// A thread asks for a tile while `forget_mirrors` forgets it: once the forget is done the + /// tile is queued or may be asked for again, and the thread is told to. Before, the asked set + /// lost the tile first, the ask in between queued it anew and the queue lost it after: asked + /// for, in no queue, never mapped (the GPU read zeros there). + #[test] + fn a_tile_asked_for_while_it_is_forgotten_is_not_lost() { + // (an address nothing reserves: only the asking is looked at) + const AT: usize = 0x7ff3_0010_0000; + assert_eq!(map_mirror(AT, TILE), 1); + let between = std::rc::Rc::new(std::cell::Cell::new(None)); + let b = between.clone(); + BETWEEN_FORGETS.with(|f| f.set(Some(Box::new(move || b.set(Some(map_mirror(AT, TILE))))))); + let (counted, before) = (ASKS_FORGOTTEN.with(|n| n.get()), mirror_asks_forgotten()); + forget_mirrors(AT, TILE); + assert_eq!(between.get(), Some(0), "asked for in between: still asked for, not queued anew"); + assert_eq!(ASKS_FORGOTTEN.with(|n| n.get()), counted + 1, "the forget after it is counted"); + assert!(mirror_asks_forgotten() > before); + let queued = MIRROR_ASKS.lock().unwrap().contains(&AT); + assert!(!MIRROR_ASKED.contains(AT) || queued, "asked for and in no queue: never mapped"); + assert_eq!(map_mirror(AT, TILE), 1, "asked for again: queued"); + forget_mirrors(AT, TILE); + } + + /// An asked tile that `take_asks` leaves out (no pair: here past the GPU view's span) leaves + /// the asked set uncounted, and may be asked for again. Counted, an address bound at every + /// draw emptied every thread's memory of its asks at every submit, and every thread asked + /// again. + #[test] + fn an_ask_left_out_is_not_counted_and_may_be_asked_for_again() { + unsafe { + let Some(mut v) = Views::new(127) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let g = v.w + 127 * TILE; + assert_eq!(cpu_of(g), g, "no pair past the views"); + assert_eq!(map_mirror(g + 0x40, 0x100), 1); + // (taken by the test's state as a submit takes them; other tests' asks stay queued) + MIRROR_ASKS.lock().unwrap().retain(|&t| t != g); + v.s.asks.push(g); + let counted = ASKS_FORGOTTEN.with(|n| n.get()); + v.s.map_mirrors(); + assert!(v.s.asks.is_empty() && v.s.mirror_src.is_empty() && !v.s.mapped.contains_key(&g), "left out"); + assert_eq!(ASKS_FORGOTTEN.with(|n| n.get()), counted, "not counted"); + assert_eq!(map_mirror(g, TILE), 1, "asked for again"); + MIRROR_ASKS.lock().unwrap().retain(|&t| t != g); + MIRROR_ASKED.remove(g); + } + } + + /// An ask a submit took that `forget_mirrors_in` drops (its CPU view forgotten) may be asked + /// for again, and the threads that remember asking for it are told. Before, it stayed in the + /// asked set: asked for again, it was not queued. + #[test] + fn an_ask_dropped_by_a_forget_may_be_asked_for_again() { + unsafe { + let Some(mut v) = Views::new(131) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + assert_eq!(map_mirror(w + 0x40, 0x100), 1); + MIRROR_ASKS.lock().unwrap().retain(|&t| t != w); + v.s.asks.push(w); + let (counted, before) = (ASKS_FORGOTTEN.with(|n| n.get()), mirror_asks_forgotten()); + v.s.forget_mirrors_in(c, c + TILE); + assert!(v.s.asks.is_empty(), "the ask over the CPU tile forgotten goes"); + assert_eq!(ASKS_FORGOTTEN.with(|n| n.get()), counted + 1, "and is counted"); + assert!(mirror_asks_forgotten() > before); + assert_eq!(map_mirror(w, TILE), 1, "asked for again"); + MIRROR_ASKS.lock().unwrap().retain(|&t| t != w); + MIRROR_ASKED.remove(w); + } + } + + /// Past `mirror_cap` tiles over CPU views get no video memory (counted once each); room + /// comes back when a CPU tile is decommitted whole, and a refused tile gets it when its CPU + /// tile is written. + #[test] + fn mirrored_tiles_stop_at_the_cap() { + unsafe { + let Some(mut v) = Views::new(47) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 4); + v.write(0, 4, 5); + v.s.mirror_cap = 2; + v.s.asks.extend((0..4).map(|k| w + k * TILE)); + v.s.map_mirrors(); + assert_eq!(v.s.mirrored, 2); + assert!(v.s.mapped.contains_key(&w) && v.s.mapped.contains_key(&(w + TILE))); + assert!(!v.s.mapped.contains_key(&(w + 2 * TILE)) && !v.s.mapped.contains_key(&(w + 3 * TILE))); + assert_eq!(v.s.counts.refused, 2); + assert_eq!(v.s.mirror_src.len(), 4, "the refused ones are still wanted"); + v.s.mirror_writes(&[c + 2 * TILE], PAGE); + assert_eq!((v.s.mirrored, v.s.counts.refused), (2, 2), "refused again, counted once"); + v.s.source_decommitted_in(c, TILE); + assert_ne!(VirtualFree(c as *mut c_void, TILE, MEM_DECOMMIT), 0); + assert_eq!(v.s.mirrored, 1); + v.s.mirror_writes(&[c + 2 * TILE + PAGE], PAGE); + assert!(v.s.mapped.contains_key(&(w + 2 * TILE)), "room again: written, it gets video memory"); + assert_eq!((v.s.mirrored, v.s.counts.refused, v.s.refused.len()), (2, 2, 1)); + v.submit(&[c + 2 * TILE + PAGE]); + } + } + + /// The holes of a CPU view's tiles are asked of Windows once for each region of pages in one + /// state, not once a tile: VirtualQuery walks a region to its end, and a call a tile over a + /// long committed range took the square of its length. They are what `query_tile_holes` says. + #[test] + fn the_holes_of_a_cpu_view_take_a_query_a_region() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + const TILES: usize = 64; + unsafe { + let c = VirtualAlloc(std::ptr::null(), TILES * TILE, MEM_RESERVE, PAGE_READWRITE) as usize; + assert!(c != 0 && !VirtualAlloc(c as *const c_void, TILES * TILE, MEM_COMMIT, PAGE_READWRITE).is_null()); + // (pages never touched are not in the working set: VirtualQuery answers for them) + assert_ne!(VirtualFree((c + 10 * TILE + 5 * PAGE) as *mut c_void, PAGE, MEM_DECOMMIT), 0); + *((c + 20 * TILE) as *mut u8) = 1; + let tiles: Vec = (0..TILES).map(|k| c + k * TILE).collect(); + let q0 = VIRTUAL_QUERIES.with(|n| n.get()); + let holes = source_holes(&tiles); + let queries = VIRTUAL_QUERIES.with(|n| n.get()) - q0; + for (k, &t) in tiles.iter().enumerate() { + assert_eq!(holes[k], query_tile_holes(t), "tile {k}"); + } + assert_eq!(holes[10], 1 << 5); + assert!(queries <= 3, "{queries} VirtualQuery calls for {TILES} tiles in 3 regions"); + assert_ne!(VirtualFree(c as *mut c_void, 0, MEM_RELEASE), 0); } } + /// A tile of a GPU view holds what its CPU view holds once it is asked for (the CPU wrote it + /// before), and follows the CPU's writes, the many small ones too (dispatches) – far into the + /// window and across the 1 GiB a dispatch reaches on a GPU. Before, the GPU read zeros there. #[test] - fn begin_slot_waits_for_the_earliest_busy_slot_without_advancing() { - use windows_sys::Win32::System::Memory::MEM_RELEASE; - + fn a_gpu_view_tile_is_filled_from_its_cpu_view_and_follows_its_writes() { unsafe { - let (base, mut s) = test_state_with_reserved(1); - add_upload_slot(&mut s, 9, true); - add_upload_slot(&mut s, 7, true); - add_upload_slot(&mut s, 8, true); - let ticket = match s.begin_slot() { - BeginSlot::Wait(ticket) => ticket, - _ => panic!("all busy slots did not return a retirement ticket"), - }; - - assert_eq!(s.next_slot, 0); - assert_eq!(ticket.target, 7); - assert!(matches!(ticket.kind, WaitKind::Slot { index: 1, next_slot: 0, fence: 7 })); - assert!(s.wait_ticket_owns_upload(&ticket)); - s.slots[1].fence_val = 10; - assert!(!s.wait_ticket_owns_upload(&ticket), "a changed selected slot accepted its old ticket"); - - drop(s); - assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + let soft = software(&test_device()); + // (the software device takes small reserved buffers only) + let tiles = if soft { 53 } else { (3 << 30) / TILE }; + let ks: [usize; 5] = if soft { [0, 1, 2, 3, 52] } else { [0, 1, (1 << 30) / TILE - 1, (1 << 30) / TILE, tiles - 1] }; + let Some(mut v) = Views::new(tiles) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + for &k in &ks { + v.commit(k, 1); + v.write(k, 1, 7 + k as u64); + } + v.s.asks.extend(ks.iter().map(|&k| v.w + k * TILE)); + v.submit(&[]); + let buf = v.buf.clone(); + for &k in &ks { + assert!(v.gpu_bytes(&buf, k * TILE, TILE) == v.cpu_tile(k), "tile {k} is filled from its CPU view"); + } + // the CPU writes runs of each again + let mut x = 0x1234_5678_9ABC_DEF1u64; + let (mut dirty, mut small) = (Vec::new(), 0usize); + for &k in &ks { + let t = v.c + k * TILE; + let mut o = 0; + loop { + o += CHUNK * (1 + next(&mut x) as usize % 9); + let n = if next(&mut x) % 23 == 0 { SCATTER_RUN + CHUNK * (next(&mut x) as usize % 40) } else { CHUNK * (1 + next(&mut x) as usize % 12) }; + if o + n > TILE { + break; + } + small += (n < SCATTER_RUN) as usize; + for i in 0..n / 8 { + *((t + o) as *mut u64).add(i) = next(&mut x); + } + dirty.extend(((t + o) & !(PAGE - 1)..t + o + n).step_by(PAGE)); + o += n; + } + } + dirty.sort_unstable(); + dirty.dedup(); + assert!(small > SCATTER_FROM * 4, "{small} small runs"); + let before = SCATTERED[1].load(Ordering::Relaxed); + v.submit(&dirty); + if !soft { + assert!(SCATTERED[1].load(Ordering::Relaxed) - before >= SCATTER_FROM as u64, "the small runs went up in dispatches"); + } + for &k in &ks { + assert!(v.gpu_bytes(&buf, k * TILE, TILE) == v.cpu_tile(k), "tile {k} follows its CPU view"); + } } } + /// What the title's lists write into a GPU view (a copy, an immediate) lands in the CPU view + /// behind it, where the title's CPU reads it. Before, it was copied to the view's own + /// addresses, which fault. #[test] - fn begin_slot_reset_failure_does_not_open_or_advance_a_slot() { - use windows_sys::Win32::System::Memory::MEM_RELEASE; - + fn a_gpu_write_into_a_gpu_view_lands_in_its_cpu_view() { unsafe { - let (base, mut s) = test_state_with_reserved(1); - add_upload_slot(&mut s, 0, false); - - assert!(matches!(s.begin_slot(), BeginSlot::RetryRequired)); - assert_eq!(s.next_slot, 0); - - s.slots[0].list.Close().expect("failed selected list close"); - drop(s); - assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + let Some(mut v) = Views::new(59) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 1); + v.s.asks.push(w); + v.submit(&[]); + assert!(v.s.mapped.contains_key(&w)); + let mut up: Option = None; + let mut d = buffer_desc(256); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + v.dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut up).expect("upload buffer"); + let up = up.expect("upload buffer"); + let mut p: *mut c_void = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).expect("Map"); + for i in 0..64u32 { + *(p as *mut u32).add(i as usize) = 0xC0DE_0000 | i; + } + let alloc: ID3D12CommandAllocator = v.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let list: ID3D12GraphicsCommandList = v.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list"); + list.CopyBufferRegion(&v.buf, 0x100, &up, 0, 256); + list.Close().expect("close"); + let title = v.title.clone(); + title.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + v.s.after_execute(&title, &[(w + 0x100, 256)], &[(w + 0x800, 0x0123_4567_89AB_CDEF, 8)]); + let t = std::time::Instant::now(); + while *((c + 0x100) as *const u32) != 0xC0DE_0000 || *((c + 0x800) as *const u64) == 0 { + v.s.drain_readbacks(Drain::TitleDone); + assert!(t.elapsed() < std::time::Duration::from_secs(5), "the copy back did not land"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + for i in 0..64u32 { + assert_eq!(*((c + 0x100) as *const u32).add(i as usize), 0xC0DE_0000 | i, "dword {i}"); + } + assert_eq!(*((c + 0x800) as *const u64), 0x0123_4567_89AB_CDEF, "the immediate"); } } + /// A buffer the title places in a GPU view shows the CPU view behind it: its tiles are the + /// window's, filled from the CPU view (one with no committed page yet too, which the buffer + /// needs: it shows the CPU's writes once they come). Before, its tiles were the view's own + /// uncommitted pages, zeros for good. #[test] - fn upload_wait_releases_and_reacquires_its_ownership_gate() { - let (acquired_tx, acquired_rx) = std::sync::mpsc::channel(); - let (release_tx, release_rx) = std::sync::mpsc::channel(); - let (mut guard, mut timing) = UploadGateTiming::acquire(false); - let worker = std::thread::spawn(move || { - let _crossing_uploader = UPLOAD_GATE.lock().unwrap(); - acquired_tx.send(()).unwrap(); - release_rx.recv().unwrap(); - }); - let released = timing.with_released(&mut guard, || { - let acquired = acquired_rx.recv_timeout(std::time::Duration::from_secs(1)).is_ok(); - release_tx.send(()).unwrap(); - worker.join().unwrap(); - acquired - }); - assert!(released, "another uploader could not cross the fence wait"); - assert!(UPLOAD_GATE.try_lock().is_err(), "the process upload gate was not reacquired"); - let times = timing.finish(); - assert_eq!((times.wait_us, times.hold_us, times.released_us), (0, 0, 0), "disabled timing read the clock"); - drop(guard); + fn a_buffer_placed_in_a_gpu_view_shows_its_cpu_view() { + unsafe { + let Some(mut v) = Views::new(61) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 1); + v.write(0, 1, 11); + let mut res: Option = None; + v.dev.CreateReservedResource(&buffer_desc(2 * TILE as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut res).expect("CreateReservedResource"); + let res = res.expect("reserved buffer"); + let tiles = v.s.buffer_tiles(w, 2 * TILE); + assert_eq!(tiles.iter().map(|t| t.0).collect::>(), vec![w, w + TILE], "both tiles, the one with no committed page too"); + assert_eq!((v.s.mapped[&w].src, v.s.mapped[&(w + TILE)].src), (c, c + TILE)); + assert_eq!(v.s.mapped[&(w + TILE)].holes, 0xFFFF); + v.s.map_tiles(&res, w, &tiles); + for &(_, tile) in &tiles { + *v.s.pinned.entry(tile).or_default() += 1; + } + v.submit(&[]); + assert!(v.gpu_bytes(&res, 0, TILE) == v.cpu_tile(0), "the buffer shows the CPU view"); + assert!(v.gpu_bytes(&res, TILE, TILE) == vec![0u8; TILE]); + v.commit(1, 1); + v.write(1, 1, 12); + let dirty: Vec = (0..PAGES_PER_TILE).map(|i| c + TILE + i * PAGE).collect(); + v.submit(&dirty); + assert!(v.gpu_bytes(&res, TILE, TILE) == v.cpu_tile(1), "and the CPU's writes to it"); + } + } + + /// `n` physical pages of the title mapped at their home, one after the other (a pool for the + /// queue's page mappings whose pages a tile may show): (the pages, the home). None: no unified + /// memory. + unsafe fn home_pages(n: usize) -> Option<(Vec, usize)> { + use crate::hle::kernelx::{AllocateTitlePhysicalPages, MapTitlePhysicalPages}; + crate::gpu::uma::get()?; + let (mut k, mut pages) = (n, vec![0usize; n]); + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut k, pages.as_mut_ptr()), 1); + let home = MapTitlePhysicalPages(std::ptr::null_mut(), n, 0, 4, pages.as_mut_ptr()) as usize; + assert!(home != 0 && home % TILE == 0); + Some((pages, home)) + } + + /// The 64 KiB at `at` written with bytes made from `seed`; returns them. + unsafe fn fill_tile(at: usize, seed: u64) -> Vec { + let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + for i in 0..TILE / 8 { + *(at as *mut u64).add(i) = next(&mut x); + } + std::slice::from_raw_parts(at as *const u8, TILE).to_vec() + } + + /// One call of the queue's page-mapping method: `ranges` (kind, start, count) from GPU-view + /// address `dest` on, in the pool of `pages` pages at `pool`. + unsafe fn map_pages_at(dest: usize, ranges: &[[u32; 3]], pool: usize, pages: u32) { + // (a batch: the first destination, the number of ranges, a pointer to them) + let batch = [dest as u64, ranges.len() as u64, ranges.as_ptr() as u64]; + assert!(crate::hle::kernelx::mirrors::apply_batches(1, batch.as_ptr() as usize, pool, pages).is_some()); + } + + /// A tile of a GPU view shows the page the queue's page mappings put there, from the submit + /// after the call: a mapped page, nothing for an unmapped one (no video memory, still asked + /// for), the CPU view for one never named; the page's later writes, a remap, a page mapped + /// where nothing was (with no new ask) and an unmap. No ask is forgotten on the way, and a + /// range over two pages kept apart is not one piece on the CPU. + #[test] + fn a_tile_of_a_gpu_view_shows_the_page_mapped_there() { + unsafe { + let Some(mut v) = Views::new(163) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let Some((mut pages, h)) = home_pages(3) else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let (w, buf) = (v.w, v.buf.clone()); + let mut pool: Vec> = (0..3).map(|k| fill_tile(h + k * TILE, 40 + k as u64)).collect(); + // three tiles over their CPU view, asked for and filled + v.commit(0, 3); + v.write(0, 3, 44); + v.ask(3); + v.submit(&[]); + assert!(v.s.mapped.contains_key(&(w + TILE))); + let forgotten = ASKS_FORGOTTEN.with(|n| n.get()); + let shown = page_tiles()[0]; + + // pool page 0 at view page 0, view page 1 unmapped, view page 2 left as it is + map_pages_at(w, &[[0, 0, 1], [2, 0, 1]], h, 3); + v.take_remaps(3); + assert_eq!(v.s.remaps, vec![w, w + TILE], "the asked tiles of the changed pages"); + v.submit(&[]); + assert!(v.gpu_bytes(&buf, 0, TILE) == pool[0], "the pool page"); + assert!(!v.s.mapped.contains_key(&(w + TILE)) && !v.s.mirror_src.contains_key(&(w + TILE)), "unmapped: no video memory"); + assert!(MIRROR_ASKED.contains(w + TILE), "and still asked for"); + assert!(v.gpu_bytes(&buf, 2 * TILE, TILE) == v.cpu_tile(2), "never named: its CPU tile"); + assert!(page_tiles()[0] >= shown + 2); + // a write to the pool page goes up + pool[0] = fill_tile(h, 50); + v.submit(&(0..PAGES_PER_TILE).map(|i| h + i * PAGE).collect::>()); + assert!(v.gpu_bytes(&buf, 0, TILE) == pool[0], "the pool page's write"); + + // view page 0 remapped to pool page 2, pool page 1 mapped at view page 1 (asked for + // while unmapped: no new ask) + assert_eq!(map_mirror(w + TILE, 0x100), 0, "still asked for"); + map_pages_at(w, &[[0, 2, 1], [0, 1, 1]], h, 3); + assert_eq!(super::super::view_want::cpu_run((w + TILE - 8) as u64, 16), None, "two pages kept apart"); + v.take_remaps(3); + v.submit(&[]); + assert!(v.gpu_bytes(&buf, 0, TILE) == pool[2], "the new page"); + assert!(v.gpu_bytes(&buf, TILE, TILE) == pool[1], "the page mapped where nothing was"); + // an unmap takes the video memory + map_pages_at(w, &[[2, 0, 1]], h, 3); + v.take_remaps(3); + v.submit(&[]); + assert!(!v.s.mapped.contains_key(&w) && MIRROR_ASKED.contains(w)); + assert_eq!(ASKS_FORGOTTEN.with(|n| n.get()), forgotten, "no ask forgotten on the way"); + + // freed: the tile over a freed page shows nothing + assert_eq!(crate::hle::kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), 3, pages.as_mut_ptr()), 1); + v.take_remaps(3); + v.submit(&[]); + assert!(!v.s.mapped.contains_key(&(w + TILE))); + } + } + + /// A buffer placed over GPU-view tiles keeps its video memory while the pages under it + /// change: a remap shows the new page on the same pool tile, an unmap zeros, and a buffer + /// placed over an unmapped page shows the page once it is mapped there. + #[test] + fn a_buffer_over_a_remapped_tile_reads_the_new_page() { + unsafe { + let Some(mut v) = Views::new(167) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let Some((mut pages, h)) = home_pages(2) else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let w = v.w; + let pool: Vec> = (0..2).map(|k| fill_tile(h + k * TILE, 60 + k as u64)).collect(); + // pool page 0 at view page 0, view page 1 unmapped; the buffer's tiles are asked for + // (as a placed buffer's are, `view_want`) + map_pages_at(w, &[[0, 0, 1], [2, 0, 1]], h, 2); + v.ask(2); + let mut res: Option = None; + v.dev.CreateReservedResource(&buffer_desc(2 * TILE as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut res).expect("CreateReservedResource"); + let res = res.expect("reserved buffer"); + let tiles = v.s.buffer_tiles(w, 2 * TILE); + assert_eq!(tiles.len(), 2); + assert_eq!((v.s.mapped[&w].src, v.s.mapped[&(w + TILE)].src), (h, no_source()), "the unmapped one over nothing"); + v.s.map_tiles(&res, w, &tiles); + for &(_, tile) in &tiles { + *v.s.pinned.entry(tile).or_default() += 1; + } + v.submit(&[]); + assert!(v.gpu_bytes(&res, 0, TILE) == pool[0], "the buffer shows the pool page"); + assert!(v.gpu_bytes(&res, TILE, TILE) == vec![0u8; TILE]); + let (p0, p1) = (v.s.mapped[&w].pool, v.s.mapped[&(w + TILE)].pool); + + // remapped: the new page on the same pool tile + map_pages_at(w, &[[0, 1, 1]], h, 2); + v.take_remaps(2); + v.submit(&[]); + assert!(v.gpu_bytes(&res, 0, TILE) == pool[1], "the buffer reads the new page"); + assert_eq!(v.s.mapped[&w].pool, p0, "on the same pool tile"); + // unmapped: zeros, the pool tile kept + map_pages_at(w, &[[2, 0, 1]], h, 2); + v.take_remaps(2); + v.submit(&[]); + assert!(v.gpu_bytes(&res, 0, TILE) == vec![0u8; TILE], "unmapped: zeros"); + assert_eq!((v.s.mapped[&w].src, v.s.mapped[&w].pool), (no_source(), p0)); + // the page mapped under the buffer's second tile, placed while it was unmapped + map_pages_at(w + TILE, &[[0, 0, 1]], h, 2); + v.take_remaps(2); + v.submit(&[]); + assert!(v.gpu_bytes(&res, TILE, TILE) == pool[0], "shown once mapped"); + assert_eq!((v.s.mapped[&(w + TILE)].src, v.s.mapped[&(w + TILE)].pool), (h, p1)); + + assert_eq!(crate::hle::kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + v.take_remaps(2); + v.submit(&[]); + } + } + + /// A tile follows its page when the page moves (`retarget`): the link moves, and its pool + /// tile, gen and sent hashes stay, with nothing cleared or filled; a scan of the new place + /// sends nothing when its bytes are the same and the chunk written when they differ; a copy + /// back recorded before the move lands at the new place; a page never used, not committed at + /// its new place, gives the video memory up. + #[test] + fn a_tile_follows_its_page_without_being_filled_again() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + unsafe { + let Some(mut v) = Views::new(173) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let Some((mut pages, h)) = home_pages(1) else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let (w, buf) = (v.w, v.buf.clone()); + let bytes = fill_tile(h, 70); + map_pages_at(w, &[[0, 0, 1]], h, 1); + v.ask(1); + v.submit(&[]); + assert!(v.gpu_bytes(&buf, 0, TILE) == bytes, "the page at its home"); + // its bytes copied to another place (as kernelx moves a page), and the tile follows + let r = VirtualAlloc(std::ptr::null(), 2 * TILE, MEM_RESERVE, PAGE_READWRITE) as usize; + assert!(r != 0 && r % TILE == 0 && !VirtualAlloc(r as *const c_void, TILE, MEM_COMMIT, PAGE_READWRITE).is_null()); + std::ptr::copy_nonoverlapping(h as *const u8, r as *mut u8, TILE); + let e = &v.s.mapped[&w]; + let (pool, gen, sent) = (e.pool, e.gen, e.sent.clone()); + let (fills, followed) = (v.s.counts.fills, page_tiles()[1]); + v.s.retarget(w, h, r, true); + let e = &v.s.mapped[&w]; + assert_eq!((e.src, e.holes, e.pool, e.gen), (r, 0, pool, gen), "the link moves, the video memory stays"); + assert!(e.sent == sent, "and what was sent"); + assert_eq!(v.s.mirror_src[&w], r); + assert!(!v.s.mirrors.contains_key(&h) && v.s.mirrors[&r] == vec![w]); + assert!(v.s.fill.is_empty() && v.s.later.is_empty() && v.s.to_zero.range((w, 0)..(w + TILE, 0)).next().is_none(), "nothing cleared or filled"); + assert!(page_tiles()[1] > followed); + v.s.retarget(w, h, r + TILE, true); + assert_eq!(v.s.mirror_src[&w], r, "a tile linked elsewhere stays"); + + // the new place's pages written (kernelx's known write): the same bytes, nothing sent + let dirty: Vec = (0..PAGES_PER_TILE).map(|i| r + i * PAGE).collect(); + v.submit(&dirty); + assert_eq!(v.s.counts.fills, fills, "no fill"); + assert!(v.s.mapped[&w].sent == sent, "nothing sent"); + // a chunk that differs goes up + *((r + 3 * PAGE + 0x40) as *mut u64) ^= 0xFFFF; + v.submit(&[r + 3 * PAGE]); + assert!(v.s.mapped[&w].sent != sent); + assert!(v.gpu_bytes(&buf, 0, TILE) == std::slice::from_raw_parts(r as *const u8, TILE), "the chunk written"); + // a copy back recorded before the move lands at the new place + let back = [0x5Au8; 256]; + v.s.copy_back(back.as_ptr() as *mut u8, w + 0x200, 0, 256, gen, true); + assert_eq!(std::slice::from_raw_parts((r + 0x200) as *const u8, 256), &back[..]); + + // a page never used: not committed at its new place, no video memory for it + v.s.retarget(w, r, r + TILE, false); + assert!(!v.s.mapped.contains_key(&w) && v.s.parked.contains_key(&w) && v.s.later.contains(&(w, r + TILE))); + v.submit(&[]); + assert!(!v.s.mapped.contains_key(&w) && v.s.mirror_src[&w] == r + TILE, "linked, with no video memory until its page is written"); + + assert_eq!(crate::hle::kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), 1, pages.as_mut_ptr()), 1); + v.take_remaps(1); + assert_ne!(VirtualFree(r as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + /// A decommit of the CPU view under way – the state told, Windows not done yet – when a submit + /// asks Windows again about pages of it written before (the look reports them): they stay + /// holes and are not read, and a tile with no page left gets no video memory back. Before, + /// Windows still had them: the submit read them while they were freed, and kept them as + /// committed for good. + #[test] + fn pages_being_decommitted_stay_holes_for_a_submit() { + unsafe { + let Some(mut v) = Views::new(67) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 2); + v.write(0, 2, 13); + v.s.asks.extend([w, w + TILE]); + v.submit(&[]); + assert_eq!((v.s.mapped[&w].holes, v.s.mapped[&(w + TILE)].holes), (0, 0)); + // a page of the first tile and the whole second: the decommitter tells the state … + let p = c + 3 * PAGE; + let (one, shown) = freeing_begins(v.s.sources, p, PAGE); + assert!(shown, "tiles show it"); + v.s.source_decommitted_in(p, PAGE); + let (two, _) = freeing_begins(v.s.sources, c + TILE, TILE); + v.s.source_decommitted_in(c + TILE, TILE); + assert!(!v.s.mapped.contains_key(&(w + TILE))); + // … a submit, with pages of both written before … + v.submit(&[p, c + TILE + 2 * PAGE]); + assert_eq!(v.s.mapped[&w].holes, 1 << 3, "Windows has the page still: a hole all the same"); + assert!(v.s.mapped[&w].sent[3].is_none(), "and not read"); + assert!(!v.s.mapped.contains_key(&(w + TILE)), "no page left: no video memory"); + // … then Windows + assert_ne!(VirtualFree(p as *mut c_void, PAGE, MEM_DECOMMIT), 0); + freeing_ends(v.s.sources, one); + assert_ne!(VirtualFree((c + TILE) as *mut c_void, TILE, MEM_DECOMMIT), 0); + freeing_ends(v.s.sources, two); + assert!(lock_sources(v.s.sources).freeing.is_empty()); + v.submit(&[p, c + TILE + 2 * PAGE]); + assert_eq!(v.s.mapped[&w].holes, 1 << 3); + assert!(!v.s.mapped.contains_key(&(w + TILE))); + } + } + + /// A tile asked for while a decommit of its CPU view is under way (nothing showed that memory + /// when the decommit began, so the state was not told): the pages being decommitted are holes + /// in it and are not read, and a decommit that begins once it is linked finds it. Before, + /// Windows had them still, and the submit filled the tile from them while they were freed. + #[test] + fn a_tile_linked_during_a_decommit_of_its_cpu_view_takes_those_pages_as_holes() { + unsafe { + let Some(mut v) = Views::new(71) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 1); + v.write(0, 1, 17); + let (span, shown) = freeing_begins(v.s.sources, c + 2 * PAGE, 2 * PAGE); + assert!(!shown, "nothing shows it yet: the decommit does not wait for the state"); + v.s.asks.push(w); + v.submit(&[]); + assert_eq!(v.s.mapped[&w].holes, 0b1100); + assert!(v.s.mapped[&w].sent[2].is_none() && v.s.mapped[&w].sent[3].is_none(), "not read"); + assert!(v.s.mapped[&w].sent[4].is_some(), "the rest went up"); + assert_ne!(VirtualFree((c + 2 * PAGE) as *mut c_void, 2 * PAGE, MEM_DECOMMIT), 0); + freeing_ends(v.s.sources, span); + let (span, shown) = freeing_begins(v.s.sources, c + 8 * PAGE, PAGE); + assert!(shown, "linked: a decommit from here on tells the state"); + freeing_ends(v.s.sources, span); + } + } + + /// The pair of a tile asked for goes between its look up and its link (the CPU view released, + /// and its `forget_mirrors` found nothing linked): the tile is not linked, and decommits of + /// that memory do not wait for the state. Before, it stayed linked over memory that may be + /// given out anew. + #[test] + fn a_tile_whose_pair_went_before_its_link_is_left_out() { + unsafe { + let Some(mut v) = Views::new(73) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 1); + v.write(0, 1, 19); + v.s.asks.push(w); + BEFORE_LINK.with(|f| f.set(Some(Box::new(move || crate::hle::kernelx::mirrors::released(c))))); + v.s.map_mirrors(); + assert!(v.s.mirror_src.is_empty() && v.s.mirrors.is_empty() && !v.s.mapped.contains_key(&w)); + assert!(lock_sources(v.s.sources).runs.is_empty()); + assert_eq!(v.s.mirrored, 0); + } } + /// `source_decommit` and `source_release` hold the pages as being freed while Windows frees + /// them (the caller's call, whose result they return), and not after. #[test] - fn replacement_waits_for_every_upload_generation_reader() { - let _placement = PLACEMENT.lock().unwrap(); - let lower_target = UPLOAD_STATE_LIFETIME.read().unwrap(); - let higher_target = UPLOAD_STATE_LIFETIME.read().unwrap(); - let (acquired_tx, acquired_rx) = std::sync::mpsc::channel(); - let replacement = std::thread::spawn(move || { - let _exclusive = UPLOAD_STATE_LIFETIME.write().unwrap(); - acquired_tx.send(()).unwrap(); - }); - - assert!(acquired_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err()); - drop(lower_target); - assert!(acquired_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err(), - "replacement passed the lower target while a higher upload was still in flight"); - drop(higher_target); - acquired_rx.recv_timeout(std::time::Duration::from_secs(1)).expect("replacement stayed blocked after every upload reader retired"); - replacement.join().unwrap(); + fn a_decommit_of_cpu_memory_is_under_way_while_windows_does_it() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + unsafe { + let a = VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert!(a != 0); + let under_way = |s: (usize, usize)| lock_sources(&SOURCES).freeing.contains(&s); + let r = source_decommit(a + PAGE + 0x10, PAGE, || { + assert!(under_way((a + PAGE, a + 3 * PAGE)), "the pages it touches"); + VirtualFree((a + PAGE) as *mut c_void, 2 * PAGE, MEM_DECOMMIT) + }); + assert_ne!(r, 0); + assert!(!under_way((a + PAGE, a + 3 * PAGE))); + let r = source_release(a, TILE, || { + assert!(under_way((a, a + TILE))); + VirtualFree(a as *mut c_void, 0, MEM_RELEASE) + }); + assert_ne!(r, 0); + assert!(!under_way((a, a + TILE))); + } } + /// A CPU view that lies in a sparse window itself (a title's reservation of 64 KiB pages) + /// decommitted there: the tiles over it get the holes too, and a tile with no page left gives + /// its video memory back; the pages are held as being freed while Windows frees them + /// (`decommit`). Before, only the view's own tiles got them, and copies back, immediates and + /// scans through the tiles over it touched the decommitted pages. #[test] - fn a_stalled_upload_ring_yields_without_publishing_hashes() { - use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; - + fn a_decommit_of_a_cpu_view_in_a_window_makes_holes_in_the_tiles_over_it() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; unsafe { - let (base, mut s) = test_state_with_reserved(1); - assert_eq!(VirtualAlloc(base as *mut c_void, TILE, MEM_COMMIT, PAGE_READWRITE) as usize, base); - std::ptr::write_bytes(base as *mut u8, 0x5a, PAGE); - s.commit_range(base, TILE); - s.wait_for(s.value); - let page = std::slice::from_raw_parts(base as *const u8, PAGE); - let mut sent = Box::new(ZERO_HASHES); - changed_chunks(page, &mut sent); - s.mapped.get_mut(&base).unwrap().sent[0] = Some(sent); - let before = *s.mapped[&base].sent[0].as_ref().unwrap().clone(); - - s.ring_write = STAGING as u64; - s.ring_submitted = STAGING as u64; - s.ring_free = 0; - s.inflight.push_back((s.value + 1, STAGING as u64)); - let ticket = match s.upload_dirty_with_timeout(&[(base + CHUNK, 2 * CHUNK)], 20) { - UploadStep::Wait(ticket) => ticket, - UploadStep::Done(_) => panic!("a full ring did not return its retirement ticket"), - }; - assert_eq!(ticket.target, s.value + 1); - assert!(s.wait_ticket_valid(&ticket)); - s.mapping_epoch += 1; - assert!(!s.wait_ticket_valid(&ticket), "a remapped destination accepted an old upload ticket"); - assert!(s.wait_ticket_generation(&ticket), "a remap invalidated the live state generation"); - let after = s.mapped[&base].sent[0].as_ref().unwrap(); - assert_eq!(after.as_ref(), &before, "a failed upload changed the published hash state"); - - let alloc = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); - let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); - list.Close().unwrap(); - s.slots.push(UploadSlot { alloc, list, fence_val: s.value + 1 }); - s.next_slot = 0; - let before_slot = s.next_slot; - let ticket = match s.begin_slot() { - BeginSlot::Wait(ticket) => ticket, - _ => panic!("a busy slot did not return its retirement ticket"), - }; - assert_eq!(s.next_slot, before_slot, "a busy slot advanced before its fence completed"); - assert!(matches!(ticket.kind, WaitKind::Slot { index: 0, next_slot: 0, .. })); - assert!(s.wait_ticket_owns_upload(&ticket)); - s.slots[0].fence_val += 1; - assert!(!s.wait_ticket_owns_upload(&ticket), "a reused slot accepted its predecessor ticket"); - assert!(s.wait_ticket_generation(&ticket), "safe slot reuse invalidated the live generation"); - s.generation += 1; - assert!(!s.wait_ticket_owns_upload(&ticket), "a replacement state accepted an old upload ticket"); - s.uploads_ordered = false; - assert!(matches!( - s.upload_dirty_with_timeout(&[(base + CHUNK, CHUNK)], 20), - UploadStep::Done(PreparationOutcome::ExecutedUntracked) - )); - - drop(s); - assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + let Some(mut v) = Views::new(79) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + let mut own: Option = None; + v.dev.CreateReservedResource(&buffer_desc((79 * TILE) as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut own).expect("CreateReservedResource"); + // (after the GPU view's window: a tile in both is the view's) + v.s.windows.push((c, own.expect("reserved buffer"))); + v.commit(0, 1); + v.s.commit_range(c, TILE); + v.write(0, 1, 23); + v.s.asks.push(w); + v.submit(&[]); + assert_eq!((v.s.mapped[&c].src, v.s.mapped[&w].src, v.s.mapped[&w].holes), (0, c, 0)); + v.s.decommit_range(c + 3 * PAGE, PAGE); + assert_ne!(VirtualFree((c + 3 * PAGE) as *mut c_void, PAGE, MEM_DECOMMIT), 0); + assert_eq!(v.s.mapped[&c].holes, 1 << 3); + assert_eq!(v.s.mapped[&w].holes, 1 << 3, "the tile over it has the hole too"); + assert!(v.s.mapped[&w].sent[3].is_none() && v.s.to_zero.contains(&(w + 3 * PAGE, PAGE))); + v.s.decommit_range(c, TILE); + assert_ne!(VirtualFree(c as *mut c_void, TILE, MEM_DECOMMIT), 0); + assert!(!v.s.mapped.contains_key(&w) && v.s.parked.contains_key(&w), "no page left: its video memory goes back"); + assert_eq!(v.s.mirrored, 0); + // (written before: the look reports it, and nothing reads it) + v.submit(&[c + 5 * PAGE]); + assert!(!v.s.mapped.contains_key(&w)); + + let a = VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert!(a != 0); + let r = decommit(a, PAGE, || { + assert!(lock_sources(&SOURCES).freeing.contains(&(a, a + PAGE)), "being freed while Windows does it"); + VirtualFree(a as *mut c_void, PAGE, MEM_DECOMMIT) + }); + assert_ne!(r, 0); + assert!(!lock_sources(&SOURCES).freeing.contains(&(a, a + PAGE))); + assert_ne!(VirtualFree(a as *mut c_void, 0, MEM_RELEASE), 0); } } + /// A copy back or an immediate recorded before the CPU memory a tile shows changed – a page + /// decommitted and committed again, or the tile shown over another CPU tile – lands nowhere: + /// the GPU's bytes were of the memory before. What is recorded now lands. Before, a copy + /// back compared only the CPU address and an immediate nothing, and the old bytes went into + /// the zero chunks of the new memory. #[test] - fn placement_create_is_unlocked_drains_releases_and_rejects_a_new_generation() { - use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; - + fn a_copy_back_or_immediate_of_memory_since_changed_lands_nowhere() { unsafe { - let (base, mut s) = test_state_with_reserved(2); - assert_eq!(VirtualAlloc(base as *mut c_void, 2 * TILE, MEM_COMMIT, PAGE_READWRITE) as usize, base); - s.commit_range(base, 2 * TILE); - s.wait_for(s.value); - let old_tile = s.mapped[&base].pool; - let new_tile = s.mapped[&(base + TILE)].pool; - - let mut placed: Option = None; - s.dev.CreateReservedResource(&buffer_desc(TILE as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut placed) - .expect("placed resource"); - let placed = placed.unwrap(); - let ptr = placed.as_raw() as usize; - s.buffers.insert(ptr, vec![old_tile]); - s.pinned.insert(old_tile, 1); - - let state = Mutex::new(Some(s)); - let forgotten = Mutex::new(Vec::new()); - let desc = buffer_desc(TILE as u64); - let returned = placed.clone().into_raw(); - let mut unlocked = false; - let result = place_buffer_in( - &state, - &forgotten, - base + TILE, - &desc, - 0, - |_| { - unlocked = state.try_lock().is_ok(); - forget_buffer_in(&state, &forgotten, ptr); - forgotten.lock().unwrap().push(ptr); - Some((0, returned)) - }, - |_| panic!("same-generation placement aborted"), - ); - assert_eq!(result, Some((0, 0))); - assert!(unlocked, "resource creation held sparse STATE"); - { - let g = lock_state_in(&state, &forgotten); - let s = g.as_ref().unwrap(); - assert_eq!(s.buffers.get(&ptr), Some(&vec![new_tile])); - assert!(!s.pinned.contains_key(&old_tile)); - assert_eq!(s.pinned.get(&new_tile), Some(&1)); + let Some(mut v) = Views::new(83) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 2); + v.s.asks.extend([w, w + TILE]); + v.submit(&[]); + let (g0, g1) = (v.s.mapped[&w].gen, v.s.mapped[&(w + TILE)].gen); + // a page of the first CPU tile decommitted, committed again and written in part: asked + // again at the submit, it is no hole + let p = c + 3 * PAGE; + v.s.source_decommitted_in(p, PAGE); + assert_ne!(VirtualFree(p as *mut c_void, PAGE, MEM_DECOMMIT), 0); + assert!(!VirtualAlloc(p as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + *(p as *mut u64) = 0x600D; + v.submit(&[p]); + assert_eq!(v.s.mapped[&w].holes, 0); + let back = vec![0xABu8; 256]; + v.s.copy_back(back.as_ptr() as *mut u8, w + 3 * PAGE, 0, 256, g0, true); + assert_eq!(*(p as *const u64), 0x600D); + assert!(std::slice::from_raw_parts((p + 8) as *const u8, 248).iter().all(|&b| b == 0), "the GPU's old bytes do not land in the new memory"); + // the second tile shown over the first CPU tile: an immediate of before lands nowhere … + v.s.drop_mirror(w + TILE); + v.s.link_mirror(w + TILE, c); + assert!(v.s.new_mirror(w + TILE, c, 0, false)); + v.s.store_imm(w + TILE + 0x80, 0x1234_5678, 8, g1); + assert_eq!(*((c + 0x80) as *const u64), 0); + // … one of now does + v.s.store_imm(w + TILE + 0x80, 0x1234_5678, 8, v.s.mapped[&(w + TILE)].gen); + assert_eq!(*((c + 0x80) as *const u64), 0x1234_5678); + // (a submission's immediates are recorded with the memory they are for) + if v.s.rbq.is_some() { + let title = v.title.clone(); + v.s.after_execute(&title, &[], &[(w + 0x100, 0x77, 8)]); + assert_eq!(v.s.readbacks.lock().unwrap().imm_jobs.back().map(|j| j.writes[0].3), Some(v.s.mapped[&w].gen)); + let t = std::time::Instant::now(); + while !v.s.readbacks.lock().unwrap().imm_jobs.is_empty() { + v.s.drain_readbacks(Drain::TitleDone); + assert!(t.elapsed() < std::time::Duration::from_secs(5), "the immediate did not land"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(*((c + 0x100) as *const u64), 0x77); } - - let original_fence = state.lock().unwrap().as_ref().unwrap().fence.clone(); - let replacement = state.lock().unwrap().as_ref().unwrap().dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); - let returned2 = placed.clone().into_raw(); - let mut aborted = false; - let result = place_buffer_in( - &state, - &forgotten, - base + TILE, - &desc, - 0, - |_| { - state.lock().unwrap().as_mut().unwrap().fence = replacement; - Some((0, returned2)) - }, - |raw| { - aborted = true; - drop(ID3D12Resource::from_raw(raw)); - }, - ); - assert!(result.is_none() && aborted, "a replacement state accepted the old generation's resource"); - state.lock().unwrap().as_mut().unwrap().fence = original_fence; - - drop(ID3D12Resource::from_raw(returned)); - let s = state.lock().unwrap().take().unwrap(); - s.wait_for(s.value); - drop(s); - assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); } } - /// `flush_parked` must keep unmapped pool tiles out of `free` (and `take_tile` must not reuse - /// them) while the sparse queue's unmap fence is still in flight on the GPU. + /// A buffer placed over a tile of a GPU view at `mirror_cap` gets the tile all the same: it + /// maps its tiles once, and the window tile could get video memory later that the buffer + /// would not have. Before, it was left out of the buffer for good. #[test] - fn flush_parked_does_not_free_or_reuse_tiles_while_unmap_is_in_flight() { - use windows_sys::Win32::System::Memory::MEM_RELEASE; - + fn a_buffer_placed_at_the_cap_gets_its_tiles() { unsafe { - let (base, mut s) = test_state_with_reserved(2); - s.commit_range(base, TILE); - let tile = s.mapped[&base].pool; - s.wait_for(s.value); - - let gate: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate fence"); - let _unblock = SignalOnDrop(gate.clone(), 1); - s.queue.Wait(&gate, 1).expect("gate sparse queue"); - - s.decommit_range(base, TILE); - s.free.clear(); - assert!(s.flush_parked()); - assert!(!s.free.contains(&tile), "unmapped tile must remain quarantined until unmap fence completes"); + let Some(mut v) = Views::new(97) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 2); + v.write(0, 2, 31); + v.s.mirror_cap = 1; + v.s.asks.push(w); + v.s.map_mirrors(); + assert_eq!(v.s.mirrored, 1); + let tiles = v.s.buffer_tiles(w + TILE, TILE); + assert_eq!(tiles.iter().map(|t| t.0).collect::>(), vec![w + TILE], "the buffer has its tile"); + assert_eq!(v.s.mapped[&(w + TILE)].src, c + TILE); + assert_eq!((v.s.mirrored, v.s.counts.refused), (2, 0), "it counts"); + v.submit(&[]); + } + } + + /// A tile kept mapped for a placed buffer while its CPU tile was decommitted whole takes its + /// video memory back once the CPU tile is committed and written again, at `mirror_cap` too: + /// the memory is held already. Before, it was refused, and stayed mapped in the window and the + /// buffer with the old bytes while the new ones never went up. + #[test] + fn a_kept_tile_is_taken_back_at_the_cap() { + unsafe { + let Some(mut v) = Views::new(101) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 2); + v.write(0, 2, 37); + v.s.asks.extend([w, w + TILE]); + v.submit(&[]); + let pool = v.s.mapped[&w].pool; + // (a placed buffer uses it) + *v.s.pinned.entry(pool).or_default() += 1; + v.s.source_decommitted_in(c, TILE); + assert_ne!(VirtualFree(c as *mut c_void, TILE, MEM_DECOMMIT), 0); + v.s.flush_parked(); + assert_eq!((v.s.kept.get(&w), v.s.mirrored), (Some(&pool), 1)); + v.s.mirror_cap = 1; + v.commit(0, 1); + v.write(0, 1, 41); + v.s.mirror_writes(&[c + PAGE], PAGE); + assert_eq!(v.s.mapped.get(&w).map(|e| e.pool), Some(pool), "taken back"); + assert_eq!((v.s.mirrored, v.s.counts.refused), (2, 0)); + assert!(v.s.fill.contains(&w)); + v.submit(&[c + PAGE]); + } + } + + /// A tile refused at `mirror_cap` gets video memory at a submit once there is room again, + /// filled with what its CPU view held (written once before, maybe never again); while there + /// is none, a write to its CPU tile does not ask Windows about it. Before, it waited for a + /// write after the room came back, and asked Windows at every write meanwhile. + #[test] + fn a_tile_refused_at_the_cap_gets_video_memory_when_there_is_room() { + unsafe { + let Some(mut v) = Views::new(103) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 2); + v.write(0, 2, 43); + // (the third CPU tile half committed: asked about, the rest takes a VirtualQuery) + assert!(!VirtualAlloc((c + 2 * TILE) as *const c_void, 8 * PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + std::ptr::write_bytes((c + 2 * TILE) as *mut u8, 0x5A, 8 * PAGE); + v.s.mirror_cap = 2; + v.s.asks.extend([w, w + TILE, w + 2 * TILE]); + v.submit(&[]); + assert!(!v.s.mapped.contains_key(&(w + 2 * TILE)) && v.s.refused.contains(&(w + 2 * TILE))); + let q0 = VIRTUAL_QUERIES.with(|n| n.get()); + v.submit(&[c + 2 * TILE]); + assert_eq!(VIRTUAL_QUERIES.with(|n| n.get()), q0, "at the cap, Windows is not asked about it"); + assert!(!v.s.mapped.contains_key(&(w + 2 * TILE))); + // room again (a CPU tile decommitted whole), and no write: it gets its video memory + v.s.source_decommitted_in(c, TILE); + assert_ne!(VirtualFree(c as *mut c_void, TILE, MEM_DECOMMIT), 0); + assert_eq!(v.s.mirrored, 1); + v.submit(&[]); + assert_eq!(v.s.mapped.get(&(w + 2 * TILE)).map(|e| e.holes), Some(0xFF00)); + assert!(v.s.refused.is_empty() && v.s.mirrored == 2 && v.s.counts.refused == 1); + assert!((0..8).all(|i| v.s.mapped[&(w + 2 * TILE)].sent[i].is_some()), "what the CPU view held went up"); + } + } + + /// A tile that found no video memory is refused like one at the cap (not asked for again at + /// every ask), and gets it at a submit once there is some. Before, it was not even recorded: + /// it read zeros until its CPU tile was written again. + #[test] + fn a_tile_refused_for_want_of_video_memory_gets_it_later() { + unsafe { + let Some(mut v) = Views::new(107) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let w = v.w; + v.commit(0, 1); + v.write(0, 1, 47); + // (as after a heap that could not be made) + v.s.no_memory = Some(std::time::Instant::now()); + v.s.asks.push(w); + v.submit(&[]); + assert!(!v.s.mapped.contains_key(&w) && v.s.refused.contains(&w)); + assert_eq!(v.s.counts.refused, 1); + v.s.no_memory = None; + v.submit(&[]); + assert!(v.s.mapped.contains_key(&w) && v.s.refused.is_empty()); + assert!(v.s.mapped[&w].sent.iter().all(|p| p.is_some()), "what the CPU view held went up"); + } + } + + /// A pool tile freed is used again `COOL` after at the earliest, the oldest first and before + /// a tile of `free`. Before, it went to `free` and was the next one taken. + #[test] + fn a_freed_pool_tile_cools_before_it_is_used_again() { + let t0 = std::time::Instant::now(); + let ms = |n: u64| t0 + std::time::Duration::from_millis(n); + let mut free = FreePools::new(); + let mut cooling: VecDeque<((u32, u32), std::time::Instant)> = VecDeque::new(); + cooling.push_back(((0, 5), ms(0))); + cooling.push_back(((0, 6), ms(10))); + assert_eq!(reuse_tile(&mut free, &mut cooling, ms(1999)), None, "freed 1999 ms ago: still cooling"); + assert!(!cooled(&cooling, ms(1999))); + free.push((1, 9)); + assert_eq!(reuse_tile(&mut free, &mut cooling, ms(1999)), Some((1, 9)), "a free tile meanwhile"); + assert!(cooled(&cooling, ms(2000))); + free.push((1, 8)); + assert_eq!(reuse_tile(&mut free, &mut cooling, ms(2005)), Some((0, 5)), "cooled: before a free tile"); + assert_eq!(reuse_tile(&mut free, &mut cooling, ms(2005)), Some((1, 8)), "the next one freed 10 ms later is not"); + cooling.push_back(((2, 1), ms(20))); + assert_eq!(reuse_tile(&mut free, &mut cooling, ms(5000)), Some((0, 6)), "the oldest first"); + assert_eq!(reuse_tile(&mut free, &mut cooling, ms(5000)), Some((2, 1))); + assert_eq!(reuse_tile(&mut free, &mut cooling, ms(5000)), None); + } + + /// The tile mapping line gives the calls and tiles since the counts before, by kind of window. + #[test] + fn the_tile_mapping_line_counts_since_the_last() { + let before = [1, 10, 2, 20, 3, 30, 4, 40]; + assert_eq!(tile_calls_line(&before, &before), None, "no call: no line"); + let now = [2, 74, 2, 20, 3, 30, 7, 41]; + assert_eq!( + tile_calls_line(&now, &before).as_deref(), + Some("sparse windows 1 calls mapping 64 tiles, 0 calls unmapping 0 tiles; GPU views 0 calls mapping 0 tiles, 3 calls unmapping 1 tiles") + ); + } - // While the unmap is still blocked on `gate`, committing another tile must not steal `tile`. - s.commit_range(base + TILE, TILE); - assert_ne!(s.mapped[&(base + TILE)].pool, tile, "in-flight unmapped tile must not be reused before GPU completion"); + /// The GPU-view diagnostics: the poison pattern a switch names, the keep decision within the + /// cap, the buckets of the submits a tile was away, and the line of the counts since the last. + #[test] + fn view_diag_switches_buckets_and_line() { + assert_eq!(poison_pattern(None), None); + assert_eq!(poison_pattern(Some("1")), Some(0x7FC0_DEAD)); + assert_eq!(poison_pattern(Some("0x0000BEEF")), Some(0xBEEF)); + assert_eq!(poison_pattern(Some("0x0")), None, "a zero pattern is no poison"); + assert_eq!(poison_pattern(Some("0xnope")), None); + assert!(!keep_view_tile(false, 1, 10), "off: given back"); + assert!(keep_view_tile(true, 10, 10), "at the cap with this tile: kept"); + assert!(!keep_view_tile(true, 11, 10), "past it (a placed buffer's tiles): given back"); + let buckets: Vec = [0, 1, 2, 8, 9, 64, 65, u64::MAX].into_iter().map(back_bucket).collect(); + assert_eq!(buckets, vec![0, 0, 1, 1, 2, 2, 3, 3]); + let mut before = [0u64; VS]; + before[VS_NOW] = 5; + assert_eq!(view_stats_line(&before, &before), None, "nothing counted: no line"); + let mut now = [7, 3, 2, 1, 4, 0, 1, 0, 3 << 19, 20, 6, 9, 1, 12, 0]; + for (n, b) in now.iter_mut().zip(before.iter_mut()).take(VS_NOW) { + *b = 1; + *n += 1; + } + assert_eq!( + view_stats_line(&now, &before).as_deref(), + Some("GPU-view tiles (2 s): 7 asked for, 3 filled, 2 given back, 1 kept; back after 0-1 / 2-8 / 9-64 / more submits: 4 / 0 / 1 / 0 (1.5 MB filled again); 6 of 20 submits left asked tiles waiting; now 9 with video memory, 1 kept, 12 waiting, 0 refused") + ); + } - gate.Signal(1).expect("release sparse queue"); - s.wait_for(s.value); - assert!(s.drain_quarantined(), "completed unmap batch should drain after fence completion"); - assert!(s.free.contains(&tile), "unmapped tile must return to free list once unmap fence completes"); - drop(_unblock); - s.wait_for(s.value); - drop(s); - assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + /// `XCL_VIEW_KEEP`: a tile whose CPU view is decommitted stays mapped where it is (kept, not + /// parked, so no submit unmaps it), and is taken back from there once its CPU tile is written + /// again, counted in the bucket of the submits it was away. + #[test] + fn a_kept_tile_stays_mapped_and_comes_back() { + unsafe { + let Some(mut v) = Views::new(191) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + (v.s.diag.keep, v.s.diag.stats) = (true, true); + v.commit(0, 1); + v.write(0, 1, 9); + v.s.asks.push(w); + v.s.map_mirrors(); + v.submit(&[]); + let pool = v.s.mapped[&w].pool; + v.s.source_decommitted_in(c, TILE); + assert_ne!(VirtualFree(c as *mut c_void, TILE, MEM_DECOMMIT), 0); + assert_eq!((v.s.kept.get(&w), v.s.parked.get(&w)), (Some(&pool), None)); + assert_eq!((v.s.mirrored, v.s.counts.given_back, v.s.diag.kept), (0, 0, 1)); + v.submit(&[]); + assert_eq!(v.s.kept.get(&w), Some(&pool), "no submit unmaps it"); + v.commit(0, 1); + *((c + 5 * PAGE) as *mut u8) = 1; + v.s.mirror_writes(&[c + 5 * PAGE], PAGE); + assert_eq!((v.s.mapped[&w].pool, v.s.kept.get(&w)), (pool, None), "back from kept"); + assert_eq!((v.s.diag.back, v.s.diag.back_bytes), ([1, 0, 0, 0], TILE as u64), "away one submit"); + v.submit(&[c + 5 * PAGE]); + } + } + + /// `XCL_VIEW_POISON`: a tile of the window without video memory reads the pattern, one with + /// it what was filled there, and one given back the pattern again once a submit unmaps it. + #[test] + fn a_tile_without_video_memory_reads_the_poison() { + unsafe { + let Some(mut v) = Views::new(193) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.s.poison_windows(0x7FC0_DEAD); + assert!(v.s.poison.is_some(), "a poison tile"); + let buf = v.buf.clone(); + let poison: Vec = std::iter::repeat_n(0x7FC0_DEADu32.to_le_bytes(), 8).flatten().collect(); + assert_eq!(v.gpu_bytes(&buf, 0, 32), poison); + assert_eq!(v.gpu_bytes(&buf, 192 * TILE + 0x40, 32), poison, "every tile"); + v.commit(0, 1); + v.write(0, 1, 11); + v.s.asks.push(w); + v.s.map_mirrors(); + v.submit(&[]); + assert_eq!(v.gpu_bytes(&buf, 0, 32), v.cpu_tile(0)[..32].to_vec(), "filled"); + assert_eq!(v.gpu_bytes(&buf, TILE, 32), poison, "the next tile still has none"); + v.s.source_decommitted_in(c, TILE); + assert_ne!(VirtualFree(c as *mut c_void, TILE, MEM_DECOMMIT), 0); + v.submit(&[]); + assert_eq!(v.gpu_bytes(&buf, 0, 32), poison, "given back"); + } + } + + /// A pool goes when all its tiles are free or cooled: one with a tile still cooling stays. + #[test] + fn a_pool_with_a_tile_still_cooling_is_not_retired() { + let t0 = std::time::Instant::now(); + let ms = |n: u64| t0 + std::time::Duration::from_millis(n); + // pool 1 free but its last tile, freed at 0 ms; pool 0 free but its first, freed at 1500 ms + let mut free = FreePools::new(); + for t in 0..POOL_TILES - 1 { + free.push((1, t)); + } + for t in 1..POOL_TILES { + free.push((0, t)); + } + let cooling = VecDeque::from([((1, POOL_TILES - 1), ms(0)), ((0, 0), ms(1500))]); + assert!(free_heaps(&free, &cooling, 2, ms(1999)).is_empty(), "their last tiles are cooling"); + assert_eq!(free_heaps(&free, &cooling, 2, ms(2000)), vec![1], "pool 1's cooled"); + assert_eq!(free_heaps(&free, &cooling, 2, ms(3500)), vec![0, 1]); + let mut partial = FreePools::new(); + for t in 1..POOL_TILES - 1 { + partial.push((1, t)); + } + for t in 1..POOL_TILES { + partial.push((0, t)); + } + assert_eq!(free_heaps(&partial, &cooling, 2, ms(3500)), vec![0], "a tile of pool 1 in use"); + } + + /// `reuse_tile` packs the fullest partially-used pool heap rather than handing out the oldest + /// cooled tile from a nearly-empty heap, so draining heaps become completely empty and retire. + /// Before, FIFO `cooling.pop_front()` re-pinned the nearly-empty heap with new allocations. + #[test] + fn reuse_tile_packs_fuller_heaps_so_nearly_empty_pools_retire() { + let t0 = std::time::Instant::now(); + let ms = |n: u64| t0 + std::time::Duration::from_millis(n); + let mut free = FreePools::new(); + let mut cooling: VecDeque<((u32, u32), std::time::Instant)> = VecDeque::new(); + // Pool 1 is almost empty (1000 tiles freed earlier at 0 ms, only 24 still live). + for t in 24..POOL_TILES { + cooling.push_back(((1, t), ms(0))); + } + // Pool 0 is mostly full (only 24 tiles freed later at 10 ms, 1000 still live). + for t in 0..24 { + cooling.push_back(((0, t), ms(10))); + } + // Allocate 24 new tiles once both have cooled: all 24 must pack into fuller pool 0, + // leaving draining pool 1 untouched. + for _ in 0..24 { + let (h, _) = reuse_tile(&mut free, &mut cooling, ms(2010)).expect("a packed tile"); + assert_eq!(h, 0, "must pack into fuller pool 0 instead of re-pinning draining pool 1"); + } + assert_eq!(free.heap_len(0), 0, "pool 0 is completely packed"); + assert_eq!(free.heap_len(1), (POOL_TILES - 24) as usize, "pool 1 stayed untouched"); + + // When pool 1's remaining 24 tiles free and cool, all of pool 1 is free and ready to retire. + for t in 0..24 { + cooling.push_back(((1, t), ms(2100))); + } + assert_eq!(free_heaps(&free, &cooling, 2, ms(4100)), vec![1]); + + // An all-free heap is skipped while a partially-used heap has space, and `has_empty_heap` + // reports it so `retire_due` retires it even after `cooling` has been drained. + free.push((0, 0)); + free.drain_cooling(&mut cooling, ms(4100)); + assert!(cooling.is_empty()); + assert!(free.has_empty_heap()); + assert_eq!(reuse_tile(&mut free, &mut cooling, ms(4100)), Some((0, 0)), "partial pool 0 before all-free pool 1"); + assert_eq!(free.heap_len(1), POOL_TILES as usize, "all-free pool 1 left intact for retirement"); + assert!(retire_due(&cooling, free.has_empty_heap(), ms(0), ms(4100))); + // When no partial pool remains, the all-free pool is reused instead of creating a new heap. + assert_eq!(reuse_tile(&mut free, &mut cooling, ms(4100)).map(|(h, _)| h), Some(1)); + } + + /// A GPU-view tile given back and unmapped at a submit is not the video memory of the next + /// tile asked for: that gets another, and the tile is used again once it cooled. Before, it + /// was the next tile taken, mapped, cleared and filled on the sparse queue while the title's + /// work submitted before could still read it. + #[test] + fn a_tile_given_back_is_not_used_again_before_it_cooled() { + unsafe { + let Some(mut v) = Views::new(113) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 3); + v.write(0, 3, 59); + v.s.asks.push(w); + v.submit(&[]); + let pool = v.s.mapped[&w].pool; + v.s.forget_mirrors_in(c, c + TILE); + assert_eq!(v.s.parked.get(&w), Some(&pool)); + v.submit(&[]); + // (unmapped at the submit, and quarantined until the GPU is past it) + settle_quarantined(&mut v.s); + assert_eq!(v.s.cooling.iter().map(|t| t.0).collect::>(), vec![pool], "unmapped, cooling"); + v.s.asks.push(w + TILE); + v.submit(&[]); + assert_ne!(v.s.mapped[&(w + TILE)].pool, pool, "another tile"); + // (as 2 s later) + for t in v.s.cooling.iter_mut() { + t.1 = t.1.checked_sub(COOL).expect("an earlier instant"); + } + v.s.asks.push(w + 2 * TILE); + v.submit(&[]); + assert_eq!(v.s.mapped[&(w + 2 * TILE)].pool, pool, "cooled: used again"); + assert!(v.s.cooling.is_empty()); } } - /// `flush_parked` must keep unmapped pool tiles quarantined until every active title queue has - /// finished its prior work, even after `s.queue` itself finishes unmapping. + /// A submit that frees no tile tries to retire pools once a tile cooled or a heap waits to + /// go, `COOL` after the last try at the earliest. #[test] - fn flush_parked_quarantines_tiles_until_title_queues_finish() { - use windows_sys::Win32::System::Memory::MEM_RELEASE; - + fn a_submit_with_nothing_freed_retires_pools_once_tiles_cooled() { + let t0 = std::time::Instant::now(); + let ms = |n: u64| t0 + std::time::Duration::from_millis(n); + // the last tile of a pool freed at 0 ms, by a flush that tried at 0 ms + let cooling = VecDeque::from([((0, 0), ms(0))]); + assert!(!retire_due(&cooling, false, ms(0), ms(1999)), "still cooling"); + assert!(retire_due(&cooling, false, ms(0), ms(2000)), "cooled"); + assert!(!retire_due(&cooling, false, ms(1000), ms(2000)), "tried 1 s ago"); + assert!(!retire_due(&VecDeque::new(), false, ms(0), ms(5000)), "nothing freed, nothing retired"); + assert!(retire_due(&VecDeque::new(), true, ms(0), ms(2000)), "a retired heap to drop"); + assert!(!retire_due(&VecDeque::new(), true, ms(500), ms(2000))); + } + + /// A pool whose last tile a submit freed goes at a submit `COOL` later that frees none. + /// Before, only a submit that freed tiles retired pools, while those it freed still cooled: + /// the pool's 64 MB stayed until the title gave back another tile. + #[test] + fn a_pool_goes_once_its_last_tile_cooled_with_nothing_parked() { unsafe { - let (base, mut s) = test_state_with_reserved(2); - let title_q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + let Some(mut v) = Views::new(113) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 3); + v.write(0, 3, 61); + v.s.asks.push(w); + v.submit(&[]); + let pool = v.s.mapped[&w].pool; + v.s.forget_mirrors_in(c, c + TILE); + v.submit(&[]); + // (unmapped at the submit, and quarantined until the GPU is past it) + settle_quarantined(&mut v.s); + assert_eq!(v.s.cooling.iter().map(|t| t.0).collect::>(), vec![pool], "unmapped, cooling"); + assert!(v.s.pools[pool.0 as usize].is_some(), "its last tile is cooling"); + v.submit(&[]); + assert!(v.s.pools[pool.0 as usize].is_some(), "less than COOL later"); + // (as 2 s later) + for t in v.s.cooling.iter_mut() { + t.1 = t.1.checked_sub(COOL).expect("an earlier instant"); + } + v.s.retire_tried = v.s.retire_tried.checked_sub(COOL).expect("an earlier instant"); + assert!(v.s.parked.is_empty()); + v.submit(&[]); + assert!(v.s.pools[pool.0 as usize].is_none(), "retired with nothing parked"); + assert!(v.s.cooling.is_empty() && !v.s.free.has_pool(pool.0)); + assert_eq!(v.s.retired.len(), 1); + } + } + /// A submit fills tiles from their CPU views up to `fill_pages` committed pages (not tiles): + /// the rest wait for the next submits in their order, and tiles asked for later wait behind + /// them. Before, a submit took 4096 tiles at once (256 MiB hashed and uploaded on the title's + /// thread with the state's lock held). + #[test] + fn a_submit_fills_a_bounded_amount_of_committed_memory_in_order() { + unsafe { + let Some(mut v) = Views::new(109) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + v.commit(0, 6); + v.write(0, 6, 53); + // four CPU tiles with one committed page each + for k in 6..10 { + assert!(!VirtualAlloc((c + k * TILE) as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + *((c + k * TILE) as *mut u64) = k as u64; + } + v.s.fill_pages = 2 * PAGES_PER_TILE; + let shown = |s: &State| (0..10).filter(|&k| s.mapped.contains_key(&(w + k * TILE))).collect::>(); + v.s.asks.extend((0..6).map(|k| w + k * TILE)); + v.submit(&[]); + assert_eq!(shown(&v.s), vec![0, 1], "two whole tiles a submit"); + assert_eq!(v.s.mirror_src.len(), 6, "the rest are linked: their CPU tiles' writes are watched"); + // asked for after: behind the first ones + v.s.asks.extend((6..10).map(|k| w + k * TILE)); + v.submit(&[]); + assert_eq!(shown(&v.s), vec![0, 1, 2, 3]); + v.submit(&[]); + assert_eq!(shown(&v.s), vec![0, 1, 2, 3, 4, 5]); + v.submit(&[]); + assert_eq!(shown(&v.s), (0..10).collect::>(), "four pages: in one submit"); + assert!(v.s.later.is_empty() && v.s.asks.is_empty()); + assert_eq!(v.s.counts.fill_bytes, (6 * PAGES_PER_TILE + 4) as u64 * PAGE as u64); + } + } + + /// A copy back the GPU is done with lands before a submit's tiles change: a page that was a + /// hole when it was recorded, committed and written in part since, does not take what the GPU + /// had there. Before, the submit cleared the hole first, and the copy put the GPU's bytes into + /// the page's zero chunks. + #[test] + fn copies_back_done_land_before_the_tiles_change() { + unsafe { + let Some(mut v) = Views::new(89) else { return crate::gpu::recomp::runner::skip_test("no reserved buffers") }; + let (w, c) = (v.w, v.c); + assert!(!VirtualAlloc(c as *const c_void, 8 * PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + v.s.asks.push(w); + v.submit(&[]); + assert_eq!(v.s.mapped[&w].holes, 0xFF00); + // a copy back of the whole tile, done on the GPU + let mut job = v.s.rb_job(TILE, D3D12_COMMAND_LIST_TYPE_DIRECT).expect("readback job"); + std::ptr::write_bytes(job.ptr, 0xAB, TILE); + job.copies.push((w, 0, TILE, v.s.mapped[&w].gen)); + let fence = || v.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + job.fences = Some((fence(), fence())); + { + let mut rq = v.s.readbacks.lock().unwrap(); + rq.job_seq += 1; + job.seq = rq.job_seq; + rq.rb_jobs.push_back(job); + } + RB_PENDING.fetch_add(1, Ordering::Release); + // a page committed and written in part since + let p = c + 9 * PAGE; + assert!(!VirtualAlloc(p as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + *(p as *mut u64) = 0x600D; + v.submit(&[p]); + assert!(v.s.readbacks.lock().unwrap().rb_jobs.is_empty(), "the copy landed"); + assert_eq!(*((c + 0x40) as *const u8), 0xAB, "in the pages committed then"); + assert_eq!(v.s.mapped[&w].holes, 0xFF00 & !(1 << 9)); + assert_eq!(*(p as *const u64), 0x600D); + assert!(std::slice::from_raw_parts((p + 8) as *const u8, PAGE - 8).iter().all(|&b| b == 0), "not in the page committed since"); + } + } + + struct SendQueue(ID3D12CommandQueue); + unsafe impl Send for SendQueue {} + + struct IsolatedAsyncState { + dev: ID3D12Device, + base: usize, + gen: u32, + state: Arc>>, + rb: Arc, + rb_submit: Arc>, + } + + impl IsolatedAsyncState { + unsafe fn new() -> Self { + let (base, mut s) = test_state_with_reserved(1); + assert!(!VirtualAlloc(base as *const c_void, TILE, MEM_COMMIT, PAGE_READWRITE).is_null()); s.commit_range(base, TILE); - let tile = s.mapped[&base].pool; - s.wait_for(s.value); - - let title_gate: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("title gate fence"); - let _unblock = SignalOnDrop(title_gate.clone(), 1); - title_q.Wait(&title_gate, 1).expect("gate title queue"); - - s.decommit_range(base, TILE); - s.free.clear(); - assert!(s.flush_parked_for(std::slice::from_ref(&title_q), &[], false)); - - // Even after `s.queue` finishes `unmap_tiles`, `title_q` is still gated behind `title_gate`. - s.wait_for(s.value); - assert!(!s.drain_quarantined(), "tile must remain quarantined while title queue has work in flight"); - assert!(!s.free.contains(&tile)); + s.flush_pending(); + std::ptr::write_bytes(base as *mut u8, 0, TILE); + let dev = s.dev.clone(); + let gen = s.mapped[&base].gen; + let rb = Arc::clone(&s.readbacks); + let rb_submit = Arc::clone(&s.rb_submit); + assert!(s.rbq.is_some(), "async readback queue required"); + Self { dev, base, gen, state: Arc::new(Mutex::new(Some(s))), rb, rb_submit } + } - s.commit_range(base + TILE, TILE); - assert_ne!(s.mapped[&(base + TILE)].pool, tile, "must not reuse tile still in use by title queue"); + unsafe fn make_job(&self, byte: u8, len: usize, title_f: ID3D12Fence, done_f: ID3D12Fence, rb_v: u64, done_v: u64) -> RbJob { + let mut job = take_or_alloc_rb_job(&self.dev, &self.rb, len, D3D12_COMMAND_LIST_TYPE_DIRECT).expect("readback job"); + std::ptr::write_bytes(job.ptr, byte, len); + job.copies.clear(); + job.copies.push((self.base, 0, len, self.gen)); + job.rb_v = rb_v; + job.done_v = done_v; + job.fences = Some((title_f, done_f)); + job + } + } - title_gate.Signal(1).expect("release title queue"); - let start = std::time::Instant::now(); - while !s.drain_quarantined() && start.elapsed() < std::time::Duration::from_secs(5) { - std::thread::sleep(std::time::Duration::from_millis(2)); + impl Drop for IsolatedAsyncState { + fn drop(&mut self) { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + let mut old = self.state.lock().unwrap().take(); + if let Some(s) = old.as_mut() { + unsafe { + s.wait_for(s.value); + } + } + drop(old); + unsafe { + let _ = VirtualFree(self.base as *mut c_void, 0, MEM_RELEASE); } - assert!(s.free.contains(&tile), "tile must return to free list after title queue completes"); - drop(_unblock); - s.wait_for(s.value); - drop(s); - assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); } } - /// Sub-tile decommits (two 32 KiB halves, sixteen 4 KiB pages, or decommitting the last - /// remaining committed page) must unmap the tile and return unpinned pool tiles to `free` - /// once `holes` reaches `0xFFFF`, pruning stale `to_zero` entries for unmapped tiles. + /// `settle_readbacks_with` spins on a title-done / copy-pending fence completely outside + /// `STATE`: another thread acquires `STATE` immediately throughout the GPU copy spin. #[test] - fn decommit_sub_tile_reclaims_pool_tile_when_all_pages_become_holes() { - let mut mapped: FxHashMap = FxHashMap::default(); - let mut pinned: FxHashMap<(u32, u32), u32> = FxHashMap::default(); - let mut free: Vec<(u32, u32)> = Vec::new(); - let mut to_zero: Vec<(usize, usize)> = Vec::new(); - - // 1. Two 32 KiB decommits across a full 64 KiB tile. - let t0 = 0x10_0000usize; - mapped.insert(t0, TileEntry::with_holes((0, 10), 0)); - assert!(decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t0, TILE / 2).is_empty()); - assert_eq!(mapped[&t0].holes, 0x00FF); - assert_eq!(to_zero.len(), 8); - assert!(free.is_empty()); + fn settle_readbacks_waits_for_copy_fence_without_holding_state() { + unsafe { + let iso = IsolatedAsyncState::new(); + let title_f: ID3D12Fence = iso.dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).expect("title fence"); + let done_f: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("done fence"); + let _unblock = SignalOnDrop(done_f.clone(), 1); + let mut job = iso.make_job(0xAB, 256, title_f, done_f.clone(), 1, 1); + { + let mut rq = iso.rb.lock().unwrap(); + rq.job_seq += 1; + job.seq = rq.job_seq; + rq.rb_jobs.push_back(job); + } + RB_PENDING.fetch_add(1, Ordering::Release); - let unmapped = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t0 + TILE / 2, TILE / 2); - assert_eq!(unmapped, vec![t0]); - assert!(!mapped.contains_key(&t0)); - assert_eq!(free, vec![(0, 10)]); - assert!(to_zero.is_empty(), "stale to_zero entries for the unmapped tile must be pruned"); + let state_c = Arc::clone(&iso.state); + let rb_c = Arc::clone(&iso.rb); + let settled = std::thread::spawn(move || settle_readbacks_with(&state_c, &rb_c, Drain::TitleDone, 200_000, None)); - // 2. Sixteen individual 4 KiB decommits in reverse order. - let t1 = 0x20_0000usize; - free.clear(); - mapped.insert(t1, TileEntry::with_holes((0, 11), 0)); - for i in (1..PAGES_PER_TILE).rev() { - let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t1 + i * PAGE, PAGE); - assert!(u.is_empty(), "tile still has committed pages after step {i}"); + // Give the settler a moment to enter the fence spin loop. + std::thread::sleep(std::time::Duration::from_millis(5)); + for _ in 0..10 { + let g = iso.state.try_lock(); + assert!(g.is_ok(), "STATE was held during GPU copy fence spin"); + drop(g); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + done_f.Signal(1).expect("signal copy done"); + assert!(settled.join().unwrap()); + assert_eq!(*(iso.base as *const u8), 0xAB, "copy landed after done_f signalled"); + assert!(iso.rb.lock().unwrap().rb_jobs.is_empty()); } - assert!(free.is_empty()); - let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t1, PAGE); - assert_eq!(u, vec![t1]); - assert!(!mapped.contains_key(&t1)); - assert_eq!(free, vec![(0, 11)]); - assert!(to_zero.is_empty()); - - // 3. Pinned tile decommitted in two halves: unmapped from `mapped`, NOT returned to `free`. - let t2 = 0x30_0000usize; - free.clear(); - mapped.insert(t2, TileEntry::with_holes((0, 12), 0)); - pinned.insert((0, 12), 1); - assert!(decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t2, TILE / 2).is_empty()); - let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t2 + TILE / 2, TILE / 2); - assert_eq!(u, vec![t2]); - assert!(!mapped.contains_key(&t2)); - assert!(free.is_empty(), "pinned pool tile must not return to free list"); - assert!(to_zero.is_empty()); - - // 4. Single-committed-page tile decommit reclaims tile without dropping another tile's to_zero. - let t3 = 0x40_0000usize; - let t4 = 0x50_0000usize; - mapped.insert(t3, TileEntry::with_holes((0, 13), 0xFFFF & !(1u16 << 2))); - mapped.insert(t4, TileEntry::with_holes((0, 14), 0)); - assert!(decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t4, PAGE).is_empty()); - assert_eq!(to_zero, vec![(t4, PAGE)]); - let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t3 + 2 * PAGE, PAGE); - assert_eq!(u, vec![t3]); - assert_eq!(free, vec![(0, 13)]); - assert_eq!(to_zero, vec![(t4, PAGE)], "unrelated mapped tile's to_zero must remain"); } - /// The pages in `early`, checking that its ranges are page-aligned, not empty, disjoint and - /// merged (no two touch). - fn early_pages(early: &BTreeMap) -> std::collections::BTreeSet { - let mut last_end = None; - let mut pages = std::collections::BTreeSet::new(); - for (&a, &b) in early { - assert!(a % PAGE == 0 && b % PAGE == 0 && a < b, "range {a:#x}..{b:#x}"); - assert!(last_end.is_none_or(|e| e < a), "range {a:#x}..{b:#x} touches the one before"); - last_end = Some(b); - pages.extend((a..b).step_by(PAGE)); - } - pages - } + /// When pending jobs have not finished on the GPU yet, `settle_readbacks_with` returns + /// promptly without acquiring `STATE` even while another thread holds `STATE`. + #[test] + fn settle_readbacks_skips_state_lock_when_no_job_finished() { + unsafe { + let iso = IsolatedAsyncState::new(); + let title_f: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("title fence"); + let done_f: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("done fence"); + let imm_f: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("imm fence"); + let mut job = iso.make_job(0xCD, 256, title_f, done_f, 1, 1); + { + let mut rq = iso.rb.lock().unwrap(); + rq.job_seq += 1; + job.seq = rq.job_seq; + rq.rb_jobs.push_back(job); + rq.job_seq += 1; + let seq = rq.job_seq; + rq.imm_jobs.push_back(ImmJob { seq, fence: imm_f, value: 1, writes: vec![(iso.base + 0x100, 0x99, 8, iso.gen)] }); + } + RB_PENDING.fetch_add(2, Ordering::Release); + + let held = iso.state.lock().unwrap(); + let state_c = Arc::clone(&iso.state); + let rb_c = Arc::clone(&iso.rb); + let (tx, rx) = std::sync::mpsc::channel(); + let t0 = std::time::Instant::now(); + let worker = std::thread::spawn(move || { + let ok = settle_readbacks_with(&state_c, &rb_c, Drain::TitleDone, 300, Some(5000)); + let _ = tx.send(ok); + }); + let outcome = rx.recv_timeout(std::time::Duration::from_millis(500)); + let took = t0.elapsed(); + drop(held); + worker.join().unwrap(); - /// xorshift64*: the same sequence on every run - fn next(x: &mut u64) -> u64 { - *x ^= *x >> 12; - *x ^= *x << 25; - *x ^= *x >> 27; - x.wrapping_mul(0x2545_F491_4F6C_DD1D) + let ok = outcome.expect("settle blocked on held STATE despite no finished jobs"); + assert!(ok, "unfinished jobs should return true without blocking on STATE"); + assert!(took < std::time::Duration::from_millis(500), "settle waited {took:?} on held STATE despite no finished jobs"); + assert_eq!(iso.rb.lock().unwrap().rb_jobs.len(), 1); + assert_eq!(iso.rb.lock().unwrap().imm_jobs.len(), 1); + } } - /// Before the device exists, commits and decommits leave the pages a plain page set would - /// hold, with the live path's rule (a range counts every page it touches): random ranges, - /// unaligned too, over 300 pages. + /// Concurrent settlers racing on overlapping finished `imm_jobs` and `rb_jobs` land every job + /// in strict ascending `seq` order and never overwrite a newer `seq` with an older one. #[test] - fn early_commits_are_the_pages_a_page_set_holds() { - let base = 0x4_2000_0000usize; - for seed in 1..=8u64 { - let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; - let (mut early, mut model) = (BTreeMap::new(), std::collections::BTreeSet::new()); - for _ in 0..4000 { - let a = base + (next(&mut x) % (300 * PAGE as u64)) as usize; - let n = match next(&mut x) % 4 { - 0 => PAGE, - 1 => 1 + (next(&mut x) % 64) as usize, - _ => 1 + (next(&mut x) % (24 * PAGE as u64)) as usize, - }; - let (start, end) = page_span(a, n); - let pages = (start..end).step_by(PAGE); - if next(&mut x) % 3 == 0 { - early_remove(&mut early, start, end); - pages.for_each(|p| { - model.remove(&p); - }); - } else { - early_add(&mut early, start, end); - model.extend(pages); + fn concurrent_settle_lands_jobs_in_strict_seq_order() { + unsafe { + let iso = IsolatedAsyncState::new(); + let done: ID3D12Fence = iso.dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).expect("done fence"); + for round in 0..16u64 { + *(iso.base as *mut u64) = 0; + let v1 = 0x1111_0000_0000_0000 | round; + let v3 = 0x3333_0000_0000_0000 | round; + let v5 = 0x5555_0000_0000_0000 | round; + let mut j2 = iso.make_job(0x22, 8, done.clone(), done.clone(), 1, 1); + let mut j4 = iso.make_job(0x44, 8, done.clone(), done.clone(), 1, 1); + { + let mut rq = iso.rb.lock().unwrap(); + rq.job_seq += 1; + let s1 = rq.job_seq; + rq.imm_jobs.push_back(ImmJob { seq: s1, fence: done.clone(), value: 1, writes: vec![(iso.base, v1, 8, iso.gen)] }); + rq.job_seq += 1; + j2.seq = rq.job_seq; + rq.rb_jobs.push_back(j2); + rq.job_seq += 1; + let s3 = rq.job_seq; + rq.imm_jobs.push_back(ImmJob { seq: s3, fence: done.clone(), value: 1, writes: vec![(iso.base, v3, 8, iso.gen)] }); + rq.job_seq += 1; + j4.seq = rq.job_seq; + rq.rb_jobs.push_back(j4); + rq.job_seq += 1; + let s5 = rq.job_seq; + rq.imm_jobs.push_back(ImmJob { seq: s5, fence: done.clone(), value: 1, writes: vec![(iso.base, v5, 8, iso.gen)] }); } - assert_eq!(early_pages(&early), model, "seed {seed}"); + RB_PENDING.fetch_add(5, Ordering::Release); + + let bar = Arc::new(std::sync::Barrier::new(4)); + let handles: Vec<_> = (0..4) + .map(|_| { + let s = Arc::clone(&iso.state); + let r = Arc::clone(&iso.rb); + let b = Arc::clone(&bar); + std::thread::spawn(move || { + b.wait(); + assert!(settle_readbacks_with(&s, &r, Drain::TitleDone, 300, None)); + }) + }) + .collect(); + for h in handles { + h.join().unwrap(); + } + assert_eq!(*(iso.base as *const u64), v5, "round {round}: final seq must win"); + let rq = iso.rb.lock().unwrap(); + assert!(rq.rb_jobs.is_empty() && rq.imm_jobs.is_empty() && rq.landing == 0); } + + // In-flight landing visibility check: `landing > 0` forces `wait_and_check_ready` to + // synchronize on `STATE` even after the queues are empty, while the background thread + // check `has_unpopped_finished_jobs` stays false. + iso.rb.lock().unwrap().landing = 1; + assert!(wait_and_check_ready(&iso.rb, Drain::Finished, 0, None) == ReadyCheck::LandNow); + assert!(!has_unpopped_finished_jobs(&iso.rb)); + iso.rb.lock().unwrap().landing = 0; } } - /// The same pages as the list this replaced, for what that list handled exactly: one - /// entry per committed page (`XMemMapPhysicalPagesScatter`, `home_again`) and page-aligned - /// decommits of any length. + /// `readback_after_execute_with` releases `STATE` before acquiring `RB_SUBMIT` and recording + /// D3D12 copy commands, and `land_finished_readbacks` returns excess `RbJob`s beyond the 32-job + /// pool cap so callers drop them outside all locks. #[test] - fn early_commits_match_the_old_list_for_page_entries() { - let base = 0x4_2000_0000usize; - let mut x = 0x1234_5678_9ABC_DEF1u64; - let (mut early, mut old): (BTreeMap, Vec<(usize, usize)>) = (BTreeMap::new(), Vec::new()); - for _ in 0..20000 { - let a = base + (next(&mut x) % 512) as usize * PAGE; - if next(&mut x) % 2 == 0 { - old.push((a, PAGE)); - early_add(&mut early, a, a + PAGE); - } else { - let n = (1 + next(&mut x) % 8) as usize * PAGE; - old.retain(|&(y, m)| y + m <= a || y >= a + n); - early_remove(&mut early, a, a + n); + fn readback_after_execute_records_outside_state_lock_and_drops_excess_outside_locks() { + unsafe { + let iso = IsolatedAsyncState::new(); + let title: ID3D12CommandQueue = iso.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + let mut up: Option = None; + let mut d = buffer_desc(256); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + iso.dev + .CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut up) + .expect("upload buffer"); + let up = up.expect("upload buffer"); + let mut p: *mut c_void = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).expect("Map"); + for i in 0..64u32 { + *(p as *mut u32).add(i as usize) = 0xC0DE_0000 | i; + } + let win_res = iso.state.lock().unwrap().as_ref().unwrap().windows[0].1.clone(); + let alloc: ID3D12CommandAllocator = iso.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let list: ID3D12GraphicsCommandList = iso.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list"); + list.CopyBufferRegion(&win_res, 0, &up, 0, 256); + list.Close().expect("close"); + { + let g = iso.state.lock().unwrap(); + let s = g.as_ref().unwrap(); + title.Wait(&s.fence, s.value).expect("wait mapping"); + } + title.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + + // Hold `rb_submit` before spawning `readback_after_execute_with`: the worker must finish + // its `STATE` snapshot (which takes the submitting token, `SubmittingGuard`), release + // `STATE`, and park on `rb_submit` while the main thread acquires `STATE` cleanly. + let sub_held = iso.rb_submit.lock().unwrap(); + let state_c = Arc::clone(&iso.state); + let q_send = SendQueue(title.clone()); + let base = iso.base; + let worker = std::thread::spawn(move || { + readback_after_execute_with(&state_c, &q_send.0, &[(base, 256)], &[(base + 0x800, 0xCAFE_BABE_1234_5678, 8)]); + }); + let t0 = std::time::Instant::now(); + loop { + // (in the code's order: `STATE`, then the readback queue) + let state = iso.state.lock().unwrap(); + let snapshot_taken = iso.rb.lock().unwrap().submitting > 0; + drop(state); + if snapshot_taken { + break; + } + assert!(t0.elapsed() < std::time::Duration::from_secs(5), "readback_after_execute_with did not release STATE while rb_submit was held"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + drop(sub_held); + worker.join().unwrap(); + + // Settle until the submitted copy back and immediate both land. + let t1 = std::time::Instant::now(); + loop { + if std::ptr::read_volatile(base as *const u32) == 0xC0DE_0000 && std::ptr::read_volatile((base + 0x800) as *const u64) == 0xCAFE_BABE_1234_5678 { + break; + } + assert!(settle_readbacks_with(&iso.state, &iso.rb, Drain::TitleDone, 2000, None)); + assert!(t1.elapsed() < std::time::Duration::from_secs(5), "async readback did not land"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(*((base + 0x800) as *const u64), 0xCAFE_BABE_1234_5678); + + // Part B: excess RbJobs above pool cap (32) are returned to be dropped outside all locks. + let done: ID3D12Fence = iso.dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).expect("done"); + let mut extra_pool = std::mem::take(&mut iso.rb.lock().unwrap().rb_pool); + while extra_pool.len() < 32 { + extra_pool.push(take_or_alloc_rb_job(&iso.dev, &iso.rb, 64 << 10, D3D12_COMMAND_LIST_TYPE_DIRECT).expect("pool job")); + } + let mut f1 = iso.make_job(0x77, 64, done.clone(), done.clone(), 1, 1); + let mut f2 = iso.make_job(0x88, 64, done.clone(), done.clone(), 1, 1); + { + let mut rq = iso.rb.lock().unwrap(); + rq.rb_pool.extend(extra_pool); + assert_eq!(rq.rb_pool.len(), 32); + rq.job_seq += 1; + f1.seq = rq.job_seq; + rq.rb_jobs.push_back(f1); + rq.job_seq += 1; + f2.seq = rq.job_seq; + rq.rb_jobs.push_back(f2); } + RB_PENDING.fetch_add(2, Ordering::Release); + + let excess = { + let mut g = iso.state.lock().unwrap(); + g.as_mut().unwrap().land_finished_readbacks() + }; + assert_eq!(iso.rb.lock().unwrap().rb_pool.len(), 32); + assert_eq!(excess.len(), 2, "excess RbJobs must be returned for drop outside STATE and READBACKS"); + drop(excess); } - let old_pages: std::collections::BTreeSet = old.iter().map(|&(y, _)| y).collect(); - assert_eq!(early_pages(&early), old_pages); } - /// A range committed in one call keeps its other pages when one page of it is decommitted - /// (`commit_homes` commits several pages, `move_home_away` gives one back). The list this - /// replaced dropped the whole entry, so `init` left those still-committed pages as holes. + /// Contention micro-bench: repeated `STATE` acquisitions stay unblocked while another thread + /// continuously spins in `settle_readbacks_with` on a title-done / copy-pending fence. #[test] - fn early_decommit_of_one_page_keeps_the_rest() { - let a = 0x4_2000_0000usize; - let mut early = BTreeMap::new(); - early_add(&mut early, a, a + 4 * TILE); - early_remove(&mut early, a + TILE, a + 2 * TILE); - assert_eq!(early.into_iter().collect::>(), vec![(a, a + TILE), (a + 2 * TILE, a + 4 * TILE)]); - } + fn state_lock_latency_stays_unblocked_under_readback_spin_contention() { + unsafe { + let iso = IsolatedAsyncState::new(); + let title_f: ID3D12Fence = iso.dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).expect("title fence"); + let done_f: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("done fence"); + let _unblock = SignalOnDrop(done_f.clone(), 1); + let mut job = iso.make_job(0x5A, 256, title_f, done_f.clone(), 1, 1); + { + let mut rq = iso.rb.lock().unwrap(); + rq.job_seq += 1; + job.seq = rq.job_seq; + rq.rb_jobs.push_back(job); + } + RB_PENDING.fetch_add(1, Ordering::Release); + + let stop = Arc::new(AtomicBool::new(false)); + let state_c = Arc::clone(&iso.state); + let rb_c = Arc::clone(&iso.rb); + let stop_c = Arc::clone(&stop); + let spinner = std::thread::spawn(move || { + let mut spins = 0u32; + while !stop_c.load(Ordering::Acquire) { + assert!(settle_readbacks_with(&state_c, &rb_c, Drain::TitleDone, 2000, None)); + spins += 1; + } + spins + }); - /// Time for n 64 KiB pages committed one at a time and decommitted one at a time in - /// reverse, before the device exists (`cargo test --release -p xcl --lib -- - /// --ignored --exact hle::d3d12x::sparse::tests::early_commit_timing --nocapture`, - /// `XCL_EARLY_PAGES=16384,32768`). Run it alone: a test that made the device keeps a state. - #[test] - #[ignore] - fn early_commit_timing() { - if STATE.lock().unwrap().is_some() { - return eprintln!("early_commit_timing: a sparse state exists – run it alone"); - } - let sizes: Vec = std::env::var("XCL_EARLY_PAGES").ok().map_or(vec![4096, 8192, 16384, 32768], |v| v.split(',').map(|s| s.trim().parse().unwrap()).collect()); - let base = 0x4_2000_0000usize; - for n in sizes { - let t = std::time::Instant::now(); - for i in 0..n { - unsafe { committed(base + i * TILE, TILE) }; + std::thread::sleep(std::time::Duration::from_millis(5)); + let mut waits_us = Vec::with_capacity(50); + for _ in 0..50 { + let t0 = std::time::Instant::now(); + let g = iso.state.lock().unwrap(); + waits_us.push(t0.elapsed().as_micros() as u64); + drop(g); + std::thread::sleep(std::time::Duration::from_millis(1)); } - let commit = t.elapsed(); - let t = std::time::Instant::now(); - for i in (0..n).rev() { - unsafe { decommitted(base + i * TILE, TILE) }; + stop.store(true, Ordering::Release); + done_f.Signal(1).expect("signal done"); + let spins = spinner.join().unwrap(); + assert!(settle_readbacks_with(&iso.state, &iso.rb, Drain::TitleDone, 2000, None)); + + waits_us.sort_unstable(); + let p50 = waits_us[waits_us.len() / 2]; + let p99 = waits_us[(waits_us.len() * 99) / 100]; + let max = *waits_us.last().unwrap(); + eprintln!("sparse lock-split contention bench ({spins} spin calls): STATE lock wait p50={p50} us, p99={p99} us, max={max} us"); + assert!(spins >= 5, "spinner ran too few iterations ({spins})"); + assert!(p99 < 1000, "STATE lock p99={p99} us exceeded 1000 us under readback spin contention"); + } + } + + /// An async readback plan prepared under `STATE` remains visible to concurrent settling + /// callers via `ReadbackQueue::submitting` until `submit_async_readback` publishes or cancels + /// it: even when an unrelated unfinished readback is already queued, a fence observer waits + /// within its budget instead of returning early with a stale CPU value, returns `false` if its + /// budget expires before publication, and wakes immediately on plan cancellation. + #[test] + fn settle_waits_for_in_flight_plan_publication_and_handles_cancellation() { + unsafe { + let iso = IsolatedAsyncState::new(); + let title_q: ID3D12CommandQueue = iso.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + let dst = iso.base + 0x800; + std::ptr::write_volatile(dst as *mut u64, 0x1111_2222_3333_4444); + + // Push an unrelated GPU-unfinished job first so `RB_PENDING > 0` already holds. + let unfin_title: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("unfin title"); + let unfin_done: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("unfin done"); + let mut unfin_job = iso.make_job(0xEE, 64, unfin_title, unfin_done, 1, 1); + { + let mut rq = iso.rb.lock().unwrap(); + rq.job_seq += 1; + unfin_job.seq = rq.job_seq; + rq.rb_jobs.push_back(unfin_job); } - let decommit = t.elapsed(); - println!("early: {n} pages: commit {:.1} ms, decommit {:.1} ms", commit.as_secs_f64() * 1e3, decommit.as_secs_f64() * 1e3); + RB_PENDING.fetch_add(1, Ordering::Release); + + // Submitter prepares an immediate write under `STATE`, drops `STATE`, signals the + // title fence, waits until that GPU fence completes, then pauses right before + // publishing into `ReadbackQueue`. + let (paused_tx, paused_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let state_c = Arc::clone(&iso.state); + let q_send = SendQueue(title_q.clone()); + let submitter = std::thread::spawn(move || { + let (plan, excess) = { + let mut g = state_c.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.note_queue(&q_send.0); + s.prepare_after_execute(&q_send.0, &[], &[(dst, 0xDEAD_BEEF_CAFE_BABE, 8)]) + }; + drop(excess); + let plan = plan.expect("immediate write must produce an async readback plan"); + let hook = move |title_f: &ID3D12Fence, v: u64| { + let t0 = std::time::Instant::now(); + while crate::hle::d3d12x::real::fence_completed(title_f) < v { + assert!(t0.elapsed() < std::time::Duration::from_secs(5), "title fence did not complete"); + std::thread::yield_now(); + } + let _ = paused_tx.send(()); + let _ = release_rx.recv(); + }; + submit_async_readback_inner(&q_send.0, plan, Some(&hook)); + }); + + paused_rx.recv_timeout(std::time::Duration::from_secs(5)).expect("submitter did not reach publication pause"); + assert_eq!(iso.rb.lock().unwrap().submitting, 1); + assert!(iso.state.try_lock().is_ok(), "STATE must already be released during publication pause"); + + // Bounded settle that expires while publication is still paused returns `false` + // instead of claiming success before the immediate is published. + assert!(!settle_readbacks_with(&iso.state, &iso.rb, Drain::TitleDone, 300, Some(20))); + assert_eq!(std::ptr::read_volatile(dst as *const u64), 0x1111_2222_3333_4444); + + // A fence observer with sufficient budget waits for publication, then lands the + // completed immediate before reporting success. + let (obs_tx, obs_rx) = std::sync::mpsc::channel(); + let obs_state = Arc::clone(&iso.state); + let obs_rb = Arc::clone(&iso.rb); + let observer = std::thread::spawn(move || { + let ok = settle_readbacks_with(&obs_state, &obs_rb, Drain::TitleDone, 300, Some(2000)); + let _ = obs_tx.send(ok); + }); + assert!( + obs_rx.recv_timeout(std::time::Duration::from_millis(25)).is_err(), + "observer returned early before paused plan published" + ); + release_tx.send(()).expect("release publication"); + let ok = obs_rx.recv_timeout(std::time::Duration::from_secs(2)).expect("observer did not wake after publication"); + assert!(ok, "observer should settle and return true once plan publishes"); + assert_eq!( + std::ptr::read_volatile(dst as *const u64), + 0xDEAD_BEEF_CAFE_BABE, + "CPU destination must hold the immediate value when observer returns" + ); + observer.join().unwrap(); + submitter.join().unwrap(); + assert_eq!(iso.rb.lock().unwrap().submitting, 0); + + // Plan cancellation (e.g. bail on fence allocation failure): dropping `AsyncReadbackPlan` + // decrements `submitting`, balances `RB_PENDING`, and wakes waiting observers cleanly. + let (cancelled_plan, excess) = { + let mut g = iso.state.lock().unwrap(); + g.as_mut().unwrap().prepare_after_execute(&title_q, &[], &[(dst, 0x5555, 8)]) + }; + drop(excess); + let cancelled_plan = cancelled_plan.expect("plan for cancellation test"); + assert_eq!(iso.rb.lock().unwrap().submitting, 1); + let (w_tx, w_rx) = std::sync::mpsc::channel(); + let rb_c = Arc::clone(&iso.rb); + let waiter = std::thread::spawn(move || { + let r = wait_and_check_ready(&rb_c, Drain::TitleDone, 0, Some(std::time::Instant::now() + std::time::Duration::from_secs(2))); + let _ = w_tx.send(r); + }); + std::thread::sleep(std::time::Duration::from_millis(10)); + drop(cancelled_plan); + let ready = w_rx.recv_timeout(std::time::Duration::from_secs(1)).expect("waiter did not wake on plan drop"); + waiter.join().unwrap(); + assert!(ready == ReadyCheck::NothingReady); + assert_eq!(iso.rb.lock().unwrap().submitting, 0); } } } diff --git a/crates/xcl/src/hle/d3d12x/standin.rs b/crates/xcl/src/hle/d3d12x/standin.rs index 27bec34145..bc5aa6ea31 100644 --- a/crates/xcl/src/hle/d3d12x/standin.rs +++ b/crates/xcl/src/hle/d3d12x/standin.rs @@ -46,7 +46,9 @@ struct Shared { impl Drop for Shared { fn drop(&mut self) { unsafe { - unref(self.pipeline); + // (lists in flight may bind it: it goes once the queues are past them, as XCL's other + // pipelines do – `late_release::hold_pipeline`) + let_go(self.pipeline); if self.root_signature != 0 { unref(self.root_signature); } @@ -56,6 +58,16 @@ impl Drop for Shared { static SHARED: Mutex>>> = Mutex::new(None); +/// A driver pipeline no shell stands on any more is let go (its reference is taken over). +fn let_go(pipeline: usize) { + // (a test keeps what would be held, on its own thread) + #[cfg(test)] + if tests::LET_GO.with(|l| l.borrow_mut().as_mut().map(|v| v.push(pipeline)).is_some()) { + return; + } + super::late_release::hold_pipeline(pipeline); +} + unsafe fn method(obj: usize, slot: usize) -> usize { *(*(obj as *const *const usize)).add(slot) } @@ -266,6 +278,16 @@ fn vtable() -> usize { mod tests { use super::*; + thread_local! { + /// Some: the driver pipelines `let_go` would hold, kept here instead + pub(super) static LET_GO: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + } + + /// What `let_go` was given on this thread since the last call (and keeps it from now on). + fn let_go_taken() -> Vec { + LET_GO.with(|l| l.borrow_mut().replace(Vec::new()).unwrap_or_default()) + } + /// A COM object that counts its references and has one interface. #[repr(C)] struct Counted { @@ -311,6 +333,7 @@ mod tests { #[test] fn pipelines_of_one_key_share_a_driver_pipeline_while_one_of_them_lives() { let (rs, a, b) = (counted(), counted(), counted()); + let_go_taken(); unsafe { let (s1, d1) = shell(key(rs, 1), || Ok(at(a))).unwrap(); let (s2, d2) = shell(key(rs, 1), || panic!("made again")).unwrap(); @@ -321,17 +344,44 @@ mod tests { assert_eq!(refs(rs), 3, "the root signature is held by each driver pipeline"); assert_eq!(release(s1), 0); assert_eq!(refs(a), 1, "still stands in for the second"); + assert_eq!(let_go_taken(), Vec::::new(), "still stands in for the second"); assert_eq!(release(s2), 0); - assert_eq!((refs(a), refs(rs)), (0, 2), "gone with the last"); + // lists in flight may bind it: let go (held until the queues are past them), not + // released here + assert_eq!((refs(a), refs(rs)), (1, 2), "the root signature goes with the last"); + assert_eq!(let_go_taken(), vec![at(a)], "the pipeline is let go with the last"); + unref(at(a)); + assert_eq!(refs(a), 0, "gone with the last"); let c = counted(); let (s4, d4) = shell(key(rs, 1), || Ok(at(c))).unwrap(); assert_eq!(d4, at(c), "made again when none of its key is alive"); release(s3); release(s4); assert_eq!(refs(rs), 1); + assert_eq!(let_go_taken(), vec![at(b), at(c)]); assert_eq!(shell(key(rs, 9), || Err(E_INVALIDARG)).err(), Some(E_INVALIDARG)); assert_eq!(refs(rs), 1); + assert_eq!(let_go_taken(), Vec::::new(), "nothing made, nothing let go"); + } + LET_GO.with(|l| l.borrow_mut().take()); + } + + /// The driver pipeline of a key's last shell goes through `late_release`: released once the + /// queues are past the lists that may bind it (at once with `XCL_LATE_RELEASE=0`). + #[test] + fn a_driver_pipeline_let_go_is_released_once_the_queues_are_past_it() { + let (rs, a) = (counted(), counted()); + unsafe { + let (s, _) = shell(key(rs, 5), || Ok(at(a))).unwrap(); + assert_eq!(release(s), 0); + } + assert_eq!(refs(rs), 1); + // (a queue XCL knows of may still be busy: the batch waits for its fence) + let start = std::time::Instant::now(); + while refs(a) != 0 && start.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(5)); } + assert_eq!(refs(a), 0, "released once the queues are past"); } #[test] @@ -368,8 +418,12 @@ mod tests { assert_eq!(set_private_data_interface(s, &id, at(held)), S_OK); release(s); assert_eq!(refs(held), 2, "let go with the object"); + let_go_taken(); release(other); + assert_eq!(let_go_taken(), vec![at(a)]); + unref(at(a)); assert_eq!(refs(a), 0); } + LET_GO.with(|l| l.borrow_mut().take()); } } diff --git a/crates/xcl/src/hle/d3d12x/submit_cost.rs b/crates/xcl/src/hle/d3d12x/submit_cost.rs new file mode 100644 index 0000000000..f0da57f19a --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/submit_cost.rs @@ -0,0 +1,222 @@ +//! Diagnostic: where the time of a title's submit (ExecuteCommandLists) goes, as averages over the +//! last 1024 of them (logged; a few relaxed adds a submit). + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +/// Cumulative microseconds by stage, and the submits counted. +static SUM: [AtomicU64; STAGES] = [const { AtomicU64::new(0) }; STAGES]; +const LOCK: usize = 0; +const REFRESH: usize = 1; +const DRIVER: usize = 2; +const AFTER: usize = 3; +const TOTAL: usize = 4; +const N: usize = 5; +const RECHECK: usize = 6; +const RANGES: usize = 7; +const TEXTURES: usize = 8; +/// what lies between the stages above: the whole call of the refresh (its lock wait and the +/// refresh with what it does around them), the lists made ready for the PC, the waits for a list's +/// previous submit, the whole of the lists' submission (the driver and after stages of each piece +/// with the work between pieces), and the end after it +const CALL: usize = 9; +const LISTS: usize = 10; +const PREVIOUS: usize = 11; +const EXEC: usize = 12; +const END: usize = 13; +/// between the pieces of a submit split at a wait (`list_x::execute_with_waits_on`): the waits, +/// the sparse windows brought up to date again, and how many splits (a count) +const SPLIT_WAITS: usize = 14; +const SPLIT_SPARSE: usize = 15; +const SPLITS: usize = 16; +const STAGES: usize = 17; + +pub(super) fn add(stage: usize, d: Duration) { + SUM[stage].fetch_add(d.as_micros() as u64, Ordering::Relaxed); +} + +pub(super) fn call(d: Duration) { + add(CALL, d); +} + +pub(super) fn lists(d: Duration) { + add(LISTS, d); +} + +pub(super) fn previous(d: Duration) { + add(PREVIOUS, d); +} + +pub(super) fn exec(d: Duration) { + add(EXEC, d); +} + +pub(super) fn end(d: Duration) { + add(END, d); +} + +/// A submit was split at a wait: the wait's time, and that of the sparse windows' update after it. +pub(super) fn split(waits: Duration, sparse: Duration) { + add(SPLIT_WAITS, waits); + add(SPLIT_SPARSE, sparse); + SUM[SPLITS].fetch_add(1, Ordering::Relaxed); +} + +/// The part of the average line for what lies outside the stages it names, from the averages a +/// submit (`ms`, ms; `SPLITS` as a count a submit): the refresh's call around its lock wait and +/// itself, the lists made ready, the waits for previous submits, the splits (the submission but its +/// driver and after stages and those waits), and the end. +fn outside_part(ms: &[f64; STAGES]) -> String { + let entry = (ms[CALL] - ms[LOCK] - ms[REFRESH]).max(0.0); + let splits = (ms[EXEC] - ms[DRIVER] - ms[AFTER] - ms[PREVIOUS]).max(0.0); + format!( + "outside them: entry {:.2}, lists {:.2}, previous submits {:.2}, splits {:.2} (waits {:.2}, sparse again {:.2}; {:.2} a submit), end {:.2}", + entry, ms[LISTS], ms[PREVIOUS], splits, ms[SPLIT_WAITS], ms[SPLIT_SPARSE], ms[SPLITS], ms[END] + ) +} + +/// the wait for the refresh lock, and the refresh itself +pub(super) fn lock_wait(d: Duration) { + add(LOCK, d); +} + +pub(super) fn refresh(d: Duration) { + add(REFRESH, d); +} + +/// the PC ExecuteCommandLists of a chunk of the title's lists, and everything XCL does after it +pub(super) fn driver(d: Duration) { + add(DRIVER, d); +} + +pub(super) fn after(d: Duration) { + add(AFTER, d); +} + +/// parts of the refresh: re-checking the sources in GPU views, the watched ranges, the textures' +/// uploads (beside the parts `sparse` counts) +pub(super) fn recheck(d: Duration) { + add(RECHECK, d); +} + +pub(super) fn ranges(d: Duration) { + add(RANGES, d); +} + +pub(super) fn textures(d: Duration) { + add(TEXTURES, d); +} + +/// The texture uploads: [looked at, unchanged, uploaded, bytes compared, bytes uploaded, µs +/// comparing, batches, µs uploading]. +static TEX: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; + +/// Textures with written pages were compared with what those held. +pub(super) fn textures_compared(textures: usize, unchanged: usize, bytes: usize, took: Duration) { + TEX[0].fetch_add(textures as u64, Ordering::Relaxed); + TEX[1].fetch_add(unchanged as u64, Ordering::Relaxed); + TEX[3].fetch_add(bytes as u64, Ordering::Relaxed); + TEX[5].fetch_add(took.as_micros() as u64, Ordering::Relaxed); +} + +/// A batch of textures, or of parts of them, went up. +pub(super) fn textures_uploaded(textures: usize, bytes: usize, took: Duration) { + TEX[2].fetch_add(textures as u64, Ordering::Relaxed); + TEX[4].fetch_add(bytes as u64, Ordering::Relaxed); + TEX[6].fetch_add(1, Ordering::Relaxed); + TEX[7].fetch_add(took.as_micros() as u64, Ordering::Relaxed); +} + +/// A whole submit (from the hook's entry) is done. +pub(super) fn done(t0: Instant) { + add(TOTAL, t0.elapsed()); + // `XCL_LOOK_STATS=2`: the title's submits for `api_cost` (and the thread that makes them), + // not XCL's own ones inside a submit or a present: those are in that one's time + if super::look_stats::deep() && !super::title_textures::is_own_work() && !super::present::presenting() { + crate::hle::api_cost::note_submitter(); + crate::hle::api_cost::add(crate::hle::api_cost::Call::Submit, t0.elapsed()); + } + let n = SUM[N].fetch_add(1, Ordering::Relaxed) + 1; + if n % 1024 != 0 { + return; + } + struct Last { + sum: [u64; STAGES], + parts: [u64; 4], + tex: [u64; 8], + at: Instant, + } + static LAST: Mutex> = Mutex::new(None); + let mut g = LAST.lock().unwrap(); + let now: [u64; STAGES] = std::array::from_fn(|i| SUM[i].load(Ordering::Relaxed)); + // [look, STATE lock wait, chunk scan, upload] µs inside the refreshes + let parts = super::sparse::timing_totals(); + let tex: [u64; 8] = std::array::from_fn(|i| TEX[i].load(Ordering::Relaxed)); + if let Some(l) = g.as_ref() { + let x = |i: usize| tex[i].saturating_sub(l.tex[i]); + crate::xlog_info!( + "submit cost, textures in these 1024: {} with written pages ({} unchanged), {:.1} MB compared in {:.1} ms; {} uploaded, {:.1} MB in {} batches, {:.1} ms", + x(0), + x(1), + x(3) as f64 / 1e6, + x(5) as f64 / 1e3, + x(2), + x(4) as f64 / 1e6, + x(6), + x(7) as f64 / 1e3 + ); + let d = |i: usize| now[i].saturating_sub(l.sum[i]) as f64 / 1024.0 / 1000.0; + let p = |i: usize| parts[i].saturating_sub(l.parts[i]) as f64 / 1024.0 / 1000.0; + let refresh = d(REFRESH); + let mut ms: [f64; STAGES] = std::array::from_fn(d); + ms[SPLITS] = now[SPLITS].saturating_sub(l.sum[SPLITS]) as f64 / 1024.0; + crate::xlog_info!( + "submit cost, average of 1024 ExecuteCommandLists: {:.2} ms in all = {:.2} refresh lock wait + {:.2} refresh (look {:.2}, ranges {:.2}, recheck {:.2}, sparse lock {:.2}, scan {:.2}, upload {:.2}, textures {:.2}, rest {:.2}) + {:.2} driver + {:.2} after ({:.0} submits/s); {}", + d(TOTAL), + d(LOCK), + refresh, + p(0), + d(RANGES), + d(RECHECK), + p(1), + p(2), + p(3), + d(TEXTURES), + refresh - p(0) - p(1) - p(2) - p(3) - d(RANGES) - d(RECHECK) - d(TEXTURES), + d(DRIVER), + d(AFTER), + 1024.0 / l.at.elapsed().as_secs_f64().max(1e-3), + outside_part(&ms) + ); + } + *g = Some(Last { sum: now, parts, tex, at: Instant::now() }); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The part for what lies outside the named stages: the refresh's call less its lock wait and + /// itself, the submission less its driver, after and previous-submit parts; never below 0. + #[test] + fn the_outside_part_is_what_the_named_stages_leave() { + let mut ms = [0.0f64; STAGES]; + ms[LOCK] = 0.5; + ms[REFRESH] = 5.0; + ms[CALL] = 5.75; + ms[LISTS] = 0.1; + ms[DRIVER] = 0.25; + ms[AFTER] = 1.0; + ms[PREVIOUS] = 0.5; + ms[EXEC] = 3.0; + ms[SPLIT_WAITS] = 0.25; + ms[SPLIT_SPARSE] = 1.0; + ms[SPLITS] = 0.5; + ms[END] = 0.2; + assert_eq!(outside_part(&ms), "outside them: entry 0.25, lists 0.10, previous submits 0.50, splits 1.25 (waits 0.25, sparse again 1.00; 0.50 a submit), end 0.20"); + ms[CALL] = 1.0; + ms[EXEC] = 0.0; + assert!(outside_part(&ms).starts_with("outside them: entry 0.00, lists 0.10, previous submits 0.50, splits 0.00")); + } +} diff --git a/crates/xcl/src/hle/d3d12x/targets.rs b/crates/xcl/src/hle/d3d12x/targets.rs new file mode 100644 index 0000000000..3dbf42db17 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/targets.rs @@ -0,0 +1,918 @@ +//! `XCL_DUMP_TARGETS=[,[,]]`: what a busy frame draws into. In the first +//! `frames` frames (default 1) with at least `work` draws and dispatches, every render target the +//! frame drew into (and the depth buffer bound most) is logged with how its draws went – ran, drew +//! nothing (a stand-in while the pipeline is built), went to the PC untranslated, skipped – and +//! the `targets` drawn into most (default eight, 64 at most) are written next to the presented +//! frame (`target_.bmp`) with how many of their texels are not zero and how many differ from +//! the first one. A black picture over a scene that was drawn tells a lost composite from a scene +//! that never was; the passes after the scene's (a few draws each) are among the last ranks. +//! `XCL_DUMP_AFTER_S=`: no frame is dumped until `s` seconds after the first present. +//! +//! A draw counts for the frame whose PresentX follows its recording (bundles, and lists executed +//! twice or never, are not exact); an ExecuteIndirect counts once, whatever its count. +//! Multisampled and non-2D targets are logged as not dumped; an array dumps its subresource 0. +//! The depth buffer is not copied: XCL does not know the state the title left it in, and a copy +//! from DEPTH_WRITE (possibly compressed) is invalid – the present list would not close. +//! Targets are kept by address only (not AddRef'd): `present::view_resource` hands one out only +//! while a view still names it, and one released meanwhile is logged as released. +//! +//! Each target written also lists the pipelines that drew into it in that frame (the 12 with +//! most draws): their shader set (`real::shaders_key`), each stage's shader (`real::shader_key`, +//! and the dump hash the `[SHADER]` lines and the debug switches take), render target 0's blend +//! state and the formats as the title made them, and what the first draw with it read through +//! its descriptor tables that is not a target written. The console VS and PS of each are kept +//! when the pipeline is made (512 MiB of them at most) and translated again on a thread of their +//! own after the dump: `target__.hlsl` and `.rdna2.txt` (the disassembly) +//! go next to the pictures. Pipelines are known only once made through +//! CreateGraphicsPipelineState (or a stream of console VS / PS) with the switch on. +//! The switch also follows 3D textures and reads the small ones back at a dump (`lut3d`). +//! The dump also lists every compute pipeline the frame dispatched, in order of first use: its +//! CS, its direct and indirect dispatches, the groups of the first direct one and of the largest, +//! and the first indirect one's arguments when they were in unified memory when it was recorded. +//! The first `COMPUTE_FILES_MOST` get `compute_cs_.hlsl` and `.rdna2.txt` the same way +//! (made through CreateComputePipelineState with the switch on; the HLSL even when the pipeline +//! runs direct DXIL, whose file names the path the running DXIL took). + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// targets dumped of one frame when the switch names no number, and the most it may name +const DUMPED: usize = 8; +const DUMPED_MOST: usize = 64; + +/// How a draw went: ran on its translated pipeline, drew nothing (a stand-in for a pipeline still +/// being built), went to the PC untranslated, or was skipped. +pub const RAN: usize = 0; +pub const STANDIN: usize = 1; +pub const PC: usize = 2; +pub const SKIPPED: usize = 3; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Config { + /// draws and dispatches a frame needs + work: u64, + /// frames to dump + frames: u64, + /// no dump before this long after the first present + after: Duration, + /// targets written of a frame + targets: usize, +} + +fn config() -> Option { + static C: OnceLock> = OnceLock::new(); + *C.get_or_init(|| { + let v = std::env::var("XCL_DUMP_TARGETS").ok()?; + let Some((work, frames, targets)) = parse(&v) else { + crate::xlog_warn!("D3D12.X: XCL_DUMP_TARGETS={v:?} is not [,[,]]: no targets dumped"); + return None; + }; + let after = match std::env::var("XCL_DUMP_AFTER_S") { + Ok(s) => parse_after(&s).unwrap_or_else(|| { + crate::xlog_warn!("D3D12.X: XCL_DUMP_AFTER_S={s:?} is not a number of seconds: dumps start at once"); + Duration::ZERO + }), + Err(_) => Duration::ZERO, + }; + Some(Config { work, frames, after, targets }) + }) +} + +/// (work, frames, targets written of a frame: 1 ..= `DUMPED_MOST`) +fn parse(v: &str) -> Option<(u64, u64, usize)> { + let mut it = v.split(',').map(|s| s.trim().parse::()); + let work = it.next()?.ok()?; + let frames = match it.next() { + Some(n) => n.ok()?, + None => 1, + }; + let targets = match it.next() { + Some(n) => n.ok()? as usize, + None => DUMPED, + }; + (work > 0 && frames > 0 && targets > 0 && it.next().is_none()).then_some((work, frames, targets.min(DUMPED_MOST))) +} + +/// `XCL_DUMP_AFTER_S`: seconds, fractions too (None: not a number of seconds) +fn parse_after(v: &str) -> Option { + v.trim().parse::().ok().and_then(|s| Duration::try_from_secs_f64(s).ok()) +} + +pub fn enabled() -> bool { + config().is_some() +} + +/// What a frame drew: its draws and dispatches, and the draws into each target by outcome. +#[derive(Default, Debug, PartialEq)] +pub struct Frame { + work: u64, + targets: HashMap, + depth: HashMap, + /// draws by (target, pipeline) + by: HashMap<(usize, usize), u64>, + /// what the first draw with each pipeline read (`bind::table_resources`) + inputs: HashMap>, + /// the compute pipelines dispatched, in order of first use, and where each is in it + computes: Vec, + compute_at: HashMap, +} + +/// A dispatch: a direct one's groups, or an indirect one's arguments as read when it was +/// recorded (None: not in memory the CPU reads). +pub enum Dispatched { + Direct([u32; 3]), + Indirect(Option), +} + +/// A compute pipeline's dispatches in a frame. +#[derive(Clone, Debug, Default, PartialEq)] +struct Compute { + pso: usize, + direct: u64, + indirect: u64, + /// groups of the first direct dispatch, and of the one with most groups + first: Option<[u32; 3]>, + largest: Option<[u32; 3]>, + /// the first indirect one's arguments (`Dispatched::Indirect`) + first_indirect: Option>, +} + +/// A resource a draw read through its descriptor tables, described when it drew. +#[derive(Clone, Debug, PartialEq)] +struct Input { + res: usize, + /// D3D12_RESOURCE_DIMENSION; width, height, depth or array size, mips, format + dimension: i32, + width: u64, + height: u32, + depth: u16, + mips: u16, + format: i32, +} + +impl Frame { + /// Draws with pipeline `pso` into `targets`: true for the frame's first draw with it (its + /// inputs are noted once). + fn drew_with(&mut self, targets: &[usize], pso: usize) -> bool { + for &t in targets { + *self.by.entry((t, pso)).or_default() += 1; + } + let first = !self.inputs.contains_key(&pso); + self.inputs.entry(pso).or_default(); + first + } + + /// A dispatch with compute pipeline `pso`. + fn dispatched(&mut self, pso: usize, d: Dispatched) { + let k = *self.compute_at.entry(pso).or_insert_with(|| { + self.computes.push(Compute { pso, ..Default::default() }); + self.computes.len() - 1 + }); + let c = &mut self.computes[k]; + match d { + Dispatched::Direct(g) => { + let groups = |g: [u32; 3]| g.iter().map(|&n| n as u64).product::(); + c.direct += 1; + c.first.get_or_insert(g); + if c.largest.map_or(true, |l| groups(g) > groups(l)) { + c.largest = Some(g); + } + } + Dispatched::Indirect(a) => { + c.indirect += 1; + c.first_indirect.get_or_insert(a); + } + } + } + + /// The pipelines that drew into `target`, most draws first (ties: by address), the first + /// `most` of them, and how many more there were. + fn pipelines_of(&self, target: usize, most: usize) -> (Vec<(usize, u64)>, usize) { + let mut v: Vec<(usize, u64)> = self.by.iter().filter(|((t, _), _)| *t == target).map(|(&(_, p), &n)| (p, n)).collect(); + v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + let more = v.len().saturating_sub(most); + v.truncate(most); + (v, more) + } + + fn draw(&mut self, targets: &[usize], depth: Option, outcome: usize) { + self.work += 1; + for &t in targets { + self.targets.entry(t).or_default()[outcome] += 1; + } + if let Some(d) = depth { + self.depth.entry(d).or_default()[outcome] += 1; + } + } + + /// targets by draws into them, most first (ties: by address, for a stable order) + fn ranked(&self) -> Vec<(usize, [u64; 4])> { + let mut v: Vec<(usize, [u64; 4])> = self.targets.iter().map(|(&t, &n)| (t, n)).collect(); + v.sort_by(|a, b| b.1.iter().sum::().cmp(&a.1.iter().sum()).then(a.0.cmp(&b.0))); + v + } + + /// the depth buffer drawn with most + fn depth(&self) -> Option<(usize, [u64; 4])> { + self.depth.iter().map(|(&d, &n)| (d, n)).max_by(|a, b| a.1.iter().sum::().cmp(&b.1.iter().sum()).then(b.0.cmp(&a.0))) + } +} + +/// the frame being recorded +static FRAME: Mutex> = Mutex::new(None); +/// frames dumped so far (their copies submitted) +static DONE: AtomicU64 = AtomicU64::new(0); +/// the frame to dump at the next present that gets as far as copying +static PENDING: Mutex> = Mutex::new(None); + +/// A draw on `list` with `outcome`: it counts for each render target and the depth buffer bound. +pub unsafe fn note_draw(list: *mut c_void, outcome: usize) { + if !enabled() { + return; + } + let mut targets: Vec = super::list_x::bound_render_targets(list).into_iter().filter_map(super::present::rtv_resource).collect(); + targets.sort_unstable(); + targets.dedup(); + for &t in &targets { + super::lut3d::wrote(t, false, || format!("drawn into as a render target (pipeline {:#x})", super::bind::bound_pso(list))); + } + let depth = super::list_x::bound_dsv(list).and_then(super::present::rtv_resource); + let pso = super::bind::bound_pso(list); + let first = { + let mut g = FRAME.lock().unwrap(); + let f = g.get_or_insert_with(Frame::default); + f.draw(&targets, depth, outcome); + f.drew_with(&targets, pso) + }; + if first { + // (described now: the title draws with them, so they are alive) + let inputs: Vec = super::bind::table_resources(list) + .into_iter() + .filter_map(|r| { + let d = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void))?.GetDesc(); + Some(Input { res: r, dimension: d.Dimension.0, width: d.Width, height: d.Height, depth: d.DepthOrArraySize, mips: d.MipLevels, format: d.Format.0 }) + }) + .collect(); + FRAME.lock().unwrap().get_or_insert_with(Frame::default).inputs.insert(pso, inputs); + } +} + +/// A dispatch: work of the frame. +pub fn note_dispatch() { + if enabled() { + FRAME.lock().unwrap().get_or_insert_with(Frame::default).work += 1; + } +} + +/// A dispatch with compute pipeline `pso` (the object the title bound): listed in the dump. +pub fn note_compute(pso: usize, d: Dispatched) { + if enabled() { + FRAME.lock().unwrap().get_or_insert_with(Frame::default).dispatched(pso, d); + } +} + +/// An ExecuteIndirect of up to `max` dispatches with `pso`: its first command at `commands` +/// (address, bytes there) and its count at `count` when they are in unified memory, read now +/// (what the title wrote there by the time it recorded); `plain`: a signature of the dispatch +/// argument alone; `counted`: it has a count buffer. +pub unsafe fn note_indirect_compute(pso: usize, commands: Option<(usize, usize)>, count: Option, counted: bool, max: u32, plain: bool) { + if !enabled() { + return; + } + let count = match count.filter(|&p| crate::gpu::shader::readable(p, 4)) { + Some(p) => format!(", count {}", (p as *const u32).read_unaligned()), + None if counted => ", count on the GPU".into(), + None => String::new(), + }; + let words = |p: usize, n: usize| (0..n).map(|k| ((p + 4 * k) as *const u32).read_unaligned()).collect::>(); + let args = match commands { + Some((p, n)) if plain && n >= 12 && crate::gpu::shader::readable(p, 12) => { + let w = words(p, 3); + Some(format!("arguments {}x{}x{} (max {max}{count})", w[0], w[1], w[2])) + } + Some((p, n)) if !plain && n >= 4 && crate::gpu::shader::readable(p, n.min(32)) => { + Some(format!("a command with root arguments, its first dwords {:x?} (max {max}{count})", words(p, n.min(32) / 4))) + } + _ => None, + }; + note_compute(pso, Dispatched::Indirect(args)); +} + +/// Whether a frame of `work` is dumped, `done` frames dumped before it, `since` the first present. +fn due(c: &Config, work: u64, done: u64, since: Duration) -> bool { + work >= c.work && done < c.frames && since >= c.after +} + +/// The title presents: a frame that did enough work is dumped at the next present that copies +/// (one still waiting for that is kept, and this one dropped). +pub fn frame_end() { + let Some(c) = config() else { return }; + static T0: OnceLock = OnceLock::new(); + let t0 = *T0.get_or_init(Instant::now); + let f = FRAME.lock().unwrap().take().unwrap_or_default(); + if !due(&c, f.work, DONE.load(Ordering::Relaxed), t0.elapsed()) { + return; + } + PENDING.lock().unwrap().get_or_insert(f); +} + +/// The frame to dump at this present, if any (`submitted` once its copies are on the GPU). +pub fn take_pending() -> Option { + if !enabled() { + return None; + } + PENDING.lock().unwrap().take() +} + +/// The copies of a frame taken by `take_pending` were submitted: it counts as dumped. +pub fn submitted() { + DONE.fetch_add(1, Ordering::Relaxed); +} + +/// Logs what frame `n` drew into; the targets to copy for its dump: (tag, resource, desc). +pub unsafe fn to_dump(n: u64, f: &Frame) -> Vec<(String, ID3D12Resource, D3D12_RESOURCE_DESC)> { + let ranked = f.ranked(); + let dumped = config().map_or(DUMPED, |c| c.targets); + crate::xlog_info!("D3D12.X: target dump of frame {n}: {} draws and dispatches, {} render targets drawn into", f.work, ranked.len()); + let mut out = Vec::new(); + let (mut sizes, mut left, mut written) = (Vec::new(), Vec::new(), Vec::new()); + let depth = f.depth().map(|(r, c)| (usize::MAX, r, c)); + for (k, r, c) in ranked.into_iter().enumerate().map(|(k, (r, c))| (k, r, c)).chain(depth) { + let res = super::present::view_resource(r); + let d = res.as_ref().map(|x| x.GetDesc()); + let what = d.map_or("released".into(), |d| format!("{}x{} format {}", d.Width, d.Height, d.Format.0)); + let copyable = d.is_some_and(|d| d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && d.SampleDesc.Count <= 1); + // past the readback cap: this target and every later one are left out + let capped = k < dumped && copyable && { + sizes.push(d.map_or(0, |d| readback_bytes(&d))); + dumped_within(&sizes, DUMP_BYTES_MOST) < sizes.len() + }; + let tag = match (k, copyable) { + (usize::MAX, _) => " (not dumped: its state is not known)".into(), + (k, true) if k < dumped && capped => format!(" (not dumped: target{k} is past the readback cap)"), + (k, true) if k < dumped => format!(" → target{k}"), + (_, false) if d.is_some() => " (not dumped)".into(), + _ => String::new(), + }; + crate::xlog_info!( + "D3D12.X: target dump: {} {r:#x} {what}: {} draws (ran {}, stand-in {}, PC {}, skipped {}){tag}", + if k == usize::MAX { "depth buffer" } else { "render target" }, + c.iter().sum::(), + c[RAN], + c[STANDIN], + c[PC], + c[SKIPPED] + ); + if let (true, Some(res), Some(d)) = (k < dumped && copyable, res, d) { + if capped { + left.push(format!("target{k}")); + } else { + out.push((format!("target{k}"), res, d)); + written.push((k, r)); + } + } + } + if !left.is_empty() { + crate::xlog_warn!("D3D12.X: target dump of frame {n}: {} of {} targets left out, past {} MiB of readback: {}", left.len(), out.len() + left.len(), DUMP_BYTES_MOST >> 20, left.join(" ")); + } + let mut files = log_pipelines(n, f, &written); + files.extend(log_computes(n, f)); + if !files.is_empty() { + if let Some(dir) = crate::state::boot().map(|b| b.logs_dir()) { + let _ = std::thread::Builder::new().name("xcl-dump-shaders".into()).spawn(move || { + write_shaders(&dir, files, HLSL_BYTES_MOST); + crate::xlog_info!("D3D12.X: target dump: the shaders of the pipelines listed are written to {}", dir.display()); + }); + } + } + out +} + +/// compute pipelines of a frame whose shaders a dump writes at most +const COMPUTE_FILES_MOST: usize = 400; + +/// The files of a frame's `k`th compute pipeline's shader: `compute_cs_` (.hlsl, .rdna2.txt). +fn compute_stem(k: usize, key: u64) -> String { + format!("compute{k}_cs_{key:016x}") +} + +/// `x`x`y`x`z`, or "none" +fn groups_text(g: Option<[u32; 3]>) -> String { + g.map_or("none".into(), |g| format!("{}x{}x{}", g[0], g[1], g[2])) +} + +/// Logs the compute pipelines frame `n` dispatched, in order of first use; the shader files of +/// the first `COMPUTE_FILES_MOST` of them. +fn log_computes(n: u64, f: &Frame) -> Vec { + let mut files = Vec::new(); + if f.computes.is_empty() { + return files; + } + crate::xlog_info!("D3D12.X: target dump of frame {n}: {} compute pipelines dispatched, in order of first use", f.computes.len()); + let pipelines = PIPELINES.lock().unwrap().clone().unwrap_or_default(); + for (k, c) in f.computes.iter().enumerate() { + let translated = super::real::is_translated_compute(super::pso_async::peek(c.pso)); + let cs = pipelines.get(&c.pso).and_then(|p| p.stages.iter().find(|s| s.0 == "cs").map(|s| (s.1, s.2, s.3.clone(), p.split))); + let shader = cs.as_ref().map_or("cs not known (made before the switch)".into(), |(key, h, ..)| format!("cs {key:016x} (dump hash {h:016x})")); + let indirect = match &c.first_indirect { + None => String::new(), + Some(Some(a)) => format!("; the first indirect one: {a}"), + Some(None) => "; the first indirect one: arguments on the GPU".into(), + }; + crate::xlog_info!( + "D3D12.X: target dump: compute #{k} pipeline {:#x}: {shader}, {} dispatches ({} direct, {} indirect), groups of the first direct one {}, largest {}{indirect}; translated {translated}", + c.pso, + c.direct + c.indirect, + c.direct, + c.indirect, + groups_text(c.first), + groups_text(c.largest) + ); + if let (true, Some((key, _, Some(b), split))) = (k < COMPUTE_FILES_MOST, cs) { + files.push((compute_stem(k, key), "cs", b, None, split)); + } + } + if f.computes.len() > COMPUTE_FILES_MOST { + crate::xlog_info!("D3D12.X: target dump of frame {n}: the shaders of compute #{COMPUTE_FILES_MOST} and later are not written ({COMPUTE_FILES_MOST} pipelines at most)"); + } + files +} + +/// pipelines a written target lists +const PIPELINES_MOST: usize = 48; +/// console shader bytes kept for the dumps at most +const BLOB_BYTES_MOST: usize = 512 << 20; + +/// A graphics pipeline as the title made it. +struct Pipeline { + /// `real::shaders_key` of its shaders + set: u64, + /// (stage, `real::shader_key`, dump hash, its bytes: None past `BLOB_BYTES_MOST`) + stages: Vec<(&'static str, u64, u64, Option>)>, + blend: D3D12_RENDER_TARGET_BLEND_DESC, + formats: Vec, + /// VS / PS translated for waves of 32 (`real::graphics_wave32`) + split: bool, +} + +/// pipelines by the address the title has (kept by address: a later one there takes its place) +static PIPELINES: Mutex>>> = Mutex::new(None); +/// console shaders by `real::shader_key`, and their bytes in all +static BLOBS: Mutex>, usize)>> = Mutex::new(None); + +/// Pipeline `pso` was made of `stages` (VS, PS, DS, HS, GS as present, in that order) with render +/// target 0's `blend` and the render target `formats`. +pub fn note_pipeline(pso: usize, stages: &[(&'static str, &[u8])], blend: &D3D12_RENDER_TARGET_BLEND_DESC, formats: &[DXGI_FORMAT], split: bool) { + if !enabled() || pso == 0 { + return; + } + let set = super::real::shaders_key(&stages.iter().map(|(_, b)| b.to_vec()).collect::>()); + let stages = stages + .iter() + .map(|&(s, b)| { + let (key, hash, blob) = keep_shader(b); + (s, key, hash, blob) + }) + .collect(); + let p = Pipeline { set, stages, blend: *blend, formats: formats.iter().map(|f| f.0).collect(), split }; + PIPELINES.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, Arc::new(p)); +} + +/// Shader `b` kept for a dump (`XCL_DUMP_TARGETS`, `XCL_CAPTURE_FRAME`; 512 MiB of them at most): +/// its `real::shader_key`, its dump hash, and its bytes (None past the cap). +pub(super) fn keep_shader(b: &[u8]) -> (u64, u64, Option>) { + let key = super::real::shader_key(b); + let mut g = BLOBS.lock().unwrap(); + let (kept, bytes) = g.get_or_insert_with(Default::default); + let blob = kept.get(&key).cloned().or_else(|| { + if *bytes + b.len() > BLOB_BYTES_MOST { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: the dump switches keep {} MiB of shaders: later ones get no HLSL in a dump", BLOB_BYTES_MOST >> 20)); + return None; + } + *bytes += b.len(); + let a: Arc<[u8]> = b.into(); + kept.insert(key, a.clone()); + Some(a) + }); + (key, crate::gpu::shader::fnv64(b), blob) +} + +/// A D3D12_BLEND by name. +fn blend_name(b: i32) -> &'static str { + const NAMES: [&str; 22] = [ + "?", "ZERO", "ONE", "SRC_COLOR", "INV_SRC_COLOR", "SRC_ALPHA", "INV_SRC_ALPHA", "DEST_ALPHA", "INV_DEST_ALPHA", "DEST_COLOR", "INV_DEST_COLOR", "SRC_ALPHA_SAT", "?", "?", + "BLEND_FACTOR", "INV_BLEND_FACTOR", "SRC1_COLOR", "INV_SRC1_COLOR", "SRC1_ALPHA", "INV_SRC1_ALPHA", "ALPHA_FACTOR", "INV_ALPHA_FACTOR", + ]; + NAMES.get(b as usize).copied().unwrap_or("?") +} + +/// Render target 0's blend state as a line: what a pass that comes out inverted is checked by. +pub(super) fn blend_text(b: &D3D12_RENDER_TARGET_BLEND_DESC) -> String { + const OPS: [&str; 6] = ["?", "ADD", "SUBTRACT", "REV_SUBTRACT", "MIN", "MAX"]; + const LOGIC: [&str; 16] = [ + "CLEAR", "SET", "COPY", "COPY_INVERTED", "NOOP", "INVERT", "AND", "NAND", "OR", "NOR", "XOR", "EQUIV", "AND_REVERSE", "AND_INVERTED", "OR_REVERSE", "OR_INVERTED", + ]; + let op = |o: D3D12_BLEND_OP| OPS.get(o.0 as usize).copied().unwrap_or("?"); + let mut s = if b.BlendEnable.as_bool() { + format!( + "blend on: colour {} {} {}, alpha {} {} {}", + blend_name(b.SrcBlend.0), + op(b.BlendOp), + blend_name(b.DestBlend.0), + blend_name(b.SrcBlendAlpha.0), + op(b.BlendOpAlpha), + blend_name(b.DestBlendAlpha.0) + ) + } else { + "blend off".to_string() + }; + if b.LogicOpEnable.as_bool() { + s += &format!(", logic op {}", LOGIC.get(b.LogicOp.0 as usize).copied().unwrap_or("?")); + } + s + &format!(", write mask {:#x}", b.RenderTargetWriteMask) +} + +/// The files of a written target's pipeline's shader: `target__` (.hlsl, .rdna2.txt). +fn shader_stem(k: usize, stage: &str, key: u64) -> String { + format!("target{k}_{stage}_{key:016x}") +} + +/// Logs the pipelines that drew into each written target `(k, resource)` of frame `n`; the files +/// of their shaders, written on a thread of their own (a later frame's dump writes over them). +fn log_pipelines(n: u64, f: &Frame, written: &[(usize, usize)]) -> Vec { + crate::xlog_info!("D3D12.X: target dump of frame {n}: the pipelines of the targets written"); + let pipelines = PIPELINES.lock().unwrap().clone().unwrap_or_default(); + let tag_of = |r: usize| written.iter().find(|w| w.1 == r).map(|w| format!("target{}", w.0)); + let mut files: Vec = Vec::new(); + for &(k, t) in written { + let (list, more) = f.pipelines_of(t, PIPELINES_MOST); + for (pso, draws) in list { + let translated = super::real::is_translated_graphics(super::pso_async::peek(pso)); + let Some(p) = pipelines.get(&pso) else { + crate::xlog_info!("D3D12.X: target dump: target{k}: {draws} draws with pipeline {pso:#x} (translated {translated}): not known (made before the switch, or a mesh pipeline)"); + continue; + }; + let stages: Vec = p.stages.iter().map(|(s, key, h, _)| format!("{s} {key:016x} (dump hash {h:016x})")).collect(); + let inputs = f.inputs.get(&pso).map_or(&[][..], |v| &v[..]); + let read: Vec = inputs.iter().filter_map(|i| tag_of(i.res)).collect(); + crate::xlog_info!( + "D3D12.X: target dump: target{k}: {draws} draws with pipeline {pso:#x} (translated {translated}): shaders {:016x} – {}; RT formats {:?}, RT0 {}{}", + p.set, + stages.join(", "), + p.formats, + blend_text(&p.blend), + if read.is_empty() { String::new() } else { format!("; reads {}", read.join(" ")) } + ); + for i in inputs.iter().filter(|i| tag_of(i.res).is_none()) { + crate::xlog_info!( + "D3D12.X: target dump: target{k}: pipeline {pso:#x} reads {:#x}: dimension {}, {}x{}x{}, {} mips, format {}", + i.res, + i.dimension, + i.width, + i.height, + i.depth, + i.mips, + i.format + ); + } + let vs = p.stages.iter().find(|s| s.0 == "vs").and_then(|s| s.3.clone()); + for (s, key, _, blob) in &p.stages { + if let Some(b) = blob { + files.push((shader_stem(k, s, *key), s, b.clone(), vs.clone(), p.split)); + } + } + } + if more > 0 { + crate::xlog_info!("D3D12.X: target dump: target{k}: and {more} more pipelines"); + } + } + files +} + +/// A shader to write (`write_shaders`): its file stem, stage (`vs`, `ps`, `cs`, …), bytes, the +/// pipeline's VS (a PS's static samplers come after the VS's) and whether it is translated for +/// waves of 32. +pub(super) type ShaderFile = (String, &'static str, Arc<[u8]>, Option>, bool); + +/// HLSL bytes of one shader a dump writes at most (`XCL_DUMP_TARGETS`, `XCL_CAPTURE_FRAME`; a +/// retail title's biggest programs are tens of MB of it) +pub(super) const HLSL_BYTES_MOST: usize = 8 << 20; + +/// Writes each console shader's disassembly and its VS / PS / CS translated again, as the pipeline +/// translates it through HLSL (`pso::console_translation`; the PS's static samplers after the +/// VS's). HLSL past `hlsl_most` bytes is not written: a note of its size takes its place. A CS's +/// file says which path made the DXIL the pipeline runs (`pso::compute_path`). +pub(super) fn write_shaders(dir: &std::path::Path, files: Vec, hlsl_most: usize) { + use crate::gpu::recomp::pso::{console_translation, is_console, mem_windows, Stage}; + let translate = |b: &[u8], stage: Stage, base: u32, split: bool| console_translation(b, stage, base, mem_windows(), split, false).map(|(t, _)| (t.hlsl, t.static_samplers.len() as u32)); + for (stem, stage, blob, vs, split) in files { + let base = dir.join(&stem); + if !is_console(&blob) { + let _ = std::fs::write(base.with_extension("txt"), format!("not a console shader ({} bytes): the PC compiles it as it is\n", blob.len())); + continue; + } + if let Some(sh) = crate::gpu::xbox::parse(&blob) { + let _ = std::fs::write(base.with_extension("rdna2.txt"), crate::gpu::xbox::listing(&sh)); + } + let hlsl = match stage { + "vs" => translate(&blob, Stage::Vertex, 0, split), + "ps" => { + let samplers = vs.as_deref().filter(|v| is_console(v)).and_then(|v| translate(v, Stage::Vertex, 0, split).ok()).map_or(0, |t| t.1); + translate(&blob, Stage::Pixel, samplers, split) + } + // (for the wave size the pipeline was noted with) + "cs" => translate(&blob, Stage::Compute, 0, split), + _ => Err(format!("a {stage} is not translated here")), + }; + let text = match hlsl { + Ok((h, _)) if h.len() > hlsl_most => format!("// {stem}: translated, {} bytes of HLSL: past {} MiB, not written\n", h.len(), hlsl_most >> 20), + Ok((h, _)) if stage == "cs" => format!( + "// {stem}: translated again from the pipeline's console shader through HLSL, for reading (a switch-form retry or a debug switch build another)\n// the running pipeline's DXIL: {}\n{h}", + crate::gpu::recomp::pso::compute_path(crate::gpu::shader::fnv64(&blob)).unwrap_or("not known (not translated in this process yet)") + ), + Ok((h, _)) => format!("// {stem}: translated again from the pipeline's console shader (the HLSL path; XCL_DIRECT_DXIL, a switch-form retry or a debug switch build another)\n{h}"), + Err(e) => format!("// {stem}: not translated: {e}\n"), + }; + let _ = std::fs::write(base.with_extension("hlsl"), text); + } +} + +/// readback bytes of one present's target dump at most: 64 targets of 2560x1440 RGBA32F are +/// about 3.8 GB, at once, on a card that may be full already +const DUMP_BYTES_MOST: u64 = 1 << 30; + +/// bytes a copy of `d`'s subresource 0 reads back (row padding aside) +fn readback_bytes(d: &D3D12_RESOURCE_DESC) -> u64 { + d.Width.saturating_mul(d.Height as u64).saturating_mul(texel_bytes(d.Format) as u64) +} + +/// Of targets of `sizes` bytes, in the order they are dumped: how many go before `most` bytes +/// are passed (the rest are left out). The first goes however large it is. +fn dumped_within(sizes: &[u64], most: u64) -> usize { + let mut total = 0u64; + for (k, &b) in sizes.iter().enumerate() { + total = total.saturating_add(b); + if k > 0 && total > most { + return k; + } + } + sizes.len() +} + +/// Of the texels sampled in `data` (every 4th of every 4th row, as the dumps do): how many are not +/// all zero, how many differ from the first one sampled (a cleared target has none), and how many +/// were sampled; any format, by its texel size; texels past the end of `data` are not sampled. +fn census(data: &[u8], width: usize, height: usize, pitch: usize, format: DXGI_FORMAT) -> (u64, u64, u64) { + let bytes = texel_bytes(format); + let (mut lit, mut differ, mut n) = (0, 0, 0); + let mut first: Option<&[u8]> = None; + for y in (0..height).step_by(4) { + for x in (0..width).step_by(4) { + let at = y * pitch + x * bytes; + let Some(t) = data.get(at..at + bytes) else { continue }; + n += 1; + if t.iter().any(|&b| b != 0) { + lit += 1; + } + if *first.get_or_insert(t) != t { + differ += 1; + } + } + } + (lit, differ, n) +} + +/// bytes of a texel of a render-target format (or of the plane of a planar format a footprint +/// names: a copied depth-stencil's depth plane is R32 / R24X8 typeless, 4 bytes) +pub(super) fn texel_bytes(f: DXGI_FORMAT) -> usize { + match f { + DXGI_FORMAT_R32G32B32A32_FLOAT | DXGI_FORMAT_R32G32B32A32_UINT | DXGI_FORMAT_R32G32B32A32_SINT | DXGI_FORMAT_R32G32B32A32_TYPELESS => 16, + DXGI_FORMAT_R16G16B16A16_FLOAT | DXGI_FORMAT_R16G16B16A16_UNORM | DXGI_FORMAT_R16G16B16A16_UINT | DXGI_FORMAT_R16G16B16A16_SNORM + | DXGI_FORMAT_R16G16B16A16_SINT | DXGI_FORMAT_R16G16B16A16_TYPELESS | DXGI_FORMAT_R32G32_FLOAT | DXGI_FORMAT_R32G32_UINT + | DXGI_FORMAT_R32G32_SINT | DXGI_FORMAT_R32G32_TYPELESS | DXGI_FORMAT_D32_FLOAT_S8X24_UINT | DXGI_FORMAT_R32G8X24_TYPELESS => 8, + DXGI_FORMAT_R8G8_UNORM | DXGI_FORMAT_R8G8_UINT | DXGI_FORMAT_R8G8_SNORM | DXGI_FORMAT_R8G8_SINT | DXGI_FORMAT_R8G8_TYPELESS + | DXGI_FORMAT_R16_FLOAT | DXGI_FORMAT_R16_UNORM | DXGI_FORMAT_R16_UINT | DXGI_FORMAT_R16_SNORM | DXGI_FORMAT_R16_SINT + | DXGI_FORMAT_R16_TYPELESS | DXGI_FORMAT_D16_UNORM | DXGI_FORMAT_B5G6R5_UNORM | DXGI_FORMAT_B5G5R5A1_UNORM | DXGI_FORMAT_B4G4R4A4_UNORM => 2, + DXGI_FORMAT_R8_UNORM | DXGI_FORMAT_R8_UINT | DXGI_FORMAT_R8_SNORM | DXGI_FORMAT_R8_SINT | DXGI_FORMAT_A8_UNORM | DXGI_FORMAT_R8_TYPELESS => 1, + // also D32 / R32 typeless, D24S8 / R24G8 typeless, R11G11B10 + _ => 4, + } +} + +/// A dump `tag` read back: how many of its texels are not all zero and differ from the first. +/// The texel size is that of the footprint's format – the copied plane's for a planar format, +/// not the resource's – and the bytes read stop at the buffer's end. +pub unsafe fn log_census(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, tag: &str) { + let mut p: *mut c_void = std::ptr::null_mut(); + if rb.Map(0, None, Some(&mut p)).is_err() || p.is_null() { + return; + } + let f = &fp.Footprint; + let len = (rb.GetDesc().Width as usize).saturating_sub(fp.Offset as usize); + let data = std::slice::from_raw_parts((p as *const u8).add(fp.Offset as usize), len); + let (lit, differ, n) = census(data, f.Width as usize, f.Height as usize, f.RowPitch as usize, f.Format); + rb.Unmap(0, None); + crate::xlog_info!("D3D12.X: target dump: {tag}: {lit} of {n} texels sampled not zero, {differ} differ from the first texel (format {})", f.Format.0); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_switch_takes_a_work_threshold_and_a_frame_count() { + assert_eq!(parse("200"), Some((200, 1, DUMPED))); + assert_eq!(parse("200,3"), Some((200, 3, DUMPED))); + assert_eq!(parse(" 50 , 2 "), Some((50, 2, DUMPED))); + assert_eq!(parse("0"), None); + assert_eq!(parse("200,0"), None); + assert_eq!(parse("x"), None); + assert_eq!(parse("200,x"), None); + // a third number: the targets written of a frame, 64 at most + assert_eq!(parse("200,3,24"), Some((200, 3, 24))); + assert_eq!(parse("200,3,1000"), Some((200, 3, DUMPED_MOST))); + assert_eq!(parse("200,3,0"), None); + assert_eq!(parse("200,3,x"), None); + assert_eq!(parse("200,3,24,1"), None); + } + + #[test] + fn dumps_wait_the_seconds_after_the_first_present() { + assert_eq!(parse_after(" 30 "), Some(Duration::from_secs(30))); + assert_eq!(parse_after("2.5"), Some(Duration::from_millis(2500))); + assert_eq!(parse_after("soon"), None); + assert_eq!(parse_after("-1"), None); + assert_eq!(parse_after("inf"), None); + let c = Config { work: 100, frames: 2, after: Duration::from_secs(30), targets: DUMPED }; + assert!(!due(&c, 500, 0, Duration::from_secs(29)), "too early"); + assert!(due(&c, 500, 0, Duration::from_secs(30))); + assert!(!due(&c, 99, 0, Duration::from_secs(40)), "too little work"); + assert!(due(&c, 100, 1, Duration::from_secs(40))); + assert!(!due(&c, 100, 2, Duration::from_secs(40)), "frames all dumped"); + } + + #[test] + fn draws_count_per_target_by_outcome() { + let mut f = Frame::default(); + f.draw(&[0x10, 0x20], Some(0x90), RAN); + f.draw(&[0x10], Some(0x90), STANDIN); + f.draw(&[0x10], None, PC); + f.draw(&[0x20], Some(0x80), SKIPPED); + f.draw(&[], None, RAN); + assert_eq!(f.work, 5); + assert_eq!(f.targets[&0x10], [1, 1, 1, 0]); + assert_eq!(f.targets[&0x20], [1, 0, 0, 1]); + assert_eq!(f.depth(), Some((0x90, [1, 1, 0, 0]))); + assert_eq!(Frame::default().depth(), None); + } + + #[test] + fn targets_rank_by_draws_and_texels_count_by_format() { + let mut f = Frame::default(); + for (t, n) in [(0x30, 5), (0x10, 9), (0x20, 5)] { + for _ in 0..n { + f.draw(&[t], None, if n == 9 { SKIPPED } else { RAN }); + } + } + let order: Vec<(usize, u64)> = f.ranked().into_iter().map(|(t, c)| (t, c.iter().sum())).collect(); + assert_eq!(order, vec![(0x10, 9), (0x20, 5), (0x30, 5)]); + // 8 x 8 texels of 8 bytes (R16G16B16A16_FLOAT), every 4th of every 4th row sampled: + // (0,0) (4,0) (0,4) (4,4); one of them has a non-zero byte in its last half + let (w, h, bytes) = (8usize, 8usize, 8usize); + let pitch = w * bytes; + let mut data = vec![0u8; pitch * h]; + data[4 * pitch + 4 * bytes + 7] = 1; + data[pitch + bytes] = 9; // a texel not sampled + assert_eq!(census(&data, w, h, pitch, DXGI_FORMAT_R16G16B16A16_FLOAT), (1, 1, 4)); + // read as 4-byte texels the same bytes land elsewhere + assert_eq!(census(&data, w, h, pitch, DXGI_FORMAT_R8G8B8A8_UNORM), (0, 0, 4)); + assert_eq!(texel_bytes(DXGI_FORMAT_R11G11B10_FLOAT), 4); + assert_eq!(texel_bytes(DXGI_FORMAT_R8_UNORM), 1); + for f in [DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM, DXGI_FORMAT_B4G4R4A4_UNORM] { + assert_eq!(texel_bytes(f), 2, "{f:?}"); + } + } + + #[test] + fn a_cleared_target_is_not_zero_but_has_no_texel_that_differs() { + // 8 x 8 of R8G8B8A8 cleared to (0, 0, 0, 1): every texel not zero, none differs + let (w, h, pitch) = (8usize, 8usize, 32usize); + let mut data: Vec = [0, 0, 0, 255].repeat(w * h); + assert_eq!(census(&data, w, h, pitch, DXGI_FORMAT_R8G8B8A8_UNORM), (4, 0, 4)); + // one draw over texel (4, 4) + data[4 * pitch + 4 * 4] = 200; + assert_eq!(census(&data, w, h, pitch, DXGI_FORMAT_R8G8B8A8_UNORM), (4, 1, 4)); + } + + #[test] + fn depth_formats_have_their_texel_sizes() { + for f in [DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_D24_UNORM_S8_UINT, DXGI_FORMAT_R24G8_TYPELESS] { + assert_eq!(texel_bytes(f), 4, "{f:?}"); + } + assert_eq!(texel_bytes(DXGI_FORMAT_D32_FLOAT_S8X24_UINT), 8); + assert_eq!(texel_bytes(DXGI_FORMAT_R32G8X24_TYPELESS), 8); + assert_eq!(texel_bytes(DXGI_FORMAT_D16_UNORM), 2); + } + + /// One present's target dump reads back 1 GiB at most: the targets past it, in the order + /// dumped, are left out; a first target larger than that still goes. + #[test] + fn a_target_dump_stops_at_a_gib_of_readback() { + let desc = |w: u64, h: u32, f: DXGI_FORMAT| D3D12_RESOURCE_DESC { Width: w, Height: h, Format: f, ..Default::default() }; + let hdr = readback_bytes(&desc(2560, 1440, DXGI_FORMAT_R32G32B32A32_FLOAT)); + assert_eq!(hdr, 2560 * 1440 * 16); + // 64 of them: 3.8 GB; 18 fit in 1 GiB + assert_eq!(dumped_within(&[hdr; 64], DUMP_BYTES_MOST), 18); + // to_dump asks once per target, with the sizes so far: a target cut stays cut + for n in 1..=64 { + assert_eq!(dumped_within(&vec![hdr; n], DUMP_BYTES_MOST), n.min(18), "{n} targets"); + } + let small = readback_bytes(&desc(1920, 1080, DXGI_FORMAT_R8_UNORM)); + assert_eq!(small, 1920 * 1080); + assert_eq!(dumped_within(&[small; 64], DUMP_BYTES_MOST), 64, "under the cap: all"); + assert_eq!(dumped_within(&[], DUMP_BYTES_MOST), 0); + // the order stays: a small target after the one past the cap is left out too + let half = readback_bytes(&desc(16384, 16384, DXGI_FORMAT_R8G8_UNORM)); + assert_eq!(half, 512 << 20); + assert_eq!(dumped_within(&[half, half, small], DUMP_BYTES_MOST), 2, "exactly 1 GiB"); + assert_eq!(dumped_within(&[half, half + 1, small], DUMP_BYTES_MOST), 1); + // a first target larger than the cap goes alone + let huge = readback_bytes(&desc(16384, 16384, DXGI_FORMAT_R32G32B32A32_FLOAT)); + assert!(huge > DUMP_BYTES_MOST); + assert_eq!(dumped_within(&[huge], DUMP_BYTES_MOST), 1); + assert_eq!(dumped_within(&[huge, small], DUMP_BYTES_MOST), 1); + } + + /// A written target lists its pipelines by draws (12 at most), each pipeline's inputs noted + /// at its first draw of the frame; the blend line names an inverting logic op. + #[test] + fn a_target_lists_its_pipelines_by_draws() { + let mut f = Frame::default(); + assert!(f.drew_with(&[0x10], 0xa)); + assert!(!f.drew_with(&[0x10, 0x20], 0xa)); + assert!(f.drew_with(&[0x10], 0xb)); + for p in 0x100..0x110 { + f.drew_with(&[0x30], p); + } + assert_eq!(f.pipelines_of(0x10, 12), (vec![(0xa, 2), (0xb, 1)], 0)); + assert_eq!(f.pipelines_of(0x20, 12), (vec![(0xa, 1)], 0)); + let (v, more) = f.pipelines_of(0x30, 12); + assert_eq!((v.len(), v[0], more), (12, (0x100, 1), 4)); + let mut b = D3D12_RENDER_TARGET_BLEND_DESC { RenderTargetWriteMask: 0xf, ..Default::default() }; + assert_eq!(blend_text(&b), "blend off, write mask 0xf"); + b.BlendEnable = true.into(); + b.SrcBlend = D3D12_BLEND_SRC_ALPHA; + b.DestBlend = D3D12_BLEND_INV_SRC_ALPHA; + b.BlendOp = D3D12_BLEND_OP_ADD; + b.SrcBlendAlpha = D3D12_BLEND_ONE; + b.DestBlendAlpha = D3D12_BLEND_ZERO; + b.BlendOpAlpha = D3D12_BLEND_OP_REV_SUBTRACT; + b.LogicOpEnable = true.into(); + b.LogicOp = D3D12_LOGIC_OP_COPY_INVERTED; + assert_eq!(blend_text(&b), "blend on: colour SRC_ALPHA ADD INV_SRC_ALPHA, alpha ONE REV_SUBTRACT ZERO, logic op COPY_INVERTED, write mask 0xf"); + assert_eq!(shader_stem(17, "ps", 0xab), "target17_ps_00000000000000ab"); + } + + /// Compute pipelines are listed in order of first use, each with its direct and indirect + /// dispatches, the first direct one's groups, the largest, and the first indirect arguments. + #[test] + fn compute_pipelines_list_in_order_of_first_use() { + let mut f = Frame::default(); + f.dispatched(0xb, Dispatched::Indirect(None)); + f.dispatched(0xa, Dispatched::Direct([80, 45, 1])); + f.dispatched(0xb, Dispatched::Indirect(Some("arguments 1x2x3 (max 1)".into()))); + f.dispatched(0xa, Dispatched::Direct([160, 90, 1])); + f.dispatched(0xa, Dispatched::Direct([1, 1, 1])); + f.dispatched(0xb, Dispatched::Direct([4, 4, 4])); + let order: Vec = f.computes.iter().map(|c| c.pso).collect(); + assert_eq!(order, vec![0xb, 0xa]); + let b = &f.computes[0]; + assert_eq!((b.direct, b.indirect, b.first, b.largest), (1, 2, Some([4, 4, 4]), Some([4, 4, 4]))); + assert_eq!(b.first_indirect, Some(None), "the first indirect one's arguments were on the GPU"); + let a = &f.computes[1]; + assert_eq!((a.direct, a.indirect, a.first, a.largest, a.first_indirect.clone()), (3, 0, Some([80, 45, 1]), Some([160, 90, 1]), None)); + assert_eq!(f.work, 0, "the work is counted by note_dispatch"); + assert_eq!(groups_text(a.first), "80x45x1"); + assert_eq!(groups_text(None), "none"); + assert_eq!(compute_stem(399, 0xab), "compute399_cs_00000000000000ab"); + } + + #[test] + fn the_census_stops_at_the_end_of_the_buffer() { + // 8 x 8 of D32S8X24 (8 bytes), a 256-byte pitch, but the buffer ends in the last row + // (the footprint's last row is not padded to its pitch): its texels are not read + let (w, h, pitch) = (8usize, 8usize, 256usize); + let mut data = vec![1u8; pitch * 4 + 4 * 8 + 4]; + assert_eq!(census(&data, w, h, pitch, DXGI_FORMAT_D32_FLOAT_S8X24_UINT), (3, 0, 3)); + data.extend_from_slice(&[0; 4]); + assert_eq!(census(&data, w, h, pitch, DXGI_FORMAT_D32_FLOAT_S8X24_UINT), (4, 1, 4)); + } +} diff --git a/crates/xcl/src/hle/d3d12x/texture_upload.rs b/crates/xcl/src/hle/d3d12x/texture_upload.rs new file mode 100644 index 0000000000..dfc1b7fce4 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/texture_upload.rs @@ -0,0 +1,1360 @@ +//! Uploads of the title's textures: what of them changed, and only that. +//! +//! A title writes its textures piece by piece – a streamed one arrives 64 KiB at a time, a video +//! plane or a glyph cache changes in places – and every submit in between wants what is there. +//! Uploading the whole texture each time sent a retail title's textures up many times over. Here +//! the written pages are compared with what they held (`changed`), the blocks of the levels those +//! bytes are (`tiling::Chain::parts`) are detiled by the standing workers straight into a mapped +//! upload buffer, and one list copies them in. Lists and buffers are kept: making them waits for +//! the video memory manager, and releasing them asked every queue how far it is. + +use std::cell::RefCell; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + +use crate::gpu::tiling::Rect; +use crate::hle::xg; + +const PAGE: usize = 0x1000; +/// what a worker reads at a time +const READ: usize = 64 << 10; +/// uploads of fewer bytes stay on the calling thread +const SHARE_FROM: u64 = 192 << 10; + +/// A texture to upload, or parts of it. +pub(super) struct Item { + pub res: ID3D12Resource, + /// where its bytes are + pub src: usize, + pub tex: Arc, + /// the states it is in and is left in: one for every subresource, or one for each + pub states: Vec, + /// the bytes of it that changed (from, to; sorted and disjoint); None: all of it + pub changed: Option>, + /// where it is kept what its pages held + pub known: Option, + /// where its pages are read, for a texture in a GPU view whose pages the title mapped + pub pages: Option>, +} + +// --------------------------------------------------------------------------------------- +// what changed +// --------------------------------------------------------------------------------------- + +/// A hash of `b` for "the same bytes as before" (four lanes of multiply-rotate over 8-byte words: +/// gigabytes a second; not for anything adversarial), never 0. +pub(super) fn content_hash(b: &[u8]) -> u64 { + const K: u64 = 0x9E37_79B9_7F4A_7C15; + let mut h = [K, K.rotate_left(17), K.rotate_left(31), K.rotate_left(47)]; + let mut chunks = b.chunks_exact(32); + for c in &mut chunks { + for (k, lane) in h.iter_mut().enumerate() { + let v = u64::from_le_bytes(c[k * 8..k * 8 + 8].try_into().unwrap()); + *lane = (*lane ^ v).wrapping_mul(K).rotate_left(29); + } + } + let mut tail = b.len() as u64; + for (k, &x) in chunks.remainder().iter().enumerate() { + tail = (tail ^ ((x as u64) << (8 * (k % 8)))).wrapping_mul(K).rotate_left(23); + } + h.iter().fold(tail, |a, &l| (a ^ l).wrapping_mul(K).rotate_left(27)).max(1) +} + +/// What a texture's pages held when they were last looked at. +#[derive(Default)] +pub(super) struct Pages { + /// the hash of each page's bytes that are the texture's (0: not known, the next write there + /// goes up). Empty: what the PC texture holds is not known at all, its next upload is of all + /// of it + hashes: Vec, + /// counts the times that was forgotten: a comparison going on then is not kept + forgotten: u64, + /// the last upload on each queue that may not have run yet + last: Vec, + /// what goes up again, and the uploads it has to come behind (`sent`) + again: Option<(Change, Vec)>, +} + +/// Where an upload went: the queue, the fence of that queue's uploads and the value behind it. +#[derive(Clone)] +pub(super) struct Sent { + pub queue: usize, + pub fence: ID3D12Fence, + pub value: u64, +} + +impl Sent { + fn done(&self) -> bool { + unsafe { super::real::fence_completed(&self.fence) >= self.value } + } + + /// The same queue's (of queues that went, `forget_queue`: the same fence's) + fn same_queue(&self, o: &Sent) -> bool { + self.queue == o.queue && (self.queue != GONE_QUEUE || self.fence == o.fence) + } +} + +pub(super) type Known = Arc>; + +/// The pages `[src, src + size)` lies on. +fn pages_of(src: usize, size: usize) -> usize { + ((src + size).div_ceil(PAGE) * PAGE - src / PAGE * PAGE) / PAGE +} + +/// All of a texture is about to go up from `size` bytes at `src`: from here on writes there are +/// compared page by page. +pub(super) fn all_sent(known: &Known, src: usize, size: usize) { + let mut k = known.lock().unwrap(); + k.hashes.clear(); + k.hashes.resize(pages_of(src, size), 0); + k.again = None; +} + +/// Nothing is known about what the PC texture holds: its next upload is of all of it. +pub(super) fn forget(known: &Known) { + let mut k = known.lock().unwrap(); + k.hashes.clear(); + k.forgotten += 1; + k.again = None; +} + +/// What a texture's memory holds from here on is not taken for what the PC texture holds (an +/// upload going on keeps nothing it reads): its next write sends all of it. What is to go up +/// again stays. +pub(super) fn unknown(known: &Known) { + let mut k = known.lock().unwrap(); + k.hashes.clear(); + k.forgotten += 1; +} + +/// `parts` of a texture (from, to) are not what its PC texture holds (a mapping changed under +/// them): they go up again with its next upload, with no comparison (`take_again`). +pub(super) fn stale(known: &Known, parts: Vec<(usize, usize)>) { + // (sorted and joined) + let parts = join(Change::Parts(Vec::new()), Change::Parts(parts)); + let mut k = known.lock().unwrap(); + k.again = Some(match k.again.take() { + Some((c, behind)) => (join(c, parts), behind), + None => (parts, Vec::new()), + }); +} + +/// `changed` of a texture (None: all of it) went up on `to`. An older upload of the texture on +/// another queue that has not run yet (and that `to`'s queue has not waited for: `waited`) can land +/// over it: it goes up again, behind that one (`take_again`). True when there is such a thing. +pub(super) fn sent(known: &Known, changed: Option<&[(usize, usize)]>, to: &Sent, waited: usize) -> bool { + let mut k = known.lock().unwrap(); + k.last.retain(|s| !s.done()); + let behind: Vec = k.last.iter().filter(|s| s.queue != to.queue && s.queue != waited).cloned().collect(); + k.last.retain(|s| s.queue != to.queue); + k.last.push(to.clone()); + if !behind.is_empty() { + let mut change = changed.map_or(Change::All, |c| Change::Parts(c.to_vec())); + let mut all = behind; + if let Some((c, b)) = k.again.take() { + change = join(c, change); + // (the newest of each queue) + all.extend(b.into_iter().filter(|o| !all.iter().any(|s| s.same_queue(o))).collect::>()); + } + k.again = Some((change, all)); + } + k.again.is_some() +} + +/// Uploads of `old` that may not have run yet can land over those of `new`, a texture over the same +/// video memory. +pub(super) fn inherit(new: &Known, old: &Known) { + let unfinished: Vec = old.lock().unwrap().last.iter().filter(|s| !s.done()).cloned().collect(); + let mut k = new.lock().unwrap(); + for s in unfinished { + match k.last.iter_mut().find(|o| o.same_queue(&s)) { + Some(o) => { + if s.value > o.value { + *o = s; + } + } + None => k.last.push(s), + } + } +} + +/// The queue of the uploads of a queue that went (`forget_queue`): no queue made later is it, so +/// only their fences say when they have run. +const GONE_QUEUE: usize = usize::MAX; + +/// Title queue `queue` went (`title_textures::forget_queue`): a queue made later at its address is +/// not taken for it. Its uploads that may not have run yet stay, under no queue's name, until their +/// fence passes (`sent`, `take_again`). +pub(super) fn forget_queue(known: &Known, queue: usize) { + let mut k = known.lock().unwrap(); + let Pages { last, again, .. } = &mut *k; + for s in last.iter_mut().chain(again.iter_mut().flat_map(|(_, behind)| behind.iter_mut())).filter(|s| s.queue == queue) { + s.queue = GONE_QUEUE; + } +} + +/// What a texture has to send again. +#[derive(Debug, PartialEq, Eq)] +pub(super) enum Again { + Nothing, + /// an upload it has to come behind has not run yet, and is on another queue + NotYet, + Now(Change), +} + +/// What of a texture goes up again with an upload on `queue`, which has waited for `waited`'s. +pub(super) fn take_again(known: &Known, queue: usize, waited: usize) -> Again { + let mut k = known.lock().unwrap(); + match k.again.take() { + None => Again::Nothing, + Some((c, behind)) if behind.iter().all(|s| s.queue == queue || s.queue == waited || s.done()) => Again::Now(c), + later => { + k.again = later; + Again::NotYet + } + } +} + +/// Both of two changes. +pub(super) fn join(a: Change, b: Change) -> Change { + match (a, b) { + (Change::All, _) | (_, Change::All) => Change::All, + (Change::None, c) | (c, Change::None) => c, + (Change::Parts(mut a), Change::Parts(b)) => { + a.extend(b); + a.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::with_capacity(a.len()); + for (from, to) in a { + match out.last_mut() { + Some(l) if l.1 >= from => l.1 = l.1.max(to), + _ => out.push((from, to)), + } + } + Change::Parts(out) + } + } +} + +/// A texture with written pages, to be compared. +pub(super) struct Written<'a> { + pub src: usize, + pub size: usize, + /// its written pages (sorted addresses) + pub dirty: &'a [usize], + pub known: &'a Known, + /// where its pages are read (`Item::pages`) + pub pages: Option<&'a PageMap>, +} + +/// What became of a texture's written pages. +#[derive(Debug, PartialEq, Eq, Clone)] +pub(super) enum Change { + /// they hold what they held + None, + /// what its PC texture holds is not known + All, + /// these bytes of it (from, to; sorted and disjoint) are not what they were + Parts(Vec<(usize, usize)>), +} + +/// The written pages of `textures` against what they held; what they hold now is remembered. +/// Also the bytes compared. `trust` false: a written page has changed (nothing is compared). +pub(super) unsafe fn changed(textures: &[Written], trust: bool) -> (Vec, usize) { + struct Page { + texture: usize, + at: usize, + len: usize, + /// its hash among the texture's + slot: *mut u64, + differs: AtomicBool, + } + // SAFETY: each page's slot is its own, and the hashes outlive the workers' use of them + unsafe impl Sync for Page {} + let mut out: Vec = textures.iter().map(|_| Change::None).collect(); + // (taken out while they are worked on, put back below) + let mut taken: Vec<(Vec, u64)> = textures + .iter() + .map(|t| { + let mut k = t.known.lock().unwrap(); + (std::mem::take(&mut k.hashes), k.forgotten) + }) + .collect(); + let mut pages: Vec = Vec::new(); + for (k, (t, (h, _))) in textures.iter().zip(taken.iter_mut()).enumerate() { + let (first, end) = (t.src / PAGE * PAGE, t.src + t.size); + if h.len() != pages_of(t.src, t.size) { + h.clear(); + if t.dirty.iter().any(|&p| p + PAGE > t.src && p < end) { + out[k] = Change::All; + } + continue; + } + for &p in t.dirty.iter().filter(|&&p| p >= first && p < end) { + let (at, to) = (p.max(t.src), (p + PAGE).min(end)); + pages.push(Page { texture: k, at, len: to - at, slot: h.as_mut_ptr().add((p - first) / PAGE), differs: AtomicBool::new(!trust) }); + } + } + let bytes = pages.iter().map(|p| p.len).sum(); + if trust { + // neighbours are read together + let mut groups: Vec> = Vec::new(); + for (k, p) in pages.iter().enumerate() { + match groups.last_mut() { + Some(g) if pages[k - 1].at + pages[k - 1].len == p.at && p.at + p.len - pages[g.start].at <= READ && pages[k - 1].texture == p.texture => g.end = k + 1, + _ => groups.push(k..k + 1), + } + } + let look = |g: usize| { + let group = &pages[groups[g].clone()]; + let (first, last) = (&group[0], &group[group.len() - 1]); + read(textures[first.texture].pages, first.at, last.at + last.len - first.at, |b| { + for p in group { + let h = content_hash(&b[p.at - first.at..][..p.len]); + // SAFETY: see `Page` + let slot = unsafe { &mut *p.slot }; + if *slot != h { + *slot = h; + p.differs.store(true, Ordering::Relaxed); + } + } + }); + }; + if bytes as u64 >= SHARE_FROM { + super::worker_pool::run(groups.len(), &look); + } else { + (0..groups.len()).for_each(look); + } + } + for p in pages.iter().filter(|p| p.differs.load(Ordering::Relaxed)) { + let from = p.at - textures[p.texture].src; + match &mut out[p.texture] { + Change::Parts(v) => match v.last_mut() { + Some(l) if l.1 >= from => l.1 = l.1.max(from + p.len), + _ => v.push((from, from + p.len)), + }, + c => *c = Change::Parts(vec![(from, from + p.len)]), + } + } + drop(pages); + for (t, (h, forgotten)) in textures.iter().zip(taken) { + let mut k = t.known.lock().unwrap(); + if k.forgotten == forgotten { + k.hashes = h; + } + } + (out, bytes) +} + +// --------------------------------------------------------------------------------------- +// reading the title's memory +// --------------------------------------------------------------------------------------- + +thread_local! { + static SCRATCH: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// Where the 64 KiB pages of a texture in a GPU view are read, resolved once for an upload +/// (`kernelx::mirrors::resolve`): a read takes no lock and asks Windows nothing but the bytes. +pub(super) struct PageMap { + /// the 64 KiB page of the texture's first byte + first: usize, + /// for each page from `first` on: where the page mapped there is kept, 0 for nothing, or (bit + /// 0 set) the address read for a page the title never mapped there + at: Box<[usize]>, +} + +impl PageMap { + const PAGE: usize = crate::hle::kernelx::mirrors::PAGE; + + /// The table of a texture at `va` from `resolve`'s addresses. + pub fn new(va: usize, at: Vec) -> Self { + PageMap { first: va & !(Self::PAGE - 1), at: at.into_boxed_slice() } + } + + /// The bytes of the texture's address `at` on into `to`, a 64 KiB page at a time: zeros for a + /// page that shows nothing (or lies past the table), where it is kept for a mapped page (one + /// read: a physical page is committed whole or not at all), as any title memory otherwise. + pub unsafe fn copy(&self, at: usize, to: &mut [u8]) { + let mut done = 0; + while done < to.len() { + let a = at + done; + let (k, off) = (a.wrapping_sub(self.first) / Self::PAGE, a & (Self::PAGE - 1)); + let n = (Self::PAGE - off).min(to.len() - done); + let piece = &mut to[done..done + n]; + match self.at.get(k).copied().filter(|_| a >= self.first).unwrap_or(0) { + 0 => piece.fill(0), + p if p & 1 != 0 => super::title_textures::read_committed_into((p & !1) + off, piece), + p => super::title_textures::copy_or_zeros(p + off, piece), + } + done += n; + } + } +} + +/// `f` with the `len` bytes of the title's memory at `at`: where they are in the window that stays +/// committed, else a copy of them (the title may decommit a page meanwhile on another thread), with +/// zeros for pages that cannot be read. With `pages`, they are read where its table says. +pub(super) unsafe fn read(pages: Option<&PageMap>, at: usize, len: usize, f: impl FnOnce(&[u8]) -> R) -> R { + if let Some(m) = pages { + if len > READ { + let mut v = vec![0u8; len]; + m.copy(at, &mut v); + return f(&v); + } + return SCRATCH.with(|s| { + let mut s = s.borrow_mut(); + if s.len() < len { + s.resize(READ, 0); + } + m.copy(at, &mut s[..len]); + f(&s[..len]) + }); + } + super::title_textures::with_title_bytes(at, len, f) +} + +// --------------------------------------------------------------------------------------- +// the plan of an upload +// --------------------------------------------------------------------------------------- + +/// Part of one subresource in an upload buffer. +struct Piece { + item: usize, + sub: u32, + /// array slice, level and the elements of it (3D: the level, all of its depth) + slice: usize, + level: usize, + rect: Rect, + /// where it goes in the subresource, in texels + to: (u32, u32), + /// where it lies in the upload buffer + at: u64, + footprint: D3D12_SUBRESOURCE_FOOTPRINT, +} + +/// The pieces of item `k`, placed in the upload buffer from `at` on. +unsafe fn plan_item(dev: &ID3D12Device, k: usize, it: &Item, at: &mut u64, out: &mut Vec) -> Result<(), String> { + let s = it.tex.texels().ok_or("a texture without texels")?; + let c = &s.chain; + let (mips, array, volume) = (c.levels.len(), s.array as usize, s.depth > 0); + let rd = it.res.GetDesc(); + let (n, layers) = if volume { (mips, s.depth as usize) } else { (mips * array, array) }; + if rd.MipLevels as usize != mips || rd.DepthOrArraySize as usize != layers || (rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) != volume { + return Err(format!("{mips} levels of {layers} slices for a resource of {} of {}", rd.MipLevels, rd.DepthOrArraySize)); + } + if it.states.len() != 1 && it.states.len() != n { + return Err(format!("{} subresource states for {n} subresources", it.states.len())); + } + let bpe = s.bpe as usize; + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + if it.changed.is_none() || volume { + // all of it: the levels have to be the resource's (a part of one is taken to be, after it) + let (mut fps, mut rows, mut row_bytes) = (vec![fp; n], 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); + for i in 0..n { + let l = &c.levels[i % mips]; + let depth = if volume { l.depth } else { 1 }; + if l.height != rows[i] as usize || l.width * bpe != row_bytes[i] as usize || depth != fps[i].Footprint.Depth as usize { + return Err(format!("texture subresource {i} is {}x{}x{depth} B, resource expects {}x{}x{} B", l.width * bpe, l.height, row_bytes[i], rows[i], fps[i].Footprint.Depth)); + } + } + fp = fps[0]; + } else { + dev.GetCopyableFootprints(&rd, 0, 1, 0, Some(&mut fp), None, None, None); + } + let format: DXGI_FORMAT = fp.Footprint.Format; + let mut push = |slice: usize, level: usize, rect: Rect, depth: usize| { + let (w, h) = (rect.x1 - rect.x0, rect.y1 - rect.y0); + let pitch = (w * bpe).next_multiple_of(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT as usize); + *at = at.next_multiple_of(D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT as u64); + out.push(Piece { + item: k, + sub: (slice * mips + level) as u32, + slice, + level, + rect, + to: ((rect.x0 as u32) * s.side, (rect.y0 as u32) * s.side), + at: *at, + footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: format, Width: w as u32 * s.side, Height: h as u32 * s.side, Depth: depth as u32, RowPitch: pitch as u32 }, + }); + *at += (pitch * h * depth) as u64; + }; + if volume { + for (i, l) in c.levels.iter().enumerate() { + push(0, i, Rect { x0: 0, y0: 0, x1: l.width, y1: l.height }, l.depth); + } + super::lut3d::wrote(it.res.as_raw() as usize, false, || { + format!( + "uploaded from the title's memory at {:#x}: {} bytes ({} tiled, swizzle mode {}), all {} levels and {} depth slices{}", + it.src, + s.size(), + if c.layout.block_d > 1 { "thick" } else { "thin" }, + s.mode, + mips, + s.depth, + if it.changed.is_some() { " (pages of it were written)" } else { "" } + ) + }); + return Ok(()); + } + let whole = [(0, c.slice_bytes * array)]; + // cut at the slices + let mut slice_ranges: Vec<(usize, usize)> = Vec::new(); + let mut slice = 0; + for &(from, to) in it.changed.as_deref().unwrap_or(&whole) { + let (mut from, to) = (from, to.min(c.slice_bytes * array)); + while from < to { + let of = from / c.slice_bytes; + if of != slice && !slice_ranges.is_empty() { + c.parts(&slice_ranges).into_iter().for_each(|(i, r)| push(slice, i, r, 1)); + slice_ranges.clear(); + } + slice = of; + let end = to.min((of + 1) * c.slice_bytes); + slice_ranges.push((from - of * c.slice_bytes, end - of * c.slice_bytes)); + from = end; + } + } + if !slice_ranges.is_empty() { + c.parts(&slice_ranges).into_iter().for_each(|(i, r)| push(slice, i, r, 1)); + } + Ok(()) +} + +/// What a worker does at a time. +enum Work { + /// blocks of one row of them + Blocks { piece: usize, by: usize, bx: std::ops::Range }, + /// the levels in a slice's mip tail: one block + Tail { pieces: std::ops::Range }, + /// rows of a linear level (of the piece) + Rows { piece: usize, y: std::ops::Range }, + /// the levels of a 3D texture + Volume { pieces: std::ops::Range }, +} + +fn work_of(items: &[Item], pieces: &[Piece]) -> Vec { + let mut out = Vec::new(); + let mut k = 0; + while k < pieces.len() { + let p = &pieces[k]; + // (planned: it has texels) + let Some(s) = items[p.item].tex.texels() else { break }; + let (c, l) = (&s.chain, &s.chain.levels[p.level]); + let same = |n: usize, f: &dyn Fn(&Piece) -> bool| pieces[n..].iter().take_while(|q| q.item == p.item && q.slice == p.slice && f(q)).count(); + if s.depth > 0 { + let n = same(k, &|_| true); + out.push(Work::Volume { pieces: k..k + n }); + k += n; + } else if l.tail.is_some() { + let n = same(k, &|q| c.levels[q.level].tail.is_some()); + out.push(Work::Tail { pieces: k..k + n }); + k += n; + } else if is_linear(c, p.level) { + let rows = (READ / (l.pitch << c.layout.elem_log2).max(1)).max(1); + out.extend((p.rect.y0..p.rect.y1).step_by(rows).map(|y| Work::Rows { piece: k, y: y..(y + rows).min(p.rect.y1) })); + k += 1; + } else { + let (rows, columns) = c.blocks_of(p.level, p.rect); + let n = (READ / c.layout.block_bytes).max(1); + for by in rows { + out.extend(columns.clone().step_by(n).map(|bx| Work::Blocks { piece: k, by, bx: bx..(bx + n).min(columns.end) })); + } + k += 1; + } + } + out +} + +fn is_linear(c: &crate::gpu::tiling::Chain, level: usize) -> bool { + c.layout.mode == 0 && c.layout.base_xor == 0 && c.levels[level].origin == (0, 0) +} + +/// The page hashes of an item while its bytes are read. +struct Hashes<'a> { + src: usize, + end: usize, + pages: &'a [AtomicU64], +} + +impl Hashes<'_> { + /// `b` was read at `from` and is about to go up: what is known of its pages is that (a page read + /// in part is not known: its next write goes up). Neighbours of a changed page are read with it, + /// and a title may write on between the comparison and here; what is kept is what the PC texture + /// gets, or older than that (a write from here on is compared with it at the next look). + fn note(&self, from: usize, b: &[u8]) { + let first = self.src / PAGE * PAGE; + let mut p = from / PAGE * PAGE; + while p < from + b.len() { + let (a, z) = (p.max(self.src), (p + PAGE).min(self.end)); + if let Some(slot) = self.pages.get((p - first) / PAGE).filter(|_| a < z) { + let whole = a >= from && z <= from + b.len(); + slot.store(if whole { content_hash(&b[a - from..z - from]) } else { 0 }, Ordering::Relaxed); + } + p += PAGE; + } + } +} + +/// The texels of `pieces` into the upload buffer mapped at `ptr`, with what is kept of the items' +/// pages brought to what was read. +unsafe fn fill(items: &[Item], pieces: &[Piece], ptr: *mut u8, bytes: u64) { + // (taken out while they are worked on) + let taken: Vec, u64)>> = items + .iter() + .map(|it| { + let mut k = it.known.as_ref()?.lock().unwrap(); + if k.hashes.len() != pages_of(it.src, it.tex.size() as usize) { + return None; + } + Some((std::mem::take(&mut k.hashes).into_iter().map(AtomicU64::new).collect(), k.forgotten)) + }) + .collect(); + fill_hashed(items, pieces, ptr, bytes, &taken); + for (it, t) in items.iter().zip(taken) { + if let (Some(known), Some((h, forgotten))) = (&it.known, t) { + let mut k = known.lock().unwrap(); + if k.forgotten == forgotten { + k.hashes = h.into_iter().map(AtomicU64::into_inner).collect(); + } + } + } +} + +unsafe fn fill_hashed(items: &[Item], pieces: &[Piece], ptr: *mut u8, bytes: u64, hashes: &[Option<(Vec, u64)>]) { + struct Mapped(*mut u8); + // SAFETY: the workers write disjoint parts of the buffer + unsafe impl Sync for Mapped {} + let to = Mapped(ptr); + let work = work_of(items, pieces); + let note = |item: usize, from: usize, b: &[u8]| { + if let Some((pages, _)) = &hashes[item] { + let it = &items[item]; + Hashes { src: it.src, end: it.src + it.tex.size() as usize, pages }.note(from, b); + } + }; + let one = |k: usize| { + let to = &to; + // SAFETY: the pieces were placed inside the buffer; the title's memory is only read + unsafe { + match &work[k] { + Work::Blocks { piece, by, bx } => { + let p = &pieces[*piece]; + let (it, c) = (&items[p.item], &items[p.item].tex.texels().unwrap().chain); + let from = it.src + p.slice * c.slice_bytes + c.block_at(p.level, bx.start, *by); + read(it.pages.as_deref(), from, bx.len() * c.layout.block_bytes, |b| { + note(p.item, from, b); + c.detile_blocks(b, p.level, p.slice, *by, bx.clone(), p.rect, to.0.add(p.at as usize), p.footprint.RowPitch as usize); + }); + } + Work::Tail { pieces: range } => { + let first = &pieces[range.start]; + let (it, c) = (&items[first.item], &items[first.item].tex.texels().unwrap().chain); + let from = it.src + first.slice * c.slice_bytes; + read(it.pages.as_deref(), from, c.layout.block_bytes, |b| { + note(first.item, from, b); + for p in &pieces[range.clone()] { + c.detile_blocks(b, p.level, p.slice, 0, 0..1, p.rect, to.0.add(p.at as usize), p.footprint.RowPitch as usize); + } + }); + } + Work::Rows { piece, y } => { + let p = &pieces[*piece]; + let (it, c) = (&items[p.item], &items[p.item].tex.texels().unwrap().chain); + let (l, e) = (&c.levels[p.level], c.layout.elem_log2); + let (stride, row) = (l.pitch << e, (p.rect.x1 - p.rect.x0) << e); + let from = it.src + p.slice * c.slice_bytes + l.offset + y.start * stride + (p.rect.x0 << e); + read(it.pages.as_deref(), from, y.len() * stride - (p.rect.x0 << e), |b| { + note(p.item, from, b); + for (n, y) in y.clone().enumerate() { + let dst = to.0.add(p.at as usize + (y - p.rect.y0) * p.footprint.RowPitch as usize); + std::ptr::copy_nonoverlapping(b[n * stride..][..row].as_ptr(), dst, row); + } + }); + } + Work::Volume { pieces: range } => { + let first = &pieces[range.start]; + let it = &items[first.item]; + let s = it.tex.texels().unwrap(); + read(it.pages.as_deref(), it.src, s.size() as usize, |b| { + note(first.item, it.src, b); + for p in &pieces[range.clone()] { + let (l, row) = (&s.chain.levels[p.level], p.rect.x1 * s.bpe as usize); + let data = s.chain.detile_volume(b, p.level); + for (n, r) in data.chunks_exact(row).enumerate().take(l.height * l.depth) { + std::ptr::copy_nonoverlapping(r.as_ptr(), to.0.add(p.at as usize + n * p.footprint.RowPitch as usize), row); + } + } + }); + } + } + } + }; + if bytes >= SHARE_FROM { + super::worker_pool::run(work.len(), &one); + } else { + (0..work.len()).for_each(one); + } +} + +fn transition(r: &ID3D12Resource, sub: u32, from: D3D12_RESOURCE_STATES, to: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // SAFETY: the list keeps no reference; the item holds one until it was submitted + pResource: unsafe { std::mem::transmute_copy(r) }, + Subresource: sub, + StateBefore: from, + StateAfter: to, + }), + }, + } +} + +/// Record the copies of `pieces` from `buf`, and the transitions of the subresources they touch +/// (of no others: a title's work may be reading those). +unsafe fn record(list: &ID3D12GraphicsCommandList, items: &[Item], pieces: &[Piece], buf: &ID3D12Resource) { + const COPY: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COPY_DEST; + let (mut there, mut back) = (Vec::new(), Vec::new()); + for of_item in pieces.chunk_by(|a, b| a.item == b.item) { + let it = &items[of_item[0].item]; + let mut subs: Vec = of_item.iter().map(|p| p.sub).collect(); + subs.sort_unstable(); + subs.dedup(); + let n = it.tex.texels().map_or(0, |s| if s.depth > 0 { s.chain.levels.len() } else { s.chain.levels.len() * s.array as usize }); + if it.states.len() == 1 && subs.len() == n { + subs = vec![D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES]; + } + for sub in subs { + let state = if it.states.len() == 1 { it.states[0] } else { it.states[sub as usize] }; + if state != COPY { + there.push(transition(&it.res, sub, state, COPY)); + back.push(transition(&it.res, sub, COPY, state)); + } + } + } + if !there.is_empty() { + list.ResourceBarrier(&there); + } + for p in pieces { + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&items[p.item].res), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: p.sub }, + }; + let placed = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: p.at, Footprint: p.footprint }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(buf), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: placed } }; + list.CopyTextureRegion(&dst, p.to.0, p.to.1, 0, &src, None); + } + if !back.is_empty() { + list.ResourceBarrier(&back); + } +} + +// --------------------------------------------------------------------------------------- +// lists and buffers +// --------------------------------------------------------------------------------------- + +/// A list with its allocator and a mapped upload buffer: one batch at a time uses them. +pub(super) struct Job { + dev: usize, + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + buf: ID3D12Resource, + ptr: *mut u8, + pub bytes: u64, +} + +// D3D12 objects are free-threaded; the mapped pointer is only used by the holder of the job +unsafe impl Send for Job {} + +/// jobs the GPU is done with +static FREE: Mutex> = Mutex::new(Vec::new()); +/// the smallest upload buffer made, and the most bytes of them kept +const BUFFER_MIN: u64 = 1 << 20; + +/// The size of the buffer made for `bytes`: up to 64 MiB a power of two (few sizes, so one fits +/// again), then the next 16 MiB. +fn capacity(bytes: u64) -> Option { + const LARGE: u64 = 64 << 20; + const STEP: u64 = 16 << 20; + if bytes <= LARGE { + Some(bytes.max(BUFFER_MIN).next_power_of_two()) + } else { + bytes.checked_next_multiple_of(STEP) + } +} + +const FREE_BYTES: u64 = 512 << 20; + +/// A job whose buffer takes `bytes` bytes. +unsafe fn take(dev: &ID3D12Device, bytes: u64) -> Result { + let key = dev.as_raw() as usize; + { + let mut g = FREE.lock().unwrap(); + let best = g.iter().enumerate().filter(|(_, j)| j.dev == key && j.bytes >= bytes).min_by_key(|(_, j)| j.bytes).map(|(i, _)| i); + if let Some(i) = best { + return Ok(g.swap_remove(i)); + } + } + let e = |x: windows::core::Error| format!("texture upload: {x}"); + let cap = capacity(bytes).ok_or("texture upload buffer size overflow")?; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(e)?; + list.Close().map_err(e)?; + let _ = list.SetName(windows::core::w!("xcl texture upload list")); + let mut buf: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: cap, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut buf, + ) + .map_err(e)?; + let buf = buf.ok_or("texture upload buffer")?; + let mut p: *mut c_void = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).map_err(e)?; + Ok(Job { dev: key, alloc, list, buf, ptr: p as *mut u8, bytes: cap }) +} + +/// The GPU is done with `job`. +pub(super) fn give_back(job: Job) { + let mut g = FREE.lock().unwrap(); + g.push(job); + // (the biggest goes first: one burst does not keep its buffers for good) + while g.iter().map(|j| j.bytes).sum::() > FREE_BYTES { + let Some(i) = g.iter().enumerate().max_by_key(|(_, j)| j.bytes).map(|(i, _)| i) else { break }; + g.swap_remove(i); + } +} + +/// Upload `items` on `queue` (a DIRECT one): the ones that could not be (with why), and the job to +/// give back once `queue` is past here (None: nothing was submitted). +pub(super) unsafe fn submit(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[Item]) -> Result<(Vec<(usize, String)>, Option, u64), String> { + let (mut failed, mut pieces, mut bytes) = (Vec::new(), Vec::new(), 0u64); + for (k, it) in items.iter().enumerate() { + let (n, at) = (pieces.len(), bytes); + if let Err(e) = plan_item(dev, k, it, &mut bytes, &mut pieces) { + pieces.truncate(n); + bytes = at; + failed.push((k, e)); + } + } + if pieces.is_empty() { + return Ok((failed, None, 0)); + } + let job = take(dev, bytes)?; + fill(items, &pieces, job.ptr, bytes); + let e = |x: windows::core::Error| format!("texture upload: {x}"); + let recorded = (|| { + job.alloc.Reset().map_err(e)?; + job.list.Reset(&job.alloc, None).map_err(e)?; + record(&job.list, items, &pieces, &job.buf); + job.list.Close().map_err(e) + })(); + if let Err(e) = recorded { + // (nothing runs it: the job goes, its list may be in any state) + return Err(e); + } + super::sparse::pc_execute(queue, &job.list); + Ok((failed, Some(job), bytes)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The written pages of a texture are compared one by one: a page never compared has changed, + /// one that holds what it held has not, the bytes next to the texture on its first and last + /// page are not the texture's, and a texture nothing is known of changed as a whole. + #[test] + fn written_pages_are_compared_with_what_they_held() { + let mut mem = vec![0u8; 12 * PAGE]; + let base = (mem.as_mut_ptr() as usize).next_multiple_of(PAGE); + // a texture from the middle of the second page to the middle of the ninth + let (src, size) = (base + PAGE + 0x800, 7 * PAGE); + let known: Known = Default::default(); + let dirty: Vec = (0..11).map(|k| base + k * PAGE).collect(); + let look = |dirty: &[usize]| unsafe { changed(&[Written { src, size, dirty, known: &known, pages: None }], true) }; + assert_eq!(look(&[]).0, vec![Change::None]); + assert_eq!(look(&dirty).0, vec![Change::All], "nothing is known of it"); + assert_eq!(look(&dirty[9..]).0, vec![Change::None], "pages it does not lie on"); + all_sent(&known, src, size); + assert_eq!(known.lock().unwrap().hashes.len(), 8); + // each page is known from its first look on + assert_eq!(look(&dirty[3..5]).0, vec![Change::Parts(vec![(PAGE + 0x800, 3 * PAGE + 0x800)])]); + assert_eq!(look(&dirty[3..5]).0, vec![Change::None]); + assert_eq!(look(&dirty), (vec![Change::Parts(vec![(0, PAGE + 0x800), (3 * PAGE + 0x800, size)])], size), "the others, up to the texture's ends"); + assert_eq!(look(&dirty).0, vec![Change::None]); + // what lies next to the texture on its pages is another's + let write = |at: usize, v: u8| unsafe { (at as *mut u8).write_volatile(v) }; + write(src - 1, 1); + write(src + size, 1); + assert_eq!(look(&dirty).0, vec![Change::None]); + write(src, 1); + write(src + 4 * PAGE, 1); + write(src + size - 1, 1); + // (only what was written is looked at) + assert_eq!(look(&[base + 5 * PAGE]).0, vec![Change::Parts(vec![(3 * PAGE + 0x800, 4 * PAGE + 0x800)])]); + assert_eq!(look(&dirty).0, vec![Change::Parts(vec![(0, 0x800), (6 * PAGE + 0x800, size)])]); + // (without trust every written page has) + assert_eq!(unsafe { changed(&[Written { src, size, dirty: &dirty[2..3], known: &known, pages: None }], false) }.0, vec![Change::Parts(vec![(0x800, PAGE + 0x800)])]); + forget(&known); + assert_eq!(look(&dirty[2..3]).0, vec![Change::All]); + // nothing taken for what the PC texture holds: all of it at the next write, and what was to + // go up again stays + all_sent(&known, src, size); + assert_eq!(look(&dirty[3..5]).0, vec![Change::Parts(vec![(PAGE + 0x800, 3 * PAGE + 0x800)])]); + known.lock().unwrap().again = Some((Change::Parts(vec![(0, 64)]), Vec::new())); + unknown(&known); + assert!(known.lock().unwrap().again.is_some()); + assert_eq!(look(&dirty[3..5]).0, vec![Change::All]); + known.lock().unwrap().again = None; + // several textures at once, many pages: the same as one by one + let big = vec![7u8; 600 * PAGE]; + let at = (big.as_ptr() as usize).next_multiple_of(PAGE); + let (a, b): (Known, Known) = (Default::default(), Default::default()); + all_sent(&a, at, 300 * PAGE); + all_sent(&b, at + 300 * PAGE, 290 * PAGE); + let pages: Vec = (0..590).map(|k| at + k * PAGE).collect(); + let both = || unsafe { changed(&[Written { src: at, size: 300 * PAGE, dirty: &pages, known: &a, pages: None }, Written { src: at + 300 * PAGE, size: 290 * PAGE, dirty: &pages, known: &b, pages: None }], true).0 }; + assert_eq!(both(), vec![Change::Parts(vec![(0, 300 * PAGE)]), Change::Parts(vec![(0, 290 * PAGE)])]); + assert_eq!(both(), vec![Change::None, Change::None]); + } + + /// The default adapter's device, else WARP's (`XCL_ADAPTER=warp`: WARP's); None, the test + /// skipped, where there is neither (a DXGI that refuses the factory, #2238). + unsafe fn test_device() -> Option { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + let warp_only = crate::gpu::adapter::Selector::from_env_or("auto") == crate::gpu::adapter::Selector::Warp; + let mut dev: Option = None; + if warp_only || D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + dev = None; + if let Ok(warp) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)).and_then(|f| f.EnumWarpAdapter::()) { + let _ = D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev); + } + } + if dev.is_none() { + crate::gpu::recomp::runner::skip_test("no D3D12 device"); + } + dev + } + + /// Textures of every kind: (dimension, width, height, slices or depth, levels, format, layout). + const KINDS: [(u32, u64, u32, u16, u16, u32, u32); 10] = [ + (3, 64, 64, 2, 3, 28, 0x105), + (3, 200, 72, 1, 5, 28, 0x105), + (4, 40, 24, 6, 3, 28, 0x105), + (3, 256, 256, 1, 9, 98, 0x10A), + (3, 4, 4, 1, 1, 28, 0x105), + (3, 1030, 516, 3, 8, 71, 0x109), + (3, 777, 555, 2, 1, 61, 1), + (3, 512, 300, 6, 10, 10, 0x11B), + (2, 300, 1, 1, 1, 28, 1), + (3, 2048, 1024, 1, 12, 98, 0x11B), + ]; + + struct Made { + res: ID3D12Resource, + tex: Arc, + } + + unsafe fn make(dev: &ID3D12Device, k: (u32, u64, u32, u16, u16, u32, u32)) -> Made { + let console = super::super::title_textures::tests::console_desc(k.0, k.1, k.2, k.3, k.4, k.5, k.6); + let pc: D3D12_RESOURCE_DESC = std::ptr::read_unaligned(super::super::device_x::pc_resource_desc(&console).as_ptr() as *const _); + let mut res: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &pc, D3D12_RESOURCE_STATE_COMMON, None, &mut res) + .unwrap_or_else(|e| panic!("{k:?}: {e}")); + Made { res: res.unwrap(), tex: Arc::new(xg::Texture::new(&console).unwrap_or_else(|e| panic!("{k:?}: {e:#x}"))) } + } + + fn random_bytes(n: usize, seed: u64) -> Vec { + let mut x = seed | 1; + (0..n.div_ceil(8)) + .flat_map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x.to_le_bytes() + }) + .take(n) + .collect() + } + + /// Some pages of a texture, as ranges of its bytes. + fn some_ranges(size: usize, seed: usize) -> Vec<(usize, usize)> { + let mut out: Vec<(usize, usize)> = Vec::new(); + let mut at = seed * 37 % size.div_ceil(PAGE) * PAGE; + let mut n = seed; + while at < size && out.len() < 6 { + n = n.wrapping_mul(1103515245).wrapping_add(12345); + let to = (at + PAGE * (1 + n / 65536 % 4)).min(size); + out.push((at, to)); + at = to + PAGE * (1 + n / 16 % (size / PAGE / 5 + 2)); + } + out + } + + /// What the pieces of an upload hold is what the texture's levels detile to, every kind of + /// texture, all of it and some of its bytes, with the workers and without. + #[test] + fn pieces_hold_the_texels_of_their_levels() { + unsafe { + let Some(dev) = test_device() else { return }; + for (n, kind) in KINDS.into_iter().enumerate() { + let m = make(&dev, kind); + let s = m.tex.texels().unwrap(); + let size = m.tex.size() as usize; + let mem = random_bytes(size, n as u64 * 977 + 5); + let want = super::super::title_textures::subresources(mem.as_ptr() as usize, &m.tex); + for round in 0..5 { + let changed = (round > 0).then(|| some_ranges(size, n * 11 + round)); + let items = [Item { res: m.res.clone(), src: mem.as_ptr() as usize, tex: Arc::clone(&m.tex), states: vec![D3D12_RESOURCE_STATE_COMMON], changed: changed.clone(), known: None, pages: None }]; + let (mut pieces, mut bytes) = (Vec::new(), 0u64); + plan_item(&dev, 0, &items[0], &mut bytes, &mut pieces).unwrap_or_else(|e| panic!("{kind:?}: {e}")); + if round == 0 { + assert_eq!(pieces.len(), want.len(), "{kind:?}: all subresources"); + } + for share in [0, u64::MAX] { + let mut buf = vec![0xA5u8; bytes as usize + 1]; + fill(&items, &pieces, buf.as_mut_ptr(), share); + assert_eq!(buf[bytes as usize], 0xA5, "{kind:?}: past the buffer"); + for p in &pieces { + let (w, f) = (&want[p.sub as usize], p.footprint); + let (row, rows) = ((p.rect.x1 - p.rect.x0) * s.bpe as usize, (p.rect.y1 - p.rect.y0) * f.Depth as usize); + assert_eq!(p.at % 512, 0); + assert_eq!((f.RowPitch % 256, f.Width, p.to.0), (0, (p.rect.x1 - p.rect.x0) as u32 * s.side, p.rect.x0 as u32 * s.side)); + for y in 0..rows { + let got = &buf[p.at as usize + y * f.RowPitch as usize..][..row]; + let from = (p.rect.y0 + y) * w.row_bytes + p.rect.x0 * s.bpe as usize; + assert!(got == &w.data[from..from + row], "{kind:?} {changed:x?}: subresource {} row {y} of {:?}", p.sub, p.rect); + } + } + } + } + } + } + } + + /// Parts of a texture that go up change those texels and no others, on the GPU: every kind of + /// texture, its levels left in different states, and the lists and buffers used again. + #[test] + fn gpu_parts_of_a_texture_go_up_and_the_rest_stays() { + unsafe { + let Some(dev) = test_device() else { return }; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut value = 0; + let mut run = |items: &[Item]| { + let (failed, job, bytes) = submit(&dev, &queue, items).unwrap(); + assert!(failed.is_empty(), "{failed:?}"); + value += 1; + queue.Signal(&fence, value).unwrap(); + crate::gpu::fence::wait(&fence, value, &dev, None, 20_000).unwrap(); + let job = job.expect("a job"); + let buffer = job.buf.as_raw() as usize; + give_back(job); + (buffer, bytes) + }; + let mut buffers = Vec::new(); + for (n, kind) in KINDS.into_iter().enumerate() { + let m = make(&dev, kind); + let s = m.tex.texels().unwrap(); + let size = m.tex.size() as usize; + let first = random_bytes(size, n as u64 * 31 + 3); + let item = |mem: &[u8], changed| Item { res: m.res.clone(), src: mem.as_ptr() as usize, tex: Arc::clone(&m.tex), states: vec![D3D12_RESOURCE_STATE_COMMON], changed, known: None, pages: None }; + let (_, all) = run(&[item(&first, None)]); + let mut want = super::super::title_textures::subresources(first.as_ptr() as usize, &m.tex); + assert!(read_back(&dev, &queue, &m.res, want.len()) == want.iter().map(|w| w.data.clone()).collect::>(), "{kind:?}: all of it"); + for round in 1..4 { + // all of the memory is written again, but only these bytes of it are taken to be + let mem = random_bytes(size, n as u64 * 31 + 100 * round as u64); + let changed = some_ranges(size, n * 13 + round); + let it = item(&mem, Some(changed.clone())); + let (mut pieces, mut bytes) = (Vec::new(), 0u64); + plan_item(&dev, 0, &it, &mut bytes, &mut pieces).unwrap(); + if pieces.is_empty() { + continue; + } + let new = super::super::title_textures::subresources(mem.as_ptr() as usize, &m.tex); + for p in &pieces { + let w = &mut want[p.sub as usize]; + for y in p.rect.y0..p.rect.y1 * p.footprint.Depth as usize { + let (from, n) = (y * w.row_bytes + p.rect.x0 * s.bpe as usize, (p.rect.x1 - p.rect.x0) * s.bpe as usize); + w.data[from..from + n].copy_from_slice(&new[p.sub as usize].data[from..from + n]); + } + } + let (buffer, sent) = run(&[it]); + buffers.push(buffer); + assert!(sent <= all, "{kind:?}: {sent} of {all} bytes"); + assert!(read_back(&dev, &queue, &m.res, want.len()) == want.iter().map(|w| w.data.clone()).collect::>(), "{kind:?}: {changed:x?}"); + } + } + buffers.sort_unstable(); + let made = buffers.len(); + buffers.dedup(); + assert!(buffers.len() < made, "an upload buffer is used again"); + dev.GetDeviceRemovedReason().unwrap(); + } + } + + /// The rows of each subresource of `r` (in the common state). + unsafe fn read_back(dev: &ID3D12Device, queue: &ID3D12CommandQueue, r: &ID3D12Resource, n: usize) -> Vec> { + let rd = r.GetDesc(); + let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n]; + let (mut rows, mut row_bytes, mut total) = (vec![0u32; n], vec![0u64; n], 0u64); + dev.GetCopyableFootprints(&rd, 0, n as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), Some(&mut total)); + let mut rb: Option = None; + let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).unwrap(); + let rb = rb.unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.ResourceBarrier(&[transition(r, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + for (k, fp) in fps.iter().enumerate() { + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + list.ResourceBarrier(&[transition(r, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + crate::gpu::texture::wait(dev, queue).unwrap(); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + (0..n) + .map(|k| { + let f = &fps[k]; + (0..rows[k] as usize * f.Footprint.Depth as usize) + .flat_map(|y| std::slice::from_raw_parts((p as *const u8).add(f.Offset as usize + y * f.Footprint.RowPitch as usize), row_bytes[k] as usize).to_vec()) + .collect() + }) + .collect() + } + + /// What is kept of a texture's pages is what went up: after an upload of all of it, or of a part + /// (the pages read along with the changed ones too), the same bytes written again are nothing to + /// send; bytes that were others, or not there, while they were read go up when they come back. + #[test] + fn what_is_kept_is_what_went_up() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + unsafe { + let Some(dev) = test_device() else { return }; + // 64 KiB blocks: 256x256 RGBA8 in 64KB_S, 4 of them + let m = make(&dev, (3, 256, 256, 1, 1, 28, 0x109)); + let size = m.tex.size() as usize; + assert_eq!(size, 4 * 0x1_0000); + let src = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + let content = random_bytes(size, 77); + let put = |from: usize, to: usize| std::ptr::copy_nonoverlapping(content.as_ptr().add(from), (src + from) as *mut u8, to - from); + put(0, size); + let known: Known = Default::default(); + let pages: Vec = (0..size / PAGE).map(|k| src + k * PAGE).collect(); + let look = |of: &[usize]| changed(&[Written { src, size, dirty: of, known: &known, pages: None }], true).0.remove(0); + let upload = |changed: Option>| { + let it = [Item { res: m.res.clone(), src, tex: Arc::clone(&m.tex), states: vec![D3D12_RESOURCE_STATE_COMMON], changed, known: Some(Arc::clone(&known)), pages: None }]; + let (mut p, mut bytes) = (Vec::new(), 0u64); + plan_item(&dev, 0, &it[0], &mut bytes, &mut p).unwrap(); + let mut buf = vec![0u8; bytes as usize]; + fill(&it, &p, buf.as_mut_ptr(), bytes); + }; + all_sent(&known, src, size); + upload(None); + assert_eq!(look(&pages), Change::None, "all of it went up as it is"); + // a page changes; while its block is read its neighbours are not there + *((src + 0x1_0000) as *mut u8) ^= 1; + assert_eq!(look(&pages), Change::Parts(vec![(0x1_0000, 0x1_1000)])); + assert_ne!(VirtualFree((src + 0x1_8000) as *mut c_void, 0x8000, MEM_DECOMMIT), 0); + upload(Some(vec![(0x1_0000, 0x1_1000)])); + assert!(!VirtualAlloc((src + 0x1_8000) as *const c_void, 0x8000, MEM_COMMIT, PAGE_READWRITE).is_null()); + put(0x1_8000, 0x2_0000); + assert_eq!(look(&pages[0x18..0x20]), Change::Parts(vec![(0x1_8000, 0x2_0000)]), "they went up as zeros"); + upload(Some(vec![(0x1_8000, 0x2_0000)])); + assert_eq!(look(&pages), Change::None); + // written between the comparison and the upload, and back again + *((src + 5) as *mut u8) ^= 1; + assert_eq!(look(&pages), Change::Parts(vec![(0, PAGE)])); + std::ptr::write_bytes(src as *mut u8, 0, PAGE); + upload(Some(vec![(0, PAGE)])); + put(0, PAGE); + *((src + 5) as *mut u8) ^= 1; + assert_eq!(look(&pages), Change::Parts(vec![(0, PAGE)]), "the cleared page is what went up"); + VirtualFree(src as *mut c_void, 0, MEM_RELEASE); + } + } + + /// An upload on another queue than an older one of the same texture that has not run yet goes + /// up again behind it: on that queue, or anywhere once it has run. A queue that waited for the + /// other one's uploads needs none. + #[test] + fn an_upload_that_may_be_overtaken_goes_up_again() { + unsafe { + let Some(dev) = test_device() else { return }; + let (direct, own, other) = (0x1000usize, 0x2000usize, 0x3000usize); + let fence = || -> ID3D12Fence { dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap() }; + let (fd, fo, fx) = (fence(), fence(), fence()); + let at = |queue: usize, f: &ID3D12Fence, value: u64| Sent { queue, fence: f.clone(), value }; + let known: Known = Default::default(); + // all of it on the direct queue (which waits for XCL's own), then parts on XCL's own + assert!(!sent(&known, None, &at(direct, &fd, 1), own)); + assert!(sent(&known, Some(&[(0, 64), (4096, 8192)]), &at(own, &fo, 1), 0), "the direct queue's is older and may run later"); + assert_eq!(take_again(&known, own, 0), Again::NotYet); + assert_eq!(take_again(&known, other, own), Again::NotYet, "another queue has no order with it"); + assert!(sent(&known, Some(&[(100, 5000)]), &at(own, &fo, 2), 0)); + assert_eq!(take_again(&known, direct, own), Again::Now(Change::Parts(vec![(0, 64), (100, 8192)])), "both, behind it on its queue"); + assert_eq!(take_again(&known, direct, own), Again::Nothing); + // sent again there: the direct queue waited for the own one, nothing is overtaken + assert!(!sent(&known, Some(&[(0, 64), (100, 8192)]), &at(direct, &fd, 2), own)); + // once the older one has run, it goes up wherever + assert!(sent(&known, None, &at(own, &fo, 3), 0)); + assert!(sent(&known, None, &at(other, &fx, 1), own), "two of the title's queues"); + assert_eq!(take_again(&known, own, 0), Again::NotYet); + fd.Signal(2).unwrap(); + assert_eq!(take_again(&known, own, 0), Again::Now(Change::All)); + // an upload of all of it, or nothing known of it: what was to go up again is moot + assert!(sent(&known, Some(&[(0, 64)]), &at(own, &fo, 4), 0), "(the other queue's is still to run)"); + all_sent(&known, 0x10_0000, 4096); + assert_eq!(take_again(&known, other, own), Again::Nothing); + assert!(sent(&known, Some(&[(0, 64)]), &at(own, &fo, 5), 0)); + forget(&known); + assert_eq!(take_again(&known, other, own), Again::Nothing); + // another texture over the same video memory takes them over + assert!(!sent(&Known::default(), None, &at(own, &fo, 6), 0)); + let over: Known = Default::default(); + inherit(&over, &known); + assert!(sent(&over, None, &at(own, &fo, 7), 0), "behind the other queue's, which is still to run"); + assert_eq!(take_again(&over, own, 0), Again::NotYet); + assert_eq!(take_again(&over, other, own), Again::Now(Change::All)); + // nothing pending: nothing overtaken + for (f, v) in [(&fd, 9), (&fo, 9), (&fx, 9)] { + f.Signal(v).unwrap(); + } + assert!(!sent(&known, None, &at(own, &fo, 10), 0)); + } + } + + /// A queue that went is not the queue made later at its address: what has to come behind its + /// uploads waits for their fence, on that queue too. + #[test] + fn a_queue_that_went_is_not_the_next_one_at_its_address() { + unsafe { + let Some(dev) = test_device() else { return }; + let (direct, own) = (0x1000usize, 0x2000usize); + let fence = || -> ID3D12Fence { dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap() }; + let (fd, fo, fd2) = (fence(), fence(), fence()); + let at = |queue: usize, f: &ID3D12Fence, value: u64| Sent { queue, fence: f.clone(), value }; + let known: Known = Default::default(); + assert!(!sent(&known, None, &at(direct, &fd, 1), 0)); + assert!(sent(&known, Some(&[(0, 64)]), &at(own, &fo, 1), 0), "the direct queue's may run later"); + forget_queue(&known, direct); + assert_eq!(take_again(&known, direct, own), Again::NotYet, "a new queue at the old address has no order with it"); + // two queues that went one after the other at one address, uploads of both still to run + let two: Known = Default::default(); + assert!(!sent(&two, None, &at(direct, &fd, 1), own)); + forget_queue(&two, direct); + assert!(sent(&two, None, &at(direct, &fd2, 1), own), "the new queue's may land before the old one's"); + forget_queue(&two, direct); + let over: Known = Default::default(); + inherit(&over, &two); + assert_eq!(over.lock().unwrap().last.iter().filter(|s| s.queue == GONE_QUEUE).count(), 2, "two queues that went, two fences"); + fd.Signal(1).unwrap(); + assert_eq!(take_again(&known, direct, own), Again::Now(Change::Parts(vec![(0, 64)])), "once it has run"); + } + } + + #[test] + fn large_buffers_grow_in_steps_of_sixteen_mib() { + let mib = 1 << 20; + assert_eq!(capacity(1), Some(mib)); + assert_eq!(capacity(33 * mib), Some(64 * mib)); + assert_eq!(capacity(64 * mib + 1), Some(80 * mib)); + assert_eq!(capacity(138_713_408), Some(144 * mib)); + assert_eq!(capacity(256 * mib + 1), Some(272 * mib)); + assert_eq!(capacity(u64::MAX), None); + } + + /// A page the title decommits while it is read (or that never was committed) reads as zeros. + #[test] + fn memory_that_is_not_there_reads_as_zeros() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + unsafe { + let p = VirtualAlloc(std::ptr::null(), 4 * PAGE, MEM_RESERVE, PAGE_READWRITE) as usize; + VirtualAlloc((p + PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE); + std::ptr::write_bytes((p + PAGE) as *mut u8, 0x77, PAGE); + // (what an earlier read left in the scratch memory does not show) + read(None, p + PAGE, PAGE, |b| assert!(b.iter().all(|&x| x == 0x77))); + read(None, p, 4 * PAGE, |b| { + assert_eq!(b.len(), 4 * PAGE); + assert!(b[..PAGE].iter().all(|&x| x == 0) && b[PAGE..2 * PAGE].iter().all(|&x| x == 0x77) && b[2 * PAGE..].iter().all(|&x| x == 0)); + }); + VirtualFree(p as *mut c_void, 0, MEM_RELEASE); + } + } + + /// A texture whose GPU-view pages are kept apart is read through its table, in one read across + /// them: two pages where they are kept, a page that shows nothing, a page never mapped (read as + /// any memory) and a page whose memory is gone; and `changed` compares through the table. + #[test] + fn an_upload_reads_pages_kept_apart() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + const VIEW: usize = 0x1_0000; + unsafe { + let page = |v: u8| { + let p = VirtualAlloc(std::ptr::null(), VIEW, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(p, 0); + std::ptr::write_bytes(p as *mut u8, v, VIEW); + p + }; + let (a, b, c, gone) = (page(0x11), page(0x22), page(0x33), page(0x44)); + VirtualFree(gone as *mut c_void, 0, MEM_RELEASE); + // (the texture's own address: a GPU view's, never touched here) + let first = 0x7E5A_0000_0000usize; + let m = PageMap::new(first + 0x8000, vec![a, b, 0, c | 1, gone]); + let want = |off: usize| match off / VIEW { + 0 => 0x11, + 1 => 0x22, + 3 => 0x33, + _ => 0, + }; + read(Some(&m), first + 0x8000, 5 * VIEW - 0x8000, |got| { + assert_eq!(got.len(), 5 * VIEW - 0x8000); + assert!(got.iter().enumerate().all(|(k, &x)| x == want(k + 0x8000)), "each page from where it is kept"); + }); + read(Some(&m), first + VIEW - 0x1000, 0x2000, |got| assert!(got[..0x1000].iter().all(|&x| x == 0x11) && got[0x1000..].iter().all(|&x| x == 0x22))); + // past the table: nothing + read(Some(&m), first + 5 * VIEW, PAGE, |got| assert!(got.iter().all(|&x| x == 0))); + // the written pages compared through the table + let (src, size) = (first, 4 * VIEW); + let known: Known = Default::default(); + let dirty: Vec = (0..size / PAGE).map(|k| src + k * PAGE).collect(); + let look = || changed(&[Written { src, size, dirty: &dirty, known: &known, pages: Some(&m) }], true).0.remove(0); + all_sent(&known, src, size); + assert_eq!(look(), Change::Parts(vec![(0, size)]), "nothing was known of them"); + assert_eq!(look(), Change::None); + *((b + 0x1005) as *mut u8) ^= 1; + assert_eq!(look(), Change::Parts(vec![(VIEW + 0x1000, VIEW + 0x2000)]), "the page that differs where it is kept"); + for p in [a, b, c] { + VirtualFree(p as *mut c_void, 0, MEM_RELEASE); + } + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 2537546de7..2ed475f350 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -140,6 +140,10 @@ unsafe extern "system" fn close(this: *mut c_void) -> HRESULT { let pc = *((this as usize + F_BACKING) as *const *mut c_void); let f: unsafe extern "system" fn(*mut c_void) -> HRESULT = std::mem::transmute(pc_slot(pc, 9)); let hr = f(pc); + super::capture::list_end(this as usize); + if hr >= 0 { + super::title_textures::note_list_closed(this as usize); + } let n = *((this as usize + F_RING_AT) as *const usize); if hr < 0 && n > 0 { let first = n.saturating_sub(RING); @@ -198,6 +202,7 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: f(primary, alloc, pso) }; if hr >= 0 { + super::title_textures::forget_list_closed(this as usize); let active = stand_in.unwrap_or(primary as usize); *((this as usize + F_BACKING) as *mut usize) = active; let moved = { @@ -225,14 +230,18 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: for seg in moved { super::bind::reset(seg as *mut c_void, 0, 0); super::list_x::clear_segment_state(seg); + // a spare records again only after its next Reset: it does not hold its + // allocator meanwhile super::alloc_pool::retire_recording(seg); } + // nor does the previous recording a stand-in now replaces: it is not reset here either if stand_in.is_some() { super::bind::reset(primary, 0, 0); super::alloc_pool::retire_recording(primary as usize); } } *((this as usize + F_RING_AT) as *mut usize) = 0; + super::capture::list_begin(this as usize, pso); } hr } @@ -379,9 +388,27 @@ pub(super) fn drop_segment(wrapper: *mut c_void, pc: *mut c_void) { } } +/// The closed PC command lists `wrapper` keeps for reuse. +#[cfg(test)] +pub(super) fn spares_for_test(wrapper: *mut c_void) -> Vec { + SEGMENTS.lock().unwrap().as_ref().and_then(|m| m.get(&(wrapper as usize))).map_or(Vec::new(), |b| b.spares.clone()) +} + /// Add the closed segment `pc` to `wrapper`'s recording, after the ones it has. pub(super) fn push_segment(wrapper: *mut c_void, pc: *mut c_void) { - SEGMENTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().extra_active.push(pc as usize); + let mut sg = SEGMENTS.lock().unwrap(); + let extra = &mut sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().extra_active; + extra.push(pc as usize); + SEGMENTS_PEAK.fetch_max(extra.len(), std::sync::atomic::Ordering::Relaxed); +} + +/// the most extra segments a recording has had (of `MAX_EXTRA_SEGMENTS`) +static SEGMENTS_PEAK: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// The most extra segments a title list's recording has had so far (the put-off dispatches' +/// line: `pso_async::put_off_line`). +pub(super) fn segments_peak() -> usize { + SEGMENTS_PEAK.load(std::sync::atomic::Ordering::Relaxed) } /// Switch `wrapper` from closed segment `old_pc` to newly opened segment `new_pc`. @@ -389,11 +416,9 @@ pub(super) unsafe fn activate_segment(wrapper: *mut c_void, old_pc: *mut c_void, *((wrapper as usize + F_BACKING) as *mut usize) = new_pc as usize; { let mut sg = SEGMENTS.lock().unwrap(); - sg.get_or_insert_with(HashMap::new) - .entry(wrapper as usize) - .or_default() - .extra_active - .push(new_pc as usize); + let extra = &mut sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().extra_active; + extra.push(new_pc as usize); + SEGMENTS_PEAK.fetch_max(extra.len(), std::sync::atomic::Ordering::Relaxed); } let mut wg = WRAPPER_OF.lock().unwrap(); let m = wg.get_or_insert_with(HashMap::new); @@ -513,14 +538,20 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(pc, 2)); let n = f(pc); if n == 0 { + super::capture::forget(this as usize); + super::title_textures::forget_list_closed(this as usize); let book = SEGMENTS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); { let mut wg = WRAPPER_OF.lock().unwrap(); if let Some(m) = wg.as_mut() { - m.remove(&(pc as usize)); + if m.get(&(pc as usize)) == Some(&(this as usize)) { + m.remove(&(pc as usize)); + } if let Some(ref b) = book { for &seg in b.extra_active.iter().chain(b.spares.iter()).chain(b.first.iter()).chain(b.failed.iter()).chain(b.unresettable.iter()) { - m.remove(&seg); + if m.get(&seg) == Some(&(this as usize)) { + m.remove(&seg); + } } } } @@ -528,11 +559,14 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 { if let Some(b) = book { for seg in b.extra_active.into_iter().chain(b.spares.into_iter()).chain(b.first).chain(b.failed).chain(b.unresettable) { let raw = seg as *mut c_void; + super::alloc_pool::forget_list(seg); super::bind::forget(raw); let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(raw, 2)); rel(raw); } } + // no forget of `pc` here: the adopted primary forgot its state in its own final Release + // (`real::cl_release`), and after `f(pc)` the address may already be a new list's std::alloc::dealloc(this as *mut u8, std::alloc::Layout::from_size_align(OBJECT_BYTES, 64).unwrap()); } n @@ -731,6 +765,77 @@ mod tests { } } + #[test] + fn reset_releases_retired_split_segment_from_alloc_pool() { + unsafe extern "system" fn fake_reset(_this: *mut c_void, _alloc: usize, _pso: usize) -> HRESULT { + 0 + } + let mut vt = vec![0usize; LIST_SLOTS]; + vt[0] = fake_qi as usize; + vt[1] = fake_add_ref as usize; + vt[2] = fake_release as usize; + vt[10] = fake_reset as usize; + let primary = Box::into_raw(Box::new(Fake { vt: vt.as_ptr(), refs: 1 })); + let seg = Box::into_raw(Box::new(Fake { vt: vt.as_ptr(), refs: 1 })); + let alloc1 = 0x7E57_A110usize; + let alloc2 = 0x7E57_A120usize; + unsafe { + let w = wrap(primary as *mut c_void); + super::super::alloc_pool::created_on(seg as usize, alloc1, 0); + assert_eq!(super::super::alloc_pool::recording_backing_for_test(seg as usize), Some(alloc1)); + activate_segment(w, primary as *mut c_void, seg as *mut c_void); + assert_eq!(reset(w, alloc2, 0), 0); + assert_eq!( + super::super::alloc_pool::recording_backing_for_test(seg as usize), + None, + "retired split segment must be forgotten by alloc_pool so its allocator can be reused" + ); + assert_eq!(release(w), 0); + drop(Box::from_raw(primary)); + drop(Box::from_raw(seg)); + } + } + + #[test] + fn release_does_not_remove_reused_pc_from_wrapper_map() { + static REUSED_WRAPPER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + unsafe extern "system" fn fake_release_reusing_pc(this: *mut c_void) -> u32 { + let f = &mut *(this as *mut Fake); + f.refs -= 1; + if f.refs == 0 { + // Simulate another thread immediately creating a new wrapper on the same PC address. + f.refs = 1; + let w2 = wrap(this); + REUSED_WRAPPER.store(w2 as usize, std::sync::atomic::Ordering::Release); + return 0; + } + f.refs + } + let mut vt = vec![0usize; LIST_SLOTS]; + vt[0] = fake_qi as usize; + vt[1] = fake_add_ref as usize; + vt[2] = fake_release_reusing_pc as usize; + let fake = Box::into_raw(Box::new(Fake { vt: vt.as_ptr(), refs: 1 })); + REUSED_WRAPPER.store(0, std::sync::atomic::Ordering::Release); + unsafe { + let w1 = wrap(fake as *mut c_void); + assert_eq!(release(w1), 0); + let w2 = REUSED_WRAPPER.load(std::sync::atomic::Ordering::Acquire) as *mut c_void; + assert!(!w2.is_null()); + assert_eq!( + wrapper_of(fake as *mut c_void), + Some(w2), + "old wrapper release must not erase the new wrapper registered for a reused pc address" + ); + // Switch vtable to normal fake_release so w2 cleans up without recursing. + let mut vt2 = vt.clone(); + vt2[2] = fake_release as usize; + (*fake).vt = vt2.as_ptr(); + assert_eq!(release(w2), 0); + drop(Box::from_raw(fake)); + } + } + #[repr(C)] struct ResetFake { vt: *const usize, @@ -882,4 +987,68 @@ mod tests { drop(Box::from_raw(seg1)); } } + + /// End-to-end `title_list` lifecycle for `title_textures::CLOSED`: + /// failed Close does not record, successful Close records the wrapper pointer, failed Reset + /// keeps it, successful Reset clears it, non-final Release keeps it, and final Release clears + /// it before freeing the wrapper address. + #[test] + fn title_list_close_reset_and_release_maintain_closed_tracking() { + #[repr(C)] + struct LifecycleFake { + vt: *const usize, + refs: u32, + close_hr: HRESULT, + reset_hr: HRESULT, + } + unsafe extern "system" fn lf_add_ref(this: *mut c_void) -> u32 { + let f = &mut *(this as *mut LifecycleFake); + f.refs += 1; + f.refs + } + unsafe extern "system" fn lf_release(this: *mut c_void) -> u32 { + let f = &mut *(this as *mut LifecycleFake); + f.refs -= 1; + f.refs + } + unsafe extern "system" fn lf_close(this: *mut c_void) -> HRESULT { + (*(this as *mut LifecycleFake)).close_hr + } + unsafe extern "system" fn lf_reset(this: *mut c_void, _alloc: usize, _pso: usize) -> HRESULT { + (*(this as *mut LifecycleFake)).reset_hr + } + let mut vt = vec![0usize; LIST_SLOTS]; + vt[1] = lf_add_ref as usize; + vt[2] = lf_release as usize; + vt[9] = lf_close as usize; + vt[10] = lf_reset as usize; + let fake = Box::into_raw(Box::new(LifecycleFake { vt: vt.as_ptr(), refs: 1, close_hr: -1, reset_hr: -1 })); + unsafe { + let w = wrap(fake as *mut c_void); + assert!(!super::super::title_textures::is_list_closed_for_test(w as usize)); + // Failed Close must not mark the list closed. + assert_eq!(close(w), -1); + assert!(!super::super::title_textures::is_list_closed_for_test(w as usize)); + // Successful Close marks the wrapper pointer closed. + (*fake).close_hr = 0; + assert_eq!(close(w), 0); + assert!(super::super::title_textures::is_list_closed_for_test(w as usize)); + // Failed Reset leaves the old closed recording intact. + assert_eq!(reset(w, 0, 0), -1); + assert!(super::super::title_textures::is_list_closed_for_test(w as usize)); + // Successful Reset clears CLOSED so the reopened list does not keep a stale timestamp. + (*fake).reset_hr = 0; + assert_eq!(reset(w, 0, 0), 0); + assert!(!super::super::title_textures::is_list_closed_for_test(w as usize)); + // Re-close, AddRef, non-final Release keeps CLOSED; final Release clears it. + assert_eq!(close(w), 0); + assert!(super::super::title_textures::is_list_closed_for_test(w as usize)); + assert_eq!(add_ref(w), 2); + assert_eq!(release(w), 1); + assert!(super::super::title_textures::is_list_closed_for_test(w as usize)); + assert_eq!(release(w), 0); + assert!(!super::super::title_textures::is_list_closed_for_test(w as usize)); + drop(Box::from_raw(fake)); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 818e3547a0..2fe0c9e12e 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -27,6 +27,7 @@ use std::sync::{Arc, Mutex}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; +use super::texture_upload; use crate::gpu::texture::{self, Subresource}; use crate::hle::xg; @@ -35,10 +36,29 @@ const WRITE_WATCH_FLAG_RESET: u32 = 1; #[link(name = "kernel32")] extern "system" { fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; + fn ResetWriteWatch(base: *const c_void, size: usize) -> u32; } -/// (device, address its bytes are read from, layout, states, registration generation) of an upload -type Upload = (usize, usize, Arc, Vec, u64); +/// A texture whose upload is due, or whose memory was written: a reference while that is seen to. +struct Due { + res: ID3D12Resource, + device: usize, + /// where its bytes are read + src: usize, + tex: Arc, + states: Vec, + known: texture_upload::Known, + /// all of it goes up, whatever was written + whole: bool, + /// what of it goes up again (`texture_upload::sent`) + again: texture_upload::Change, + /// (`Entry::target`) + target: bool, + /// where its pages are read (`Entry::paged`) + pages: Option>, + /// registration generation (Entry::generation) when it was picked + generation: u64, +} /// One incarnation of a title command queue. The raw address alone can be reused after release. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -74,6 +94,9 @@ struct Entry { src: usize, /// `va` lies in a GPU view: `src` is checked again when that view's mappings change in_gpu_view: bool, + /// the title mapped pages of a GPU view under it (the queue's page mappings): `src` is `va`, + /// and each upload reads its pages where they are kept (`texture_upload::PageMap`) + paged: bool, tex: Arc, /// the state the title's submitted work leaves the texture in (uploads leave it there): /// the creation state, then what its transitions give – one state for every subresource, @@ -84,6 +107,10 @@ struct Entry { /// the title's GPU work wrote it (CopyTextureRegion into it): its CPU view is stale from /// then on and no longer uploaded gpu_written: bool, + /// the calls of the queue's page mappings made when a list that writes it was last submitted + /// (`kernelx::mirrors::calls`): a mapping changed under it by a later call is newer than the + /// GPU's write + written_call: u64, /// Last submitted GPU writer: one for the whole resource while uniform, otherwise one per /// subresource in D3D12 order. Empty until a tracked write is submitted. gpu_writers: Vec>, @@ -96,6 +123,11 @@ struct Entry { unmapped: bool, /// monotonic registration generation (newest wins when uncovering shadowed textures) generation: u64, + /// what its pages held at its last upload + known: texture_upload::Known, + /// the GPU can write it other than by copies (a render target, a UAV): XCL does not see all of + /// that, so when the CPU's bytes of it change it goes up as a whole + target: bool, } /// textures waiting for their first upload @@ -116,6 +148,30 @@ struct Table { /// Largest byte span currently in `shadowed` (bounds range queries) max_shadowed_size: usize, next_generation: u64, + /// the active textures by the 1 MiB pieces of their source (`Entry::src`) they cover: which of + /// them lie under a written page. A title has tens of thousands of textures; a submit asks + /// about the few its dirty pages touch + src_pieces: BTreeMap>, + /// textures whose first upload is still to come (`Entry::pending`; may name ones that went) + pending_res: std::collections::BTreeSet, + /// 16 MiB blocks of the textures' sources -> how many active ones cover it: the part of the + /// watched ranges that textures make (cheap to rebuild from, unlike all textures) + coarse: BTreeMap, +} + +/// the size of `Table::coarse`'s blocks +const SRC_COARSE_SHIFT: usize = 24; + +/// goes up whenever a block of `Table::coarse` becomes used or unused +static COARSE_GEN: AtomicU64 = AtomicU64::new(0); + +/// the piece (1 MiB) of an address, for `Table::src_pieces` +const SRC_PIECE_SHIFT: usize = 20; + +/// Whether `src` lies in a view window of unified memory: never watched (`Uma::watch_regions`), +/// so a texture read there (`Entry::paged`) adds no block to `Table::coarse`. +fn in_view_window(src: usize) -> bool { + crate::gpu::uma::get().is_some_and(|u| u.is_view(src)) } impl Table { @@ -127,7 +183,70 @@ impl Table { shadowed_by_va: BTreeMap::new(), max_shadowed_size: 0, next_generation: 0, + src_pieces: BTreeMap::new(), + pending_res: std::collections::BTreeSet::new(), + coarse: BTreeMap::new(), + } + } + + fn link_src(&mut self, res: usize, src: usize, size: usize) { + for p in (src >> SRC_PIECE_SHIFT)..=((src + size.max(1) - 1) >> SRC_PIECE_SHIFT) { + self.src_pieces.entry(p).or_default().push(res); + } + if in_view_window(src) { + return; + } + for b in (src >> SRC_COARSE_SHIFT)..=((src + size.max(1) - 1) >> SRC_COARSE_SHIFT) { + let c = self.coarse.entry(b).or_insert(0); + *c += 1; + if *c == 1 { + COARSE_GEN.fetch_add(1, Ordering::Release); + } + } + } + + fn unlink_src(&mut self, res: usize, src: usize, size: usize) { + for p in (src >> SRC_PIECE_SHIFT)..=((src + size.max(1) - 1) >> SRC_PIECE_SHIFT) { + if let Some(v) = self.src_pieces.get_mut(&p) { + v.retain(|&r| r != res); + if v.is_empty() { + self.src_pieces.remove(&p); + } + } + } + if in_view_window(src) { + return; + } + for b in (src >> SRC_COARSE_SHIFT)..=((src + size.max(1) - 1) >> SRC_COARSE_SHIFT) { + let gone = match self.coarse.get_mut(&b) { + Some(c) if *c > 1 => { + *c -= 1; + false + } + Some(_) => true, + None => false, + }; + if gone { + self.coarse.remove(&b); + COARSE_GEN.fetch_add(1, Ordering::Release); + } + } + } + + /// The textures (active) whose source the dirty pages `dirty` (sorted) may touch. + fn touched_by(&self, dirty: &[usize]) -> std::collections::BTreeSet { + let mut out = std::collections::BTreeSet::new(); + let mut last = usize::MAX; + for &p in dirty { + let piece = p >> SRC_PIECE_SHIFT; + if piece != last { + last = piece; + if let Some(v) = self.src_pieces.get(&piece) { + out.extend(v.iter().copied()); + } + } } + out } fn has_active_overlap(&self, va: usize, end: usize) -> bool { @@ -175,6 +294,7 @@ impl Table { for (ova, ores, _) in self.active_overlaps(va, end) { self.by_va.remove(&(ova, ores)); if let Some(old) = self.by_res.remove(&ores) { + self.unlink_src(ores, old.src, old.tex.size() as usize); if old.pending { pending_delta -= 1; } @@ -210,6 +330,7 @@ impl Table { let mut pending_delta = 0isize; let mut to_unmap = Vec::new(); if let Some(old) = self.by_res.remove(&res) { + self.unlink_src(res, old.src, old.tex.size() as usize); self.by_va.remove(&(old.va, res)); if old.pending { pending_delta -= 1; @@ -224,6 +345,7 @@ impl Table { } self.by_va.remove(&(ova, ores)); if let Some(mut old) = self.by_res.remove(&ores) { + self.unlink_src(ores, old.src, old.tex.size() as usize); if old.pending { pending_delta -= 1; } @@ -231,6 +353,9 @@ impl Table { old.unmapped = true; to_unmap.push(ores); } + if old.placed && entry.placed { + texture_upload::inherit(&entry.known, &old.known); + } self.max_shadowed_size = self.max_shadowed_size.max(oend.saturating_sub(ova)); self.shadowed_by_va.insert((ova, ores), oend); self.shadowed.insert(ores, old); @@ -252,8 +377,11 @@ impl Table { entry.generation = self.next_generation; if entry.pending { pending_delta += 1; + self.pending_res.insert(res); } self.by_va.insert((va, res), end); + let (src, size) = (entry.src, entry.tex.size() as usize); + self.link_src(res, src, size); self.by_res.insert(res, entry); (pending_delta, to_unmap) } @@ -269,6 +397,7 @@ impl Table { return (true, 0, Vec::new()); } let Some(old) = self.by_res.remove(&res) else { return (false, 0, Vec::new()) }; + self.unlink_src(res, old.src, old.tex.size() as usize); self.by_va.remove(&(old.va, res)); let mut pending_delta = if old.pending { -1 } else { 0 }; let va = old.va; @@ -286,6 +415,8 @@ impl Table { } self.shadowed_by_va.remove(&(sva, sres)); if let Some(mut e) = self.shadowed.remove(&sres) { + // (the one that lay over it may have been uploaded over the same video memory) + texture_upload::forget(&e.known); if e.unmapped { e.unmapped = false; to_remap.push(sres); @@ -297,6 +428,11 @@ impl Table { pending_delta += 1; } self.by_va.insert((sva, sres), send); + let (src, size) = (e.src, e.tex.size() as usize); + self.link_src(sres, src, size); + if e.pending { + self.pending_res.insert(sres); + } self.by_res.insert(sres, e); } } @@ -345,16 +481,10 @@ static TEXTURES: Mutex = Mutex::new(Table::new()); static REFRESH: Mutex<()> = Mutex::new(()); static TEXTURES_GEN: AtomicU64 = AtomicU64::new(0); static TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -static CPU_TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - -struct WatchRanges { - ranges: Vec<(usize, usize)>, - wanted_bytes: usize, - excess_bytes: usize, -} +/// cached `watch_ranges` keyed by `watch_key` +static WATCH_CACHE: Mutex>)>> = Mutex::new(None); -/// cached `watch_ranges` keyed by `(sparse::mapped_gen, TEXTURES_GEN, graphics_reservations_gen)` -static WATCH_CACHE: Mutex)>> = Mutex::new(None); +static CPU_TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// the queue uploads go to, per device static QUEUES: Mutex> = Mutex::new(BTreeMap::new()); static UPLOADS: AtomicU64 = AtomicU64::new(0); @@ -393,8 +523,7 @@ fn is_small_cpu_filled_target(w: u64, h: u32, samples: u32, flags: u32) -> bool /// A texture the title placed at `va` (its console desc `desc`): kept in step with the memory. pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, desc: &[u8; 0x38], state: D3D12_RESOURCE_STATES) -> Result<(), String> { - // (a new texture object, or the address of an old one again: its first upload is not left out) - LAST_CONTENT.lock().unwrap().remove(&(res as usize)); + // (a new texture object, or the address of an old one again: no stale fingerprint schedule) STREAM_RECHECK.lock().unwrap().remove(&(res as usize)); let tex = xg::Texture::new(desc).map_err(|hr| format!("layout {hr:#x}"))?; // the console's 32-bit 116 / 117 floats are half floats on the PC (`pc_resource_desc`): the @@ -429,7 +558,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, if ID3D12Resource::from_raw_borrowed(&res).is_none() { return Err("no resource".into()); } - let src = mirror_source(va); + let (src, paged) = source_of(va, tex.size() as usize); if src != va { static N: AtomicU64 = AtomicU64::new(0); let n = N.fetch_add(1, Ordering::Relaxed) + 1; @@ -437,6 +566,9 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, crate::xlog_info!("D3D12.X: a texture at {va:#x} lies in a GPU view of the title's CPU memory: kept in step with {src:#x} ({n} so far)"); } } + if paged { + note_paged(va); + } let in_gpu_view = crate::hle::kernelx::mirrors::source(va).is_some(); let placed = super::vram::is_placed_texture(res as usize); let e = Entry { @@ -445,16 +577,21 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, va, src, in_gpu_view, + paged, tex: Arc::new(tex), states: vec![state], pending: true, gpu_written: false, + written_call: 0, gpu_writers: Vec::new(), cpu_backed: true, placed, unmapped: false, generation: 0, + known: Default::default(), + target: u32::from_le_bytes(desc[0x30..0x34].try_into().unwrap()) & 0x7 != 0, }; + let (hot_src, hot_bytes) = (e.src, e.tex.size() as usize); let to_unmap = { let mut t = TEXTURES.lock().unwrap(); let (delta, unmap_ptrs) = t.insert(res as usize, e); @@ -466,6 +603,8 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, super::vram::unmap_superseded(r); } TEXTURES_GEN.fetch_add(1, Ordering::Release); + // the data the title is about to write there is for the next submit + mark_hot(hot_src, hot_bytes); Ok(()) } @@ -534,6 +673,10 @@ pub(super) unsafe fn register_gpu_owned( placed: true, unmapped: false, generation: 0, + paged: false, + written_call: 0, + known: Default::default(), + target: false, }; let to_unmap = { let mut t = TEXTURES.lock().unwrap(); @@ -558,44 +701,201 @@ fn mirror_source(va: usize) -> usize { return va; } use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + #[cfg(test)] + tests::QUERIES.with(|n| n.set(n.get() + 1)); let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; let mapped = unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0 && m.State == MEM_COMMIT; if mapped { va } else { src } } +/// Where a texture at `va` of `size` bytes is read, and whether through a table of its pages: a +/// texture over pages of a GPU view the queue's page mappings named is read at `va`, each page +/// where it is kept (no lock of AWAY, no VirtualQuery); any other as `mirror_source` says. +fn source_of(va: usize, size: usize) -> (usize, bool) { + if crate::hle::kernelx::mirrors::touched(va, size) { + return (va, true); + } + (mirror_source(va), false) +} + +/// A texture at `va` is read through the pages the title mapped under it. +fn note_paged(va: usize) { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: a texture at {va:#x} lies in a GPU view whose pages the title mapped (CopyPageMappingsBatchX): read where each page is kept ({n} so far)"); + } +} + +/// The pages of the uploads read through a table: [kept elsewhere, kept at the CPU view's same +/// offset, at that offset never mapped, unmapped] (`kernelx::mirrors::resolve`). +static PAGE_COUNTS: [AtomicU64; 4] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; + +/// What `PAGE_COUNTS` counted so far. +pub fn page_counts() -> [u64; 4] { + PAGE_COUNTS.each_ref().map(|c| c.load(Ordering::Relaxed)) +} + +/// The table an upload of the texture at `va` of `size` bytes reads its pages through (None: the +/// title mapped none of them); `count`: its pages go into `PAGE_COUNTS`. +fn page_map(va: usize, size: usize, count: bool) -> Option> { + let mut at = Vec::new(); + let counts = crate::hle::kernelx::mirrors::resolve(va, size, &mut at)?; + if count { + for (c, n) in PAGE_COUNTS.iter().zip(counts) { + c.fetch_add(n as u64, Ordering::Relaxed); + } + } + Some(Arc::new(texture_upload::PageMap::new(va, at))) +} + +/// the changed GPU-view pages of the queue's page mappings a submit takes at most (one upload +/// batch of them); the rest at the next +const CHANGED_MAX: usize = BATCH_BYTES / crate::hle::kernelx::mirrors::PAGE; + +/// textures read again for a mapping changed under them +static REREAD: AtomicU64 = AtomicU64::new(0); + +/// The textures read again so far because a mapping changed under them. +pub fn rereads() -> u64 { + REREAD.load(Ordering::Relaxed) +} + /// Physical pages were mapped or unmapped in a GPU view since the last look: textures there /// whose source changed (a page now mapped under one, or gone from it) read from the new one, -/// uploaded again at this submit. +/// uploaded again at this submit. The pages the queue's page mappings changed go up again in +/// the textures read through them (`mapping_changed`). fn recheck_gpu_view_sources() { + use crate::hle::kernelx::mirrors; static SEEN: AtomicU64 = AtomicU64::new(0); + // (the cursor of the changed pages of the queue's page mappings: one reader, under REFRESH) + static PAGES_SEEN: AtomicU64 = AtomicU64::new(0); let gen = crate::hle::kernelx::gpu_view_map_gen(); - if SEEN.swap(gen, Ordering::AcqRel) == gen { + let seen = SEEN.swap(gen, Ordering::AcqRel); + let (cursor, pages) = mirrors::changes_since(PAGES_SEEN.load(Ordering::Acquire), 0, usize::MAX, CHANGED_MAX); + PAGES_SEEN.store(cursor, Ordering::Release); + if seen == gen && pages.is_empty() { return; } let mut changed = false; // (the shadowed textures too: one comes back when the texture over it goes) let mut g = TEXTURES.lock().unwrap(); let t = &mut *g; - for e in t.by_res.values_mut().chain(t.shadowed.values_mut()) { - changed |= recheck_source(e); + // the textures over a changed page: the newest call among their changed pages, and those + // pages' bytes of them + let mut remapped: BTreeMap)> = BTreeMap::new(); + for &(p, call) in &pages { + let end = p + mirrors::PAGE; + for (va, r, to) in t.active_overlaps(p, end).into_iter().chain(t.shadowed_overlaps(p, end)) { + let e = remapped.entry(r).or_insert((0, Vec::new())); + e.0 = e.0.max(call); + e.1.push((p.max(va) - va, end.min(to) - va)); + } + } + // the textures whose source may have changed: those overlapping the ranges whose mappings + // changed since the last look (all of them when the log of changes has lost some) + let names: Option> = if seen == gen { + Some(std::collections::BTreeSet::new()) + } else { + crate::hle::kernelx::gpu_view_map_changes(seen).map(|ranges| { + let mut s = std::collections::BTreeSet::new(); + for (lo, hi) in ranges { + s.extend(t.active_overlaps(lo, hi).into_iter().map(|(_, r, _)| r)); + s.extend(t.shadowed_overlaps(lo, hi).into_iter().map(|(_, r, _)| r)); + } + s + }) + } + .map(|mut s| { + s.extend(remapped.keys().copied()); + s + }); + let mut moved: Vec<(usize, usize, usize, usize, bool)> = Vec::new(); + let mut again: Vec = Vec::new(); + let Table { by_res, shadowed, .. } = t; + let mut look = |res: usize, e: &mut Entry, active: bool| { + let (old, size) = (e.src, e.tex.size() as usize); + if recheck_source(e) { + changed = true; + if active { + moved.push((res, old, e.src, size, e.pending)); + } + } + if let Some((call, parts)) = remapped.remove(&res) { + if mapping_changed(e, call, parts, active) { + again.push(res); + } + } + }; + match &names { + Some(s) => { + for &r in s { + if let Some(e) = by_res.get_mut(&r) { + look(r, e, true); + } else if let Some(e) = shadowed.get_mut(&r) { + look(r, e, false); + } + } + } + None => { + for (&r, e) in by_res.iter_mut() { + look(r, e, true); + } + for (&r, e) in shadowed.iter_mut() { + look(r, e, false); + } + } + } + for (res, old, new, size, pending) in moved { + t.unlink_src(res, old, size); + t.link_src(res, new, size); + if pending { + t.pending_res.insert(res); + } } drop(g); + if !again.is_empty() { + AGAIN.lock().unwrap().extend(again); + } if changed { TEXTURES_GEN.fetch_add(1, Ordering::Release); } } +/// The queue's page mappings changed `parts` (from, to) of `e` by call `call`. A texture read +/// through its pages sends them again with its next upload, as known changes with no comparison +/// (a clean pool page newly mapped holds bytes the PC texture never had): true, and it goes into +/// AGAIN. A shadowed one goes up whole once it is uncovered, as on a change of its source. The +/// GPU's write of a list submitted at or after that call stays; an older one gives way. +fn mapping_changed(e: &mut Entry, call: u64, parts: Vec<(usize, usize)>, active: bool) -> bool { + if !e.paged || e.pending || (e.gpu_written && e.written_call >= call) { + return false; + } + e.gpu_written = false; + REREAD.fetch_add(1, Ordering::Relaxed); + if !active { + e.pending = true; + PENDING.fetch_add(1, Ordering::Relaxed); + return false; + } + texture_upload::stale(&e.known, parts); + true +} + /// `e`'s source again (a texture in a GPU view): when it changed, `e` reads the new one and is /// uploaded at the next submit. Whether it changed. fn recheck_source(e: &mut Entry) -> bool { if !e.cpu_backed || !e.in_gpu_view { return false; } - let src = mirror_source(e.va); - if src == e.src { + let (src, paged) = source_of(e.va, e.tex.size() as usize); + if src == e.src && paged == e.paged { return false; } - e.src = src; + if paged && !e.paged { + note_paged(e.va); + } + (e.src, e.paged) = (src, paged); if !e.pending { e.pending = true; PENDING.fetch_add(1, Ordering::Relaxed); @@ -635,6 +935,8 @@ pub(super) fn publish_submission_effects(queue: Option, writes: & let mut newly_written = Vec::new(); { let mut t = TEXTURES.lock().unwrap(); + // (the stamp is for the queue's page mappings: with them off, a publish takes no call count) + let call = crate::hle::kernelx::mirrors::page_mappings().then(crate::hle::kernelx::mirrors::calls); if let Some(queue) = queue { for &write in writes { let Some(e) = t.get_mut(write.res).filter(|e| e.generation == write.generation) else { continue }; @@ -645,6 +947,10 @@ pub(super) fn publish_submission_effects(queue: Option, writes: & let epoch = NEXT_GPU_EPOCH.fetch_add(1, Ordering::Relaxed) + 1; let writer = GpuWriter { epoch, queue }; apply_gpu_writer(&mut e.gpu_writers, n, write.subresource, writer); + if let Some(call) = call { + // (`Entry::written_call`: a mapping changed by a later call is newer than this write) + e.written_call = call; + } if !e.gpu_written { e.gpu_written = true; GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); @@ -721,7 +1027,6 @@ pub(super) unsafe fn retire_overlapping(va: usize, len: usize) { /// The PC texture was released for good. pub fn forget(res: usize) { - LAST_CONTENT.lock().unwrap().remove(&res); STREAM_RECHECK.lock().unwrap().remove(&res); let (removed, to_remap) = { let mut t = TEXTURES.lock().unwrap(); @@ -806,7 +1111,7 @@ fn apply_gpu_writer(writers: &mut Vec>, n: usize, sub: u32, wr /// `states` (one for all `n` subresources, or one each) after a transition of subresource `sub` /// (or all of them) to `after`; a subresource the texture does not have is ignored. -fn apply_transition(states: &mut Vec, n: usize, sub: u32, after: D3D12_RESOURCE_STATES) { +pub(super) fn apply_transition(states: &mut Vec, n: usize, sub: u32, after: D3D12_RESOURCE_STATES) { if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES || (n <= 1 && sub == 0) { *states = vec![after]; return; @@ -832,8 +1137,22 @@ thread_local! { static WATCH_BUF: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; /// Reusable dirty page list for `refresh_once`. static DIRTY_BUF: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + /// Reusable list of the GPU-view pages the dirty pages are written to (`views_of_written`). + static TWINS_BUF: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } +/// What the watched ranges are made of, as generations. +fn watch_key() -> (u64, u64, u64, u64) { + (super::sparse::mapped_gen(), COARSE_GEN.load(Ordering::Acquire), crate::hle::kernelx::graphics_reservations_gen(), crate::hle::kernelx::mirrors::shown_gen()) +} + +/// The ranges the last look used, and whether they are still all there is. +fn last_watch_ranges() -> Option<(Arc>, bool)> { + let g = WATCH_CACHE.lock().unwrap(); + g.as_ref().map(|(k, ranges)| (Arc::clone(ranges), *k == watch_key())) +} + +#[cfg_attr(not(test), allow(dead_code))] fn watched_texture_span(src: usize, bytes: u64) -> Option<(usize, usize)> { let bytes = usize::try_from(bytes).ok()?; if bytes == 0 { @@ -862,12 +1181,13 @@ fn texture_needs_upload( dirty_overlap() } -fn cached_watch_ranges(u: &crate::gpu::uma::Uma, measure: bool) -> Arc { - let key = ( - super::sparse::mapped_gen(), - TEXTURES_GEN.load(Ordering::Acquire), - crate::hle::kernelx::graphics_reservations_gen(), - ); +/// What the watch ranges last made cost, for the write-watch trace (`note_watch_measurement`): +/// the bytes of what is wanted itself (`plan_watch_ranges` with no call budget; 0 when the ranges +/// were made without `measure`) and the bytes watched beyond it (gaps, whole blocks). +static WATCH_PLAN: Mutex<(usize, usize)> = Mutex::new((0, 0)); + +fn cached_watch_ranges(u: &crate::gpu::uma::Uma, measure: bool) -> Arc> { + let key = watch_key(); { let g = WATCH_CACHE.lock().unwrap(); if let Some((k, ref ranges)) = *g { @@ -880,21 +1200,24 @@ fn cached_watch_ranges(u: &crate::gpu::uma::Uma, measure: bool) -> Arc = TEXTURES - .lock() - .unwrap() - .by_res - .values() - .filter(|e| e.cpu_backed) - .filter_map(|e| watched_texture_span(e.src, e.tex.size())) - .collect(); + // (by 16 MiB blocks, not by texture: a title has tens of thousands, and their sources change + // every submit while it loads) + let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().coarse.keys().map(|&b| (b << SRC_COARSE_SHIFT, (b + 1) << SRC_COARSE_SHIFT)).collect(); wanted.extend(super::sparse::mapped_ranges()); + // (the blocks where the pages the queue's page mappings show are kept: the pool, the CPU view) + wanted.extend(crate::hle::kernelx::mirrors::shown_blocks()); let exact = measure.then(|| plan_watch_ranges(®ions, wanted.clone(), usize::MAX)); - let ranges = watch_ranges(®ions, wanted); + let computed = watch_ranges(®ions, wanted); let wanted_bytes = exact.as_ref().map_or(0, |exact| exact.iter().fold(0usize, |bytes, &(_, n)| bytes.saturating_add(n))); - let scanned_bytes = ranges.iter().fold(0usize, |bytes, &(_, n)| bytes.saturating_add(n)); - let computed = Arc::new(WatchRanges { ranges, wanted_bytes, excess_bytes: scanned_bytes.saturating_sub(wanted_bytes) }); - *WATCH_CACHE.lock().unwrap() = Some((key, Arc::clone(&computed))); + let scanned_bytes = computed.iter().fold(0usize, |bytes, &(_, n)| bytes.saturating_add(n)); + let mut g = WATCH_CACHE.lock().unwrap(); + *WATCH_PLAN.lock().unwrap() = (wanted_bytes, scanned_bytes.saturating_sub(wanted_bytes)); + // (ranges that came out the same stay the same object: `hot_runs` keeps its blocks by it) + let computed = match g.take() { + Some((_, old)) if *old == computed => old, + _ => Arc::new(computed), + }; + *g = Some((key, Arc::clone(&computed))); computed } @@ -923,9 +1246,151 @@ pub(super) unsafe fn refresh(queue: *mut c_void) -> super::sparse::PreparationOu let _refresh = REFRESH.lock().unwrap(); let active_t0 = measure.then(std::time::Instant::now); let mut look = measure.then(super::sparse::LookSample::default); - let outcome = own_work(|| refresh_once(queue, look.as_mut())); + let outcome = own_work(|| refresh_once(queue, true, look.as_mut())); if let (Some(wait_t0), Some(active_t0), Some(look)) = (wait_t0, active_t0, look) { - super::sparse::note_look(look, active_t0.elapsed(), active_t0.duration_since(wait_t0)); + super::sparse::note_look_sample(look, active_t0.elapsed(), active_t0.duration_since(wait_t0)); + } + outcome +} + +/// microseconds since the first call, never 0 +fn now_us() -> u64 { + static T0: std::sync::OnceLock = std::sync::OnceLock::new(); + T0.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 + 1 +} + +/// `(began_us, frame)` of the last look for CPU writes (`began_us == 0`: none yet; `frame` is +/// `present::activity().0` when the look began so every new frame takes at least one fresh look). +static LAST_LOOK: Mutex<(u64, u64)> = Mutex::new((0, u64::MAX)); +/// title list -> when the title closed it (`now_us`) +static CLOSED: Mutex>> = Mutex::new(None); + +fn last_look() -> (u64, u64) { + *LAST_LOOK.lock().unwrap() +} + +fn advance_look(state: &mut (u64, u64), began: u64, frame: u64) { + if state.0 == 0 || frame > state.1 { + state.0 = began; + state.1 = frame; + } else if frame == state.1 { + state.0 = state.0.max(began); + } +} + +/// Record that a write-watch look began at `began` (`now_us`) during `frame`. +/// Monotonic in `(frame, began)` so an older `XCL_LOOK_AHEAD` round never rewinds a newer frame. +fn note_look_began(began: u64, frame: u64) { + let mut g = LAST_LOOK.lock().unwrap(); + advance_look(&mut g, began, frame); +} + +/// The title closed `list` (its own pointer): what the list's GPU work reads was written by now. +pub(super) fn note_list_closed(list: usize) { + CLOSED.lock().unwrap().get_or_insert_with(Default::default).insert(list, now_us()); +} + +/// Clear any recorded close time for `list` (reset, reopened via `KickoffX`, or released) so a +/// reopened or pointer-reused list never retains a stale `t < LOOK_BEGAN` timestamp. +pub(super) fn forget_list_closed(list: usize) { + let mut g = CLOSED.lock().unwrap(); + if let Some(m) = g.as_mut() { + if !m.is_empty() { + m.remove(&list); + } + } +} + +#[cfg(test)] +pub(super) fn is_list_closed_for_test(list: usize) -> bool { + CLOSED.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&list)) +} + +/// `XCL_LOOK_SKIP=1`: a submit in the same frame as the last look whose lists were all closed +/// before that look began goes without a look of its own (that look took what the lists read). +/// Every new frame still guarantees at least one fresh look. Off unless set: a title may write +/// what a closed list reads until it submits the list. +fn look_skip() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_LOOK_SKIP").is_ok_and(|v| v.trim() == "1")) +} + +/// when the walk last made a block hot (`now_us`): no look before that took the block +static WALK_FOUND: AtomicU64 = AtomicU64::new(0); + +fn closed_before_last_look_in(lists: &[*mut c_void], began: u64, look_frame: u64, current_frame: u64, walk_found: u64) -> bool { + if began == 0 || lists.is_empty() { + return false; + } + // Every new frame guarantees at least one fresh write-watch look. + if look_frame != current_frame { + return false; + } + // (a block the walk found written since: the look that began then did not take it) + if walk_found >= began { + return false; + } + let g = CLOSED.lock().unwrap(); + let Some(m) = g.as_ref() else { return false }; + lists.iter().all(|&l| m.get(&(l as usize)).is_some_and(|&t| t < began)) +} + +fn closed_before_last_look(lists: &[*mut c_void]) -> bool { + let (began, look_frame) = last_look(); + let current_frame = super::present::activity().0; + let walk_found = WALK_FOUND.load(Ordering::Acquire); + closed_before_last_look_in(lists, began, look_frame, current_frame, walk_found) +} + +#[inline] +fn should_look(all_closed_before_last_look: bool, skip_enabled: bool, presenting: bool) -> bool { + !(all_closed_before_last_look && skip_enabled) && !presenting +} + +/// When the youngest of `lists` was closed (None: one was not seen closing). +fn youngest_closed(lists: &[*mut c_void]) -> Option { + let g = CLOSED.lock().unwrap(); + let m = g.as_ref()?; + lists.iter().map(|&l| m.get(&(l as usize)).copied()).try_fold(0, |a, t| Some(t?.max(a))) +} + +thread_local! { + /// diagnostic: how long ago the youngest list of this thread's submit was closed (µs) + static CLOSED_AGO: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// `refresh` before the title's ExecuteCommandLists of `lists` (its own pointers). +pub(super) unsafe fn refresh_for(queue: *mut c_void, lists: &[*mut c_void]) -> super::sparse::PreparationOutcome { + if BUSY.with(|b| b.get()) { + return super::sparse::PreparationOutcome::Ready; + } + let measure = super::memory_report::enabled(); + let t0 = std::time::Instant::now(); + let _refresh = REFRESH.lock().unwrap(); + let locked = std::time::Instant::now(); + super::submit_cost::lock_wait(locked.duration_since(t0)); + // with the lock: the look before this one is done, and its uploads are submitted + let old = closed_before_last_look(lists); + static N: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; + let n = N[0].fetch_add(1, Ordering::Relaxed) + 1; + let k = N[1].fetch_add(old as u64, Ordering::Relaxed) + old as u64; + if n % 1024 == 0 { + crate::xlog_info!( + "D3D12.X: {k} of {n} ExecuteCommandLists so far had all their lists closed before the last look for CPU writes began ({})", + if look_skip() { "their looks were left out" } else { "XCL_LOOK_SKIP=1 leaves their looks out" } + ); + } + let t1 = std::time::Instant::now(); + // (XCL's copy of the frame to its window reads no memory of the title) + let look = should_look(old, look_skip(), super::present::presenting()); + if look && super::look_stats::on() { + CLOSED_AGO.with(|c| c.set(youngest_closed(lists).map(|t| now_us().saturating_sub(t)))); + } + let mut sample = measure.then(super::sparse::LookSample::default); + let outcome = own_work(|| refresh_once(queue, look, sample.as_mut())); + super::submit_cost::refresh(t1.elapsed()); + if let Some(sample) = sample { + super::sparse::note_look_sample(sample, locked.elapsed(), locked.duration_since(t0)); } outcome } @@ -950,15 +1415,23 @@ unsafe fn take_written( ) -> bool { let Some(end) = base.checked_add(size) else { return false }; let mut at = base; + // (`XCL_LOOK_STATS=2`: each call timed, for the look split) + let split = super::look_stats::deep(); while at < end { let mut n = buf.len(); - let started = measurement.as_ref().map(|_| std::time::Instant::now()); - let result = GetWriteWatch(WRITE_WATCH_FLAG_RESET, at as *const c_void, end - at, buf.as_mut_ptr(), &mut n, page); - if let Some(m) = measurement.as_mut() { - m.calls += 1; - m.elapsed_ns = m.elapsed_ns.saturating_add(started.unwrap().elapsed().as_nanos().min(u64::MAX as u128) as u64); + let t = (split || measurement.is_some()).then(std::time::Instant::now); + let failed = GetWriteWatch(WRITE_WATCH_FLAG_RESET, at as *const c_void, end - at, buf.as_mut_ptr(), &mut n, page) != 0; + if let Some(t) = t { + let took = t.elapsed(); + if split { + super::look_stats::watch_call(took, end - at, if failed { 0 } else { n }); + } + if let Some(m) = measurement.as_mut() { + m.calls += 1; + m.elapsed_ns = m.elapsed_ns.saturating_add(took.as_nanos().min(u64::MAX as u128) as u64); + } } - if result != 0 { + if failed { return false; } dirty.extend(buf[..n].iter().map(|&p| p as usize)); @@ -971,13 +1444,14 @@ unsafe fn take_written( true } -fn note_watch_measurement(plan: &WatchRanges, measurement: &WatchMeasurement) { +fn note_watch_measurement(ranges: &[(usize, usize)], measurement: &WatchMeasurement) { static TOTALS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; + let (wanted_bytes, excess_bytes) = *WATCH_PLAN.lock().unwrap(); let values = [ 1, - plan.wanted_bytes as u64, - plan.excess_bytes as u64, - plan.ranges.len() as u64, + wanted_bytes as u64, + excess_bytes as u64, + ranges.len() as u64, measurement.calls, measurement.elapsed_ns, ]; @@ -993,42 +1467,540 @@ fn note_watch_measurement(plan: &WatchRanges, measurement: &WatchMeasurement) { } } -unsafe fn refresh_once(queue: *mut c_void, mut look: Option<&mut super::sparse::LookSample>) -> super::sparse::PreparationOutcome { +/// `XCL_WATCH_HOT=0`: every look before a submit walks all the watched memory, as before. +/// Otherwise a look takes the 2 MiB blocks written in the last few seconds only, and a thread of +/// its own walks the rest in small steps and makes a block hot when it finds a written page there +/// (within ~10 ms; its pages stay reported until a look takes them). A look over 8 GiB of +/// committed memory took 4.3-4.9 ms however few pages were written, on one thread or split over +/// sixteen (measured, Windows 11 26300); 64 looks of 2 MiB took 0.2 ms. A retail title's world +/// made ~66 submits a frame on one thread, each behind a 7 ms look over ~11 GiB. +fn hot_looks() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WATCH_HOT").map_or(true, |v| v.trim() != "0")) +} + +const HOT_BLOCK: usize = 2 << 20; +/// the gap up to which hot blocks go into one write-watch call (`XCL_WATCH_GAP_MB`, 64 unless +/// given): a call waits for the process's memory lock, which is busy while the title loads, and +/// costs more than walking some megabytes of pages +fn hot_gap() -> usize { + static GAP: std::sync::OnceLock = std::sync::OnceLock::new(); + *GAP.get_or_init(|| std::env::var("XCL_WATCH_GAP_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(64) << 20) +} +/// a block nothing was written to for this long is left to the walk again (`XCL_WATCH_HOT_MS`, +/// 1500 unless given) +fn hot_for() -> std::time::Duration { + static MS: std::sync::OnceLock = std::sync::OnceLock::new(); + std::time::Duration::from_millis(*MS.get_or_init(|| std::env::var("XCL_WATCH_HOT_MS").ok().and_then(|v| v.trim().parse().ok()).filter(|&v| v >= 20).unwrap_or(1500))) +} + +#[derive(Default)] +struct HotBlocks { + /// block -> when a look or the walk last found a written page in it + hot: BTreeMap, + /// the ranges `known` was made for + ranges: Option>>, + /// the blocks of those ranges (a block new to the ranges starts hot) + known: std::collections::HashSet, +} + +static HOT: Mutex> = Mutex::new(None); +/// the ranges of the last look, for the walk +static WALK_RANGES: Mutex>>> = Mutex::new(None); +/// a look is at its write-watch calls: the walk stays out of the way (the kernel does one such +/// call at a time; with the walk going all the time, a look of 45 calls waited behind it for +/// ~1.3 ms in all) +static LOOKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// looks, runs they took, bytes they covered, blocks the walk made hot +static HOT_STATS: [AtomicU64; 4] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; + +/// The hot blocks of `ranges` as runs, each inside one range (a write-watch call covers one +/// allocation), and how many blocks are hot. +fn hot_runs(ranges: &Arc>, now: std::time::Instant) -> (Vec<(usize, usize)>, usize) { + let mut g = HOT.lock().unwrap(); + let h = g.get_or_insert_with(HotBlocks::default); + // a block new to the ranges starts hot: memory just mapped is often written and used at once + if !h.ranges.as_ref().is_some_and(|r| Arc::ptr_eq(r, ranges)) { + let mut known = std::collections::HashSet::with_capacity(h.known.len()); + for &(base, size) in ranges.iter() { + let mut b = base & !(HOT_BLOCK - 1); + while b < base + size { + if !h.known.contains(&b) { + h.hot.insert(b, now); + } + known.insert(b); + b += HOT_BLOCK; + } + } + h.known = known; + h.ranges = Some(Arc::clone(ranges)); + } + let keep = hot_for(); + h.hot.retain(|_, t| now.saturating_duration_since(*t) < keep); + let mut runs: Vec<(usize, usize)> = Vec::new(); + for (&b, _) in h.hot.iter() { + let mut j = ranges.partition_point(|&(base, size)| base + size <= b); + while let Some(&(base, size)) = ranges.get(j) { + if base >= b + HOT_BLOCK { + break; + } + let (lo, hi) = (b.max(base), (b + HOT_BLOCK).min(base + size)); + if lo < hi { + match runs.last_mut() { + // one call for hot blocks up to HOT_GAP apart in the same range: a call costs + // about as much as walking 6 MiB of committed pages + Some(last) if last.0 >= base && lo - (last.0 + last.1) <= hot_gap() => last.1 = hi - last.0, + _ => runs.push((lo, hi - lo)), + } + } + j += 1; + } + } + (runs, h.hot.len()) +} + +/// The blocks of `pages`, which a look found written, are hot from `now` on. +fn keep_hot(pages: &[usize], now: std::time::Instant) { + if pages.is_empty() { + return; + } + if let Some(h) = HOT.lock().unwrap().as_mut() { + let mut last = usize::MAX; + for &p in pages { + let b = p & !(HOT_BLOCK - 1); + if b != last { + h.hot.insert(b, now); + last = b; + } + } + } +} + +/// `XCL_LOOK_AHEAD=ms` (off unless given): a thread takes the written pages of the hot blocks every +/// so many milliseconds while the title submits. They are dirty by XCL's account from then on +/// (`AHEAD`): the next submit takes them with what its own look finds, and one whose lists were +/// closed before such a round began needs no look (`XCL_LOOK_SKIP`). A look's time goes up with the +/// pages it takes – each is a page-table entry changed and flushed on every core, ~0.5 µs with the +/// title's threads running – and a retail title's world had ~8,000 a look: 5 ms on the thread that +/// submits. +fn look_ahead() -> Option { + static MS: std::sync::OnceLock = std::sync::OnceLock::new(); + let ms = *MS.get_or_init(|| std::env::var("XCL_LOOK_AHEAD").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)); + (ms > 0 && hot_looks()).then(|| std::time::Duration::from_millis(ms)) +} + +/// pages found ahead of the next submit +static AHEAD: Mutex> = Mutex::new(Vec::new()); +/// one look, or a piece of the thread's, at a time: what the one before was told is in `AHEAD` or in +/// its submit's hands when the next one asks +static ONE_LOOK: Mutex<()> = Mutex::new(()); +/// when the last submit came (`now_us`; the thread rests while there are none) +static LAST_SUBMIT: AtomicU64 = AtomicU64::new(0); + +/// The written pages of `[at, at + len)` taken into `ahead`: how many. +unsafe fn take_piece(at: usize, len: usize, buf: &mut [*mut c_void], ahead: &Mutex>) -> usize { + let (mut found, mut page) = (Vec::new(), 0x1000u32); + { + let _one = ONE_LOOK.lock().unwrap_or_else(|e| e.into_inner()); + LOOKING.store(true, Ordering::Release); + take_written(at, len, buf, &mut found, &mut page, None); + LOOKING.store(false, Ordering::Release); + ahead.lock().unwrap().extend_from_slice(&found); + } + keep_hot(&found, std::time::Instant::now()); + found.len() +} + +/// The written pages of all hot blocks, in pieces (a submit's look waits for one at most). +unsafe fn take_round(buf: &mut [*mut c_void]) -> usize { + const PIECE: usize = 64 << 20; + // (frame before `began`: guarantees `began` is never earlier than `frame`'s start, + // and both precede asking for ranges so memory new after that is not in the round) + let frame = super::present::activity().0; + let began = now_us(); + let Some((ranges, all)) = last_watch_ranges() else { return 0 }; + let mut n = 0; + for (base, size) in hot_runs(&ranges, std::time::Instant::now()).0 { + for at in (base..base + size).step_by(PIECE) { + n += take_piece(at, PIECE.min(base + size - at), buf, &AHEAD); + } + } + // (memory new since the last look: that one's ranges are made again by the next submit's, and + // it does not stand for this round) + if all { + note_look_began(began, frame); + } + n +} + +fn start_look_ahead() { + let Some(pause) = look_ahead() else { return }; + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + crate::xlog_info!("D3D12.X: XCL_LOOK_AHEAD: a thread takes the written pages every {} ms between the submits", pause.as_millis()); + let _ = std::thread::Builder::new().name("xcl-look-ahead".into()).spawn(move || { + let mut buf: Vec<*mut c_void> = vec![std::ptr::null_mut(); 16384]; + let (mut rounds, mut pages, mut us, mut longest) = (0u64, 0u64, 0u64, 0u64); + loop { + std::thread::sleep(pause); + if now_us().saturating_sub(LAST_SUBMIT.load(Ordering::Relaxed)) > 200_000 { + continue; + } + let t = std::time::Instant::now(); + let n = unsafe { take_round(&mut buf) }; + let took = t.elapsed().as_micros() as u64; + (rounds, pages, us, longest) = (rounds + 1, pages + n as u64, us + took, longest.max(took)); + if rounds % 4096 == 0 { + crate::xlog_info!( + "D3D12.X: {rounds} rounds ahead of the submits so far; the last 4096: {} pages and {:.2} ms each on average, the longest {:.1} ms", + pages / 4096, + us as f64 / 4096e3, + longest as f64 / 1e3 + ); + (pages, us, longest) = (0, 0, 0); + } + } + }); + }); +} + +/// The written pages of the hot blocks inside `ranges` (see `hot_looks`). +unsafe fn take_hot( + ranges: &Arc>, + buf: &mut [*mut c_void], + dirty: &mut Vec, + page: &mut u32, + mut measurement: Option<&mut WatchMeasurement>, +) { + start_walk(ranges); + let now = std::time::Instant::now(); + let (runs, hot_now) = hot_runs(ranges, now); + let first = dirty.len(); + LOOKING.store(true, Ordering::Release); + for &(base, size) in &runs { + take_written(base, size, buf, dirty, page, measurement.as_deref_mut()); + } + LOOKING.store(false, Ordering::Release); + keep_hot(&dirty[first..], now); + let n = HOT_STATS[0].fetch_add(1, Ordering::Relaxed) + 1; + let r = HOT_STATS[1].fetch_add(runs.len() as u64, Ordering::Relaxed) + runs.len() as u64; + let covered: usize = runs.iter().map(|r| r.1).sum(); + let bytes = HOT_STATS[2].fetch_add(covered as u64, Ordering::Relaxed) + covered as u64; + if n.is_power_of_two() && n >= 256 { + let watched: usize = ranges.iter().map(|r| r.1).sum(); + crate::xlog_info!( + "D3D12.X: looks for CPU writes: {n} so far, {} runs and {} MB a look on average ({} MB watched in {} ranges); {hot_now} blocks hot now, {} made hot by the walk", + r / n, + (bytes / n) >> 20, + watched >> 20, + ranges.len(), + HOT_STATS[3].load(Ordering::Relaxed) + ); + } +} + +fn start_walk(ranges: &Arc>) { + { + let mut g = WALK_RANGES.lock().unwrap(); + if !g.as_ref().is_some_and(|r| Arc::ptr_eq(r, ranges)) { + *g = Some(Arc::clone(ranges)); + } + } + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let _ = std::thread::Builder::new().name("xcl-watch-walk".into()).spawn(|| unsafe { walk() }); + crate::xlog_info!( + "D3D12.X: a look for CPU writes takes the blocks written in the last {} ms; a thread walks the rest (XCL_WATCH_HOT=0: every look walks everything)", + hot_for().as_millis() + ); + }); +} + +/// The walk: all watched memory in steps of 64 MiB, without taking the written pages (they stay +/// reported until a look takes them); a block with a written page is hot from then on. +unsafe fn walk() { + const STEP: usize = 32 << 20; + let mut buf: Vec<*mut c_void> = vec![std::ptr::null_mut(); 8192]; + let mut found: Vec = Vec::new(); + loop { + let ranges = WALK_RANGES.lock().unwrap().clone(); + let Some(ranges) = ranges else { + std::thread::sleep(std::time::Duration::from_millis(5)); + continue; + }; + // (`XCL_LOOK_STATS=2`: how long a pass takes – how long a write to a block no look takes + // may wait to be found) + let pass = super::look_stats::deep().then(std::time::Instant::now); + for &(base, size) in ranges.iter() { + let end = base + size; + let mut at = base; + while at < end { + let stop = (at + STEP).min(end); + let mut from = at; + while LOOKING.load(Ordering::Acquire) { + std::thread::yield_now(); + } + while from < stop { + let (mut n, mut page) = (buf.len(), 0u32); + if GetWriteWatch(0, from as *const c_void, stop - from, buf.as_mut_ptr(), &mut n, &mut page) != 0 || n == 0 { + break; + } + let mut last = usize::MAX; + for &p in &buf[..n] { + let b = p as usize & !(HOT_BLOCK - 1); + if b != last { + found.push(b); + last = b; + } + } + if n < buf.len() { + break; + } + // go on after the block of the last page reported + from = (buf[n - 1] as usize & !(HOT_BLOCK - 1)) + HOT_BLOCK; + } + if !found.is_empty() { + let now = std::time::Instant::now(); + let mut g = HOT.lock().unwrap(); + let h = g.get_or_insert_with(HotBlocks::default); + for b in found.drain(..) { + if let std::collections::btree_map::Entry::Vacant(v) = h.hot.entry(b) { + v.insert(now); + HOT_STATS[3].fetch_add(1, Ordering::Relaxed); + WALK_FOUND.fetch_max(now_us(), Ordering::Release); + } + } + } + at = stop; + } + } + if let Some(pass) = pass { + super::look_stats::walk_pass(pass.elapsed()); + } + // a pass takes the process's memory lock some hundred times (a call each); the pause keeps + // the thread from holding up the title's own calls + std::thread::sleep(std::time::Duration::from_millis(15)); + } +} + +/// Ranges of the title's memory XCL wrote itself (DirectStorage data) since the last look: a +/// title's loads write gigabytes that way, and the write watch would find the pages one look after +/// the other (each block of them stayed hot for `hot_for`, and every look walked it). +static KNOWN: Mutex> = Mutex::new(Vec::new()); + +/// `XCL_DS_KNOWN_WRITES=0`: what DirectStorage writes is found by the write watch, as before. +fn known_writes() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_DS_KNOWN_WRITES").map_or(true, |v| v.trim() != "0")) +} + +/// XCL wrote `[at, at + len)` of the title's memory itself (DirectStorage data). Called once the +/// bytes are there and before the title can learn of it. The write watch is cleared for the pages +/// inside the range (written whole by this, and by nobody else while the request ran); the pages +/// at its ends stay in it, for a neighbour's writes. +pub fn note_known_write(at: usize, len: usize) { + if len == 0 || !known_writes() || crate::gpu::uma::get().is_none() { + return; + } + let (lo, hi) = ((at + 0xFFF) & !0xFFF, (at + len) & !0xFFF); + if hi > lo { + // (not write-watched memory: nothing to clear) + unsafe { ResetWriteWatch(lo as *const c_void, hi - lo) }; + } + KNOWN.lock().unwrap().push((at, len)); +} + +#[cfg(test)] +pub(super) fn known_in(at: usize, len: usize) -> Vec<(usize, usize)> { + KNOWN.lock().unwrap().iter().copied().filter(|r| r.0 >= at && r.0 < at + len).collect() +} + +#[cfg(test)] +pub(super) fn forget_known_in(at: usize, len: usize) { + KNOWN.lock().unwrap().retain(|r| r.0 < at || r.0 >= at + len); +} + +/// The pages of the known writes, added to `dirty`. +fn take_known(dirty: &mut Vec) { + let ranges = std::mem::take(&mut *KNOWN.lock().unwrap()); + for (at, len) in ranges { + let mut p = at & !0xFFF; + while p < at + len { + dirty.push(p); + p += 0x1000; + } + } +} + +/// Memory the title just committed or placed something in: the looks take its blocks for a +/// while, as they do a block new to the ranges (a write made right after the commit is there +/// for the next submit). +pub(super) fn mark_hot(at: usize, len: usize) { + if len == 0 || !hot_looks() { + return; + } + let mut g = HOT.lock().unwrap_or_else(|e| e.into_inner()); + // (nothing looked yet: blocks new to the ranges start hot) + let Some(h) = g.as_mut() else { return }; + let now = std::time::Instant::now(); + let mut b = at & !(HOT_BLOCK - 1); + while b < at + len { + h.hot.insert(b, now); + b += HOT_BLOCK; + } +} + +/// Diagnostic: where the written pages of the looks are, in 64 MiB pieces. The 12 with the most +/// pages are logged every 4096 looks, each with its UMA window and that window's kind. +fn note_dirty_regions(u: &crate::gpu::uma::Uma) { + static COUNTS: Mutex>> = Mutex::new(None); + static LOOKS: AtomicU64 = AtomicU64::new(0); + const PIECE: usize = 64 << 20; + DIRTY_BUF.with(|d| { + let d = d.borrow(); + if d.is_empty() { + return; + } + let mut g = COUNTS.lock().unwrap(); + let m = g.get_or_insert_with(Default::default); + let (mut last, mut n) = (usize::MAX, 0u64); + for &p in d.iter() { + let b = p & !(PIECE - 1); + if b != last { + if n != 0 { + *m.entry(last).or_insert(0) += n; + } + last = b; + n = 0; + } + n += 1; + } + if n != 0 { + *m.entry(last).or_insert(0) += n; + } + }); + let looks = LOOKS.fetch_add(1, Ordering::Relaxed) + 1; + if looks % 2048 == 0 { + let mut g = COUNTS.lock().unwrap(); + if let Some(m) = g.as_mut() { + let total: u64 = m.values().sum(); + let mut v: Vec<(usize, u64)> = m.iter().map(|(&a, &c)| (a, c)).collect(); + v.sort_by(|a, b| b.1.cmp(&a.1)); + let top: Vec = v + .iter() + .take(12) + .map(|&(a, c)| { + let w = u.window_of(a); + let kind = match w { + Some(k) if u.is_committed_window(k) => "committed", + Some(k) if u.is_view_window(k) => "GPU view", + Some(_) => "sparse", + None => "outside", + }; + format!("{a:#x} ({kind}{}): {} %", w.map_or(String::new(), |k| format!(" window {k}")), c * 100 / total.max(1)) + }) + .collect(); + crate::xlog_info!("D3D12.X: written pages of the last 2048 looks by 64 MiB piece ({total} pages in {} pieces): {}", v.len(), top.join(", ")); + m.clear(); + } + } +} + +/// `refresh_parts`, then the title's queue waits for XCL's own uploads it has not waited for. +/// `look`: take the pages written since the last look (not with `XCL_LOOK_SKIP`'s skipped ones); +/// `sample`: the look's counters (`memory_report`). +unsafe fn refresh_once(queue: *mut c_void, look: bool, sample: Option<&mut super::sparse::LookSample>) -> super::sparse::PreparationOutcome { + let outcome = refresh_parts(queue, look, sample); + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { + wait_for_own_uploads(q); + } + outcome +} + +unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut super::sparse::LookSample>) -> super::sparse::PreparationOutcome { let Some(u) = crate::gpu::uma::get() else { return super::sparse::PreparationOutcome::Ready }; let sparse = u.has_sparse(); if !sparse && CPU_TEXTURES_LEN.load(Ordering::Relaxed) == 0 { return super::sparse::PreparationOutcome::Ready; } + let t_recheck = std::time::Instant::now(); recheck_gpu_view_sources(); + retry_failed(); + super::file_reads::take_finished(); + super::submit_cost::recheck(t_recheck.elapsed()); let mut page = 0x1000u32; - let ranges = cached_watch_ranges(u, look.is_some()); - let watch_t0 = look.is_some().then(std::time::Instant::now); - let mut measurement = look.is_some().then(WatchMeasurement::default); + let t_ranges = std::time::Instant::now(); + LAST_SUBMIT.store(now_us(), Ordering::Relaxed); + // (frame before `began`, and both before ranges: memory new after that is not in this look) + let frame = super::present::activity().0; + let began = now_us(); + let ranges = cached_watch_ranges(u, sample.is_some()); + // (also of a submit without a look: memory that is new is walked from now on) + if hot_looks() { + start_walk(&ranges); + } + super::submit_cost::ranges(t_ranges.elapsed()); + let watch_t0 = std::time::Instant::now(); + let mut ahead = 0usize; + let mut measurement = sample.is_some().then(WatchMeasurement::default); let dirty_len = DIRTY_BUF.with(|dcell| { let mut dirty = dcell.borrow_mut(); dirty.clear(); + // (with a look of its own: what the thread's piece in progress finds is there first) + let _one = look.then(|| ONE_LOOK.lock().unwrap_or_else(|e| e.into_inner())); + // (a submit without a look of its own takes these too: they are dirty by XCL's account) + take_known(&mut dirty); + { + let mut found = AHEAD.lock().unwrap(); + ahead = found.len(); + dirty.append(&mut found); + } + if !look { + dirty.sort_unstable(); + dirty.dedup(); + return dirty.len(); + } + if super::look_stats::deep() { + // (the walk made a block hot since the look before began: written up to a walk pass + // ago, and only this look takes it) + let before = last_look().0; + super::look_stats::walk_stale(before != 0 && WALK_FOUND.load(Ordering::Acquire) >= before); + super::sparse::note_look(); + } + note_look_began(began, frame); WATCH_BUF.with(|wcell| { let mut buf = wcell.borrow_mut(); if buf.len() < 16384 { buf.resize(16384, std::ptr::null_mut()); } - for &(base, size) in &ranges.ranges { - take_written(base, size, &mut buf, &mut dirty, &mut page, measurement.as_mut()); + if hot_looks() { + start_look_ahead(); + take_hot(&ranges, &mut buf, &mut dirty, &mut page, measurement.as_mut()); + } else { + for &(base, size) in ranges.iter() { + take_written(base, size, &mut buf, &mut dirty, &mut page, measurement.as_mut()); + } } }); dirty.sort_unstable(); + dirty.dedup(); dirty.len() }); - if let Some(measurement) = &measurement { - note_watch_measurement(&ranges, measurement); + if look { + super::sparse::note_watch(watch_t0.elapsed(), dirty_len); + note_dirty_regions(u); + DIRTY_BUF.with(|d| super::look_stats::look(&d.borrow(), ahead, watch_t0.elapsed(), CLOSED_AGO.with(|c| c.take()))); + if let Some(measurement) = &measurement { + note_watch_measurement(&ranges, measurement); + } } - if let (Some(sample), Some(watch_t0)) = (look.as_deref_mut(), watch_t0) { - super::sparse::note_watch( + if let Some(sample) = sample.as_deref_mut() { + super::sparse::note_watch_sample( sample, watch_t0.elapsed(), dirty_len, - ranges.ranges.iter().fold(0usize, |bytes, range| bytes.saturating_add(range.1)), - ranges.ranges.len(), + ranges.iter().fold(0usize, |bytes, range| bytes.saturating_add(range.1)), + ranges.len(), ); } if super::present::trace_frame() { @@ -1041,9 +2013,18 @@ unsafe fn refresh_once(queue: *mut c_void, mut look: Option<&mut super::sparse:: // level 0 last) let content = |e: &Entry| -> usize { let size = e.tex.size() as usize; + // (a texture read through its pages: where they are kept) + let pages = if e.paged { page_map(e.va, size, false) } else { None }; + let mut sample = [0u8; 4096]; (0..16usize) .map(|k| e.src + (size.saturating_sub(4096)) * k / 15) - .map(|a| with_title_bytes(a, 4096, |s| s.iter().filter(|&&b| b != 0).count())) + .map(|a| match &pages { + Some(m) => { + m.copy(a, &mut sample); + sample.iter().filter(|&&b| b != 0).count() + } + None => with_title_bytes(a, 4096, |s| s.iter().filter(|&&b| b != 0).count()), + }) .sum() }; let (mut with, mut without) = (0, 0); @@ -1063,9 +2044,10 @@ unsafe fn refresh_once(queue: *mut c_void, mut look: Option<&mut super::sparse:: if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { let outcome = DIRTY_BUF.with(|dcell| { let dirty = dcell.borrow(); + super::bvh_want::written(&dirty, page as usize); let mut outcome = super::sparse::PreparationOutcome::RetryRequired; for _ in 0..3 { - outcome = super::sparse::before_execute(q, &dirty, page as usize, look.as_deref_mut()); + outcome = super::sparse::before_execute(q, &dirty, page as usize, sample.as_deref_mut()); if outcome != super::sparse::PreparationOutcome::RetryRequired { break; } @@ -1079,58 +2061,110 @@ unsafe fn refresh_once(queue: *mut c_void, mut look: Option<&mut super::sparse:: } super::vram::before_execute(q); } + // a write where a page the queue's page mappings show is kept is a write to the GPU-view pages + // that show it: the textures read through their pages find it by their own range (sparse had + // the real addresses above) + let dirty_len = if crate::hle::kernelx::mirrors::any_mapped() { + DIRTY_BUF.with(|dcell| { + let mut dirty = dcell.borrow_mut(); + TWINS_BUF.with(|tcell| { + let mut twins = tcell.borrow_mut(); + twins.clear(); + crate::hle::kernelx::mirrors::views_of_written(&dirty, &mut twins); + dirty.extend_from_slice(&twins); + }); + dirty.sort_unstable(); + dirty.dedup(); + dirty.len() + }) + } else { + dirty_len + }; let recheck_frame = { let (p, b) = super::present::counters(); p.max(b) }; - recheck_streamed_unwatched(&ranges.ranges, recheck_frame); - if dirty_len == 0 && PENDING.load(Ordering::Relaxed) == 0 { + recheck_streamed_unwatched(&ranges, recheck_frame); + if dirty_len == 0 && PENDING.load(Ordering::Relaxed) == 0 && AGAIN.lock().unwrap().is_empty() { return super::sparse::PreparationOutcome::Ready; } + let target = upload_target(ID3D12CommandQueue::from_raw_borrowed(&queue)); // textures made since the last submit and those with a written page; a reference each // while they are uploaded - let measure_selection = look.is_some(); - let (todo, selection_measurement): (Vec<(ID3D12Resource, Upload)>, _) = DIRTY_BUF.with(|dcell| { + let measure_selection = sample.is_some(); + let (todo, selection_measurement): (Vec, _) = DIRTY_BUF.with(|dcell| { let dirty = dcell.borrow(); let wait_started = measure_selection.then(std::time::Instant::now); let mut t = TEXTURES.lock().unwrap(); let locked_at = wait_started.map(|_| std::time::Instant::now()); let (mut visited, mut dirty_tests, mut matches, mut retained) = (0usize, 0usize, 0usize, 0usize); + let mut names = t.touched_by(&dirty); + names.extend(std::mem::take(&mut t.pending_res)); + let waiting = std::mem::take(&mut *AGAIN.lock().unwrap()); + names.extend(waiting.iter().copied()); + let mut later = std::collections::BTreeSet::new(); let mut todo = Vec::new(); - for (&res, e) in &mut t.by_res { + for res in names { + let Some(e) = t.by_res.get_mut(&res) else { continue }; if measure_selection { visited += 1; } + let mut again = texture_upload::Change::None; + if waiting.contains(&res) && e.cpu_backed && !e.gpu_written { + let (queue, waited) = target.on(e.device); + match texture_upload::take_again(&e.known, queue, waited) { + texture_upload::Again::Now(c) => again = c, + texture_upload::Again::NotYet => drop(later.insert(res)), + texture_upload::Again::Nothing => {} + } + } if measure_selection && e.cpu_backed && !e.pending && !e.gpu_written { dirty_tests += 1; } - let selected = texture_needs_upload( + // (a GPU-owned texture is never uploaded: `texture_needs_upload`) + let wanted = texture_needs_upload( e.cpu_backed, - e.pending, + e.pending || again != texture_upload::Change::None, e.gpu_written, || { let i = dirty.partition_point(|&p| p + page as usize <= e.src); dirty.get(i).is_some_and(|&p| p < e.src + e.tex.size() as usize) }, ); - if !selected { + if !wanted { continue; } if measure_selection { matches += 1; } + let whole = e.pending; if e.pending { e.pending = false; PENDING.fetch_sub(1, Ordering::Relaxed); } let p = res as *mut c_void; + // (its pages resolved once, for all reads of this upload) + let pages = if e.paged { page_map(e.va, e.tex.size() as usize, true) } else { None }; if let Some(r) = ID3D12Resource::from_raw_borrowed(&p) { - todo.push((r.clone(), (e.device, e.src, Arc::clone(&e.tex), e.states.clone(), e.generation))); + todo.push(Due { + res: r.clone(), + device: e.device, + src: e.src, + tex: Arc::clone(&e.tex), + states: e.states.clone(), + known: Arc::clone(&e.known), + whole, + again, + target: e.target, + pages, + generation: e.generation, + }); if measure_selection { retained += 1; } } } + AGAIN.lock().unwrap().extend(later); drop(t); let finished_at = locked_at.map(|_| std::time::Instant::now()); let measurement = wait_started.zip(locked_at).zip(finished_at).map(|((started, locked), finished)| { @@ -1138,11 +2172,13 @@ unsafe fn refresh_once(queue: *mut c_void, mut look: Option<&mut super::sparse:: }); (todo, measurement) }); - if let (Some(sample), Some((wait, hold, visited, dirty_tests, matches, retained))) = (look.as_deref_mut(), selection_measurement) { + if let (Some(sample), Some((wait, hold, visited, dirty_tests, matches, retained))) = (sample.as_deref_mut(), selection_measurement) { super::sparse::note_texture_selection(sample, wait, hold, visited, dirty_tests, matches, retained); } - seed_stream_recheck(&todo, &ranges.ranges, recheck_frame); - upload_all(todo, ID3D12CommandQueue::from_raw_borrowed(&queue)); + seed_stream_recheck(&todo, &ranges, recheck_frame); + let t_tex = std::time::Instant::now(); + DIRTY_BUF.with(|dcell| upload_all(todo, &dcell.borrow(), page as usize, ID3D12CommandQueue::from_raw_borrowed(&queue))); + super::submit_cost::textures(t_tex.elapsed()); super::sparse::PreparationOutcome::Ready } @@ -1242,39 +2278,18 @@ impl TextureSelectionBench { } } -/// texture → `content_hash` of its memory at its last upload -static LAST_CONTENT: Mutex> = Mutex::new(BTreeMap::new()); static UNCHANGED: AtomicU64 = AtomicU64::new(0); -/// `XCL_TEXTURE_SKIP_UNCHANGED=0` uploads a texture whenever its pages were written, as before. -fn unchanged_skip() -> bool { +/// `XCL_TEXTURE_PARTS=0`: a texture that changed goes up as a whole. +fn upload_parts() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_TEXTURE_SKIP_UNCHANGED").map_or(true, |v| v.trim() != "0")) + *ON.get_or_init(|| std::env::var("XCL_TEXTURE_PARTS").map_or(true, |v| v.trim() != "0")) } -/// Whether texture `res` was last uploaded from memory with hash `h`; `h` is remembered as its -/// content from here on (the caller uploads it when this is false). -fn same_as_last_upload(res: usize, h: u64) -> bool { - LAST_CONTENT.lock().unwrap().insert(res, h) == Some(h) -} - -/// A 64-bit hash of `b` for "the same bytes as before" (four lanes of multiply-rotate over -/// 8-byte words: gigabytes a second; not for anything adversarial). -fn content_hash(b: &[u8]) -> u64 { - const K: u64 = 0x9E37_79B9_7F4A_7C15; - let mut h = [K, K.rotate_left(17), K.rotate_left(31), K.rotate_left(47)]; - let mut chunks = b.chunks_exact(32); - for c in &mut chunks { - for (k, lane) in h.iter_mut().enumerate() { - let v = u64::from_le_bytes(c[k * 8..k * 8 + 8].try_into().unwrap()); - *lane = (*lane ^ v).wrapping_mul(K).rotate_left(29); - } - } - let mut tail = b.len() as u64; - for (k, &x) in chunks.remainder().iter().enumerate() { - tail = (tail ^ ((x as u64) << (8 * (k % 8)))).wrapping_mul(K).rotate_left(23); - } - h.iter().fold(tail, |a, &l| (a ^ l).wrapping_mul(K).rotate_left(27)) +/// `XCL_TEXTURE_SKIP_UNCHANGED=0` uploads what was written without comparing it. +fn unchanged_skip() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TEXTURE_SKIP_UNCHANGED").map_or(true, |v| v.trim() != "0")) } /// Frame milestones (relative to last upload or detected content change) at which unwatched @@ -1288,7 +2303,9 @@ const STREAM_SAMPLE_SLICE: usize = 16 * 1024; struct StreamRecheck { base_frame: u64, stage: u8, - last_fp: u64, + /// `None`: no whole upload since the entry was made (a partial upload made it), so the PC + /// texture has no known content to compare with and the first milestone queues a whole upload. + last_fp: Option, } static STREAM_RECHECK: Mutex> = Mutex::new(BTreeMap::new()); @@ -1332,6 +2349,7 @@ unsafe fn sample_fingerprint(src: usize, size: usize) -> u64 { if size == 0 { return 0; } + use texture_upload::content_hash; if size <= 3 * STREAM_SAMPLE_SLICE { let buf = read_committed(src, size); return content_hash(&buf); @@ -1349,26 +2367,42 @@ unsafe fn sample_fingerprint(src: usize, size: usize) -> u64 { content_hash(&mix) } -/// Record baseline fingerprints for unwatched textures queued into `todo` so late streaming writes -/// into mapped physical pages are caught at subsequent frame milestones. -unsafe fn seed_stream_recheck(todo: &[(ID3D12Resource, Upload)], watched: &[(usize, usize)], frame: u64) { +/// Record baseline fingerprints for unwatched textures that go up whole in `todo` so late streaming +/// writes into mapped physical pages are caught at subsequent frame milestones. +unsafe fn seed_stream_recheck(todo: &[Due], watched: &[(usize, usize)], frame: u64) { if !stream_recheck_enabled() || todo.is_empty() { return; } let mut seeded = Vec::new(); - for (r, (_, src, tex, _, _)) in todo { - let size = tex.size() as usize; - if size == 0 || range_is_fully_watched(*src, size, watched) { + let mut unsent = Vec::new(); + for d in todo { + let size = d.tex.size() as usize; + // (a texture read through its pages counts as watched: they are found written where they + // are kept, and a fingerprint of the view's own address would read zeros) + if size == 0 || d.pages.is_some() || range_is_fully_watched(d.src, size, watched) { + continue; + } + // A partial upload sends only the written pages it knows of, or nothing when they are + // unchanged, so the PC texture does not hold what its memory holds now: the baseline of + // the last whole upload stays, and so does its schedule (moving the schedule on every + // partial upload would keep a texture written every few frames from reaching a milestone). + // A texture with no entry (retired, pruned, never seeded) gets one without a baseline, so + // its first milestone queues the whole upload that sets one. + if !d.whole { + unsent.push(d.res.as_raw() as usize); continue; } - let fp = sample_fingerprint(*src, size); - seeded.push((r.as_raw() as usize, StreamRecheck { base_frame: frame, stage: 0, last_fp: fp })); + let fp = sample_fingerprint(d.src, size); + seeded.push((d.res.as_raw() as usize, StreamRecheck { base_frame: frame, stage: 0, last_fp: Some(fp) })); } - if !seeded.is_empty() { + if !seeded.is_empty() || !unsent.is_empty() { let mut g = STREAM_RECHECK.lock().unwrap(); for (res, state) in seeded { g.insert(res, state); } + for res in unsent { + g.entry(res).or_insert(StreamRecheck { base_frame: frame, stage: 0, last_fp: None }); + } } } @@ -1386,7 +2420,7 @@ unsafe fn recheck_streamed_unwatched(watched: &[(usize, usize)], frame: u64) { /// Re-fingerprint due unwatched textures at `frame`, re-queuing changed entries and resetting /// their milestone schedule so subsequent higher-resolution mip streams are also caught. unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) { - let due: Vec<(usize, u64)> = { + let due: Vec<(usize, Option)> = { let g = STREAM_RECHECK.lock().unwrap(); if g.is_empty() { return; @@ -1412,7 +2446,7 @@ unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) Some(e) if e.pending => {} Some(e) => { let size = e.tex.size() as usize; - if range_is_fully_watched(e.src, size, watched) { + if e.paged || range_is_fully_watched(e.src, size, watched) { prune.push(res); } else { check.push((res, e.src, size, prev_fp)); @@ -1436,7 +2470,7 @@ unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) return; } - let results: Vec<(usize, u64, u64)> = check + let results: Vec<(usize, Option, u64)> = check .into_iter() .map(|(res, src, size, prev_fp)| (res, prev_fp, sample_fingerprint(src, size))) .collect(); @@ -1448,8 +2482,9 @@ unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) let Some(st) = g.get_mut(&res) else { continue; }; - if cur_fp != prev_fp { - *st = StreamRecheck { base_frame: frame, stage: 0, last_fp: cur_fp }; + // (an entry without a baseline is always queued) + if prev_fp != Some(cur_fp) { + *st = StreamRecheck { base_frame: frame, stage: 0, last_fp: Some(cur_fp) }; changed.push(res); } else { st.stage = st.stage.saturating_add(1); @@ -1468,6 +2503,8 @@ unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) if !e.gpu_written && !e.pending { e.pending = true; PENDING.fetch_add(1, Ordering::Relaxed); + // (a submit takes the pending ones from this set, not from every texture) + t.pending_res.insert(res); queued += 1; } } @@ -1482,10 +2519,9 @@ unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) } } -/// staging bytes and texture count of one batch at most: bounds the persistent upload staging -/// buffer (`gpu::texture::upload_batch` rounds it up to a power of two and keeps the peak size) -/// and keeps each GPU copy list short enough to avoid WDDM 2 s TDR when thousands of small -/// textures stream at once. +/// bytes and textures of one batch at most: a batch's upload buffer is kept at its size, and each GPU +/// copy list stays short enough for the 2 s a driver gives one, when thousands of small textures +/// stream at once const BATCH_BYTES: usize = 32 << 20; const BATCH_ITEMS: usize = 256; @@ -1502,7 +2538,7 @@ fn batch_fits(picked_count: usize, picked_bytes: usize, batch_dev: usize, next_d struct QueueUploads { fence: ID3D12Fence, value: u64, - in_flight: std::collections::VecDeque<(u64, texture::InFlight)>, + in_flight: std::collections::VecDeque<(u64, texture_upload::Job)>, bytes: u64, } @@ -1524,13 +2560,27 @@ fn queue_upload_state(key: usize) -> QueueUploadState { ) } -/// Drop completed uploads cached for a retired title queue after releasing the cache lock. +/// Drop completed uploads cached for a retired title queue after releasing the cache lock, and +/// what it waited for of XCL's own uploads (a queue made later at the same address has waited for +/// none of them). pub(super) fn forget_queue(id: super::present::QueueId) { - let gone = ON_QUEUE.lock().unwrap().remove(&id.raw()); + let raw = id.raw(); + let gone = ON_QUEUE.lock().unwrap().remove(&raw); drop(gone); + OWN_WAITED.lock().unwrap().remove(&raw); + let known: Vec = { + let t = TEXTURES.lock().unwrap(); + t.by_res.values().chain(t.shadowed.values()).map(|e| Arc::clone(&e.known)).collect() + }; + for k in &known { + texture_upload::forget_queue(k, raw); + } } +/// upload buffers the GPU has not read yet, before a submit waits for it: a moment past the first, +/// in earnest past the second (a title's queue can stand at a wait that another submit ends) const IN_FLIGHT_BYTES: u64 = 512 << 20; +const IN_FLIGHT_MAX: u64 = 2 << 30; unsafe fn title_queue_for(dev: &ID3D12Device, title: Option<&ID3D12CommandQueue>) -> Option { let q = title?; @@ -1545,86 +2595,161 @@ unsafe fn title_queue_for(dev: &ID3D12Device, title: Option<&ID3D12CommandQueue> (qd?.as_raw() == dev.as_raw()).then(|| q.clone()) } -unsafe fn reclaim(dev: &ID3D12Device, q: &mut QueueUploads, cap: u64, wait_ms: u32) -> Vec { +/// The uploads of `q` the GPU is done with, oldest first, and, while more than `cap` bytes are in +/// flight, the older ones as it gets done with them, for up to `wait_ms`. The caller gives them +/// back (`texture_upload::give_back`) once it no longer holds the queue's state. +unsafe fn reclaim(q: &mut QueueUploads, cap: u64, wait_ms: u64) -> Vec { let mut retired = Vec::new(); - let done = q.fence.GetCompletedValue(); - while q.in_flight.front().is_some_and(|&(v, _)| v <= done) { - let (_, f) = q.in_flight.pop_front().unwrap(); - q.bytes -= f.bytes; - retired.push(f); - } - while q.bytes > cap { - let Some(&(v, _)) = q.in_flight.front() else { break }; - if crate::gpu::fence::wait(&q.fence, v, dev, None, wait_ms).is_err() { - break; + let start = std::time::Instant::now(); + while let Some(&(v, _)) = q.in_flight.front() { + if super::real::fence_completed(&q.fence) < v { + if q.bytes <= cap || start.elapsed().as_millis() as u64 >= wait_ms { + break; + } + // (no event: a wait that gives up would leave its registration behind) + std::thread::sleep(std::time::Duration::from_micros(500)); + continue; } - let (_, f) = q.in_flight.pop_front().unwrap(); - q.bytes -= f.bytes; - retired.push(f); + let Some((_, job)) = q.in_flight.pop_front() else { break }; + q.bytes -= job.bytes; + retired.push(job); } retired } -unsafe fn submit_on_title_queue( - dev: &ID3D12Device, - queue: &ID3D12CommandQueue, - batch: &[texture::UploadBatchItem], - zero_mips: &[Vec], -) -> Result, String> { - // The textures' tile mappings made since the title queue last waited for them (a texture - // made on another thread after `refresh_once`'s wait, or its levels mapped just now by +/// The queue a submit's uploads go to, by device, and the one it waits for first. +struct Target { + /// the title's queue, when they go to it + title: Option<(usize, usize)>, +} + +impl Target { + /// (the queue, the one it has waited for) of uploads for `device`; 0: none. + fn on(&self, device: usize) -> (usize, usize) { + let own = QUEUES.lock().unwrap().get(&device).map_or(0, |q| q.as_raw() as usize); + match self.title { + Some((q, d)) if d == device => (q, own), + _ => (own, 0), + } + } +} + +unsafe fn upload_target(title: Option<&ID3D12CommandQueue>) -> Target { + let of = |q: &ID3D12CommandQueue| { + if q.GetDesc().Type != D3D12_COMMAND_LIST_TYPE_DIRECT { + return None; + } + let mut dev: Option = None; + q.GetDevice(&mut dev).ok()?; + Some((q.as_raw() as usize, dev?.as_raw() as usize)) + }; + Target { title: title.and_then(of) } +} + +/// textures with something to send again (`texture_upload::sent`) +static AGAIN: Mutex> = Mutex::new(std::collections::BTreeSet::new()); + +/// Upload `items` on `queue`, a DIRECT one: the ones that could not be, the bytes of the others and +/// where they went (None: there were none). +unsafe fn submit_on(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[texture_upload::Item]) -> Result<(Vec<(usize, String)>, u64, Option), String> { + // The textures' tile mappings made since the queue last waited for them (a texture made on + // another thread after `refresh_once`'s wait, or its levels mapped just now by // `map_levels_with_texels`): a copy into a tile still unmapped is a copy-engine page fault - // on NVIDIA (`DmaPageFaultWrite`), as the upload queue's own path already waits for. + // on NVIDIA (`DmaPageFaultWrite`). super::vram::before_execute(queue); - let (failed, f) = texture::submit_batch_with_zero_mips(dev, queue, batch, zero_mips)?; - let Some(f) = f else { return Ok(failed) }; let key = queue.as_raw() as usize; let state = queue_upload_state(key); let mut slot = state.lock().unwrap(); if slot.is_none() { - match dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) { - Ok(fence) => { - *slot = Some(QueueUploads { fence, value: 0, in_flight: std::collections::VecDeque::new(), bytes: 0 }); - } - Err(e) => { - drop(slot); - texture::drop_after_wait(f, texture::wait(dev, queue))?; - return Err(e.to_string()); - } - } - } - let q = slot.as_mut().unwrap(); - q.value += 1; - if let Err(e) = super::real::native_queue_signal(queue, &q.fence, q.value) { - q.value -= 1; + // (before anything runs that it would have to follow) + let fence = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE).map_err(|e| e.to_string())?; + *slot = Some(QueueUploads { fence, value: 0, in_flight: std::collections::VecDeque::new(), bytes: 0 }); + } + let Some(q) = slot.as_mut() else { return Err("no fence for the queue".into()) }; + // (a piece that panicked on the way into the upload buffer: the batch fails before anything + // is executed and is tried again, `RETRY`, rather than going up with what the buffer held) + let submitted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| texture_upload::submit(dev, queue, items))); + let (failed, f, bytes) = submitted.map_err(|_| "texture upload: filling the upload buffer panicked".to_string())??; + let Some(f) = f else { return Ok((failed, 0, None)) }; + // (through the PC queue slot: a title's queue may have the console's layout) + if let Err(e) = super::real::native_queue_signal(queue, &q.fence, q.value + 1) { drop(slot); - texture::drop_after_wait(f, texture::wait(dev, queue))?; + // the GPU may still run the list and read the buffer: they stay when it does not get there + match texture::wait(dev, queue) { + Ok(()) => drop(f), + Err(_) => std::mem::forget(f), + } return Err(e.to_string()); } + q.value += 1; q.bytes += f.bytes; - let v = q.value; - q.in_flight.push_back((v, f)); - let retired = reclaim(dev, q, IN_FLIGHT_BYTES, 10_000); + let sent = texture_upload::Sent { queue: key, fence: q.fence.clone(), value: q.value }; + q.in_flight.push_back((sent.value, f)); + let mut retired = reclaim(q, IN_FLIGHT_BYTES, 20); + retired.extend(reclaim(q, IN_FLIGHT_MAX, 10_000)); drop(slot); - drop(retired); - Ok(failed) + retired.into_iter().for_each(texture_upload::give_back); + Ok((failed, bytes, Some(sent))) } -/// A preparation worker failed before this exact batch could be submitted. A texture still at the -/// captured registration generation is made pending again; a replacement, removal, GPU writer, or -/// non-CPU-backed entry owns its own state and must not be changed by the stale work item. -fn requeue_failed_preparation(picked: &[(ID3D12Resource, usize, Arc, Vec, u64)]) { - let keys: Vec<_> = picked.iter().map(|(resource, _, _, _, generation)| (resource.as_raw() as usize, *generation)).collect(); - let mut table = TEXTURES.lock().unwrap(); - let added = requeue_generations(&mut table, &keys); - if !added.is_empty() { - PENDING.fetch_add(added.len(), Ordering::Relaxed); +/// The uploads on XCL's own queue (its fence, the last value): each of the title's queues waits for +/// them before its next lists (on the GPU; that queue waits for nothing of the title's). +static OWN_UPLOADS: Mutex> = Mutex::new(None); +/// title queue → the value it waited for last +static OWN_WAITED: Mutex> = Mutex::new(BTreeMap::new()); + +unsafe fn wait_for_own_uploads(queue: &ID3D12CommandQueue) { + let Some((fence, v)) = OWN_UPLOADS.lock().unwrap().clone() else { return }; + let key = queue.as_raw() as usize; + let mut g = OWN_WAITED.lock().unwrap(); + if g.get(&key).is_some_and(|&w| w >= v) { + return; } - drop(table); - let mut content = LAST_CONTENT.lock().unwrap(); - for resource in added { content.remove(&resource); } + // (through the PC queue slot: a title's queue may have the console's layout) + if super::real::fence_completed(&fence) < v && super::real::native_queue_wait(queue, &fence, v).is_ok() { + super::list_x::note_internal_wait(key, "texture uploads", &fence, v); + } + g.insert(key, v); } +/// The pages `[src, src + size)` lies on that were written since the look that took them last; they +/// stay reported. None for memory that is not watched. +unsafe fn written_pages(src: usize, size: usize) -> Vec { + const PAGE: usize = 0x1000; + let (mut at, end) = (src / PAGE * PAGE, (src + size).next_multiple_of(PAGE)); + let mut out = Vec::new(); + let mut buf = [std::ptr::null_mut::(); 512]; + // (the walk stays out of the way, as in a look) + let was = LOOKING.swap(true, Ordering::AcqRel); + while at < end { + let (mut n, mut page) = (buf.len(), PAGE as u32); + if GetWriteWatch(0, at as *const c_void, end - at, buf.as_mut_ptr(), &mut n, &mut page) != 0 { + break; + } + out.extend(buf[..n].iter().map(|&p| p as usize)); + if n < buf.len() { + break; + } + at = buf[n - 1] as usize + PAGE; + } + LOOKING.store(was, Ordering::Release); + out +} + +/// Whether the looks take every block `[src, src + size)` lies in. +fn all_hot(src: usize, size: usize) -> bool { + if !hot_looks() { + return true; + } + let g = HOT.lock().unwrap(); + let Some(h) = g.as_ref() else { return false }; + (src & !(HOT_BLOCK - 1)..src + size).step_by(HOT_BLOCK).all(|b| h.hot.contains_key(&b)) +} + +/// The textures of failed batches whose time came (`retry_failed`), as (texture, registration +/// generation): one still at that generation, CPU-backed, not written by the GPU and not pending is +/// made pending again (a whole upload); a replacement, removal, GPU writer or non-CPU-backed entry +/// owns its own state and is left alone. Returns the textures made pending. fn requeue_generations(table: &mut Table, keys: &[(usize, u64)]) -> Vec { let mut added = Vec::new(); for &(resource, generation) in keys { @@ -1634,116 +2759,220 @@ fn requeue_generations(table: &mut Table, keys: &[(usize, u64)]) -> Vec { added.push(resource); } } + for &resource in &added { + table.pending_res.insert(resource); + } added } -/// The uploads `todo`, in batches of up to `BATCH_BYTES` and `BATCH_ITEMS` (one list and one wait each). -unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>, title: Option<&ID3D12CommandQueue>) { +/// What changed of the textures `todo` (written pages: `dirty`, sorted) goes up, in batches of up to +/// `BATCH_BYTES` and `BATCH_ITEMS` (one list each). +unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option<&ID3D12CommandQueue>) { static N: AtomicU64 = AtomicU64::new(0); let warn = |e: &str| { if N.fetch_add(1, Ordering::Relaxed) < 4 { crate::xlog_warn!("title texture: upload failed: {e}"); } }; - let mut todo = todo.into_iter().peekable(); + // The written pages that hold what they held at their texture's last upload are nothing to do: + // the write watch is per page and a title writes next to its textures (and rewrites what it + // wrote). + let t = std::time::Instant::now(); + let mut changes: std::collections::VecDeque = { + let pages: Vec> = todo + .iter() + .filter(|d| !d.whole) + .map(|d| { + let size = d.tex.size() as usize; + let (from, to) = (dirty.partition_point(|&p| p + page <= d.src), dirty.partition_point(|&p| p < d.src + size)); + let mine = &dirty[from..to.max(from)]; + // (a look takes the blocks written lately: the others' pages of this texture too, or + // it would go up in part as it was and in part as it is; not for one read through + // its pages, whose own address is not watched) + let also = if mine.is_empty() || d.pages.is_some() || all_hot(d.src, size) { Vec::new() } else { written_pages(d.src, size) }; + if also.iter().all(|p| mine.binary_search(p).is_ok()) { + return mine.into(); + } + let mut all = [mine, &also].concat(); + all.sort_unstable(); + all.dedup(); + all.into() + }) + .collect(); + let written: Vec = todo + .iter() + .filter(|d| !d.whole) + .zip(&pages) + .map(|(d, pages)| texture_upload::Written { src: d.src, size: d.tex.size() as usize, dirty: pages, known: &d.known, pages: d.pages.as_deref() }) + .collect(); + let (changes, compared) = texture_upload::changed(&written, unchanged_skip()); + let same = changes.iter().filter(|c| **c == texture_upload::Change::None).count() as u64; + let before = UNCHANGED.fetch_add(same, Ordering::Relaxed); + if same > 0 && (before == 0 || (before >= 512 && before.ilog2() != (before + same).ilog2())) { + crate::xlog_info!("title textures: {} uploads left out so far – the texture's memory held what it held at its last upload", before + same); + } + super::submit_cost::textures_compared(written.len(), same as usize, compared, t.elapsed()); + changes.into() + }; + let mut todo = todo.into_iter().filter_map(|d| { + let change = if d.whole { texture_upload::Change::All } else { changes.pop_front()? }; + let changed = match texture_upload::join(change, d.again.clone()) { + texture_upload::Change::None => return None, + texture_upload::Change::All => None, + texture_upload::Change::Parts(_) if d.target || !upload_parts() => None, + texture_upload::Change::Parts(p) => Some(p), + }; + let size = d.tex.size() as usize; + // (whole blocks go up, and whole volumes) + const BLOCK: usize = 0x1_0000; + let volume = d.tex.texels().is_some_and(|s| s.depth > 0); + let parts = changed.as_ref().filter(|_| !volume); + let bytes = parts.map_or(size, |p| p.iter().map(|r| (r.1.div_ceil(BLOCK) - r.0 / BLOCK) * BLOCK).sum::().min(size)); + Some((d, changed, bytes)) + }).peekable(); while todo.peek().is_some() { - let mut picked = Vec::new(); - let mut bytes = 0usize; - let mut device = 0usize; - while let Some((_, (dev, _, tex, _, _))) = todo.peek() { - if !batch_fits(picked.len(), bytes, device, *dev, tex.size() as usize) { - break; - } - let (r, (dev, va, tex, states, generation)) = todo.next().unwrap(); - // The same bytes as at this texture's last upload: nothing to do. The write watch is - // per page and a title writes next to its textures (and rewrites what it wrote): a - // retail title's video planes and UI targets went up again for every submit, ~25 MB - // a presented frame where ~3 MB had changed, and the submits waited here. - if unchanged_skip() { - let h = with_title_bytes(va, tex.size() as usize, content_hash); - if same_as_last_upload(r.as_raw() as usize, h) { - let n = UNCHANGED.fetch_add(1, Ordering::Relaxed) + 1; - if n == 1 || (n.is_power_of_two() && n >= 1024) { - crate::xlog_info!("title textures: {n} uploads left out so far – the texture's memory held what it held at its last upload"); - } - continue; + let (mut items, mut known): (Vec, Vec) = (Vec::new(), Vec::new()); + let mut generations: Vec = Vec::new(); + let (mut bytes, mut device) = (0usize, 0usize); + while let Some((d, mut changed, n)) = todo.next_if(|(d, _, n)| batch_fits(items.len(), bytes, device, d.device, *n)) { + device = d.device; + bytes += n; + let mut unmapped = false; + if super::vram::level_pages() && super::vram::has_lazy_levels(d.res.as_raw() as usize) { + // (the queue waits for these mappings before the copies: `vram::before_execute` + // below; what a level's fresh pages held is another texture's, so all of it goes up) + if !map_levels_with_texels(&d.res, &subresources_in(d.src, &d.tex, d.pages.as_deref())).is_empty() { + changed = None; } + unmapped = super::vram::has_unmapped_levels(d.res.as_raw() as usize); + } + if unmapped { + // A level left without pages (zeros when looked at above) may get its texels + // before the copy reads them: the copy to its tiles is dropped, and what it read + // must not be kept as what the PC texture holds – the next write then looks the + // same and the level never goes up. The next write sends all of it, and the level + // gets its pages then. + texture_upload::unknown(&d.known); + } else if changed.is_none() { + // (before its bytes are read: what is written from here on is compared) + texture_upload::all_sent(&d.known, d.src, d.tex.size() as usize); } - device = dev; - bytes += tex.size() as usize; - picked.push((r, va, tex, states, generation)); - } - if picked.is_empty() { - continue; - } - let Some(subs) = subresources_of_all(&picked, bytes) else { - requeue_failed_preparation(&picked); - warn("a texture preparation worker stopped; the batch will be retried"); - continue; - }; - let mut batch = Vec::with_capacity(picked.len()); - let mut zero_mips = Vec::new(); - let level_pages = super::vram::level_pages(); - for ((r, va, _, states, _), subs) in picked.into_iter().zip(subs) { if super::present::trace_frame() { - note_content(va, &r, &subs); + note_content(d.src, &d.res, &subresources_in(d.src, &d.tex, d.pages.as_deref())); } - if level_pages { - // (the queue waits for these mappings before the copies: `vram::before_execute` below) - zero_mips.push(map_levels_with_texels(&r, &subs)); + generations.push(d.generation); + items.push(texture_upload::Item { res: d.res, src: d.src, tex: d.tex, states: d.states, changed, known: Some(Arc::clone(&d.known)), pages: d.pages }); + known.push(d.known); + } + let p = device as *mut c_void; + let Some(dev) = ID3D12Device::from_raw_borrowed(&p) else { continue }; + let t_submit = std::time::Instant::now(); + // (`submit_on` waits for the tile mappings made before it: the level pages mapped above too) + let done = own_work(|| match title_queue_for(dev, title) { + Some(q) => { + // what went up on XCL's own queue first: these may be newer bytes of the same texture + wait_for_own_uploads(&q); + submit_on(dev, &q, &items) } - batch.push((r, subs, states)); - } - let d = device as *mut c_void; - let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { continue }; - if let Some(tq) = title_queue_for(dev, title) { - match own_work(|| submit_on_title_queue(dev, &tq, &batch, &zero_mips)) { - Ok(failed) => { - for (_, e) in failed { - warn(&e); + // not from a compute or copy queue: on XCL's own, which the title's queues wait for + None => { + let queue = upload_queue(dev, device)?; + let r = submit_on(dev, &queue, &items)?; + if let Some(s) = &r.2 { + *OWN_UPLOADS.lock().unwrap() = Some((s.fence.clone(), s.value)); + } + Ok(r) + } + }); + // (what did not go up is not what the PC texture holds: as a whole at its next write) + match done { + Ok((failed, bytes, to)) => { + for (k, e) in &failed { + warn(e); + texture_upload::forget(&known[*k]); + } + if let Some(to) = to { + let waited = QUEUES.lock().unwrap().get(&device).map_or(0, |q| q.as_raw() as usize); + for (k, it) in items.iter().enumerate().filter(|(k, _)| !failed.iter().any(|f| f.0 == *k)) { + // (XCL's own queue waits for none of the title's) + if texture_upload::sent(&known[k], it.changed.as_deref(), &to, if to.queue == waited { 0 } else { waited }) { + AGAIN.lock().unwrap().insert(it.res.as_raw() as usize); + } } - UPLOADS.fetch_add(batch.len() as u64, Ordering::Relaxed); } - Err(e) => warn(&e), + UPLOADS.fetch_add((items.len() - failed.len()) as u64, Ordering::Relaxed); + super::submit_cost::textures_uploaded(items.len() - failed.len(), bytes as usize, t_submit.elapsed()); } - continue; - } - let queue = match upload_queue(dev, device) { - Ok(q) => q, Err(e) => { warn(&e); - continue; + known.iter().for_each(texture_upload::forget); + // (no memory for a buffer, most likely: again in a moment) + let at = std::time::Instant::now() + RETRY_AFTER; + RETRY.lock().unwrap().extend(items.iter().zip(&generations).map(|(it, &generation)| (at, it.res.as_raw() as usize, generation))); } - }; - match own_work(|| { - super::vram::before_execute(&queue); - texture::upload_batch_with_zero_mips(dev, &queue, &batch, &zero_mips) - }) { - Ok(failed) => { - for (_, e) in failed { - warn(&e); - } - UPLOADS.fetch_add(batch.len() as u64, Ordering::Relaxed); - } - Err(e) => warn(&e), } } } +/// textures of batches that could not be uploaded, with their registration generation, and when +/// they are tried again +static RETRY: Mutex> = Mutex::new(Vec::new()); +const RETRY_AFTER: std::time::Duration = std::time::Duration::from_millis(100); + +/// Those whose time has come are to be uploaded as a whole, like new ones: each still at the +/// generation it failed at (`requeue_generations`). +fn retry_failed() { + let mut g = RETRY.lock().unwrap(); + if g.is_empty() { + return; + } + let now = std::time::Instant::now(); + let mut due = Vec::new(); + g.retain(|&(at, res, generation)| { + if at > now { + return true; + } + due.push((res, generation)); + false + }); + let added = requeue_generations(&mut TEXTURES.lock().unwrap(), &due); + PENDING.fetch_add(added.len(), Ordering::Relaxed); +} + +/// An upload of `changed` (None: all) of `res`, a texture of the console description `desc` with its +/// bytes in `mem`, on `queue`, waited for: for the test of its barriers under the debug layer. +#[doc(hidden)] +pub unsafe fn upload_and_wait(dev: &ID3D12Device, queue: &ID3D12CommandQueue, res: &ID3D12Resource, desc: &[u8; 0x38], mem: &[u8], states: Vec, changed: Option>) -> Result<(), String> { + let tex = Arc::new(xg::Texture::new(desc).map_err(|hr| format!("layout {hr:#x}"))?); + if mem.len() < tex.size() as usize { + return Err(format!("{} bytes of {}", mem.len(), tex.size())); + } + let item = texture_upload::Item { res: res.clone(), src: mem.as_ptr() as usize, tex, states, changed, known: None, pages: None }; + let (failed, job, _) = own_work(|| texture_upload::submit(dev, queue, &[item]))?; + texture::wait(dev, queue)?; + job.into_iter().for_each(texture_upload::give_back); + failed.into_iter().next().map_or(Ok(()), |(_, e)| Err(e)) +} + /// (`vram::level_pages`) Before an upload of title texture `r`: its levels with texels in `subs` -/// (its subresources as they go up) get their video memory pages if they have none - a texture -/// placed with lazy levels. Return a mask of zero levels so their copies can share staging. -/// A level of zeros needs no new pages. Its copy still clears any existing tiles, including a -/// previously streamed level or tiles mapped for other levels in the same packed tail. -unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) -> Vec { +/// (its subresources as they go up) get their video memory pages if they have none, and those +/// with pages and no texels now give them back (`vram::unmap_levels`) - a texture placed with +/// lazy levels; any other: nothing to do. A level of zeros has no texels: a streamed +/// texture's larger levels before the title has memory behind them (read as zeros, +/// `read_committed`). It keeps no pages, reads as zeros as it would with them, and its copy goes +/// to tiles that are not mapped, which drops it (tiled resources tier 2). Returns the levels that +/// got pages now (`vram::map_levels`). +unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) -> Vec { if !super::vram::has_lazy_levels(r.as_raw() as usize) { return Vec::new(); } // (one slice: its subresources are its levels) - let zero: Vec = subs.iter().map(|s| all_zero(&s.data)).collect(); - let present: Vec = zero.iter().enumerate().filter_map(|(i, &zero)| (!zero).then_some(i as u32)).collect(); - super::vram::map_levels(r, Some(&present)); - zero + let present: Vec = subs.iter().enumerate().filter(|(_, s)| !all_zero(&s.data)).map(|(i, _)| i as u32).collect(); + // a level that had texels and has none now: the title took its memory, and it gives back its + // pages (this upload would only have written zeros to them) + let zero: Vec = (0..subs.len() as u32).filter(|l| !present.contains(l)).collect(); + super::vram::unmap_levels(r, &zero); + super::vram::map_levels(r, Some(&present)) } /// Whether every byte of `b` is zero (eight at a time: gigabytes a second where it is). @@ -1771,27 +3000,30 @@ fn note_content(va: usize, r: &ID3D12Resource, subs: &[texture::Subresource]) { ); } -/// `XCL_TRACE_FRAME`: what the GPU holds in level 0 of title texture `res` (read back on XCL's -/// queue; the texture is taken to be in a shader-resource state) against the CPU's view of the -/// memory now. Each texture once, four at most. +/// `XCL_TRACE_FRAME`: what the GPU holds in each level of the first slice of title texture `res` +/// (read back on XCL's queue; the texture is taken to be in a shader-resource state) against the +/// CPU's view of the memory now. Each texture once, four at most (`XCL_TRACE_PROBES=n`: n). pub unsafe fn probe_gpu_content(res: usize) { static SEEN: Mutex> = Mutex::new(Vec::new()); + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + let most = *MOST.get_or_init(|| std::env::var("XCL_TRACE_PROBES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(4)); { let mut g = SEEN.lock().unwrap(); - if g.contains(&res) || g.len() >= 4 { + if g.contains(&res) || g.len() >= most { return; } g.push(res); } - let Some((device, va, tex, gpu_written)) = TEXTURES.lock().unwrap().by_res.get(&res).map(|e| (e.device, e.src, Arc::clone(&e.tex), e.gpu_written)) else { return }; + let Some((device, va, tex, gpu_written, paged)) = TEXTURES.lock().unwrap().by_res.get(&res).map(|e| (e.device, e.src, Arc::clone(&e.tex), e.gpu_written, e.paged)) else { return }; let d = device as *mut c_void; let r = res as *mut c_void; let (Some(dev), Some(r)) = (ID3D12Device::from_raw_borrowed(&d), ID3D12Resource::from_raw_borrowed(&r)) else { return }; let rd = r.GetDesc(); - let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); - let (mut rows, mut row_bytes, mut total) = (0u32, 0u64, 0u64); - dev.GetCopyableFootprints(&rd, 0, 1, 0, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut total)); - let result = own_work(|| -> Result, String> { + let levels = (rd.MipLevels as usize).clamp(1, 16); + let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); levels]; + let (mut rows, mut row_bytes, mut total) = (vec![0u32; levels], vec![0u64; levels], 0u64); + dev.GetCopyableFootprints(&rd, 0, levels as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), Some(&mut total)); + let result = own_work(|| -> Result>, String> { let queue = upload_queue(dev, device)?; super::vram::before_execute(&queue); let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(|e| e.to_string())?; @@ -1816,46 +3048,60 @@ pub unsafe fn probe_gpu_content(res: usize) { ) .map_err(|e| e.to_string())?; let rb = rb.ok_or("no readback buffer")?; - let barrier = |a: D3D12_RESOURCE_STATES, b: D3D12_RESOURCE_STATES| D3D12_RESOURCE_BARRIER { + let barrier = |sub: u32, a: D3D12_RESOURCE_STATES, b: D3D12_RESOURCE_STATES| D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { - Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(r), Subresource: 0, StateBefore: a, StateAfter: b }), + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(r), Subresource: sub, StateBefore: a, StateAfter: b }), }, }; let srv = D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE; - list.ResourceBarrier(&[barrier(srv, D3D12_RESOURCE_STATE_COPY_SOURCE)]); - let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; - let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; - list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); - list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, srv)]); + for (i, fp) in fps.iter().enumerate() { + list.ResourceBarrier(&[barrier(i as u32, srv, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: i as u32 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.ResourceBarrier(&[barrier(i as u32, D3D12_RESOURCE_STATE_COPY_SOURCE, srv)]); + } list.Close().map_err(|e| e.to_string())?; let list = list.cast().map_err(|e| e.to_string())?; super::real::native_queue_execute(&queue, &list); texture::wait(dev, &queue)?; let mut p: *mut c_void = std::ptr::null_mut(); rb.Map(0, None, Some(&mut p)).map_err(|e| e.to_string())?; - let mut out = Vec::with_capacity(rows as usize * row_bytes as usize); - for y in 0..rows as usize { - out.extend_from_slice(std::slice::from_raw_parts((p as *const u8).add(y * fp.Footprint.RowPitch as usize), row_bytes as usize)); + let mut out = Vec::with_capacity(levels); + for (i, fp) in fps.iter().enumerate() { + let mut level = Vec::with_capacity(rows[i] as usize * row_bytes[i] as usize); + for y in 0..rows[i] as usize { + level.extend_from_slice(std::slice::from_raw_parts((p as *const u8).add(fp.Offset as usize + y * fp.Footprint.RowPitch as usize), row_bytes[i] as usize)); + } + out.push(level); } rb.Unmap(0, None); Ok(out) }); - let cpu = subresources(va, &tex).into_iter().next().map(|s| s.data).unwrap_or_default(); + // (a texture read through its pages: where they are kept, with a table of its own) + let pages = if paged { page_map(va, tex.size() as usize, false) } else { None }; + let cpu = subresources_in(va, &tex, pages.as_deref()); match result { Ok(gpu) => { - let nonzero = gpu.iter().filter(|&&b| b != 0).count(); - let same = gpu.iter().zip(cpu.iter()).filter(|(a, b)| a == b).count(); + let nonzero = |b: &[u8]| b.iter().filter(|&&x| x != 0).count(); + let per: Vec = gpu + .iter() + .enumerate() + .map(|(i, g)| { + let c = cpu.get(i).map_or(&[][..], |s| s.data.as_slice()); + format!("L{i} {} B: GPU {} not zero, CPU {}, {} equal", g.len(), nonzero(g), nonzero(c), g.iter().zip(c.iter()).filter(|(a, b)| a == b).count()) + }) + .collect(); crate::xlog_info!( - "frame trace: GPU content of title texture {res:#x} at {va:#x} ({}x{} format {}, {} mips, GPU-written {gpu_written}): {nonzero} of {} bytes of level 0 not zero; {same} equal to the CPU view ({} of its bytes not zero); first bytes {:02x?}", + "frame trace: GPU content of title texture {res:#x} at {va:#x} ({}x{} format {}, {} mips, GPU-written {gpu_written}): {}; first bytes of level 0 {:02x?}", rd.Width, rd.Height, rd.Format.0, rd.MipLevels, - gpu.len(), - cpu.iter().filter(|&&b| b != 0).count(), - &gpu[..gpu.len().min(16)] + per.join("; "), + gpu.first().map_or(&[][..], |g| &g[..g.len().min(16)]) ); } Err(e) => crate::xlog_warn!("frame trace: GPU content of title texture {res:#x}: {e}"), @@ -2014,16 +3260,27 @@ unsafe fn copy_committed_region(src: usize, dst: *mut u8, len: usize) { copy_rec(GetCurrentProcess(), src, dst, len); } +/// The bytes at `at` into `to` in one read, all zeros when it fails: for memory committed whole +/// or not at all (a physical page where it is kept), with no question to Windows about it. +pub(super) unsafe fn copy_or_zeros(at: usize, to: &mut [u8]) { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut read = 0usize; + if ReadProcessMemory(GetCurrentProcess(), at as *const c_void, to.as_mut_ptr() as *mut c_void, to.len(), &mut read) == 0 || read < to.len() { + to.fill(0); + } +} + /// `len` bytes at `at`: the committed, readable pages copied, the rest zero (a streaming pool /// has only some of its pages mapped). -unsafe fn read_committed(at: usize, len: usize) -> Vec { +pub(super) unsafe fn read_committed(at: usize, len: usize) -> Vec { let mut out = vec![0u8; len]; read_committed_into(at, &mut out); out } /// `read_committed` of `out.len()` bytes at `at` into `out` (every byte of it written). -unsafe fn read_committed_into(at: usize, out: &mut [u8]) { +pub(super) unsafe fn read_committed_into(at: usize, out: &mut [u8]) { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; use windows_sys::Win32::System::Threading::GetCurrentProcess; @@ -2048,7 +3305,9 @@ unsafe fn read_committed_into(at: usize, out: &mut [u8]) { if !crate::util::under_wine() && ReadProcessMemory(GetCurrentProcess(), at as *const c_void, out.as_mut_ptr() as *mut c_void, len, &mut read) != 0 { return; } - // with holes: region by region (a refused `ReadProcessMemory` costs more than the walk) + // with holes: region by region (a refused `ReadProcessMemory` costs more than the walk; a + // retail title makes its textures before it maps their memory: 13.6 GB of them went up at + // 0.5 GB/s while its world loaded when every page was tried on its own) let mut p = at; while p < limit { let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); @@ -2067,129 +3326,7 @@ unsafe fn read_committed_into(at: usize, out: &mut [u8]) { } p = end; } - out[p - at..].fill(0); -} - -/// Batches of at least this many bytes are detiled on several threads (`subresources_of_all`) -const PARALLEL_BYTES: usize = 1 << 20; - -struct DetileJob { - index: usize, - va: usize, - tex: Arc, - done: std::sync::mpsc::Sender<(usize, Option>)>, -} - -struct DetilePool { - jobs: std::sync::mpsc::Sender, - workers: usize, -} - -fn detile_pool() -> &'static DetilePool { - static POOL: std::sync::OnceLock = std::sync::OnceLock::new(); - POOL.get_or_init(|| { - let wanted = std::thread::available_parallelism().map_or(1, |n| n.get() / 2).clamp(1, 8); - let (jobs, receive) = std::sync::mpsc::channel::(); - let receive = Arc::new(Mutex::new(receive)); - let mut workers = 0; - for k in 0..wanted { - let receive = Arc::clone(&receive); - let made = std::thread::Builder::new().name(format!("xcl-detile-{k}")).spawn(move || loop { - let job = { - let receive = receive.lock().unwrap_or_else(|e| e.into_inner()); - receive.recv() - }; - let Ok(job) = job else { break }; - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { - subresources(job.va, &job.tex) - })) - .ok(); - let _ = job.done.send((job.index, result)); - }); - if made.is_ok() { - workers += 1; - } - } - DetilePool { jobs, workers } - }) -} - -/// `subresources` of every texture of a batch (`bytes` of them), in order: on several threads -/// when the batch is big. Process-lifetime workers avoid creating and joining up to eight OS -/// threads in every title submit. None means a worker or its queue stopped; the caller retries the -/// exact registration generation rather than uploading an incomplete texture. -unsafe fn subresources_of_all( - picked: &[(ID3D12Resource, usize, Arc, Vec, u64)], - bytes: usize, -) -> Option>> { - let work: Vec<_> = picked.iter().map(|(_, va, tex, _, _)| (*va, Arc::clone(tex))).collect(); - pooled_subresources(&work, bytes) -} - -unsafe fn pooled_subresources(picked: &[(usize, Arc)], bytes: usize) -> Option>> { - if bytes < PARALLEL_BYTES || picked.len() <= 1 { - return Some(picked.iter().map(|(va, tex)| subresources(*va, tex)).collect()); - } - let pool = detile_pool(); - if pool.workers == 0 { - return None; - } - let (done, results) = std::sync::mpsc::channel(); - for (index, (va, tex)) in picked.iter().enumerate() { - if pool.jobs.send(DetileJob { index, va: *va, tex: Arc::clone(tex), done: done.clone() }).is_err() { - return None; - } - } - drop(done); - ordered_subresources(picked.len(), results) -} - -fn ordered_subresources( - count: usize, - results: impl IntoIterator>)>, -) -> Option>> { - let mut out: Vec>> = (0..count).map(|_| None).collect(); - let mut failed = false; - for (index, result) in results { - match (out.get_mut(index), result) { - (Some(slot), Some(result)) if slot.is_none() => *slot = Some(result), - _ => failed = true, - } - } - (!failed).then(|| out.into_iter().collect()).flatten() -} - -/// `subresources` of each (address, texture), in order, on up to `threads` threads. -#[cfg(test)] -unsafe fn subresources_on(picked: &[(usize, &xg::Texture)], threads: usize) -> Vec> { - let threads = threads.min(picked.len()); - if threads <= 1 { - return picked.iter().map(|&(va, tex)| subresources(va, tex)).collect(); - } - // the next texture to take; each thread hands back (index, subresources) - let next = std::sync::atomic::AtomicUsize::new(0); - let mut out: Vec> = (0..picked.len()).map(|_| Vec::new()).collect(); - let done: Vec)>> = std::thread::scope(|s| { - let workers: Vec<_> = (0..threads) - .map(|_| { - s.spawn(|| { - let mut mine = Vec::new(); - loop { - let k = next.fetch_add(1, Ordering::Relaxed); - let Some(&(va, tex)) = picked.get(k) else { break }; - // SAFETY: as in the serial path – the title's memory is only read - mine.push((k, unsafe { subresources(va, tex) })); - } - mine - }) - }) - .collect(); - workers.into_iter().map(|w| w.join().unwrap_or_default()).collect() - }); - for (k, subs) in done.into_iter().flatten() { - out[k] = subs; - } - out + out[p - at..].fill(0); } thread_local! { @@ -2203,10 +3340,14 @@ thread_local! { const TITLE_BYTES_KEPT: usize = 64 << 20; /// `f` of the title's `len` bytes at `at`: where they are in the coherent window (committed as a -/// whole, never decommitted), else as `read_committed` reads them, into a buffer reused on this -/// thread – the title can decommit its other memory from another thread at any moment, and a -/// read in place then faults. -unsafe fn with_title_bytes(at: usize, len: usize, f: impl FnOnce(&[u8]) -> R) -> R { +/// whole, never decommitted), by the GPU's copy in a GPU_UPLOAD segment of a mixed driver window +/// (CPU reads of that video memory through the BAR are slow), else as `read_committed` reads +/// them, into a buffer reused on this thread – the title can decommit its other memory from +/// another thread at any moment, and a read in place then faults. +pub(super) unsafe fn with_title_bytes(at: usize, len: usize, f: impl FnOnce(&[u8]) -> R) -> R { + if let Some(bytes) = super::uma_driver::read_vram_bytes(at, len) { + return f(&bytes); + } if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)) { return f(std::slice::from_raw_parts(at as *const u8, len)); } @@ -2229,16 +3370,23 @@ unsafe fn with_title_bytes(at: usize, len: usize, f: impl FnOnce(&[u8]) -> R) } /// Every subresource (D3D12 order) of a texture from the title's memory at `va`. -unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { +#[cfg(test)] +pub(super) unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { + subresources_in(va, tex, None) +} + +/// Every subresource (D3D12 order) of a texture from the title's memory at `va`, read through +/// `pages` when it has a table of them. +unsafe fn subresources_in(va: usize, tex: &xg::Texture, pages: Option<&texture_upload::PageMap>) -> Vec { let Some(tex) = tex.texels() else { return Vec::new() }; let c = &tex.chain; let bpe = tex.bpe as usize; if tex.depth > 0 { - return with_title_bytes(va, tex.size() as usize, |mem| c.levels.iter().enumerate().map(|(i, l)| Subresource { depth: l.depth, rows: l.height, row_bytes: l.width * bpe, data: c.detile_volume(mem, i) }).collect()); + return texture_upload::read(pages, va, tex.size() as usize, |mem| c.levels.iter().enumerate().map(|(i, l)| Subresource { depth: l.depth, rows: l.height, row_bytes: l.width * bpe, data: c.detile_volume(mem, i) }).collect()); } let mut out = Vec::with_capacity(tex.array as usize * c.levels.len()); for s in 0..tex.array as usize { - with_title_bytes(va + s * c.slice_bytes, c.slice_bytes, |slice| { + texture_upload::read(pages, va + s * c.slice_bytes, c.slice_bytes, |slice| { for (i, l) in c.levels.iter().enumerate() { out.push(Subresource { depth: 1, rows: l.height, row_bytes: l.width * bpe, data: c.detile_level(slice, i, s) }); } @@ -3067,54 +4215,14 @@ pub(super) unsafe fn prepare_texture_download( #[cfg(test)] -mod tests { +pub(super) mod tests { use super::*; - struct DirectQueueUploads(usize); - - impl DirectQueueUploads { - fn new(queue: &ID3D12CommandQueue) -> Self { - let key = queue.as_raw() as usize; - let stale = ON_QUEUE.lock().unwrap().remove(&key); - drop(stale); - Self(key) - } - } - - impl Drop for DirectQueueUploads { - fn drop(&mut self) { - let state = ON_QUEUE.lock().unwrap().remove(&self.0); - drop(state); - } - } - - /// A texture is left out only when its memory hashes as at its own last upload, and a - /// texture that was forgotten (released, or its address registered again) is uploaded again. - #[test] - fn a_texture_with_unchanged_memory_is_left_out_until_it_is_forgotten() { - let (a, b) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize); - let mut mem = vec![0u8; 3 << 20]; - mem[5] = 1; - let h = content_hash(&mem); - assert!(!same_as_last_upload(a, h), "the first upload is not left out"); - assert!(same_as_last_upload(a, h), "the same bytes again: left out"); - assert!(!same_as_last_upload(b, h), "another texture over the same bytes has its own first upload"); - // one byte anywhere, also in the tail that is not a whole 32-byte step - for at in [0usize, 31, 32, (3 << 20) - 1] { - let mut m = mem.clone(); - m[at] ^= 0x80; - assert_ne!(content_hash(&m), h, "byte {at} changed"); - } - mem[(3 << 20) - 1] = 9; - let h2 = content_hash(&mem); - assert!(!same_as_last_upload(a, h2), "changed memory is uploaded"); - assert!(same_as_last_upload(a, h2)); - // the length is part of the content: a prefix of zeros is not the whole - assert_ne!(content_hash(&[0u8; 64]), content_hash(&[0u8; 96])); - forget(a); - assert!(!same_as_last_upload(a, h2), "forgotten: its next upload is a first one"); - forget(a); - forget(b); + /// A 64x64 R8 texture's upload from memory full of `value`, with that memory. + fn r8_item(texture: &ID3D12Resource, value: u8) -> (texture_upload::Item, Vec) { + let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 61, 1)).unwrap()); + let mem = vec![value; tex.size() as usize]; + (texture_upload::Item { res: texture.clone(), src: mem.as_ptr() as usize, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], changed: None, known: None, pages: None }, mem) } unsafe fn read_r8(dev: &ID3D12Device, queue: &ID3D12CommandQueue, texture: &ID3D12Resource) -> Vec { @@ -3157,6 +4265,26 @@ mod tests { }) } + /// The title queue's upload state for a test: none left by an earlier queue at the same address, + /// and none left behind. + struct DirectQueueUploads(usize); + + impl DirectQueueUploads { + fn new(queue: &ID3D12CommandQueue) -> Self { + let key = queue.as_raw() as usize; + let stale = ON_QUEUE.lock().unwrap().remove(&key); + drop(stale); + Self(key) + } + } + + impl Drop for DirectQueueUploads { + fn drop(&mut self) { + let state = ON_QUEUE.lock().unwrap().remove(&self.0); + drop(state); + } + } + #[test] fn gpu_uploads_on_the_title_queue_run_before_its_later_work_and_are_released() { use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; @@ -3185,8 +4313,8 @@ mod tests { let key = queue.as_raw() as usize; let _queue_uploads = DirectQueueUploads::new(&queue); let upload = |value: u8| { - let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![value; 64 * 64] }]; - own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])], &[])).unwrap(); + let (item, _mem) = r8_item(&texture, value); + own_work(|| submit_on(dev, &queue, &[item])).unwrap(); }; for value in [0x21, 0xC4] { upload(value); @@ -3198,16 +4326,131 @@ mod tests { let mut slot = state.lock().unwrap(); let q = slot.as_mut().unwrap(); assert_eq!(q.value, 3); - let retired = reclaim(dev, q, 0, 10_000); + let retired = reclaim(q, 0, 10_000); assert!(q.in_flight.is_empty() && q.bytes == 0, "over the cap the oldest uploads are waited for and released"); assert!(q.fence.GetCompletedValue() >= 3); drop(slot); - drop(retired); + retired.into_iter().for_each(texture_upload::give_back); } assert_eq!(read_r8(dev, &queue, &texture), vec![0x5E; 64 * 64]); } } + /// An upload on XCL's own queue (for a compute queue's submit) is waited for by the next submit + /// on each queue, on the GPU and once; the thread that submits does not wait. + #[test] + fn gpu_every_queue_waits_once_for_the_uploads_on_the_own_queue() { + let _guard = TEST_LOCK.lock().unwrap(); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let was = OWN_UPLOADS.lock().unwrap().replace((gate.clone(), 1)); + let types = [D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_LIST_TYPE_COMPUTE, D3D12_COMMAND_LIST_TYPE_COPY]; + let queues: Vec = types.iter().map(|&t| dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: t, ..Default::default() }).unwrap()).collect(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let t0 = std::time::Instant::now(); + for (k, q) in queues.iter().enumerate() { + OWN_WAITED.lock().unwrap().remove(&(q.as_raw() as usize)); + wait_for_own_uploads(q); + // (a second time: nothing more to wait for) + wait_for_own_uploads(q); + let own: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + q.Signal(&own, 1).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(20)); + assert_eq!(own.GetCompletedValue(), 0, "queue {k} went on without the upload"); + q.Signal(&done, k as u64 + 1).unwrap(); + } + assert!(t0.elapsed().as_millis() < 2_000, "the submitting thread waited"); + gate.Signal(1).unwrap(); + for (k, q) in queues.iter().enumerate() { + let own: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + q.Signal(&own, 1).unwrap(); + crate::gpu::fence::wait(&own, 1, dev, None, 5_000).unwrap_or_else(|e| panic!("queue {k}: {e:?}")); + OWN_WAITED.lock().unwrap().remove(&(q.as_raw() as usize)); + } + *OWN_UPLOADS.lock().unwrap() = was; + } + } + + /// Uploads of one texture that go to different queues end in the order they were made, whichever + /// queue stands still: an older one on XCL's own queue behind a newer one of a direct queue's + /// submit, and an older one on a direct queue behind a newer one of a compute queue's. + #[test] + fn gpu_uploads_of_a_texture_on_two_queues_keep_their_order() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let Some(mem) = crate::gpu::uma::get().and_then(|u| u.alloc(0x1_0000, 0x1_0000)) else { return }; + let direct: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let compute: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let own = upload_queue(dev, raw_device as usize).unwrap(); + let mut texture = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut texture, + ).unwrap(); + let texture: ID3D12Resource = texture.unwrap(); + let key = texture.as_raw() as usize; + std::ptr::write_bytes(mem, 0, 0x1_0000); + register(raw_device, texture.as_raw(), mem as usize, &console_desc(3, 64, 64, 1, 1, DXGI_FORMAT_R8_UNORM.0 as u32, 1), D3D12_RESOURCE_STATE_COMMON).unwrap(); + let write = |value: u8, q: &ID3D12CommandQueue| { + std::ptr::write_bytes(mem, value, 0x1_0000); + note_known_write(mem as usize, 0x1_0000); + refresh(q.as_raw()); + }; + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + write(0x11, &direct); + assert_eq!(read_r8(dev, &direct, &texture), vec![0x11; 64 * 64]); + + // XCL's own queue stands; an upload for the compute queue is behind that, then one for + // the direct queue, which has to wait for it + own.Wait(&gate, 1).unwrap(); + write(0x22, &compute); + write(0x33, &direct); + let after: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + direct.Signal(&after, 1).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(30)); + assert_eq!(super::super::real::fence_completed(&after), 0, "the direct queue did not wait for the older upload"); + gate.Signal(1).unwrap(); + assert_eq!(read_r8(dev, &direct, &texture), vec![0x33; 64 * 64], "the newer upload is the one that stays"); + + // the direct queue stands with an upload on it; one for the compute queue runs at once on + // XCL's own queue, and goes up again behind the older one with the direct queue's next + direct.Wait(&gate, 2).unwrap(); + write(0x44, &direct); + write(0x55, &compute); + assert!(AGAIN.lock().unwrap().contains(&key), "it can be overtaken"); + refresh(compute.as_raw()); + assert!(AGAIN.lock().unwrap().contains(&key), "not behind the older one yet"); + refresh(direct.as_raw()); + assert!(!AGAIN.lock().unwrap().contains(&key), "went up again on the direct queue"); + gate.Signal(2).unwrap(); + assert_eq!(read_r8(dev, &direct, &texture), vec![0x55; 64 * 64], "the newer upload is the one that stays"); + // with nothing pending nothing goes up again + write(0x66, &compute); + texture::wait(dev, &own).unwrap(); + assert!(!AGAIN.lock().unwrap().contains(&key)); + refresh(direct.as_raw()); + assert_eq!(read_r8(dev, &direct, &texture), vec![0x66; 64 * 64]); + forget(key); + crate::gpu::uma::get().unwrap().free(mem as usize); + dev.GetDeviceRemovedReason().unwrap(); + } + } + /// An upload on the title's queue waits there for the texture page mappings made before it, /// as one on XCL's upload queue does: without the wait its copy can run into tiles whose /// mapping has not run yet (a copy-engine write page fault on NVIDIA). @@ -3238,15 +4481,15 @@ mod tests { D3D12_RESOURCE_STATE_COMMON, None, &mut texture, ).unwrap(); let texture: ID3D12Resource = texture.unwrap(); - let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![0x3C; 64 * 64] }]; - own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])], &[])).unwrap(); + let _queue_uploads = DirectQueueUploads::new(&queue); + let (item, _mem) = r8_item(&texture, 0x3C); + own_work(|| submit_on(dev, &queue, &[item])).unwrap(); assert_eq!( super::super::vram::waited_for_test(raw_device as usize, key), mapped, "the title queue's upload must wait for the page mappings made before it" ); assert_eq!(read_r8(dev, &queue, &texture), vec![0x3C; 64 * 64]); - ON_QUEUE.lock().unwrap().remove(&key); } } @@ -3274,30 +4517,28 @@ mod tests { ).unwrap(); let texture: ID3D12Resource = texture.unwrap(); let key = queue.as_raw() as usize; - let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![0x77; 64 * 64] }]; - own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])], &[])).unwrap(); + let _queue_uploads = DirectQueueUploads::new(&queue); + let (item, _mem) = r8_item(&texture, 0x77); + own_work(|| submit_on(dev, &queue, &[item])).unwrap(); { let state = ON_QUEUE.lock().unwrap().get(&key).unwrap().clone(); let mut slot = state.lock().unwrap(); let q = slot.as_mut().unwrap(); - let retired = reclaim(dev, q, 0, 50); + let retired = reclaim(q, 0, 50); assert_eq!(q.in_flight.len(), 1, "a batch the GPU has not run stays in flight when its wait times out"); - assert!(q.bytes > 0); - drop(slot); - drop(retired); + assert!(q.bytes > 0 && retired.is_empty()); } gate.Signal(1).unwrap(); { let state = ON_QUEUE.lock().unwrap().get(&key).unwrap().clone(); let mut slot = state.lock().unwrap(); let q = slot.as_mut().unwrap(); - let retired = reclaim(dev, q, 0, 10_000); + let retired = reclaim(q, 0, 10_000); assert!(q.in_flight.is_empty() && q.bytes == 0); drop(slot); - drop(retired); + retired.into_iter().for_each(texture_upload::give_back); } assert_eq!(read_r8(dev, &queue, &texture), vec![0x77; 64 * 64]); - ON_QUEUE.lock().unwrap().remove(&key); } } @@ -3396,6 +4637,89 @@ mod tests { refresh(queue.as_raw()); assert_eq!(read_r8(dev, &queue, &texture), vec![0x9A; 64 * 64], "unmapping restores the earlier CPU view"); assert_eq!(address(key), Some(va)); + + // the queue's page mappings: a texture registered over a page mapped into the GPU + // view reads the pool page, where it is kept + struct Pool(Vec); + impl Drop for Pool { + fn drop(&mut self) { + unsafe { kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), self.0.len(), self.0.as_mut_ptr()) }; + } + } + let (mut n, mut ids) = (2usize, vec![0usize; 2]); + assert_eq!(kernelx::AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, ids.as_mut_ptr()), 1); + let mut pool = Pool(ids); + let home = kernelx::MapTitlePhysicalPages(std::ptr::null_mut(), 2, 0, 4, pool.0.as_mut_ptr()) as usize; + assert_ne!(home, 0); + std::ptr::write_bytes(home as *mut u8, 0x51, PAGE); + std::ptr::write_bytes((home + PAGE) as *mut u8, 0x62, PAGE); + let g = va + 4 * PAGE; + map_pages(g, &[[0, 0, 1]], home, 2); + let mut paged = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut paged, + ).unwrap(); + let paged: ID3D12Resource = paged.unwrap(); + register(raw_device, paged.as_raw(), g, &console, D3D12_RESOURCE_STATE_COMMON).unwrap(); + let _paged = RegisteredTexture(paged.as_raw() as usize); + assert!(TEXTURES.lock().unwrap().by_res.get(&(paged.as_raw() as usize)).is_some_and(|e| e.paged && e.src == g)); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &paged), vec![0x51; 64 * 64], "the pool page mapped there"); + // a mapping that changes under it: a pool page written and looked at before it was + // mapped, with no write since; the same bytes in another page; an unmap + map_pages(g, &[[0, 1, 1]], home, 2); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &paged), vec![0x62; 64 * 64], "a clean pool page newly mapped"); + std::ptr::write_bytes(home as *mut u8, 0x62, PAGE); + let reread = rereads(); + map_pages(g, &[[0, 0, 1]], home, 2); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &paged), vec![0x62; 64 * 64], "equal bytes in the old and the new page"); + assert!(rereads() > reread, "read again for the mapping, equal bytes or not"); + map_pages(g, &[[2, 0, 1]], home, 2); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &paged), vec![0; 64 * 64], "unmapped: nothing"); + map_pages(g, &[[0, 1, 1]], home, 2); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &paged), vec![0x62; 64 * 64]); + // writes where the page is kept: in the pool; just before the page moves into the CPU + // view, with no look in between; where it is kept after that; by its page number + // (`mark_hot`: the looks take those blocks now, not once the walk finds them) + std::ptr::write_bytes((home + PAGE) as *mut u8, 0x73, PAGE); + mark_hot(home, 2 * PAGE); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &paged), vec![0x73; 64 * 64], "a write to the pool page"); + std::ptr::write_bytes((home + PAGE) as *mut u8, 0x84, PAGE); + let kept = src + 6 * PAGE; + let mut one = [pool.0[1]]; + assert_eq!(kernelx::MapTitlePhysicalPages(kept as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, kept); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &paged), vec![0x84; 64 * 64], "a write made just before the page moved"); + std::ptr::write_bytes(kept as *mut u8, 0x95, PAGE); + mark_hot(kept, PAGE); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &paged), vec![0x95; 64 * 64], "a write where the page is kept now"); + assert!(kernelx::write_physical_pages(&[pool.0[1]], 0, &[0xA6; PAGE])); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &paged), vec![0xA6; 64 * 64], "a write by page number"); + // the GPU's write of a submitted list stays over a CPU write, and gives way to a later + // mapping; a CPU write after that goes up + let write = capture_gpu_write(paged.as_raw() as usize, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES).unwrap(); + publish_gpu_writes(WriterQueueId { raw: queue.as_raw() as usize, generation: 1 }, &[write]); + std::ptr::write_bytes(kept as *mut u8, 0xB7, PAGE); + mark_hot(kept, PAGE); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &paged), vec![0xA6; 64 * 64], "the GPU's"); + map_pages(g, &[[0, 0, 1]], home, 2); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &paged), vec![0x62; 64 * 64], "a later mapping takes it back"); + std::ptr::write_bytes(home as *mut u8, 0xC8, PAGE); + mark_hot(home, PAGE); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &paged), vec![0xC8; 64 * 64], "and a CPU write after it goes up"); + assert_eq!(kernelx::MapTitlePhysicalPages(kept as *mut c_void, 1, 0, 4, std::ptr::null_mut()) as usize, kept); dev.GetDeviceRemovedReason().unwrap(); } } @@ -3429,7 +4753,7 @@ mod tests { d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); d[0x2C..0x30].copy_from_slice(&0x105u32.to_le_bytes()); let tex = Arc::new(xg::Texture::new(&d).unwrap()); - let mut e = Entry { device: 0, committed_bytes: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0 }; + let mut e = Entry { device: 0, committed_bytes: 0, va: at, src: mirror_source(at), in_gpu_view: true, paged: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, written_call: 0, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0, known: Default::default(), target: false }; assert_eq!(e.src, cpu + 0x2_0000); assert!(!recheck_source(&mut e), "nothing changed yet"); assert_eq!(kernelx::MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, at); @@ -3452,6 +4776,370 @@ mod tests { } } + thread_local! { + /// the VirtualQuery calls `mirror_source` made on this thread + pub(super) static QUERIES: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + /// One call of the queue's page-mapping method: `ranges` (kind, start, count) from GPU-view + /// address `dest` on, in the pool of `pages` pages at `pool`. + unsafe fn map_pages(dest: usize, ranges: &[[u32; 3]], pool: usize, pages: u32) { + // (a batch: the first destination, the number of ranges, a pointer to them) + let batch = [dest as u64, ranges.len() as u64, ranges.as_ptr() as u64]; + assert!(crate::hle::kernelx::mirrors::apply_batches(1, batch.as_ptr() as usize, pool, pages).is_some()); + } + + /// A pair of views of `size` bytes (a size of the test's own: no other test's views pair with + /// these) and `n` physical pages of the title at their home, the pool: (CPU view, GPU view, + /// the pages, their home). + unsafe fn paged_views(size: usize, n: usize) -> (usize, usize, Vec, usize) { + use crate::hle::kernelx::{self, mirrors}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_RESERVE, PAGE_READWRITE}; + let cpu = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE, PAGE_READWRITE) as usize; + let gpu = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE, PAGE_READWRITE) as usize; + assert!(cpu != 0 && gpu != 0); + mirrors::reserved(cpu, size, 0x2040_2000, 0x04); + assert!(mirrors::reserved(gpu, size, 0x2040_2000, 0x801)); + let (mut k, mut pages) = (n, vec![0usize; n]); + assert_eq!(kernelx::AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut k, pages.as_mut_ptr()), 1); + let home = kernelx::MapTitlePhysicalPages(std::ptr::null_mut(), n, 0, 4, pages.as_mut_ptr()) as usize; + assert_ne!(home, 0); + (cpu, gpu, pages, home) + } + + /// The pages and the views of `paged_views` go. + unsafe fn drop_paged_views(cpu: usize, gpu: usize, mut pages: Vec) { + use windows_sys::Win32::System::Memory::{VirtualFree, MEM_RELEASE}; + crate::hle::kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), pages.len(), pages.as_mut_ptr()); + crate::hle::kernelx::mirrors::released(cpu); + VirtualFree(cpu as *mut c_void, 0, MEM_RELEASE); + VirtualFree(gpu as *mut c_void, 0, MEM_RELEASE); + } + + /// A texture over GPU-view pages the queue's page mappings named is read at its own address + /// through a table of where each page is kept, found with no VirtualQuery; one over pages + /// never named takes the CPU view, as before. The table counts its pages by kind. + #[test] + fn a_texture_over_mapped_pages_is_read_where_they_are_kept() { + use crate::hle::kernelx::mirrors::PAGE; + use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, PAGE_READWRITE}; + let _guard = TEST_LOCK.lock().unwrap(); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let (cpu, gpu, pages, home) = paged_views(179 * PAGE, 2); + std::ptr::write_bytes(home as *mut u8, 0x5A, PAGE); + assert_eq!(VirtualAlloc(cpu as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE) as usize, cpu); + std::ptr::write_bytes(cpu as *mut u8, 0x77, PAGE); + // pool page 0 at view page 1, view page 2 unmapped + map_pages(gpu + PAGE, &[[0, 0, 1], [2, 0, 1]], home, 2); + let queries = || QUERIES.with(|n| n.get()); + let q = queries(); + assert_eq!(source_of(gpu + PAGE + 0x100, 0x4000), (gpu + PAGE + 0x100, true), "over a mapped page: its own address"); + assert_eq!(source_of(gpu + 2 * PAGE, 0x4000), (gpu + 2 * PAGE, true), "over an unmapped one too"); + assert_eq!(queries(), q, "no VirtualQuery"); + assert_eq!(source_of(gpu + 5 * PAGE, 0x4000), (cpu + 5 * PAGE, false), "never named: the CPU view, as before"); + assert_eq!(queries(), q + 1); + // a texture over view pages 0 to 3: never named, kept at the pool, nothing, never named + let before = page_counts(); + let m = page_map(gpu + PAGE - 0x2000, 2 * PAGE + 0x4000, true).expect("a table"); + let after = page_counts(); + assert_eq!(std::array::from_fn::(|k| after[k] - before[k]), [1, 0, 2, 1]); + assert!(page_map(gpu + PAGE, 0x4000, false).is_some() && page_counts() == after, "a table of its own is not counted"); + assert!(page_map(gpu + 10 * PAGE, PAGE, true).is_none(), "no page named"); + let mut b = vec![0xEEu8; 3 * PAGE]; + m.copy(gpu, &mut b); + assert!(b[..PAGE].iter().all(|&x| x == 0x77), "the CPU view under a page never named"); + assert!(b[PAGE..2 * PAGE].iter().all(|&x| x == 0x5A), "the pool page where it is kept"); + assert!(b[2 * PAGE..].iter().all(|&x| x == 0), "nothing"); + drop_paged_views(cpu, gpu, pages); + } + } + + /// The GPU's write of a texture read through its pages counts from the submit of the list + /// that records it: a mapping changed by a later call takes the texture back (its pages go up + /// again as they are), one changed before that submit leaves it the GPU's – a list recorded + /// before the call and submitted after it, a list submitted again – and a list reset writes + /// nothing more. + #[test] + fn a_gpu_write_counts_from_the_submit_of_its_list() { + use crate::hle::kernelx::mirrors::{self, PAGE}; + use texture_upload::{Again, Change}; + let _guard = TEST_LOCK.lock().unwrap(); + // (no submit looks while a texture of no resource is in the table) + let _refresh = REFRESH.lock().unwrap(); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let (cpu, gpu, pages, home) = paged_views(181 * PAGE, 2); + map_pages(gpu, &[[0, 0, 1]], home, 2); + recheck_gpu_view_sources(); + let tex = Arc::new(xg::Texture::new(&console_desc(3, 128, 128, 1, 1, 28, 0x105)).unwrap()); + assert_eq!(tex.size() as usize, PAGE); + // a key of no resource, never dereferenced + let res = 0x7E57_0000_5000usize; + let known: texture_upload::Known = Default::default(); + texture_upload::all_sent(&known, gpu, PAGE); + let e = Entry { device: 0, va: gpu, src: gpu, in_gpu_view: true, paged: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, written_call: 0, placed: false, unmapped: false, generation: 0, known: Arc::clone(&known), target: false, committed_bytes: 0, gpu_writers: Vec::new(), cpu_backed: true }; + TEXTURES.lock().unwrap().insert(res, e); + TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); + let state = || TEXTURES.lock().unwrap().by_res.get(&res).map(|e| (e.gpu_written, e.written_call)).unwrap(); + let again = || (AGAIN.lock().unwrap().remove(&res), texture_upload::take_again(&known, 0, 0)); + let page_again = || (true, Again::Now(Change::Parts(vec![(0, PAGE)]))); + let queue = WriterQueueId { raw: 0x7E57_0000_6000, generation: 1 }; + let all = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + + // recorded before a call, submitted after it + let w1 = capture_gpu_write(res, all).unwrap(); + assert_eq!(state(), (false, 0), "nothing is marked as it is recorded"); + map_pages(gpu, &[[0, 1, 1]], home, 2); + let c1 = mirrors::calls(); + publish_gpu_writes(queue, &[w1]); + assert!(state().0 && state().1 >= c1, "marked and stamped at its submit"); + recheck_gpu_view_sources(); + assert!(state().0, "the GPU's write came after the mapping"); + assert_eq!(again(), (false, Again::Nothing)); + // a mapping changed by a later call takes it back + map_pages(gpu, &[[2, 0, 1]], home, 2); + recheck_gpu_view_sources(); + assert!(!state().0, "an older GPU write gives way"); + assert_eq!(again(), page_again(), "the page goes up again as it is, with no comparison"); + // a segment submitted before a call and again after it + let w2 = capture_gpu_write(res, all).unwrap(); + publish_gpu_writes(queue, &[w2]); + map_pages(gpu, &[[0, 0, 1]], home, 2); + publish_gpu_writes(queue, &[w1, w2]); + recheck_gpu_view_sources(); + assert!(state().0, "the second submit came after the mapping"); + assert_eq!(again(), (false, Again::Nothing)); + // a submit of segments that write nothing marks nothing + map_pages(gpu, &[[0, 1, 1]], home, 2); + publish_gpu_writes(queue, &[]); + recheck_gpu_view_sources(); + assert!(!state().0); + assert_eq!(again(), page_again()); + forget(res); + drop_paged_views(cpu, gpu, pages); + } + } + + /// A texture read through its pages finds its written pages through the GPU-view pages a + /// write reaches: a write where a mapped page is kept, and one in the CPU view under a page + /// the queue's page mappings never named; those that differ from what went up are sent. + #[test] + fn an_untouched_page_of_a_paged_texture_is_found_written() { + use crate::hle::kernelx::mirrors::{views_of_written, PAGE}; + use texture_upload::{Change, Written}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, PAGE_READWRITE}; + let _guard = TEST_LOCK.lock().unwrap(); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let (cpu, gpu, pages, home) = paged_views(191 * PAGE, 1); + assert_eq!(VirtualAlloc((cpu + PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE) as usize, cpu + PAGE); + std::ptr::write_bytes(home as *mut u8, 0x21, PAGE); + std::ptr::write_bytes((cpu + PAGE) as *mut u8, 0x43, PAGE); + // a texture over view pages 0 (the pool page mapped there) and 1 (never named) + map_pages(gpu, &[[0, 0, 1]], home, 1); + let m = page_map(gpu, 2 * PAGE, false).expect("a table"); + let known: texture_upload::Known = Default::default(); + texture_upload::all_sent(&known, gpu, 2 * PAGE); + let compare = |dirty: &[usize]| texture_upload::changed(&[Written { src: gpu, size: 2 * PAGE, dirty, known: &known, pages: Some(&m) }], true).0.remove(0); + let all: Vec = (0..2 * PAGE / 0x1000).map(|k| gpu + k * 0x1000).collect(); + assert_eq!(compare(&all), Change::Parts(vec![(0, 2 * PAGE)]), "nothing was known of it"); + // a write where the mapped page is kept, and one in the CPU view under the other page + let (a, b) = (home + 0x2000, cpu + PAGE + 0x3000); + let mut written = vec![a, b]; + written.sort_unstable(); + let look = |written: &[usize]| { + let mut twins = Vec::new(); + views_of_written(written, &mut twins); + twins.sort_unstable(); + twins.dedup(); + assert!(twins.contains(&(gpu + 0x2000)) && twins.contains(&(gpu + PAGE + 0x3000)), "{twins:x?}"); + compare(&twins) + }; + assert_eq!(look(&written), Change::None, "they hold what went up"); + *(a as *mut u8) ^= 1; + *(b as *mut u8) ^= 1; + assert_eq!(look(&written), Change::Parts(vec![(0x2000, 0x3000), (PAGE + 0x3000, PAGE + 0x4000)])); + assert_eq!(look(&written), Change::None); + drop_paged_views(cpu, gpu, pages); + } + } + + /// `written_pages` reports what was written and not taken, at any number, and leaves it reported. + #[test] + fn written_pages_are_reported_without_being_taken() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + const N: usize = 1500; + unsafe { + let p = VirtualAlloc(std::ptr::null(), N << 12, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + assert_ne!(p, 0); + assert!(written_pages(p, N << 12).is_empty()); + for k in 0..N { + *((p + (k << 12) + 5) as *mut u8) = 1; + } + let all: Vec = (0..N).map(|k| p + (k << 12)).collect(); + assert_eq!(written_pages(p, N << 12), all); + assert_eq!(written_pages(p + 0x1800, 0x1000), vec![p + 0x1000, p + 0x2000], "the pages a range lies on"); + // (they are still there for a look) + let (mut buf, mut dirty, mut page) = (vec![std::ptr::null_mut(); 4096], Vec::new(), 0x1000); + take_written(p, N << 12, &mut buf, &mut dirty, &mut page, None); + assert_eq!(dirty, all); + assert!(written_pages(p, N << 12).is_empty()); + VirtualFree(p as *mut c_void, 0, MEM_RELEASE); + let plain = VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + *(plain as *mut u8) = 1; + assert!(written_pages(plain, 0x1000).is_empty(), "memory that is not watched"); + VirtualFree(plain as *mut c_void, 0, MEM_RELEASE); + } + } + + /// A submit whose lists were closed before the last look began goes without a look of its own + /// (`XCL_LOOK_SKIP`) – not once the walk has found a written block since: no look took that one. + #[test] + fn a_block_the_walk_found_since_ends_the_skip() { + let list = 0x7E57_1157usize as *mut c_void; + note_list_closed(list as usize); + std::thread::sleep(std::time::Duration::from_millis(2)); + // (other tests' submits only raise the time of the last look) + let frame = super::super::present::activity().0; + note_look_began(now_us(), frame); + let (began, _) = last_look(); + if WALK_FOUND.load(Ordering::Acquire) < began { + assert!(closed_before_last_look(&[list])); + } + WALK_FOUND.store(u64::MAX, Ordering::Release); + assert!(!closed_before_last_look(&[list]), "the look before did not take the block the walk found"); + // (the next submit of the process looks for itself: nothing is lost by this) + WALK_FOUND.store(now_us(), Ordering::Release); + forget_list_closed(list as usize); + } + + #[test] + fn closed_timestamp_cleared_on_list_reset() { + let list = 0x7E57_2001usize as *mut c_void; + note_list_closed(list as usize); + let began = now_us() + 1000; + assert!(closed_before_last_look_in(&[list], began, 5, 5, 0)); + // (a Reset of the list: list_x forgets its close) + forget_list_closed(list as usize); + assert!(!is_list_closed_for_test(list as usize), "a reset must clear CLOSED"); + assert!(!closed_before_last_look_in(&[list], began, 5, 5, 0), "reset list must not keep a stale CLOSED timestamp"); + } + + #[test] + fn closed_timestamp_cleared_on_release_and_pointer_reuse() { + let list = 0x7E57_2002usize as *mut c_void; + note_list_closed(list as usize); + let began = now_us() + 1000; + assert!(closed_before_last_look_in(&[list], began, 7, 7, 0)); + // Release removes CLOSED before deallocation so a newly allocated list at the same + // address does not inherit the old object's pre-look close timestamp. + forget_list_closed(list as usize); + assert!(!is_list_closed_for_test(list as usize)); + assert!(!closed_before_last_look_in(&[list], began, 7, 7, 0), "reused list pointer must not skip before closing"); + } + + #[test] + fn new_frame_forces_look_even_for_pre_closed_list() { + let list = 0x7E57_2003usize as *mut c_void; + note_list_closed(list as usize); + let began = now_us() + 1000; + assert!(closed_before_last_look_in(&[list], began, 10, 10, 0), "same frame skips pre-closed list"); + assert!(!closed_before_last_look_in(&[list], began, 10, 11, 0), "new frame must force at least one fresh look"); + assert!(should_look(closed_before_last_look_in(&[list], began, 10, 11, 0), true, false)); + // `advance_look` advances monotonically across frames and never rewinds on a late round. + let mut st = (0u64, u64::MAX); + advance_look(&mut st, 100, 0); + assert_eq!(st, (100, 0)); + advance_look(&mut st, 200, 0); + assert_eq!(st, (200, 0)); + advance_look(&mut st, 150, 0); + assert_eq!(st, (200, 0)); + advance_look(&mut st, 250, 1); + assert_eq!(st, (250, 1)); + advance_look(&mut st, 300, 0); + assert_eq!(st, (250, 1)); + forget_list_closed(list as usize); + } + + #[test] + fn same_frame_pre_closed_lists_skip_look_when_enabled() { + let l1 = 0x7E57_2004usize as *mut c_void; + let l2 = 0x7E57_2005usize as *mut c_void; + note_list_closed(l1 as usize); + note_list_closed(l2 as usize); + let began = now_us() + 1000; + let old = closed_before_last_look_in(&[l1, l2], began, 12, 12, began - 1); + assert!(old); + assert!(!should_look(old, true, false), "XCL_LOOK_SKIP=1 skips look for same-frame pre-closed lists"); + assert!(should_look(old, false, false), "default off still runs look"); + forget_list_closed(l1 as usize); + forget_list_closed(l2 as usize); + } + + #[test] + fn list_closed_after_look_began_runs_look() { + let l1 = 0x7E57_2006usize as *mut c_void; + let l2 = 0x7E57_2007usize as *mut c_void; + note_list_closed(l1 as usize); + std::thread::sleep(std::time::Duration::from_millis(2)); + let began = now_us(); + std::thread::sleep(std::time::Duration::from_millis(2)); + note_list_closed(l2 as usize); + let old = closed_before_last_look_in(&[l1, l2], began, 15, 15, 0); + assert!(!old, "list closed after LOOK_BEGAN must force a look even in the same frame"); + assert!(should_look(old, true, false)); + forget_list_closed(l1 as usize); + forget_list_closed(l2 as usize); + } + + #[test] + fn walk_found_at_or_after_look_began_runs_look() { + let list = 0x7E57_2008usize as *mut c_void; + note_list_closed(list as usize); + let began = now_us() + 1000; + assert!(closed_before_last_look_in(&[list], began, 20, 20, began - 1)); + assert!(!closed_before_last_look_in(&[list], began, 20, 20, began), "WALK_FOUND == LOOK_BEGAN must run look"); + assert!(!closed_before_last_look_in(&[list], began, 20, 20, began + 1), "WALK_FOUND > LOOK_BEGAN must run look"); + assert!(should_look(closed_before_last_look_in(&[list], began, 20, 20, began), true, false)); + forget_list_closed(list as usize); + } + + /// Pages found ahead of a submit are kept until one takes them, are not reported again, and a + /// page written after that is found again. + #[test] + fn pages_found_ahead_are_kept_for_the_next_submit() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + const N: usize = 256; + unsafe { + let base = VirtualAlloc(std::ptr::null(), N << 12, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + let mut buf = vec![std::ptr::null_mut::(); 64]; + let ahead = Mutex::new(Vec::new()); + let write = |k: usize| ((base + (k << 12)) as *mut u8).write_volatile(1); + for k in (0..N).step_by(2) { + write(k); + } + assert_eq!(take_piece(base, N << 12, &mut buf, &ahead), N / 2, "past a full buffer too"); + assert_eq!(*ahead.lock().unwrap(), (0..N).step_by(2).map(|k| base + (k << 12)).collect::>()); + let (mut dirty, mut page) = (Vec::new(), 0u32); + take_written(base, N << 12, &mut buf, &mut dirty, &mut page, None); + assert!(dirty.is_empty(), "a look does not find them again"); + write(8); + write(9); + assert_eq!(take_piece(base, N << 12, &mut buf, &ahead), 2); + assert_eq!(ahead.lock().unwrap()[N / 2..], [base + 0x8000, base + 0x9000], "written again: found again, behind the others"); + // (only of its own piece) + write(0); + write(200); + assert_eq!(take_piece(base + (100 << 12), 100 << 12, &mut buf, &ahead), 0); + assert_eq!(take_piece(base + (100 << 12), 101 << 12, &mut buf, &ahead), 1); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + /// More written pages than one call reports: each is found once, in order, and the look /// resets them – a buffer that fills in the middle of the range and one that fills exactly. #[test] @@ -3619,6 +5307,10 @@ mod tests { placed: false, unmapped: false, generation: 0, + paged: false, + written_call: 0, + known: Default::default(), + target: false, }; let generation = { let mut t = TEXTURES.lock().unwrap(); @@ -3771,7 +5463,7 @@ mod tests { assert_eq!(subresource_count(&tex), 6); // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it let (res, other) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize); - TEXTURES.lock().unwrap().insert(res, Entry { device: 0, committed_bytes: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0 }); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, committed_bytes: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, paged: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, written_call: 0, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0, known: Default::default(), target: false }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().by_res.get(&res).unwrap().states.clone(); let e1 = capture_transitions(&[(res, ALL, SRV), (other, ALL, D3D12_RESOURCE_STATE_RENDER_TARGET), (res, 4, D3D12_RESOURCE_STATE_COPY_SOURCE)]); @@ -4013,36 +5705,8 @@ mod tests { } } - /// The textures of a batch detiled on several threads come back as on one: complete and in - /// order (2D with mips and slices, 3D, BC7, a tiny one; more textures than threads). - #[test] - fn a_batch_detiled_on_several_threads_matches_one_thread() { - let descs = [ - console_desc(3, 64, 64, 2, 3, 28, 0x105), - console_desc(3, 200, 72, 1, 5, 28, 0x105), - console_desc(4, 40, 24, 6, 3, 28, 0x105), - console_desc(3, 256, 256, 1, 9, 98, 0x10A), - console_desc(3, 4, 4, 1, 1, 28, 0x105), - console_desc(3, 128, 32, 3, 2, 28, 0x105), - console_desc(3, 64, 64, 1, 1, 28, 0x105), - ]; - let textures: Vec> = descs.iter().map(|d| Arc::new(xg::Texture::new(d).unwrap())).collect(); - // each texture's console memory: distinct bytes per texture - let mems: Vec> = textures.iter().enumerate().map(|(t, x)| (0..x.size() as usize).map(|i| (i * 7 + t * 61) as u8).collect()).collect(); - let picked: Vec<(usize, &xg::Texture)> = mems.iter().zip(&textures).map(|(m, x)| (m.as_ptr() as usize, &**x)).collect(); - unsafe { - let one = subresources_on(&picked, 1); - assert!(one.iter().all(|s| !s.is_empty()), "a texture gave no subresources"); - for threads in [2, 3, 8] { - assert!(subresources_on(&picked, threads) == one, "{threads} threads differ from one"); - } - let pooled: Vec<_> = picked.iter().zip(&textures).map(|(&(va, _), tex)| (va, Arc::clone(tex))).collect(); - assert_eq!(pooled_subresources(&pooled, usize::MAX), Some(one), "persistent workers preserve order and content"); - } - } - #[test] - fn failed_preparation_requeues_only_the_exact_cpu_generation() { + fn failed_upload_requeues_only_the_exact_cpu_generation() { let tex = Arc::new(xg::Texture::new(&console_desc(3, 4, 4, 1, 1, 28, 0x105)).unwrap()); let entry = |generation, gpu_written| Entry { device: 0, @@ -4059,6 +5723,10 @@ mod tests { placed: false, unmapped: false, generation, + paged: false, + written_call: 0, + known: Default::default(), + target: false, }; let mut table = Table::new(); table.by_res.insert(1, entry(7, false)); @@ -4067,19 +5735,11 @@ mod tests { assert_eq!(requeue_generations(&mut table, &[(1, 7), (2, 7), (3, 9), (4, 1)]), [1]); assert!(table.by_res[&1].pending); + assert!(table.pending_res.contains(&1) && table.pending_res.len() == 1, "nv's pending set follows"); assert!(!table.by_res[&2].pending, "a replacement generation owns its own pending state"); assert!(!table.by_res[&3].pending, "GPU-written content must not be overwritten by a retry"); } - #[test] - fn preparation_results_fail_closed_on_worker_loss() { - assert!(ordered_subresources(2, [(1, Some(Vec::new())), (0, Some(Vec::new()))]).is_some()); - assert!(ordered_subresources(2, [(0, Some(Vec::new()))]).is_none(), "a missing worker result must fail the batch"); - assert!( - ordered_subresources(2, [(0, Some(Vec::new())), (1, None)]).is_none(), - "a caught worker panic must fail the batch", - ); - } #[test] fn small_cpu_filled_target_accepts_wide_glyph_atlas_and_rejects_large_or_depth() { @@ -4093,7 +5753,7 @@ mod tests { assert!(!is_small_cpu_filled_target(256, 256, 4, 0x1), "MSAA RTs skipped"); } - fn console_desc(dim: u32, w: u64, h: u32, array_or_depth: u16, mips: u16, format: u32, layout: u32) -> [u8; 0x38] { + pub(in crate::hle::d3d12x) fn console_desc(dim: u32, w: u64, h: u32, array_or_depth: u16, mips: u16, format: u32, layout: u32) -> [u8; 0x38] { let mut d = [0u8; 0x38]; d[0..4].copy_from_slice(&dim.to_le_bytes()); d[0x10..0x18].copy_from_slice(&w.to_le_bytes()); @@ -4125,6 +5785,10 @@ mod tests { placed, unmapped: false, generation: 0, + paged: false, + written_call: 0, + known: Default::default(), + target: false, }; let mut table = Table::new(); table.insert(1, entry(7, 0x10_0000, 3 * M, false)); @@ -4333,15 +5997,19 @@ mod tests { va, src: va, in_gpu_view: false, + paged: false, tex: Arc::clone(tex), states: vec![D3D12_RESOURCE_STATE_COMMON], pending, gpu_written: false, + written_call: 0, gpu_writers: Vec::new(), cpu_backed: true, placed, unmapped: false, generation: 0, + known: Default::default(), + target: false, }; let mut tbl = Table::new(); // Two adjacent placed 16 KiB textures + one placed 64 KiB texture after them. @@ -4748,6 +6416,10 @@ mod tests { placed: !cpu_backed, unmapped: false, generation: 0, + paged: false, + written_call: 0, + known: Default::default(), + target: false, }; let mut t = Table::new(); t.insert(1, entry(true)); @@ -4767,6 +6439,8 @@ mod tests { #[test] fn stream_recheck_schedule_catches_late_writes_and_resets_milestones() { + // (STREAM_RECHECK is shared with the other stream recheck test) + let _guard = TEST_LOCK.lock().unwrap(); let desc = console_desc(3, 256, 256, 1, 1, 28, 0x109); // 256 KiB RGBA8 let tex = Arc::new(xg::Texture::new(&desc).expect("layout")); let size = tex.size() as usize; @@ -4781,15 +6455,19 @@ mod tests { va, src: va, in_gpu_view: false, + paged: false, tex: Arc::clone(&tex), states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, + written_call: 0, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0, + known: Default::default(), + target: false, }; let e_gpu = Entry { device: 0, @@ -4797,15 +6475,19 @@ mod tests { va: va + size, src: va, in_gpu_view: false, + paged: false, tex: Arc::clone(&tex), states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, + written_call: 0, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0, + known: Default::default(), + target: false, }; { let mut t = TEXTURES.lock().unwrap(); @@ -4816,8 +6498,8 @@ mod tests { let fp0 = unsafe { sample_fingerprint(va, size) }; { let mut g = STREAM_RECHECK.lock().unwrap(); - g.insert(res_id, StreamRecheck { base_frame: 100, stage: 0, last_fp: fp0 }); - g.insert(gpu_res_id, StreamRecheck { base_frame: 100, stage: 0, last_fp: fp0 }); + g.insert(res_id, StreamRecheck { base_frame: 100, stage: 0, last_fp: Some(fp0) }); + g.insert(gpu_res_id, StreamRecheck { base_frame: 100, stage: 0, last_fp: Some(fp0) }); } // Before first milestone (+4 frames -> frame 104), nothing is checked or re-queued. @@ -4841,7 +6523,7 @@ mod tests { assert!(!g.contains_key(&gpu_res_id), "gpu_written texture must be pruned from STREAM_RECHECK"); let st = g.get(&res_id).copied().expect("schedule reset after change"); assert_eq!((st.base_frame, st.stage), (104, 0)); - assert_ne!(st.last_fp, fp0); + assert_ne!(st.last_fp, Some(fp0)); } // Advance through all 5 milestones with no further writes: entry must not re-queue and must @@ -4856,14 +6538,257 @@ mod tests { forget(gpu_res_id); } + /// A partial upload does not replace the baseline of the last whole upload: an unwatched write + /// it did not send is still caught at the milestone. + #[test] + fn stream_recheck_keeps_the_whole_upload_baseline_over_partial_uploads() { + let _guard = TEST_LOCK.lock().unwrap(); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + // (software adapter only: the resource only gives the Due its key) + 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; + }; + let mut dev: Option = None; + 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 hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 0x1_0000, + 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 res: Option = None; + dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COMMON, None, &mut res).unwrap(); + let res = res.unwrap(); + let res_id = res.as_raw() as usize; + + let desc = console_desc(3, 256, 256, 1, 1, 28, 0x109); // 256 KiB RGBA8 + let tex = Arc::new(xg::Texture::new(&desc).expect("layout")); + let size = tex.size() as usize; + let mut backing = vec![0u8; size]; + let va = backing.as_ptr() as usize; + let entry = Entry { + device: 0, + va, + src: va, + in_gpu_view: false, + paged: false, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written: false, + written_call: 0, + placed: false, + unmapped: false, + generation: 0, + known: Default::default(), + target: false, + committed_bytes: 0, + gpu_writers: Vec::new(), + cpu_backed: true, + }; + let generation = { + let mut t = TEXTURES.lock().unwrap(); + let (d, _) = t.insert(res_id, entry); + adjust_pending(d); + t.by_res[&res_id].generation + }; + let due = |whole: bool| Due { + res: res.clone(), + device: 0, + src: va, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + known: Default::default(), + whole, + again: texture_upload::Change::None, + target: false, + pages: None, + generation, + }; + + // The whole upload at frame 0 sets the baseline. + seed_stream_recheck(&[due(true)], &[], 0); + let fp0 = sample_fingerprint(va, size); + assert_eq!(STREAM_RECHECK.lock().unwrap().get(&res_id).copied(), Some(StreamRecheck { base_frame: 0, stage: 0, last_fp: Some(fp0) })); + + // An unwatched page is written, then a partial upload (of other pages) runs at frame 2. + backing[size - 16] = 0xCD; + seed_stream_recheck(&[due(false)], &[], 2); + assert_eq!( + STREAM_RECHECK.lock().unwrap().get(&res_id).copied(), + Some(StreamRecheck { base_frame: 0, stage: 0, last_fp: Some(fp0) }), + "a partial upload must not replace the baseline or move the schedule" + ); + + // At frame 6 milestone 0 is due from either base frame, and it finds what the GPU does + // not hold yet. + recheck_streamed_unwatched_at(&[], 6); + { + let mut t = TEXTURES.lock().unwrap(); + let e = t.by_res.get_mut(&res_id).unwrap(); + assert!(e.pending, "the unwatched write the partial upload did not send must queue the texture"); + e.pending = false; + PENDING.fetch_sub(1, Ordering::Relaxed); + } + + forget(res_id); + } + } + + /// A partial upload of a texture whose recheck entry has retired makes an entry without a + /// baseline: its first milestone queues a whole upload, which sets the baseline. + #[test] + fn stream_recheck_partial_upload_without_an_entry_queues_a_whole_upload() { + let _guard = TEST_LOCK.lock().unwrap(); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + // (software adapter only: the resource only gives the Due its key) + 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; + }; + let mut dev: Option = None; + 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 hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 0x1_0000, + 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 res: Option = None; + dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COMMON, None, &mut res).unwrap(); + let res = res.unwrap(); + let res_id = res.as_raw() as usize; + + let desc = console_desc(3, 256, 256, 1, 1, 28, 0x109); // 256 KiB RGBA8 + let tex = Arc::new(xg::Texture::new(&desc).expect("layout")); + let size = tex.size() as usize; + let mut backing = vec![0u8; size]; + let va = backing.as_ptr() as usize; + let entry = Entry { + device: 0, + va, + src: va, + in_gpu_view: false, + paged: false, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written: false, + written_call: 0, + placed: false, + unmapped: false, + generation: 0, + known: Default::default(), + target: false, + committed_bytes: 0, + gpu_writers: Vec::new(), + cpu_backed: true, + }; + let generation = { + let mut t = TEXTURES.lock().unwrap(); + let (d, _) = t.insert(res_id, entry); + adjust_pending(d); + t.by_res[&res_id].generation + }; + let due = |whole: bool| Due { + res: res.clone(), + device: 0, + src: va, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + known: Default::default(), + whole, + again: texture_upload::Change::None, + target: false, + pages: None, + generation, + }; + let pending = || TEXTURES.lock().unwrap().by_res.get(&res_id).unwrap().pending; + let entry = || STREAM_RECHECK.lock().unwrap().get(&res_id).copied(); + + // A whole upload at frame 0, then every milestone finds nothing new and the entry retires. + seed_stream_recheck(&[due(true)], &[], 0); + for f in [4, 16, 56, 176, 576] { + recheck_streamed_unwatched_at(&[], f); + assert!(!pending(), "unchanged texture must not re-queue at frame {f}"); + } + assert_eq!(entry(), None, "entry must retire after final 400-frame milestone"); + + // An unwatched page is written, a partial upload (of other pages) runs at frame 600, and + // another unwatched page is written after it. + backing[16] = 0x11; + seed_stream_recheck(&[due(false)], &[], 600); + assert_eq!(entry(), Some(StreamRecheck { base_frame: 600, stage: 0, last_fp: None }), "a partial upload without an entry makes one without a baseline"); + backing[size - 16] = 0x22; + // A later partial upload leaves that entry as it is. + seed_stream_recheck(&[due(false)], &[], 602); + assert_eq!(entry(), Some(StreamRecheck { base_frame: 600, stage: 0, last_fp: None }), "a partial upload must not touch an existing entry"); + + recheck_streamed_unwatched_at(&[], 603); + assert!(!pending(), "nothing is checked before the first milestone"); + recheck_streamed_unwatched_at(&[], 604); + { + let mut t = TEXTURES.lock().unwrap(); + let e = t.by_res.get_mut(&res_id).unwrap(); + assert!(e.pending, "the first milestone of an entry without a baseline must queue the texture"); + e.pending = false; + PENDING.fetch_sub(1, Ordering::Relaxed); + } + + // The whole upload that follows sets the baseline: with no further write, the next + // milestone queues nothing. + seed_stream_recheck(&[due(true)], &[], 605); + let fp = sample_fingerprint(va, size); + assert_eq!(entry(), Some(StreamRecheck { base_frame: 605, stage: 0, last_fp: Some(fp) })); + recheck_streamed_unwatched_at(&[], 609); + assert!(!pending(), "after the whole upload an unchanged texture must not re-queue"); + assert_eq!(entry(), Some(StreamRecheck { base_frame: 605, stage: 1, last_fp: Some(fp) })); + + forget(res_id); + } + } + /// Real GPU, `vram::level_pages` (`XCL_TEXTURE_LEVEL_PAGES=1`): a sampled texture placed on the /// shared pages gets the pages of a level when an upload has texels for it. Its memory has /// every level but the largest at first, as a title streams a texture: no page before the /// first upload, then pages for those levels only and their texels right, zeros where there /// are none. With memory under the largest level too, a texture placed there again (as a /// title does) takes that level's pages - the others are shared - and holds all of it. A - /// texture the GPU writes gets the pages of all its levels. A mapped level also clears when - /// the CPU's next upload sources zeros from shared staging. + /// texture the GPU writes gets the pages of all its levels. When the title takes the memory + /// from under the largest level again, that level gives its pages back at the next upload + /// (the other texture on them keeps them), and gets them again with its texels. A small level + /// that shares its pages with levels that keep texels clears with the next upload. #[test] fn a_placed_texture_gets_the_pages_of_a_level_with_its_texels() { let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); @@ -4871,7 +6796,7 @@ mod tests { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; use windows::Win32::Graphics::Dxgi::*; - use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; const NAME: &str = "a_placed_texture_gets_the_pages_of_a_level_with_its_texels"; unsafe { let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); @@ -4975,12 +6900,15 @@ mod tests { assert!(read_sub(&small, sub) == want[sub as usize].data, "level {sub} after the first upload"); } assert!(read_sub(&small, 0).iter().all(|&b| b == 0), "a level without pages reads as zeros"); + // (what its upload read is not kept: mip 0 may have been written while it was read) + assert!(super::super::vram::has_unmapped_levels(small.as_raw() as usize)); // the title maps memory under mip 0 and fills it assert!(!VirtualAlloc((at + top) as *const c_void, size - top, MEM_COMMIT, PAGE_READWRITE).is_null()); std::ptr::copy_nonoverlapping(whole.as_ptr().add(top), (at + top) as *mut u8, size - top); let full = place_tex(at); refresh(queue.as_raw()); assert_eq!(dev_pages() - p0, (all as usize) << 16, "mip 0's pages come with its texels; the other levels' are shared"); + assert!(!super::super::vram::has_unmapped_levels(full.as_raw() as usize)); for sub in 0..11u32 { assert!(read_sub(&full, sub) == want[sub as usize].data, "level {sub} once all of it is there"); } @@ -4990,21 +6918,43 @@ mod tests { publish_gpu_writes(WriterQueueId { raw: queue.as_raw() as usize, generation: 1 }, &[write]); assert_eq!(dev_pages() - p0, (all as usize) << 16, "the same pages"); assert!(read_sub(&small, 0) == want[0].data, "a GPU-written texture has pages under all its levels"); - std::ptr::write_bytes((at + top) as *mut u8, 0, size - top); + // the title takes the memory from under mip 0 again (a streamed level it let go): the + // second texture's next upload finds mip 0 all zeros, and mip 0 gives back its pages; + // the first one, on the same pages, keeps them + let full_key = full.as_raw() as usize; + assert_eq!(super::super::vram::mapped_level_tiles(full_key), Some(all as u64)); + assert_ne!(VirtualFree((at + top) as *mut c_void, size - top, MEM_DECOMMIT), 0); + assert!(map_levels_with_texels(&full, &subresources(at, &tex)).is_empty(), "no level got pages"); + assert_eq!(super::super::vram::mapped_level_tiles(full_key), Some((all - top_tiles) as u64), "mip 0 gave its pages back"); + assert!(super::super::vram::has_unmapped_levels(full_key)); + assert!(read_sub(&full, 0).iter().all(|&b| b == 0), "a level that gave its pages back reads as zeros"); + for sub in 1..11u32 { + assert!(read_sub(&full, sub) == want[sub as usize].data, "level {sub} keeps its pages and texels"); + } + assert!(read_sub(&small, 0) == want[0].data, "the other texture on those pages keeps them"); + // mip 0's texels come back: its pages too, the ones the other texture holds + assert!(!VirtualAlloc((at + top) as *const c_void, size - top, MEM_COMMIT, PAGE_READWRITE).is_null()); + std::ptr::copy_nonoverlapping(whole.as_ptr().add(top), (at + top) as *mut u8, size - top); + assert_eq!(map_levels_with_texels(&full, &subresources(at, &tex)), vec![0], "mip 0 got its pages again"); + assert_eq!(super::super::vram::mapped_level_tiles(full_key), Some(all as u64)); + assert!(read_sub(&full, 0) == want[0].data, "mip 0 on the pages the other texture kept"); + // a small level whose pages hold levels that keep texels: zeros there clear it at the + // next upload, and its neighbours keep their texels let cpu = std::slice::from_raw_parts_mut(at as *mut u8, chain.slice_bytes); chain.tile_level(cpu, 10, 0, &vec![0u8; want[10].data.len()]); // The synthetic allocation here is not write-watched. Queue the normal batch update. { let mut t = TEXTURES.lock().unwrap(); - let e = t.by_res.get_mut(&(full.as_raw() as usize)).unwrap(); + let key = full.as_raw() as usize; + let e = t.by_res.get_mut(&key).unwrap(); assert!(!e.pending, "the preceding refresh uploaded this texture"); e.pending = true; + t.pending_res.insert(key); adjust_pending(1); } refresh(queue.as_raw()); - assert_eq!(dev_pages() - p0, (all as usize) << 16, "clearing a level keeps its backing"); - assert!(read_sub(&full, 0).iter().all(|&b| b == 0), "the previously streamed level was cleared"); assert!(read_sub(&full, 10).iter().all(|&b| b == 0), "a small level sharing the zero span was cleared"); + assert!(read_sub(&full, 0) == want[0].data, "mip 0 kept its texels"); assert!(read_sub(&full, 1) == want[1].data, "a nonzero mip kept its texels"); assert!(read_sub(&full, 9) == want[9].data, "the small level's neighbour kept its texels"); super::super::vram::LEVEL_PAGES_FOR_TEST.store(false, Ordering::Relaxed); @@ -5151,7 +7101,7 @@ mod tests { let before = decommits.load(Ordering::Relaxed); for _ in 0..2000 { let ok = with_title_bytes(base, PAGES * PAGE, |b| { - std::hint::black_box(content_hash(b)); + std::hint::black_box(texture_upload::content_hash(b)); b.chunks(4096).enumerate().all(|(k, c)| { let n = c.iter().position(|&x| x != tag(k)).unwrap_or(c.len()); c[n..].iter().all(|&x| x == 0) diff --git a/crates/xcl/src/hle/d3d12x/uma_driver.rs b/crates/xcl/src/hle/d3d12x/uma_driver.rs index e4c4b8b7ee..5d41c303cb 100644 --- a/crates/xcl/src/hle/d3d12x/uma_driver.rs +++ b/crates/xcl/src/hle/d3d12x/uma_driver.rs @@ -9,9 +9,21 @@ //! stays in `Uma::watch_regions` and the title's CPU writes reach its textures as before; a driver //! that refuses it, or whose mapping `GetWriteWatch` cannot read, keeps the import. //! -//! `XCL_UMA_DRIVER`: `custom` or `1` on, `0` off; unset: on for an NVIDIA adapter outside Wine. +//! +//! `mixed::[,...]` makes the window several driver heaps instead of one: each +//! range a `GPU_UPLOAD` heap (video memory the CPU writes through the BAR; on NVIDIA it stays in +//! video memory up to 2 GiB) and the rest CUSTOM write-back L0 heaps, each segment's CPU mapping at +//! its place in the window and one reserved buffer over all of them on the GPU +//! (`UpdateTileMappings`). The `GPU_UPLOAD` segments are not write-watched (write-combined pages +//! refuse the watch trap's read-only protection); the title texture code reads them through a copy +//! on the GPU (`read_vram_bytes`). +//! +//! `XCL_UMA_DRIVER`: `custom` or `1` on, `mixed:...` on with the ranges above, `0` off; unset: on +//! (one CUSTOM heap) for an NVIDIA adapter outside Wine. use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; @@ -21,6 +33,7 @@ use windows_sys::Win32::System::Memory::{ }; const MEM_WRITE_WATCH: u32 = 0x20_0000; +const TILE: usize = 0x1_0000; #[link(name = "kernel32")] extern "system" { @@ -36,11 +49,32 @@ pub(super) fn wanted(device: &ID3D12Device) -> bool { fn decide(switch: Option<&str>, wine: impl FnOnce() -> bool, vendor: impl FnOnce() -> Option) -> bool { match switch.map(str::trim) { Some("custom" | "1") => true, + Some(s) if s.starts_with("mixed:") => true, Some("0") => false, _ => !wine() && vendor() == Some(0x10DE), } } +/// `XCL_UMA_DRIVER=mixed::[,...]`: the window's `GPU_UPLOAD` ranges +/// `(start, len)` in bytes, in order; None for any other value. +fn mixed_ranges() -> Option> { + parse_mixed(&std::env::var("XCL_UMA_DRIVER").ok()?) +} + +fn parse_mixed(raw: &str) -> Option> { + let list = raw.trim().strip_prefix("mixed:")?; + let mut ranges = Vec::new(); + for part in list.split(',') { + let (a, b) = part.trim().split_once(':')?; + let (start_mb, size_mb): (usize, usize) = (a.trim().parse().ok()?, b.trim().parse().ok()?); + if size_mb != 0 { + ranges.push((start_mb << 20, size_mb << 20)); + } + } + ranges.sort_by_key(|r| r.0); + (!ranges.is_empty()).then_some(ranges) +} + /// PCI vendor id of `device`'s adapter. fn vendor(device: &ID3D12Device) -> Option { use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory4}; @@ -82,8 +116,12 @@ unsafe fn written_pages(base: usize, size: usize) -> Result) /// outside `[hole, hole + len)`. A window under 1 GiB (512 MB with the 16-window layout) found a /// stretch between its size and 1 GiB unreserved, and the driver mapped its heap there. unsafe fn groom(hole: usize, len: usize) -> Vec { + groom_with(hole, len, len.min(1 << 30), (256usize << 20).min(len / 2) & !0xFFFF) +} + +/// `groom` for stretches of `min_region` or more, leaving `headroom` at the start of each. +unsafe fn groom_with(hole: usize, len: usize, min_region: usize, headroom: usize) -> Vec { let (top, mut a, mut got) = (0x7FFF_FFFE_0000usize, 0x1_0000usize, Vec::new()); - let (least, margin) = (len.min(1 << 30), (256usize << 20).min(len / 2) & !0xFFFF); while a < top { let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); if VirtualQuery(a as *const c_void, &mut m, std::mem::size_of::()) == 0 { @@ -91,10 +129,10 @@ unsafe fn groom(hole: usize, len: usize) -> Vec { } let (base, end) = (m.BaseAddress as usize, (m.BaseAddress as usize + m.RegionSize).min(top)); a = end; - if m.State != MEM_FREE || m.RegionSize < least { + if m.State != MEM_FREE || m.RegionSize < min_region { continue; } - let s = ((base + 0xFFFF) & !0xFFFF) + margin; + let s = ((base + 0xFFFF) & !0xFFFF).saturating_add(headroom); for (s, e) in [(s, end.min(hole)), (s.max(hole + len), end)] { let mut s = s; while s < e { @@ -222,15 +260,441 @@ unsafe fn remake_with_after_release( } } -/// `heap` and `buf` as the raw pointers `open_uma` keeps. -pub(super) fn raw(heap: ID3D12Heap, buf: ID3D12Resource) -> (usize, u64, usize) { - let va = unsafe { buf.GetGPUVirtualAddress() }; - (buf.into_raw() as usize, va, heap.into_raw() as usize) +/// A coherent window remade as driver heap(s): the buffer shaders bind, the heaps `(offset, len, +/// heap)` that resources placed in the window go to, and the write-watched parts `(va, len)` when +/// they are not the whole window (a mixed window's CUSTOM segments). +pub(super) struct Remade { + pub buf_raw: usize, + pub gpu_va: u64, + pub heaps: Vec<(usize, usize, usize)>, + pub watched_regions: Option>, +} + +/// `remake`, or `remake_mixed` with `XCL_UMA_DRIVER=mixed:...` when `first` (the ranges are those +/// of the first coherent window; a 16-window layout's further ones are one CUSTOM heap each). +pub(super) unsafe fn remake_window(device: &ID3D12Device, base: usize, size: usize, first: bool) -> Result { + if let Some(ranges) = mixed_ranges().filter(|_| first) { + if gpu_upload_heaps(device) { + return remake_mixed(device, base, size, &ranges); + } + crate::xlog_warn!("D3D12.X: XCL_UMA_DRIVER=mixed: the adapter has no GPU_UPLOAD heaps (Resizable BAR off?), so the coherent window is one CUSTOM heap"); + } + let (heap, buf) = remake(device, base, size)?; + let gpu_va = buf.GetGPUVirtualAddress(); + Ok(Remade { buf_raw: buf.into_raw() as usize, gpu_va, heaps: vec![(0, size, heap.into_raw() as usize)], watched_regions: None }) +} + +/// Whether the adapter makes `GPU_UPLOAD` heaps (`D3D12_OPTIONS16`; needs Resizable BAR). Asked +/// before the window is released: a segment's mapping stays with the driver after its heap is +/// dropped, so a window cannot be made whole again once a segment has been mapped. +unsafe fn gpu_upload_heaps(device: &ID3D12Device) -> bool { + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default(); + device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS16, &mut opts as *mut _ as *mut c_void, std::mem::size_of::() as u32) + .is_ok() + && opts.GPUUploadHeapSupported.as_bool() +} + +#[cfg(test)] +thread_local! { + /// tests: `mapped_segment` refuses `GPU_UPLOAD` heaps on this thread + static REFUSE_GPU_UPLOAD: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +fn heap_props(upload: bool) -> D3D12_HEAP_PROPERTIES { + if upload { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_GPU_UPLOAD, ..Default::default() } + } else { + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + } + } +} + +fn buffer_desc(size: usize) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + } +} + +/// `XCL_UMA_UPLOAD_PRIORITY=1` (read once): the `GPU_UPLOAD` segments of a mixed window get +/// `D3D12_RESIDENCY_PRIORITY_MAXIMUM`, so Windows demotes other heaps first when the process is +/// over its video memory budget. +fn upload_priority_wanted() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_UMA_UPLOAD_PRIORITY").is_ok_and(|v| v.trim() == "1")) +} + +/// One segment of a mixed window: a heap of `size` bytes (write-watched when `watch`), a buffer +/// over all of it and where the driver mapped it for the CPU. +unsafe fn mapped_segment(device: &ID3D12Device, size: usize, upload: bool, watch: bool) -> Result<(ID3D12Heap, ID3D12Resource, usize), String> { + #[cfg(test)] + if upload && REFUSE_GPU_UPLOAD.with(|r| r.get()) { + return Err("CreateHeap: refused by the test".into()); + } + let flags = if watch { D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS | D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH } else { D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }; + let desc = D3D12_HEAP_DESC { SizeInBytes: size as u64, Properties: heap_props(upload), Alignment: 0x1_0000, Flags: flags }; + let mut heap: Option = None; + device.CreateHeap(&desc, &mut heap).map_err(|e| format!("CreateHeap{}: {e}", if watch { " (write-watched)" } else { "" }))?; + let heap = heap.ok_or("CreateHeap")?; + if upload && upload_priority_wanted() { + // (a process over its video memory budget has heaps demoted to system memory: not this one, + // which every console program reads its buffers from) + let set = device.cast::().and_then(|d| { + let obj: ID3D12Pageable = heap.cast()?; + d.SetResidencyPriority(1, &Some(obj), &D3D12_RESIDENCY_PRIORITY_MAXIMUM) + }); + match set { + Ok(()) => crate::xlog_info!("D3D12.X: XCL_UMA_UPLOAD_PRIORITY: the {} MB GPU_UPLOAD segment has the highest residency priority", size >> 20), + Err(e) => crate::xlog_warn!("D3D12.X: XCL_UMA_UPLOAD_PRIORITY: SetResidencyPriority: {e}"), + } + } + let mut buf: Option = None; + device.CreatePlacedResource(&heap, 0, &buffer_desc(size), D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("CreatePlacedResource: {e}"))?; + let buf = buf.ok_or("CreatePlacedResource")?; + let mut p: *mut c_void = std::ptr::null_mut(); + buf.Map(0, Some(&D3D12_RANGE::default()), Some(&mut p)).map_err(|e| format!("Map: {e}"))?; + Ok((heap, buf, p as usize)) +} + +/// `[0, size)` as contiguous `(offset, len, upload)` segments: `vram_ranges` (sorted) on 64 KiB +/// tiles as `GPU_UPLOAD` segments, the rest CUSTOM. +fn build_segments(size: usize, vram_ranges: &[(usize, usize)]) -> Result, String> { + let mut segs = Vec::new(); + let mut cur = 0usize; + for &(start, len) in vram_ranges { + let s = start.min(size) & !(TILE - 1); + let e = start.saturating_add(len).min(size) & !(TILE - 1); + if e <= s { + continue; + } + if s < cur { + return Err(format!("overlapping mixed ranges at {s:#x} < {cur:#x}")); + } + if s > cur { + segs.push((cur, s - cur, false)); + } + segs.push((s, e - s, true)); + cur = e; + } + if cur < size { + segs.push((cur, size - cur, false)); + } + if !segs.iter().any(|s| s.2) { + return Err("no GPU_UPLOAD range inside the window".into()); + } + Ok(segs) +} + +/// The window could not be made again at its address after it was released: the title's memory +/// there is gone, so the process stops before guest code uses it (as `remake` does). +unsafe fn stop_unbacked(base: usize, size: usize, got: *mut c_void, why: &str) -> ! { + let os_error = windows_sys::Win32::Foundation::GetLastError(); + crate::xlog_error!( + "D3D12.X: coherent window could not be restored at {base:#x} ({size} bytes, got {got:?}, Windows error {os_error}) after {why}; stopping before guest memory is used" + ); + crate::log::flush(); + windows_sys::Win32::System::Threading::TerminateProcess(windows_sys::Win32::System::Threading::GetCurrentProcess(), 0x7C1_0003); + std::process::abort(); +} + +/// `remake` with `XCL_UMA_DRIVER=mixed:...`: the window as one driver heap per segment +/// (`build_segments`), each mapped for the CPU at its place in the window, and one reserved buffer +/// over the window whose tiles map to the segments' heaps. The CUSTOM segments are write-watched +/// (a segment that refuses it fails the remake); the `GPU_UPLOAD` ones are not, and are read +/// through `read_vram_bytes`. On failure the window is the title's memory again, its pages as they +/// were. +unsafe fn remake_mixed(device: &ID3D12Device, base: usize, size: usize, vram_ranges: &[(usize, usize)]) -> Result { + let t0 = std::time::Instant::now(); + let spec = build_segments(size, vram_ranges)?; + let min_seg = spec.iter().map(|s| s.1).min().unwrap_or(64 << 20); + let pages = written_pages(base, size)?; + let kept: usize = pages.iter().map(|p| p.1.len()).sum(); + if VirtualFree(base as *mut c_void, 0, MEM_RELEASE) == 0 { + return Err(format!("VirtualFree of the window at {base:#x} failed")); + } + let restore = |why: String, placed: Vec<(usize, usize, bool, ID3D12Heap, ID3D12Resource)>, placeholders: Vec| -> String { + for (_, _, _, h, b) in placed { + b.Unmap(0, None); + drop((b, h)); + } + for p in placeholders { + if p != 0 { + VirtualFree(p as *mut c_void, 0, MEM_RELEASE); + } + } + let p = VirtualAlloc(base as *const c_void, size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE); + if p as usize != base { + stop_unbacked(base, size, p, &why); + } + for (a, bytes) in &pages { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), *a as *mut u8, bytes.len()); + } + why + }; + + // every segment's place reserved on its own, so one segment's mapping cannot land in another's + let mut placeholders: Vec = Vec::with_capacity(spec.len()); + for &(off, len, _) in &spec { + let want = base + off; + let p = VirtualAlloc(want as *const c_void, len, MEM_RESERVE, PAGE_NOACCESS); + if p as usize != want { + if !p.is_null() { + VirtualFree(p, 0, MEM_RELEASE); + } + return Err(restore(format!("placeholder reserve at {want:#x} ({} MB) got {p:?}", len >> 20), Vec::new(), placeholders)); + } + placeholders.push(want); + } + + // every free stretch of `min_seg` or more outside the window reserved, but 16 MiB at its start + // for the driver's own small mappings + let groomed = groom_with(base, size, min_seg, (16 << 20).min(min_seg / 4)); + let reservations = groomed.len(); + let readable = |at: usize, len: usize| { + let (mut one, mut n, mut page) = ([std::ptr::null_mut::(); 1], 1usize, 0u32); + GetWriteWatch(0, at as *const c_void, len, one.as_mut_ptr(), &mut n, &mut page) == 0 + }; + let mut placed: Vec<(usize, usize, bool, ID3D12Heap, ID3D12Resource)> = Vec::with_capacity(spec.len()); + let mut fail: Option = None; + for (idx, &(off, len, upload)) in spec.iter().enumerate() { + let want = base + off; + let ph = std::mem::replace(&mut placeholders[idx], 0); + if VirtualFree(ph as *mut c_void, 0, MEM_RELEASE) == 0 { + fail = Some(format!("VirtualFree of the placeholder at {want:#x} failed")); + break; + } + // (no write watch on GPU_UPLOAD: its write-combined pages refuse the watch trap's + // read-only protection, which then retried tens of thousands of times) + let mut made = mapped_segment(device, len, upload, !upload); + let mut upload = upload; + if upload && !matches!(&made, Ok((_, _, p)) if *p == want) { + // a refused GPU_UPLOAD segment becomes a CUSTOM one: the segments mapped so far cannot + // be given back (their mappings stay with the driver), so the window is kept whole + let why = match &made { + Ok((_, _, p)) => format!("Map gave {p:#x}"), + Err(e) => e.clone(), + }; + if let Ok((heap, buf, _)) = std::mem::replace(&mut made, Err(String::new())) { + buf.Unmap(0, None); + drop((buf, heap)); + } + crate::xlog_warn!("D3D12.X: XCL_UMA_DRIVER=mixed: segment {idx} ({} MB GPU_UPLOAD): {why}; it is a CUSTOM write-watched heap instead", len >> 20); + upload = false; + made = mapped_segment(device, len, false, true); + } + let what = if upload { "GPU_UPLOAD" } else { "CUSTOM" }; + match made { + Ok((heap, buf, p)) if p == want && (upload || readable(want, len)) => placed.push((off, len, upload, heap, buf)), + Ok((heap, buf, p)) => { + buf.Unmap(0, None); + drop((buf, heap)); + fail = Some(if p == want { + format!("segment {idx} ({} MB {what}): GetWriteWatch cannot read its mapping", len >> 20) + } else { + format!("segment {idx} ({} MB {what}): Map gave {p:#x}, wanted {want:#x}", len >> 20) + }); + break; + } + Err(e) => { + fail = Some(format!("segment {idx} ({} MB {what}): {e}", len >> 20)); + break; + } + } + } + ungroom(groomed); + if let Some(why) = fail { + return Err(restore(why, placed, placeholders)); + } + + // one reserved buffer over the window, its 64 KiB tiles mapped onto the segments' heaps + let reserved = (|| -> Result { + let mut res: Option = None; + device.CreateReservedResource(&buffer_desc(size), D3D12_RESOURCE_STATE_COMMON, None, &mut res).map_err(|e| format!("CreateReservedResource: {e}"))?; + let res = res.ok_or("CreateReservedResource")?; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .map_err(|e| format!("CreateCommandQueue: {e}"))?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(|e| format!("CreateFence: {e}"))?; + for (off, len, _, heap, _) in &placed { + let count = (*len / TILE) as u32; + let coord = D3D12_TILED_RESOURCE_COORDINATE { X: (*off / TILE) as u32, ..Default::default() }; + let region = D3D12_TILE_REGION_SIZE { NumTiles: count, UseBox: false.into(), ..Default::default() }; + let flag = D3D12_TILE_RANGE_FLAG_NONE; + queue.UpdateTileMappings(&res, 1, Some(&coord), Some(®ion), heap, 1, Some(&flag), Some(&0u32), Some(&count), D3D12_TILE_MAPPING_FLAG_NONE); + } + queue.Signal(&fence, 1).map_err(|e| format!("Signal: {e}"))?; + crate::gpu::fence::wait(&fence, 1, device, None, 2000).map_err(|e| format!("tile mapping wait: {e}"))?; + Ok(res) + })(); + let res = match reserved { + Ok(r) => r, + Err(why) => return Err(restore(why, placed, placeholders)), + }; + + for (a, bytes) in &pages { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), *a as *mut u8, bytes.len()); + } + let mut parts = Vec::with_capacity(placed.len()); + let mut heaps = Vec::with_capacity(placed.len()); + let mut watched = Vec::new(); + let heaps_upload: Vec<(usize, usize)> = placed.iter().filter(|p| p.2).map(|p| (p.0, p.1)).collect(); + for (off, len, upload, heap, placed_buf) in placed { + parts.push(format!("{off:#x}+{}MB {}", len >> 20, if upload { "GPU_UPLOAD" } else { "CUSTOM, write-watched" })); + if !upload { + watched.push((base + off, len)); + } + heaps.push((off, len, heap.into_raw() as usize)); + // the segment's CPU mapping lives as long as its buffer: kept for the process + std::mem::forget(placed_buf); + } + crate::xlog_info!( + "D3D12.X: the coherent window at {base:#x} ({} MB) is mixed driver heaps mapped at its address [{}] ({reservations} reservations, {} pages kept, {} KB, {} ms)", + size >> 20, + parts.join(", "), + pages.len(), + kept >> 10, + t0.elapsed().as_millis() + ); + let vram: Vec<(usize, usize)> = heaps_upload.iter().map(|&(off, len)| (base + off, base + off + len)).collect(); + if !vram.is_empty() { + init_vram_reader(device, base, size, &res, vram); + } + let gpu_va = res.GetGPUVirtualAddress(); + Ok(Remade { buf_raw: res.into_raw() as usize, gpu_va, heaps, watched_regions: Some(watched) }) +} + +static VRAM_READER_ACTIVE: AtomicBool = AtomicBool::new(false); +static VRAM_READER: Mutex> = Mutex::new(None); + +/// Reads the `GPU_UPLOAD` segments of a mixed window by a copy on the GPU into a readback buffer. +struct VramReader { + window_base: usize, + window_end: usize, + vram_ranges: Vec<(usize, usize)>, + device: ID3D12Device, + src_buf: ID3D12Resource, + queue: ID3D12CommandQueue, + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + fence_val: u64, + readback: ID3D12Resource, + readback_ptr: *mut u8, + readback_cap: usize, +} + +unsafe impl Send for VramReader {} + +unsafe fn make_readback(device: &ID3D12Device, cap: usize) -> Result<(ID3D12Resource, *mut u8), String> { + let mut rb: Option = None; + let desc = D3D12_RESOURCE_DESC { Flags: D3D12_RESOURCE_FLAG_NONE, ..buffer_desc(cap) }; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut rb, + ) + .map_err(|e| format!("readback CreateCommittedResource({cap}): {e}"))?; + let rb = rb.ok_or("readback")?; + let mut p: *mut c_void = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).map_err(|e| format!("readback Map: {e}"))?; + Ok((rb, p as *mut u8)) +} + +unsafe fn init_vram_reader(device: &ID3D12Device, window_base: usize, window_size: usize, src_buf: &ID3D12Resource, vram_ranges: Vec<(usize, usize)>) { + let made = (|| -> Result { + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COPY, ..Default::default() }) + .map_err(|e| format!("copy queue: {e}"))?; + let alloc: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY).map_err(|e| format!("copy allocator: {e}"))?; + let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &alloc, None).map_err(|e| format!("copy list: {e}"))?; + list.Close().map_err(|e| format!("copy list Close: {e}"))?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(|e| format!("copy fence: {e}"))?; + let cap = 32 << 20; + let (readback, readback_ptr) = make_readback(device, cap)?; + Ok(VramReader { + window_base, + window_end: window_base + window_size, + vram_ranges, + device: device.clone(), + src_buf: src_buf.clone(), + queue, + alloc, + list, + fence, + fence_val: 0, + readback, + readback_ptr, + readback_cap: cap, + }) + })(); + match made { + Ok(r) => { + *VRAM_READER.lock().unwrap() = Some(r); + VRAM_READER_ACTIVE.store(true, Ordering::Release); + } + Err(e) => crate::xlog_warn!("D3D12.X: no GPU reader for the mixed window's GPU_UPLOAD segments ({e}): they are read through the BAR"), + } +} + +/// `[at, at + len)` read by a copy on the GPU (`CopyBufferRegion` to a readback buffer) where it +/// overlaps a `GPU_UPLOAD` segment of a mixed window: CPU reads of that video memory through the +/// BAR ran at 12-84 MiB/s. None where it does not. +pub(super) unsafe fn read_vram_bytes(at: usize, len: usize) -> Option> { + if len == 0 || !VRAM_READER_ACTIVE.load(Ordering::Acquire) { + return None; + } + let mut g = VRAM_READER.lock().unwrap(); + let r = g.as_mut()?; + let end = at.checked_add(len)?; + if at < r.window_base || end > r.window_end || !r.vram_ranges.iter().any(|&(s, e)| at < e && end > s) { + return None; + } + if len > r.readback_cap { + let cap = len.next_power_of_two().max(32 << 20); + let (rb, ptr) = make_readback(&r.device, cap).ok()?; + r.readback.Unmap(0, None); + r.readback = rb; + r.readback_ptr = ptr; + r.readback_cap = cap; + } + r.alloc.Reset().ok()?; + r.list.Reset(&r.alloc, None).ok()?; + r.list.CopyBufferRegion(&r.readback, 0, &r.src_buf, (at - r.window_base) as u64, len as u64); + r.list.Close().ok()?; + let cl: ID3D12CommandList = r.list.cast().ok()?; + r.queue.ExecuteCommandLists(&[Some(cl)]); + r.fence_val += 1; + r.queue.Signal(&r.fence, r.fence_val).ok()?; + crate::gpu::fence::wait(&r.fence, r.fence_val, &r.device, None, 5000).ok()?; + let mut out = vec![0u8; len]; + std::ptr::copy_nonoverlapping(r.readback_ptr, out.as_mut_ptr(), len); + Some(out) } #[cfg(test)] mod tests { - use super::decide; + use super::{build_segments, decide, parse_mixed}; + + /// The tests that remake a mixed window run one at a time: a remake reserves the process's other + /// free stretches so that the driver maps each segment at its place, and another remake releasing + /// its reservations meanwhile lets a segment land elsewhere, which stops the process. + static MIXED_REMAKE: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// On by default for NVIDIA outside Wine only; the switch overrides either way. #[test] @@ -242,6 +706,130 @@ mod tests { assert!(!decide(Some("0"), || false, || Some(0x10DE))); assert!(decide(Some("custom"), || true, || Some(0x1002))); assert!(decide(Some(" 1 "), || false, || None)); + assert!(decide(Some("mixed:1536:1792"), || true, || Some(0x1002))); + } + + #[test] + fn mixed_ranges_parse_in_order() { + assert_eq!(parse_mixed("mixed:1536:1792"), Some(vec![(1536 << 20, 1792 << 20)])); + assert_eq!(parse_mixed(" mixed:2048:512,512:256 "), Some(vec![(512 << 20, 256 << 20), (2048 << 20, 512 << 20)])); + assert_eq!(parse_mixed("mixed:0:0"), None); + assert_eq!(parse_mixed("mixed:12"), None); + assert_eq!(parse_mixed("custom"), None); + } + + #[test] + fn mixed_segments_cover_the_window() { + let segs = build_segments(4095 << 20, &[(1536 << 20, 1792 << 20)]).unwrap(); + assert_eq!(segs, vec![(0, 1536 << 20, false), (1536 << 20, 1792 << 20, true), (3328 << 20, 767 << 20, false)]); + assert!(build_segments(256 << 20, &[(512 << 20, 64 << 20)]).is_err()); + assert!(build_segments(256 << 20, &[(0, 128 << 20), (64 << 20, 64 << 20)]).is_err()); + } + + /// A mixed window keeps the title's bytes in every segment, and the GPU reads the CPU's later + /// writes to each segment through the one reserved buffer; `read_vram_bytes` reads only the + /// `GPU_UPLOAD` segment. + #[test] + fn mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment() { + use super::*; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + let _alone = MIXED_REMAKE.lock().unwrap_or_else(|e| e.into_inner()); + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + return crate::gpu::recomp::runner::skip_test("no D3D12 device"); + } + let dev = dev.unwrap(); + if !unsafe { gpu_upload_heaps(&dev) } { + return crate::gpu::recomp::runner::skip_test("no GPU_UPLOAD heaps"); + } + unsafe { + let size = 256 << 20; + let base = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + let at = [0x1000, (64 << 20) + 0x1000, (192 << 20) + 0x1000]; + for (i, &o) in at.iter().enumerate() { + std::ptr::write_volatile((base + o) as *mut u32, 0x1111_0000 + i as u32); + } + let remade = match remake_mixed(&dev, base, size, &[(64 << 20, 128 << 20)]) { + Ok(r) => r, + Err(e) if e.contains("CreateHeap") => return crate::gpu::recomp::runner::skip_test("no GPU_UPLOAD heaps"), + Err(e) => panic!("remake_mixed: {e}"), + }; + assert_eq!(remade.heaps.len(), 3); + assert_eq!(remade.watched_regions, Some(vec![(base, 64 << 20), (base + (192 << 20), 64 << 20)])); + for (i, &o) in at.iter().enumerate() { + assert_eq!(std::ptr::read_volatile((base + o) as *const u32), 0x1111_0000 + i as u32); + std::ptr::write_volatile((base + o + 0x1000) as *mut u32, 0xCAFE_0000 + i as u32); + } + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let (rb, ptr) = make_readback(&dev, 256).unwrap(); + let raw = remade.buf_raw as *mut c_void; + let src = ID3D12Resource::from_raw_borrowed(&raw).unwrap(); + for (i, &o) in at.iter().enumerate() { + list.CopyBufferRegion(&rb, 4 * i as u64, src, (o + 0x1000) as u64, 4); + } + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 2000).unwrap(); + assert_eq!(std::slice::from_raw_parts(ptr as *const u32, 3), &[0xCAFE_0000, 0xCAFE_0001, 0xCAFE_0002]); + assert!(read_vram_bytes(base + at[0] + 0x1000, 4).is_none()); + let got = read_vram_bytes(base + at[1] + 0x1000, 4).expect("read of the GPU_UPLOAD segment"); + assert_eq!(u32::from_le_bytes(got.try_into().unwrap()), 0xCAFE_0001); + } + } + + /// A `GPU_UPLOAD` segment refused after a CUSTOM one was mapped (an adapter without Resizable + /// BAR, or one out of BAR space): the window stays whole, that segment a write-watched CUSTOM + /// heap. (It stopped the process: the mapped segment's pages stay with the driver after its + /// heap is dropped, so the window could not be reserved again.) + #[test] + fn a_refused_gpu_upload_segment_becomes_custom() { + use super::*; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + let _alone = MIXED_REMAKE.lock().unwrap_or_else(|e| e.into_inner()); + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + return crate::gpu::recomp::runner::skip_test("no D3D12 device"); + } + let dev = dev.unwrap(); + unsafe { + let size = 256 << 20; + let base = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + let at = [0x1000, (64 << 20) + 0x1000, (192 << 20) + 0x1000]; + for (i, &o) in at.iter().enumerate() { + std::ptr::write_volatile((base + o) as *mut u32, 0x2222_0000 + i as u32); + } + REFUSE_GPU_UPLOAD.with(|r| r.set(true)); + let remade = remake_mixed(&dev, base, size, &[(64 << 20, 128 << 20)]); + REFUSE_GPU_UPLOAD.with(|r| r.set(false)); + let remade = remade.expect("remake_mixed with the GPU_UPLOAD segment refused"); + assert_eq!(remade.heaps.len(), 3); + assert_eq!(remade.watched_regions, Some(vec![(base, 64 << 20), (base + (64 << 20), 128 << 20), (base + (192 << 20), 64 << 20)])); + for (i, &o) in at.iter().enumerate() { + assert_eq!(std::ptr::read_volatile((base + o) as *const u32), 0x2222_0000 + i as u32); + std::ptr::write_volatile((base + o + 0x1000) as *mut u32, 0xBEEF_0000 + i as u32); + } + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let (rb, ptr) = make_readback(&dev, 256).unwrap(); + let raw = remade.buf_raw as *mut c_void; + let src = ID3D12Resource::from_raw_borrowed(&raw).unwrap(); + for (i, &o) in at.iter().enumerate() { + list.CopyBufferRegion(&rb, 4 * i as u64, src, (o + 0x1000) as u64, 4); + } + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 2000).unwrap(); + assert_eq!(std::slice::from_raw_parts(ptr as *const u32, 3), &[0xBEEF_0000, 0xBEEF_0001, 0xBEEF_0002]); + } } #[test] diff --git a/crates/xcl/src/hle/d3d12x/view_want.rs b/crates/xcl/src/hle/d3d12x/view_want.rs new file mode 100644 index 0000000000..f51345ff55 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/view_want.rs @@ -0,0 +1,312 @@ +//! The title's GPU view of its own memory, as the GPU is told about it. +//! +//! A retail title reserves two ranges for the same physical pages: one the CPU reads and writes, +//! and a GPU view the CPU cannot touch (`kernelx::mirrors`). It gives the GPU only addresses in +//! the GPU view: buffer views made by address, root views, vertex and index buffers, the +//! operands of memory operations. With the 16-window layout that view lies in view windows +//! (`Uma::is_view`), whose 64 KiB tiles get video memory, filled from the CPU's range, when an +//! address in them is first used (`sparse::map_mirror`). +//! +//! Every path that takes such an address from the title calls `want` with what it knows of the +//! range. The counters say which paths a title uses and how much of the view each asks for. + +use std::cell::Cell; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// The paths a GPU-view address reaches the GPU by. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Path { + /// a buffer view made by address (device #70 / #71) + ViewAt = 0, + /// a constant buffer view + Cbv, + /// a view of a buffer resource placed in the view + BufferView, + /// a buffer resource placed in the view + PlacedBuffer, + /// a root CBV / SRV / UAV (its size is not known) + RootView, + /// a vertex or index buffer + VertexIndex, + /// a memory operation of the list (copy, fill, write, timestamps, predication) + MemoryOp, + /// a wait on a value in memory + Wait, + /// a file read into the view + FileRead, + /// a Map of a resource in the view + MapRead, + /// a GPU copy or query resolve into a buffer in the view + CopyInto, + /// a root view of a two-pass mesh stage + MeshStage, + /// an acceleration-structure view (asked for from its root on: its size is not known) + Bvh, +} + +const PATHS: usize = 13; +const NAMES: [&str; PATHS] = [ + "views by address", + "constant buffer views", + "buffer views", + "placed buffers", + "root views", + "vertex / index buffers", + "memory operations", + "waits", + "file reads", + "maps", + "copies into it", + "mesh stage views", + "acceleration-structure views", +]; + +#[allow(clippy::declare_interior_mutable_const)] +const ZERO: AtomicU64 = AtomicU64::new(0); +static CALLS: [AtomicU64; PATHS] = [ZERO; PATHS]; +static BYTES: [AtomicU64; PATHS] = [ZERO; PATHS]; + +/// Tile spans a thread remembers having asked for (`asked_lately`). +const LATELY: usize = 32; +/// The tiles of a view window (64 KiB, `sparse::map_mirror`) +const TILE_SHIFT: u32 = 16; +/// An empty place of `ASKED`: a span no other is inside +const NO_SPAN: (u64, u64) = (u64::MAX, 0); + +thread_local! { + /// The tile spans (first and last 64 KiB tile) this thread asked for last, the generation + /// they were asked in (`generation`: of the GPU views and of the asks forgotten since) and + /// where the next one goes. A title binds the same vertex buffers and root views for draw after draw, on the + /// thread that records the list, and root views at a new offset of the same tiles (a + /// constant allocator moving on for each draw); asking again walks every tile of the range + /// (`sparse::map_mirror`: a shared set). + static ASKED: Cell<([(u64, u64); LATELY], (u64, u64), usize)> = const { Cell::new(([NO_SPAN; LATELY], (0, 0), 0)) }; +} + +/// What an ask is remembered under: the GPU views as they are (`kernelx::gpu_view_map_gen`) and +/// the asks `sparse` has forgotten so far (`sparse::mirror_asks_forgotten`). A tile given back +/// when the title decommits its source may be asked for again, and must be when the title +/// commits and binds that memory again: a thread that still remembered asking for it left the +/// tile unmapped, and the draw read zeros through the view (a mesh without vertices). +pub(super) fn generation() -> (u64, u64) { + (crate::hle::kernelx::gpu_view_map_gen(), super::sparse::mirror_asks_forgotten()) +} + +/// Whether every tile of `[va, va + len)` lies in one of the tile spans this thread asked for +/// last (`LATELY` of them) in this `generation`; its span is remembered if not. A view that went +/// or came since, or an ask forgotten since, empties the memory. A range reaching one tile past +/// what was asked for is not in it. +fn asked_lately(va: u64, len: u64, generation: (u64, u64)) -> bool { + let span = (va >> TILE_SHIFT, va.saturating_add(len.saturating_sub(1)) >> TILE_SHIFT); + ASKED.with(|a| { + let (mut spans, asked_in, mut next) = a.get(); + if asked_in != generation { + (spans, next) = ([NO_SPAN; LATELY], 0); + } else if spans.iter().any(|&(first, last)| first <= span.0 && span.1 <= last) { + return true; + } + spans[next] = span; + a.set((spans, generation, (next + 1) % LATELY)); + false + }) +} + +/// Whether `va` lies in a view window (false without the 16-window layout). +pub fn is_view(va: u64) -> bool { + crate::gpu::uma::get().is_some_and(|u| u.is_view(va as usize)) +} + +/// The title gave `[va, va + len)` to the GPU on `path`: when it lies in a view window its +/// tiles are asked for (mapped and filled from the CPU's range at the next submit). True when +/// it was a view address. +pub fn want(path: Path, va: u64, len: u64) -> bool { + if va == 0 || len == 0 || !is_view(va) { + return false; + } + let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewWant); + CALLS[path as usize].fetch_add(1, Ordering::Relaxed); + let len = reach(path, va, len); + if !asked_lately(va, len, generation()) { + let queued = super::sparse::map_mirror(va as usize, len as usize) as u64; + if queued != 0 { + BYTES[path as usize].fetch_add(queued << TILE_SHIFT, Ordering::Relaxed); + } + } + true +} + +/// `XCL_VIEW_REACH_MB=n` (an experiment): a view whose size the title does not give – a root +/// view, a mesh stage's root view, an acceleration structure – is asked for `n` MiB from its +/// address on instead of 64 KiB, as far as that still lies in a view window. Tiles whose CPU +/// pages are not committed get no video memory (`sparse::fill_later`), so the cost is what the +/// title really has there. Off (0) by default. +fn reach(path: Path, va: u64, len: u64) -> u64 { + static MB: std::sync::OnceLock = std::sync::OnceLock::new(); + let mb = *MB.get_or_init(|| { + let mb = std::env::var("XCL_VIEW_REACH_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0).min(4096); + if mb != 0 { + crate::xlog_info!("D3D12.X: XCL_VIEW_REACH_MB: root views, mesh stage views and acceleration structures are asked for {mb} MiB from their address on"); + } + mb + }); + // `XCL_VIEW_REACH=bvh,root,mesh`: only those kinds (all three without it) + static KINDS: std::sync::OnceLock<[bool; 3]> = std::sync::OnceLock::new(); + let kinds = KINDS.get_or_init(|| match std::env::var("XCL_VIEW_REACH") { + Ok(v) => ["bvh", "root", "mesh"].map(|k| v.split(',').any(|x| x.trim().eq_ignore_ascii_case(k))), + Err(_) => [true; 3], + }); + let sizeless = match path { + Path::Bvh => kinds[0], + Path::RootView => kinds[1], + Path::MeshStage => kinds[2], + _ => false, + }; + longer(sizeless, mb, len, |end| is_view(va.saturating_add(end - 1))) +} + +/// `len`, or `mb` MiB when that is more, the path has no size (`sizeless`) and the last byte +/// of the longer range is still in a view window (`in_view`, by the length). +fn longer(sizeless: bool, mb: u64, len: u64, in_view: impl Fn(u64) -> bool) -> u64 { + let want = mb << 20; + if sizeless && want > len && in_view(want) { want } else { len } +} + +/// The CPU address behind `va` (itself unless `va` lies in a GPU view of the title's memory, +/// in a view window or not: `sparse::cpu_of` asks `kernelx::mirrors`, a lock). Callers on a hot +/// path ask `is_view` first. +pub fn cpu(va: u64) -> u64 { + super::sparse::cpu_of(va as usize) as u64 +} + +/// The CPU address behind `[va, va + len)` (`cpu`) when the range is one piece there: every later +/// 64 KiB page of it lies right behind the first (`cpu(b) == cpu(va) + (b - va)` at each page +/// boundary `b`). None when its pages are kept apart (the queue's page mappings, +/// `kernelx::mirrors`) or one of them lies outside the GPU view. +pub fn cpu_run(va: u64, len: u64) -> Option { + let end = va.checked_add(len)?; + let c = cpu(va); + let mut b = (va | ((1 << TILE_SHIFT) - 1)).checked_add(1)?; + while b < end { + if cpu(b) != c.wrapping_add(b - va) { + return None; + } + b = b.checked_add(1 << TILE_SHIFT)?; + } + Some(c) +} + +/// (calls, bytes asked for) of each path so far: the 64 KiB tiles each path asked for first +/// (`sparse::map_mirror` queued them), not the length of every range given. +pub fn totals() -> [(u64, u64); PATHS] { + std::array::from_fn(|i| (CALLS[i].load(Ordering::Relaxed), BYTES[i].load(Ordering::Relaxed))) +} + +/// What was asked for between two `totals`: the paths with calls, for the periodic log line. +pub fn line(now: &[(u64, u64); PATHS], before: &[(u64, u64); PATHS]) -> Option { + let parts: Vec = (0..PATHS) + .filter(|&i| now[i].0 > before[i].0) + .map(|i| format!("{} {} ({} KB new)", now[i].0 - before[i].0, NAMES[i], (now[i].1 - before[i].1) >> 10)) + .collect(); + (!parts.is_empty()).then(|| parts.join(", ")) +} + +#[cfg(test)] +mod reach_tests { + /// Only a view without a size reaches further, only when asked to, and never past the + /// view window it is in. + #[test] + fn a_sizeless_view_reaches_further_inside_its_window_only() { + let all = |_: u64| true; + assert_eq!(super::longer(true, 0, 0x1_0000, all), 0x1_0000, "off"); + assert_eq!(super::longer(true, 64, 0x1_0000, all), 64 << 20); + assert_eq!(super::longer(false, 64, 0x1_0000, all), 0x1_0000, "a view with a size keeps it"); + assert_eq!(super::longer(true, 1, 8 << 20, all), 8 << 20, "never shorter"); + assert_eq!(super::longer(true, 64, 0x1_0000, |end| end <= 32 << 20), 0x1_0000, "past the window"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The line names only the paths used since the totals before, with their new bytes. + #[test] + fn the_line_names_the_paths_used_since() { + let mut before = [(0u64, 0u64); PATHS]; + let mut now = before; + assert_eq!(line(&now, &before), None, "nothing asked for: no line"); + now[Path::ViewAt as usize] = (3, 3 << 20); + now[Path::RootView as usize] = (1, 65536); + assert_eq!(line(&now, &before).as_deref(), Some("3 views by address (3072 KB new), 1 root views (64 KB new)")); + before = now; + now[Path::RootView as usize] = (2, 65536); + assert_eq!(line(&now, &before).as_deref(), Some("1 root views (0 KB new)"), "a range asked for again adds a call, no bytes"); + assert_eq!(NAMES[Path::Bvh as usize], "acceleration-structure views"); + } + + /// An address outside a view window (every address without the 16-window layout, and null) + /// asks for nothing and is not counted. + #[test] + fn an_address_outside_the_views_asks_for_nothing() { + let before = totals(); + assert!(!want(Path::Cbv, 0, 256)); + assert!(!want(Path::Cbv, 0x1000, 0)); + assert_eq!(totals(), before); + } + + /// A thread that asks for the same range again (a vertex buffer bound for every draw), or + /// for another range in tiles it asked for (a root view at the next offset of a constant + /// allocator), does not walk its tiles again; a range reaching a tile it did not ask for, a + /// span pushed out by `LATELY` later ones, and GPU views that changed since make it ask again. + #[test] + fn a_range_asked_for_lately_is_not_asked_for_again() { + std::thread::spawn(|| { + const A: u64 = 0x14_0000_1000; + assert!(!asked_lately(A, 0x2000, (7, 0)), "the first time"); + assert!(asked_lately(A, 0x2000, (7, 0)), "again: remembered"); + assert!(asked_lately(0x14_0000_8000, 0x4000, (7, 0)), "another range in the same tile"); + assert!(asked_lately(0x14_0000_0000, 0x1_0000, (7, 0)), "the whole tile"); + assert!(!asked_lately(0x14_0000_8000, 0x1_0000, (7, 0)), "a range reaching the next tile"); + assert!(asked_lately(0x14_0001_0000, 0x100, (7, 0)), "the next tile was asked for with it"); + assert!(asked_lately(0x14_0000_0000, 0x2_0000, (7, 0)), "both tiles"); + assert!(!asked_lately(0x14_0000_0000, 0x2_0001, (7, 0)), "and one byte of a third"); + assert!(!asked_lately(A, 0x2000, (8, 0)), "the views changed: asked again"); + for k in 0..LATELY as u64 - 1 { + assert!(!asked_lately(0x15_0000_0000 + (k << 16), 0x1000, (8, 0))); + } + assert!(asked_lately(A, 0x2000, (8, 0)), "{LATELY} spans are remembered"); + assert!(!asked_lately(0x16_0000_0000, 0x1000, (8, 0))); + assert!(!asked_lately(A, 0x2000, (8, 0)), "pushed out by {LATELY} later spans"); + assert!(asked_lately(A, 0x2000, (8, 0))); + // a tile given back since (its source decommitted) may be asked for again: every + // remembered ask goes, also the ones whose tiles stayed + assert!(!asked_lately(A, 0x2000, (8, 1)), "an ask was forgotten: asked again"); + assert!(asked_lately(A, 0x2000, (8, 1))); + assert!(!asked_lately(A, 0x2000, (8, 2))); + }) + .join() + .unwrap(); + } + + /// A range of a GPU view is its CPU view's range while the view's pages show the CPU view at + /// the same offset; a range running past the view's end is not one piece. + #[test] + fn a_range_in_a_gpu_view_is_one_piece_only_while_its_pages_are() { + use crate::hle::kernelx::mirrors; + const SIZE: usize = 157 << 16; + // (addresses far above anything Windows hands out: only the pairing is used) + let (c, g) = (0x72C0_0000_0000u64, 0x72C8_0000_0000u64); + mirrors::reserved(c as usize, SIZE, 0x2040_2000, 0x04); + assert!(mirrors::reserved(g as usize, SIZE, 0x2040_2000, 0x801)); + assert_eq!(cpu_run(g + 0x1_2340, 0x100), Some(c + 0x1_2340), "inside one page"); + assert_eq!(cpu_run(g + 0x1_fff0, 0x5_0000), Some(c + 0x1_fff0), "across five page boundaries"); + assert_eq!(cpu_run(g, SIZE as u64), Some(c), "the whole view"); + assert_eq!(cpu_run(g + 0x40, 0), Some(c + 0x40)); + assert_eq!(cpu_run(g + SIZE as u64 - 0x100, 0x100), Some(c + SIZE as u64 - 0x100)); + assert_eq!(cpu_run(g + SIZE as u64 - 0x100, 0x101), None, "past the view's end"); + assert_eq!(cpu_run(g - 0x10, 0x20), None, "from before the view into it"); + assert_eq!(cpu_run(u64::MAX - 0x10, 0x20), None, "past the end of the address space"); + mirrors::released(c as usize); + assert_eq!(cpu_run(g + 0x1_fff0, 0x20), Some(g + 0x1_fff0), "unpaired: the address itself"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 9c7bc5e358..7cf0d35835 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -735,6 +735,7 @@ fn forget_resource_backing(resource: usize) { if let Some(id) = ARENA_OF.lock().unwrap().as_mut().and_then(|m| m.remove(&resource)) { ARENAS.lock().unwrap().release(id, std::time::Instant::now()); } + super::placements::released(resource); } } @@ -1179,6 +1180,9 @@ struct TilePool { free_total: usize, /// Tiles given back, reusable after `COOL`. cooling: std::collections::VecDeque<(Tile, std::time::Instant)>, + /// Whether heap index h has a heap (false: reclaimed by `reclaim_empty_heaps`, its slot free + /// for the next `add_heap_at`). + live: Vec, } impl TilePool { @@ -1189,6 +1193,7 @@ impl TilePool { heap_evictable: Vec::new(), free_total: 0, cooling: std::collections::VecDeque::new(), + live: Vec::new(), } } @@ -1197,11 +1202,13 @@ impl TilePool { if idx >= self.free_by_heap.len() { self.free_by_heap.resize_with(idx + 1, Vec::new); self.dirty_sort.resize(idx + 1, false); + self.live.resize(idx + 1, false); self.heap_evictable.resize(idx + 1, false); } debug_assert!(self.free_by_heap[idx].is_empty()); self.free_by_heap[idx] = (0..pool_pages).rev().collect(); self.dirty_sort[idx] = false; + self.live[idx] = true; self.heap_evictable[idx] = evictable; self.free_total += pool_pages as usize; } @@ -1209,12 +1216,14 @@ impl TilePool { /// Reclaim completely empty cooled heaps (`free_by_heap[h].len() == pool_pages`), keeping up /// to `keep_spare` empty heaps of each class warm so steady-state streaming never thrashes `CreateHeap`. /// Returns the reclaimed heap indices so the caller can drop their `ID3D12Heap`s. + /// No tile of a reclaimed heap is handed out after this (`live`): a page still mapped onto + /// one would be a page of whatever heap takes its slot next. fn reclaim_empty_heaps(&mut self, keep_spare: usize, pool_pages: u32) -> Vec { let full = pool_pages as usize; let mut kept = [0usize; 2]; let mut reclaimed = Vec::new(); for h in 0..self.free_by_heap.len() { - if self.free_by_heap[h].len() != full { + if !self.live[h] || self.free_by_heap[h].len() != full { continue; } let class = self.heap_evictable[h] as usize; @@ -1225,6 +1234,7 @@ impl TilePool { self.free_by_heap[h].clear(); self.free_by_heap[h].shrink_to_fit(); self.dirty_sort[h] = false; + self.live[h] = false; self.heap_evictable[h] = false; self.free_total -= full; reclaimed.push(h as u32); @@ -1242,7 +1252,7 @@ impl TilePool { while self.cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { let Some(((h, t), _)) = self.cooling.pop_front() else { break }; let idx = h as usize; - if idx < self.free_by_heap.len() { + if idx < self.free_by_heap.len() && self.live[idx] { self.free_by_heap[idx].push(t); self.dirty_sort[idx] = true; self.free_total += 1; @@ -1253,7 +1263,7 @@ impl TilePool { fn return_tiles(&mut self, tiles: &[Tile]) { for &(h, t) in tiles { let idx = h as usize; - if idx < self.free_by_heap.len() { + if idx < self.free_by_heap.len() && self.live[idx] { self.free_by_heap[idx].push(t); self.dirty_sort[idx] = true; self.free_total += 1; @@ -1398,6 +1408,11 @@ impl PoolHeaps { self.free_slots.push(idx); Some(h) } + + /// The live heap at `idx` (None: reclaimed or never made). + fn get(&self, idx: usize) -> Option<&ID3D12Heap> { + self.slots.get(idx).and_then(Option::as_ref) + } } impl std::ops::Index for PoolHeaps { @@ -1426,6 +1441,9 @@ struct HeldUnmap { level_tiles: Vec<(Vec, Vec<(usize, usize)>)>, /// Completion marks for every relevant title or upload queue. marks: Vec<(ID3D12Fence, u64)>, + /// Its pages cool at once (`unmap_superseded`), or stay for `IDLE` with what they hold + /// (`unmap_superseded_target`). + immediate_cool: bool, } fn all_marks_complete(marks: &[(F, u64)], mut completed: impl FnMut(&F) -> u64) -> bool { @@ -1440,6 +1458,7 @@ struct Pages { value: u64, /// per-device timestamp of the last periodic reclaim check last_reclaim: std::time::Instant, + /// pool heaps by `Tile` index (a reclaimed one's slot is empty, as `TilePool::live` has it) pools: PoolHeaps, pool: TilePool, /// title page address → its video memory @@ -1652,6 +1671,8 @@ impl Pages { self.scratch_heaps.dedup(); for i in 0..self.scratch_heaps.len() { let h = self.scratch_heaps[i]; + // (a tile is only ever of a heap the pool has: `TilePool::reclaim_empty_heaps`) + let Some(heap) = self.pools.get(h as usize) else { continue }; let ranges = heap_ranges_trimmed(h, tiles); if ranges.is_empty() { continue; @@ -1673,7 +1694,7 @@ impl Pages { 1, Some(&coord), Some(®ion), - &self.pools[h as usize], + heap, ranges.len() as u32, Some(self.scratch_flags.as_ptr()), Some(self.scratch_offsets.as_ptr()), @@ -1688,10 +1709,16 @@ impl Pages { /// Unmap every tile of `res` (`D3D12_TILE_RANGE_FLAG_NULL`) so its unshared tiles can return /// to the pool even while the title keeps the COM object alive. unsafe fn unmap(&mut self, res: &ID3D12Resource, total: u32) { + self.unmap_range(res, 0, total); + } + + /// `unmap` for the `n` tiles of `res` from the first one of subresource `sub` on. + unsafe fn unmap_range(&mut self, res: &ID3D12Resource, sub: u32, n: u32) { + let total = n; if total == 0 { return; } - let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let coord = D3D12_TILED_RESOURCE_COORDINATE { Subresource: sub, ..Default::default() }; let region = D3D12_TILE_REGION_SIZE { NumTiles: total, UseBox: false.into(), ..Default::default() }; let flag = D3D12_TILE_RANGE_FLAG_NULL; self.queue.UpdateTileMappings( @@ -1782,9 +1809,9 @@ impl Pages { } } self.unmap(&held.res, held.total); - self.release_tiles(held.used, held.used_extra, now, true); + self.release_tiles(held.used, held.used_extra, now, held.immediate_cool); for (used, used_extra) in held.level_tiles { - self.release_tiles(used, used_extra, now, true); + self.release_tiles(used, used_extra, now, held.immediate_cool); } done.push(held.res); } else { @@ -1918,7 +1945,8 @@ unsafe fn held_unmap_completions(dev_key: usize) -> Vec<(ID3D12Fence, u64)> { fences.sort_unstable_by_key(|fence| fence.as_raw() as usize); fences.dedup_by_key(|fence| fence.as_raw() as usize); fences.into_iter().map(|fence| { - let value = fence.GetCompletedValue(); + // (XCL's own fences, without the title's hook) + let value = super::real::fence_completed(&fence); (fence, value) }).collect() } @@ -1996,7 +2024,7 @@ unsafe fn reservable(dev: &ID3D12Device, desc: &D3D12_RESOURCE_DESC) -> bool { /// shared 64 KiB VRAM pages and arenas alias instead of duplicating video memory. If distinct /// physical or committed pages are mapped directly at `va`, keep `va` unaliased (matching /// `title_textures::mirror_source`). -fn canonical_va(va: usize) -> usize { +pub(super) fn canonical_va(va: usize) -> usize { let Some(src) = crate::hle::kernelx::mirrors::source(va) else { return va }; if crate::hle::kernelx::physical_page_at(va) { return va; @@ -2095,6 +2123,12 @@ unsafe fn place_on_pages( return None; } PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); + let (first, own) = owned_pages(va, console_bytes, total as usize).unwrap_or((va, 0)); + let kind = if gpu_owned(desc.Flags.0 as u32) { super::placements::Kind::Target } else { super::placements::Kind::Sampled }; + // (the older targets it supersedes leave the shared pages once the work before is done) + for r in super::placements::placed(raw as usize, va, (first, first + own * PAGE), super::placements::Backing::Pages(dev_key), kind, desc) { + super::late_release::hold_unmap(r); + } Some(hr) } @@ -2102,6 +2136,17 @@ unsafe fn place_on_pages( /// Polling completion on the CPU avoids a dependency from the mapping queue back to a title queue, /// which may itself already be waiting for later mapping work. pub(super) unsafe fn unmap_superseded(res: &ID3D12Resource) { + unmap_placed(res, true); +} + +/// `unmap_superseded` for a target superseded by a newer placement over other pages of it +/// (`placements`): its pages no other texture uses stay for `IDLE` with what they hold, as a +/// released target's do – the title may use it again, and it then gets them back. +pub(super) unsafe fn unmap_superseded_target(res: &ID3D12Resource) { + unmap_placed(res, false); +} + +unsafe fn unmap_placed(res: &ID3D12Resource, immediate_cool: bool) { let mut dev: Option = None; if res.GetDevice(&mut dev).is_err() { return; @@ -2130,6 +2175,7 @@ pub(super) unsafe fn unmap_superseded(res: &ID3D12Resource) { used_extra: std::mem::take(&mut target.used_extra), level_tiles: take_level_tiles(target.levels.as_mut()), marks, + immediate_cool, }; target.mapped = false; pages.held_unmaps.push(held); @@ -2356,7 +2402,10 @@ unsafe fn collect_device_queues(dev_key: usize, extra: Option<&ID3D12CommandQueu } /// Retire `newly_reclaimed` across all live queues on `dev_key`, sweep completed batches, and prune -/// dead-queue fences; drops every finished `ID3D12Heap` and `ID3D12Fence` outside all locks. +/// dead-queue fences; drops every finished `ID3D12Fence` outside all locks. The finished heaps +/// go as a resource the title released does (`late_release::hold_heap`), outside all locks too: +/// a texture the title released may still map pages of one, and is held there until the work +/// queued before its release is done – a heap gone under that work is a page fault of the GPU. unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_reclaimed: Vec, unmap_mark: Option<(ID3D12Fence, u64)>, extra_queue: Option<&ID3D12CommandQueue>) { let queues = collect_device_queues(dev_key, extra_queue); let live_keys: HashSet = queues.iter().map(|&(k, _)| k).collect(); @@ -2379,7 +2428,8 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla probes.sort_unstable_by_key(|fence| fence.as_raw() as usize); probes.dedup_by_key(|fence| fence.as_raw() as usize); let observed: Vec<_> = probes.into_iter().map(|fence| { - let completed = fence.GetCompletedValue(); + // (XCL's own fences, without the title's hook) + let completed = super::real::fence_completed(&fence); (fence, completed) }).collect(); let (done, pruned) = { @@ -2389,7 +2439,12 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla }) }; RETIRING_BATCHES.fetch_sub(done.len(), std::sync::atomic::Ordering::AcqRel); - drop((immediate, done, pruned, observed)); + // (the finished heaps go as a resource the title released does: a texture the title released + // may still map pages of one until the work queued before its release is done) + for heap in immediate.into_iter().chain(done.into_iter().flat_map(|b| b.heaps)) { + super::late_release::hold_heap(heap); + } + drop((pruned, observed)); } /// Before GPU work on `queue`: have it wait for every tile mapping made so far on its device, @@ -2581,6 +2636,30 @@ pub(super) fn tile_mappings_for(device: usize, resource: usize) -> Option<(Vec<( } /// (bytes of pages in use by tiled textures, bytes of pool heaps) – `XCL_ACTIVITY` +/// Who holds the target pages, for the activity log: the textures on them by kind, the pages +/// they stand for (shared pages count once for each texture on them) and the pages no texture +/// uses any more that wait to go back to the pools (`sweep_idle`). +pub fn page_owners() -> String { + let g = PAGES.lock().unwrap(); + // (with every page, with pages by level): textures, pages held + let mut kinds = [(0usize, 0usize); 2]; + let (mut pages, mut idle) = (0usize, 0usize); + for p in g.values().flatten() { + pages += p.pages.len() + p.extra_pages.len(); + idle += p.idle.len(); + for t in p.targets.values() { + let k = if t.levels.is_none() { 0 } else { 1 }; + kinds[k].0 += 1; + kinds[k].1 += t.used.len() + t.used_extra.len(); + } + } + let mb = |n: usize| n * PAGE >> 20; + format!( + "target pages by owner: {} textures with all their pages hold {} MB, {} sampled textures with pages by level hold {} MB (a shared page counts for each); {} MB of pages in all, {} MB of them idle", + kinds[0].0, mb(kinds[0].1), kinds[1].0, mb(kinds[1].1), mb(pages), mb(idle) + ) +} + pub fn page_bytes() -> (usize, usize) { let g = PAGES.lock().unwrap(); g.values().flatten().fold((0, 0), |(used, pools), p| { @@ -2617,6 +2696,12 @@ pub unsafe fn place_pages( } // (one slice: the tiles of an array's packed levels are not asked about here) let lazy = level_pages() && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.DepthOrArraySize == 1 && desc.SampleDesc.Count == 1 && desc.Flags == D3D12_RESOURCE_FLAG_NONE; + // (as `place`: without a size every PC tile went on the title's pages from `va` on) + let console_bytes = console_bytes.or_else(|| { + let least = least_texture_bytes(desc); + note_unknown_size(desc, least); + least + }); place_on_pages(dev, this, va, desc, state, clear, console_bytes, false, lazy, riid, ppv) } @@ -2675,6 +2760,61 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> Vec::new() } +/// The levels `zero` of `res` hold no texels now: the title took the memory from under them, as +/// a streaming title does with the levels of a texture it no longer shows at that size. A +/// texture placed with lazy levels gives back the pages of each group of levels that has pages +/// and whose levels are all in `zero`, as it had none before their first texels (`map_levels` +/// gives them pages again with their next ones): tiles without memory read as zeros, as those +/// levels would with it (tiled resources tier 2). Its pages go back to the pools when no other +/// texture uses them (`release_tiles`, `IDLE`). Returns the tiles that lost their pages. +pub(super) unsafe fn unmap_levels(res: &ID3D12Resource, zero: &[u32]) -> u64 { + let key = res.as_raw() as usize; + let mut g = PAGES.lock().unwrap(); + for pages in g.values_mut().flatten() { + let Some(t) = pages.targets.get_mut(&key) else { continue }; + let Some(lv) = t.levels.as_mut().filter(|_| t.mapped) else { return 0 }; + let mut ranges = Vec::new(); + let (mut gone, mut gone_extra) = (Vec::new(), Vec::new()); + for k in 0..lv.groups.len() { + if !lv.groups[k].3 || !lv.levels_of(k).all(|l| zero.contains(&l)) { + continue; + } + let (sub, _, n, _) = lv.groups[k]; + lv.groups[k].3 = false; + ranges.push((sub, n)); + // (the pages the group owns) + let (used, used_extra) = std::mem::take(&mut lv.group_tiles[k]); + gone.extend(used); + gone_extra.extend(used_extra); + } + if ranges.is_empty() { + return 0; + } + let freed: u64 = ranges.iter().map(|&(_, n)| n as u64).sum(); + for (sub, n) in ranges { + pages.unmap_range(res, sub, n); + } + pages.release_tiles(gone, gone_extra, std::time::Instant::now(), false); + LEVEL_STATS[2].fetch_sub(freed, std::sync::atomic::Ordering::Relaxed); + let n = LEVELS_GIVEN_BACK.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n.is_power_of_two() && n >= 64 { + let (textures, stand, mapped, _) = level_stats(); + crate::xlog_info!("D3D12.X: level pages: {n} times a texture's levels lost their texels and gave their pages back; {textures} textures standing for {} MB have pages for {} MB", stand >> 4, mapped >> 4); + } + return freed; + } + 0 +} + +/// The times `unmap_levels` gave pages back. +static LEVELS_GIVEN_BACK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// The tiles of texture `resource` (lazy levels) that have pages: for a test. +#[cfg(test)] +pub(super) fn mapped_level_tiles(resource: usize) -> Option { + PAGES.lock().unwrap().values().flatten().find_map(|p| p.targets.get(&resource).and_then(|t| t.levels.as_ref()).map(|l| l.mapped_tiles())) +} + /// Record which mip levels of placed sampled texture `resource` an SRV can sample. pub(super) fn note_srv(resource: usize, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) { if !super::memory_report::enabled() || resource == 0 || !is_placed_texture(resource) { @@ -2700,6 +2840,11 @@ pub(super) fn has_lazy_levels(resource: usize) -> bool { PAGES.lock().unwrap().values().flatten().any(|p| p.targets.get(&resource).is_some_and(|t| t.levels.is_some())) } +/// Whether `resource` is a texture with lazy levels of which some have no pages yet. +pub(super) fn has_unmapped_levels(resource: usize) -> bool { + PAGES.lock().unwrap().values().flatten().any(|p| p.targets.get(&resource).and_then(|t| t.levels.as_ref()).is_some_and(|l| l.groups.iter().any(|g| !g.3))) +} + /// XG and the PC driver pack volume mip tails differently. Keep these textures on the /// detile/upload path rather than mapping title pages directly onto the driver's packed tail. fn console_has_packed_3d_mips(desc: &D3D12_RESOURCE_DESC) -> bool { @@ -2720,6 +2865,45 @@ fn console_has_packed_3d_mips(desc: &D3D12_RESOURCE_DESC) -> bool { .unwrap_or(false) } +/// The least a texture of `desc` takes on the console – the texels of its first level, one +/// after the other (a block-compressed format's by its blocks, a multisampled one's once) – for +/// a texture whose size there is not known: the pages it has to itself at its address. The PC's +/// tiles past those pages are its own (`owned_pages`), not the pages of what the title placed +/// behind it. None: a buffer, or a 1D texture. +fn least_texture_bytes(desc: &D3D12_RESOURCE_DESC) -> Option { + if desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D { + return None; + } + let (w, h, d) = (desc.Width, desc.Height as u64, desc.DepthOrArraySize as u64); + let bytes = match desc.Format.0 { + // BC1 and BC4: 8 bytes a 4x4 block; BC2, BC3, BC5, BC6H and BC7: 16 + f @ (70..=84 | 94..=99) => w.div_ceil(4) * h.div_ceil(4) * if matches!(f, 70..=72 | 79..=81) { 8 } else { 16 } * d, + _ => w * h * d * super::targets::texel_bytes(desc.Format) as u64, + }; + Some(bytes).filter(|&b| b != 0) +} + +/// A texture placed without a known console size, once for each kind: what `least_texture_bytes` +/// stands in for. +fn note_unknown_size(desc: &D3D12_RESOURCE_DESC, least: Option) { + static SEEN: Mutex>> = Mutex::new(None); + let kind = (desc.Dimension.0, desc.Format.0, desc.Flags.0, desc.SampleDesc.Count); + if SEEN.lock().unwrap().get_or_insert_with(HashSet::new).insert(kind) { + crate::xlog_info!( + "D3D12.X: a texture's size on the console is not known (dimension {}, {}x{}x{}, {} mips, format {}, flags {:#x}, {} samples): it keeps {} of the title's pages to itself", + desc.Dimension.0, + desc.Width, + desc.Height, + desc.DepthOrArraySize, + desc.MipLevels, + desc.Format.0, + desc.Flags.0, + desc.SampleDesc.Count, + least.map_or("none".to_string(), |b| format!("{} KiB", b >> 10)) + ); + } +} + /// A GPU-owned texture of the title at `va` (`desc`: the PC description, `console_bytes` its /// size on the console): on the title's pages there, else in the arena for that address (None: /// neither – the caller makes a resource of its own). @@ -2730,6 +2914,14 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st if !tier2(dev) { return None; } + // (a 3D render target's size on the console is not modelled: without one, every PC tile of + // it went on the title's pages from `va` on – more of them than the console's texture takes, + // so the last ones were the first pages of the title's next texture) + let console_bytes = console_bytes.or_else(|| { + let least = least_texture_bytes(desc); + note_unknown_size(desc, least); + least + }); if std::env::var_os("XCL_VRAM_ARENAS").is_none() { if let Some(hr) = place_on_pages(dev, this, va, desc, state, clear, console_bytes, true, false, riid, ppv) { return Some(hr); @@ -2754,6 +2946,8 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st } PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); ARENA_OF.lock().unwrap().get_or_insert_with(std::collections::HashMap::new).insert(*ppv as usize, id); + // (an arena has no tiles to unmap: nothing is superseded) + drop(super::placements::placed(*ppv as usize, va, (va, va + info.SizeInBytes as usize), super::placements::Backing::Arena(id), super::placements::Kind::Target, desc)); Some(hr) } @@ -3784,6 +3978,61 @@ mod tests { assert_eq!(pool.free_total, 8, "OOM rollback must return all popped tiles"); } + /// A pool heap is reclaimed once every tile of it is free and cooled – not while one is in + /// use or cooling – and no tile of it is handed out after that until a new heap takes its + /// slot: not as `preferred`, not for a tile of it that comes back to the pool. + #[test] + fn tile_pool_never_hands_out_tiles_of_reclaimed_heaps() { + let t0 = Instant::now(); + const P: u32 = 4; + let mut pool = TilePool::new(); + let free_slots = std::cell::RefCell::new(Vec::new()); + let made = std::cell::RefCell::new(Vec::new()); + let mut make = || { + let h = free_slots.borrow_mut().pop().unwrap_or(made.borrow().iter().max().map_or(0, |m| m + 1)); + made.borrow_mut().push(h); + Some(h) + }; + let a = pool.take_batch(P as usize, None, false, t0, P, &mut make).unwrap(); + let b = pool.take_batch(P as usize, None, false, t0, P, &mut make).unwrap(); + let c = pool.take_batch(2, None, false, t0, P, &mut make).unwrap(); + assert_eq!(*made.borrow(), [0, 1, 2]); + assert!(a.iter().all(|t| t.0 == 0) && b.iter().all(|t| t.0 == 1) && c.iter().all(|t| t.0 == 2)); + assert!(pool.reclaim_empty_heaps(0, P).is_empty(), "heap 2 has 2 tiles in use"); + + // heap 0 given back whole, heap 1 but one tile + for &t in &a { + pool.push_cooling(t, t0); + } + for &t in &b[1..] { + pool.push_cooling(t, t0); + } + pool.drain_cooling(t0 + COOL / 2); + assert!(pool.reclaim_empty_heaps(0, P).is_empty(), "heap 0's tiles are still cooling"); + pool.drain_cooling(t0 + COOL); + assert_eq!(pool.reclaim_empty_heaps(0, P), [0], "heap 1 has a tile in use"); + assert_eq!(pool.free_total, 3 + 2, "heap 1's 3 and heap 2's 2 free tiles, heap 0's gone"); + assert!(pool.reclaim_empty_heaps(0, P).is_empty(), "reclaimed once"); + free_slots.borrow_mut().push(0); + + // a tile of heap 0 that came back (none should) is not handed out + pool.push_cooling((0, 1), t0); + pool.drain_cooling(t0 + COOL); + pool.return_tiles(&[(0, 2)]); + assert_eq!(pool.free_total, 5); + + // heap 0 is never picked, also as the heap the texture's other pages are on + let t1 = t0 + COOL; + let d = pool.take_batch(5, Some(0), false, t1, P, &mut make).unwrap(); + assert!(d.iter().all(|t| t.0 == 1 || t.0 == 2), "{d:?}"); + assert_eq!(made.borrow().len(), 3, "no heap made while the pool had tiles"); + // the next heap takes the slot given back, with all its tiles free + let e = pool.take_batch(2, None, false, t1, P, &mut make).unwrap(); + assert_eq!(*made.borrow(), [0, 1, 2, 0]); + assert_eq!(e, [(0, 0), (0, 1)]); + assert_eq!(pool.free_total, P as usize - 2); + } + #[test] fn tile_pool_keeps_evictable_and_pinned_tiles_in_separate_heaps() { let t0 = Instant::now(); @@ -4281,6 +4530,40 @@ mod tests { } } + /// Title textures placed one behind the other, 512 KiB apart: 3D render targets of 33 texels + /// a side with 8-byte texels, whose size on the console XCL does not model. Each has the pages + /// of its own texels and no page of the next one, however many tiles the PC's texture has + /// (18 here: with all of them on the title's pages, the tenth to the eighteenth were the + /// next texture's first pages, and two such textures wrote over each other). + #[test] + fn a_3d_texture_of_unknown_console_size_keeps_off_the_next_textures_pages() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D, + Width: 33, + Height: 33, + DepthOrArraySize: 33, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_FLOAT, + ..Default::default() + }; + let bytes = least_texture_bytes(&desc); + assert_eq!(bytes, Some(33 * 33 * 33 * 8)); + let (a, b, pc_tiles) = (0x12_31f1_0000usize, 0x12_31f9_0000usize, 18); + let (first_a, n_a) = owned_pages(a, bytes, pc_tiles).unwrap(); + let (first_b, _) = owned_pages(b, bytes, pc_tiles).unwrap(); + assert_eq!((first_a, n_a), (a, 5)); + assert!(first_a + n_a * PAGE <= first_b, "the first texture's pages end before the second's"); + // as it was: every tile on the title's pages + let (_, all) = owned_pages(a, None, pc_tiles).unwrap(); + assert!(a + all * PAGE > b); + // a 2D target of unknown size the same way; a block-compressed texture by its blocks + let d2 = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 2560, Height: 1440, DepthOrArraySize: 1, ..desc }; + assert_eq!(least_texture_bytes(&d2), Some(2560 * 1440 * 8)); + let bc1 = D3D12_RESOURCE_DESC { Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_BC1_UNORM, Width: 1024, Height: 1024, ..d2 }; + assert_eq!(least_texture_bytes(&bc1), Some(256 * 256 * 8)); + assert_eq!(least_texture_bytes(&D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, ..desc }), None); + } + /// Reserved only with TILED support, and for MSAA a tiled sample count (#940: the driver /// refused R32G8X24_TYPELESS reserved, at 1 and 4 samples, and the debug layer said so). #[test] diff --git a/crates/xcl/src/hle/d3d12x/watch.rs b/crates/xcl/src/hle/d3d12x/watch.rs new file mode 100644 index 0000000000..cd5badb731 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/watch.rs @@ -0,0 +1,638 @@ +//! What XCL does when a call into the graphics driver does not return or the driver reports an +//! error, and what it was doing when that began. +//! +//! A retail title's world ended twice in a driver error whose cause the log did not hold: the +//! process was killed from outside seconds after the driver's first event, before the device was +//! reported removed, and the second time it then hung half-terminated in the driver for five +//! minutes with the desktop behind it. Three things, all cheap enough to be always on: +//! +//! - a ring of the last draws and dispatches (pipeline, kind, size, frame), written when one is +//! recorded on a list (an index and two stores) and read only for a report: which programs the +//! title recorded last (not necessarily submitted, and a list submitted again is not in it twice); +//! - a thread (`xcl-gpu-watch`) that looks for a removed device ten times a second (a title +//! whose threads all wait submits nothing and would never notice), and times the calls into +//! the driver that return at once on a working system: an ExecuteCommandLists or a Present that +//! has not returned after `XCL_GPU_STALL_MS` (2 000) is logged with the ring, again every 5 s +//! while it lasts, and when it returns. Nothing is held for it: a call that waits for GPU work +//! another submit brings would wait for ever. A call that took a quarter of a second and +//! returned is logged too (video memory being paged shows there first); +//! - `XCL_STOP_FILE=`, read by a thread of its own (`xcl-stop-file`) that calls nothing in +//! the driver: when that file has content the title ends itself in order (`real::end_title`: +//! its threads suspended, its fences signalled, the queues drained) – a process killed from +//! outside with GPU work in flight can hang in the driver. A file that begins with `fault` (the +//! driver reported an error) first gives the driver its time-out to say whether the device is +//! removed, with the title's command lists held meanwhile; the watch thread's poll then writes +//! the reason and DRED's report and ends the process. +//! +//! `XCL_GPU_WATCH=0`: no watch thread (the ring is still written, the stop file still read). + +use std::cell::Cell; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +// --------------------------------------------------------------------------------------- +// the ring +// --------------------------------------------------------------------------------------- + +/// draws and dispatches kept (about two frames of a retail title's world) +const RING: usize = 1 << 14; + +static AT: AtomicUsize = AtomicUsize::new(0); +static RING_PSO: [AtomicUsize; RING] = [const { AtomicUsize::new(0) }; RING]; +/// frame (28 bits) << 36 | work (32 bits) << 4 | kind +static RING_INFO: [AtomicU64; RING] = [const { AtomicU64::new(0) }; RING]; + +/// kinds of work in the ring (`gpu_profile::Kind` + 1, then the mesh draws; 4 bits) +pub(super) const MESH: u8 = 6; +pub(super) const INDIRECT_MESH: u8 = 7; +/// a DispatchMesh with a PC pipeline (a translated pass-through one) +pub(super) const PC_MESH: u8 = 8; + +fn kind_name(kind: u8) -> &'static str { + match kind { + 1 => "Dispatch", + 2 => "ExecuteIndirect (dispatches)", + 3 => "draw", + 4 => "ExecuteIndirect (draws)", + 5 => "ExecuteIndirect with a PC pipeline", + MESH => "DispatchMesh in two passes", + INDIRECT_MESH => "ExecuteIndirect (DispatchMesh) in two passes", + PC_MESH => "DispatchMesh", + _ => "?", + } +} + +fn dispatches(kind: u8) -> bool { + kind == 1 || kind == 2 +} + +/// the product of a size's parts that are not 0 (a dispatch's groups, a draw's vertices x +/// instances, an ExecuteIndirect's largest count), at most `u32::MAX` +fn work_of(size: [u32; 3]) -> u32 { + size.iter().filter(|&&d| d != 0).fold(1u64, |a, &d| a.saturating_mul(d as u64)).min(u32::MAX as u64) as u32 +} + +fn pack(kind: u8, work: u32, frame: u64) -> u64 { + (frame & 0x0FFF_FFFF) << 36 | (work as u64) << 4 | (kind & 15) as u64 +} + +fn unpack(info: u64) -> (u8, u32, u32) { + ((info & 15) as u8, (info >> 4) as u32, (info >> 36) as u32) +} + +/// A draw or dispatch with pipeline `pso` (the title's handle) is recorded on a list. +pub(super) fn note(pso: usize, kind: u8, size: [u32; 3]) { + let i = AT.fetch_add(1, Ordering::Relaxed) & (RING - 1); + RING_PSO[i].store(pso, Ordering::Relaxed); + RING_INFO[i].store(pack(kind, work_of(size), super::present::activity().0), Ordering::Relaxed); +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Entry { + pso: usize, + kind: u8, + work: u32, + frame: u32, +} + +/// the ring, oldest first (entries never written left out) +fn snapshot() -> Vec { + let at = AT.load(Ordering::Relaxed); + let n = at.min(RING); + (at - n..at) + .map(|k| { + let i = k & (RING - 1); + let (kind, work, frame) = unpack(RING_INFO[i].load(Ordering::Relaxed)); + Entry { pso: RING_PSO[i].load(Ordering::Relaxed), kind, work, frame } + }) + .filter(|e| e.kind != 0) + .collect() +} + +/// The lines of a report of `entries` (oldest first): the dispatching pipelines by the groups +/// they were given, the drawing ones by their calls, and the last ones in order. `name`: what is +/// known of a pipeline. +fn summarise(entries: &[Entry], name: impl Fn(usize) -> String) -> Vec { + if entries.is_empty() { + return vec!["recorded last: no draw or dispatch recorded yet".into()]; + } + // (pipeline, kind) → calls, work in all, largest, last frame + let mut by: std::collections::HashMap<(usize, u8), (u64, u64, u32, u32)> = std::collections::HashMap::new(); + for e in entries { + let s = by.entry((e.pso, e.kind)).or_default(); + s.0 += 1; + s.1 += e.work as u64; + s.2 = s.2.max(e.work); + s.3 = e.frame; + } + let (first, last) = (entries[0].frame, entries[entries.len() - 1].frame); + let mut lines = vec![format!("recorded last: the last {} draws and dispatches (frames {first} to {last}), {} pipelines", entries.len(), by.len())]; + let mut all: Vec<((usize, u8), (u64, u64, u32, u32))> = by.into_iter().collect(); + // dispatches by the groups given (a program that runs long runs on every one of them), + // then draws by calls; ties by address, for a stable order + all.sort_by(|a, b| { + dispatches(b.0 .1) + .cmp(&dispatches(a.0 .1)) + .then(if dispatches(a.0 .1) { b.1 .1.cmp(&a.1 .1) } else { b.1 .0.cmp(&a.1 .0) }) + .then(a.0.cmp(&b.0)) + }); + let (mut shown_dispatch, mut shown_draw) = (0, 0); + for ((pso, kind), (calls, work, largest, frame)) in &all { + let shown = if dispatches(*kind) { &mut shown_dispatch } else { &mut shown_draw }; + *shown += 1; + if *shown > if dispatches(*kind) { 24 } else { 12 } { + continue; + } + lines.push(format!("recorded last: {} {pso:#x} ({}): {calls} calls, {work} in all, largest {largest}, last in frame {frame}", kind_name(*kind), name(*pso))); + } + let tail: Vec = entries[entries.len().saturating_sub(24)..].iter().map(|e| format!("{} {:#x} {}", kind_name(e.kind), e.pso, e.work)).collect(); + lines.push(format!("recorded last: the last {} in order: {}", tail.len(), tail.join("; "))); + lines +} + +/// What is known of the pipeline behind the title's handle `pso`: its console shaders (no side +/// effects: a report must not start a pipeline build). Graphics pipelines are in `pso_shaders` +/// only while profiling; DRED's label names them otherwise. +fn pipeline_name(pso: usize) -> String { + let real = super::pso_async::peek(pso); + match super::real::pso_shaders(real) { + Some((cs, 0)) => format!("cs {cs:016x}"), + Some((vs, ps)) => format!("vs {vs:016x} ps {ps:016x}"), + None => super::dred::on().then(|| super::dred::label_of(real)).flatten().unwrap_or_else(|| "no console shader known".into()), + } +} + +/// The ring into the log (`why`: what happened), at most once a second. +pub(super) fn report(why: &str) { + static LAST: AtomicU64 = AtomicU64::new(0); + let now = now_ms(); + let last = LAST.load(Ordering::Relaxed); + if last != 0 && now.saturating_sub(last) < 1000 { + return; + } + LAST.store(now, Ordering::Relaxed); + crate::xlog_error!("recorded last ({why}):"); + for line in summarise(&snapshot(), pipeline_name) { + crate::xlog_error!("{line}"); + } +} + +// --------------------------------------------------------------------------------------- +// calls into the driver +// --------------------------------------------------------------------------------------- + +/// threads whose calls are timed (a title submits from a handful) +const SLOTS: usize = 64; + +/// when the thread of slot k entered the driver (`now_ms`; 0: it is not in it) +static SINCE: [AtomicU64; SLOTS] = [const { AtomicU64::new(0) }; SLOTS]; +static WHAT: [AtomicU32; SLOTS] = [const { AtomicU32::new(0) }; SLOTS]; +static TID: [AtomicU32; SLOTS] = [const { AtomicU32::new(0) }; SLOTS]; +static NEXT_SLOT: AtomicUsize = AtomicUsize::new(0); + +thread_local! { + /// this thread's slot (`usize::MAX`: none yet; `SLOTS`: none left) + static SLOT: Cell = const { Cell::new(usize::MAX) }; +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Call { + Execute = 1, + Present = 2, +} + +fn call_name(what: u32) -> &'static str { + match what { + 1 => "ExecuteCommandLists", + 2 => "Present", + _ => "a call", + } +} + +/// milliseconds since the first use, never 0 +fn now_ms() -> u64 { + static T0: OnceLock = OnceLock::new(); + T0.get_or_init(Instant::now).elapsed().as_millis() as u64 + 1 +} + +/// a call that returned after this long is logged +const SLOW_MS: u64 = 250; + +/// The thread is inside a driver call until this is dropped. +pub(super) struct InDriver { + slot: usize, + since: u64, +} + +/// The calling thread enters `call` (one the driver returns from at once when it works). +pub(super) fn in_driver(call: Call) -> InDriver { + let slot = SLOT.with(|s| { + if s.get() == usize::MAX { + s.set(NEXT_SLOT.fetch_add(1, Ordering::Relaxed).min(SLOTS)); + if s.get() < SLOTS { + TID[s.get()].store(unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }, Ordering::Relaxed); + } else { + static SAID: AtomicBool = AtomicBool::new(false); + if !SAID.swap(true, Ordering::Relaxed) { + crate::xlog_warn!("D3D12: {SLOTS} threads have called into the driver – the calls of further threads are not timed"); + } + } + } + s.get() + }); + // (a call inside a call of the same thread is the outer one's time) + if slot >= SLOTS || SINCE[slot].load(Ordering::Relaxed) != 0 { + return InDriver { slot: SLOTS, since: 0 }; + } + let since = now_ms(); + WHAT[slot].store(call as u32, Ordering::Relaxed); + SINCE[slot].store(since, Ordering::Release); + InDriver { slot, since } +} + +impl Drop for InDriver { + fn drop(&mut self) { + if self.slot >= SLOTS { + return; + } + SINCE[self.slot].store(0, Ordering::Release); + let took = now_ms().saturating_sub(self.since); + if took >= SLOW_MS { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 16 || n.is_power_of_two() { + crate::xlog_warn!("D3D12: {} took {took} ms in the driver ({n} such calls so far)", call_name(WHAT[self.slot].load(Ordering::Relaxed))); + } + } + } +} + +/// The call that has been in the driver longest: (milliseconds, which, thread). +fn longest_call(now: u64) -> Option<(u64, u32, u32)> { + (0..SLOTS) + .filter_map(|k| { + let since = SINCE[k].load(Ordering::Acquire); + (since != 0).then(|| (now.saturating_sub(since), WHAT[k].load(Ordering::Relaxed), TID[k].load(Ordering::Relaxed))) + }) + .max() +} + +/// a stop for a graphics driver error is being handled (`stop_asked`): the title's command lists +/// wait +static HOLD: AtomicBool = AtomicBool::new(false); + +/// The title submits command lists: not while a stop for a driver error is being handled. +pub(super) fn wait_while_held() { + wait_while(&HOLD); +} + +/// `wait_while_held` on `hold`. A thread inside a timed call (a submit made from within it) +/// goes on: it would wait on itself. +fn wait_while(hold: &AtomicBool) { + if !hold.load(Ordering::Acquire) || in_timed_call() { + return; + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12: a submit is held – a stop for a graphics driver error is being handled"); + } + while hold.load(Ordering::Acquire) { + std::thread::sleep(Duration::from_millis(20)); + } +} + +/// The calling thread is inside a timed call (`in_driver`). +fn in_timed_call() -> bool { + let slot = SLOT.with(|s| s.get()); + slot < SLOTS && SINCE[slot].load(Ordering::Relaxed) != 0 +} + +fn stall_ms() -> u64 { + static MS: OnceLock = OnceLock::new(); + *MS.get_or_init(|| std::env::var("XCL_GPU_STALL_MS").ok().and_then(|v| v.trim().parse().ok()).filter(|&ms| ms >= 100).unwrap_or(2000)) +} + +/// A call that stands still, as the watch knows it between polls. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Stall { + /// when it entered the driver (`now_ms`; 0: no call stands still) + since: u64, + /// when it was last logged + said: u64, +} + +/// What the watch logs after a poll. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Say { + Nothing, + /// a call passed the limit: (ms, which, thread) + Stalled(u64, u32, u32), + /// it still has not returned, 5 s after it was last logged: (ms, which, thread) + Still(u64, u32, u32), + /// it returned: how long it stood in the driver (ms) + Returned(u64), +} + +/// One poll of the watch: the stall before it, the time, the call in the driver longest +/// (`longest_call`) and the stall time in; the stall after it and what to log out. +fn watch_step(s: Stall, now: u64, longest: Option<(u64, u32, u32)>, limit: u64) -> (Stall, Say) { + match longest { + // (the call that stands still is the oldest in the driver until it returns) + Some((ms, what, tid)) if s.since != 0 && now.saturating_sub(ms) == s.since => { + if now.saturating_sub(s.said) >= 5000 { + (Stall { said: now, ..s }, Say::Still(ms, what, tid)) + } else { + (s, Say::Nothing) + } + } + _ if s.since != 0 => (Stall::default(), Say::Returned(now.saturating_sub(s.since))), + Some((ms, what, tid)) if ms >= limit => (Stall { since: now.saturating_sub(ms), said: now }, Say::Stalled(ms, what, tid)), + _ => (s, Say::Nothing), + } +} + +/// the watch thread runs (`XCL_GPU_WATCH` is not 0) +static WATCHING: AtomicBool = AtomicBool::new(false); +/// the watch thread's heartbeat: when its last poll of the device returned (`now_ms`; when it +/// was started, before the first) +static BEAT: AtomicU64 = AtomicU64::new(0); + +/// The watching thread and the stop file's, once the device is made. +pub(super) fn start() { + static STARTED: AtomicBool = AtomicBool::new(false); + if STARTED.swap(true, Ordering::AcqRel) { + return; + } + start_stop_file(); + if std::env::var("XCL_GPU_WATCH").is_ok_and(|v| v.trim() == "0") { + return; + } + BEAT.store(now_ms(), Ordering::Relaxed); + let watch = std::thread::Builder::new().name("xcl-gpu-watch".into()).spawn(move || { + let limit = stall_ms(); + let mut stall = Stall::default(); + loop { + std::thread::sleep(Duration::from_millis(100)); + super::real::stop_if_device_removed(); + let now = now_ms(); + BEAT.store(now, Ordering::Relaxed); + let (next, say) = watch_step(stall, now, longest_call(now), limit); + stall = next; + match say { + Say::Nothing => {} + Say::Stalled(ms, what, tid) => { + crate::xlog_warn!("D3D12: {} on thread {tid} has not returned for {ms} ms – a call the driver returns from at once when it works", call_name(what)); + crate::log::flush(); + report("a call into the driver stands still"); + crate::log::flush(); + } + Say::Still(ms, what, tid) => { + crate::xlog_error!("D3D12: {} on thread {tid} still has not returned ({ms} ms)", call_name(what)); + crate::log::flush(); + } + Say::Returned(ms) => { + crate::xlog_warn!("D3D12: the graphics driver answers again – the call returned after {ms} ms"); + crate::log::flush(); + } + } + } + }); + WATCHING.store(watch.is_ok(), Ordering::Release); +} + +/// `XCL_STOP_FILE`: read on a thread of its own, which calls nothing in the driver or DXGI before +/// the title ends – a call that does not return (one on another thread never did in a driver +/// error) must not keep the stop from being taken. +fn start_stop_file() { + let Some(path) = std::env::var_os("XCL_STOP_FILE").map(std::path::PathBuf::from) else { return }; + let _ = std::thread::Builder::new().name("xcl-stop-file".into()).spawn(move || { + // polls in a row that found the file there and empty + let mut empty = 0; + loop { + std::thread::sleep(Duration::from_millis(100)); + let Ok(bytes) = std::fs::read(&path) else { + empty = 0; + continue; + }; + match stop_wanted(&bytes) { + Some(fault) => stop_asked(fault), + // (its writer may have made it and not written yet; one that stays empty: end) + None => { + empty += 1; + if empty >= 10 { + stop_asked(false); + } + } + } + } + }); +} + +/// What a stop file's bytes ask for: None – nothing yet (empty or white space); Some(true) – +/// `fault…` (any case), the driver reported an error; Some(false) – anything else, end now. +/// UTF-8 (a BOM stripped) or UTF-16 LE (a BOM, or a NUL as the second byte), decoded lossily. +fn stop_wanted(bytes: &[u8]) -> Option { + let text = if bytes.starts_with(&[0xFF, 0xFE]) || bytes.get(1) == Some(&0) { + let units: Vec = bytes.strip_prefix(&[0xFF, 0xFE]).unwrap_or(bytes).chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); + String::from_utf16_lossy(&units) + } else { + String::from_utf8_lossy(bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes)).into_owned() + }; + let text = text.trim(); + (!text.is_empty()).then(|| text.get(..5).is_some_and(|w| w.eq_ignore_ascii_case("fault"))) +} + +/// A stop was asked for from outside (`fault`: the driver reported an error): the title ends +/// itself. +fn stop_asked(fault: bool) -> ! { + crate::xlog_warn!("XCL_STOP_FILE: a stop was asked for from outside ({}) – the title ends itself", if fault { "the graphics driver reported an error" } else { "end" }); + crate::log::flush(); + report("a stop was asked for"); + crate::log::flush(); + if fault { + // the driver gets its time-out to say whether the device is removed: the watch thread's + // poll (`real::stop_if_device_removed`) then writes the reason and DRED's report and ends + // the process; this thread calls nothing in the driver meanwhile. Only the title's + // command lists are held (`q_execute_command_lists`): queue Signal and Wait, tile + // mappings and pipeline creation go on. The hold stays into `end_title`, whose drain + // signals and submits no list. + HOLD.store(true, Ordering::Release); + for _ in 0..120 { + std::thread::sleep(Duration::from_millis(100)); + } + // (since the last poll that returned, which may be before the stop was asked) + let quiet = now_ms().saturating_sub(BEAT.load(Ordering::Relaxed)); + let check = if !WATCHING.load(Ordering::Acquire) { + " – no check of the device runs (XCL_GPU_WATCH=0)".to_string() + } else if quiet > 1000 { + format!(" – the check of the device has itself not returned ({quiet} ms since the last one)") + } else { + String::new() + }; + crate::xlog_warn!("XCL_STOP_FILE: the device was not reported removed within 12 s{check}"); + crate::log::flush(); + } + crate::report::write_final(Some("stopped from outside (XCL_STOP_FILE)".into())); + crate::log::flush(); + super::real::end_title(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_entry_packs_and_unpacks() { + for (kind, work, frame) in [(1u8, 0u32, 0u64), (7, u32::MAX, 0x0FFF_FFFF), (3, 1234, 5), (PC_MESH, 9, 1)] { + assert_eq!(unpack(pack(kind, work, frame)), (kind, work, frame as u32)); + } + assert_eq!(kind_name(PC_MESH), "DispatchMesh"); + // a frame count past 28 bits wraps, and does not reach the work + assert_eq!(unpack(pack(2, 7, 0x1_0000_0003)), (2, 7, 3)); + assert_eq!(work_of([4, 5, 6]), 120); + assert_eq!(work_of([4, 0, 0]), 4, "an ExecuteIndirect's count"); + assert_eq!(work_of([0, 0, 0]), 1); + assert_eq!(work_of([u32::MAX, u32::MAX, 2]), u32::MAX, "saturates"); + } + + #[test] + fn the_report_ranks_dispatches_by_groups_and_draws_by_calls() { + let e = |pso, kind, work, frame| Entry { pso, kind, work, frame }; + let entries = [ + e(0x10, 3, 6, 1), // draw + e(0x20, 1, 100, 1), // small dispatch + e(0x30, 1, 4_000_000, 2), // a full-screen dispatch + e(0x10, 3, 6, 2), + e(0x20, 1, 100, 2), + e(0x40, MESH, 12, 2), + ]; + let lines = summarise(&entries, |pso| format!("p{pso:x}")); + assert_eq!(lines[0], "recorded last: the last 6 draws and dispatches (frames 1 to 2), 4 pipelines"); + assert!(lines[1].contains("Dispatch 0x30 (p30): 1 calls, 4000000 in all, largest 4000000, last in frame 2"), "{}", lines[1]); + assert!(lines[2].contains("Dispatch 0x20 (p20): 2 calls, 200 in all, largest 100"), "{}", lines[2]); + assert!(lines[3].contains("draw 0x10 (p10): 2 calls"), "{}", lines[3]); + assert!(lines[4].contains("DispatchMesh in two passes 0x40 (p40): 1 calls"), "{}", lines[4]); + assert!(lines[5].starts_with("recorded last: the last 6 in order: draw 0x10 6; Dispatch 0x20 100; "), "{}", lines[5]); + assert_eq!(summarise(&[], |_| String::new()), vec!["recorded last: no draw or dispatch recorded yet".to_string()]); + } + + #[test] + fn the_report_keeps_to_a_few_pipelines_of_each_kind() { + let entries: Vec = (0..100).map(|k| Entry { pso: 0x1000 + k, kind: if k % 2 == 0 { 1 } else { 3 }, work: k as u32, frame: 1 }).collect(); + let lines = summarise(&entries, |_| String::new()); + // the head line, 24 dispatching pipelines, 12 drawing ones, the tail + assert_eq!(lines.len(), 1 + 24 + 12 + 1); + assert!(lines[1].contains("Dispatch 0x1062"), "the largest first: {}", lines[1]); + } + + #[test] + fn a_stall_is_logged_when_it_passes_the_limit_every_5_s_and_when_it_ends() { + // a call enters the driver at 1 s and returns 13 s later; the watch polls every 100 ms + let (limit, began) = (2000, 1000u64); + let (mut stall, mut said) = (Stall::default(), Vec::new()); + for now in (1100..=20_000u64).step_by(100) { + let longest = (now < began + 13_000).then(|| (now - began, Call::Execute as u32, 7)); + let (next, say) = watch_step(stall, now, longest, limit); + stall = next; + if say != Say::Nothing { + said.push((now, say)); + } + } + assert_eq!(said, vec![(3000, Say::Stalled(2000, 1, 7)), (8000, Say::Still(7000, 1, 7)), (13_000, Say::Still(12_000, 1, 7)), (14_000, Say::Returned(13_000))]); + assert_eq!(stall, Stall::default()); + } + + #[test] + fn a_stall_ends_when_its_call_returns_and_another_is_in_the_driver() { + let stalled = Stall { since: 1000, said: 3000 }; + assert_eq!(watch_step(Stall::default(), 3000, Some((1999, 1, 7)), 2000), (Stall::default(), Say::Nothing)); + assert_eq!(watch_step(Stall::default(), 3000, None, 2000), (Stall::default(), Say::Nothing)); + assert_eq!(watch_step(stalled, 4000, Some((3000, 1, 7)), 2000), (stalled, Say::Nothing), "the same call, said 1 s ago"); + assert_eq!(watch_step(stalled, 4000, Some((3, 2, 9)), 2000), (Stall::default(), Say::Returned(3000)), "that call returned, another began"); + // one past the limit already: logged at the next poll + assert_eq!(watch_step(stalled, 6000, Some((2500, 2, 9)), 2000), (Stall::default(), Say::Returned(5000))); + assert_eq!(watch_step(Stall::default(), 6100, Some((2600, 2, 9)), 2000), (Stall { since: 3500, said: 6100 }, Say::Stalled(2600, 2, 9))); + } + + #[test] + fn a_held_submit_goes_on_when_the_hold_ends_and_at_once_inside_a_timed_call() { + // (holds of their own: other tests' submits are not held) + static HELD: AtomicBool = AtomicBool::new(true); + let (tx, rx) = std::sync::mpsc::channel(); + let t = std::thread::spawn(move || { + tx.send(()).unwrap(); + wait_while(&HELD); + tx.send(()).unwrap(); + }); + rx.recv_timeout(Duration::from_secs(10)).expect("the thread runs"); + assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "held"); + HELD.store(false, Ordering::Release); + rx.recv_timeout(Duration::from_secs(10)).expect("goes on once the hold ends"); + t.join().unwrap(); + + static HELD_TOO: AtomicBool = AtomicBool::new(true); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _call = in_driver(Call::Present); + assert!(in_timed_call(), "a slot was left for this thread"); + wait_while(&HELD_TOO); + let _ = tx.send(()); + }); + let inside = rx.recv_timeout(Duration::from_secs(10)); + HELD_TOO.store(false, Ordering::Release); + inside.expect("a thread inside a timed call is not held (it would wait on itself)"); + } + + #[test] + fn a_stop_file_says_whether_the_driver_reported_an_error() { + assert_eq!(stop_wanted(b""), None, "made, not yet written"); + assert_eq!(stop_wanted(b" \r\n\t"), None); + assert_eq!(stop_wanted(b"fault 2026-11-25T05:36:37\r\n"), Some(true)); + assert_eq!(stop_wanted(b" FAULT"), Some(true)); + assert_eq!(stop_wanted(b"end"), Some(false)); + assert_eq!(stop_wanted(b"faul"), Some(false)); + assert_eq!(stop_wanted(b"\xEF\xBB\xBFfault\r\n"), Some(true), "a UTF-8 BOM"); + assert_eq!(stop_wanted(b"\xEF\xBB\xBF"), None); + let utf16 = |s: &str, bom: bool| -> Vec { bom.then_some([0xFF, 0xFE]).into_iter().flatten().chain(s.encode_utf16().flat_map(u16::to_le_bytes)).collect() }; + for bom in [true, false] { + assert_eq!(stop_wanted(&utf16("fault\r\n", bom)), Some(true), "UTF-16 LE, BOM {bom}"); + assert_eq!(stop_wanted(&utf16(" Fault", bom)), Some(true), "UTF-16 LE, BOM {bom}"); + assert_eq!(stop_wanted(&utf16("end\r\n", bom)), Some(false), "UTF-16 LE, BOM {bom}"); + } + assert_eq!(stop_wanted(&utf16(" \r\n", true)), None); + } + + #[test] + fn a_thread_in_the_driver_is_seen_until_it_returns() { + // (its own thread: the slot is the thread's) + std::thread::spawn(|| { + let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + let seen = |now: u64| (0..SLOTS).any(|k| TID[k].load(Ordering::Relaxed) == tid && SINCE[k].load(Ordering::Relaxed) != 0 && now >= SINCE[k].load(Ordering::Relaxed)); + { + let _call = in_driver(Call::Execute); + assert!(seen(now_ms())); + // a call inside it is the outer one's time and does not end it + drop(in_driver(Call::Present)); + assert!(seen(now_ms())); + assert!(longest_call(now_ms() + 5000).is_some_and(|(ms, _, _)| ms >= 5000)); + } + assert!(!seen(now_ms())); + }) + .join() + .unwrap(); + } + + #[test] + fn the_ring_holds_what_was_noted_last() { + // (other tests of the crate may note work too: only what this one put in is looked for) + note(0xABCD_0001, MESH, [7, 0, 0]); + note(0xABCD_0002, 1, [3, 5, 2]); + let snap = snapshot(); + let a = snap.iter().rposition(|e| e.pso == 0xABCD_0001).expect("noted"); + let b = snap.iter().rposition(|e| e.pso == 0xABCD_0002).expect("noted"); + assert!(a < b, "oldest first"); + assert_eq!((snap[a].kind, snap[a].work), (MESH, 7)); + assert_eq!((snap[b].kind, snap[b].work), (1, 30)); + } +} diff --git a/crates/xcl/src/hle/d3d12x/worker_pool.rs b/crates/xcl/src/hle/d3d12x/worker_pool.rs new file mode 100644 index 0000000000..59005092dc --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/worker_pool.rs @@ -0,0 +1,235 @@ +//! A few worker threads that share one submit's bulk memory work: the scan of written pages and +//! the copies into the staging ring (`sparse::before_execute`). The submitting thread takes part +//! and waits for the workers, so nothing of the submit is left running when `run` returns. + +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +/// What one `run` shares: the function and how many calls it makes (one per item). +struct Job { + /// the caller's closure: valid while `run` waits for every worker that took the job + f: *const (dyn Fn(usize) + Sync), + items: usize, + /// when it was handed out + start: Instant, +} + +/// How a `run`'s items were shared (`XCL_LOOK_STATS=2` reports it for the scan): a caller that +/// did most of them itself, or workers that came late, make the pool worth nothing. +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct Shares { + pub by_caller: usize, + pub by_workers: usize, + /// how long after the job was handed out the first worker took an item (None: none did) + pub first: Option, +} + +// SAFETY: the pointer is only used while `run` (which holds the closure) waits. +unsafe impl Send for Job {} + +struct State { + gen: u64, + job: Option, + /// workers that took the job and have not finished it + running: usize, +} + +struct Shared { + state: Mutex, + start: Condvar, + done: Condvar, + next: AtomicUsize, + /// the job's items the workers did, and the ns until the first of them took one (`Shares`) + by_workers: AtomicUsize, + first_ns: AtomicU64, + /// an item of the job panicked on a worker: `run` panics on the caller's thread once all are + /// back, as the item would have there (its work was not done: nothing may go on as if it was) + panicked: AtomicBool, +} + +struct Pool { + shared: Arc, +} + +fn worker(s: Arc) { + let mut seen = 0u64; + loop { + let (f, items, start) = { + let mut st = s.state.lock().unwrap_or_else(|e| e.into_inner()); + while st.gen == seen || st.job.is_none() { + st = s.start.wait(st).unwrap_or_else(|e| e.into_inner()); + } + seen = st.gen; + st.running += 1; + let j = st.job.as_ref().expect("job"); + (j.f, j.items, j.start) + }; + let mut did = 0usize; + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| loop { + let i = s.next.fetch_add(1, Ordering::Relaxed); + if i >= items { + break; + } + if did == 0 { + s.first_ns.fetch_min(start.elapsed().as_nanos() as u64, Ordering::Relaxed); + } + did += 1; + // SAFETY: `run` waits for `running` to reach 0 before its closure goes away + unsafe { (*f)(i) }; + })); + // (before `running` goes down: `run` reads it once that is 0) + if ran.is_err() { + s.panicked.store(true, Ordering::Relaxed); + } + s.by_workers.fetch_add(did, Ordering::Relaxed); + let mut st = s.state.lock().unwrap_or_else(|e| e.into_inner()); + st.running -= 1; + if st.running == 0 { + s.done.notify_all(); + } + } +} + +/// `XCL_COPY_THREADS` workers (4 unless given, 0: none), started with the first use. +fn pool() -> Option<&'static Pool> { + static POOL: OnceLock> = OnceLock::new(); + POOL.get_or_init(|| { + let n: usize = std::env::var("XCL_COPY_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(4).min(15); + if n == 0 { + return None; + } + let shared = Arc::new(Shared { + state: Mutex::new(State { gen: 0, job: None, running: 0 }), + start: Condvar::new(), + done: Condvar::new(), + next: AtomicUsize::new(0), + by_workers: AtomicUsize::new(0), + first_ns: AtomicU64::new(u64::MAX), + panicked: AtomicBool::new(false), + }); + let mut made = 0; + for i in 0..n { + let s = Arc::clone(&shared); + if std::thread::Builder::new().name(format!("xcl-copy-{i}")).spawn(move || worker(s)).is_ok() { + made += 1; + } + } + (made > 0).then_some(Pool { shared }) + }) + .as_ref() +} + +/// `f(0) … f(items - 1)`, on the calling thread and the workers; returns when all have returned, +/// with who did them. +pub(super) fn run(items: usize, f: &(dyn Fn(usize) + Sync)) -> Shares { + let Some(p) = (items > 1).then(pool).flatten() else { + (0..items).for_each(f); + return Shares { by_caller: items, ..Shares::default() }; + }; + // one job at a time + static ONE: Mutex<()> = Mutex::new(()); + let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: the pointer outlives the workers' use of it (`run` waits for them below) + let erased: *const (dyn Fn(usize) + Sync) = unsafe { std::mem::transmute::<&(dyn Fn(usize) + Sync), &'static (dyn Fn(usize) + Sync)>(f) }; + { + let mut st = p.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + p.shared.next.store(0, Ordering::Relaxed); + p.shared.by_workers.store(0, Ordering::Relaxed); + p.shared.first_ns.store(u64::MAX, Ordering::Relaxed); + p.shared.panicked.store(false, Ordering::Relaxed); + st.gen += 1; + st.job = Some(Job { f: erased, items, start: Instant::now() }); + } + p.shared.start.notify_all(); + let mut by_caller = 0; + // (a panic of the caller's own item waits for the workers too: they still use `f`) + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| loop { + let i = p.shared.next.fetch_add(1, Ordering::Relaxed); + if i >= items { + break; + } + f(i); + by_caller += 1; + })); + if ran.is_err() { + // (the items no one took yet are not started) + p.shared.next.store(items, Ordering::Relaxed); + } + let mut st = p.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + while st.running > 0 { + st = p.shared.done.wait(st).unwrap_or_else(|e| e.into_inner()); + } + st.job = None; + drop(st); + if let Err(panic) = ran { + std::panic::resume_unwind(panic); + } + if p.shared.panicked.load(Ordering::Relaxed) { + panic!("worker_pool: an item panicked on a worker thread"); + } + let first = p.shared.first_ns.load(Ordering::Relaxed); + Shares { by_caller, by_workers: p.shared.by_workers.load(Ordering::Relaxed), first: (first != u64::MAX).then(|| Duration::from_nanos(first)) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_item_runs_once() { + for items in [0usize, 1, 2, 7, 64, 1000] { + let hits: Vec = (0..items).map(|_| AtomicUsize::new(0)).collect(); + run(items, &|i| { + hits[i].fetch_add(1, Ordering::Relaxed); + }); + assert!(hits.iter().all(|h| h.load(Ordering::Relaxed) == 1), "{items} items"); + } + // many runs one after the other, with the same workers + for _ in 0..200 { + let n = AtomicUsize::new(0); + run(20, &|_| { + n.fetch_add(1, Ordering::Relaxed); + }); + assert_eq!(n.load(Ordering::Relaxed), 20); + } + } + + /// An item that panics, on the caller or on a worker, panics `run` (its work was not done), and + /// the workers are back first; the pool works on after it. + #[test] + fn a_panicking_item_panics_the_run() { + for items in [2usize, 7, 64, 1000] { + for bad in [0, items - 1] { + let r = std::panic::catch_unwind(|| { + run(items, &|i| { + if i == bad { + panic!("item {i} of {items}"); + } + }) + }); + assert!(r.is_err(), "item {bad} of {items}"); + } + } + let n = AtomicUsize::new(0); + run(20, &|_| { + n.fetch_add(1, Ordering::Relaxed); + }); + assert_eq!(n.load(Ordering::Relaxed), 20); + } + + #[test] + fn the_caller_and_the_workers_did_every_item() { + for items in [0usize, 1, 2, 7, 64, 1000] { + for _ in 0..20 { + let s = run(items, &|_| std::hint::black_box(())); + assert_eq!(s.by_caller + s.by_workers, items, "{s:?}"); + // (a worker's first item is when it is counted as begun) + assert_eq!(s.first.is_some(), s.by_workers > 0, "{s:?}"); + } + } + // items that take a while: the workers have time to take some + let s = run(64, &|_| std::thread::sleep(std::time::Duration::from_micros(200))); + assert_eq!(s.by_caller + s.by_workers, 64, "{s:?}"); + } +} diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 2a9d878708..a60ac2c6da 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -6,7 +6,8 @@ //! riid, out), CreateStatusArray(capacity, name, riid, out), SetCpuAffinity(mask), //! SetDebugFlags(flags), SetStagingBufferSize(bytes), then 7 more, //! * queue desc (0x18): source type u32 @0 (0 file, 1 memory), capacity u16 @8, priority i8 -//! @10 (-1 … 2; memory queues 2), name @0x10, +//! @10 (-1 … 2; memory queues 2), name @0x10; the newer factory's desc (0x20) adds options +//! u64 @0x18 (`DSTORAGE_QUEUE_OPTIONS`: bit 0 `AutoSubmitDisabled`), //! * request (0x48): options u64 @0 (`DSTORAGE_REQUEST_OPTIONS`: bit 0 `ZlibDecompress`, //! bits 1–4 `BcpackMode`, bits 5–20 `SwizzleMode`, bit 21 `DestinationIsPhysicalPages`, //! bit 22 `SourceType` (0 file / 1 memory), bit 23 `SourceIsPhysicalPages`), @@ -346,11 +347,9 @@ unsafe fn bcpack_fill(r: &Request, target: &FillTarget) -> bool { let ok = match target { FillTarget::Pages(pages) => crate::hle::kernelx::write_physical_pages(pages, r.destination_page_offset as usize, &bytes), FillTarget::Virtual => { - if !writable(r.destination as usize, n) { - return false; - } + let Some(dest) = cpu_range(r.destination as usize, n).filter(|&d| writable(d, n)) else { return false }; if n > 0 { - std::ptr::copy_nonoverlapping(bytes.as_ptr(), r.destination as *mut u8, n); + std::ptr::copy_nonoverlapping(bytes.as_ptr(), dest as *mut u8, n); } true } @@ -484,17 +483,25 @@ unsafe extern "system" fn factory_unknown(_p: *mut c_void) -> HRESULT { E_NOTIMPL } +/// `DSTORAGE_QUEUE_OPTIONS` bit 0: the queue runs its requests only at `Submit`, not when it is +/// half full. +const AUTO_SUBMIT_DISABLED: u64 = 1; + /// Slot 10 of the newer factory: CreateQueue with a 0x20-byte desc – the 0x18 of -/// `factory_create_queue`, then a u64 (a retail game: 1). -unsafe extern "system" fn factory_create_queue1(p: *mut c_void, desc: *const u8, riid: *const GUID, out: *mut *mut c_void) -> HRESULT { +/// `factory_create_queue`, then the queue's options u64 (a retail game: `AutoSubmitDisabled`). +unsafe extern "system" fn factory_create_queue1(_p: *mut c_void, desc: *const u8, riid: *const GUID, out: *mut *mut c_void) -> HRESULT { + let mut options = 0; if !desc.is_null() { - let extra = (desc.add(0x18) as *const u64).read_unaligned(); + options = (desc.add(0x18) as *const u64).read_unaligned(); static SEEN: AtomicBool = AtomicBool::new(false); if !SEEN.swap(true, Ordering::Relaxed) { - crate::xlog_info!("DirectStorage: CreateQueue (0x20 desc), u64 @0x18 = {extra:#x}"); + crate::xlog_info!("DirectStorage: CreateQueue (0x20 desc), options {options:#x}"); + } + if options & !AUTO_SUBMIT_DISABLED != 0 { + warn_once("DSTORAGE_QUEUE_OPTIONS", format_args!("unknown queue option bits {:#x}", options & !AUTO_SUBMIT_DISABLED)); } } - factory_create_queue(p, desc, riid, out) + create_queue(desc, riid, out, options & AUTO_SUBMIT_DISABLED == 0) } unsafe extern "system" fn factory_set_cpu_affinity(_p: *mut c_void, _mask: u64) -> HRESULT { @@ -805,6 +812,8 @@ unsafe fn snapshot_page_array(ptr: u64, offset: u16, byte_len: u32) -> Result bool { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; @@ -812,6 +821,45 @@ pub(crate) unsafe fn read_own(at: usize, out: *mut u8, len: usize) -> bool { at != 0 && ReadProcessMemory(GetCurrentProcess(), at as *const c_void, out as *mut c_void, len, &mut done) != 0 && done == len } +/// Whether `[p, p + n)` lies in XCL's sparse windows: memory the title's GPU heaps are in. XCL +/// commits their allocations whole; a part of one that the title gave back is found by the write +/// (`write_title`), not by a query of the pages (a VirtualQuery there walks to the end of the +/// committed run: 3-5 ms each for a 1-2 GB heap). +fn in_sparse_memory(p: usize, n: usize) -> bool { + let Some(u) = crate::gpu::uma::get() else { return false }; + n > 0 && u.is_sparse(p) && p.checked_add(n - 1).is_some_and(|e| u.is_sparse(e)) +} + +/// The bytes into the title's memory; false when the memory is not there (a write that faults). +unsafe fn write_title(p: usize, bytes: &[u8]) -> bool { + #[link(name = "ntdll", kind = "raw-dylib")] + extern "system" { + fn NtWriteVirtualMemory(process: HANDLE, at: *mut c_void, data: *const c_void, len: usize, done: *mut usize) -> i32; + } + let mut done = 0usize; + let st = NtWriteVirtualMemory(windows_sys::Win32::System::Threading::GetCurrentProcess(), p as *mut c_void, bytes.as_ptr().cast(), bytes.len(), &mut done); + st >= 0 && done == bytes.len() +} + +/// Where the CPU reads or writes `[p, p + n)` of the title's memory for a request: a GPU view of +/// its memory in a view window (`d3d12x::view_want`; the CPU cannot touch it) at the CPU view +/// behind it, whose pages the view's tiles show – a retail title gives DirectStorage the GPU +/// view's addresses; any other address as it is. None: the range runs past its GPU view, or its +/// pages are kept apart (the queue's page mappings: written there, it would land in another +/// page's bytes). +fn cpu_range(p: usize, n: usize) -> Option { + cpu_range_in(p, n, |a| crate::hle::d3d12x::view_want::is_view(a as u64)) +} + +/// `cpu_range`, with `in_view` saying which addresses lie in a view window. +fn cpu_range_in(p: usize, n: usize, in_view: impl Fn(usize) -> bool) -> Option { + if p == 0 || !in_view(p) { + return Some(p); + } + // (every page of the range, not only its first and last byte) + crate::hle::d3d12x::view_want::cpu_run(p as u64, n as u64).map(|c| c as usize) +} + /// Whether `n` bytes at `p` are committed, writable memory. fn writable(p: usize, n: usize) -> bool { let Some(end) = p.checked_add(n) else { return false }; @@ -879,13 +927,26 @@ fn note_request(r: &Request) { r.intermediate_size ); } + // destinations in a GPU view (written at its CPU view, `cpu_range`) + if !r.dest_physical_pages() && crate::hle::d3d12x::view_want::is_view(r.destination) { + static VIEW: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + static VIEW_BYTES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let k = VIEW.fetch_add(1, Ordering::Relaxed) + 1; + let b = VIEW_BYTES.fetch_add(n as u64, Ordering::Relaxed) + n as u64; + if k.is_power_of_two() { + crate::xlog_info!("DirectStorage: {k} requests so far into a GPU view of the title's memory ({} MB), written at its CPU view", b >> 20); + } + } } /// Run a request; the destination gets the bytes or nothing. unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[usize]>, dest_on_stack: bool, src_pages: Option<&[usize]>) -> Result<(), HRESULT> { let n = r.destination_size as usize; note_request(r); - if !r.dest_physical_pages() && !writable(r.destination as usize, n) { + // (a page list is read where it is: only a destination of bytes can be a GPU view) + let dest = if r.dest_physical_pages() { r.destination as usize } else { cpu_range(r.destination as usize, n).ok_or(E_ACCESS_VIOLATION)? }; + let sparse_dest = !r.dest_physical_pages() && in_sparse_memory(dest, n); + if !r.dest_physical_pages() && !sparse_dest && !writable(dest, n) { return Err(E_ACCESS_VIOLATION); } let src: Vec = if r.memory_source() { @@ -896,11 +957,12 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us return Err(E_ACCESS_VIOLATION); } } else { - if !crate::gpu::shader::readable(r.source as usize, r.source_size as usize) { + let at = cpu_range(r.source as usize, b.len()).ok_or(E_ACCESS_VIOLATION)?; + if !crate::gpu::shader::readable(at, r.source_size as usize) { return Err(E_ACCESS_VIOLATION); } if !b.is_empty() { - std::ptr::copy_nonoverlapping(r.source as *const u8, b.as_mut_ptr(), b.len()); + std::ptr::copy_nonoverlapping(at as *const u8, b.as_mut_ptr(), b.len()); } } b @@ -964,11 +1026,10 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us // A page number of 0 in the snapshot taken at enqueue (no page has it): the entry is // read again now. A retail title keeps its page arrays in its own tables and fills an // entry after EnqueueRequest – its streaming requests were refused by the thousand - // with page 0. An array that had its pages at enqueue stays as it was snapshotted - // (titles also pass arrays on the stack). The title keeps an array with such an entry - // until the request is done: one it has freed or reused meanwhile cannot be told from - // a late fill. Read like the snapshot (`read_own`): an array unmapped since then fails - // the request instead of faulting in this worker (#476). + // with page 0. The title keeps an array with such an entry until the request is done: one + // it has freed or reused meanwhile cannot be told from a late fill. Read like the snapshot + // (`read_own`): an array unmapped since then fails the request instead of faulting in this + // worker (#476). let late: Vec; let pages = if pages.contains(&0) { let mut now = vec![0usize; pages.len()]; @@ -985,7 +1046,16 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us return Err(E_ACCESS_VIOLATION); } } else if n > 0 { - std::ptr::copy_nonoverlapping(payload.as_ptr(), r.destination as *mut u8, n); + crate::hle::kernelx::pagelog::note("DirectStorage write", dest, 0, n); + if sparse_dest { + if !write_title(dest, &payload[..n]) { + return Err(E_ACCESS_VIOLATION); + } + } else { + std::ptr::copy_nonoverlapping(payload.as_ptr(), dest as *mut u8, n); + } + // (where the bytes are: the CPU view's pages are watched and shown, a GPU view's are not) + crate::hle::d3d12x::title_textures::note_known_write(dest, n); } Ok(()) } @@ -1079,6 +1149,11 @@ struct QueueInner { pool_override: OnceLock>>, #[cfg(test)] test_hook: OnceLock, + /// a half-full queue submits by itself (not when made with `AutoSubmitDisabled`) + auto_submit: bool, + /// signalled when pending entries leave (`Submit`, a cancel, `Close`): a full queue made with + /// `AutoSubmitDisabled` holds its next enqueue until then + room: Condvar, } impl QueueInner { @@ -1109,6 +1184,7 @@ impl QueueInner { return; } let batch = std::mem::take(&mut self.pending.lock().unwrap().entries); + self.room.notify_all(); if batch.is_empty() { return; } @@ -1213,9 +1289,19 @@ impl QueueInner { } } + /// A queue made with `AutoSubmitDisabled` that holds `capacity` entries: wait until the title's + /// `Submit` (from another thread), a cancel or `Close` takes some, as the console's queue + /// stalls an enqueue at capacity. Others never wait: they submit when half full. + fn wait_for_room<'a>(&self, mut p: std::sync::MutexGuard<'a, Pending>) -> std::sync::MutexGuard<'a, Pending> { + while !self.auto_submit && p.entries.len() >= self.capacity && !self.closed.load(Ordering::Acquire) { + p = self.room.wait(p).unwrap(); + } + p + } + fn enqueue(self: &Arc, e: Entry) { let n = { - let mut p = self.pending.lock().unwrap(); + let mut p = self.wait_for_room(self.pending.lock().unwrap()); if self.closed.load(Ordering::Acquire) { return; } @@ -1228,7 +1314,7 @@ impl QueueInner { p.entries.len() }; // as on PC: a half-full queue submits by itself - if n >= (self.capacity / 2).max(1) { + if self.auto_submit && n >= (self.capacity / 2).max(1) { self.submit(); } } @@ -1244,7 +1330,7 @@ impl QueueInner { fn enqueue_numbered(self: &Arc, entry: impl FnOnce(u64) -> Entry) { let n = { - let mut p = self.pending.lock().unwrap(); + let mut p = self.wait_for_room(self.pending.lock().unwrap()); if self.closed.load(Ordering::Acquire) { return; } @@ -1253,7 +1339,7 @@ impl QueueInner { p.entries.push(entry(seq)); p.entries.len() }; - if n >= (self.capacity / 2).max(1) { + if self.auto_submit && n >= (self.capacity / 2).max(1) { self.submit(); } } @@ -1291,6 +1377,11 @@ fn queue_vtbl() -> &'static [usize] { } unsafe extern "system" fn factory_create_queue(_p: *mut c_void, desc: *const u8, riid: *const GUID, out: *mut *mut c_void) -> HRESULT { + create_queue(desc, riid, out, true) +} + +/// A queue from the 0x18 bytes of `desc` (`auto_submit`: a half-full queue submits by itself). +unsafe fn create_queue(desc: *const u8, riid: *const GUID, out: *mut *mut c_void, auto_submit: bool) -> HRESULT { if out.is_null() { return E_POINTER; } @@ -1331,6 +1422,8 @@ unsafe extern "system" fn factory_create_queue(_p: *mut c_void, desc: *const u8, pool_override: OnceLock::new(), #[cfg(test)] test_hook: OnceLock::new(), + auto_submit, + room: Condvar::new(), }); let o = new_object(queue_vtbl(), inner); let hr = queue_qi(o, riid, out); @@ -1476,6 +1569,7 @@ unsafe extern "system" fn queue_cancel(p: *mut c_void, mask: u64, value: u64) { let cutoff = { let mut pend = q.pending.lock().unwrap(); pend.entries.retain(|e| !matches!(e, Entry::Request { req, .. } | Entry::Refused { req, .. } if req.tag & mask == value)); + q.room.notify_all(); pend.next_seq.saturating_sub(1) }; if cutoff == 0 { @@ -1503,6 +1597,8 @@ unsafe extern "system" fn queue_close(p: *mut c_void) { std::mem::take(&mut pend.entries) } }; + // an enqueue held by a full queue goes on (and finds the queue closed) + q.room.notify_all(); for e in drained { if let Entry::Status(s, i) = e { if let Some(slot) = s.slots.get(i as usize) { @@ -1603,6 +1699,114 @@ mod tests { b } + /// A queue the newer factory makes with `AutoSubmitDisabled` runs its requests at `Submit` + /// only, not when it is half full; one made without the option still submits by itself. + #[test] + fn a_queue_with_auto_submit_disabled_waits_for_submit() { + use std::time::{Duration, Instant}; + unsafe { + let mut f = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&IID_FACTORY_X1, &mut f), S_OK); + let vt = *(f as *const *const usize); + let create_queue1: unsafe extern "system" fn(*mut c_void, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(10)); + for (options, by_itself) in [(AUTO_SUBMIT_DISABLED, false), (0, true)] { + let mut desc = [0u8; 0x20]; + desc[0..4].copy_from_slice(&1u32.to_le_bytes()); // memory source + desc[8..10].copy_from_slice(&4u16.to_le_bytes()); // capacity 4: half full at 2 + desc[10] = 2; + desc[0x18..0x20].copy_from_slice(&options.to_le_bytes()); + let mut q = std::ptr::null_mut(); + assert_eq!(create_queue1(f, desc.as_ptr(), &IID_QUEUE_X1, &mut q), S_OK); + let qv = *(q as *const *const usize); + let enqueue: unsafe extern "system" fn(*mut c_void, *const u8) = std::mem::transmute(*qv.add(3)); + let submit: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(*qv.add(6)); + + let src = [0x5Au8; 64]; + let dst = [vec![0u8; 64], vec![0u8; 64]]; + for d in &dst { + enqueue(q, request(SOURCE_MEMORY_BIT, d.as_ptr() as u64, 64, src.as_ptr() as u64, 0, 64).as_ptr()); + } + let done = || dst.iter().all(|d| d.iter().all(|b| std::ptr::read_volatile(b) == 0x5A)); + let t = Instant::now(); + while !done() && t.elapsed() < Duration::from_millis(300) { + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(done(), by_itself, "options {options:#x}: a half-full queue submits by itself only without AutoSubmitDisabled"); + if !by_itself { + submit(q); + let t = Instant::now(); + while !done() && t.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(5)); + } + assert!(done(), "Submit runs the queue's requests"); + } + queue_close(q); + queue_release(q); + } + } + } + + /// A full queue made with `AutoSubmitDisabled` holds the next enqueue until another thread's + /// `Submit` takes its entries, and `Close` lets a held enqueue go (into the closed queue). + #[test] + fn a_full_queue_with_auto_submit_disabled_holds_an_enqueue_until_submit() { + use std::time::{Duration, Instant}; + unsafe { + let mut f = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&IID_FACTORY_X1, &mut f), S_OK); + let vt = *(f as *const *const usize); + let create_queue1: unsafe extern "system" fn(*mut c_void, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(10)); + let mut desc = [0u8; 0x20]; + desc[0..4].copy_from_slice(&1u32.to_le_bytes()); // memory source + desc[8..10].copy_from_slice(&2u16.to_le_bytes()); // capacity 2 + desc[10] = 2; + desc[0x18..0x20].copy_from_slice(&AUTO_SUBMIT_DISABLED.to_le_bytes()); + for close_instead in [false, true] { + let mut q = std::ptr::null_mut(); + assert_eq!(create_queue1(f, desc.as_ptr(), &IID_QUEUE_X1, &mut q), S_OK); + let qv = *(q as *const *const usize); + let enqueue: unsafe extern "system" fn(*mut c_void, *const u8) = std::mem::transmute(*qv.add(3)); + let submit: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(*qv.add(6)); + + let src = [0x3Cu8; 64]; + let dst = [vec![0u8; 64], vec![0u8; 64], vec![0u8; 64]]; + let req = |k: usize| request(SOURCE_MEMORY_BIT, dst[k].as_ptr() as u64, 64, src.as_ptr() as u64, 0, 64); + enqueue(q, req(0).as_ptr()); + enqueue(q, req(1).as_ptr()); + // the queue is full: a third enqueue waits + let (third, qa) = (req(2), q as usize); + let t = std::thread::spawn(move || { + let e: unsafe extern "system" fn(*mut c_void, *const u8) = enqueue; + e(qa as *mut c_void, third.as_ptr()); + }); + std::thread::sleep(Duration::from_millis(200)); + assert!(!t.is_finished(), "an enqueue into a full queue waits"); + if close_instead { + queue_close(q); + } else { + submit(q); + } + let t0 = Instant::now(); + while !t.is_finished() && t0.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(5)); + } + assert!(t.is_finished(), "{} lets the held enqueue go", if close_instead { "Close" } else { "Submit" }); + t.join().unwrap(); + if !close_instead { + submit(q); + let done = || dst.iter().all(|d| d.iter().all(|b| std::ptr::read_volatile(b) == 0x3C)); + let t0 = Instant::now(); + while !done() && t0.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(5)); + } + assert!(done(), "all three requests ran"); + queue_close(q); + } + queue_release(q); + } + } + } + #[test] fn a_refused_factory_iid_returns_e_nointerface_and_clears_out() { unsafe { @@ -1635,6 +1839,70 @@ mod tests { assert_eq!(Request::parse(&request(0, 0, 64, 0x2000, 0, 64)).check(false), Err(E_ACCESS_VIOLATION)); } + /// A destination (or memory source) in a GPU view of the title's memory is reached at the CPU + /// view behind it – the CPU cannot touch the GPU view, and such a request failed with + /// E_ACCESS_VIOLATION; a range that runs past the view is refused, and every other address, + /// every one without view windows too, is used as it is. + #[test] + fn a_range_in_a_gpu_view_is_reached_at_its_cpu_view() { + use crate::hle::kernelx::mirrors; + const SIZE: usize = 67 << 16; + // (addresses far above anything Windows hands out: only the pairing is used) + let (c, g) = (0x7250_0000_0000usize, 0x7258_0000_0000usize); + mirrors::reserved(c, SIZE, 0x2040_2000, 0x04); + assert!(mirrors::reserved(g, SIZE, 0x2040_2000, 0x801)); + let view = |a: usize| (g..g + SIZE).contains(&a); + assert_eq!(cpu_range_in(g + 0x1_2340, 0x800, view), Some(c + 0x1_2340)); + assert_eq!(cpu_range_in(g + SIZE - 0x100, 0x100, view), Some(c + SIZE - 0x100)); + assert_eq!(cpu_range_in(g + SIZE - 0x100, 0x101, view), None, "past the view's end"); + assert_eq!(cpu_range_in(g, 0, view), Some(c)); + assert_eq!(cpu_range_in(c + 0x40, 0x100, view), Some(c + 0x40), "the CPU view itself"); + assert_eq!(cpu_range_in(g + 0x40, 0x100, |_| false), Some(g + 0x40), "no view windows: as it was"); + mirrors::released(c); + assert_eq!(cpu_range_in(g + 0x40, 0x100, view), Some(g + 0x40), "unpaired: as it was (and refused where it is written)"); + } + + /// A range over GPU-view pages the queue's page mappings keep apart is refused (it would be + /// written into another page's bytes); one inside a single page is reached where that page is + /// kept, and one over pages never named at the CPU view, as before. + #[test] + fn a_range_over_gpu_view_pages_kept_apart_is_refused() { + use crate::hle::d3d12x::view_want::cpu_run; + use crate::hle::kernelx::{self, mirrors::{self, PAGE}}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + unsafe { + if crate::gpu::uma::get().is_none() { + return crate::gpu::recomp::runner::skip_test("no unified memory"); + } + // a pair of views of a size of the test's own, and two physical pages at their home: + // the pool + let size = 229 * PAGE; + let c = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE, PAGE_READWRITE) as usize; + let g = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE, PAGE_READWRITE) as usize; + assert!(c != 0 && g != 0); + mirrors::reserved(c, size, 0x2040_2000, 0x04); + assert!(mirrors::reserved(g, size, 0x2040_2000, 0x801)); + let (mut n, mut pages) = (2usize, [0usize; 2]); + assert_eq!(kernelx::AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let home = kernelx::MapTitlePhysicalPages(std::ptr::null_mut(), 2, 0, 4, pages.as_mut_ptr()) as usize; + assert_ne!(home, 0); + // pool page 1 at view page 0, pool page 0 at view page 1: kept apart + let ranges: [[u32; 3]; 2] = [[0, 1, 1], [0, 0, 1]]; + let batch = [g as u64, 2, ranges.as_ptr() as u64]; + assert!(mirrors::apply_batches(1, batch.as_ptr() as usize, home, 2).is_some()); + let view = |a: usize| (g..g + size).contains(&a); + assert_eq!(cpu_run(g as u64, 2 * PAGE as u64), None); + assert_eq!(cpu_range_in(g + PAGE - 8, 16, view), None, "over two pages kept apart"); + assert_eq!(cpu_range_in(g + 8, 16, view), Some(home + PAGE + 8), "inside one: where it is kept"); + assert_eq!(cpu_range_in(g + PAGE + 8, 16, view), Some(home + 8)); + assert_eq!(cpu_range_in(g + 2 * PAGE, 2 * PAGE, view), Some(c + 2 * PAGE), "pages never named: the CPU view"); + kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()); + mirrors::released(c); + VirtualFree(c as *mut c_void, 0, MEM_RELEASE); + VirtualFree(g as *mut c_void, 0, MEM_RELEASE); + } + } + #[test] fn a_memory_queue_inflates_zlib_and_reports_through_status_and_errors() { unsafe { diff --git a/crates/xcl/src/hle/dstorage/parallel.rs b/crates/xcl/src/hle/dstorage/parallel.rs index 198f4a86e8..c62aff029c 100644 --- a/crates/xcl/src/hle/dstorage/parallel.rs +++ b/crates/xcl/src/hle/dstorage/parallel.rs @@ -1,7 +1,7 @@ //! Bounded preparation of file-backed zlib requests. The queue thread owns //! file reads, cancellation checks, and retirement; decoders own private buffers. -use super::{note_request, read_exact_at, writable, Entry, FileInner, QueueInner, Request, E_ABORT, E_ACCESS_VIOLATION, E_FILE_HANDLE, E_ZLIB_DATA}; +use super::{cpu_range, in_sparse_memory, note_request, read_exact_at, writable, Entry, FileInner, QueueInner, Request, E_ABORT, E_ACCESS_VIOLATION, E_FILE_HANDLE, E_ZLIB_DATA}; use crate::util::{HRESULT, S_OK}; use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; @@ -423,7 +423,9 @@ impl<'a> Pipeline<'a> { } note_request(&req); let loaded = (|| { - if !writable(req.destination as usize, req.destination_size as usize) { + let n = req.destination_size as usize; + let at = cpu_range(req.destination as usize, n).ok_or(E_ACCESS_VIOLATION)?; + if !in_sparse_memory(at, n) && !writable(at, n) { return Err(E_ACCESS_VIOLATION); } let handle = task.file.as_ref().and_then(|file| file.handle()).ok_or(E_FILE_HANDLE)?; @@ -459,10 +461,12 @@ impl<'a> Pipeline<'a> { notify_test(self.queue, TestEvent::BeforeRetire(task.seq)); let result = result.and_then(|payload| { let n = task.req.destination_size as usize; - let at = task.req.destination as usize; + // (a GPU view's bytes go to its CPU view; the pair may have gone meanwhile) + let at = cpu_range(task.req.destination as usize, n).ok_or(E_ACCESS_VIOLATION)?; // The title can unmap the destination while a decoder runs. The late // check resolves lazy pages, and the kernel copy handles a subsequent unmap. - if writable(at, n) && (n == 0 || write_destination(at, &payload.bytes[..n])) { + if (in_sparse_memory(at, n) || writable(at, n)) && (n == 0 || write_destination(at, &payload.bytes[..n])) { + crate::hle::d3d12x::title_textures::note_known_write(at, n); Ok(()) } else { Err(E_ACCESS_VIOLATION) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index f752450bad..eb20edb1ef 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -169,8 +169,9 @@ const MEM_WRITE_WATCH: u32 = 0x20_0000; /// video was its colour of zero luma and chroma, a green screen. `source` names the CPU view /// behind an address of such a GPU view, which `d3d12x::title_textures` reads and watches. pub mod mirrors { - use std::collections::BTreeMap; - use std::sync::Mutex; + use std::collections::{BTreeMap, BTreeSet, HashMap}; + use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; + use std::sync::{LazyLock, Mutex, RwLock}; /// MEM_LARGE_PAGES | MEM_PHYSICAL: the console's 64 KiB pages const PAGES_64K: u32 = 0x2040_0000; @@ -184,6 +185,9 @@ pub mod mirrors { gpu: BTreeMap, } static STATE: Mutex = Mutex::new(State { cpu: Vec::new(), gpu: BTreeMap::new() }); + /// The pairs in `STATE.gpu`: while there are none no GPU view shows CPU memory, and a + /// decommit asks nothing more (`cpu_view_part`). + static PAIRS: AtomicUsize = AtomicUsize::new(0); /// Whether `(t, p)` is a CPU-inaccessible GPU-view alias reservation (`MEM_64K_PAGES` /// reserve with `PAGE_GRAPHICS_NOACCESS | PAGE_NOACCESS`). @@ -191,30 +195,91 @@ pub mod mirrors { t & PAGES_64K == PAGES_64K && t & 0x1000 == 0 && p & GRAPHICS_NOACCESS != 0 && p & 0xFF == super::mem::PAGE_NOACCESS } + /// The most recent CPU view of `size` bytes without a GPU view yet. + fn unpaired_cpu(s: &State, size: usize) -> Option { + let taken: Vec = s.gpu.values().map(|&(_, c)| c).collect(); + s.cpu.iter().rev().find(|&&(b, n)| n == size && !taken.contains(&b)).map(|&(b, _)| b) + } + + /// Whether a GPU-view reservation of `size` bytes made now would be paired (`reserved`): a + /// CPU view of that size waits for its GPU view. + pub fn would_pair(size: usize) -> bool { + unpaired_cpu(&STATE.lock().unwrap(), size).is_some() + } + /// A reservation of `size` bytes at `base` with allocation type `t` and protection `p`. - pub fn reserved(base: usize, size: usize, t: u32, p: u32) { + /// True: it is a GPU view and was paired with its CPU view. + pub fn reserved(base: usize, size: usize, t: u32, p: u32) -> bool { if t & PAGES_64K != PAGES_64K || t & 0x1000 != 0 { - return; + return false; } let mut s = STATE.lock().unwrap(); if p & GRAPHICS_NOACCESS != 0 && p & 0xFF == super::mem::PAGE_NOACCESS { - // the most recent CPU view of the same size without a GPU view yet - let taken: Vec = s.gpu.values().map(|&(_, c)| c).collect(); - if let Some(&(cpu, _)) = s.cpu.iter().rev().find(|&&(b, n)| n == size && !taken.contains(&b)) { - s.gpu.insert(base, (size, cpu)); + if let Some(cpu) = unpaired_cpu(&s, size) { + if s.gpu.insert(base, (size, cpu)).is_none() { + PAIRS.fetch_add(1, Ordering::Release); + } + drop(s); crate::xlog_info!("kernelx: reservation {base:#x} ({size:#x} bytes, no CPU access) is the GPU view of {cpu:#x}"); + // what `source` says for these addresses changed (readers of GPU views look again) + super::note_gpu_view_change(base, size); + return true; } } else if p & 0xFF != super::mem::PAGE_NOACCESS { s.cpu.push((base, size)); } + false } - /// The reservation at `base` was released. + /// The reservation at `base` was released (before its address can be handed out again: a + /// new reservation there would otherwise still be paired). A pair that goes takes the + /// tiles that showed its CPU view with it (`sparse::forget_mirrors`, told with this lock + /// dropped: sparse asks `source` with its own held), and both addresses may be given out anew. pub fn released(base: usize) { let mut s = STATE.lock().unwrap(); s.cpu.retain(|&(b, _)| b != base); - s.gpu.remove(&base); - s.gpu.retain(|_, &mut (_, c)| c != base); + // (GPU view, size, CPU view) + let mut gone: Vec<(usize, usize, usize)> = s.gpu.remove(&base).map(|(n, c)| (base, n, c)).into_iter().collect(); + s.gpu.retain(|&g, &mut (n, c)| { + if c == base { + gone.push((g, n, c)); + } + c != base + }); + PAIRS.fetch_sub(gone.len(), Ordering::Release); + // the pages the page-mapping method named in the views that go (with the views' lock held) + if !gone.is_empty() && MAPPED.load(Ordering::Acquire) != 0 { + let mut p = write_pages(); + for &(g, n, _) in &gone { + let named: Vec = p.shown.range(g..g + n).map(|(&k, _)| k).collect(); + for k in named { + p.unset(k); + } + } + } + drop(s); + for (g, n, c) in gone { + super::note_gpu_view_change(g, n); + for (a, len) in [(g, n), (c, n)] { + #[cfg(test)] + super::tests::FORGOTTEN.with(|f| f.borrow_mut().push((a, len))); + crate::hle::d3d12x::sparse::forget_mirrors(a, len); + } + } + } + + /// The part of `[a, a + n)` (`n == 0`: from `a` to the end of its reservation) that lies in + /// the CPU view of a pair – memory whose pages tiles of its GPU view may show – as (start, + /// bytes). One atomic load while nothing is paired. + pub fn cpu_view_part(a: usize, n: usize) -> Option<(usize, usize)> { + if PAIRS.load(Ordering::Acquire) == 0 { + return None; + } + let s = STATE.lock().unwrap(); + s.gpu.values().find_map(|&(size, c)| { + let end = c + size; + (a >= c && a < end).then(|| (a, if n == 0 { end - a } else { n.min(end - a) })) + }) } /// The CPU-view address behind `va` when `va` lies in a GPU view. @@ -232,6 +297,577 @@ pub mod mirrors { .filter_map(|(&gpu, &(size, cpu))| (cpu_va >= cpu && cpu_va < cpu + size).then(|| gpu + (cpu_va - cpu))) .collect() } + + /// Bytes of a page the queue's page-mapping method maps (the console's 64 KiB pages). + pub const PAGE: usize = 0x1_0000; + + /// The mappings of one call of the queue's page-mapping method, `CopyPageMappingsBatchX(count, + /// batches, pool, pool pages, …)` (queue #29; #31 in the newer layout), checked whole: (GPU-view + /// page, the pool page it is given or `None`: unmapped), in the call's order. `count` batches + /// of 24 bytes – the first destination address (u64), the number of ranges (u32), a pointer + /// to them at +16 – each range three u32: the kind (0: `count` pool pages from `start` on, + /// 1: pool page `start` at each of `count` pages, 2: unmapped, 3: left as they are), `start` + /// and `count`. The pool is `pool_pages` pages of `PAGE` at `pool`. `None` when a batch or a + /// range is not readable, a range leaves the pool or has an unknown kind, or the call names + /// over `MOST` pages. No lock. + pub unsafe fn decode_batches(count: u32, batches: usize, pool: usize, pool_pages: u32) -> Option)>> { + const BATCH: usize = 24; + const RANGE: usize = 12; + const MOST: usize = 1 << 20; + let readable = crate::gpu::shader::readable; + let n = count as usize; + if n == 0 { + return Some(Vec::new()); + } + if n > MOST || !readable(batches, n * BATCH) { + return None; + } + let mut changes: Vec<(usize, Option)> = Vec::new(); + for b in 0..n { + let p = batches + b * BATCH; + let dest = (p as *const u64).read_unaligned() as usize & !(PAGE - 1); + let ranges_n = ((p + 8) as *const u32).read_unaligned() as usize; + let ranges = ((p + 16) as *const usize).read_unaligned(); + if ranges_n == 0 { + continue; + } + if ranges_n > MOST || !readable(ranges, ranges_n * RANGE) { + return None; + } + let mut at = dest; + for r in 0..ranges_n { + let q = (ranges + r * RANGE) as *const u32; + let (kind, start, len) = (q.read_unaligned(), q.add(1).read_unaligned() as usize, q.add(2).read_unaligned() as usize); + let inside = |k: usize| start.checked_add(k).is_some_and(|e| e <= pool_pages as usize); + if changes.len() + len > MOST || at.checked_add(len * PAGE).is_none() { + return None; + } + match kind { + 0 if inside(len) => changes.extend((0..len).map(|k| (at + k * PAGE, Some(pool + (start + k) * PAGE)))), + 1 if start < pool_pages as usize => changes.extend((0..len).map(|k| (at + k * PAGE, Some(pool + start * PAGE)))), + 2 => changes.extend((0..len).map(|k| (at + k * PAGE, None))), + 3 => {} + _ => return None, + } + at += len * PAGE; + } + } + Some(changes) + } + + /// What a GPU-view page the page-mapping method named shows (`apply_batches`). + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub struct Shown { + /// the physical page (0: nothing) + pub page: usize, + /// where XCL keeps that page's bytes now (0: nothing) + pub at: usize, + /// the place is memory whose decommit and release kernelx sees: a tile may show it + pub tile: bool, + /// the call (`calls`) that last changed what it shows + pub call: u64, + /// its key in `Pages::log` + pub seq: u64, + } + + /// The record of the page-mapping method: the GPU-view pages it named, and what leads to them. + #[derive(Default)] + struct Pages { + /// GPU-view page → what it shows + shown: BTreeMap, + /// physical page → the GPU-view pages that show it + by_page: HashMap>, + /// (place, GPU-view page); pages with no place are not in it + by_at: BTreeSet<(usize, usize)>, + /// 16 MiB block of a place (`place >> 24`) → the pages kept in it + blocks: HashMap, + /// seq → GPU-view page: one entry a page, its last change + log: BTreeMap, + seq: u64, + } + + impl Pages { + /// `g` shows `page`, kept at `at`, from `call` on. False, and nothing logged, when it + /// shows that page at that place already (the title named the mapping it has). + fn set(&mut self, g: usize, page: usize, at: usize, tile: bool, call: u64) -> bool { + if self.shown.get(&g).is_some_and(|e| e.page == page && e.at == at) { + return false; + } + self.unlink(g); + self.seq += 1; + let seq = self.seq; + if page != 0 { + self.by_page.entry(page).or_default().push(g); + } + self.link_at(at, g); + self.log.insert(seq, g); + self.shown.insert(g, Shown { page, at, tile, call, seq }); + MAPPED.store(self.shown.len(), Ordering::Release); + CHANGE_SEQ.store(seq, Ordering::Release); + true + } + + /// `g` leaves the record (its view went). + fn unset(&mut self, g: usize) { + self.unlink(g); + self.shown.remove(&g); + MAPPED.store(self.shown.len(), Ordering::Release); + } + + /// `g`'s entry out of the indexes and the log (it stays in `shown`). + fn unlink(&mut self, g: usize) { + let Some(e) = self.shown.get(&g).copied() else { return }; + if let Some(v) = self.by_page.get_mut(&e.page) { + v.retain(|&x| x != g); + if v.is_empty() { + self.by_page.remove(&e.page); + } + } + self.unlink_at(e.at, g); + self.log.remove(&e.seq); + } + + /// `g` is kept at `at` (0: nothing) in `by_at` and `blocks`. + fn link_at(&mut self, at: usize, g: usize) { + if at != 0 { + self.by_at.insert((at, g)); + let n = self.blocks.entry(at >> 24).or_insert(0); + *n += 1; + if *n == 1 { + SHOWN_GEN.fetch_add(1, Ordering::Release); + } + } + } + + /// `g` is no longer kept at `at` (0: nothing) in `by_at` and `blocks`. + fn unlink_at(&mut self, at: usize, g: usize) { + if at != 0 { + self.by_at.remove(&(at, g)); + if let Some(n) = self.blocks.get_mut(&(at >> 24)) { + *n -= 1; + if *n == 0 { + self.blocks.remove(&(at >> 24)); + SHOWN_GEN.fetch_add(1, Ordering::Release); + } + } + } + } + + /// The page `g` shows is kept at `at` now (0: nowhere), with `tile` for it. A move + /// keeps its call and its place in the log; `changed` (a call) logs it as a change of + /// what `g` shows: its bytes appear or go. + fn place(&mut self, g: usize, at: usize, tile: bool, changed: Option) { + let Some(mut e) = self.shown.get(&g).copied() else { return }; + self.unlink_at(e.at, g); + self.link_at(at, g); + (e.at, e.tile) = (at, tile); + if let Some(call) = changed { + self.log.remove(&e.seq); + self.seq += 1; + (e.seq, e.call) = (self.seq, call); + self.log.insert(e.seq, g); + CHANGE_SEQ.store(e.seq, Ordering::Release); + } + self.shown.insert(g, e); + } + } + + /// The record, under a lock of its own: `STATE` → `PAGES` where both are held (`apply_batches`, + /// `released`); every reader takes it alone. Nothing is called with it held. + static PAGES: LazyLock> = LazyLock::new(Default::default); + /// The pages in the record: while there are none, a reader takes today's path after one + /// atomic load. + static MAPPED: AtomicUsize = AtomicUsize::new(0); + /// The calls of the page-mapping method that were recorded. + static CALLS: AtomicU64 = AtomicU64::new(0); + /// `Pages::seq`: the last change of the record. + static CHANGE_SEQ: AtomicU64 = AtomicU64::new(0); + /// Counts the times a 16 MiB block came to hold the place of a shown page, or ceased to. + static SHOWN_GEN: AtomicU64 = AtomicU64::new(0); + /// GPU-view pages whose page moved, and whose place followed it (`page_at`). + static MOVED: AtomicU64 = AtomicU64::new(0); + + fn read_pages() -> std::sync::RwLockReadGuard<'static, Pages> { + PAGES.read().unwrap_or_else(|e| e.into_inner()) + } + + fn write_pages() -> std::sync::RwLockWriteGuard<'static, Pages> { + PAGES.write().unwrap_or_else(|e| e.into_inner()) + } + + /// What one `apply_batches` call did, in 64 KiB pages. + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] + pub struct Mapped { + /// given a pool page with a physical page the title mapped there + pub mapped: u64, + /// unmapped + pub unmapped: u64, + /// given a pool page with no physical page mapped there (or one with no place): they + /// show nothing + pub empty: u64, + /// outside every GPU view: not recorded + pub elsewhere: u64, + } + + /// One call of the queue's page-mapping method (`decode_batches`): each page of a GPU view it + /// names records the physical page the title had mapped at its pool page then (the console + /// copies the mapping at the call; `Away::title`) and where XCL keeps that page's bytes now. + /// A pool page with no page mapped shows nothing. `None` – nothing recorded – for a call + /// `decode_batches` refuses. AWAY is held from the lookup to the record, so a page that moves + /// in between cannot be recorded at the place it left. + pub unsafe fn apply_batches(count: u32, batches: usize, pool: usize, pool_pages: u32) -> Option { + let changes = decode_batches(count, batches, pool, pool_pages)?; + let call = CALLS.fetch_add(1, Ordering::AcqRel) + 1; + let away = super::AWAY.lock().unwrap(); + // (GPU-view page, None: unmapped, or (physical page, place, tile) with 0 for none) + let changes: Vec<(usize, Option<(usize, usize, bool)>)> = changes + .into_iter() + .map(|(g, to)| { + let to = to.map(|pool| { + let page = away.as_ref().and_then(|a| a.title.get(&pool).copied()).unwrap_or(0); + let (at, home) = if page != 0 { super::place_of(away.as_ref(), page) } else { (0, false) }; + (page, at, at != 0 && (home || super::freeing_is_seen(at))) + }); + (g, to) + }) + .collect(); + // (the views stay while the record is written) + let s = STATE.lock().unwrap(); + let in_view = |va: usize| s.gpu.range(..=va).next_back().is_some_and(|(&g, &(size, _))| va < g + size); + let mut pages = write_pages(); + let mut out = Mapped::default(); + // (the GPU-view pages that show something else now) + let mut changed: Vec = Vec::new(); + for (g, to) in changes { + if !in_view(g) { + out.elsewhere += 1; + continue; + } + let set = match to { + None => { + out.unmapped += 1; + pages.set(g, 0, 0, false, call) + } + Some((page, at, _)) if page == 0 || at == 0 => { + out.empty += 1; + pages.set(g, 0, 0, false, call) + } + Some((page, at, tile)) => { + out.mapped += 1; + pages.set(g, page, at, tile, call) + } + }; + if set { + changed.push(g); + } + } + drop(pages); + drop(s); + // (the tiles over them are linked again at the next submit) + crate::hle::d3d12x::sparse::remapped(&changed); + drop(away); + Some(out) + } + + /// What an address shows to the GPU (`shows`). + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub enum Shows { + /// not in a GPU view + NoView, + /// a page the page-mapping method never named: the CPU view at the same offset (this + /// address of it) + Same(usize), + /// the mapped page: this byte's address where it is kept; `tile`: a tile may show it + Page { at: usize, tile: bool }, + /// nothing (zeros): unmapped, or no page behind it + Nothing, + } + + /// What `va` shows. One atomic load more than `source` while nothing is mapped. + pub fn shows(va: usize) -> Shows { + if MAPPED.load(Ordering::Acquire) != 0 { + let p = read_pages(); + if let Some(e) = p.shown.get(&(va & !(PAGE - 1))) { + return if e.at == 0 { Shows::Nothing } else { Shows::Page { at: e.at + (va & (PAGE - 1)), tile: e.tile } }; + } + } + source(va).map_or(Shows::NoView, Shows::Same) + } + + /// The first and the last 64 KiB page of `[va, va + len)` (`len` 0: one byte). + fn span(va: usize, len: usize) -> (usize, usize) { + (va & !(PAGE - 1), va.saturating_add(len.max(1) - 1) & !(PAGE - 1)) + } + + /// Where the pages of `[va, va + len)` are read: `None` when the page-mapping method named + /// none of them. Else `at` gets one address for each 64 KiB page from `va`'s on: where the + /// mapped page is kept, 0 for nothing, and for a page never named the CPU view's same + /// offset (outside a view the page itself) with bit 0 set (read as any title memory). The + /// counts: [kept elsewhere, kept at the CPU view's same offset, never named, nothing]. + pub fn resolve(va: usize, len: usize, at: &mut Vec) -> Option<[u32; 4]> { + at.clear(); + if MAPPED.load(Ordering::Acquire) == 0 { + return None; + } + let (first, last) = span(va, len); + let view = STATE.lock().unwrap().gpu.range(..=first).next_back().map(|(&g, &(size, c))| (g, size, c)); + let same = |g: usize| match view { + Some((b, size, c)) if g >= b && g < b + size => c + (g - b), + _ => g, + }; + let p = read_pages(); + if p.shown.range(first..=last).next().is_none() { + return None; + } + let mut counts = [0u32; 4]; + let mut g = first; + loop { + at.push(match p.shown.get(&g) { + None => { + counts[2] += 1; + same(g) | 1 + } + Some(e) if e.at == 0 => { + counts[3] += 1; + 0 + } + Some(e) => { + counts[(e.at == same(g)) as usize] += 1; + e.at + } + }); + if g == last { + break; + } + g += PAGE; + } + Some(counts) + } + + /// Whether the page-mapping method named a page of `[va, va + len)`. + pub fn touched(va: usize, len: usize) -> bool { + if MAPPED.load(Ordering::Acquire) == 0 { + return false; + } + let (first, last) = span(va, len); + read_pages().shown.range(first..=last).next().is_some() + } + + /// Whether any page of a GPU view is in the record. + pub fn any_mapped() -> bool { + MAPPED.load(Ordering::Acquire) != 0 + } + + /// The calls of the page-mapping method recorded so far. + pub fn calls() -> u64 { + CALLS.load(Ordering::Acquire) + } + + /// Whether the queue's page-mapping method is applied (`apply_batches`). Off + /// (XCL_PAGE_MAPPINGS=0) its queue slot is the stub it was and the record stays empty. + pub fn page_mappings() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = page_mappings_on(std::env::var("XCL_PAGE_MAPPINGS").ok().as_deref()); + if !on { + crate::xlog_info!("kernelx: XCL_PAGE_MAPPINGS=0 – the queue's page mappings (CopyPageMappingsBatchX) are left out: a GPU-view page shows the CPU view at the same offset"); + } + on + }) + } + + /// XCL_PAGE_MAPPINGS `v`: on unless it is 0. + pub fn page_mappings_on(v: Option<&str>) -> bool { + v.map_or(true, |v| v.trim() != "0") + } + + /// XCL keeps physical page `page`'s bytes at `at` now (0: nowhere; `tile`: a tile may show + /// it there): the GPU-view pages that show it follow. A move is no change of what they show + /// (their call and their place in the log stay), but a page that gets its first place, or + /// loses it, is: its bytes appear or go. `None` when no page shows it elsewhere (one atomic + /// load while nothing is recorded); else the pages that followed, each with where it was kept + /// and whether a tile could show it there (`Shown::at`, `Shown::tile`). + /// Called on the moving thread with AWAY held, before the memory it left can go. + pub(super) fn page_at(page: usize, at: usize, tile: bool) -> Option> { + if MAPPED.load(Ordering::Acquire) == 0 || !read_pages().by_page.contains_key(&page) { + return None; + } + let mut p = write_pages(); + let moving: Vec<(usize, usize, bool)> = + p.by_page.get(&page)?.iter().filter_map(|&g| p.shown.get(&g).filter(|e| e.at != at || e.tile != tile).map(|e| (g, e.at, e.tile))).collect(); + if moving.is_empty() { + return None; + } + let call = calls(); + for &(g, was, _) in &moving { + p.place(g, at, tile, ((was == 0) != (at == 0)).then_some(call)); + } + drop(p); + MOVED.fetch_add(moving.len() as u64, Ordering::Relaxed); + Some(moving) + } + + /// Physical page `page` was freed: the GPU-view pages that showed it show nothing from here + /// on (a change of what they show). Returns them. Caller holds AWAY. + pub(super) fn page_freed(page: usize) -> Vec { + if MAPPED.load(Ordering::Acquire) == 0 || !read_pages().by_page.contains_key(&page) { + return Vec::new(); + } + let mut p = write_pages(); + let gone = p.by_page.get(&page).cloned().unwrap_or_default(); + let call = calls(); + for &g in &gone { + p.set(g, 0, 0, false, call); + } + gone + } + + /// The memory `[base, base + len)` was released: the shown pages kept there have no place + /// from now on (they show nothing until their page is placed again; a change of what they + /// show). Returns those GPU-view pages. + pub(super) fn place_gone(base: usize, len: usize) -> Vec { + if MAPPED.load(Ordering::Acquire) == 0 { + return Vec::new(); + } + let end = base.saturating_add(len); + if read_pages().by_at.range((base, 0)..(end, 0)).next().is_none() { + return Vec::new(); + } + let mut p = write_pages(); + let gone: Vec = p.by_at.range((base, 0)..(end, 0)).map(|&(_, g)| g).collect(); + let call = calls(); + for &g in &gone { + p.place(g, 0, false, Some(call)); + } + gone + } + + /// The GPU-view pages in `[lo, hi)` whose content changed after cursor `seen` (0 at first), + /// each once, with the call that last changed it, in the order of their last change – at + /// most `most` – and the cursor to pass next. Nothing is drained: each reader keeps a cursor + /// of its own. One atomic load when nothing changed. + pub fn changes_since(seen: u64, lo: usize, hi: usize, most: usize) -> (u64, Vec<(usize, u64)>) { + let mut out = Vec::new(); + if CHANGE_SEQ.load(Ordering::Acquire) == seen { + return (seen, out); + } + let p = read_pages(); + let mut cursor = seen; + for (&seq, &g) in p.log.range(seen.saturating_add(1)..) { + if g >= lo && g < hi { + if out.len() >= most { + return (cursor, out); + } + out.push((g, p.shown.get(&g).map_or(0, |e| e.call))); + } + cursor = seq; + } + (p.seq.max(cursor), out) + } + + /// The GPU-view pages a CPU write reaches, added to `out` for `dirty` (sorted 4 KiB pages + /// written): each written page of a place where a mapped page is kept, at every GPU-view + /// page that shows it; and a written page of a CPU view at its GPU-view page when the + /// page-mapping method never named that one (it shows the CPU view at the same offset). A + /// GPU-view page that is mapped or unmapped gets nothing from the CPU view under it. + pub fn views_of_written(dirty: &[usize], out: &mut Vec) { + if MAPPED.load(Ordering::Acquire) == 0 || dirty.is_empty() { + return; + } + // (GPU view, size, CPU view) + let pairs: Vec<(usize, usize, usize)> = STATE.lock().unwrap().gpu.iter().map(|(&g, &(n, c))| (g, n, c)).collect(); + let p = read_pages(); + let mut i = 0; + while i < dirty.len() { + let page = dirty[i] & !(PAGE - 1); + let n = dirty[i..].iter().take_while(|&&d| d & !(PAGE - 1) == page).count(); + let written = &dirty[i..i + n]; + for &(_, g) in p.by_at.range((page, 0)..=(page, usize::MAX)) { + out.extend(written.iter().map(|&d| g + (d - page))); + } + for &(gv, size, c) in &pairs { + if page >= c && page < c + size && !p.shown.contains_key(&(gv + (page - c))) { + out.extend(written.iter().map(|&d| gv + (d - c))); + } + } + i += n; + } + } + + /// The 16 MiB blocks that hold the place of a shown page, as (start, end), in order. + pub fn shown_blocks() -> Vec<(usize, usize)> { + if MAPPED.load(Ordering::Acquire) == 0 { + return Vec::new(); + } + let mut v: Vec<(usize, usize)> = read_pages().blocks.keys().map(|&b| (b << 24, (b + 1) << 24)).collect(); + v.sort_unstable(); + v + } + + /// Changes each time a 16 MiB block comes to hold the place of a shown page, or ceases to. + pub fn shown_gen() -> u64 { + SHOWN_GEN.load(Ordering::Acquire) + } + + /// The GPU-view pages that followed their physical page to another place so far. + pub fn moved_pages() -> u64 { + MOVED.load(Ordering::Relaxed) + } + + /// What the record says of GPU-view page `g` (a test's own pages). + #[cfg(test)] + pub(super) fn shown_at(g: usize) -> Option { + read_pages().shown.get(&g).copied() + } +} + +/// Where XCL keeps page `page`'s bytes now: the address the title mapped it at last, else its +/// home (`true`); `(0, false)` when no allocated page has that number. Caller holds AWAY. +fn place_of(away: Option<&Away>, page: usize) -> (usize, bool) { + if let Some(&at) = away.and_then(|a| a.page.get(&page)) { + return (at, false); + } + page_home(page).map_or((0, false), |h| (h, true)) +} + +/// Whether kernelx sees memory at `at` decommitted or released, and can tell sparse first: +/// unified memory or a graphics reservation (a tile of a GPU view may show such a place). +fn freeing_is_seen(at: usize) -> bool { + crate::gpu::uma::get().is_some_and(|u| u.contains(at)) || in_graphics_reservation(at) +} + +/// XCL keeps physical page `page`'s bytes at `at` now (0: nowhere; `home`: its home): the +/// GPU-view pages that show it follow (`mirrors::page_at`). `whole`: its 64 KiB were copied +/// there, a known write at the new address – a CPU write made just before the move went with the +/// page and has no other report. Call it with AWAY held, once the bytes are in place and before +/// the memory the page left can go. +unsafe fn page_placed(page: usize, at: usize, home: bool, whole: bool) { + if !mirrors::any_mapped() { + return; + } + let tile = at != 0 && (home || freeing_is_seen(at)); + let Some(moving) = mirrors::page_at(page, at, tile) else { return }; + // the tiles linked over the place it left follow it, before that memory can go: those of + // the view pages kept where a tile could show them, and now kept where one may. The others + // are linked again (to nothing, or to the new place): their bytes appear or go, or no tile + // was linked where they were – a page that leaves plain memory for memory a tile may show + let from = if tile { moving.iter().find(|m| m.1 != 0 && m.2).map_or(0, |m| m.1) } else { 0 }; + let (mut follow, mut relink): (Vec, Vec) = (Vec::new(), Vec::new()); + for &(g, was, could) in &moving { + let to = if from != 0 && was == from && could { &mut follow } else { &mut relink }; + to.push(g); + } + #[cfg(test)] + tests::PLACED.with(|s| s.borrow_mut().push((page, from, at, follow.clone(), relink.clone()))); + if !relink.is_empty() { + crate::hle::d3d12x::sparse::remapped(&relink); + } + if !follow.is_empty() { + crate::hle::d3d12x::sparse::moved(&follow, from, at, whole); + } + if whole { + crate::hle::d3d12x::title_textures::note_known_write(at, PHYS_PAGE); + } } /// Graphics memory (MEM_GRAPHICS, committed, no fixed address) comes from the unified @@ -270,6 +906,7 @@ unsafe fn note_protection(addr: *const c_void, size: usize, protection: u32) { } pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: u32, p: u32) -> *mut c_void { + let _cost = super::api_cost::time(super::api_cost::Call::Memory); if let Some(q) = placeholders::alloc(addr, size, t, sanitize_protect(p)) { trace_mem("VirtualAlloc (placeholder)", addr as usize, size, t as u64, p, q as usize); return q; @@ -281,6 +918,25 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: trace_mem("VirtualAlloc (sparse commit)", addr as usize, size, t as u64, p, q as usize); return q; } + // committing in a GPU view (a view window): plain pages, as before the views had windows – + // never the sparse windows' commit, whose tiles would take these pages for the view's bytes + if !addr.is_null() && t & 0x1000 != 0 && uma.is_some_and(|u| u.is_view(addr as usize)) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("kernelx: the title commits memory in a GPU view ({addr:?}, {size:#x} bytes): plain pages there, which the GPU does not see")); + } + // a GPU view of the title's CPU memory (`mirrors`) with a CPU view waiting for it: in the view + // windows (16 windows), where shaders reach it; the CPU view stays where it is. Taken before + // the 64 KiB-page branch below: that one is for the CPU view, which is reserved first. + if addr.is_null() && t & 0x2000 != 0 && mirrors::is_gpu_view_reservation(t, p) && mirrors::would_pair(size) { + if let Some((u, q)) = uma.and_then(|u| Some((u, u.view_reserve(size)?))) { + if mirrors::reserved(q, size, t, p) { + trace_mem("VirtualAlloc (GPU view, view windows)", 0, size, t as u64, p, q); + return q as *mut c_void; + } + // (another thread paired that CPU view in the meantime: as before the windows) + u.view_release(q); + } + } // the title's own reservations of 64 KiB pages: in a sparse window, so the GPU sees them. // Skip CPU-inaccessible GPU-view mirror reservations (`PAGE_NOACCESS | PAGE_GRAPHICS_NOACCESS`): // their pixels live in the paired CPU view (`mirrors::source`), so putting them in sparse VA @@ -345,13 +1001,29 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: // the CPU writes and the GPU reads, as a PC game's upload heaps): in the coherent window, which // the GPU reads where it is – one copy (a retail game's 4.4 GB; as plain memory its shaders // read zeros, in the sparse windows video memory would have doubled them). The window is as - // large as what the title asked for last time (`uma::coherent_hint`). + // large as what the title put in it last time with this setting (`uma::coherent_hint`). if addr.is_null() && t & 0x1000 != 0 && p & PAGE_GRAPHICS_ANY != 0 && size <= crate::gpu::uma::MAX_SIZE && std::env::var("XCL_COHERENT_HEAPS").map_or(true, |v| v != "0") { + let align = if t & 0x2000_0000 != 0 && t & 0x0040_0000 == 0 { 2 << 20 } else { crate::gpu::uma::GRAIN }; static ASKED: AtomicUsize = AtomicUsize::new(0); + // `XCL_COHERENT_HEAPS=sparse[:N]`: heaps of at least N MB (all with no N) go to the + // sparse windows instead – video memory, the CPU's writes uploaded before each + // submission (`d3d12x::sparse`). In the coherent window the GPU reads them over the bus, + // uncached, and on NVIDIA its writes that do not fill whole lines run at ~0.1 GB/s + // (#505). Costs a second copy in video memory and the write-watch scan of it. + if sparse_heaps_min().is_some_and(|min| size >= min) { + let rounded = size.max(1).div_ceil(align) * align; + if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc(rounded, align) { + crate::xlog_info!("kernelx: a GPU heap of {} MB in the sparse windows (XCL_COHERENT_HEAPS)", size >> 20); + trace_mem("VirtualAlloc (graphics heap, sparse VRAM)", 0, rounded, t as u64, p, q); + // nothing of it in the coherent window, noted all the same: a run whose heaps all + // come here stores what it put there too (`uma::note_coherent_need`) + crate::gpu::uma::note_coherent_need(ASKED.load(Ordering::Relaxed)); + return q as *mut c_void; + } + } let asked = ASKED.fetch_add(size, Ordering::Relaxed) + size; crate::gpu::uma::note_coherent_need(asked); if let Some(u) = uma { - let align = if t & 0x2000_0000 != 0 && t & 0x0040_0000 == 0 { 2 << 20 } else { crate::gpu::uma::GRAIN }; // what XCL keeps of the window for itself (readback heaps; its per-draw arguments have // a pool of their own) const KEEP: usize = 96 << 20; @@ -360,6 +1032,15 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: trace_mem("VirtualAlloc (graphics, coherent window)", 0, size, t as u64, p, q as usize); return q as *mut c_void; } + // diagnostic: a GPU heap the coherent window has no room for (plain memory from here) + static UNFIT: AtomicUsize = AtomicUsize::new(0); + static UNFIT_BYTES: AtomicUsize = AtomicUsize::new(0); + let k = UNFIT.fetch_add(1, Ordering::Relaxed) + 1; + let total = UNFIT_BYTES.fetch_add(size, Ordering::Relaxed) + size; + if k <= 8 || k.is_power_of_two() { + let (free, _, used, _) = u.committed_state(); + crate::xlog_warn!("kernelx: a GPU heap of {} MB does not fit in the coherent window ({} MB used, {} MB free): #{k}, {} MB in all", size >> 20, used >> 20, free >> 20, total >> 20); + } } } // GPU-visible title memory the windows above had no room for (a retail game: a 24 GB @@ -381,6 +1062,42 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: q } +/// `XCL_COHERENT_HEAPS=sparse` (every GPU heap) or `sparse:N` (heaps of at least N MB): the +/// smallest heap the sparse windows take instead of the coherent window. Read once. +fn sparse_heaps_min() -> Option { + static MIN: std::sync::OnceLock> = std::sync::OnceLock::new(); + *MIN.get_or_init(|| std::env::var("XCL_COHERENT_HEAPS").ok().and_then(|v| parse_sparse_heaps(&v))) +} + +/// Which of the title's GPU heaps go to the coherent window, as the window's size is kept for +/// each (`uma::coherent_hint_for`). +pub(crate) fn coherent_heaps_route() -> String { + heaps_route(std::env::var("XCL_COHERENT_HEAPS").ok().as_deref()) +} + +/// `coherent_heaps_route` of a value of `XCL_COHERENT_HEAPS`, read as `VirtualAlloc` reads it: +/// `off` (`0`: none), `sparse` (only those the sparse windows have no room for), `sparse:N` +/// (those under N MB too), else every heap (`uma::ALL_HEAPS`). +fn heaps_route(v: Option<&str>) -> String { + match v { + Some("0") => "off".into(), + Some(v) => match parse_sparse_heaps(v) { + Some(0) => "sparse".into(), + Some(min) => format!("sparse:{}", min >> 20), + None => crate::gpu::uma::ALL_HEAPS.into(), + }, + None => crate::gpu::uma::ALL_HEAPS.into(), + } +} + +/// `sparse` -> 0, `sparse:N` -> N MB in bytes; anything else -> None +fn parse_sparse_heaps(v: &str) -> Option { + match v.trim().strip_prefix("sparse")? { + "" => Some(0), + rest => rest.strip_prefix(':')?.trim().parse::().ok().and_then(|mb| mb.checked_mul(1 << 20)), + } +} + /// Whether a VirtualAlloc that reached the plain-memory fallback is GPU-visible title memory /// (a reservation with MEM_GRAPHICS, MEM_LARGE_PAGES / MEM_64K_PAGES or a PAGE_GRAPHICS_* /// protection, at no fixed address), which is reserved write-watched (`reserve_watched`). @@ -430,9 +1147,53 @@ fn keep_last_error(f: impl FnOnce() -> R) -> R { r } +/// The part of `[a, a + n)` (`n == 0`: to the end of the reservation at `a`) that lies in a +/// paired CPU view (`mirrors`): the pages `source_going` tells sparse about. One atomic load +/// while nothing is paired; else a look at the pairs. While the page-mapping method shows pages +/// in GPU views (`mirrors::any_mapped`) any memory may hold the place of one that a tile shows: +/// all of `[a, a + n)` then (sparse decides by its own index whether a tile shows it); one atomic +/// load more while nothing is mapped. +unsafe fn source_part(a: usize, n: usize) -> Option<(usize, usize)> { + if let Some((lo, len)) = mirrors::cpu_view_part(a, n) { + #[cfg(test)] + tests::SOURCES_GOING.with(|s| s.borrow_mut().push((lo, len, committed_page(lo)))); + return Some((lo, len)); + } + if n != 0 && mirrors::any_mapped() { + #[cfg(test)] + tests::KEPT_GOING.with(|s| s.borrow_mut().push((a, n, committed_page(a)))); + return Some((a, n)); + } + None +} + +/// `os` decommits (or, with `release`, releases) pages of `[a, a + n)` (`n == 0`: to the end of +/// the reservation at `a`) in Windows. Those of a paired CPU view (`mirrors`) may be shown by +/// tiles of its GPU view, which a submit fills from them and scans with the sparse state's lock +/// held – that read faults on a page that goes meanwhile. So sparse is told around the call +/// (`sparse::source_decommit` / `source_release`): the pages are holes for every submit from +/// before Windows takes them until after, and a submit that asks Windows about them in between +/// does not take them back. Telling it only before left that gap. Call it with no lock held +/// that sparse takes (AWAY is fine: AWAY → sparse is the order); `os` runs with no lock of +/// sparse's held. +unsafe fn source_going(a: usize, n: usize, release: bool, os: impl FnOnce() -> R) -> R { + source_part_going(source_part(a, n), release, os) +} + +/// `source_going` for a part looked up before (`source_part`: a release unpairs the views +/// before Windows is called, and the part is not found after that). +unsafe fn source_part_going(part: Option<(usize, usize)>, release: bool, os: impl FnOnce() -> R) -> R { + match part { + Some((lo, len)) if release => crate::hle::d3d12x::sparse::source_release(lo, len, os), + Some((lo, len)) => crate::hle::d3d12x::sparse::source_decommit(lo, len, os), + None => os(), + } +} + /// Blocks of the unified memory region go back to it (MEM_RELEASE) or stay (MEM_DECOMMIT /// zeroes them); others to Windows. pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32) -> BOOL { + let _cost = super::api_cost::time(super::api_cost::Call::Memory); if let Some(ok) = placeholders::free(addr, size, t) { return ok; } @@ -440,66 +1201,120 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 // space back); their video memory goes with it if let Some(u) = crate::gpu::uma::get().filter(|u| u.is_sparse(addr as usize)) { let a = addr as usize; - let release = t & mem::MEM_RELEASE != 0; - let decommit = t & mem::MEM_DECOMMIT != 0; - if release == decommit || (release && size != 0) { - fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); - return 0; - } - let n = if release || size == 0 { - match u.sparse_reservation(a) { - Some((start, len)) if start == a => len, - _ => { - fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); - return 0; - } - } - } else { - match u.sparse_reservation(a) { - Some((start, len)) if a.checked_add(size).is_some_and(|end| end <= start + len) => size, - _ => { - fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); - return 0; - } - } - }; + let Some((n, release)) = reservation_part(a, size, t, u.sparse_reservation(a)) else { return 0 }; if n > 0 { // sparse first: under its lock, so no copy of CPU writes to video memory reads the // pages while they go (the submit thread's copy faulted on them) crate::hle::d3d12x::sparse::decommitted(a, n); - if mem::VirtualFree(addr, n, mem::MEM_DECOMMIT) == 0 { + // (the CPU view of a pair may lie here too: tiles of its GPU view show these pages) + if source_going(a, n, false, || mem::VirtualFree(addr, n, mem::MEM_DECOMMIT)) == 0 { return 0; } } if release { + // unpaired before the address can be handed out again; and the pages kept here show + // nothing from now on, before then too (a submit would link a tile over it) + mirrors::released(a); + forget_title_mappings(a, n); + let gone = mirrors::place_gone(a, n); u.sparse_release(a); + // (tiles may show pages kept here) + if mirrors::any_mapped() { + crate::hle::d3d12x::sparse::forget_mirrors(a, n); + } + crate::hle::d3d12x::sparse::remapped(&gone); + } + return 1; + } + // a GPU view in the view windows: what the GPU has of it goes first (`sparse::decommitted` + // drops its tiles), then pages the title may have committed there; on release the pair, then + // the address space + if let Some(u) = crate::gpu::uma::get().filter(|u| u.is_view(addr as usize)) { + let a = addr as usize; + let Some((n, release)) = reservation_part(a, size, t, u.view_reservation(a)) else { return 0 }; + if n > 0 { + crate::hle::d3d12x::sparse::decommitted(a, n); + if mem::VirtualFree(addr, n, mem::MEM_DECOMMIT) == 0 { + return 0; + } + } + if release { mirrors::released(a); + u.view_release(a); + forget_title_mappings(a, n); } + trace_mem(if release { "VirtualFree (GPU view, released)" } else { "VirtualFree (GPU view, decommitted)" }, a, n, t as u64, 0, 1); return 1; } if let Some(u) = crate::gpu::uma::get().filter(|u| u.contains(addr as usize)) { if t & 0x8000 != 0 { - return u.free(addr as usize) as BOOL; + // (the block stays committed in its window: nothing goes in Windows, the tiles do; the + // pages the title mapped here, and the shown pages kept here, go before the block can + // be handed out again) + let a = addr as usize; + let n = u.block_len(a).unwrap_or(0); + forget_title_mappings(a, n); + let gone = mirrors::place_gone(a, n); + source_going(a, n, true, || ()); + mirrors::released(a); + crate::hle::d3d12x::sparse::remapped(&gone); + return u.free(a) as BOOL; } if t & 0x4000 != 0 && size > 0 { std::ptr::write_bytes(addr as *mut u8, 0, size); } return 1; } - let ok = mem::VirtualFree(addr, size, t); - if ok != 0 && t & 0x8000 != 0 && GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)).is_some() { - GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + // a decommit, or a release (of the whole reservation: size 0), of a paired CPU view – the + // title's CPU view is plain write-watched memory – is told to sparse before Windows does it + let release = t & mem::MEM_RELEASE != 0; + // (looked up before the pair goes: a graphics reservation is unpaired below, before Windows; + // size 0 is the whole of a graphics reservation, which may hold places of shown pages) + let whole = if size == 0 { GRAPHICS_RESERVATIONS.lock().unwrap().get(&(addr as usize)).copied().unwrap_or(0) } else { size }; + let part = if release != (t & mem::MEM_DECOMMIT != 0) && !(release && size != 0) { source_part(addr as usize, whole) } else { None }; + // a graphics reservation is unpaired before Windows can hand its address out again + let graphics = t & 0x8000 != 0 && size == 0 && GRAPHICS_RESERVATIONS.lock().unwrap().contains_key(&(addr as usize)); + if graphics { mirrors::released(addr as usize); } + let ok = source_part_going(part, release, || mem::VirtualFree(addr, size, t)); + if ok != 0 && t & 0x8000 != 0 { + let released = GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)); + if let Some(len) = released { + GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + if !graphics { + mirrors::released(addr as usize); + } + forget_title_mappings(addr as usize, len); + crate::hle::d3d12x::sparse::remapped(&mirrors::place_gone(addr as usize, len)); + } + } ok } +/// The part of the reservation `res` (start, bytes) that `VirtualFree(a, size, t)` gives back – +/// all of it on MEM_RELEASE or a decommit of size 0 – and whether it is a release. None: the +/// arguments do not name one (ERROR_INVALID_PARAMETER is set). +unsafe fn reservation_part(a: usize, size: usize, t: u32, res: Option<(usize, usize)>) -> Option<(usize, bool)> { + let release = t & mem::MEM_RELEASE != 0; + let decommit = t & mem::MEM_DECOMMIT != 0; + let n = match res { + _ if release == decommit || (release && size != 0) => None, + Some((start, len)) if release || size == 0 => (start == a).then_some(len), + Some((start, len)) => a.checked_add(size).is_some_and(|end| end <= start + len).then_some(size), + None => None, + }; + if n.is_none() { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + } + n.map(|n| (n, release)) +} + pub unsafe extern "system" fn VirtualFreeEx(proc_: HANDLE, addr: *mut c_void, size: usize, t: u32) -> BOOL { if own_process(proc_) { let a = addr as usize; - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(a) || u.contains(a)) - || (t & 0x8000 != 0 && in_graphics_reservation(a)) - { + // (a graphics reservation's decommits too: one may be a paired CPU view, `source_going`) + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(a) || u.contains(a) || u.is_view(a)) || in_graphics_reservation(a) { return VirtualFree(addr, size, t); } } @@ -936,6 +1751,65 @@ pub unsafe extern "system" fn XMemIsToolsMemAvailable() -> BOOL { /// video-memory tiles, they took the system's commit.) const PHYS_PAGE: usize = 0x1_0000; +/// Diagnostic: the last events on the title's 64 KiB pages, for the report of an unhandled +/// exception (`describe`): what happened lately at the pages the registers point into. +pub mod pagelog { + use std::collections::VecDeque; + use std::sync::Mutex; + + const KEEP: usize = 400_000; + const PAGE: usize = 0x1_0000; + + #[derive(Clone, Copy)] + struct Event { + at_ms: u64, + what: &'static str, + /// the address the event is at, a second address (a move's source) and a number (page / bytes) + a: usize, + b: usize, + n: usize, + } + + static LOG: Mutex> = Mutex::new(VecDeque::new()); + static COUNTS: Mutex> = Mutex::new(Vec::new()); + + fn now_ms() -> u64 { + static T0: std::sync::OnceLock = std::sync::OnceLock::new(); + T0.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 + } + + /// `what` happened at address `a` (`b`: another address it involves, `n`: a page number or bytes). + pub fn note(what: &'static str, a: usize, b: usize, n: usize) { + let mut g = LOG.lock().unwrap_or_else(|e| e.into_inner()); + if g.len() >= KEEP { + g.pop_front(); + } + g.push_back(Event { at_ms: now_ms(), what, a, b, n }); + drop(g); + let mut c = COUNTS.lock().unwrap_or_else(|e| e.into_inner()); + match c.iter_mut().find(|e| e.0 == what) { + Some(e) => e.1 += 1, + None => c.push((what, 1)), + } + } + + /// The events so far by kind. + pub fn counts() -> String { + // (called from the exception filter, perhaps with the lock held by the thread that faulted) + let Ok(c) = COUNTS.try_lock() else { return "(busy)".into() }; + c.iter().map(|(w, n)| format!("{n} {w}")).collect::>().join(", ") + } + + /// The last events (up to 6) at the 64 KiB page of `addr`, newest first; empty: none kept. + pub fn describe(addr: usize) -> String { + let page = addr & !(PAGE - 1); + let Ok(g) = LOG.try_lock() else { return String::new() }; + let now = now_ms(); + let hit = |e: &&Event| (e.a..e.a + if e.what.starts_with("DirectStorage") { e.n.max(1) } else { PAGE }).contains(&addr) || e.a & !(PAGE - 1) == page || (e.b != 0 && e.b & !(PAGE - 1) == page); + g.iter().rev().filter(hit).take(6).map(|e| format!("{} ms ago: {} at {:#x}{}{}", now.saturating_sub(e.at_ms), e.what, e.a, if e.b != 0 { format!(" (other address {:#x})", e.b) } else { String::new() }, if e.n != 0 { format!(" [{:#x}]", e.n) } else { String::new() })).collect::>().join("; ") + } +} + /// Size of one console physical page (64 KiB). pub const PHYS_PAGE_SIZE: usize = PHYS_PAGE; @@ -954,9 +1828,33 @@ struct Away { /// homes in a sparse window whose pages went away in this call, given back at its end in /// runs (`give_back_homes`): one page at a time, a retail game's start took 20 s gone: Vec, + /// homes committed ahead of the pages the call in progress unmaps (`commit_homes_ahead`) + ready: std::collections::HashSet, + /// address → the page the title mapped there last. `at` cannot serve: it holds an address + /// only while the page's bytes are kept there, and when the title maps the same page at a + /// second address XCL moves the bytes and `move_away` drops the first one – on the console + /// the page stays mapped there too, and that first address is the pool address the queue's + /// page-mapping method names. + title: std::collections::HashMap, } static AWAY: std::sync::Mutex> = std::sync::Mutex::new(None); +/// The title released `[base, base + len)`: the pages it mapped there are mapped there no more. +fn forget_title_mappings(base: usize, len: usize) { + if let Some(a) = AWAY.lock().unwrap().as_mut() { + let end = base.saturating_add(len); + // (a range of fewer pages than there are entries: each of its pages, not every entry) + let (first, pages) = (base & !(PHYS_PAGE - 1), len.div_ceil(PHYS_PAGE) + 1); + if pages < a.title.len() { + for at in (first..end).step_by(PHYS_PAGE).filter(|&at| at >= base) { + a.title.remove(&at); + } + } else { + a.title.retain(|&at, _| at < base || at >= end); + } + } +} + /// Whether a physical page is mapped at the page holding `va` away from its home – committed /// or not yet (`lazy`: a page never used is committed at its first access). pub fn physical_page_at(va: usize) -> bool { @@ -974,9 +1872,45 @@ pub fn gpu_view_map_gen() -> u64 { /// Pages are mapped or unmapped at `va`: a GPU view's mappings changed if it lies in one. fn note_mapping_at(va: usize) { - if mirrors::source(va).is_some() { - GPU_VIEW_MAP_GEN.fetch_add(1, Ordering::Release); + note_mapping_range(va, PHYS_PAGE); +} + +/// The address ranges of the last mapping changes inside GPU views with the generation each made +/// (`gpu_view_map_gen`), oldest first, and the newest generation dropped from the front (`0`: +/// none): a reader that has seen generation n looks at the ranges with a later one. +static GPU_VIEW_MAP_LOG: std::sync::Mutex<(u64, std::collections::VecDeque<(u64, usize, usize)>)> = std::sync::Mutex::new((0, std::collections::VecDeque::new())); +const MAP_LOG: usize = 4096; + +/// Pages are mapped or unmapped in `[lo, lo + len)`. +fn note_mapping_range(lo: usize, len: usize) { + if len == 0 || (mirrors::source(lo).is_none() && mirrors::source(lo + len - 1).is_none()) { + return; } + note_gpu_view_change(lo, len); +} + +/// What `[lo, lo + len)` of a GPU view shows changed (its mappings, or the view was paired with +/// its CPU view or went): a new generation of `gpu_view_map_gen` with the range in the log. +fn note_gpu_view_change(lo: usize, len: usize) { + let mut g = GPU_VIEW_MAP_LOG.lock().unwrap(); + let gen = GPU_VIEW_MAP_GEN.load(Ordering::Relaxed) + 1; + g.1.push_back((gen, lo, lo.saturating_add(len))); + if g.1.len() > MAP_LOG { + if let Some((dropped, _, _)) = g.1.pop_front() { + g.0 = dropped; + } + } + GPU_VIEW_MAP_GEN.store(gen, Ordering::Release); +} + +/// The ranges whose mappings in GPU views changed after generation `since`, or None when the log +/// no longer has them all. +pub fn gpu_view_map_changes(since: u64) -> Option> { + let g = GPU_VIEW_MAP_LOG.lock().unwrap(); + if since < g.0 { + return None; + } + Some(g.1.iter().filter(|e| e.0 > since).map(|e| (e.1, e.2)).collect()) } /// Page numbers count 4 KiB frames, as on the console: a 64 KiB page's is a multiple of 16 (a retail game @@ -1065,13 +1999,56 @@ pub unsafe fn write_physical_pages(pages: &[usize], offset: usize, src: &[u8]) - let mut page_off = offset; for addr in addrs { let chunk = (PHYS_PAGE - page_off).min(src.len() - done); + pagelog::note("DirectStorage write by page number", addr + page_off, 0, chunk); std::ptr::copy_nonoverlapping(src.as_ptr().add(done), (addr + page_off) as *mut u8, chunk); + crate::hle::d3d12x::title_textures::note_known_write(addr + page_off, chunk); done += chunk; page_off = 0; } true } +/// Homes `move_home_away` collects before it gives them back (`give_back_homes`). +const GIVE_BACK_PAGES: usize = 4096; + +/// Pages `map_pages` mapped in a sparse window, told to `sparse::committed` once per run of +/// neighbouring pages instead of once a page. Each call is an `UpdateTileMappings` and a fence +/// signal: about 0.5 ms a page on NVIDIA, and a retail game in Series S mode maps 3.4 GB in one +/// `MapTitlePhysicalPages` at boot – 24 s on its main thread, and its stall check ended it. +struct SparseRun { + start: usize, + end: usize, + commit: unsafe fn(usize, usize), +} + +impl SparseRun { + fn new(commit: unsafe fn(usize, usize)) -> Self { + SparseRun { start: 0, end: 0, commit } + } + + /// The page at `at` was mapped in a sparse window. + unsafe fn add(&mut self, at: usize) { + if self.start == self.end || at != self.end { + self.flush(); + self.start = at; + } + self.end = at + PHYS_PAGE; + } + + /// Whether the page at `a` waits in the run. + fn holds(&self, a: usize) -> bool { + (self.start..self.end).contains(&a) + } + + /// The run's pages are committed now (before anything decommits one of them). + unsafe fn flush(&mut self) { + if self.end > self.start { + (self.commit)(self.start, self.end - self.start); + } + (self.start, self.end) = (0, 0); + } +} + /// A page's data went from `home` to another address: a home in a sparse window is /// decommitted at the end of the call or every 256 MB (`give_back_homes`; its GPU tiles go too: the GPU does /// not see the page while it is away). True if homes were given back now. @@ -1080,7 +2057,7 @@ unsafe fn move_home_away(away: &mut Away, home: usize) -> bool { away.gone.push(home); // (256 MB at a time: a call that maps gigabytes would otherwise hold them twice until // it ends) - if away.gone.len() >= 4096 { + if away.gone.len() >= GIVE_BACK_PAGES { give_back_homes(away); return true; } @@ -1105,7 +2082,8 @@ unsafe fn give_back_homes(away: &mut Away) { if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(start)) { crate::hle::d3d12x::sparse::decommitted(start, end - start); } - mem::VirtualFree(start as *mut c_void, end - start, mem::MEM_DECOMMIT); + // (a tile may show a page kept at its home: `source_part`) + source_going(start, end - start, false, || mem::VirtualFree(start as *mut c_void, end - start, mem::MEM_DECOMMIT)); } } @@ -1123,6 +2101,57 @@ unsafe fn home_again(home: usize) -> Option { Some(home) } +/// The pages of a scatter whose homes are committed ahead together: they and the memory the pages +/// leave are both committed while these are copied (64 MiB). +const HOMES_AHEAD: usize = 1024; + +/// The homes of the pages mapped at `ats`, which the caller unmaps next, committed in runs of +/// neighbouring pages (`Away::ready`) – `home_again` does it page by page, and in a sparse window +/// each is a tile mapping of its own: a retail game unmapping 4136 and then 6720 pages while it +/// loads, the homes of each call one run, spent 2.7 s in those two calls. A home committed +/// already (another page may be mapped at that address, given up in this call), or that cannot +/// be, is left to `home_again`. +unsafe fn commit_homes_ahead(away: &mut Away, ats: impl Iterator) { + let mut homes: Vec = ats + .filter_map(|at| away.at.get(&at).filter(|_| !lazy::is_marked(at)).and_then(|&p| page_home(p))) + .filter(|&h| lazy_home(h) && !away.gone.contains(&h)) + .collect(); + homes.sort_unstable(); + homes.dedup(); + let mut i = 0; + while i < homes.len() { + let start = homes[i]; + let mut end = start + PHYS_PAGE; + i += 1; + while i < homes.len() && homes[i] == end { + end += PHYS_PAGE; + i += 1; + } + let mut a = start; + while a < end { + let mut m: mem::MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if mem::VirtualQuery(a as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 { + break; + } + let to = (m.BaseAddress as usize + m.RegionSize).min(end); + // (whole pages: a state that changes inside one is `home_again`'s) + let (first, last) = (a.next_multiple_of(PHYS_PAGE), to & !(PHYS_PAGE - 1)); + if m.State == mem::MEM_RESERVE + && first < last + && !mem::VirtualAlloc(first as *const c_void, last - first, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() + { + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(first)) { + crate::hle::d3d12x::sparse::committed(first, last - first); + } + #[cfg(test)] + tests::HOME_RUNS.with(|c| c.set(c.get() + 1)); + away.ready.extend((first..last).step_by(PHYS_PAGE)); + } + a = to; + } + } +} + /// `n` pages from `home` committed (a sparse home is only reserved until it is used). unsafe fn commit_homes(home: usize, n: usize) -> bool { let Some(u) = crate::gpu::uma::get() else { return false }; @@ -1217,18 +2246,26 @@ unsafe fn unmap_away(away: &mut Away, at: usize, committed: &std::ops::Range Option { - if let Some((p, _)) = u.sparse_alloc(bytes, PHYS_PAGE) { + if let Some((p, _)) = u.sparse_alloc_above(bytes, PHYS_PAGE) { return Some(p); } if !u.has_sparse() { @@ -1342,7 +2390,15 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: if let Some(at) = away.page.remove(&*arr.add(i)) { away.at.remove(&at); note_mapping_at(at); + pagelog::note("page freed while mapped (the address keeps its bytes)", at, 0, *arr.add(i)); } + // (those at home too: their home goes with the block) + crate::hle::d3d12x::sparse::remapped(&mirrors::page_freed(*arr.add(i))); + } + // (page numbers are never handed out again: their entries go) + if !away.title.is_empty() { + let freed: std::collections::HashSet = (0..n).map(|i| *arr.add(i)).collect(); + away.title.retain(|_, p| !freed.contains(p)); } } let mut g = PHYS_BLOCKS.lock().unwrap(); @@ -1357,19 +2413,23 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: e.1 = e.1.saturating_sub(1); if e.1 == 0 { g.remove(&first); - if u.is_sparse(home) { - crate::hle::d3d12x::sparse::free(home); - } else if u.contains(home) { - u.free(home); - } else { - mem::VirtualFree(home as *mut c_void, 0, mem::MEM_RELEASE); - } + // (a tile may show a page kept in the block: `source_part`) + source_going(home, count * PHYS_PAGE, true, || { + if u.is_sparse(home) { + crate::hle::d3d12x::sparse::free(home); + } else if u.contains(home) { + u.free(home); + } else { + mem::VirtualFree(home as *mut c_void, 0, mem::MEM_RELEASE); + } + }); } } 1 } pub unsafe extern "system" fn MapTitlePhysicalPages(va: *mut c_void, n: usize, _t: u32, _p: u32, arr: *mut usize) -> *mut c_void { + let _cost = super::api_cost::time(super::api_cost::Call::PhysicalPages); let mut g = AWAY.lock().unwrap(); let away = g.get_or_insert_with(Away::default); let r = map_pages(away, va, n, arr); @@ -1380,11 +2440,17 @@ pub unsafe extern "system" fn MapTitlePhysicalPages(va: *mut c_void, n: usize, _ /// `MapTitlePhysicalPages` with `AWAY` held; the homes it moves away are given back by the /// caller (`give_back_homes`). unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) -> *mut c_void { - note_mapping_at(va as usize); + note_mapping_range(va as usize, n.saturating_mul(PHYS_PAGE)); if crate::gpu::uma::get().is_none() || n == 0 || (va.is_null() && arr.is_null()) { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return std::ptr::null_mut(); } + // pages in a GPU view (a view window) are plain pages there, as before the views had windows + // (`contains` and `is_sparse` are false there: no sparse commit), which the GPU does not see + if !va.is_null() && crate::gpu::uma::get().is_some_and(|u| u.is_view(va as usize)) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("kernelx: the title maps physical pages in a GPU view ({va:?}, {n} pages): plain pages there, which the GPU does not see")); + } let pages: Vec = if arr.is_null() { vec![0; n] } else { (0..n).map(|i| *arr.add(i)).collect() }; if pages.iter().any(|&p| p != 0 && page_home(p).is_none()) { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); @@ -1404,6 +2470,9 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) } // (pages this call moved away and back are home again, not given back) away.gone.retain(|&h| h < home || h >= home + n * PHYS_PAGE); + for (i, &p) in pages.iter().enumerate() { + away.title.insert(home + i * PHYS_PAGE, p); + } for &p in &pages { if let Some(&at) = away.page.get(&p) { unmap_away(away, at, &(home..home + n * PHYS_PAGE)); @@ -1423,8 +2492,11 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) // unmapped first) – bar an address that is another page's home (a home in plain memory): // that answer was wrong before the runs too. let (mut at_run, mut home_run) = (StateRun::default(), StateRun::default()); + let mut sparse_run = SparseRun::new(crate::hle::d3d12x::sparse::committed); for (i, &p) in pages.iter().enumerate() { let at = base + i * PHYS_PAGE; + // what was mapped at `at` goes; the new page is written down once it is in place + away.title.remove(&at); if unmap_away(away, at, &(0..0)) { (at_run, home_run) = Default::default(); } @@ -1432,16 +2504,22 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) continue; } if let Some(&old) = away.page.get(&p) { + // (the move decommits `old`: committed first if it waits in the run) + if sparse_run.holds(old) { + sparse_run.flush(); + } // (a move commits `at` and decommits `old`, which may lie in a run already answered: // both runs go – #556) match move_away(away, old, at, p, in_uma(at)) { Ok(true) => { (at_run, home_run) = Default::default(); + away.title.insert(at, p); continue; } // a lazy page is only unmarked: memory is as it was, the runs stay Ok(false) => {} Err(()) => { + sparse_run.flush(); fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); return std::ptr::null_mut(); } @@ -1456,26 +2534,48 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) lazy::mark(at); away.at.insert(at, p); away.page.insert(p, at); + away.title.insert(at, p); + page_placed(p, at, false, false); + pagelog::note("page mapped (never used: zeros on first touch)", at, 0, p); continue; } + pagelog::note("page mapped (its bytes copied from home, or zeros)", at, 0, p); if !in_uma(at) && mem::VirtualAlloc(at as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { + sparse_run.flush(); fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); return std::ptr::null_mut(); } + let in_sparse = crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)); if committed_page(home) { + // (told before its bytes come: a look for CPU writes between the two would take the + // written pages of a tile that has no video memory yet, and nothing reported them again) + if in_sparse { + crate::hle::d3d12x::sparse::committed(at, PHYS_PAGE); + } std::ptr::copy_nonoverlapping(home as *const u8, at as *mut u8, PHYS_PAGE); + // (before the home can be given back) + page_placed(p, at, false, true); + // (giving homes back decommits them, and one may be an address in the run) + if sparse_run.holds(home) || away.gone.len() + 1 >= GIVE_BACK_PAGES { + sparse_run.flush(); + } if move_home_away(away, home) { (at_run, home_run) = Default::default(); } - } else if !fresh { - std::ptr::write_bytes(at as *mut u8, 0, PHYS_PAGE); // a page never used: zeros - } - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { - crate::hle::d3d12x::sparse::committed(at, PHYS_PAGE); + } else { + if !fresh { + std::ptr::write_bytes(at as *mut u8, 0, PHYS_PAGE); // a page never used: zeros + } + if in_sparse { + sparse_run.add(at); + } + page_placed(p, at, false, true); } away.at.insert(at, p); away.page.insert(p, at); + away.title.insert(at, p); } + sparse_run.flush(); va } @@ -1495,6 +2595,7 @@ pub unsafe extern "system" fn XMemMapPhysicalPages(va: *mut c_void, n: usize, ar /// a retail game unmaps that way while it streams its world and stops on its own `int3` when the /// call fails. pub unsafe extern "system" fn XMemMapPhysicalPagesScatter(addresses: *const *mut c_void, n: usize, pages: *mut u64) -> BOOL { + let _cost = super::api_cost::time(super::api_cost::Call::PhysicalPages); if addresses.is_null() { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; @@ -1507,10 +2608,19 @@ pub unsafe extern "system" fn XMemMapPhysicalPagesScatter(addresses: *const *mut let away = g.get_or_insert_with(Away::default); // no page array: page 0 (unmap) for every address let ok = (0..n).all(|i| { + // a part of the call that only unmaps + if i % HOMES_AHEAD == 0 { + let part = i..n.min(i + HOMES_AHEAD); + if part.len() > 1 && part.clone().all(|k| pages.is_null() || *pages.add(k) == 0) { + commit_homes_ahead(away, part.map(|k| *addresses.add(k) as usize)); + } + } let mut none = 0usize; let page = if pages.is_null() { &mut none as *mut usize } else { pages.add(i) as *mut usize }; !map_pages(away, *addresses.add(i), 1, page).is_null() }); + // (a call that failed part way: homes no page went back to) + away.gone.extend(away.ready.drain()); give_back_homes(away); ok as BOOL } @@ -2127,6 +3237,57 @@ pub unsafe extern "system" fn DisableThreadLibraryCalls(h: usize) -> BOOL { mod tests { use super::*; + /// `XCL_COHERENT_HEAPS=sparse[:N]`: which heaps go to the sparse windows + #[test] + fn sparse_heaps_setting() { + assert_eq!(parse_sparse_heaps("sparse"), Some(0), "every heap"); + assert_eq!(parse_sparse_heaps("sparse:1024"), Some(1024 << 20)); + assert_eq!(parse_sparse_heaps(" sparse: 512 "), Some(512 << 20)); + assert_eq!(parse_sparse_heaps("0"), None, "heaps off the coherent window altogether: not this"); + assert_eq!(parse_sparse_heaps("1"), None); + assert_eq!(parse_sparse_heaps("sparse:"), None); + assert_eq!(parse_sparse_heaps("sparse:big"), None); + assert_eq!(parse_sparse_heaps("sparsex"), None); + assert_eq!(parse_sparse_heaps(&format!("sparse:{}", usize::MAX)), None, "no overflow"); + } + + /// The setting the coherent window's size is kept for: what goes there + /// differs between them, and the same heaps' setting is one name however it is written. + #[test] + fn coherent_heaps_routes() { + assert_eq!(heaps_route(None), crate::gpu::uma::ALL_HEAPS); + assert_eq!(heaps_route(Some("1")), crate::gpu::uma::ALL_HEAPS, "not a setting: every heap, as VirtualAlloc reads it"); + assert_eq!(heaps_route(Some("0")), "off"); + assert_eq!(heaps_route(Some("sparse")), "sparse"); + assert_eq!(heaps_route(Some("sparse:0")), "sparse", "the same heaps as `sparse`"); + assert_eq!(heaps_route(Some(" sparse: 16 ")), "sparse:16"); + } + + /// Neighbouring sparse pages a mapping call maps are committed as one run; a gap starts + /// another, and `holds` names the pages still waiting (they are flushed before a decommit). + #[test] + fn sparse_pages_are_committed_once_per_run() { + static CALLS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + unsafe fn note(a: usize, n: usize) { + CALLS.lock().unwrap().push((a, n)); + } + let a = 0x10_0000_0000usize; + let mut run = SparseRun::new(note); + unsafe { + for i in 0..3 { + run.add(a + i * PHYS_PAGE); + } + assert!(CALLS.lock().unwrap().is_empty(), "nothing committed while the run grows"); + assert!(run.holds(a + PHYS_PAGE) && !run.holds(a + 3 * PHYS_PAGE)); + // a page past a gap: the run before it goes first + run.add(a + 5 * PHYS_PAGE); + run.flush(); + run.flush(); + } + assert_eq!(*CALLS.lock().unwrap(), vec![(a, 3 * PHYS_PAGE), (a + 5 * PHYS_PAGE, PHYS_PAGE)], "one call per run, none for an empty run"); + assert!(!run.holds(a)); + } + fn real_sleep(ms: u32) { std::thread::sleep(std::time::Duration::from_millis(ms as u64)); } @@ -2783,6 +3944,216 @@ mod tests { thread_local! { /// pages `unmap_away` copied back home on this thread pub(super) static HOME_COPIES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// runs of homes `commit_homes_ahead` committed on this thread + pub(super) static HOME_RUNS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// what `source_going` told sparse on this thread: (start, bytes, whether the first page + /// was still committed then) + pub(super) static SOURCES_GOING: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + /// what `source_going` told sparse on this thread of memory of no pair while pages were + /// shown (`mirrors::any_mapped`): (start, bytes, whether the first page was still + /// committed then) + pub(super) static KEPT_GOING: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + /// what `page_placed` told sparse on this thread: (page, the place the tiles follow it + /// from – 0: none, its new place, the GPU-view pages whose tiles follow it, those linked + /// again) + pub(super) static PLACED: std::cell::RefCell, Vec)>> = const { std::cell::RefCell::new(Vec::new()) }; + /// the ranges `mirrors::released` had sparse forget on this thread + pub(super) static FORGOTTEN: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + + /// The CPU view of a pair (`mirrors`) as the title's is – plain write-watched memory – with + /// a GPU view at `g` (only paired: never touched). `size` is the test's own, so no other + /// test's views pair with these. + unsafe fn cpu_view(size: usize, g: usize) -> usize { + let c = reserve_watched(size, 0x2040_2000, mem::PAGE_READWRITE) as usize; + assert!(c != 0 && in_graphics_reservation(c), "the CPU view is a graphics reservation: the looks take it"); + mirrors::reserved(c, size, 0x2040_2000, mem::PAGE_READWRITE); + assert!(mirrors::reserved(g, size, 0x2040_2000, 0x801)); + assert_eq!(mirrors::source(g + 0x1_2340), Some(c + 0x1_2340)); + c + } + + /// The title's decommit and release of its CPU view are told to sparse while the pages are + /// still committed (a submit's scan reads the pages tiles of the GPU view show, and faulted + /// on one decommitted under it), the release as the whole view; memory of no pair is not + /// told. The release ends the pair, and sparse forgets the tiles over either view (their + /// addresses may be handed out again). + #[test] + fn a_decommit_or_release_of_a_cpu_view_is_told_to_sparse_first() { + const SIZE: usize = 61 * PHYS_PAGE; + let g = 0x7230_0000_0000usize; + unsafe { + let c = cpu_view(SIZE, g); + let other = reserve_watched(SIZE, 0x2000, mem::PAGE_READWRITE) as usize; + for at in [c, c + 3 * PHYS_PAGE, other + PHYS_PAGE] { + assert_eq!(VirtualAlloc(at as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE) as usize, at); + } + SOURCES_GOING.with(|s| s.borrow_mut().clear()); + FORGOTTEN.with(|f| f.borrow_mut().clear()); + assert_eq!(VirtualFree((c + 3 * PHYS_PAGE + 0x4000) as *mut c_void, 0x2000, mem::MEM_DECOMMIT), 1); + assert_eq!(SOURCES_GOING.with(|s| s.take()), vec![(c + 3 * PHYS_PAGE + 0x4000, 0x2000, true)], "told while it was still committed"); + assert!(!committed_page(c + 3 * PHYS_PAGE + 0x4000) && committed_page(c + 3 * PHYS_PAGE)); + // through VirtualFreeEx too + assert_eq!(VirtualFreeEx(thr::GetCurrentProcess(), (c + 3 * PHYS_PAGE) as *mut c_void, 0x1000, mem::MEM_DECOMMIT), 1); + assert_eq!(SOURCES_GOING.with(|s| s.take()), vec![(c + 3 * PHYS_PAGE, 0x1000, true)]); + assert_eq!(VirtualFree((other + PHYS_PAGE) as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT), 1); + assert!(SOURCES_GOING.with(|s| s.take()).is_empty(), "memory of no pair"); + // a release that names no reservation's start does nothing + assert_eq!(VirtualFree(c as *mut c_void, PHYS_PAGE, mem::MEM_RELEASE), 0); + assert!(SOURCES_GOING.with(|s| s.take()).is_empty()); + assert_eq!(VirtualFree(c as *mut c_void, 0, mem::MEM_RELEASE), 1); + assert_eq!(SOURCES_GOING.with(|s| s.take()), vec![(c, SIZE, true)], "the whole view, before Windows releases it"); + assert_eq!(FORGOTTEN.with(|f| f.take()), vec![(g, SIZE), (c, SIZE)]); + assert_eq!(mirrors::source(g), None); + assert_eq!(VirtualFree(other as *mut c_void, 0, mem::MEM_RELEASE), 1); + assert!(SOURCES_GOING.with(|s| s.take()).is_empty() && FORGOTTEN.with(|f| f.take()).is_empty()); + } + } + + /// A physical page mapped never used into the CPU view of a pair is left lazy; the title's + /// first write commits it – the tiles of the GPU view may have been asked for before, with a + /// hole there – and the look finds the page written, which is how sparse clears the hole and + /// sends the page. Moved to another address, or unmapped, the page is told to sparse while it + /// is still committed (`release_at`). + #[test] + fn a_lazy_page_of_a_cpu_view_is_found_written_and_told_to_sparse_when_it_goes() { + const SIZE: usize = 59 * PHYS_PAGE; + let g = 0x7240_0000_0000usize; + unsafe { + let Some(mut pages) = sparse_pages(1) else { return }; + let c = cpu_view(SIZE, g); + let at = c + 2 * PHYS_PAGE; + assert_eq!(MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, at); + assert!(lazy::is_marked(at) && !committed_page(at), "never used: left lazy"); + let mut buf = [std::ptr::null_mut::(); 16]; + let (mut n, mut gran) = (buf.len(), 0u32); + assert_eq!(mem::GetWriteWatch(1, c as *const c_void, SIZE, buf.as_mut_ptr(), &mut n, &mut gran), 0); + ((at + 0x1238) as *mut u32).write_volatile(0xC0FF_EE00); + assert!(committed_page(at) && !lazy::is_marked(at), "committed by the write"); + n = buf.len(); + assert_eq!(mem::GetWriteWatch(1, c as *const c_void, SIZE, buf.as_mut_ptr(), &mut n, &mut gran), 0); + assert_eq!(&buf[..n], &[(at + 0x1000) as *mut c_void], "the look finds the page written"); + + SOURCES_GOING.with(|s| s.borrow_mut().clear()); + let to = c + 5 * PHYS_PAGE; + assert_eq!(MapTitlePhysicalPages(to as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, to); + assert_eq!(*((to + 0x1238) as *const u32), 0xC0FF_EE00); + assert_eq!(SOURCES_GOING.with(|s| s.take()), vec![(at, PHYS_PAGE, true)], "the address it moved from, before it was decommitted"); + assert!(!committed_page(at)); + let mut none = [0usize]; + assert_eq!(MapTitlePhysicalPages(to as *mut c_void, 1, 0, 4, none.as_mut_ptr()) as usize, to); + assert_eq!(SOURCES_GOING.with(|s| s.take()), vec![(to, PHYS_PAGE, true)], "unmapped"); + assert!(!committed_page(to)); + // a page of no pair goes untold + let r = mem::VirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, r); + *(r as *mut u32) = 1; + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 1, 0, 4, none.as_mut_ptr()) as usize, r); + assert!(SOURCES_GOING.with(|s| s.take()).is_empty()); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, pages.as_mut_ptr()), 1); + assert_eq!(VirtualFree(c as *mut c_void, 0, mem::MEM_RELEASE), 1); + mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + /// Pages allocated and mapped one by one (page i at address `n - 1 - i` of a reservation), + /// each but those in `unused` written: (pages, their home, the reservation, its addresses in + /// page order). + unsafe fn pages_away(n: usize, unused: &[usize]) -> (Vec, usize, usize, Vec<*mut c_void>) { + let mut count = n; + let mut pages = vec![0usize; n]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut count, pages.as_mut_ptr()), 1); + let h = page_home(pages[0]).unwrap(); + let r = mem::VirtualAlloc(std::ptr::null(), n * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert!(r != 0); + let addrs: Vec<*mut c_void> = (0..n).map(|i| (r + (n - 1 - i) * PHYS_PAGE) as *mut c_void).collect(); + let mut ids: Vec = pages.iter().map(|&p| p as u64).collect(); + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), n, ids.as_mut_ptr()), 1); + for (i, &a) in addrs.iter().enumerate().filter(|(i, _)| !unused.contains(i)) { + *(a as *mut u32) = i as u32 + 1; + *((a as usize + PHYS_PAGE - 4) as *mut u32) = !(i as u32); + } + (pages, h, r, addrs) + } + + unsafe fn check_home(pages: &mut [usize], h: usize, unused: &[usize]) { + assert_eq!(MapTitlePhysicalPages(std::ptr::null_mut(), pages.len(), 0, 4, pages.as_mut_ptr()) as usize, h); + for i in 0..pages.len() { + let a = h + i * PHYS_PAGE; + let want = if unused.contains(&i) { (0, 0) } else { (i as u32 + 1, !(i as u32)) }; + assert_eq!((*(a as *const u32), *((a + PHYS_PAGE - 4) as *const u32)), want, "page {i}"); + } + } + + /// A scatter that unmaps many pages commits their neighbouring homes together, whatever the + /// order of the addresses: a run per `HOMES_AHEAD` pages of the call and per gap (a page + /// never used has nothing to bring home). An address given twice, or with no page, changes + /// nothing; every page reads at home what was written to it. + #[test] + fn a_scatter_that_unmaps_commits_homes_in_runs() { + unsafe { + let Some(_) = crate::gpu::uma::get() else { return }; + let n = HOMES_AHEAD + 40; + let unused = [100, 500]; + let (mut pages, h, r, mut addrs) = pages_away(n, &unused); + assert!(lazy_home(h) && !committed_page(h)); + let free = mem::VirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE); + addrs.push(addrs[n - 1]); + addrs.push(free); + let mut none = vec![0u64; addrs.len()]; + let (runs, copies) = (HOME_RUNS.with(|c| c.get()), HOME_COPIES.with(|c| c.get())); + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), addrs.len(), none.as_mut_ptr()), 1); + assert_eq!(HOME_COPIES.with(|c| c.get()) - copies, n - unused.len()); + // pages 0..1024 in three runs (two gaps), the other 40 in one + assert_eq!(HOME_RUNS.with(|c| c.get()) - runs, 4); + assert!(addrs.iter().all(|&a| !committed_page(a as usize))); + check_home(&mut pages, h, &unused); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), n, pages.as_mut_ptr()), 1); + mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); + mem::VirtualFree(free, 0, mem::MEM_RELEASE); + } + } + + /// A home at which another page is mapped is not committed ahead: that page's unmapping in + /// the same call decommits the address, and the home is asked again. + #[test] + fn a_home_another_page_is_mapped_at_is_not_committed_ahead() { + unsafe { + let Some(_) = crate::gpu::uma::get() else { return }; + let (mut pages, h, r, addrs) = pages_away(4, &[]); + // page 0 goes to page 2's home + let at = [(h + 2 * PHYS_PAGE) as *mut c_void]; + let mut one = [pages[0] as u64]; + assert_eq!(XMemMapPhysicalPagesScatter(at.as_ptr(), 1, one.as_mut_ptr()), 1); + let all = [at[0], addrs[1], addrs[2], addrs[3]]; + let mut none = [0u64; 4]; + let runs = HOME_RUNS.with(|c| c.get()); + assert_eq!(XMemMapPhysicalPagesScatter(all.as_ptr(), 4, none.as_mut_ptr()), 1); + assert_eq!(HOME_RUNS.with(|c| c.get()) - runs, 2, "homes 0..2 and 3"); + check_home(&mut pages, h, &[]); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 4, pages.as_mut_ptr()), 1); + mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + /// A scatter refused part way gives back the homes committed ahead of the pages it did not + /// reach; those stay mapped with what they hold. + #[test] + fn a_scatter_refused_part_way_gives_its_homes_back() { + unsafe { + let Some(_) = crate::gpu::uma::get() else { return }; + let (mut pages, h, r, addrs) = pages_away(4, &[]); + let bad = (addrs[2] as usize + 0x1000) as *mut c_void; + let all = [addrs[0], bad, addrs[1], addrs[2], addrs[3]]; + let mut none = [0u64; 5]; + assert_eq!(XMemMapPhysicalPagesScatter(all.as_ptr(), 5, none.as_mut_ptr()), 0); + assert!(committed_page(h) && (1..4).all(|i| !committed_page(h + i * PHYS_PAGE))); + assert!(!committed_page(addrs[0] as usize)); + assert!((1..4).all(|i| *(addrs[i] as *const u32) == i as u32 + 1)); + check_home(&mut pages, h, &[]); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 4, pages.as_mut_ptr()), 1); + mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); + } } /// A page mapped away that the title maps somewhere else goes there straight, with what it @@ -2824,7 +4195,7 @@ mod tests { let at = mem::VirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; mem::VirtualFree(at as *mut c_void, 0, mem::MEM_RELEASE); let page = 0x7E57_0000usize; - let mut away = Away { at: Default::default(), page: Default::default(), gone: Vec::new() }; + let mut away = Away { at: Default::default(), page: Default::default(), gone: Vec::new(), ready: Default::default(), ..Default::default() }; away.at.insert(old, page); away.page.insert(page, old); assert!(move_away(&mut away, old, at, page, false).is_err()); @@ -2835,6 +4206,590 @@ mod tests { } } + /// The page the title mapped at `at` last (`Away::title`). + fn title_at(at: usize) -> Option { + AWAY.lock().unwrap().as_ref().and_then(|a| a.title.get(&at).copied()) + } + + /// An address keeps the page the title mapped there last, also once XCL moved the page's + /// bytes to another address the title mapped it at; an unmap, another page, a free, a failed + /// map and the release of the reservation each leave it right. + #[test] + fn an_address_keeps_the_page_the_title_mapped_there_last() { + let null = std::ptr::null_mut(); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let mut n = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1); + let (p, q) = (pages[0], pages[1]); + let h = page_home(p).unwrap(); + // a graphics reservation of the test's own + let r = reserve_watched(4 * PHYS_PAGE, 0x2000, mem::PAGE_READWRITE) as usize; + assert!(r != 0); + let (r1, r2) = (r, r + PHYS_PAGE); + let (mut one_p, mut one_q, mut none) = ([p], [q], [0usize]); + assert_eq!(MapTitlePhysicalPages(r1 as *mut c_void, 1, 0, 4, one_p.as_mut_ptr()) as usize, r1); + *(r1 as *mut u32) = 5; + assert_eq!(title_at(r1), Some(p)); + // mapped at a second address: its bytes move there, the first address still names it + assert_eq!(MapTitlePhysicalPages(r2 as *mut c_void, 1, 0, 4, one_p.as_mut_ptr()) as usize, r2); + assert_eq!(*(r2 as *const u32), 5); + assert!(AWAY.lock().unwrap().as_ref().is_some_and(|a| a.page.get(&p) == Some(&r2) && !a.at.contains_key(&r1)), "the bytes moved"); + assert_eq!((title_at(r1), title_at(r2)), (Some(p), Some(p))); + // unmapped at the first + assert_eq!(MapTitlePhysicalPages(r1 as *mut c_void, 1, 0, 4, none.as_mut_ptr()) as usize, r1); + assert_eq!((title_at(r1), title_at(r2)), (None, Some(p))); + // another page at the second: replaced (p goes home with its bytes) + assert_eq!(MapTitlePhysicalPages(r2 as *mut c_void, 1, 0, 4, one_q.as_mut_ptr()) as usize, r2); + assert_eq!(title_at(r2), Some(q)); + // a map that fails (nothing reserved there, and p's home holds bytes) leaves no entry + let bad = mem::VirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + mem::VirtualFree(bad as *mut c_void, 0, mem::MEM_RELEASE); + assert!(MapTitlePhysicalPages(bad as *mut c_void, 1, 0, 4, one_p.as_mut_ptr()).is_null()); + assert_eq!(title_at(bad), None); + // both at their home: their homes name them + assert_eq!(MapTitlePhysicalPages(null, 2, 0, 4, pages.as_mut_ptr()) as usize, h); + assert_eq!(*(h as *const u32), 5); + assert_eq!((title_at(h), title_at(h + PHYS_PAGE)), (Some(p), Some(q))); + // the release of the reservation forgets what was mapped in it + assert_eq!(VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE), 1); + assert_eq!((title_at(r1), title_at(r2)), (None, None)); + assert_eq!(title_at(h), Some(p), "outside the reservation"); + // freed: no address names them + assert_eq!(FreeTitlePhysicalPages(null, 2, pages.as_mut_ptr()), 1); + assert!(AWAY.lock().unwrap().as_ref().is_some_and(|a| a.title.values().all(|&v| v != p && v != q))); + } + } + + /// A batch of the queue's page-mapping method: the first destination, the number of ranges + /// (`kind, start, count` each) and a pointer to them. + #[repr(C)] + struct Batch { + dest: u64, + ranges_n: u32, + _pad: u32, + ranges: usize, + } + fn batch(dest: usize, r: &[[u32; 3]]) -> Batch { + Batch { dest: dest as u64, ranges_n: r.len() as u32, _pad: 0, ranges: r.as_ptr() as usize } + } + + /// The page-mapping method's batches decode to (GPU-view page, pool page or unmapped) in the + /// call's order, from the destination's page on; a call with anything wrong in it gives + /// nothing at all. + #[test] + fn the_page_mapping_batches_are_decoded_whole() { + use mirrors::{decode_batches, PAGE}; + let (d, d2, pool, pool_pages) = (0x7100_0004_0000usize, 0x7300_0000_0000usize, 0x7200_0000_0000usize, 64u32); + unsafe { + // two pool pages from 10 on, one page kept, pool page 5 three times, one unmapped; + // then a second batch of two pages + let r1 = [[0, 10, 2], [3, 0, 1], [1, 5, 3], [2, 0, 1]]; + let r2 = [[0, 0, 2]]; + let b = [batch(d + 0x1234, &r1), batch(d2, &r2)]; + let want = vec![ + (d, Some(pool + 10 * PAGE)), + (d + PAGE, Some(pool + 11 * PAGE)), + (d + 3 * PAGE, Some(pool + 5 * PAGE)), + (d + 4 * PAGE, Some(pool + 5 * PAGE)), + (d + 5 * PAGE, Some(pool + 5 * PAGE)), + (d + 6 * PAGE, None), + (d2, Some(pool)), + (d2 + PAGE, Some(pool + PAGE)), + ]; + assert_eq!(decode_batches(2, b.as_ptr() as usize, pool, pool_pages), Some(want)); + // a batch with no ranges gives nothing and refuses nothing + let none = Batch { dest: d as u64, ranges_n: 0, _pad: 0, ranges: 0 }; + assert_eq!(decode_batches(1, [none].as_ptr() as usize, pool, pool_pages), Some(Vec::new())); + assert_eq!(decode_batches(0, 0, pool, pool_pages), Some(Vec::new()), "no batches"); + + // bad calls: a range leaving the pool (after a good one), an unknown kind, ranges and + // batches that are not readable, more than MOST pages + let leaves = [[0, 0, 1], [0, 63, 2]]; + assert_eq!(decode_batches(1, [batch(d, &leaves)].as_ptr() as usize, pool, pool_pages), None); + let one_out = [[1, 64, 1]]; + assert_eq!(decode_batches(1, [batch(d, &one_out)].as_ptr() as usize, pool, pool_pages), None); + let unknown = [[7, 0, 1]]; + assert_eq!(decode_batches(1, [batch(d, &unknown)].as_ptr() as usize, pool, pool_pages), None); + let unreadable = Batch { dest: d as u64, ranges_n: 1, _pad: 0, ranges: 0 }; + assert_eq!(decode_batches(1, [unreadable].as_ptr() as usize, pool, pool_pages), None); + assert_eq!(decode_batches(1, 0, pool, pool_pages), None, "batches not readable"); + let many = [[2, 0, (1 << 20) + 1]]; + assert_eq!(decode_batches(1, [batch(d, &many)].as_ptr() as usize, pool, pool_pages), None); + assert_eq!(decode_batches((1 << 20) + 1, b.as_ptr() as usize, pool, pool_pages), None); + } + } + + /// GPU-view pages the page-mapping method names record the physical page the title had + /// mapped at their pool page, where XCL keeps it now and whether a tile may show it there – + /// also when the title mapped it elsewhere before the call; a pool page with no page, and an + /// unmapped page, show nothing; a page not named shows the CPU view. The same mapping named + /// again changes nothing, a bad call records nothing, the views' release drops their pages. + #[test] + fn gpu_view_pages_record_the_physical_page_mapped_into_them() { + use mirrors::{apply_batches, resolve, shown_at, shows, touched, Mapped, Shows, PAGE}; + const SIZE: usize = 199 * PAGE; + let g = 0x7270_0000_0000usize; + let null = std::ptr::null_mut(); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let mut n = 3usize; + let mut pages = [0usize; 3]; + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1); + let [a, b, c] = pages; + let cv = cpu_view(SIZE, g); + // the pool, a graphics reservation: page a used at pool page 1, b never used at 2, + // nothing at 0; c mapped at pool page 3, then kept in plain memory + let pool = reserve_watched(4 * PAGE, 0x2000, mem::PAGE_READWRITE) as usize; + let plain = mem::VirtualAlloc(std::ptr::null(), PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert!(pool != 0 && plain != 0); + for (at, page) in [(pool + PAGE, a), (pool + 2 * PAGE, b), (pool + 3 * PAGE, c), (plain, c)] { + let mut one = [page]; + assert_eq!(MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, at); + } + *((pool + PAGE) as *mut u32) = 0xA; + + // pool pages 0 to 2 at view pages 2 to 4, page 5 left as it is, 6 unmapped; and two + // pages outside any view + let r1 = [[0, 0, 3], [3, 0, 1], [2, 0, 1]]; + let r2 = [[1, 1, 2]]; + let bs = [batch(g + 2 * PAGE + 0x10, &r1), batch(pool, &r2)]; + assert_eq!(apply_batches(2, bs.as_ptr() as usize, pool, 4), Some(Mapped { mapped: 2, unmapped: 1, empty: 1, elsewhere: 2 })); + assert_eq!(shows(g + 8), Shows::Same(cv + 8), "never named"); + assert_eq!(shows(g + 2 * PAGE), Shows::Nothing, "no page at pool page 0"); + assert_eq!(shows(g + 3 * PAGE + 8), Shows::Page { at: pool + PAGE + 8, tile: true }); + assert_eq!(shows(g + 4 * PAGE), Shows::Page { at: pool + 2 * PAGE, tile: true }, "a page never used is kept where it was mapped"); + assert_eq!(shows(g + 5 * PAGE + 8), Shows::Same(cv + 5 * PAGE + 8), "kind 3 leaves it"); + assert_eq!(shows(g + 6 * PAGE), Shows::Nothing, "unmapped"); + assert_eq!(shows(pool), Shows::NoView); + assert!(shown_at(pool).is_none() && shown_at(pool + PAGE).is_none(), "outside any view: not recorded"); + assert_eq!(shown_at(g + 3 * PAGE).map(|e| e.page), Some(a)); + // one address a page, view pages 1 to 6 + let mut at = Vec::new(); + assert_eq!(resolve(g + PAGE + 0x10, 5 * PAGE, &mut at), Some([2, 0, 2, 2])); + assert_eq!(at, vec![(cv + PAGE) | 1, 0, pool + PAGE, pool + 2 * PAGE, (cv + 5 * PAGE) | 1, 0]); + assert_eq!(resolve(g + 20 * PAGE, PAGE, &mut at), None, "no page named"); + assert!(at.is_empty()); + assert!(touched(g + 3 * PAGE + 0x100, 4) && touched(g, 3 * PAGE)); + assert!(!touched(g, 2 * PAGE) && !touched(g + 7 * PAGE, 30 * PAGE)); + + // the title maps a into the CPU view (its bytes move there); a call made after that + // still finds a by its pool address, kept at the CPU view's same offset + let mut one = [a]; + assert_eq!(MapTitlePhysicalPages((cv + 7 * PAGE) as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, cv + 7 * PAGE); + assert_eq!(*((cv + 7 * PAGE) as *const u32), 0xA); + let r = [[0, 1, 1]]; + assert_eq!(apply_batches(1, [batch(g + 7 * PAGE, &r)].as_ptr() as usize, pool, 4), Some(Mapped { mapped: 1, ..Mapped::default() })); + assert_eq!(shows(g + 7 * PAGE + 4), Shows::Page { at: cv + 7 * PAGE + 4, tile: true }); + assert_eq!(resolve(g + 7 * PAGE, PAGE, &mut at), Some([0, 1, 0, 0])); + assert_eq!(at, vec![cv + 7 * PAGE]); + // the same mapping named again changes nothing + let before = shown_at(g + 7 * PAGE); + assert_eq!(apply_batches(1, [batch(g + 7 * PAGE, &r)].as_ptr() as usize, pool, 4), Some(Mapped { mapped: 1, ..Mapped::default() })); + assert_eq!(shown_at(g + 7 * PAGE), before, "neither its call nor its place in the log"); + // a bad call records nothing + let bad = [[0, 1, 1], [0, 3, 2]]; + assert_eq!(apply_batches(1, [batch(g + 8 * PAGE, &bad)].as_ptr() as usize, pool, 4), None); + assert_eq!(shows(g + 8 * PAGE), Shows::Same(cv + 8 * PAGE)); + // a page kept outside graphics memory: no tile may show it there + let r = [[1, 3, 1]]; + assert_eq!(apply_batches(1, [batch(g + 9 * PAGE, &r)].as_ptr() as usize, pool, 4), Some(Mapped { mapped: 1, ..Mapped::default() })); + assert_eq!(shows(g + 9 * PAGE), Shows::Page { at: plain, tile: false }); + // remapped to pool page 1: a, with a later call + let call = shown_at(g + 9 * PAGE).unwrap().call; + let r = [[0, 1, 1]]; + assert_eq!(apply_batches(1, [batch(g + 9 * PAGE, &r)].as_ptr() as usize, pool, 4), Some(Mapped { mapped: 1, ..Mapped::default() })); + assert!(shown_at(g + 9 * PAGE).is_some_and(|e| e.page == a && e.call > call)); + assert_eq!(shows(g + 9 * PAGE), Shows::Page { at: cv + 7 * PAGE, tile: true }); + + // the pages unmapped and freed, then the views released: their pages go with them + let mut none = [0usize]; + for at in [pool + 2 * PAGE, plain, cv + 7 * PAGE] { + assert_eq!(MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, none.as_mut_ptr()) as usize, at); + } + assert_eq!(FreeTitlePhysicalPages(null, 3, pages.as_mut_ptr()), 1); + assert_eq!(VirtualFree(cv as *mut c_void, 0, mem::MEM_RELEASE), 1); + assert_eq!(shows(g + 3 * PAGE), Shows::NoView); + assert!((0..10).all(|k| shown_at(g + k * PAGE).is_none()), "released with its view"); + assert!(!touched(g, SIZE)); + assert_eq!(VirtualFree(pool as *mut c_void, 0, mem::MEM_RELEASE), 1); + mem::VirtualFree(plain as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + /// A GPU-view page follows its physical page where XCL keeps it: mapped elsewhere (its bytes + /// move there), unmapped (home, with its bytes), mapped at the CPU view's same offset, and a + /// page never used mapped elsewhere (a place not committed yet). A move is no change of what + /// the page shows; a freed page shows nothing. + #[test] + fn a_gpu_view_page_follows_its_physical_page() { + use mirrors::{apply_batches, resolve, shown_at, shows, Shown, Shows, PAGE}; + const SIZE: usize = 137 * PAGE; + let g = 0x7280_0000_0000usize; + let null = std::ptr::null_mut(); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let mut n = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1); + let [a, b] = pages; + let (home_a, home_b) = (page_home(a).unwrap(), page_home(b).unwrap()); + let cv = cpu_view(SIZE, g); + // the pool and another address, graphics reservations both + let pool = reserve_watched(2 * PAGE, 0x2000, mem::PAGE_READWRITE) as usize; + let r = reserve_watched(2 * PAGE, 0x2000, mem::PAGE_READWRITE) as usize; + assert!(pool != 0 && r != 0); + for (at, page) in [(pool, a), (pool + PAGE, b)] { + let mut one = [page]; + assert_eq!(MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, at); + } + *((pool + 0x10) as *mut u32) = 0xA; + // a at view pages 2 and 5, b (never used) at 3 + let (r1, r2) = ([[0, 0, 2]], [[0, 0, 1]]); + let bs = [batch(g + 2 * PAGE, &r1), batch(g + 5 * PAGE, &r2)]; + assert!(apply_batches(2, bs.as_ptr() as usize, pool, 2).is_some()); + assert_eq!(shows(g + 2 * PAGE), Shows::Page { at: pool, tile: true }); + let first = shown_at(g + 2 * PAGE).unwrap(); + + // mapped elsewhere: its bytes move, both view pages follow, what they show is unchanged + let mut one = [a]; + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, r); + assert_eq!(*((r + 0x10) as *const u32), 0xA); + for k in [2, 5] { + assert_eq!(shows(g + k * PAGE + 0x10), Shows::Page { at: r + 0x10, tile: true }); + } + assert!(shown_at(g + 2 * PAGE).is_some_and(|e| e.page == a && e.call == first.call && e.seq == first.seq), "a move is no change"); + // unmapped there: home, with its bytes + let mut none = [0usize]; + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 1, 0, 4, none.as_mut_ptr()) as usize, r); + assert_eq!(shows(g + 5 * PAGE), Shows::Page { at: home_a, tile: true }); + assert_eq!(*((home_a + 0x10) as *const u32), 0xA); + // mapped at the CPU view's offset of view page 2: kept at the same offset there, and + // elsewhere for view page 5 + assert_eq!(MapTitlePhysicalPages((cv + 2 * PAGE) as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, cv + 2 * PAGE); + assert_eq!(*((cv + 2 * PAGE + 0x10) as *const u32), 0xA); + let mut at = Vec::new(); + assert_eq!(resolve(g + 2 * PAGE, PAGE, &mut at), Some([0, 1, 0, 0])); + assert_eq!(resolve(g + 5 * PAGE, PAGE, &mut at), Some([1, 0, 0, 0])); + assert_eq!(at, vec![cv + 2 * PAGE]); + // b, never used, mapped elsewhere: its place follows, not committed (unless its home + // is committed memory: then its bytes were copied) + let mut one = [b]; + assert_eq!(MapTitlePhysicalPages((r + PAGE) as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, r + PAGE); + assert_eq!(shows(g + 3 * PAGE), Shows::Page { at: r + PAGE, tile: true }); + assert_eq!(committed_page(r + PAGE), !lazy_home(home_b)); + assert_eq!(first, shown_at(g + 2 * PAGE).map(|e| Shown { at: first.at, tile: first.tile, ..e }).unwrap(), "only the place changed"); + + // freed (unmapped first): what the view pages showed is gone, a change of what they show + for at in [cv + 2 * PAGE, r + PAGE] { + assert_eq!(MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, none.as_mut_ptr()) as usize, at); + } + assert_eq!(FreeTitlePhysicalPages(null, 2, pages.as_mut_ptr()), 1); + for k in [2, 3, 5] { + assert_eq!(shows(g + k * PAGE), Shows::Nothing); + } + assert!(shown_at(g + 2 * PAGE).is_some_and(|e| e.page == 0 && e.at == 0 && e.seq > first.seq)); + assert_eq!(VirtualFree(cv as *mut c_void, 0, mem::MEM_RELEASE), 1); + assert!((0..8).all(|k| shown_at(g + k * PAGE).is_none())); + for q in [pool, r] { + assert_eq!(VirtualFree(q as *mut c_void, 0, mem::MEM_RELEASE), 1); + } + } + } + + /// When a shown page moves, the tiles of its GPU-view pages follow it from a place a tile + /// could show to another such place (`sparse::moved`, from the place it left). They are linked + /// again when it goes to plain memory (no tile may show it there), and when it comes back + /// from there: no tile was linked over plain memory, so none can follow it. + #[test] + fn a_page_leaving_plain_memory_has_the_tiles_over_it_linked_again() { + use mirrors::{apply_batches, shows, Shows, PAGE}; + const SIZE: usize = 223 * PAGE; + let g = 0x72D0_0000_0000usize; + let null = std::ptr::null_mut(); + let placed = || PLACED.with(|s| s.take()); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let mut n = 1usize; + let mut pages = [0usize; 1]; + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1); + let a = pages[0]; + let home = page_home(a).unwrap(); + let cv = cpu_view(SIZE, g); + // the pool and another address, graphics reservations both; and plain memory + let pool = reserve_watched(PAGE, 0x2000, mem::PAGE_READWRITE) as usize; + let r = reserve_watched(2 * PAGE, 0x2000, mem::PAGE_READWRITE) as usize; + let plain = mem::VirtualAlloc(std::ptr::null(), PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert!(pool != 0 && r != 0 && plain != 0); + let (mut one, mut none) = ([a], [0usize]); + assert_eq!(MapTitlePhysicalPages(pool as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, pool); + *(pool as *mut u32) = 0xA; + // a at view pages 1 and 2 + let ranges = [[1, 0, 2]]; + assert!(apply_batches(1, [batch(g + PAGE, &ranges)].as_ptr() as usize, pool, 1).is_some()); + assert_eq!(shows(g + PAGE), Shows::Page { at: pool, tile: true }); + let views = vec![g + PAGE, g + 2 * PAGE]; + placed(); + + // mapped in plain memory: linked again (to nothing there) + assert_eq!(MapTitlePhysicalPages(plain as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, plain); + assert_eq!(shows(g + 2 * PAGE), Shows::Page { at: plain, tile: false }); + assert_eq!(placed(), vec![(a, 0, plain, vec![], views.clone())]); + // from there to a graphics reservation: linked again, to the new place + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, r); + assert_eq!(*(r as *const u32), 0xA); + assert_eq!(shows(g + PAGE), Shows::Page { at: r, tile: true }); + assert_eq!(placed(), vec![(a, 0, r, vec![], views.clone())]); + // from there to another: they follow it from the place it left + assert_eq!(MapTitlePhysicalPages((r + PAGE) as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, r + PAGE); + assert_eq!(placed(), vec![(a, r, r + PAGE, views.clone(), vec![])]); + // unmapped: home, with its bytes; they follow it there + assert_eq!(MapTitlePhysicalPages((r + PAGE) as *mut c_void, 1, 0, 4, none.as_mut_ptr()) as usize, r + PAGE); + assert_eq!(shows(g + PAGE), Shows::Page { at: home, tile: true }); + assert_eq!(placed(), vec![(a, r + PAGE, home, views.clone(), vec![])]); + + assert_eq!(FreeTitlePhysicalPages(null, 1, pages.as_mut_ptr()), 1); + for q in [cv, pool, r] { + assert_eq!(VirtualFree(q as *mut c_void, 0, mem::MEM_RELEASE), 1); + } + mem::VirtualFree(plain as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + /// The title's release of a block of unified memory (MEM_GRAPHICS) that holds the place of a + /// shown page is told to sparse as the whole block; the page shows nothing from then on and + /// the title's mapping there is forgotten – before the block can be handed out again. + #[test] + fn the_release_of_unified_memory_under_a_shown_page_leaves_it_showing_nothing() { + use mirrors::{apply_batches, shows, Shows, PAGE}; + const SIZE: usize = 227 * PAGE; + let g = 0x72E0_0000_0000usize; + let null = std::ptr::null_mut(); + let kept = || KEPT_GOING.with(|s| s.take()); + unsafe { + let Some(u) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let Some(block) = u.alloc(2 * PAGE, PAGE).map(|p| p as usize) else { return crate::gpu::recomp::runner::skip_test("no room in unified memory") }; + let mut n = 1usize; + let mut pages = [0usize; 1]; + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1); + let cv = cpu_view(SIZE, g); + // the page mapped in the block, at view page 1 + let mut one = [pages[0]]; + assert_eq!(MapTitlePhysicalPages((block + PAGE) as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, block + PAGE); + let ranges = [[0, 1, 1]]; + assert!(apply_batches(1, [batch(g + PAGE, &ranges)].as_ptr() as usize, block, 2).is_some()); + assert_eq!(shows(g + PAGE), Shows::Page { at: block + PAGE, tile: true }); + kept(); + + assert_eq!(VirtualFree(block as *mut c_void, 0, mem::MEM_RELEASE), 1); + assert_eq!(kept(), vec![(block, 2 * PAGE, true)], "the whole block, still committed"); + assert_eq!(shows(g + PAGE), Shows::Nothing); + assert!(AWAY.lock().unwrap().as_ref().is_some_and(|a| !a.title.contains_key(&(block + PAGE))), "the title's mapping there is forgotten"); + + // (freed while mapped there: the address keeps its bytes) + assert_eq!(FreeTitlePhysicalPages(null, 1, pages.as_mut_ptr()), 1); + assert_eq!(VirtualFree(cv as *mut c_void, 0, mem::MEM_RELEASE), 1); + } + } + + /// The changed pages of a GPU view are told in the order of their last change, each once, + /// with the call that changed it last; a move is no change; `most` hands them out one by one + /// and the range keeps other pages out; the pages of a released view are not told. + #[test] + fn changed_gpu_view_pages_are_told_once_in_order() { + use mirrors::{apply_batches, changes_since, shown_at, shows, Shows, PAGE}; + const SIZE: usize = 139 * PAGE; + let g = 0x7290_0000_0000usize; + let (lo, hi, all) = (g, g + SIZE, usize::MAX); + let null = std::ptr::null_mut(); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let mut n = 3usize; + let mut pages = [0usize; 3]; + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1); + let cv = cpu_view(SIZE, g); + let pool = reserve_watched(3 * PAGE, 0x2000, mem::PAGE_READWRITE) as usize; + let r = reserve_watched(PAGE, 0x2000, mem::PAGE_READWRITE) as usize; + assert!(pool != 0 && r != 0); + assert_eq!(MapTitlePhysicalPages(pool as *mut c_void, 3, 0, 4, pages.as_mut_ptr()) as usize, pool); + let apply = |ranges: &[[u32; 3]], at: usize| assert!(apply_batches(1, [batch(at, ranges)].as_ptr() as usize, pool, 3).is_some()); + let call = |k: usize| shown_at(g + k * PAGE).unwrap().call; + let (start, got) = changes_since(0, lo, hi, all); + assert!(got.is_empty(), "a view of the test's own"); + + // one call of three pages + apply(&[[0, 0, 3]], g + PAGE); + let c1 = call(1); + let (s1, got) = changes_since(start, lo, hi, all); + assert_eq!(got, vec![(g + PAGE, c1), (g + 2 * PAGE, c1), (g + 3 * PAGE, c1)]); + assert!(changes_since(s1, lo, hi, all).1.is_empty(), "told once"); + // remapped: that page comes again, last, with its new call + apply(&[[0, 2, 1]], g + PAGE); + assert!(call(1) > c1); + let (s2, got) = changes_since(s1, lo, hi, all); + assert_eq!(got, vec![(g + PAGE, call(1))]); + // a move is no change: the page of view page 2 mapped elsewhere + let mut one = [pages[1]]; + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, r); + assert_eq!(shows(g + 2 * PAGE), Shows::Page { at: r, tile: true }); + let (s3, got) = changes_since(s2, lo, hi, all); + assert!(got.is_empty(), "a move"); + // view page 2 unmapped, then 3, then 2 mapped again: 3 and 2, once each + apply(&[[2, 0, 1]], g + 2 * PAGE); + apply(&[[2, 0, 1]], g + 3 * PAGE); + apply(&[[0, 1, 1]], g + 2 * PAGE); + assert_eq!(shows(g + 2 * PAGE), Shows::Page { at: r, tile: true }); + let want = vec![(g + 3 * PAGE, call(3)), (g + 2 * PAGE, call(2))]; + assert!(call(2) > call(3)); + assert_eq!(changes_since(s3, lo, hi, all).1, want); + // one at a time + let (t1, got) = changes_since(s3, lo, hi, 1); + assert_eq!(got, want[..1]); + let (t2, got) = changes_since(t1, lo, hi, 1); + assert_eq!(got, want[1..]); + assert!(changes_since(t2, lo, hi, 1).1.is_empty()); + // the range: view page 3 alone + assert_eq!(changes_since(s3, g + 3 * PAGE, g + 4 * PAGE, all).1, want[..1]); + + // released with the view: none of them is told + assert_eq!(VirtualFree(cv as *mut c_void, 0, mem::MEM_RELEASE), 1); + assert!(changes_since(start, lo, hi, all).1.is_empty()); + assert_eq!(MapTitlePhysicalPages(pool as *mut c_void, 3, 0, 4, std::ptr::null_mut()) as usize, pool); + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 1, 0, 4, std::ptr::null_mut()) as usize, r); + assert_eq!(FreeTitlePhysicalPages(null, 3, pages.as_mut_ptr()), 1); + for q in [pool, r] { + assert_eq!(VirtualFree(q as *mut c_void, 0, mem::MEM_RELEASE), 1); + } + } + } + + /// A write where a mapped page is kept reaches every GPU-view page that shows it, and none + /// once the page left that address; a write to the CPU view reaches the GPU-view page at the + /// same offset only while the page-mapping method never named that page. The 16 MiB blocks + /// of the places follow. + #[test] + fn a_write_where_a_page_is_kept_is_a_write_to_the_views_showing_it() { + use mirrors::{apply_batches, shown_blocks, shown_gen, views_of_written, PAGE}; + const SIZE: usize = 149 * PAGE; + const BLOCK: usize = 1 << 24; + let g = 0x72A0_0000_0000usize; + let null = std::ptr::null_mut(); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let mut n = 1usize; + let mut pages = [0usize; 1]; + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1); + let cv = cpu_view(SIZE, g); + // the pool in a 16 MiB block of the test's own + let space = reserve_watched(2 * BLOCK, 0x2000, mem::PAGE_READWRITE) as usize; + let r = reserve_watched(PAGE, 0x2000, mem::PAGE_READWRITE) as usize; + assert!(space != 0 && r != 0); + let pool = (space + BLOCK - 1) & !(BLOCK - 1); + assert_eq!(MapTitlePhysicalPages(pool as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, pool); + *(pool as *mut u32) = 1; + let gen = shown_gen(); + // the page at view pages 1 and 4 + let ranges = [[0, 0, 1]]; + let bs = [batch(g + PAGE, &ranges), batch(g + 4 * PAGE, &ranges)]; + assert!(apply_batches(2, bs.as_ptr() as usize, pool, 1).is_some()); + assert!(shown_blocks().contains(&(pool, pool + BLOCK)) && shown_gen() > gen); + let twins = |dirty: &[usize]| { + let mut v = Vec::new(); + views_of_written(dirty, &mut v); + v.sort_unstable(); + v + }; + assert_eq!(twins(&[pool + 0x1000, pool + 0x3000]), vec![g + PAGE + 0x1000, g + PAGE + 0x3000, g + 4 * PAGE + 0x1000, g + 4 * PAGE + 0x3000]); + // moved: the address it left reaches none of them, its new place both + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, r); + assert!(twins(&[pool + 0x1000]).is_empty()); + assert_eq!(twins(&[r + 0x2000]), vec![g + PAGE + 0x2000, g + 4 * PAGE + 0x2000]); + let rb = r & !(BLOCK - 1); + assert!(!shown_blocks().contains(&(pool, pool + BLOCK)) && shown_blocks().contains(&(rb, rb + BLOCK))); + // the CPU view under a page never named reaches it; under a mapped or unmapped one, not + assert_eq!(twins(&[cv + 6 * PAGE + 0x2000, cv + 6 * PAGE + 0x5000]), vec![g + 6 * PAGE + 0x2000, g + 6 * PAGE + 0x5000]); + assert!(twins(&[cv + PAGE + 0x2000]).is_empty(), "mapped"); + assert!(apply_batches(1, [batch(g + 6 * PAGE, &[[2, 0, 1]])].as_ptr() as usize, pool, 1).is_some()); + assert!(twins(&[cv + 6 * PAGE + 0x2000]).is_empty(), "unmapped"); + + assert_eq!(VirtualFree(cv as *mut c_void, 0, mem::MEM_RELEASE), 1); + assert!(twins(&[r + 0x2000]).is_empty(), "released with the view"); + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 1, 0, 4, std::ptr::null_mut()) as usize, r); + assert_eq!(FreeTitlePhysicalPages(null, 1, pages.as_mut_ptr()), 1); + for q in [space, r] { + assert_eq!(VirtualFree(q as *mut c_void, 0, mem::MEM_RELEASE), 1); + } + } + } + + /// While GPU views show mapped pages, memory of no pair is told to sparse before it goes (a + /// tile may show a page kept there): the address a page leaves, while still committed; the + /// home given back once the page was mapped away from it again; the release of the block's + /// home. The release of the pool leaves the page kept there showing nothing. + #[test] + fn memory_under_a_shown_page_is_told_to_sparse_before_it_goes() { + use mirrors::{apply_batches, shows, Shows, PAGE}; + const SIZE: usize = 151 * PAGE; + let g = 0x72B0_0000_0000usize; + let null = std::ptr::null_mut(); + let kept = || KEPT_GOING.with(|s| s.take()); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let mut n = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1); + let [a, b] = pages; + let home = page_home(a).unwrap(); + let cv = cpu_view(SIZE, g); + let pool = reserve_watched(2 * PAGE, 0x2000, mem::PAGE_READWRITE) as usize; + let r = reserve_watched(2 * PAGE, 0x2000, mem::PAGE_READWRITE) as usize; + assert!(pool != 0 && r != 0); + for (at, page) in [(pool, a), (pool + PAGE, b)] { + let mut one = [page]; + assert_eq!(MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, at); + *(at as *mut u32) = page as u32; + } + // a at view page 1, b at 2 + let ranges = [[0, 0, 2]]; + assert!(apply_batches(1, [batch(g + PAGE, &ranges)].as_ptr() as usize, pool, 2).is_some()); + assert_eq!(shows(g + PAGE), Shows::Page { at: pool, tile: true }); + SOURCES_GOING.with(|s| s.borrow_mut().clear()); + kept(); + + // a mapped elsewhere: the address it leaves is told while still committed + let (mut one, mut none) = ([a], [0usize]); + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, r); + assert_eq!(kept(), vec![(pool, PAGE, true)]); + assert!(!committed_page(pool)); + // unmapped there (home), then mapped elsewhere again: the home is given back, told while + // still committed (a home in committed memory stays) + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 1, 0, 4, none.as_mut_ptr()) as usize, r); + assert_eq!(kept(), vec![(r, PAGE, true)]); + assert_eq!(shows(g + PAGE), Shows::Page { at: home, tile: true }); + assert_eq!(MapTitlePhysicalPages((r + PAGE) as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, r + PAGE); + assert_eq!(*((r + PAGE) as *const u32), a as u32); + assert_eq!(kept(), if lazy_home(home) { vec![(home, PAGE, true)] } else { Vec::new() }); + assert_eq!(shows(g + PAGE), Shows::Page { at: r + PAGE, tile: true }); + assert!(SOURCES_GOING.with(|s| s.take()).is_empty(), "no pair"); + + // the pool released: b, kept there, shows nothing; a is kept elsewhere + assert_eq!(VirtualFree(pool as *mut c_void, 0, mem::MEM_RELEASE), 1); + assert_eq!(kept(), vec![(pool, 2 * PAGE, false)]); + assert_eq!(shows(g + 2 * PAGE), Shows::Nothing); + assert_eq!(shows(g + PAGE), Shows::Page { at: r + PAGE, tile: true }); + // a home again, then both freed: the release of their home block is told + assert_eq!(MapTitlePhysicalPages((r + PAGE) as *mut c_void, 1, 0, 4, none.as_mut_ptr()) as usize, r + PAGE); + kept(); + assert_eq!(FreeTitlePhysicalPages(null, 2, pages.as_mut_ptr()), 1); + assert_eq!(kept(), vec![(home, 2 * PAGE, true)]); + assert_eq!(shows(g + PAGE), Shows::Nothing); + for q in [cv, r] { + assert_eq!(VirtualFree(q as *mut c_void, 0, mem::MEM_RELEASE), 1); + } + } + } + /// A page mapped at another page's home, then the whole allocation mapped back home: the /// first page goes home and leaves that address committed, as the second one's home. #[test] @@ -3079,6 +5034,34 @@ mod tests { mirrors::released(other); } + /// A pair that forms or goes is a change of what the GPU view shows: readers of GPU views + /// (`gpu_view_map_changes`) look at its range again – once paired, a texture placed there + /// before reads the CPU view, and once unpaired it no longer does. + #[test] + fn a_gpu_view_pair_that_forms_or_goes_is_a_change_of_the_view() { + // (addresses far above anything Windows hands out: only the bookkeeping is tested) + let (a, b, size) = (0x7100_0000_0000usize, 0x7106_0000_0000usize, 0x6_1000_0000usize); + let seen = |since: u64| gpu_view_map_changes(since).unwrap_or_default().contains(&(b, b + size)); + assert!(!mirrors::would_pair(size)); + mirrors::reserved(a, size, 0x2040_2000, mem::PAGE_READWRITE); + assert!(mirrors::would_pair(size), "a CPU view waits for its GPU view"); + let before = gpu_view_map_gen(); + assert!(mirrors::reserved(b, size, 0x2040_2000, 0x801)); + assert!(!mirrors::would_pair(size)); + assert!(gpu_view_map_gen() > before && seen(before), "the pair is a change of the view"); + let paired = gpu_view_map_gen(); + mirrors::released(b); + assert_eq!(mirrors::source(b), None); + assert!(gpu_view_map_gen() > paired && seen(paired), "the end of the pair is a change too"); + // the CPU view waits again; released with it, a GPU view goes too + assert!(mirrors::would_pair(size)); + assert!(mirrors::reserved(b, size, 0x2040_2000, 0x801)); + let paired = gpu_view_map_gen(); + mirrors::released(a); + assert!(seen(paired), "a GPU view whose CPU view went"); + assert!(!mirrors::would_pair(size) && !mirrors::reserved(b, size, 0x2040_2000, 0x801)); + } + /// GPU-visible title memory that reaches the plain-memory fallback (64 KiB pages, large /// pages, a graphics protection) is write-watched: a texture placed there sees the CPU's /// writes. The fallback is called directly: through `VirtualAlloc` these sizes land in a @@ -3246,9 +5229,13 @@ mod tests { Some(cpu as usize + 0x2_0000), "GPU view must resolve to CPU view even when CPU view lives in sparse UMA" ); - // GPU-view alias must not consume sparse UMA VA. + // GPU-view alias must not consume sparse UMA VA: it goes to a view window (16 windows) + // or stays outside unified memory. if let Some(u) = crate::gpu::uma::get() { assert!(!u.is_sparse(gpu as usize), "CPU-inaccessible GPU view should stay outside sparse UMA"); + let views = (0..u.shader_windows()).any(|k| u.is_view_window(k)); + assert_eq!(u.is_view(gpu as usize), views, "the GPU view is in a view window when there are any"); + assert!(!u.contains(gpu as usize), "the CPU cannot touch a GPU view"); } assert_eq!(VirtualFree(gpu, 0, mem::MEM_RELEASE), 1); assert_eq!(mirrors::source(gpu as usize + 0x2_0000), None); @@ -3281,6 +5268,25 @@ mod tests { } } + /// Homes of physical pages leave window 0 – the console's low 4 GiB – to the title: after + /// the Series S run's 2.9 GB of sparse GPU heaps and 664 MB of pages, its 38 MB view heap still + /// fits there (the homes in window 0 left it none, and the heap went to window 1). + #[test] + fn physical_homes_leave_window_0_to_the_title() { + let u = crate::gpu::uma::Uma::for_runtime(16 << 20).unwrap(); + unsafe { + let heaps = u.sparse_alloc(2892 << 20, 2 << 20).unwrap().0; + let home = alloc_physical_home(&u, 664 << 20).unwrap(); + assert_eq!(u.window_of(home), Some(1), "the home keeps out of window 0"); + assert!(lazy_home(home)); + let view_heap = u.sparse_alloc(0x260_0000, crate::gpu::uma::GRAIN).unwrap().0; + assert_eq!(u.window_of(view_heap), Some(0)); + for p in [view_heap, home, heaps] { + assert!(u.sparse_release(p).is_some()); + } + } + } + #[test] fn physical_home_without_sparse_windows_uses_coherent_window() { let u = crate::gpu::uma::Uma::with_windows(1, 16 << 20).unwrap(); diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index fa750b9a48..2f858372e7 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -83,6 +83,11 @@ pub(super) fn unmark(page: usize) -> bool { LAZY.write().unwrap_or_else(|e| e.into_inner()).remove(&page) } +/// Whether `page` is mapped and still not committed. +pub(super) fn is_marked(page: usize) -> bool { + LAZY.read().unwrap_or_else(|e| e.into_inner()).contains(&page) +} + /// The lazy pages of `[p, p + len)` committed – memory a kernel call or XCL writes. pub fn ensure(p: usize, len: usize) { if len == 0 { diff --git a/crates/xcl/src/hle/kernelx/placeholders.rs b/crates/xcl/src/hle/kernelx/placeholders.rs index 218a9bb3b6..f44b1b401b 100644 --- a/crates/xcl/src/hle/kernelx/placeholders.rs +++ b/crates/xcl/src/hle/kernelx/placeholders.rs @@ -127,7 +127,8 @@ pub(super) unsafe fn free(addr: *mut c_void, size: usize, flags: u32) -> Option< } let len = if size == 0 { r.end - base } else { size }; super::super::d3d12x::sparse::decommitted(base, len); - return Some(mem::VirtualFree(addr, len, mem::MEM_DECOMMIT)); + // (the place of a page a tile shows may lie here: `source_part`) + return Some(super::source_going(base, len, false, || mem::VirtualFree(addr, len, mem::MEM_DECOMMIT))); } if start != base || (flags != PRESERVE && flags != mem::MEM_RELEASE) || (flags == mem::MEM_RELEASE && size != 0) || (flags == PRESERVE && size != 0 && size != r.end - base) @@ -136,7 +137,7 @@ pub(super) unsafe fn free(addr: *mut c_void, size: usize, flags: u32) -> Option< } if !r.placeholder { super::super::d3d12x::sparse::decommitted(base, r.end - base); - if mem::VirtualFree(addr, r.end - base, mem::MEM_DECOMMIT) == 0 { + if super::source_going(base, r.end - base, false, || mem::VirtualFree(addr, r.end - base, mem::MEM_DECOMMIT)) == 0 { return Some(0); } } diff --git a/crates/xcl/src/hle/mod.rs b/crates/xcl/src/hle/mod.rs index abea3ae4ee..1555d4d8d8 100644 --- a/crates/xcl/src/hle/mod.rs +++ b/crates/xcl/src/hle/mod.rs @@ -10,6 +10,7 @@ use std::sync::OnceLock; use crate::config::Config; use crate::util::glob_match; +pub mod api_cost; pub mod acphal; pub mod bcpack; pub mod bink; diff --git a/crates/xcl/src/hle/xg.rs b/crates/xcl/src/hle/xg.rs index be12ded2ab..dd8b0a792d 100644 --- a/crates/xcl/src/hle/xg.rs +++ b/crates/xcl/src/hle/xg.rs @@ -11,7 +11,8 @@ //! GetResourceSizeBytes, GetResourceBaseAlignmentBytes, GetMipLevelOffsetBytes(plane, mip), //! GetTexelElementOffsetBytes(plane, mip, x, y, slice, sample, bit*), GetTexelCoordinate, //! CopyIntoSubresource(dst, plane, subresource, src, row pitch, slice pitch), -//! CopyFromSubresource(dst, plane, subresource, src, row pitch, slice pitch), then 2 more. +//! CopyFromSubresource(dst, plane, subresource, src, row pitch, slice pitch) – a newer library +//! has a 32-bit argument before `src` (`copy_args`) –, then 2 more. //! * XG_RESOURCE_LAYOUT (0x1B40): size @0, alignment @8, mips @0x10, planes @0x14, planes //! from 0x18, 0x6C8 bytes each (usage @0, size @8, slice size @0x10, alignment @0x20, bytes //! per element @0x28, first mip in the tail @0x2C, mips in the tail @0x30, then 15 mips of @@ -673,8 +674,41 @@ fn subresource(t: &Texture, plane: u32, sub: u32) -> Option<(&Surface, u64, usiz (k < s.array as usize).then_some((s, at, i, k)) } +/// The arguments after `subresource` of CopyIntoSubresource / CopyFromSubresource: (pointer, row +/// pitch, slice pitch). The library XDefiant and Fortnite ship takes (pointer, row pitch, slice +/// pitch); a newer one (a retail game's) has a 32-bit argument before the pointer – passed as 0, +/// stored as a dword, so the slot's upper half is whatever the stack held. Read the older way, +/// that call gave the low half of a pointer as the row pitch and the copy wrote rows gigabytes +/// past the destination. Told apart per call: a small value there with a readable pointer after +/// it is the newer form. +unsafe fn copy_args(a4: usize, a5: usize, a6: usize, a7: usize) -> (*const u8, u32, u32) { + // (address space, not readable memory: the title's pages are committed on first use) + let in_use = |a: usize| { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_FREE}; + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + a >= 0x1_0000 && VirtualQuery(a as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 && m.State != MEM_FREE + }; + let newer = a4 as u32 <= 0xFFFF && in_use(a5); + // (a retail game calls both forms) + static SEEN: AtomicU32 = AtomicU32::new(0); + let bit = 1 << newer as u32; + if SEEN.fetch_or(bit, Ordering::Relaxed) & bit == 0 { + crate::xlog_info!("xg: CopyInto/FromSubresource called in the {} form", if newer { "newer 7-argument" } else { "6-argument" }); + } + if newer { + if a4 as u32 != 0 { + static EXTRA: std::sync::Once = std::sync::Once::new(); + EXTRA.call_once(|| crate::xlog_warn!("xg: CopyInto/FromSubresource with {:#x} in its added argument (meaning unknown, ignored)", a4 as u32)); + } + (a5 as *const u8, a6 as u32, a7 as u32) + } else { + (a4 as *const u8, a5 as u32, a6 as u32) + } +} + /// rows of `src` (`row_pitch` apart) → the level's place in `dst` (the whole resource) -unsafe extern "system" fn copy_into(p: *mut c_void, dst: *mut u8, plane: u32, sub: u32, src: *const u8, row_pitch: u32, slice_pitch: u32) -> HRESULT { +unsafe extern "system" fn copy_into(p: *mut c_void, dst: *mut u8, plane: u32, sub: u32, a4: usize, a5: usize, a6: usize, a7: usize) -> HRESULT { + let (src, row_pitch, slice_pitch) = copy_args(a4, a5, a6, a7); let Some((t, at, i, k)) = subresource(tex(p), plane, sub).filter(|_| !dst.is_null() && !src.is_null()) else { return E_INVALIDARG }; let m = t.chain.levels[i]; let row = m.width * t.bpe as usize; @@ -697,7 +731,8 @@ unsafe extern "system" fn copy_into(p: *mut c_void, dst: *mut u8, plane: u32, su } /// the level's place in `src` (the whole resource) → rows of `dst` (`row_pitch` apart) -unsafe extern "system" fn copy_from(p: *mut c_void, dst: *mut u8, plane: u32, sub: u32, src: *const u8, row_pitch: u32, slice_pitch: u32) -> HRESULT { +unsafe extern "system" fn copy_from(p: *mut c_void, dst: *mut u8, plane: u32, sub: u32, a4: usize, a5: usize, a6: usize, a7: usize) -> HRESULT { + let (src, row_pitch, slice_pitch) = copy_args(a4, a5, a6, a7); let Some((t, at, i, k)) = subresource(tex(p), plane, sub).filter(|_| !dst.is_null() && !src.is_null()) else { return E_INVALIDARG }; let m = t.chain.levels[i]; let row = m.width * t.bpe as usize; @@ -734,6 +769,41 @@ mod tests { d } + /// CopyInto / CopyFromSubresource in both forms: the 6-argument one, and the newer one with a + /// 32-bit argument before the pointer whose stack slot's upper half holds garbage – the same + /// bytes tiled and read back, the pitch not taken from the pointer. + #[test] + fn subresource_copies_take_both_argument_forms() { + type Six = unsafe extern "system" fn(*mut c_void, *mut u8, u32, u32, *const u8, u32, u32) -> HRESULT; + type Seven = unsafe extern "system" fn(*mut c_void, *mut u8, u32, u32, usize, *const u8, u32, u32) -> HRESULT; + let d = desc(64, 32, 1, 1, 28, 0x109); + let mut c: *mut c_void = std::ptr::null_mut(); + unsafe { + assert!(XGCreateTextureComputer(d.as_ptr(), &mut c) >= 0); + let t = Texture::new(&d).unwrap(); + let size = t.size() as usize; + let pitch = 64 * 4 + 32; + let lin: Vec = (0..pitch * 32).map(|i| (i * 7 + i / 251) as u8).collect(); + let slot = |k: usize| *(*(c as *const *const usize)).add(k); + let (into6, from6): (Six, Six) = (std::mem::transmute(slot(8)), std::mem::transmute(slot(9))); + let (into7, from7): (Seven, Seven) = (std::mem::transmute(slot(8)), std::mem::transmute(slot(9))); + let (mut a, mut b) = (vec![0u8; size], vec![0u8; size]); + assert_eq!(into6(c, a.as_mut_ptr(), 0, 0, lin.as_ptr(), pitch as u32, 0), S_OK); + let garbage = 0x0000_0016_0000_0000usize; // a dword 0 under an old stack value + assert_eq!(into7(c, b.as_mut_ptr(), 0, 0, garbage, lin.as_ptr(), pitch as u32, 0), S_OK); + assert_eq!(a, b, "both forms tile the same bytes"); + let (mut back6, mut back7) = (vec![0u8; pitch * 32], vec![0u8; pitch * 32]); + assert_eq!(from6(c, back6.as_mut_ptr(), 0, 0, a.as_ptr(), pitch as u32, 0), S_OK); + assert_eq!(from7(c, back7.as_mut_ptr(), 0, 0, garbage, a.as_ptr(), pitch as u32, 0), S_OK); + for y in 0..32 { + let row = y * pitch..y * pitch + 64 * 4; + assert_eq!(back6[row.clone()], lin[row.clone()], "6-argument form, row {y}"); + assert_eq!(back7[row.clone()], lin[row], "7-argument form, row {y}"); + } + release(c); + } + } + /// As the console's library answers (seen on it): RGBA8 256×256, full chain, 64KB_S. #[test] fn rgba8_64kb_s_layout() { diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 3697b2a328..f76e9a7a8d 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -113,8 +113,15 @@ pub fn host_main(boot_path: &Path) -> i32 { let mut last = activity.then(snap); let mut last_looks = activity.then(crate::hle::d3d12x::sparse::look_counters); let mut pressure_turn = 0u64; + let mut cost = crate::hle::api_cost::totals(); + let mut own_cost = crate::hle::api_cost::submitter_totals(); + let mut views = crate::hle::d3d12x::view_want::totals(); + let mut tile_calls = crate::hle::d3d12x::sparse::tile_calls(); + let mut last_tick = std::time::Instant::now(); loop { std::thread::sleep(std::time::Duration::from_secs(2)); + let window_ms = last_tick.elapsed().as_millis() as u64; + last_tick = std::time::Instant::now(); let owner = activity.then(crate::hle::d3d12x::memory_report::snapshot); if pressure { pressure_turn = pressure_turn.wrapping_add(1); @@ -138,25 +145,53 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::hle::d3d12x::sparse::look_delta(looks, last_looks.unwrap()), 2, )); last_looks = Some(looks); + // the time the title's threads spent in some of XCL's calls + let spent = crate::hle::api_cost::totals(); + let calls = crate::hle::api_cost::all_threads_summary_parts(&spent, &cost); + cost = spent; + if !calls.is_empty() { + crate::xlog_info!("calls (2 s, all threads): {}", calls.join(", ")); + } + // `XCL_LOOK_STATS=2`: those of the thread that submits, its submits and presents + // with them: the time of its frames, added up + let spent = crate::hle::api_cost::submitter_totals(); + if let Some(summary) = crate::hle::api_cost::submitter_summary_line(&spent, &own_cost, window_ms) { + crate::xlog_info!("calls of the submitting thread (2 s): {summary}"); + } + own_cost = spent; + // the addresses in its GPU view the title gave the GPU, by the path they took + let asked = crate::hle::d3d12x::view_want::totals(); + if let Some(line) = crate::hle::d3d12x::view_want::line(&asked, &views) { + crate::xlog_info!("GPU view (2 s): {line}"); + } + views = asked; + // the sparse queue's UpdateTileMappings calls and tiles, by kind of window + let mappings = crate::hle::d3d12x::sparse::tile_calls(); + if let Some(line) = crate::hle::d3d12x::sparse::tile_calls_line(&mappings, &tile_calls) { + crate::xlog_info!("tile mappings (2 s): {line}"); + } + tile_calls = mappings; // where the memory is: the process's commit, video memory, and XCL's parts of it let owner = owner.unwrap(); let private = owner.commit.unwrap_or(0); let local = owner.local.map_or(0, |s| s.usage); let non_local = owner.non_local.map_or(0, |s| s.usage); + let budget = owner.local.map_or(0, |s| s.budget); let (arenas, arenas_made) = crate::hle::d3d12x::vram::arena_bytes(); let (pools, pools_mapped) = crate::hle::d3d12x::sparse::pool_bytes(); let (pages, page_pools) = crate::hle::d3d12x::vram::page_bytes(); let mb = |b: u64| b >> 20; + // (at the end: tools read the line's beginning; the guard script reads the budget) + let mut budget_text = if budget != 0 { format!("; video memory budget {} MB", mb(budget)) } else { String::new() }; // the system's commit: this process's memory counts against it with every other // program's (video memory does not), and where it ends allocations fail let (commit, commit_limit) = system_commit(); - let mut commit_text = String::new(); if commit_limit != 0 { - commit_text = format!("; system commit {} of {} MB", mb(commit), mb(commit_limit)); - warn_low_commit(commit, commit_limit, private as u64, local); + budget_text += &format!("; system commit {} of {} MB", mb(commit), mb(commit_limit)); + warn_low_commit(commit, commit_limit, private, local); } crate::xlog_info!( - "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped){commit_text}", + "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped){budget_text}", mb(private), mb(local), mb(non_local), @@ -190,6 +225,15 @@ pub fn host_main(boot_path: &Path) -> i32 { pct ); } + if pages != 0 { + crate::xlog_info!("{}", crate::hle::d3d12x::vram::page_owners()); + } + // past the budget Windows moves the process's video memory off the card and + // every frame pays for bringing it back; a run at the card's limit is also + // where the driver gave up (the guard script ends a run that stays there) + if let Some(over) = crate::hle::d3d12x::real::over_video_budget(local, budget) { + crate::xlog_warn!("video memory: {} MB in use, {} MB over the budget of {} MB Windows gives this process", mb(local), mb(over), mb(budget)); + } last = Some(now); } }); diff --git a/crates/xcl/src/loader.rs b/crates/xcl/src/loader.rs index 52c49afe78..bb38bb8bb8 100644 --- a/crates/xcl/src/loader.rs +++ b/crates/xcl/src/loader.rs @@ -230,6 +230,10 @@ fn map_image_ex(path: &Path, is_main: bool) -> Result, String> for s in pe.sections.iter().filter(|s| s.characteristics & 0x2000_0000 != 0) { let len = (s.mapped_size() as usize).min(size.saturating_sub(s.va as usize)); unsafe { crate::eh::hook_gs_failure(base + s.va as usize, len, &name) }; + // 9. a title's CLZERO loops on a CPU without CLZERO: native code in their place + if !crate::eh::cpu_has_clzero() { + unsafe { crate::eh::patch_clzero_loops(base + s.va as usize, len, &name) }; + } } Ok(module) } diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index 6fe7571fef..4c19f01568 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -128,6 +128,20 @@ fn run_picked_game() -> i32 { let Some(target) = target else { return 0 }; let _ = std::fs::create_dir_all(xcl::launcher::data_root()); let _ = std::fs::write(&last_file, target.to_string_lossy().as_bytes()); + // which console XCL is to the game, unless the environment says (`XCL_DEVICE_TYPE`) + if std::env::var_os("XCL_DEVICE_TYPE").is_none() { + let console_file = xcl::launcher::data_root().join("last-console.txt"); + let saved = std::fs::read_to_string(&console_file).ok(); + let picked = { + let _ui = Ui::enter(); + console_menu(console_of(saved.as_deref())) + }; + let Some(console) = picked else { return 0 }; + let _ = std::fs::write(&console_file, console); + // (the menu runs before the game and before XCL starts any thread of its own) + std::env::set_var("XCL_DEVICE_TYPE", console); + println!("console: {}", console_name(console)); + } println!("xcl run \"{}\"", target.display()); let code = xcl::launcher::run_from_menu(&target); if code != 0 { @@ -248,6 +262,56 @@ fn menu(last: Option<&std::path::Path>) -> Choice { } } +/// The device type a saved choice names: "lockhart" (Series S) or, for anything else and for +/// no choice yet, "anaconda" (Series X), the names `XCL_DEVICE_TYPE` takes. +fn console_of(saved: Option<&str>) -> &'static str { + match saved.map(str::trim) { + Some(s) if s.eq_ignore_ascii_case("lockhart") => "lockhart", + _ => "anaconda", + } +} + +fn console_name(console: &str) -> &'static str { + if console == "lockhart" { "Xbox Series S" } else { "Xbox Series X" } +} + +/// The second menu: which console XCL is to the game. A game asks which console it runs on and +/// sizes its memory, its resolution and its detail by the answer; XCL keeps what it learns +/// about a game's memory per console. `last` is the default. None: cancelled. Without a task +/// dialog on this system: `last`, unasked. +fn console_menu(last: &'static str) -> Option<&'static str> { + use windows_sys::Win32::UI::Controls::*; + const X: i32 = 110; + const S: i32 = 111; + type TaskDialogIndirect = unsafe extern "system" fn(*const TASKDIALOGCONFIG, *mut i32, *mut i32, *mut i32) -> i32; + let Some(f) = (unsafe { system_proc("comctl32.dll", "TaskDialogIndirect") }) else { return Some(last) }; + let title = wide("XCL"); + let heading = wide("Which console should XCL be?"); + let content = wide("The game asks which console it runs on and sets its memory, resolution and detail by the answer. This can be changed at every start; XCL_DEVICE_TYPE sets it without this question."); + let x = wide("Xbox Series X\nThe game's full settings. Needs the most video memory."); + let s = wide("Xbox Series S\nLower resolution and detail, 8 GB of game memory. Needs less video memory."); + let buttons = [TASKDIALOG_BUTTON { nButtonID: X, pszButtonText: x.as_ptr() }, TASKDIALOG_BUTTON { nButtonID: S, pszButtonText: s.as_ptr() }]; + let mut c: TASKDIALOGCONFIG = unsafe { std::mem::zeroed() }; + c.cbSize = std::mem::size_of::() as u32; + c.hwndParent = unsafe { windows_sys::Win32::System::Console::GetConsoleWindow() }; + c.dwFlags = TDF_USE_COMMAND_LINKS | TDF_ALLOW_DIALOG_CANCELLATION | TDF_POSITION_RELATIVE_TO_WINDOW; + c.dwCommonButtons = TDCBF_CANCEL_BUTTON; + c.pszWindowTitle = title.as_ptr(); + c.pszMainInstruction = heading.as_ptr(); + c.pszContent = content.as_ptr(); + c.cButtons = buttons.len() as u32; + c.pButtons = buttons.as_ptr(); + c.nDefaultButton = if last == "lockhart" { S } else { X }; + let mut pressed = 0i32; + let hr = unsafe { std::mem::transmute::(f)(&c, &mut pressed, std::ptr::null_mut(), std::ptr::null_mut()) }; + match (hr, pressed) { + (h, _) if h < 0 => Some(last), + (_, X) => Some("anaconda"), + (_, S) => Some("lockhart"), + _ => None, + } +} + /// The standard Windows open dialog (None: cancelled). fn pick_game_file() -> Option { use windows_sys::Win32::UI::Controls::Dialogs::*; @@ -271,3 +335,19 @@ fn pick_game_file() -> Option { let n = file.iter().position(|&c| c == 0).unwrap_or(file.len()); Some(PathBuf::from(String::from_utf16_lossy(&file[..n]))) } + +#[cfg(test)] +mod console_tests { + /// A saved choice names the Series S only as "lockhart"; no choice yet, or anything else, + /// is the Series X. + #[test] + fn the_saved_console_is_the_default_of_the_menu() { + assert_eq!(super::console_of(None), "anaconda"); + assert_eq!(super::console_of(Some(" lockhart\n")), "lockhart"); + assert_eq!(super::console_of(Some("LOCKHART")), "lockhart"); + assert_eq!(super::console_of(Some("anaconda")), "anaconda"); + assert_eq!(super::console_of(Some("")), "anaconda"); + assert_eq!(super::console_name("lockhart"), "Xbox Series S"); + assert_eq!(super::console_name("anaconda"), "Xbox Series X"); + } +} diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 57a6e5d5f9..427de54058 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -846,7 +846,9 @@ struct ShadersOptions { recomp: bool, iface: bool, example: Option, - windows: u32, + /// `--windows`; None: the runtime's count for `--precompile` / `--export-hlsl` / + /// `--measure-pso` (`configured_runtime_windows`), 4 for `--direct` + windows: Option, split: Option, export_hlsl: Option, min_kb: usize, @@ -887,7 +889,7 @@ fn parse_args(args: &[String]) -> Result { recomp: false, iface: false, example: None, - windows: 4, + windows: None, split: None, export_hlsl: None, min_kb: 1024, @@ -929,7 +931,7 @@ fn parse_args(args: &[String]) -> Result { "--example" => opts.example = Some(p.value("--example")?.to_string()), "--windows" => { let w = p.parse_usize("--windows")?; - opts.windows = u32::try_from(w).map_err(|_| format!("invalid value for --windows: {w}"))?; + opts.windows = Some(u32::try_from(w).map_err(|_| format!("invalid value for --windows: {w}"))?); } "--split" => opts.split = Some(p.parse_bool_01("--split")?), "--export-hlsl" => opts.export_hlsl = Some(PathBuf::from(p.value("--export-hlsl")?)), @@ -1051,7 +1053,18 @@ pub fn run(path: &Path, args: &[String]) -> i32 { Err(e) => { eprintln!("xcl shaders: {e}"); 2 } }; } - let runtime_windows = || runtime_windows(opts.windows); + // the runtime's memory windows: as many as a run has (`XCL_UMA_WINDOWS`) unless `--windows` + // says, as its shaders take them (`runtime_windows`), as `--precompile` + let runtime_windows = { + let windows = opts.windows.map_or_else(crate::gpu::uma::configured_runtime_windows, |w| w as usize); + let heap = windows > 1 && recomp::pso::heap_windows(); + if !recomp::valid_window_count(windows, heap) { + eprintln!("xcl shaders: --windows {windows}: 1 to 4, or 8 or 16 with XCL_HEAP_WINDOWS=1"); + return 2; + } + let windows = windows as u32; + move || runtime_windows(windows) + }; if opts.graphics_records { return graphics_worker(path, runtime_windows(), opts.threads); } @@ -2563,6 +2576,10 @@ pub(crate) struct LaunchPreparation { pub graphics: std::sync::atomic::AtomicBool, /// While replaying the discovered corpus, only verified native successes advance `done`. pub corpus: std::sync::atomic::AtomicBool, + /// The shaders earlier runs used (`pso_async::earlier_used_shaders`), when there are any: + /// only their records are translated before the title starts, and it translates another + /// when it first uses it. `XCL_PREPARE_ALL=1`: every record, as without the list. + pub only: Option>, } impl LaunchPreparation { @@ -2803,76 +2820,23 @@ fn progress_count(line: &str) -> Option { d.parse().ok() } -/// A pipeline one process builds: a file beside the driver blob it will write (`.claim`), -/// made when the build starts and gone when it ends. A second process that finds it leaves the -/// pipeline to the first. One left behind by a process that died is taken over after `STALE`. -struct WorkerClaim(PathBuf); - -impl WorkerClaim { - const STALE: std::time::Duration = std::time::Duration::from_secs(30 * 60); - - /// None: another process has it. - fn take(blob: &std::path::Path) -> Option { - let mut name = blob.as_os_str().to_owned(); - name.push(".claim"); - let path = PathBuf::from(name); - let make = || std::fs::OpenOptions::new().write(true).create_new(true).open(&path); - match make() { - Ok(_) => Some(WorkerClaim(path)), - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { - let old = std::fs::metadata(&path).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > Self::STALE); - (old && std::fs::remove_file(&path).is_ok() && make().is_ok()).then(|| WorkerClaim(path)) - } - // (the folder cannot be written: nothing is shared through it either) - Err(_) => Some(WorkerClaim(PathBuf::new())), - } - } -} - -impl Drop for WorkerClaim { - fn drop(&mut self) { - if !self.0.as_os_str().is_empty() { - let _ = std::fs::remove_file(&self.0); - } - } -} - -#[cfg(test)] -mod claim_tests { - use super::WorkerClaim; - - /// The first process to ask builds a pipeline, a second one leaves it, and it is free again - /// when the first is done. - #[test] - fn a_pipeline_is_claimed_by_one_builder_at_a_time() { - let dir = std::env::temp_dir().join(format!("xcl-claim-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let blob = dir.join("0123.pso"); - let first = WorkerClaim::take(&blob).expect("free"); - assert!(dir.join("0123.pso.claim").exists()); - assert!(WorkerClaim::take(&blob).is_none(), "claimed"); - assert!(WorkerClaim::take(&dir.join("4567.pso")).is_some(), "another pipeline is free"); - drop(first); - assert!(!dir.join("0123.pso.claim").exists()); - assert!(WorkerClaim::take(&blob).is_some(), "free again"); - let _ = std::fs::remove_dir_all(&dir); - } -} - /// The compute pipelines of `pack` built by `workers` processes of this program, each on its own /// slice of the records (`XCL_PRECOMPILE_SLICE`). A failed worker prevents guest entry. fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usize, progress: &LaunchPreparation, coverage: Option<&ComputeCoverage>) -> Result<(), String> { let me = std::env::current_exe().map_err(|e| e.to_string())?; + let series_s = crate::hle::d3d12x::pso_async::profile_is_series_s(); let map = coverage.map(|c| c.slice_file()).transpose()?.flatten(); + // only the pipelines an earlier run of the title used, when that list exists and the title's + // shaders are limited to those an earlier run used (`LaunchPreparation::only`; the title + // builds another when it first uses it) + let used_only = progress.only.is_some() && !crate::hle::d3d12x::pso_async::earlier_used_keys().is_empty(); let t0 = std::time::Instant::now(); - crate::xlog_info!("Shader preparation: compute pipelines in {workers} worker processes"); + crate::xlog_info!("Shader preparation: compute pipelines in {workers} worker processes{}", if used_only { ", those an earlier run used" } else { "" }); let (cancelled, failed, _) = in_workers(workers, records, progress, |i| { - let mut c = worker_command(&me); + let mut c = pipeline_worker_command(&me, pack, windows, used_only, &format!("{i}/{workers}"), series_s); if let Some((file, dir)) = &map { c.env(COVERAGE_MAP, &file.0).env(COVERAGE_DIR, dir); } - c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); if std::env::var_os("XCL_ADAPTER").is_none() && !progress.adapter.is_empty() { c.env("XCL_ADAPTER", &progress.adapter); } - c.env("XCL_PRECOMPILE_SLICE", format!("{i}/{workers}")); c }); if cancelled { return Err("Shader preparation cancelled".into()); } @@ -2881,6 +2845,17 @@ fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usiz Ok(()) } +/// Compute pipeline worker `slice` (`i/n`) of `pack`, with the console profile: the worker reads +/// that profile's used-pipeline list (`used_pipelines_name`). +fn pipeline_worker_command(me: &Path, pack: &Path, windows: u32, used_only: bool, slice: &str, series_s: bool) -> std::process::Command { + let mut c = worker_command(me); + c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); + if used_only { c.arg("--used-only"); } + c.env("XCL_PRECOMPILE_SLICE", slice); + c.env("XCL_DEVICE_TYPE", if series_s { "lockhart" } else { "anaconda" }); + c +} + /// A preparation worker: this program, not a host and not a launcher's child, a builder that /// ends when this process does. fn worker_command(me: &Path) -> std::process::Command { @@ -3513,6 +3488,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on record_done(); continue; } + if startup.and_then(|p| p.only.as_ref()).is_some_and(|used| !used.contains(&crate::hle::d3d12x::real::shader_key(&blob))) { + record_done(); + continue; + } // a compute program as a title's pipeline translates it (`pso::console_to_dxil_in`): // into the translation cache too, so the title does not translate it again if sh.fssm.iter().any(|f| matches!(recomp::interface(&blob, &sh, f), Some(recomp::Mode::Compute(_)))) { @@ -3588,7 +3567,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // as `pso` translates: with the title's memory windows (`console_translation`, // `translate_mesh`) let split = if matches!(mode, recomp::Mode::Vertex(_) | recomp::Mode::Pixel(_)) { graphics_split } else { split }; - let opt = recomp::Options { mode: mode.clone(), wave64: recomp::fssm_wave64(f, code), split_wave64: split, mem_windows: windows, ..Default::default() }; + let opt = recomp::Options { mode: mode.clone(), wave64: recomp::fssm_wave64(f, code), split_wave64: split, mem_windows: windows, rodata: f.rodata(p), ..Default::default() }; let t = match recomp::translate(code, &opt) { Ok(t) if t.complete() => t, Ok(_) => { @@ -4243,6 +4222,18 @@ mod tests { assert!(!super::used_indirect_split(&b, &indirect)); } + #[test] + fn pipeline_worker_command_forwards_console_profile() { + let dev_env = |series_s| { + let cmd = super::pipeline_worker_command(Path::new("xcl.exe"), Path::new("shaders.rpf"), 4, false, "0/2", series_s); + cmd.get_envs() + .find_map(|(k, v)| (k == std::ffi::OsStr::new("XCL_DEVICE_TYPE")).then(|| v.map(|s| s.to_string_lossy().into_owned()))) + .flatten() + }; + assert_eq!(dev_env(true).as_deref(), Some("lockhart")); + assert_eq!(dev_env(false).as_deref(), Some("anaconda")); + } + use super::*; use crate::gpu::xbox::tests::{fssm, sample, CODE}; @@ -4502,7 +4493,7 @@ fn direct_sweep(input: &Input, opts: &ShadersOptions, t0: std::time::Instant) -> let seed = opts.seed; let validate = opts.validate; let compare = opts.compare; - let windows = opts.windows; + let windows = opts.windows.unwrap_or(4); let split = opts.split.unwrap_or(true); // records hold one or more programs: sample records, stop at `want` programs let order = coverage::sample_indices(input.len(), want, seed); @@ -4573,9 +4564,9 @@ fn direct_sweep(input: &Input, opts: &ShadersOptions, t0: std::time::Instant) -> let t = std::time::Instant::now(); let r = { let (tx, rx) = std::sync::mpsc::channel(); - let (c, m) = (code.to_vec(), mode.clone()); + let (c, m, rodata) = (code.to_vec(), mode.clone(), f.rodata(p)); std::thread::spawn(move || { - let _ = tx.send(coverage::translate_mode(&c, &m, o, validate)); + let _ = tx.send(coverage::translate_mode(&c, &m, o, validate, &rodata)); }); rx.recv_timeout(timeout).unwrap_or_else(|_| Err(format!("timeout: over {} s", timeout.as_secs()))) }; @@ -4617,7 +4608,7 @@ fn direct_sweep(input: &Input, opts: &ShadersOptions, t0: std::time::Instant) -> recomp::Mode::Pixel(_) => "ps_6_6", _ => "cs_6_6", }; - let opt = recomp::Options { mode: mode.clone(), wave64, split_wave64: wave64 && split, mem_windows: windows, ..Default::default() }; + let opt = recomp::Options { mode: mode.clone(), wave64, split_wave64: wave64 && split, mem_windows: windows, rodata: f.rodata(p), ..Default::default() }; let t = recomp::translate(code, &opt).ok().filter(|t| t.complete())?; dump("hlsl", t.hlsl.as_bytes()); let d = recomp::dxc::compile(&t.hlsl, "main", profile, &[]).ok()?; diff --git a/crates/xcl/src/vfs_hooks.rs b/crates/xcl/src/vfs_hooks.rs index 0767cf1e1c..437951d401 100644 --- a/crates/xcl/src/vfs_hooks.rs +++ b/crates/xcl/src/vfs_hooks.rs @@ -527,14 +527,19 @@ unsafe extern "system" fn hk_remove_dir_w(n: *const u16) -> i32 { } /// ReadFile: a buffer in pages the title mapped but has not used yet (`kernelx::lazy`) is -/// committed first – the kernel's write there would fail rather than fault in the title. +/// committed first – the kernel's write there would fail rather than fault in the title. What it +/// puts into graphics memory is noted (`d3d12x::file_reads`). unsafe extern "system" fn hk_read_file(h: *mut c_void, buf: *mut c_void, n: u32, read: *mut u32, ov: *mut c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut u32, *mut c_void) -> i32; let orig = orig!(O_READ_FILE as F); if !buf.is_null() { crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); } - orig(h, buf, n, read, ov) + let r = orig(h, buf, n, read, ov); + let error = windows_sys::Win32::Foundation::GetLastError(); + crate::hle::d3d12x::file_reads::returned(r != 0, error, buf, n, read, ov); + SetLastError(error); + r } unsafe extern "system" fn hk_delete_file_w(n: *const u16) -> i32 { diff --git a/crates/xcl/tests/d3d12_mesh_stream.rs b/crates/xcl/tests/d3d12_mesh_stream.rs index d742ee26d0..3a9cdbdd0a 100644 --- a/crates/xcl/tests/d3d12_mesh_stream.rs +++ b/crates/xcl/tests/d3d12_mesh_stream.rs @@ -2,8 +2,8 @@ //! (`d3d12x::real::dev_create_pipeline_state` / `translated_mesh_stream`), with no game data. //! //! Runs on any D3D12 adapter (AMD, NVIDIA, Intel, or WARP) with zero vendor-specific skips: -//! 1. Synthetic console MS placed in the AS slot with no MS slot is refused cleanly with -//! `E_INVALIDARG` and records the `"in the AS slot – refused"` error. +//! 1. Synthetic console MS placed in the AS slot with no MS slot is taken as the mesh shader +//! (#541) and, having no NGG variant, refused cleanly with `E_INVALIDARG` by its translation. //! 2. Synthetic console MS paired with an AS subobject is refused cleanly with `E_INVALIDARG`. //! 3. Empty, truncated, unknown-subobject, and unreadable-shader pipeline streams fail cleanly //! without panicking or crashing. @@ -91,11 +91,13 @@ fn console_ms_in_as_slot_and_ms_with_as_are_refused_cleanly() { SizeInBytes: std::mem::size_of::(), pPipelineStateSubobjectStream: &st as *const _ as *mut c_void, }; - let err = unsafe { d2.CreatePipelineState::(&desc) }.expect_err("MS in AS slot must be refused"); + let err = unsafe { d2.CreatePipelineState::(&desc) }.expect_err("MS with no NGG variant must be refused"); assert_eq!(err.code(), E_INVALIDARG); + // since #541 it is not refused for its slot: it is translated as the MS it is, and this + // container has no NGG variant to translate assert!( - real::stats().translation_errors.iter().any(|e| e.contains("in the AS slot")), - "expected AS-slot refusal in translation_errors: {:?}", + real::stats().translation_errors.iter().any(|e| e.starts_with("MS: ")), + "expected the MS translation's refusal in translation_errors: {:?}", real::stats().translation_errors ); diff --git a/crates/xcl/tests/gpu_compute_e2e.rs b/crates/xcl/tests/gpu_compute_e2e.rs index 5374ef2b06..ffdf1c848b 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -160,8 +160,10 @@ fn split_compute_prefers_the_offline_whole_pipeline() { assert!(files.next().is_none() && blob.metadata().unwrap().len() > 0); for case in ["hit","stale","miss"] { if case == "stale" { fs::write(&blob, b"rejected driver cache fixture").unwrap(); } + // (16: the entry block, with its thread limit test, is about 50 instructions, and a block + // over 4 x the limit keeps the program whole) run(Command::new(std::env::current_exe().unwrap()).args(["--exact","split_compute_prefers_the_offline_whole_pipeline","--nocapture"]) - .env("XCL_DIRECT_SPLIT_INSTRUCTIONS","12").env("XCL_TEST_WHOLE_CASE",case)); + .env("XCL_DIRECT_SPLIT_INSTRUCTIONS","16").env("XCL_TEST_WHOLE_CASE",case)); assert_eq!(blob.exists(), case == "hit"); } fs::remove_dir_all(dir).unwrap(); @@ -306,6 +308,59 @@ fn offline_split_compute_pipeline_is_reused_by_a_second_process() { let _ = fs::remove_dir_all(&dir); } +/// A title's preparation worker (`XCL_PRECOMPILE_PARENT`) leaves the whole form of a split +/// program in the driver cache besides its pieces: the title needs it at a split program's first +/// ExecuteIndirect, and builds it there itself when it is missing. +#[test] +fn a_preparation_worker_also_builds_a_split_programs_whole_form() { + use std::{fs, process::Command}; + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + if xcl::gpu::recomp::dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("xcl-worker-whole-{}-{nonce}", std::process::id())); + let input = dir.join("input"); + let cache = dir.join("cache"); + fs::create_dir_all(&input).unwrap(); + fs::write(input.join("split.bin"), console_cs(&split_program(), 2 << 1 | 1 << 7, [32, 1, 1])).unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_xcl")) + .arg("shaders") + .arg(&input) + .args(["--precompile", "--pipelines", "--windows", "1"]) + .env("XCL_DXIL_CACHE", &cache) + .env("XCL_DIRECT_DXIL", "1") + .env("XCL_DIRECT_SPLIT_INSTRUCTIONS", "12") + .env("XCL_PSO_DISK_CACHE", "1") + // as `pipelines_in_workers` starts it: this test is its parent + .env("XCL_PRECOMPILE_PARENT", std::process::id().to_string()) + .output() + .unwrap(); + let text = String::from_utf8_lossy(&out.stdout).into_owned(); + assert!(out.status.success(), "{text} +{}", String::from_utf8_lossy(&out.stderr)); + let files: Vec<_> = fs::read_dir(cache.join("driver")).unwrap().flatten().map(|e| e.path()).collect(); + // the split program's pieces, as the precompile counts them ("split compute programs: 1 (N + // pieces)"); the whole form is one more pipeline, its blob kept beside theirs + let pieces: usize = text + .split("split compute programs: 1 (") + .nth(1) + .and_then(|t| t.split(' ').next()) + .and_then(|n| n.parse().ok()) + .unwrap_or_else(|| panic!("no split program: {text}")); + assert!(pieces >= 2, "{text}"); + assert!(text.contains(&format!("pipelines made on the GPU {}, refused 0", pieces + 1)), "the whole form was not built: {text}"); + assert_eq!(files.len(), pieces + 1, "a blob for each piece and the whole form: {files:?} +{text}"); + assert!(files.iter().all(|p| p.metadata().unwrap().len() > 0)); + let _ = fs::remove_dir_all(&dir); +} + /// 16×8 threads per group (two wave64s), s[0:1] = output base and row width, TGID_X/Y in /// s2/s3, thread ids in v0/v1: each thread writes its global (x, y), and through LDS + /// s_barrier the (x, y) of the thread at the mirrored index, which is in the other wave. @@ -580,8 +635,13 @@ fn async_compute_pso_registers_real_pso_and_not_standin() { assert!(!real::is_translated_compute(standin_raw), "stand-in must remain unregistered after background build"); assert!(real::pso_root_signature(real_raw).is_some(), "real compute PSO must have an ABI root signature"); - // Releasing the stand-in must release and forget the background-built real PSO too. + // Releasing the stand-in must release and forget the background-built real PSO too: once the + // queues are past it (late release since eb49926b; `XCL_LATE_RELEASE=0`: in the call). drop(pso); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while real::is_translated_compute(real_raw) && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(2)); + } assert!(!real::is_translated_compute(real_raw), "forgetting released async compute PSO must clean up TRANSLATED_COMPUTE"); } diff --git a/crates/xcl/tests/gpu_two_pass_cache_e2e.rs b/crates/xcl/tests/gpu_two_pass_cache_e2e.rs index 3f5938aa46..b5dbb60c8c 100644 --- a/crates/xcl/tests/gpu_two_pass_cache_e2e.rs +++ b/crates/xcl/tests/gpu_two_pass_cache_e2e.rs @@ -575,6 +575,12 @@ float4 main(V v) : SV_Target0 { return v.p0; } assert_eq!(draw_two_pass_and_read(&dev, &gs, 1, true), [0.0, 1.0, 0.0, 1.0]); assert_eq!(real::two_pass_count(), before + 3); drop((ms1, ms2, gs)); + // the compute passes go once the queues are past them (late release since eb49926b; + // `XCL_LATE_RELEASE=0`: in the call) + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while real::two_pass_count() != before && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(2)); + } assert_eq!(real::two_pass_count(), before, "releasing the title PSOs releases their two-pass state"); if dev.cast::().is_ok() { diff --git a/crates/xcl/tests/gpu_view_lists.rs b/crates/xcl/tests/gpu_view_lists.rs new file mode 100644 index 0000000000..009873b5b2 --- /dev/null +++ b/crates/xcl/tests/gpu_view_lists.rs @@ -0,0 +1,53 @@ +//! What a command list is given in a GPU view of the title's memory (`XCL_HEAP_WINDOWS=1`, +//! `XCL_UMA_WINDOWS=16`: the view lies in the view windows): an index or vertex buffer there goes +//! to the PC at its view window's address and never as the console address, which is no PC +//! address; a value there (a wait's, a sync cell's) is the CPU view's. Its own process: the window +//! layout is chosen at the first `uma::get()`, from the environment. No device is needed (without +//! one no window has a PC address yet). + +use xcl::gpu::uma; +use xcl::hle::d3d12x::list_x; +use xcl::hle::kernelx; + +const MEM_COMMIT: u32 = 0x1000; +const MEM_RESERVE: u32 = 0x2000; +const MEM_RELEASE: u32 = 0x8000; +/// MEM_LARGE_PAGES | MEM_PHYSICAL: the console's 64 KiB pages +const MEM_64K_PAGES: u32 = 0x2040_0000; +const PAGE_NOACCESS: u32 = 0x01; +const PAGE_READWRITE: u32 = 0x04; +const PAGE_GRAPHICS_NOACCESS: u32 = 0x800; + +/// the title's views: 24 GiB each (as a retail title reserves them: the CPU view stays out of the windows) +const SIZE: usize = 24 << 30; + +#[test] +fn a_list_takes_a_gpu_view_address_to_its_window_and_its_values_to_the_cpu_view() { + std::env::set_var("XCL_HEAP_WINDOWS", "1"); + std::env::set_var("XCL_UMA_WINDOWS", "16"); + std::env::set_var("XCL_COHERENT_MB", "512"); + let u = uma::get().expect("unified memory"); + assert_eq!(u.shader_windows(), uma::MAX_HEAP_WINDOWS, "the 16-window layout was not reserved"); + let null = std::ptr::null(); + unsafe { + let c = kernelx::VirtualAlloc(null, SIZE, MEM_RESERVE | MEM_64K_PAGES, PAGE_READWRITE) as usize; + assert_ne!(c, 0, "the CPU view"); + let g = kernelx::VirtualAlloc(null, SIZE, MEM_RESERVE | MEM_64K_PAGES, PAGE_NOACCESS | PAGE_GRAPHICS_NOACCESS) as usize; + assert_ne!(g, 0, "the GPU view"); + assert!(u.is_view(g), "the GPU view is in a view window"); + assert_eq!(kernelx::VirtualAlloc(c as *const _, 0x1_0000, MEM_COMMIT, PAGE_READWRITE) as usize, c); + + for x in [0usize, 0x40, 0x1_0008, SIZE - 8] { + // no window has a PC address without a device: none, never the console address + assert_eq!(list_x::pc_va_of((g + x) as u64), 0, "G + {x:#x}"); + assert_eq!(list_x::cpu_at((g + x) as u64), (c + x) as u64, "G + {x:#x}"); + assert_eq!(list_x::cpu_at((c + x) as u64), (c + x) as u64, "C + {x:#x}"); + } + // the CPU view is no unified memory: as it is + assert_eq!(list_x::pc_va_of(c as u64), c as u64); + + assert_eq!(kernelx::VirtualFree(g as *mut _, 0, MEM_RELEASE), 1); + assert_eq!(list_x::cpu_at(g as u64), g as u64, "unpaired: no CPU view"); + assert_eq!(kernelx::VirtualFree(c as *mut _, 0, MEM_RELEASE), 1); + } +} diff --git a/crates/xcl/tests/gpu_view_windows.rs b/crates/xcl/tests/gpu_view_windows.rs new file mode 100644 index 0000000000..e05bbaa24c --- /dev/null +++ b/crates/xcl/tests/gpu_view_windows.rs @@ -0,0 +1,83 @@ +//! A retail title reserves 24 GiB of 64 KiB pages twice: a CPU view (read/write, it holds the +//! bytes) and a GPU-only view of the same pages, whose addresses are all the GPU is given. With +//! 16 memory windows (`XCL_HEAP_WINDOWS=1`, `XCL_UMA_WINDOWS=16`) the GPU view goes to the view +//! windows, where shaders reach it, and still names its CPU view; the CPU view stays plain +//! write-watched memory outside the windows. Its own process: the window layout is chosen at the +//! first `uma::get()`, from the environment. No device is needed. + +use std::ffi::c_void; + +use xcl::gpu::uma; +use xcl::hle::kernelx::{self, mirrors}; + +const MEM_COMMIT: u32 = 0x1000; +const MEM_RESERVE: u32 = 0x2000; +const MEM_DECOMMIT: u32 = 0x4000; +const MEM_RELEASE: u32 = 0x8000; +/// MEM_LARGE_PAGES | MEM_PHYSICAL: the console's 64 KiB pages +const MEM_64K_PAGES: u32 = 0x2040_0000; +const PAGE_NOACCESS: u32 = 0x01; +const PAGE_READWRITE: u32 = 0x04; +const PAGE_GRAPHICS_NOACCESS: u32 = 0x800; + +/// the title's views: 24 GiB each +const SIZE: usize = 24 << 30; + +#[test] +fn a_gpu_view_lands_in_a_view_window_and_names_its_cpu_view() { + std::env::set_var("XCL_HEAP_WINDOWS", "1"); + std::env::set_var("XCL_UMA_WINDOWS", "16"); + // (the coherent window as small as it gets: not the size an earlier run of a title noted) + std::env::set_var("XCL_COHERENT_MB", "512"); + let u = uma::get().expect("unified memory"); + assert_eq!(u.shader_windows(), uma::MAX_HEAP_WINDOWS, "the 16-window layout was not reserved"); + let aperture = u.base()..u.base() + uma::MAX_HEAP_WINDOWS * uma::WINDOW; + let null = std::ptr::null(); + unsafe { + let c = kernelx::VirtualAlloc(null, SIZE, MEM_RESERVE | MEM_64K_PAGES, PAGE_READWRITE) as usize; + assert_ne!(c, 0, "the CPU view"); + let g = kernelx::VirtualAlloc(null, SIZE, MEM_RESERVE | MEM_64K_PAGES, PAGE_NOACCESS | PAGE_GRAPHICS_NOACCESS) as usize; + assert_ne!(g, 0, "the GPU view"); + + // G: in the view windows, from a window's start, all of it + let k = u.window_of(g).expect("the GPU view is in a window"); + assert!(u.is_view_window(k), "window {k} is no view window"); + assert_eq!(g, u.window(k).0); + assert!(u.is_view(g + SIZE - 1) && u.is_title_address(g) && u.is_title_address(g + SIZE - 1)); + assert!(!u.contains(g) && !u.is_sparse(g), "the CPU cannot touch a GPU view"); + for x in [0, 0x1234_5678, 5 << 30, SIZE - 0x1_0000] { + assert_eq!(mirrors::source(g + x), Some(c + x), "G + {x:#x}"); + } + + // C: not in the windows (never sparse video memory), plain write-watched memory the CPU writes + assert!(!aperture.contains(&c) && !aperture.contains(&(c + SIZE - 1)), "the CPU view {c:#x} is in the aperture {aperture:x?}"); + assert!(u.window_of(c).is_none() && !u.contains(c) && !u.is_title_address(c)); + assert!(kernelx::in_graphics_reservation(c)); + let page = kernelx::VirtualAlloc(c as *const c_void, 0x1_0000, MEM_COMMIT, PAGE_READWRITE) as usize; + assert_eq!(page, c); + std::ptr::write_volatile((c + 8) as *mut u64, 0x5843_4C00_0000_0016); + + // the title commits at G and decommits it again: plain pages, nothing breaks, the pair stays + assert_ne!(kernelx::VirtualAlloc((g + 0x2_0000) as *const c_void, 0x1_0000, MEM_COMMIT, PAGE_READWRITE), std::ptr::null_mut()); + assert_eq!(kernelx::VirtualFree((g + 0x2_0000) as *mut c_void, 0x1_0000, MEM_DECOMMIT), 1); + assert_eq!(mirrors::source(g + 0x2_0000), Some(c + 0x2_0000)); + // a release names the reservation's start, as Windows wants it + assert_eq!(kernelx::VirtualFree((g + 0x1_0000) as *mut c_void, 0, MEM_RELEASE), 0); + + // released: unpaired, and its range is free for the next GPU view + assert_eq!(kernelx::VirtualFree(g as *mut c_void, 0, MEM_RELEASE), 1); + assert_eq!(mirrors::source(g), None); + assert!(!u.is_title_address(g) && u.view_reservation(g).is_none()); + let again = kernelx::VirtualAlloc(null, SIZE, MEM_RESERVE | MEM_64K_PAGES, PAGE_NOACCESS | PAGE_GRAPHICS_NOACCESS) as usize; + assert_eq!(again, g, "the view windows' range came back whole"); + assert_eq!(mirrors::source(again + 0x10_0000), Some(c + 0x10_0000)); + assert_eq!(std::ptr::read_volatile((c + 8) as *const u64), 0x5843_4C00_0000_0016); + + // the CPU view goes, and the GPU view no longer names it + assert_eq!(kernelx::VirtualFree(c as *mut c_void, 0, MEM_RELEASE), 1); + assert_eq!(mirrors::source(again), None); + assert!(!kernelx::in_graphics_reservation(c)); + assert_eq!(kernelx::VirtualFree(again as *mut c_void, 0, MEM_RELEASE), 1); + assert!(u.view_reservation(again).is_none()); + } +} diff --git a/crates/xcl/tests/predication_e2e.rs b/crates/xcl/tests/predication_e2e.rs index 95b84430d8..776091a773 100644 --- a/crates/xcl/tests/predication_e2e.rs +++ b/crates/xcl/tests/predication_e2e.rs @@ -99,6 +99,60 @@ unsafe fn wait_fence(queue: &ID3D12CommandQueue, fence: &ID3D12Fence, value: &mu } } +/// Whether the host runs a copy that `SetPredication` should skip (D3DMetal 3.0 does: it skips +/// predicated draws, dispatches and ExecuteIndirect, not copies). A 4-byte copy under +/// EQUAL_ZERO on eight zero bytes, and the same copy unpredicated, into a readback buffer. +unsafe fn host_runs_predicated_copies(raw_dev: *mut c_void) -> bool { + let dev = ID3D12Device::from_raw_borrowed(&raw_dev).expect("backend device"); + // predicate (bytes 0..8) and copy source (bytes 8..12); GENERIC_READ includes PREDICATION + let upload = buffer( + dev, + 256, + D3D12_HEAP_TYPE_UPLOAD, + D3D12_RESOURCE_STATE_GENERIC_READ, + ); + let readback = buffer( + dev, + 256, + D3D12_HEAP_TYPE_READBACK, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let canary = 0x5843_4C50u32; + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).unwrap(); + (p as *mut u64).write(0); + (p as *mut u32).add(2).write(canary); + upload.Unmap(0, None); + + let queue: ID3D12CommandQueue = dev + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .expect("probe CreateCommandQueue"); + let alloc: ID3D12CommandAllocator = dev + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .expect("probe CreateCommandAllocator"); + let list: ID3D12GraphicsCommandList = dev + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None) + .expect("probe CreateCommandList"); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + list.SetPredication(&upload, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); + list.CopyBufferRegion(&readback, 0, &upload, 8, 4); + list.SetPredication(None, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); + list.CopyBufferRegion(&readback, 4, &upload, 8, 4); + list.Close().expect("probe Close"); + let cl: ID3D12CommandList = list.cast().unwrap(); + queue.ExecuteCommandLists(&[Some(cl)]); + wait_fence(&queue, &fence, &mut 0); + + readback.Map(0, None, Some(&mut p)).expect("Map probe readback"); + let got = std::slice::from_raw_parts(p as *const u32, 2).to_vec(); + readback.Unmap(0, None); + assert_eq!(got[1], canary, "the unpredicated probe copy must run"); + got[0] == canary +} + struct ReadbackCtx<'a> { queue: &'a ID3D12CommandQueue, alloc: &'a ID3D12CommandAllocator, @@ -179,6 +233,11 @@ fn set_predication_buffer_state_and_kickoff() { runner::skip_test("no GPU UMA"); return; } + if unsafe { host_runs_predicated_copies(real::device_raw()) } { + println!("the host runs predicated copies – skipping"); + runner::skip_test("host ignores SetPredication for copies"); + return; + } let raw_dev = real::device_raw(); let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw_dev) } diff --git a/crates/xcl/tests/texture_states.rs b/crates/xcl/tests/texture_states.rs index 420141f282..583b6ab734 100644 --- a/crates/xcl/tests/texture_states.rs +++ b/crates/xcl/tests/texture_states.rs @@ -1,14 +1,16 @@ -//! Uploads into a texture whose subresources are in different states (#104): the barriers -//! `gpu::texture::upload_batch` records start from each subresource's own state and return to -//! it, checked by the D3D12 debug layer's state tracking. Its own process: the debug layer has -//! to be on before the first device exists. +//! Uploads into a texture whose subresources are in different states (#104): the barriers the +//! uploads of title textures record start from each subresource's own state and return to it, for +//! all of a texture and for parts of it, checked by the D3D12 debug layer's state tracking. Its own +//! process: the debug layer has to be on before the first device exists. use windows::core::Interface; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; -use xcl::gpu::texture::{self, Subresource}; +use xcl::gpu::texture; +use xcl::hle::d3d12x::title_textures; +use xcl::hle::xg; const SRV: D3D12_RESOURCE_STATES = texture::SHADER_READ; @@ -79,11 +81,26 @@ fn uploads_start_from_each_subresources_state() { let mut r: Option = None; dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut r).unwrap(); let r = r.unwrap(); - let subs = |v: u8| -> Vec { (0..mips as usize).map(|m| Subresource { rows: 64 >> m, row_bytes: (64 >> m) * 4, depth: 1, data: vec![v; (64 >> m) * (64 >> m) * 4] }).collect() }; + // the title's description of it (4KB_S) and its memory + let mut desc = [0u8; 0x38]; + desc[0..4].copy_from_slice(&3u32.to_le_bytes()); + desc[0x10..0x18].copy_from_slice(&64u64.to_le_bytes()); + desc[0x18..0x1C].copy_from_slice(&64u32.to_le_bytes()); + desc[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + desc[0x1E..0x20].copy_from_slice(&mips.to_le_bytes()); + desc[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); + desc[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + desc[0x2C..0x30].copy_from_slice(&0x105u32.to_le_bytes()); + let tex = xg::Texture::new(&desc).unwrap(); + let size = tex.size() as usize; + let chain = &tex.texels().unwrap().chain; // made in COPY_DEST, left in the shader-resource states - let up = |states: Vec, v: u8| texture::upload_batch(&dev, &queue, &[(r.clone(), subs(v), states)]).unwrap(); - assert!(up(vec![D3D12_RESOURCE_STATE_COPY_DEST], 1).is_empty()); + let up = |states: Vec, v: u8| title_textures::upload_and_wait(&dev, &queue, &r, &desc, &vec![v; size], states, None).unwrap(); + // a part of the top level (the blocks of its last rows) alone + let top = chain.level_bytes(0); + let part = |states: Vec, v: u8| title_textures::upload_and_wait(&dev, &queue, &r, &desc, &vec![v; size], states, Some(vec![(top.end - 4096, top.end)])).unwrap(); + up(vec![D3D12_RESOURCE_STATE_COPY_DEST], 1); let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); list.ResourceBarrier(&[transition(&r, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST, SRV)]); @@ -97,15 +114,20 @@ fn uploads_start_from_each_subresources_state() { // each subresource's state: no error, and it is left in it let mut states = vec![SRV; mips as usize]; states[1] = D3D12_RESOURCE_STATE_COPY_SOURCE; - assert!(up(states.clone(), 2).is_empty()); + up(states.clone(), 2); let right = errors(&q); println!("per-subresource states: {} debug-layer errors", right.len()); assert!(right.is_empty(), "uploads with each subresource's state: {right:?}"); - assert!(up(states, 3).is_empty()); + up(states.clone(), 3); assert!(errors(&q).is_empty(), "the upload did not leave the subresources in their states"); + // part of the top level: that subresource's state alone (mip 1 is in another one) + part(states.clone(), 4); + part(vec![SRV], 5); + let of_part = errors(&q); + assert!(of_part.is_empty(), "an upload of a part of one subresource: {of_part:?}"); // one state for all of them, as uploads did before: mip 1 is not in it - assert!(up(vec![SRV], 4).is_empty()); + up(vec![SRV], 6); let wrong = errors(&q); println!("one state for all: {} debug-layer errors, first: {:?}", wrong.len(), wrong.first()); assert!(!wrong.is_empty(), "the debug layer did not see a transition from the wrong state – the check above proves nothing"); diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index 581a32b3c2..9a01a70742 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -52,11 +52,12 @@ SGPRs of both halves and the tests fail if they ever differ. ### Synchronisation -* **One console wave per group** (≤ 64 threads: kernel mode, most compute, ES+GS): - `GroupMemoryBarrierWithGroupSync` between writing and reading the slot. All hardware - waves of the group are the two halves of the same console wave, which execute the same - sequence of exchanges, so every barrier is reached by both. Portable (no forward-progress - assumption) and cheap. +* **One console wave per group** (≤ 64 threads), now only in kernel mode (the tests), with + `XCL_WAVE64_SPIN=0` in the HLSL path and in the direct translator's ES phase with + `XCL_SAFE_BARRIER=0`: `GroupMemoryBarrierWithGroupSync` between writing and reading the + slot. All hardware waves of the group are the two halves of the same console wave, which + execute the same sequence of exchanges, so every barrier is reached by both. Portable (no + forward-progress assumption) and cheap, but such barriers hung NVIDIA GPUs (#1727). * **Several console waves per group** (mesh: 128 threads, compute > 64 threads): a group barrier would also wait for the *other* console waves, whose control flow may differ (wave index, per-wave data). Each pair instead meets through groupshared arrival counters: @@ -71,8 +72,10 @@ SGPRs of both halves and the tests fail if they ever differ. counter failed unless that partner arrived first. Both halves then stop before later instructions can consume half-local exchange values. This relies on co-resident waves of one group making progress, which holds on GPUs (all waves of a group - are resident on one SM / CU) but not necessarily on WARP. `XCL_WAVE64_SPIN=1` forces this - variant everywhere (the test suite passes with it too). + are resident on one SM / CU) but not necessarily on WARP. Both translators use this variant + by default for one console wave per group too; `XCL_WAVE64_SPIN=0` forces the group barrier + for groups of one console wave in the HLSL path only (the direct translator always spins for + compute and mesh). A console wave whose upper half does not exist (group of 32 or 96 threads) exchanges with nobody: the missing lanes count as inactive (ballot bits 0), exactly as on the console. The diff --git a/scripts/precompile-shaders.ps1 b/scripts/precompile-shaders.ps1 new file mode 100644 index 0000000000..c7ea5a7ac1 --- /dev/null +++ b/scripts/precompile-shaders.ps1 @@ -0,0 +1,94 @@ +# Fill XCL's DXIL cache from a readable RPF9 shader package without launching a title. +# +# .\scripts\precompile-shaders.ps1 -Package 'D:\data\shaders.rpf' +# .\scripts\precompile-shaders.ps1 -Package 'D:\data\shaders.rpf' -Pipelines +# +# The package is read only. Cached DXIL goes to XCL_DXIL_CACHE when -Cache is supplied, +# otherwise to XCL's default (%LOCALAPPDATA%\xcl\dxil). -Pipelines also asks the GPU +# driver to warm its own compute-pipeline cache; it does not execute shader code. +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)][string]$Package, + [string]$Xcl = (Join-Path $PSScriptRoot '..\target\release\xcl.exe'), + [ValidateSet('all', 'cs', 'vs', 'ps', 'ms')][string]$Only = 'cs', + [ValidateRange(1, 32)][int]$MemoryWindows = 4, + [ValidateSet('auto', 'on', 'off')][string]$SplitWave64 = 'auto', + [ValidateRange(0, [int]::MaxValue)][int]$Limit = 0, + [ValidateRange(0, 256)][int]$DxcThreads = 0, + [ValidateRange(0, 256)][int]$PipelineThreads = 0, + [string]$Cache, + [switch]$Pipelines, + [switch]$NoBuild, + [switch]$PlanOnly +) +$ErrorActionPreference = 'Stop' + +$packagePath = (Resolve-Path -LiteralPath $Package).Path +if (-not (Test-Path -LiteralPath $packagePath -PathType Leaf)) { + throw "shader package is not a file: $packagePath" +} + +# Fail early with a useful error instead of asking XCL to scan an unrelated or protected file. +$stream = [System.IO.File]::OpenRead($packagePath) +try { + $magic = New-Object byte[] 4 + if ($stream.Read($magic, 0, 4) -ne 4 -or [System.Text.Encoding]::ASCII.GetString($magic) -ne '9FPR') { + throw "shader package is not a readable RPF9 archive: $packagePath" + } +} finally { + $stream.Dispose() +} + +$repoRoot = Split-Path $PSScriptRoot -Parent +$xclPath = [System.IO.Path]::GetFullPath($Xcl) +$arguments = @('shaders', $packagePath, '--precompile', '--windows', "$MemoryWindows") +if ($Only -ne 'all') { $arguments += @('--only', $Only) } +if ($SplitWave64 -eq 'on') { $arguments += @('--split', '1') } +if ($SplitWave64 -eq 'off') { $arguments += @('--split', '0') } +if ($Limit -gt 0) { $arguments += @('--limit', "$Limit") } +if ($Pipelines) { + if ($Only -notin @('all', 'cs')) { + throw '-Pipelines is available only with -Only cs or -Only all' + } + $arguments += '--pipelines' +} + +$environment = @{} +if ($Cache) { $environment.XCL_DXIL_CACHE = [System.IO.Path]::GetFullPath($Cache) } +if ($DxcThreads -gt 0) { $environment.XCL_DXC_THREADS = "$DxcThreads" } +if ($PipelineThreads -gt 0) { $environment.XCL_PIPELINE_THREADS = "$PipelineThreads" } + +Write-Host "Package: $packagePath" +Write-Host "DXIL cache: $(if ($Cache) { $environment.XCL_DXIL_CACHE } else { '%LOCALAPPDATA%\xcl\dxil' })" +Write-Host "Command: `"$xclPath`" $($arguments -join ' ')" +foreach ($entry in $environment.GetEnumerator() | Sort-Object Key) { + Write-Host "Environment: $($entry.Key)=$($entry.Value)" +} +if ($PlanOnly) { return } + +if (-not (Test-Path -LiteralPath $xclPath -PathType Leaf)) { + if ($NoBuild) { throw "no $xclPath - omit -NoBuild to build it" } + & cargo build --release -p xcl --manifest-path (Join-Path $repoRoot 'Cargo.toml') + if ($LASTEXITCODE -ne 0) { throw "cargo build failed with exit code $LASTEXITCODE" } +} + +$saved = @{} +try { + foreach ($entry in $environment.GetEnumerator()) { + $saved[$entry.Key] = @{ + Present = Test-Path -LiteralPath "Env:$($entry.Key)" + Value = [System.Environment]::GetEnvironmentVariable($entry.Key, 'Process') + } + [System.Environment]::SetEnvironmentVariable($entry.Key, $entry.Value, 'Process') + } + & $xclPath @arguments + if ($LASTEXITCODE -ne 0) { throw "shader precompile failed with exit code $LASTEXITCODE" } +} finally { + foreach ($entry in $saved.GetEnumerator()) { + if ($entry.Value.Present) { + [System.Environment]::SetEnvironmentVariable($entry.Key, $entry.Value.Value, 'Process') + } else { + Remove-Item -LiteralPath "Env:$($entry.Key)" -ErrorAction SilentlyContinue + } + } +}