From 2e2d9320ae0d72e2e635eebfacb6a8913c0107a9 Mon Sep 17 00:00:00 2001 From: nathan Date: Mon, 30 Nov 2026 11:56:31 +0100 Subject: [PATCH 1/2] D3D12.X: XboxBvhBuilder builds give their destinations video memory With XCL_SPARSE_LAZY=1 a tile the title commits has no video memory until the CPU's first bytes go up to it, or a placed buffer or a copy names it. XboxBvhBuilder.dll writes its acceleration structures with compute programs through the sparse windows, which none of those see: in a retail title the destination tiles of its builds and of every compaction copy had none, so the structures read as zeros and rays hit nothing. With the switch, the builder's batched and single build exports and its copy export are hooked when the title resolves them. Each build asks the builder's own GetRaytracingAccelerationStructurePrebuildInfo for the most it writes (XCL's prebuild_size underestimates some top levels) and gives that range to sparse::will_write, which maps it before the list runs; a clone or compacted copy writes as much as its source's build or the copy that made it, and a destination whose new size is unknown forgets its old one. A build's postbuild infos get the bytes of their type at their own DestBuffer, which can be on a tile of its own. The prebuild query is made before the size map's lock is taken. Without XCL_SPARSE_LAZY=1 nothing is hooked. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/bvh_builder.rs | 291 +++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/sparse.rs | 23 +- crates/xcl/src/resolver.rs | 2 +- 4 files changed, 315 insertions(+), 2 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/bvh_builder.rs diff --git a/crates/xcl/src/hle/d3d12x/bvh_builder.rs b/crates/xcl/src/hle/d3d12x/bvh_builder.rs new file mode 100644 index 0000000000..d0a233682e --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/bvh_builder.rs @@ -0,0 +1,291 @@ +//! XboxBvhBuilder.dll's exports that build and copy acceleration structures, when the title +//! resolves them with `XCL_SPARSE_LAZY=1`: the ranges each call writes on the GPU are given +//! video memory (`sparse::will_write`) before the builder records its passes. +//! +//! With the switch, a tile the title commits has no video memory until the CPU's first bytes go +//! up to it or a placed buffer or a copy names it. The builder writes its structures with +//! compute programs through the sparse windows, which none of those see: in a retail title all +//! of a build's destination tiles and every compaction copy's had none, so what the builder +//! wrote went nowhere and the structures read as zeros (rays found nothing). + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::modules::MappedModule; +use crate::pe::{ExportTarget, ImportName}; + +const BATCHED: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z"; +const SINGLE: &str = "?BuildRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@IPEBUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC@@@Z"; +const COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z"; +const PREBUILD: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z"; + +/// the builder's own entry points (0: not resolved by the title yet) +static F_BATCHED: AtomicUsize = AtomicUsize::new(0); +static F_SINGLE: AtomicUsize = AtomicUsize::new(0); +static F_COPY: AtomicUsize = AtomicUsize::new(0); +/// its `GetRaytracingAccelerationStructurePrebuildInfo`, found in the module when a hook is made +static F_PREBUILD: AtomicUsize = AtomicUsize::new(0); + +type PrebuildFn = unsafe extern "system-unwind" fn( + *mut c_void, + *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS, + *const c_void, + *mut D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, +); + +/// destination -> the bytes its build may write: what a copy of it writes +static SIZES: Mutex>> = Mutex::new(None); + +/// One element of `BuildRaytracingAccelerationStructureBatched2X`'s array: the build's +/// description, then 32 bytes of the builder's (its postbuild infos and two words). +#[repr(C)] +#[derive(Clone, Copy)] +struct BatchedDesc { + build: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, + postbuild_count: u32, + _padding: u32, + postbuild: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC, + _tail: [u64; 2], +} + +/// The address the title gets for an export of `module` it resolves (`original`): one of +/// XboxBvhBuilder.dll's build and copy exports goes through its hook here, with +/// `XCL_SPARSE_LAZY=1` only. +pub(crate) fn intercept(module: &MappedModule, what: &ImportName, rva: u32, original: usize) -> usize { + if !module.name.eq_ignore_ascii_case("xboxbvhbuilder.dll") || !super::sparse::lazy_asked() { + return original; + } + let name = match what { + ImportName::Name { name, .. } => Some(name.as_str()), + ImportName::Ordinal(_) => module.exports.by_name.iter().find_map(|(n, t)| matches!(t, ExportTarget::Rva(v) if *v == rva).then_some(n.as_str())), + }; + let Some((slot, hook)) = hook_for(name.unwrap_or("")) else { return original }; + if let Some(ExportTarget::Rva(p)) = module.exports.by_name.get(PREBUILD) { + F_PREBUILD.store(module.base + *p as usize, Ordering::Release); + } + match slot.compare_exchange(0, original, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => { + crate::xlog_info!("D3D12.X: XboxBvhBuilder's {} gives the ranges it writes video memory (XCL_SPARSE_LAZY)", name.unwrap_or("?").split('@').next().unwrap_or("?").trim_start_matches('?')); + hook + } + Err(e) if e == original => hook, + Err(_) => original, + } +} + +/// the slot and hook of one of the exports hooked here +fn hook_for(name: &str) -> Option<(&'static AtomicUsize, usize)> { + match name { + BATCHED => Some((&F_BATCHED, batched as usize)), + SINGLE => Some((&F_SINGLE, single as usize)), + COPY => Some((&F_COPY, copy as usize)), + _ => None, + } +} + +/// The builder's own `prebuild` answer for build `b`'s inputs (asked without a stream). +unsafe fn prebuild_info(prebuild: PrebuildFn, this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) -> D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO { + let mut info = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default(); + prebuild(this, &b.Inputs, std::ptr::null(), &mut info); + info +} + +/// What build `b` writes on the GPU, `info` being the builder's prebuild answer for it: its +/// destination, for the most the builder writes there (remembered in `sizes` for a copy of it; +/// with no size given, the destination's old one is forgotten). +fn build_writes(b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, info: &D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, sizes: &mut HashMap) -> Option<(u64, u64)> { + let dest = b.DestAccelerationStructureData; + if dest == 0 { + return None; + } + if info.ResultDataMaxSizeInBytes == 0 { + sizes.remove(&dest); + return None; + } + sizes.insert(dest, info.ResultDataMaxSizeInBytes); + Some((dest, info.ResultDataMaxSizeInBytes)) +} + +/// What a copy of `source` to `dest` writes: as much as `source`'s build (or the copy that made +/// it) could write, a clone or a compacted copy being no larger; that size becomes `dest`'s, for +/// a copy of the copy. Other modes, and sources of unknown size: None, and `dest`'s old size is +/// forgotten. +fn copy_writes(dest: u64, source: u64, mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE, sizes: &mut HashMap) -> Option<(u64, u64)> { + if dest == 0 { + return None; + } + let same_size = mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE || mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT; + match sizes.get(&source).copied().filter(|_| same_size) { + Some(n) => { + sizes.insert(dest, n); + Some((dest, n)) + } + None => { + sizes.remove(&dest); + None + } + } +} + +/// What a build's postbuild infos `posts` write on the GPU: each one's `DestBuffer`, for the +/// bytes of its info type (an unknown type: nothing). +pub(super) fn postbuild_writes(posts: &[D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC]) -> impl Iterator + '_ { + posts.iter().filter_map(|p| { + let n = match p.InfoType { + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE => std::mem::size_of::(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TOOLS_VISUALIZATION => std::mem::size_of::(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION => std::mem::size_of::(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE => std::mem::size_of::(), + _ => return None, + }; + (p.DestBuffer != 0).then_some((p.DestBuffer, n as u64)) + }) +} + +/// The GPU writes `[va, va + len)`: its tiles get video memory before the list runs. +fn give(va: u64, len: u64) { + super::sparse::will_write(va as usize, len as usize); +} + +unsafe fn give_build(this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) { + let pf = F_PREBUILD.load(Ordering::Acquire); + if pf == 0 { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: XboxBvhBuilder exports no prebuild-info query: its builds get no video memory where they write")); + return; + } + if b.DestAccelerationStructureData == 0 { + return; + } + // asked before the lock: other lists' builds do not wait for this one's query + let info = prebuild_info(std::mem::transmute::(pf), this, b); + let writes = build_writes(b, &info, SIZES.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new)); + if let Some((va, len)) = writes { + give(va, len); + } +} + +/// a build's `count` postbuild infos at `posts` give what they write video memory +unsafe fn give_postbuild(count: u32, posts: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC) { + if count > 0 && crate::gpu::shader::readable(posts as usize, count as usize * std::mem::size_of::()) { + for (va, len) in postbuild_writes(std::slice::from_raw_parts(posts, count as usize)) { + give(va, len); + } + } +} + +unsafe extern "system-unwind" fn batched(this: *mut c_void, list: *mut c_void, count: u32, descs: *const BatchedDesc) { + if count > 0 && crate::gpu::shader::readable(descs as usize, count as usize * std::mem::size_of::()) { + for d in std::slice::from_raw_parts(descs, count as usize) { + give_build(this, &d.build); + give_postbuild(d.postbuild_count, d.postbuild); + } + } + let f: unsafe extern "system-unwind" fn(*mut c_void, *mut c_void, u32, *const BatchedDesc) = std::mem::transmute(F_BATCHED.load(Ordering::Acquire)); + f(this, list, count, descs) +} + +unsafe extern "system-unwind" fn single(this: *mut c_void, list: *mut c_void, desc: *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, pc: u32, posts: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC) { + if crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + give_build(this, &*desc); + } + give_postbuild(pc, posts); + let f: unsafe extern "system-unwind" fn(*mut c_void, *mut c_void, *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, u32, *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC) = std::mem::transmute(F_SINGLE.load(Ordering::Acquire)); + f(this, list, desc, pc, posts) +} + +unsafe extern "system-unwind" fn copy(this: *mut c_void, list: *mut c_void, dest: u64, source: u64, mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE) { + let writes = copy_writes(dest, source, mode, SIZES.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new)); + if let Some((va, len)) = writes { + give(va, len); + } + let f: unsafe extern "system-unwind" fn(*mut c_void, *mut c_void, u64, u64, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE) = std::mem::transmute(F_COPY.load(Ordering::Acquire)); + f(this, list, dest, source, mode) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// a builder's prebuild query: 0x3000 result bytes, 0x1800 scratch bytes for any input + unsafe extern "system-unwind" fn fake_prebuild( + _this: *mut c_void, + _inputs: *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS, + stream: *const c_void, + out: *mut D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, + ) { + assert!(stream.is_null(), "asked without a stream"); + *out = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO { ResultDataMaxSizeInBytes: 0x3000, ScratchDataSizeInBytes: 0x1800, UpdateScratchDataSizeInBytes: 0 }; + } + + /// A build writes its destination for the size the builder's own query gives, and that size + /// is what a compacted or cloned copy of it writes; other copy modes, unknown sources and + /// builds without a destination give nothing. + #[test] + fn a_build_and_its_copies_write_the_builders_own_result_size() { + let mut sizes = HashMap::new(); + let mut b = D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC { DestAccelerationStructureData: 0x10_4000_0000, ScratchAccelerationStructureData: 0x11_7051_0000, ..Default::default() }; + let info = unsafe { prebuild_info(fake_prebuild, std::ptr::null_mut(), &b) }; + assert_eq!(build_writes(&b, &info, &mut sizes), Some((0x10_4000_0000, 0x3000))); + b.DestAccelerationStructureData = 0; + assert_eq!(build_writes(&b, &info, &mut sizes), None, "no destination"); + assert_eq!(sizes.len(), 1); + assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), Some((0x10_5000_0000, 0x3000))); + assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, &mut sizes), Some((0x10_5000_0000, 0x3000))); + assert_eq!(copy_writes(0x10_6000_0000, 0x10_5000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, &mut sizes), Some((0x10_6000_0000, 0x3000)), "a copy of a copy writes its source's size"); + assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_SERIALIZE, &mut sizes), None, "a serialized copy has another size"); + assert!(!sizes.contains_key(&0x10_5000_0000), "and its destination's old size is forgotten"); + assert_eq!(copy_writes(0x10_6000_0000, 0x10_7000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), None, "a source whose build was not seen"); + assert!(!sizes.contains_key(&0x10_6000_0000), "and its destination's old size is forgotten"); + assert_eq!(copy_writes(0, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), None); + } + + /// A destination built smaller before takes the size of what is copied over it, so a copy of + /// it writes all of that; a build whose size the builder does not give forgets the old one. + #[test] + fn a_reused_destination_never_keeps_a_stale_size() { + let mut sizes = HashMap::new(); + let small = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO { ResultDataMaxSizeInBytes: 0x1000, ..Default::default() }; + let large = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO { ResultDataMaxSizeInBytes: 0x3_0000, ..Default::default() }; + let (a, b, c) = (0x10_4000_0000, 0x10_5000_0000, 0x10_6000_0000); + let built = |dest| D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC { DestAccelerationStructureData: dest, ..Default::default() }; + assert_eq!(build_writes(&built(b), &small, &mut sizes), Some((b, 0x1000))); + assert_eq!(build_writes(&built(a), &large, &mut sizes), Some((a, 0x3_0000))); + assert_eq!(copy_writes(b, a, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, &mut sizes), Some((b, 0x3_0000))); + assert_eq!(copy_writes(c, b, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), Some((c, 0x3_0000)), "not the old build's 0x1000"); + assert_eq!(build_writes(&built(c), &D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default(), &mut sizes), None); + assert!(!sizes.contains_key(&c), "a build of unknown size forgets the old one"); + } + + /// Each postbuild info writes its own buffer, which may lie on a tile apart from the build's + /// destination, for its type's size; one without a buffer or of an unknown type writes nothing. + #[test] + fn postbuild_infos_write_their_own_buffers() { + let post = |va, t| D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC { DestBuffer: va, InfoType: t }; + let posts = [ + post(0x10_4002_0008, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE), + post(0x10_4003_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION), + post(0x10_4003_0010, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE), + post(0x10_4003_0018, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TOOLS_VISUALIZATION), + post(0, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE), + post(0x10_4004_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TYPE(7)), + ]; + assert_eq!(postbuild_writes(&posts).collect::>(), [(0x10_4002_0008, 8), (0x10_4003_0000, 16), (0x10_4003_0010, 8), (0x10_4003_0018, 8)]); + } + + /// Only the build and copy exports are hooked; the batched element is laid out as the + /// builder reads it. + #[test] + fn the_build_and_copy_exports_are_hooked() { + assert!(hook_for(BATCHED).is_some_and(|(s, _)| std::ptr::eq(s, &F_BATCHED))); + assert!(hook_for(SINGLE).is_some_and(|(s, _)| std::ptr::eq(s, &F_SINGLE))); + assert!(hook_for(COPY).is_some_and(|(s, _)| std::ptr::eq(s, &F_COPY))); + assert!(hook_for(PREBUILD).is_none(), "the query is called, not hooked"); + assert!(hook_for("?Rehydrate").is_none()); + assert_eq!(std::mem::size_of::(), std::mem::size_of::() + 32); + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 943bfec115..f766f64acb 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -14,6 +14,7 @@ pub use alloc_pool::AllocatorSubmitStats; mod barrier_groups; mod build_queue; pub mod bind; +pub(crate) mod bvh_builder; mod bvh_want; mod capture; pub mod console_heap; diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index cae13913f2..95eceb14f0 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -153,7 +153,7 @@ fn lazy_commits() -> bool { } /// `XCL_SPARSE_LAZY=1` was given -fn lazy_asked() -> bool { +pub(super) 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")) } @@ -11385,6 +11385,27 @@ mod tests { drop(lazy); } + /// A ray-tracing build's compacted-size result on a tile of its own, apart from the build's + /// destination, gets that tile's memory before the build writes its eight bytes there. + #[test] + fn a_postbuild_result_on_a_tile_of_its_own_gets_memory() { + let lazy = Lazy::on(true); + unsafe { + let Some((base, mut s, _queue)) = lazy_state(3) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") }; + s.commit_range(base, 3 * TILE); + let posts = [D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC { + DestBuffer: (base + 2 * TILE + 8) as u64, + InfoType: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE, + }]; + let asks: Vec<(usize, usize)> = super::super::bvh_builder::postbuild_writes(&posts).map(|(va, n)| (va as usize, n as usize)).collect(); + s.give_memory(&asks); + assert_ne!(s.mapped[&(base + 2 * TILE)].pool, LAZY, "the result's tile got memory"); + assert_eq!(s.mapped[&base].pool, LAZY, "the destination's is left to its build"); + assert_eq!(s.mapped[&(base + TILE)].pool, LAZY, "the tile between is left"); + } + 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] diff --git a/crates/xcl/src/resolver.rs b/crates/xcl/src/resolver.rs index 72dbacae7b..e833420d7d 100644 --- a/crates/xcl/src/resolver.rs +++ b/crates/xcl/src/resolver.rs @@ -181,7 +181,7 @@ fn resolve_export_of_mapped_inner( ImportName::Ordinal(o) => m.exports.by_ordinal.get(&(*o as u32))?, }; match t { - ExportTarget::Rva(r) => Some(m.base + *r as usize), + ExportTarget::Rva(r) => Some(crate::hle::d3d12x::bvh_builder::intercept(m, what, *r, m.base + *r as usize)), ExportTarget::Forwarder(f) => { if depth > 8 { return None; From 5abd576bc772444ad8d3a2365143fb6db6142831 Mon Sep 17 00:00:00 2001 From: nathan Date: Mon, 30 Nov 2026 12:09:21 +0100 Subject: [PATCH 2/2] D3D12.X: a ray-tracing build's scratch gets window tiles of its own The title maps physical pages over the scratch of XboxBvhBuilder's builds whose bytes XCL keeps at another address, so the scratch address stays reserved: no commit lists its tiles and no CPU view links them. With XCL_SPARSE_LAZY=1 the builder's scratch writes went nowhere in 256 of 256 builds checked in a retail title, and its passes read zeros back. sparse::will_write_unbacked asks, like will_write, for the next submit: the range's window tiles with no entry and no CPU view under them get video memory of their own, the pages the CPU has not committed holes (nothing goes up or comes back there). The builder hook asks it for the scratch range the builder's own prebuild query gives, and for its destinations and copies too (tiles already listed are left to will_write). A tile that already shows a CPU view not linked yet is not given a tile of its own: it is asked for as a mirror in the same submit, so the CPU's bytes there stay visible; a tile of its own that comes to show a CPU view later (a page mapped there) gives its tile up and is linked over it. When tiles of its own find no video memory the asks are kept and the submit returns RetryRequired, so a build never runs over scratch with nothing behind it. A PERFORM_UPDATE build's scratch is the UpdateScratchDataSizeInBytes of the ALLOW_UPDATE build (or copy) it updates, kept from that build's query; not known, the larger of the two scratch sizes the update's own query gives. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/bvh_builder.rs | 134 +++++++++--- crates/xcl/src/hle/d3d12x/sparse.rs | 247 ++++++++++++++++++++++- 2 files changed, 352 insertions(+), 29 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bvh_builder.rs b/crates/xcl/src/hle/d3d12x/bvh_builder.rs index d0a233682e..b2bd14d21f 100644 --- a/crates/xcl/src/hle/d3d12x/bvh_builder.rs +++ b/crates/xcl/src/hle/d3d12x/bvh_builder.rs @@ -7,6 +7,10 @@ //! compute programs through the sparse windows, which none of those see: in a retail title all //! of a build's destination tiles and every compaction copy's had none, so what the builder //! wrote went nowhere and the structures read as zeros (rays found nothing). +//! +//! A build's scratch needs more: the title maps physical pages there whose bytes XCL keeps at +//! another address, so the address stays reserved and no commit lists its tiles at all +//! (`sparse::will_write_unbacked` gives them tiles of their own). use std::collections::HashMap; use std::ffi::c_void; @@ -37,8 +41,18 @@ type PrebuildFn = unsafe extern "system-unwind" fn( *mut D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, ); -/// destination -> the bytes its build may write: what a copy of it writes -static SIZES: Mutex>> = Mutex::new(None); +/// destination -> what its build may write there and what an update of it needs +static SIZES: Mutex>> = Mutex::new(None); + +/// A structure the builder built (or copied) at a destination. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Built { + /// the bytes its build may write: what a copy of it writes + result: u64, + /// the scratch an update of it needs, from the query for the build that allowed updates + /// (a query made for the update itself may give none); 0: not known + update_scratch: u64, +} /// One element of `BuildRaytracingAccelerationStructureBatched2X`'s array: the build's /// description, then 32 bytes of the builder's (its postbuild infos and two words). @@ -95,34 +109,55 @@ unsafe fn prebuild_info(prebuild: PrebuildFn, this: *mut c_void, b: &D3D12_BUILD } /// What build `b` writes on the GPU, `info` being the builder's prebuild answer for it: its -/// destination, for the most the builder writes there (remembered in `sizes` for a copy of it; -/// with no size given, the destination's old one is forgotten). -fn build_writes(b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, info: &D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, sizes: &mut HashMap) -> Option<(u64, u64)> { +/// destination and its scratch, for the most the builder writes there (the destination's +/// remembered in `sizes` for a copy of it; with no size given, the destination's old one is +/// forgotten). An update (`PERFORM_UPDATE`) writes the scratch the structure it updates needs for +/// one (`UpdateScratchDataSizeInBytes` of the build that allowed it); not known, the larger of +/// the two scratch sizes `info` gives. +fn build_writes(b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, info: &D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, sizes: &mut HashMap) -> Vec<(u64, u64)> { let dest = b.DestAccelerationStructureData; if dest == 0 { - return None; + return Vec::new(); } + let flags = b.Inputs.Flags; + let (scratch, update_scratch) = if flags.contains(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE) { + // (an update in place has no source of its own: its destination is the structure updated) + let source = if b.SourceAccelerationStructureData != 0 { b.SourceAccelerationStructureData } else { dest }; + match sizes.get(&source).map(|s| s.update_scratch).filter(|&n| n != 0) { + Some(n) => (n, n), + None => (info.ScratchDataSizeInBytes.max(info.UpdateScratchDataSizeInBytes), info.UpdateScratchDataSizeInBytes), + } + } else if flags.contains(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE) { + (info.ScratchDataSizeInBytes, info.UpdateScratchDataSizeInBytes) + } else { + (info.ScratchDataSizeInBytes, 0) + }; + let mut out = Vec::new(); if info.ResultDataMaxSizeInBytes == 0 { sizes.remove(&dest); - return None; + } else { + sizes.insert(dest, Built { result: info.ResultDataMaxSizeInBytes, update_scratch }); + out.push((dest, info.ResultDataMaxSizeInBytes)); } - sizes.insert(dest, info.ResultDataMaxSizeInBytes); - Some((dest, info.ResultDataMaxSizeInBytes)) + if b.ScratchAccelerationStructureData != 0 && scratch != 0 { + out.push((b.ScratchAccelerationStructureData, scratch)); + } + out } /// What a copy of `source` to `dest` writes: as much as `source`'s build (or the copy that made /// it) could write, a clone or a compacted copy being no larger; that size becomes `dest`'s, for -/// a copy of the copy. Other modes, and sources of unknown size: None, and `dest`'s old size is -/// forgotten. -fn copy_writes(dest: u64, source: u64, mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE, sizes: &mut HashMap) -> Option<(u64, u64)> { +/// a copy of the copy (with what an update of it needs). Other modes, and sources of unknown +/// size: None, and `dest`'s old size is forgotten. +fn copy_writes(dest: u64, source: u64, mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE, sizes: &mut HashMap) -> Option<(u64, u64)> { if dest == 0 { return None; } let same_size = mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE || mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT; match sizes.get(&source).copied().filter(|_| same_size) { - Some(n) => { - sizes.insert(dest, n); - Some((dest, n)) + Some(s) => { + sizes.insert(dest, s); + Some((dest, s.result)) } None => { sizes.remove(&dest); @@ -146,9 +181,11 @@ pub(super) fn postbuild_writes(posts: &[D3D12_RAYTRACING_ACCELERATION_STRUCTURE_ }) } -/// The GPU writes `[va, va + len)`: its tiles get video memory before the list runs. +/// The GPU writes `[va, va + len)`: its tiles get video memory before the list runs, those +/// listed with none and those no commit listed. fn give(va: u64, len: u64) { super::sparse::will_write(va as usize, len as usize); + super::sparse::will_write_unbacked(va as usize, len as usize); } unsafe fn give_build(this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) { @@ -164,7 +201,7 @@ unsafe fn give_build(this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_ // asked before the lock: other lists' builds do not wait for this one's query let info = prebuild_info(std::mem::transmute::(pf), this, b); let writes = build_writes(b, &info, SIZES.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new)); - if let Some((va, len)) = writes { + for (va, len) in writes { give(va, len); } } @@ -222,17 +259,19 @@ mod tests { *out = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO { ResultDataMaxSizeInBytes: 0x3000, ScratchDataSizeInBytes: 0x1800, UpdateScratchDataSizeInBytes: 0 }; } - /// A build writes its destination for the size the builder's own query gives, and that size - /// is what a compacted or cloned copy of it writes; other copy modes, unknown sources and - /// builds without a destination give nothing. + /// A build writes its destination and its scratch for the sizes the builder's own query + /// gives, and the destination's is what a compacted or cloned copy of it writes; other copy + /// modes, unknown sources and builds without a destination give nothing. #[test] fn a_build_and_its_copies_write_the_builders_own_result_size() { let mut sizes = HashMap::new(); let mut b = D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC { DestAccelerationStructureData: 0x10_4000_0000, ScratchAccelerationStructureData: 0x11_7051_0000, ..Default::default() }; let info = unsafe { prebuild_info(fake_prebuild, std::ptr::null_mut(), &b) }; - assert_eq!(build_writes(&b, &info, &mut sizes), Some((0x10_4000_0000, 0x3000))); + assert_eq!(build_writes(&b, &info, &mut sizes), vec![(0x10_4000_0000, 0x3000), (0x11_7051_0000, 0x1800)]); + b.ScratchAccelerationStructureData = 0; + assert_eq!(build_writes(&b, &info, &mut sizes), vec![(0x10_4000_0000, 0x3000)], "no scratch"); b.DestAccelerationStructureData = 0; - assert_eq!(build_writes(&b, &info, &mut sizes), None, "no destination"); + assert_eq!(build_writes(&b, &info, &mut sizes), vec![], "no destination"); assert_eq!(sizes.len(), 1); assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), Some((0x10_5000_0000, 0x3000))); assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, &mut sizes), Some((0x10_5000_0000, 0x3000))); @@ -253,14 +292,59 @@ mod tests { let large = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO { ResultDataMaxSizeInBytes: 0x3_0000, ..Default::default() }; let (a, b, c) = (0x10_4000_0000, 0x10_5000_0000, 0x10_6000_0000); let built = |dest| D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC { DestAccelerationStructureData: dest, ..Default::default() }; - assert_eq!(build_writes(&built(b), &small, &mut sizes), Some((b, 0x1000))); - assert_eq!(build_writes(&built(a), &large, &mut sizes), Some((a, 0x3_0000))); + assert_eq!(build_writes(&built(b), &small, &mut sizes), vec![(b, 0x1000)]); + assert_eq!(build_writes(&built(a), &large, &mut sizes), vec![(a, 0x3_0000)]); assert_eq!(copy_writes(b, a, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, &mut sizes), Some((b, 0x3_0000))); assert_eq!(copy_writes(c, b, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), Some((c, 0x3_0000)), "not the old build's 0x1000"); - assert_eq!(build_writes(&built(c), &D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default(), &mut sizes), None); + assert_eq!(build_writes(&built(c), &D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default(), &mut sizes), vec![]); assert!(!sizes.contains_key(&c), "a build of unknown size forgets the old one"); } + /// An update writes the scratch the build that allowed it asked for an update, larger or + /// smaller than that build's own and whatever the query made for the update gives: across a + /// 64 KiB tile boundary, the larger one reaches the next tile and the smaller one does not. + /// Updates in place, of a copy, and of a structure whose build was not seen are covered too. + #[test] + fn an_update_writes_the_update_scratch_of_the_structure_it_updates() { + const TILE: u64 = 0x1_0000; + let mut sizes = HashMap::new(); + let scratch: u64 = 0x11_7051_0000 + TILE - 0x1000; + let tiles = |w: &[(u64, u64)]| w.iter().find(|r| r.0 == scratch).map(|&(a, n)| (a + n - 1) / TILE - a / TILE + 1); + let info = |result, scratch, update| D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO { ResultDataMaxSizeInBytes: result, ScratchDataSizeInBytes: scratch, UpdateScratchDataSizeInBytes: update }; + let build = |dest, source, flags| D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC { + DestAccelerationStructureData: dest, + SourceAccelerationStructureData: source, + ScratchAccelerationStructureData: scratch, + Inputs: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS { Flags: flags, ..Default::default() }, + }; + let allow = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE; + let update = allow | D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE; + let (a, b, c) = (0x10_4000_0000, 0x10_5000_0000, 0x10_6000_0000); + + // the update needs more than the build: it reaches the next tile + let w = build_writes(&build(a, 0, allow), &info(0x3000, 0x800, 0x2000), &mut sizes); + assert_eq!((w.clone(), tiles(&w)), (vec![(a, 0x3000), (scratch, 0x800)], Some(1))); + // (the query made for an update: no update scratch, and the first build's own scratch) + let w = build_writes(&build(b, a, update), &info(0x3000, 0x800, 0), &mut sizes); + assert_eq!((w.clone(), tiles(&w)), (vec![(b, 0x3000), (scratch, 0x2000)], Some(2)), "the update's own scratch"); + let w = build_writes(&build(b, 0, update), &info(0x3000, 0x800, 0), &mut sizes); + assert_eq!(w, vec![(b, 0x3000), (scratch, 0x2000)], "updated again in place, it still needs as much"); + + // the update needs less than the build: it leaves the next tile alone + let w = build_writes(&build(a, 0, allow), &info(0x3000, 0x2000, 0x800), &mut sizes); + assert_eq!(tiles(&w), Some(2)); + let w = build_writes(&build(a, 0, update), &info(0x3000, 0x2000, 0), &mut sizes); + assert_eq!((w.clone(), tiles(&w)), (vec![(a, 0x3000), (scratch, 0x800)], Some(1)), "not the build's 0x2000"); + + // a copy is updated as its source would be + assert_eq!(copy_writes(c, a, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), Some((c, 0x3000))); + assert_eq!(build_writes(&build(c, 0, update), &info(0x3000, 0x2000, 0), &mut sizes)[1], (scratch, 0x800)); + // a structure whose build allowed no update, or was not seen: the larger the query gives + build_writes(&build(a, 0, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS(0)), &info(0x3000, 0x800, 0x2000), &mut sizes); + assert_eq!(build_writes(&build(b, a, update), &info(0x3000, 0x800, 0x1800), &mut sizes)[1], (scratch, 0x1800)); + assert_eq!(build_writes(&build(b, 0x10_7000_0000, update), &info(0x3000, 0x800, 0), &mut sizes)[1], (scratch, 0x800)); + } + /// Each postbuild info writes its own buffer, which may lie on a tile apart from the build's /// destination, for its type's size; one without a buffer or of an unknown type writes nothing. #[test] diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 95eceb14f0..e88de79c98 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -2580,6 +2580,9 @@ struct State { /// 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, + /// window tiles given video memory of their own for a GPU write where nothing showed a CPU + /// view (`give_own_tiles`): one that comes to show one gives it up (`yield_own`) + own: FxHashSet, counts: MirrorCounts, diag: ViewDiag, /// `XCL_VIEW_POISON`: the tile the windows' tiles without video memory show (`poison_windows`) @@ -3353,6 +3356,7 @@ unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) - refused: FxHashSet::default(), no_memory: None, starved: Vec::new(), + own: FxHashSet::default(), counts: MirrorCounts::default(), diag: ViewDiag { keep: view_switches().keep, stats: view_switches().stats, ..Default::default() }, poison: None, @@ -3837,6 +3841,64 @@ impl State { self.to_zero.extend(reused); } + /// The title's lists about to be submitted write `ranges` on the GPU before anything reads + /// them where no commit was seen (`will_write_unbacked`): their window tiles with no entry and + /// no CPU view under them get video memory of their own, cleared at this submit; the pages + /// not committed on the CPU side are holes (nothing goes up or comes back there). A tile that + /// shows a CPU view not linked yet is asked for instead (`take_asks`, in this submit's + /// `map_mirrors`): with memory of its own it would hide what the CPU wrote there. Returned: + /// the tiles that found no video memory (`take_tile`), as ranges. + unsafe fn give_own_tiles(&mut self, ranges: &[(usize, usize)]) -> Vec<(usize, usize)> { + let mut unmet = Vec::new(); + for &(a, n) in ranges { + let end = a.saturating_add(n); + let mut t = a & !(TILE - 1); + while t < end { + if !self.mapped.contains_key(&t) && !self.mirror_src.contains_key(&t) && self.window_index(t).is_some() { + // (asked for as `map_mirror` asks: a page mapped there later reaches the tile, + // `remapped`) + MIRROR_ASKED.insert(t, ()); + if matches!(tile_shows(t), Under::Cpu(_)) { + self.asks.push(t); + } else { + self.ensure_mapped(t, TILE, |t| { + let holes = query_tile_holes(t); + (holes, !holes) + }); + if self.mapped.contains_key(&t) { + self.own.insert(t); + } else { + unmet.push((t, TILE)); + } + } + } + match t.checked_add(TILE) { + Some(next) => t = next, + None => break, + } + } + } + unmet + } + + /// Window tile `w`'s video memory of its own (`give_own_tiles`) is parked, to be taken back + /// when it is linked over the CPU view it now shows (`new_mirror`). False: it has none. + fn yield_own(&mut self, w: usize) -> bool { + if !self.own.remove(&w) || !self.mapped.get(&w).is_some_and(|e| e.src == 0) { + return false; + } + let e = self.mapped.remove(&w).expect("a tile of its own"); + while let Some(&piece) = self.to_zero.range((w, 0)..(w + TILE, 0)).next() { + self.to_zero.remove(&piece); + } + early_remove(&mut self.runs, w, w + TILE); + if e.pool != LAZY { + self.parked.insert(w, e.pool); + } + MAPPED_GEN.fetch_add(1, Ordering::Release); + true + } + /// tiles of `[a, a + n)` get video memory (mapped in their window); `initial_state` supplies /// the initial `(holes, untrusted protection)` masks for each newly mapped 64 KiB tile. Tiles /// over a CPU view (`mirror_src`) are left to `new_mirror`. @@ -6750,9 +6812,16 @@ impl State { 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 }; + // (a tile of its own, `give_own_tiles`, gives way to a CPU view it shows now) + let own = self.own.contains(&g); + let under = if (own || !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)), + Under::Cpu(c) => { + self.yield_own(g); + want.push((g, c)); + } + // (a tile of its own stays asked for: a page mapped there later reaches it) + Under::Nothing | Under::NoView if own => {} // (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 @@ -6834,8 +6903,9 @@ impl State { 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) { + // (a tile of the window's own is not a view's – but one given for a GPU write where + // nothing showed a CPU view gives way to one shown now) + if self.mapped.get(&g).is_some_and(|e| e.src == 0) && !(self.own.contains(&g) && matches!(tile_shows(g), Under::Cpu(_)) && self.yield_own(g)) { continue; } let now = tile_shows(g); @@ -7551,6 +7621,40 @@ pub(super) fn will_write(va: usize, len: usize) { WRITE_ASKING.store(true, Ordering::Release); } +/// `will_write_unbacked`'s ranges, taken by the next submit +static OWN_ASKS: Mutex> = Mutex::new(Vec::new()); +static OWN_ASKING: AtomicBool = AtomicBool::new(false); + +/// A list being recorded writes `[va, va + len)` on the GPU before anything reads it, where the +/// title may have mapped physical pages whose bytes XCL keeps at another address (a ray-tracing +/// build's scratch): that address stays reserved, so no commit gives its tiles an entry and no +/// CPU view links them. With `lazy_commits`, such tiles get video memory of their own at the next +/// submit, before the list's (`State::give_own_tiles`). Never waits for the state. +pub(super) fn will_write_unbacked(va: usize, len: usize) { + if len == 0 || !lazy_commits() { + return; + } + OWN_ASKS.lock().unwrap_or_else(|e| e.into_inner()).push((va, len)); + OWN_ASKING.store(true, Ordering::Release); +} + +/// The ranges asked in `asks` (`OWN_ASKS`, `asking` set when there are some) get tiles of their +/// own (`State::give_own_tiles`). False: some tiles found no video memory; they stay asked for, +/// and the submit is to be tried again (the GPU write must not go nowhere). +unsafe fn give_own_asks(s: &mut State, asks: &Mutex>, asking: &AtomicBool) -> bool { + if !asking.swap(false, Ordering::AcqRel) { + return true; + } + let taken = std::mem::take(&mut *asks.lock().unwrap_or_else(|e| e.into_inner())); + let unmet = s.give_own_tiles(&taken); + if unmet.is_empty() { + return true; + } + asks.lock().unwrap_or_else(|e| e.into_inner()).extend(unmet); + asking.store(true, Ordering::Release); + false +} + /// microseconds in `before_execute`, the wait for the state's lock with it static SUBMIT_US: AtomicU64 = AtomicU64::new(0); @@ -8127,6 +8231,13 @@ unsafe fn before_execute_locked( let asks = std::mem::take(&mut *WRITE_ASKS.lock().unwrap_or_else(|e| e.into_inner())); s.give_memory(&asks); } + if !give_own_asks(s, &OWN_ASKS, &OWN_ASKING) { + drop(held); + drop(g); + drop(observed); + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); + return PreparationOutcome::RetryRequired; + } 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) @@ -8762,6 +8873,7 @@ mod tests { refused: FxHashSet::default(), no_memory: None, starved: Vec::new(), + own: FxHashSet::default(), counts: MirrorCounts::default(), diag: ViewDiag::default(), poison: None, @@ -10262,6 +10374,7 @@ mod tests { refused: FxHashSet::default(), no_memory: None, starved: Vec::new(), + own: FxHashSet::default(), counts: MirrorCounts::default(), diag: ViewDiag::default(), poison: None, @@ -10680,6 +10793,7 @@ mod tests { refused: FxHashSet::default(), no_memory: None, starved: Vec::new(), + own: FxHashSet::default(), counts: MirrorCounts::default(), diag: ViewDiag::default(), poison: None, @@ -10813,6 +10927,7 @@ mod tests { refused: FxHashSet::default(), no_memory: None, starved: Vec::new(), + own: FxHashSet::default(), counts: MirrorCounts::default(), diag: ViewDiag::default(), poison: None, @@ -11406,6 +11521,64 @@ mod tests { drop(lazy); } + /// A GPU write where no commit gave the tiles an entry (a build's scratch over pages whose + /// bytes are kept elsewhere: reserved on the CPU side) gets tiles of its own, all pages holes, + /// reading zeros; a tile listed with no video memory is left to `give_memory`. + #[test] + fn an_unbacked_gpu_write_gets_tiles_of_its_own() { + use windows_sys::Win32::System::Memory::MEM_DECOMMIT; + + let lazy = Lazy::on(true); + unsafe { + let Some((base, mut s, _queue)) = lazy_state(3) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") }; + // tiles 0 and 1: reserved only (no commit seen); tile 2: committed, listed with none + assert_ne!(VirtualFree(base as *mut c_void, 2 * TILE, MEM_DECOMMIT), 0); + s.commit_range(base + 2 * TILE, TILE); + assert!(!s.mapped.contains_key(&base) && !s.mapped.contains_key(&(base + TILE))); + assert_eq!(s.mapped[&(base + 2 * TILE)].pool, LAZY); + assert!(s.give_own_tiles(&[(base + 0x100, 3 * TILE - 0x200)]).is_empty()); + for t in [base, base + TILE] { + let e = &s.mapped[&t]; + assert_ne!(e.pool, LAZY, "tile {:#x} got video memory", t - base); + assert_eq!(e.holes, 0xFFFF, "its CPU pages are all holes"); + } + assert_eq!(s.mapped[&(base + 2 * TILE)].pool, LAZY, "a listed tile is not given one here"); + assert!(window_bytes(&mut s, base, 2 * TILE).iter().all(|&b| b == 0), "the new tiles read zeros"); + } + drop(lazy); + } + + /// Tiles of their own that find no video memory hold the submit back (it is to be tried + /// again: the GPU write must not go nowhere) and stay asked for; the same ask tried again + /// once there is memory gives them their tiles, and the submit goes on. + #[test] + fn own_tiles_that_find_no_memory_hold_the_submit_back() { + use windows_sys::Win32::System::Memory::MEM_DECOMMIT; + + 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") }; + assert_ne!(VirtualFree(base as *mut c_void, 2 * TILE, MEM_DECOMMIT), 0); + let (asks, asking) = (Mutex::new(vec![(base + 0x100, TILE)]), AtomicBool::new(true)); + lazy.no_tiles(true); + assert!(!give_own_asks(&mut s, &asks, &asking), "no video memory: the submit is tried again"); + assert!(asking.load(Ordering::Acquire), "and the tiles stay asked for"); + assert_eq!(*asks.lock().unwrap(), [(base, TILE), (base + TILE, TILE)]); + assert!(!s.mapped.contains_key(&base) && !s.mapped.contains_key(&(base + TILE))); + assert!(!give_own_asks(&mut s, &asks, &asking), "still none: tried again"); + lazy.no_tiles(false); + assert!(give_own_asks(&mut s, &asks, &asking), "memory at the next try: the submit goes on"); + assert!(asks.lock().unwrap().is_empty() && !asking.load(Ordering::Acquire)); + for t in [base, base + TILE] { + assert_ne!(s.mapped[&t].pool, LAZY, "tile {:#x} got video memory", t - base); + } + assert!(give_own_asks(&mut s, &asks, &asking), "nothing asked: ready"); + s.before_execute_on(&queue, &[], PAGE); + assert!(window_bytes(&mut s, base, 2 * TILE).iter().all(|&b| b == 0), "the new tiles read zeros"); + } + 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] @@ -12390,6 +12563,72 @@ mod tests { } } + /// A GPU write asked tiles of their own for (a build's scratch) over GPU-view tiles that show + /// their CPU view but are not linked yet, their first ask in the same submit: the tiles are + /// linked over the CPU view, not given memory of their own, so what the CPU wrote there is + /// what the GPU reads, through that submit and after a later remap of one of them. + #[test] + fn a_scratch_write_never_hides_a_cpu_view_not_linked_yet() { + unsafe { + let Some(mut v) = Views::new(197) 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, c, buf) = (v.w, v.c, v.buf.clone()); + let page = fill_tile(h, 90); + v.commit(0, 2); + v.write(0, 2, 91); + // the first ask and a partial write over both tiles, taken by one submit (own tiles + // first, as `before_execute_locked` takes them) + v.ask(2); + assert!(v.s.give_own_tiles(&[(w + TILE / 2, TILE)]).is_empty()); + assert!(v.s.own.is_empty() && !v.s.mapped.contains_key(&w) && !v.s.mapped.contains_key(&(w + TILE)), "no tile of its own over a CPU view"); + v.submit(&[]); + for k in 0..2 { + assert_eq!(v.s.mapped[&(w + k * TILE)].src, c + k * TILE, "tile {k} shows its CPU tile"); + assert!(v.gpu_bytes(&buf, k * TILE, TILE) == v.cpu_tile(k), "tile {k}: the CPU bytes"); + } + assert!(v.s.own.is_empty()); + // a page mapped at the first: shown; the second keeps its CPU bytes + map_pages_at(w, &[[0, 0, 1]], h, 1); + v.take_remaps(2); + v.submit(&[]); + assert!(v.gpu_bytes(&buf, 0, TILE) == page, "the remapped tile shows the page"); + assert!(v.gpu_bytes(&buf, TILE, TILE) == v.cpu_tile(1), "the other still its CPU bytes"); + assert_eq!(crate::hle::kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), 1, pages.as_mut_ptr()), 1); + v.take_remaps(2); + v.submit(&[]); + } + } + + /// A GPU-view tile that showed nothing when a GPU write gave it memory of its own gives that + /// up once a page is mapped there: it shows the page from the next submit on. + #[test] + fn an_own_tile_gives_way_to_a_page_mapped_there_later() { + unsafe { + let Some(mut v) = Views::new(199) 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 page = fill_tile(h, 92); + // nothing at view page 0: the write gets a tile of its own + map_pages_at(w, &[[2, 0, 1]], h, 1); + assert!(v.s.give_own_tiles(&[(w + 0x100, 0x100)]).is_empty()); + assert_eq!(v.s.mapped[&w].src, 0); + assert!(v.s.own.contains(&w)); + v.submit(&[]); + assert!(v.gpu_bytes(&buf, 0, TILE).iter().all(|&b| b == 0)); + // a page mapped there + map_pages_at(w, &[[0, 0, 1]], h, 1); + v.take_remaps(1); + assert_eq!(v.s.remaps, vec![w], "the tile of its own is told"); + v.submit(&[]); + assert_eq!(v.s.mapped[&w].src, h, "linked over the page"); + assert!(!v.s.own.contains(&w)); + assert!(v.gpu_bytes(&buf, 0, TILE) == page, "and shows it"); + assert_eq!(crate::hle::kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), 1, pages.as_mut_ptr()), 1); + v.take_remaps(1); + 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