From 3e04ddb46472bdb326d7d2411bf3116b2abace60 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:24:24 +0000 Subject: [PATCH] D3D12.X: remember committed source regions instead of asking Windows per submit holes_now asked Windows about every CPU-view tile a submit touched (K32QueryWorkingSetEx, then VirtualQuery for pages outside the working set) while holding the sparse lock, and shader::readable and read_committed_into walked VirtualQuery for title memory outside the coherent window. SourceRegions keeps the spans found committed and accessible. Only accessible spans are kept, so a commit needs no invalidation. Whatever takes pages away clears their span before Windows does it (no reader trusts it meanwhile) and after (nothing a query found in between stays): kernelx's VirtualFree, VirtualFreeEx, a VirtualProtect or a commit that leaves pages unreadable, physical pages given up (release_at, give_back_homes) and blocks FreeTitlePhysicalPages releases, GPU-view reservations, and sparse's own decommit, release and free paths. A free of size 0 clears the whole reservation, as long as XCL knows it (sparse and view windows, graphics reservations) or VirtualQuery finds it; nothing for a block of a committed window; and the whole cache only when the length is unknown. A query that raced a clear replays the latest 256 clears before inserting, or drops its result when it cannot. XCL_SOURCE_HOLES_CACHE=0 turns the cache off. Each unit test has a cache of its own, on only in the tests that turn it on, so tests that free memory without XCL's hooks leave nothing behind for others. Measured on amd-dev (3a3a8e9c, RX 9070 XT, 5+ minutes in a retail title's world): asking Windows which pages are committed went from 1.513 ms avg / 10.233 ms max to 0.002 / 0.009 ms, the sparse lock per submit from 1.637 / 10.414 ms to 0.149 / 0.767 ms. Not measured on main. Ported from amd-dev 3a3a8e9c, with the read_committed_into fast path from 4d6d4a77. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- crates/xcl/src/gpu/shader.rs | 13 +- crates/xcl/src/hle/d3d12x/sparse.rs | 336 +++++++++++++++++++- crates/xcl/src/hle/d3d12x/title_textures.rs | 4 +- crates/xcl/src/hle/kernelx.rs | 89 +++++- 4 files changed, 435 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/gpu/shader.rs b/crates/xcl/src/gpu/shader.rs index 0d510f18d3..4da0ad33eb 100644 --- a/crates/xcl/src/gpu/shader.rs +++ b/crates/xcl/src/gpu/shader.rs @@ -215,6 +215,10 @@ pub fn readable(p: usize, len: usize) -> bool { if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(p, len)) { return true; } + if crate::hle::d3d12x::sparse::known_readable(p, end) { + return true; + } + let rev0 = crate::hle::d3d12x::sparse::source_regions_rev(); if let Some(answer) = pages_readable(p, end) { return answer; } @@ -225,7 +229,14 @@ pub fn readable(p: usize, len: usize) -> bool { if n == 0 || mbi.State != MEM_COMMIT || mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD) != 0 || mbi.Protect == 0 { return false; } - cur = mbi.BaseAddress as usize + mbi.RegionSize; + let lo = mbi.BaseAddress as usize; + let hi = lo.saturating_add(mbi.RegionSize); + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(lo) || u.is_view(lo) || u.contains(lo)) + || crate::hle::kernelx::in_graphics_reservation(lo) + { + crate::hle::d3d12x::sparse::cache_readable_region(lo, hi, rev0); + } + cur = hi; } true } diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index fb532258fd..47a69e5967 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -265,6 +265,243 @@ unsafe fn source_holes(tiles: &[usize]) -> Vec { out } +/// `XCL_SOURCE_HOLES_CACHE=0`: query Windows (`source_holes`) on every `holes_now` without +/// caching known-accessible source regions across submits. On by default; in unit tests only on +/// the threads that turn it on (`tests::REGION_CACHE`), so tests that free their memory without +/// XCL's hooks leave nothing behind for others. +fn source_holes_cache_on() -> bool { + #[cfg(test)] + if !tests::REGION_CACHE.with(|on| on.get()) { + return false; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SOURCE_HOLES_CACHE").ok().is_none_or(|v| v.trim() != "0")) +} + +/// Sorted, disjoint, coalesced `[lo, hi)` page-aligned spans known to be `MEM_COMMIT` and +/// accessible (`Protect != 0`, not `PAGE_NOACCESS | PAGE_GUARD`). Only accessible spans are +/// cached, so committing new pages needs no invalidation; decommits, frees, and non-writable +/// protection changes punch their exact span out (`invalidate_source_range`). +#[derive(Default)] +struct SourceRegions { + rev: u64, + ranges: Vec<(usize, usize)>, + /// Recent invalidations `(rev, lo, hi)` so an in-flight `VirtualQuery` can still safely + /// populate unaffected regions (`(rev, 0, usize::MAX)` marks a full clear). + recent: VecDeque<(u64, usize, usize)>, +} + +impl SourceRegions { + const RECENT_CAP: usize = 256; + + fn contains_tile(&self, tile: usize) -> bool { + let Some(end) = tile.checked_add(TILE) else { return false }; + let i = self.ranges.partition_point(|&(lo, _)| lo <= tile); + i > 0 && self.ranges[i - 1].1 >= end + } + + fn insert(&mut self, lo: usize, hi: usize) { + if lo >= hi { + return; + } + let mut start = lo; + let mut end = hi; + // First range whose end >= start (touches or overlaps `[start, end)`). + let first = self.ranges.partition_point(|&(_, r_end)| r_end < start); + let mut last = first; + while last < self.ranges.len() && self.ranges[last].0 <= end { + start = start.min(self.ranges[last].0); + end = end.max(self.ranges[last].1); + last += 1; + } + self.ranges.splice(first..last, std::iter::once((start, end))); + } + + fn subtract(&mut self, lo: usize, hi: usize) { + if lo >= hi || self.ranges.is_empty() { + return; + } + let first = self.ranges.partition_point(|&(_, r_end)| r_end <= lo); + let mut last = first; + let mut repl: Vec<(usize, usize)> = Vec::new(); + while last < self.ranges.len() && self.ranges[last].0 < hi { + let (a, b) = self.ranges[last]; + if a < lo { + repl.push((a, lo)); + } + if b > hi { + repl.push((hi, b)); + } + last += 1; + } + if first < last { + self.ranges.splice(first..last, repl); + } + } + + fn note_invalidation(&mut self, lo: usize, hi: usize) { + self.rev = self.rev.wrapping_add(1); + if self.recent.len() >= Self::RECENT_CAP { + self.recent.pop_front(); + } + self.recent.push_back((self.rev, lo, hi)); + } + + fn invalidate(&mut self, a: usize, n: usize) { + if n == 0 { + // (unknown length: the memory may hold several spans, so all go, and a query in + // flight drops what it found) + self.ranges.clear(); + self.note_invalidation(0, usize::MAX); + return; + } + let (lo, hi) = page_span(a, n); + self.subtract(lo, hi); + self.note_invalidation(lo, hi); + } + + /// Add `spans` (found accessible by a `VirtualQuery` begun at revision `rev0`) unless an + /// invalidation since then cannot be replayed, then subtract the invalidations since `rev0`. + fn insert_since(&mut self, rev0: u64, spans: &[(usize, usize)]) -> bool { + let delta = self.rev.wrapping_sub(rev0); + let replayable = delta == 0 + || (delta <= self.recent.len() as u64 + && self.recent.iter().rev().take(delta as usize).all(|&(_, lo, hi)| !(lo == 0 && hi == usize::MAX))); + if !replayable { + return false; + } + for &(lo, hi) in spans { + self.insert(lo, hi); + } + if delta > 0 { + let subtracts: Vec<(usize, usize)> = self.recent.iter().rev().take(delta as usize).map(|&(_, lo, hi)| (lo, hi)).collect(); + for (lo, hi) in subtracts { + self.subtract(lo, hi); + } + } + true + } +} + +/// Leaf lock (never held across OS syscalls or `STATE`): cached known-accessible source regions for +/// `holes_now`. +#[cfg(not(test))] +static SOURCE_REGIONS: Mutex = Mutex::new(SourceRegions { rev: 0, ranges: Vec::new(), recent: VecDeque::new() }); + +/// `f` with `SOURCE_REGIONS` locked. Each unit test has a cache of its own +/// (`tests::SOURCE_REGIONS`): one test's frees do not clear another's. +fn with_regions(f: impl FnOnce(&mut SourceRegions) -> R) -> R { + #[cfg(not(test))] + return f(&mut SOURCE_REGIONS.lock().unwrap_or_else(|e| e.into_inner())); + #[cfg(test)] + return tests::SOURCE_REGIONS.with(|s| f(&mut s.borrow_mut())); +} + +/// Drop `[a, a + n)` (everything when `n == 0`: the length is not known) from the +/// `source_holes` region cache. Call before and after any decommit, release, or protection +/// change that leaves process memory unreadable: before, so that no reader trusts it while it +/// goes, and after, so that nothing a query found meanwhile stays. +pub fn invalidate_source_range(a: usize, n: usize) { + with_regions(|s| s.invalidate(a, n)); +} + +/// Fast-path check for `gpu::shader::readable`: returns `true` if `[p, end)` lies completely +/// inside a cached committed, readable region (`SOURCE_REGIONS`). Never returns a false positive: +/// every free, decommit, and non-writable protection change in `kernelx` / `sparse` punches out +/// the affected span. +pub(crate) fn known_readable(p: usize, end: usize) -> bool { + if !source_holes_cache_on() || p >= end { + return false; + } + with_regions(|s| { + let i = s.ranges.partition_point(|&(lo, _)| lo <= p); + i > 0 && s.ranges[i - 1].1 >= end + }) +} + +/// Snapshot the current invalidation revision of `SOURCE_REGIONS` before querying Windows. +pub(crate) fn source_regions_rev() -> u64 { + with_regions(|s| s.rev) +} + +/// Record `[lo, hi)` (already verified `MEM_COMMIT` + readable via `VirtualQuery`) into +/// `SOURCE_REGIONS`, only for regions whose lifecycle is 100% intercepted by XCL (`uma` windows +/// or `kernelx` graphics reservations) and subtracting any invalidations since `rev0`. +pub(crate) fn cache_readable_region(lo: usize, hi: usize, rev0: u64) { + if !source_holes_cache_on() || lo >= hi { + return; + } + with_regions(|s| s.insert_since(rev0, &[(lo, hi)])); +} + +/// Cached `source_holes`: checks `SOURCE_REGIONS` first, then runs sorted `VirtualQuery` over +/// cache misses without `K32QueryWorkingSetEx` working-set-lock contention, caching newly +/// discovered accessible spans (minus any concurrent invalidations or `freeing` ranges). +unsafe fn source_holes_cached(tiles: &[usize], freeing: &[(usize, usize)]) -> Vec { + if tiles.is_empty() { + return Vec::new(); + } + if !source_holes_cache_on() { + return source_holes(tiles); + } + let mut out = vec![0u16; tiles.len()]; + let mut misses: Vec<(usize, usize)> = Vec::new(); + let rev0 = with_regions(|s| { + for (idx, &t) in tiles.iter().enumerate() { + if !s.contains_tile(t) { + misses.push((t, idx)); + } + } + s.rev + }); + if misses.is_empty() { + return out; + } + misses.sort_unstable_by_key(|&(t, _)| t); + let mut region = (0usize, 0usize, false); + let mut newly_accessible: Vec<(usize, usize)> = Vec::new(); + for (t, idx) in misses { + if region.0 <= t && t.saturating_add(TILE) <= region.1 { + out[idx] = if region.2 { 0 } else { 0xFFFF }; + continue; + } + let mut holes = 0xFFFFu16; + for i in 0..PAGES_PER_TILE { + let pg = t + i * PAGE; + if !(region.0..region.1).contains(&pg) { + #[cfg(test)] + tests::VIRTUAL_QUERIES.with(|n| n.set(n.get() + 1)); + let mut mbi: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + region = if VirtualQuery(pg as *const c_void, &mut mbi, std::mem::size_of::()) == 0 || mbi.RegionSize == 0 { + (pg, pg + PAGE, false) + } else { + let ok = mbi.State == MEM_COMMIT && mbi.Protect != 0 && (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) == 0; + let lo = (mbi.BaseAddress as usize).min(pg); + let hi = (mbi.BaseAddress as usize).saturating_add(mbi.RegionSize).max(pg + PAGE); + if ok { + newly_accessible.push((lo, hi)); + } + (lo, hi, ok) + }; + } + if region.2 { + holes &= !(1u16 << i); + } + } + out[idx] = holes; + } + if !newly_accessible.is_empty() { + with_regions(|s| { + if s.insert_since(rev0, &newly_accessible) { + for &(a, end) in freeing { + s.subtract(a, end); + } + } + }); + } + out +} + /// Query actual OS page commitment across the 64 KiB tile at `tile`. /// Bit `i` in the returned mask is set whenever 4 KiB page `tile + i * PAGE` is not committed /// and accessible (`MEM_RESERVE`, `MEM_FREE`, `PAGE_NOACCESS`, `PAGE_GUARD`, etc.). @@ -4922,6 +5159,7 @@ pub unsafe fn free(p: usize) -> bool { let Some((start, len)) = u.sparse_reservation(p).filter(|&(start, _)| start == p) else { return false }; decommitted(start, len); VirtualFree(p as *mut c_void, len, MEM_DECOMMIT); + invalidate_source_range(start, len); u.sparse_release(p).is_some() } @@ -5673,6 +5911,7 @@ pub unsafe fn decommitted(a: usize, n: usize) { if n == 0 { return; } + invalidate_source_range(a, n); let mut g = lock_in_turn(&STATE, &SUBMITS_WAITING); let _held = holding(Holder::Commits); forget_released(&mut g); @@ -5829,6 +6068,7 @@ impl State { /// `decommitted` with the state locked: the tiles that go are parked (`flush_parked` unmaps /// them and frees their pool tiles) unsafe fn decommit_range(&mut self, a: usize, n: usize) { + invalidate_source_range(a, n); let mut pools: Vec<(usize, (u32, u32))> = Vec::new(); let end = a.saturating_add(n); // tiles over a CPU view go as a whole (their holes are the CPU view's pages, not these) @@ -6410,10 +6650,12 @@ pub unsafe fn source_decommit(a: usize, n: usize, os: impl FnOnce() -> R) -> return os(); } let (span, shown) = freeing_begins(&SOURCES, a, n); + invalidate_source_range(a, n); if shown { source_decommitted(a, n); } let r = os(); + invalidate_source_range(a, n); freeing_ends(&SOURCES, span); r } @@ -6427,10 +6669,12 @@ pub unsafe fn source_release(a: usize, n: usize, os: impl FnOnce() -> R) -> R return os(); } let (span, shown) = freeing_begins(&SOURCES, a, n); + invalidate_source_range(a, n); if shown { source_decommitted(a, n); } let r = os(); + invalidate_source_range(a, n); forget_mirrors(a, n); freeing_ends(&SOURCES, span); r @@ -6466,6 +6710,7 @@ pub fn forget_mirrors(a: usize, n: usize) { if n == 0 { return; } + invalidate_source_range(a, n); let end = a.saturating_add(n); // (out of the queue before out of the set: an ask in between finds the tile still asked // for, or stays queued, and the count after it has the thread ask again. The other way @@ -6880,7 +7125,7 @@ impl State { /// is in the list read here. unsafe fn holes_now(&self, tiles: &[usize]) -> Vec { let freeing = lock_sources(self.sources).freeing.clone(); - let mut holes = source_holes(tiles); + let mut holes = source_holes_cached(tiles, &freeing); for &(a, end) in &freeing { for (h, &t) in holes.iter_mut().zip(tiles) { let (lo, hi) = (a.max(t), end.min(t + TILE)); @@ -6982,6 +7227,7 @@ impl State { /// holes (`decommit_tiles`); a tile all holes is parked, and stays in `mirrors` (a commit and /// write there gives it video memory again). unsafe fn source_decommitted_in(&mut self, a: usize, n: usize) { + invalidate_source_range(a, n); let end = a.saturating_add(n); for t in self.src_tiles_in(a, end) { let (lo, hi) = (a.max(t), end.min(t + TILE)); @@ -8444,6 +8690,11 @@ mod tests { 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) }; + /// `source_holes_cache_on` for this thread's test (off unless a test turns it on). + pub(super) static REGION_CACHE: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// This thread's test's `SOURCE_REGIONS` (`with_regions`). + pub(super) static SOURCE_REGIONS: std::cell::RefCell = + const { std::cell::RefCell::new(SourceRegions { rev: 0, ranges: Vec::new(), recent: VecDeque::new() }) }; /// 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) }; @@ -12097,6 +12348,89 @@ mod tests { } } + /// `source_holes_cached` caches known-accessible regions across calls (zero VirtualQuery on + /// repeat queries even for unsorted tiles), keeps unrelated regions cached when another range + /// is freed, immediately exposes a decommitted hole after `invalidate_source_range`, and sees + /// a newly re-committed page without needing commit invalidation. + #[test] + fn source_holes_cached_reuses_regions_and_invalidates_only_freed_ranges() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + const TILES: usize = 32; + REGION_CACHE.with(|on| on.set(true)); + unsafe { + let a = VirtualAlloc(std::ptr::null(), TILES * TILE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + let b = VirtualAlloc(std::ptr::null(), 4 * TILE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert!(a != 0 && b != 0); + // Unsorted tiles inside `a` populate the region cache in one VirtualQuery. + let tiles_a: Vec = [20, 3, 31, 0, 10].into_iter().map(|k| a + k * TILE).collect(); + let q0 = VIRTUAL_QUERIES.with(|n| n.get()); + assert_eq!(source_holes_cached(&tiles_a, &[]), vec![0; tiles_a.len()]); + let q1 = VIRTUAL_QUERIES.with(|n| n.get()); + assert!(q1 - q0 >= 1 && q1 - q0 <= 2, "initial miss should populate `a` in <= 2 queries, got {}", q1 - q0); + + // Second query over different tiles in `a` makes zero VirtualQuery calls. + let more_a: Vec = [1, 15, 29, 7].into_iter().map(|k| a + k * TILE).collect(); + assert_eq!(source_holes_cached(&more_a, &[]), vec![0; more_a.len()]); + assert_eq!(VIRTUAL_QUERIES.with(|n| n.get()), q1, "cache hit must do 0 VirtualQuery calls"); + + // Invalidating unrelated region `b` must not evict `a`. + invalidate_source_range(b, 4 * TILE); + assert_eq!(source_holes_cached(&tiles_a, &[]), vec![0; tiles_a.len()]); + assert_eq!(VIRTUAL_QUERIES.with(|n| n.get()), q1, "unrelated free must not evict `a`"); + + // Decommitting one page in tile 10 and invalidating it exposes the hole immediately. + let hole_pg = a + 10 * TILE + 5 * PAGE; + assert_ne!(VirtualFree(hole_pg as *mut c_void, PAGE, MEM_DECOMMIT), 0); + invalidate_source_range(hole_pg, PAGE); + let holes = source_holes_cached(&[a + 10 * TILE, a + 20 * TILE], &[]); + assert_eq!(holes, vec![1 << 5, 0]); + + // Re-committing the hole is seen immediately (holes are never cached). + assert!(!VirtualAlloc(hole_pg as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + assert_eq!(source_holes_cached(&[a + 10 * TILE], &[]), vec![0]); + + invalidate_source_range(a, TILES * TILE); + invalidate_source_range(b, 4 * TILE); + assert_ne!(VirtualFree(a as *mut c_void, 0, MEM_RELEASE), 0); + assert_ne!(VirtualFree(b as *mut c_void, 0, MEM_RELEASE), 0); + } + REGION_CACHE.with(|on| on.set(false)); + } + + /// kernelx clears what the title takes away from the region cache: a decommit, a protection + /// that leaves pages unreadable (by VirtualProtect, or by committing them again), and the + /// release of a whole reservation; the rest stays cached, other allocations too. + #[test] + fn the_title_s_frees_and_protections_leave_the_region_cache() { + use crate::hle::kernelx; + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + REGION_CACHE.with(|on| on.set(true)); + unsafe { + let a = VirtualAlloc(std::ptr::null(), 8 * TILE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + let b = VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert!(a != 0 && b != 0); + let tiles: Vec = (0..8).map(|k| a + k * TILE).collect(); + assert_eq!(source_holes_cached(&tiles, &[]), vec![0; 8]); + assert_eq!(source_holes_cached(&[b], &[]), vec![0]); + assert!(known_readable(a, a + 8 * TILE), "cached whole"); + assert_ne!(kernelx::VirtualFree((a + TILE + 3 * PAGE) as *mut c_void, PAGE, MEM_DECOMMIT), 0); + let mut old = 0u32; + assert_ne!(kernelx::VirtualProtect((a + 3 * TILE + 5 * PAGE) as *const c_void, PAGE, PAGE_NOACCESS, &mut old), 0); + assert!(!kernelx::VirtualAlloc((a + 5 * TILE + 7 * PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_NOACCESS).is_null()); + for pg in [a + TILE + 3 * PAGE, a + 3 * TILE + 5 * PAGE, a + 5 * TILE + 7 * PAGE] { + assert!(!known_readable(pg, pg + PAGE), "{:#x}", pg - a); + } + assert!(known_readable(a, a + TILE), "the rest stays cached"); + assert_eq!(source_holes_cached(&tiles, &[]), vec![0, 1 << 3, 0, 1 << 5, 0, 1 << 7, 0, 0]); + assert_ne!(kernelx::VirtualFree(a as *mut c_void, 0, MEM_RELEASE), 0); + assert!(!known_readable(a, a + TILE) && !known_readable(a + 7 * TILE, a + 8 * TILE), "released, past its holes too"); + assert!(known_readable(b, b + TILE), "another allocation stays cached"); + assert_ne!(kernelx::VirtualFree(b as *mut c_void, 0, MEM_RELEASE), 0); + assert!(!known_readable(b, b + TILE)); + } + REGION_CACHE.with(|on| on.set(false)); + } + /// 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. diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d809b1c2a2..5443fa9c2c 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -3328,7 +3328,9 @@ pub(super) unsafe fn read_committed_into(at: usize, out: &mut [u8]) { let Some(limit) = at.checked_add(len) else { return out.fill(0) }; // (the coherent window is committed as a whole: no `VirtualQuery`, which sizes a region by // walking it) - if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)) { + if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)) + || super::sparse::known_readable(at, limit) + { std::ptr::copy_nonoverlapping(at as *const u8, out.as_mut_ptr(), len); return; } diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index a29d3c4498..d5428898d6 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -216,6 +216,7 @@ pub mod mirrors { if t & PAGES_64K != PAGES_64K || t & 0x1000 != 0 { return false; } + crate::hle::d3d12x::sparse::invalidate_source_range(base, size); let mut s = STATE.lock().unwrap(); if p & GRAPHICS_NOACCESS != 0 && p & 0xFF == super::mem::PAGE_NOACCESS { if let Some(cpu) = unpaired_cpu(&s, size) { @@ -909,6 +910,20 @@ 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 { + // (a commit that leaves pages unreadable changes their protection: out of the region cache + // around it, as in `VirtualProtect`) + if addr.is_null() || t & 0x1000 == 0 || read_write(sanitize_protect(p)) { + return virtual_alloc(addr, size, t, p); + } + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); + let q = virtual_alloc(addr, size, t, p); + if !q.is_null() { + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); + } + q +} + +unsafe fn virtual_alloc(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); @@ -1197,6 +1212,49 @@ unsafe fn source_part_going(part: Option<(usize, usize)>, release: bool, 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 { + // (the region cache answers for none of it while it goes, nor after) + let span = if size != 0 { Some(size) } else { whole_len(addr as usize) }; + if let Some(n) = span { + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, n); + } + let ok = virtual_free(addr, size, t); + if let Some(n) = span.filter(|_| ok != 0) { + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, n); + } + ok +} + +/// The bytes a free of size 0 at `a` (the whole of its reservation) takes away, for the region +/// cache, as XCL and Windows have them before the call: None when none of it can be cached (a +/// block of a committed window stays committed), 0 when it is not known (the cache is cleared). +unsafe fn whole_len(a: usize) -> Option { + if let Some(u) = crate::gpu::uma::get() { + if let Some((start, n)) = u.sparse_reservation(a).or_else(|| u.view_reservation(a)) { + return Some(start + n - a); + } + if u.in_committed_window(a, 1) { + return None; + } + } + if let Some(&n) = GRAPHICS_RESERVATIONS.lock().unwrap().get(&a) { + return Some(n); + } + // (other memory: the regions of the allocation at `a`) + let mut end = a; + loop { + let mut mbi: mem::MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if mem::VirtualQuery(end as *const c_void, &mut mbi, std::mem::size_of::()) == 0 + || mbi.State == mem::MEM_FREE + || mbi.AllocationBase as usize != a + || mbi.RegionSize == 0 + { + return Some(end - a); + } + end = mbi.BaseAddress as usize + mbi.RegionSize; + } +} + +unsafe fn virtual_free(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; @@ -1321,6 +1379,13 @@ pub unsafe extern "system" fn VirtualFreeEx(proc_: HANDLE, addr: *mut c_void, si 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); } + let n = if size != 0 { size } else { whole_len(a).unwrap_or(0) }; + crate::hle::d3d12x::sparse::invalidate_source_range(a, n); + let ok = mem::VirtualFreeEx(proc_, addr, size, t); + if ok != 0 { + crate::hle::d3d12x::sparse::invalidate_source_range(a, n); + } + return ok; } mem::VirtualFreeEx(proc_, addr, size, t) } @@ -1337,10 +1402,15 @@ pub unsafe extern "system" fn VirtualProtect(addr: *const c_void, size: usize, p let writable = read_write(protection); if !writable { note_protection(addr, size, protection); + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); } let ok = mem::VirtualProtect(addr, size, protection, old); - if ok != 0 && writable { - note_protection(addr, size, protection); + if ok != 0 { + if writable { + note_protection(addr, size, protection); + } else { + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); + } } ok } @@ -1351,10 +1421,15 @@ pub unsafe extern "system" fn VirtualProtectEx(proc_: HANDLE, addr: *const c_voi let writable = read_write(protection); if own && !writable { note_protection(addr, size, protection); + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); } let ok = mem::VirtualProtectEx(proc_, addr, size, protection, old); - if ok != 0 && own && writable { - note_protection(addr, size, protection); + if ok != 0 && own { + if writable { + note_protection(addr, size, protection); + } else { + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); + } } ok } @@ -2116,7 +2191,9 @@ unsafe fn give_back_homes(away: &mut Away) { crate::hle::d3d12x::sparse::decommitted(start, end - start); } // (a tile may show a page kept at its home: `source_part`) + crate::hle::d3d12x::sparse::invalidate_source_range(start, end - start); source_going(start, end - start, false, || mem::VirtualFree(start as *mut c_void, end - start, mem::MEM_DECOMMIT)); + crate::hle::d3d12x::sparse::invalidate_source_range(start, end - start); } } @@ -2319,7 +2396,9 @@ unsafe fn release_at(at: usize) { crate::hle::d3d12x::sparse::decommitted(at, PHYS_PAGE); } // (most pages are mapped in the CPU view of a pair: the tiles of its GPU view show them) + crate::hle::d3d12x::sparse::invalidate_source_range(at, PHYS_PAGE); source_going(at, PHYS_PAGE, false, || mem::VirtualFree(at as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT)); + crate::hle::d3d12x::sparse::invalidate_source_range(at, PHYS_PAGE); } /// A page mapped away from home (at `old`) that the title maps at `at`: what `old` holds copied @@ -2457,6 +2536,7 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: drop(away); for (home, count) in homes { // (a tile may show a page kept in the block: `source_part`) + crate::hle::d3d12x::sparse::invalidate_source_range(home, count * PHYS_PAGE); source_going(home, count * PHYS_PAGE, true, || { if u.is_sparse(home) { crate::hle::d3d12x::sparse::free(home); @@ -2466,6 +2546,7 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: mem::VirtualFree(home as *mut c_void, 0, mem::MEM_RELEASE); } }); + crate::hle::d3d12x::sparse::invalidate_source_range(home, count * PHYS_PAGE); } 1 }