From 7692dd87db07ad91d93d7f013f739abc960b3bba Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:20:58 -0500 Subject: [PATCH 1/2] D3D12.X: XCL_WATCH_TRAP=1 leaves memory nobody writes out of the looks Every submit looks at all watched memory with GetWriteWatch, and the call is paid per byte looked at (about 0.5 ms per GiB). In a streamed world 17.6 GB are watched, and most of it is written once when it streams in and not again. With XCL_WATCH_TRAP=1 a 2 MiB block of a watched range that 64 looks in a row found clean is made read-only and left out of the looks. Its first write faults into a vectored handler, which gives the block its protection back and returns it to the looks; the write happens after that, so write-watch reports it as before. A block that cannot be made read-only (pinned, nothing committed, not all read-write) is tried again after another 64 looks, not at every look, and a block with nothing committed leaves the looks as a hole until a commit in it. A kernel write into a read-only page fails instead of faulting, so the title's ReadFile buffers get their protection back and stay pinned until the read is over, and their pages are then reported as written. A pending read is over when a look sees its OVERLAPPED done, or when the title uses that OVERLAPPED for its next read. Commits, decommits and protection changes through kernelx, lazy pages and sparse commits give the blocks they meet their protection back first, and so do XCL's own checks whether memory is writable. Off by default; without the variable only a sorted list gets a dedup. Measured on title ea3b5e4d on a tree with the driver-heap windows of #2844 (RTX 5070 Ti, one timed run per arm, the trap the only change): 5.79 against 4.01 presents/s over 107-223 s of the run, 8.45 against 4.60 over 187-229 s, the same draws per present, no device removal. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5 --- crates/xcl/src/eh.rs | 1 + crates/xcl/src/hle/d3d12x/cpu_writes.rs | 3 + crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/sparse.rs | 2 + crates/xcl/src/hle/d3d12x/title_textures.rs | 11 +- crates/xcl/src/hle/d3d12x/watch_trap.rs | 710 ++++++++++++++++++++ crates/xcl/src/hle/dstorage.rs | 2 + crates/xcl/src/hle/dstorage/parallel.rs | 3 + crates/xcl/src/hle/kernelx.rs | 10 + crates/xcl/src/hle/kernelx/lazy.rs | 1 + crates/xcl/src/vfs_hooks.rs | 9 +- 11 files changed, 750 insertions(+), 3 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/watch_trap.rs diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 2d431e5a47..0619aae534 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -253,6 +253,7 @@ fn is_writable(va: usize, bytes: usize) -> bool { if bytes > 0 && crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { return true; } + let _trap = crate::hle::d3d12x::watch_trap::guard(va, bytes); let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; let found = unsafe { VirtualQuery(va as *const std::ffi::c_void, &mut m, std::mem::size_of_val(&m)) } != 0; found diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 0b20bfbd6a..b0234b0e08 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -92,6 +92,7 @@ fn worker() -> &'static Mutex> { unsafe fn write_now(va: usize, words: &[u32]) { let bytes = 4 * words.len(); if !crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { + let _trap = super::watch_trap::guard(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(); if VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT { @@ -115,6 +116,7 @@ unsafe fn u64_writable_now(va: usize) -> bool { if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, 8)) { return true; } + let _trap = super::watch_trap::guard(va, 8); use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_GUARD, PAGE_READWRITE}; let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); if VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT { @@ -147,6 +149,7 @@ pub(super) fn writable(va: usize, bytes: usize) -> bool { return true; } crate::hle::kernelx::lazy::ensure(va, bytes); + let _trap = super::watch_trap::guard(va, bytes); use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; let found = unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0; diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 8886624632..73bc2a1cbd 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -33,6 +33,7 @@ mod standin; pub mod title_list; pub mod title_textures; pub mod vram; +pub mod watch_trap; use std::ffi::c_void; use std::sync::OnceLock; diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index b7560f861e..7df18978c8 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1327,6 +1327,7 @@ pub unsafe fn committed(a: usize, n: usize) { if n == 0 { return; } + super::watch_trap::changed(a, n); let mut g = lock_state(); let Some(s) = g.as_mut() else { let (start, end) = page_span(a, n); @@ -1343,6 +1344,7 @@ pub unsafe fn decommitted(a: usize, n: usize) { if n == 0 { return; } + super::watch_trap::changed(a, n); let mut g = lock_state(); let Some(s) = g.as_mut() else { let (start, end) = page_span(a, n); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 6d97bc6e4e..38bd25a675 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -746,11 +746,18 @@ unsafe fn refresh_once(queue: *mut c_void) { if buf.len() < 16384 { buf.resize(16384, std::ptr::null_mut()); } - for &(base, size) in ranges.iter() { - take_written(base, size, &mut buf, &mut dirty, &mut page); + if super::watch_trap::on() { + let mut p = page; + super::watch_trap::look(&ranges, &mut dirty, 0x1000, |a, n, d| take_written(a, n, &mut buf, d, &mut p)); + page = p; + } else { + for &(base, size) in ranges.iter() { + take_written(base, size, &mut buf, &mut dirty, &mut page); + } } }); dirty.sort_unstable(); + dirty.dedup(); dirty.len() }); super::sparse::note_watch(watch_t0.elapsed(), dirty_len); diff --git a/crates/xcl/src/hle/d3d12x/watch_trap.rs b/crates/xcl/src/hle/d3d12x/watch_trap.rs new file mode 100644 index 0000000000..d87f3788f0 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/watch_trap.rs @@ -0,0 +1,710 @@ +//! `XCL_WATCH_TRAP=1`: the looks before each submit skip watched memory nobody writes. +//! +//! A 2 MiB block of a watched range that no look has found written for `COLD_LOOKS` looks is +//! made read-only (its committed read-write parts) and left out of the looks. The first write +//! there faults into `handler`, which gives the block its protection back and returns it to the +//! looks; the write itself happens after that, so write-watch sees it as before. When a block +//! is made read-only, a last look at it reports what was written since the previous one. +//! +//! What the handler cannot catch: a kernel write into a read-only page fails (ERROR_NOACCESS) +//! instead of faulting. The title's ReadFile buffers are therefore given their protection back +//! and pinned (never made read-only) until the read is over: when ReadFile returns, or for a +//! pending read when a look sees its OVERLAPPED completed (or the title uses that OVERLAPPED +//! for its next read, which only a finished one allows). Either way the buffer's pages are +//! then reported as written: an unbuffered read flags its pages when it starts, not when the +//! data lands, so a look in between would reset them. Commits, decommits and protection changes +//! through kernelx and lazy pages (`guard`) and sparse commits (`changed`) give the blocks they +//! meet their protection back first and keep them from going read-only meanwhile. XCL's own +//! checks whether memory is writable (DirectStorage destinations, CPU-side writes for the GPU, +//! emulated stores) give it back too: their writes come from user mode and would be let +//! through, but the check reads the protection. + +use std::collections::BTreeMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; +use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS}; +use windows_sys::Win32::System::Memory::{VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_RESERVE}; + +const BLOCK: usize = 2 << 20; +/// looks a block must be found clean before it is made read-only: protecting 2 MiB costs about +/// 36 us, looking at it ~1 us, so it pays once a block stays cold ~40 looks (one to two frames) +const COLD_LOOKS: u32 = 64; +/// blocks made read-only per look at most (~36 us each), so a cold world goes over in steps +const PROTECTS_PER_LOOK: usize = 32; +const PAGE_READWRITE: u32 = 0x04; +const PAGE_READONLY: u32 = 0x02; +/// protection modifiers kept as they are (PAGE_NOCACHE, PAGE_WRITECOMBINE) +const MODIFIERS: u32 = 0x200 | 0x400; +const STATUS_PENDING: usize = 0x103; +const EXCEPTION_CONTINUE_EXECUTION: i32 = -1; +const EXCEPTION_CONTINUE_SEARCH: i32 = 0; + +/// A read-only span: its end and the committed parts with the protection they had. +struct Cold { + end: usize, + parts: Vec<(usize, usize, u32)>, +} + +/// read-only spans by start (one block or the part of it in one watched range) +static COLD: Mutex> = Mutex::new(BTreeMap::new()); +/// blocks with a kernel read into them in flight -> how many +static PINS: Mutex> = Mutex::new(BTreeMap::new()); +/// pending title reads: (OVERLAPPED, buffer, length, byte count output) +static PENDING: Mutex> = Mutex::new(Vec::new()); +/// finished reads whose pages the next look reports as written +static REPORT: Mutex> = Mutex::new(Vec::new()); +/// an OVERLAPPED's size (Internal, InternalHigh, Offset/Pointer, hEvent) +const OVERLAPPED_LEN: usize = 32; +/// the looks' own state (one look at a time: `title_textures::REFRESH`) +static LOOKS: Mutex = Mutex::new(Looks { clean: BTreeMap::new(), n: 0 }); +/// blocks ever made read-only (for `was_ours`) +static EVER: Mutex> = Mutex::new(std::collections::BTreeSet::new()); +static INSTALLED: AtomicBool = AtomicBool::new(false); +/// faults taken, blocks made read-only, spans given back by `changed`, bytes left out of looks, +/// committed regions a thaw could not give back +static STATS: [AtomicU64; 6] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; + +struct Looks { + /// block -> (span looked at in it this look, looks found clean in a row) + clean: BTreeMap, + n: u64, +} + +pub fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var("XCL_WATCH_TRAP").is_ok_and(|v| v.trim() == "1"); + if on { + crate::xlog_info!("watch trap: on (blocks of {} MiB clean for {COLD_LOOKS} looks are made read-only)", BLOCK >> 20); + } + on + }) +} + +fn install() { + if !INSTALLED.swap(true, Ordering::AcqRel) { + unsafe { AddVectoredExceptionHandler(1, Some(handler)) }; + } +} + +unsafe fn protect(a: usize, n: usize, p: u32) -> bool { + let mut old = 0u32; + VirtualProtect(a as *const c_void, n, p, &mut old) != 0 +} + +/// Give a read-only span its protection back. A part with pages decommitted since then cannot +/// be protected as a whole (ERROR_INVALID_ADDRESS): its committed regions are, one by one. +unsafe fn thaw(c: &Cold) { + for &(a, n, p) in &c.parts { + if protect(a, n, p) { + continue; + } + let end = a + n; + let mut at = a; + while at < end { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 { + break; + } + let next = (m.BaseAddress as usize + m.RegionSize).min(end); + if m.State == MEM_COMMIT && m.Protect & !MODIFIERS == PAGE_READONLY && !protect(at, next - at, p) { + STATS[4].fetch_add(1, Ordering::Relaxed); + } + at = next; + } + } +} + +/// The read-only spans meeting `[a, a + n)` given their protection back and dropped. +unsafe fn thaw_range(cold: &mut BTreeMap, a: usize, n: usize) -> usize { + let end = a.saturating_add(n); + let from = cold.range(..=a).next_back().filter(|(_, c)| c.end > a).map_or(a, |(&s, _)| s); + let hit: Vec = cold.range(from..end).map(|(&s, _)| s).collect(); + for s in &hit { + if let Some(c) = cold.remove(s) { + thaw(&c); + } + } + hit.len() +} + +unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + let r = &*(*info).ExceptionRecord; + if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 || r.ExceptionInformation[0] != 1 { + return EXCEPTION_CONTINUE_SEARCH; + } + let at = r.ExceptionInformation[1]; + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + let Some(s) = cold.range(..=at).next_back().filter(|(_, c)| at < c.end).map(|(&s, _)| s) else { + // another thread gave the span back after this write faulted: go on if it may write now + drop(cold); + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + let now = VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 + && m.State == MEM_COMMIT + && matches!(m.Protect & !MODIFIERS, PAGE_READWRITE | 0x40); + return if now && was_ours(at) { EXCEPTION_CONTINUE_EXECUTION } else { EXCEPTION_CONTINUE_SEARCH }; + }; + let c = cold.remove(&s).unwrap(); + thaw(&c); + STATS[0].fetch_add(1, Ordering::Relaxed); + EXCEPTION_CONTINUE_EXECUTION +} + +/// Whether `at` lies in a block this trap has made read-only at some point (a write fault there +/// that finds the page writable again lost a race with another thread's `thaw`). +fn was_ours(at: usize) -> bool { + EVER.lock().unwrap_or_else(|e| e.into_inner()).contains(&(at & !(BLOCK - 1))) +} + +/// `[a, a + n)` is about to be committed, decommitted, freed or given another protection (or a +/// kernel write goes there): the read-only spans it meets get their protection back first. +pub fn changed(a: usize, n: usize) { + if on() { + changed_now(a, n); + } +} + +/// `guard` for a VirtualFree of `[a, a + n)`; `n == 0` (a release) means the whole allocation. +pub fn guard_free(a: usize, n: usize) -> Guard { + if !on() || a == 0 { + return Guard(0, 0); + } + if n != 0 { + return guard(a, n); + } + let mut at = a; + loop { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + if unsafe { VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 || m.AllocationBase as usize != a { + break; + } + at = m.BaseAddress as usize + m.RegionSize; + } + guard(a, at.saturating_sub(a)) +} + +fn changed_now(a: usize, n: usize) { + if n == 0 { + return; + } + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + if cold.is_empty() { + return; + } + let k = unsafe { thaw_range(&mut cold, a, n) }; + STATS[2].fetch_add(k as u64, Ordering::Relaxed); +} + +fn blocks(a: usize, n: usize) -> impl Iterator { + let first = a & !(BLOCK - 1); + let last = (a + n.max(1) - 1) & !(BLOCK - 1); + (first..=last).step_by(BLOCK) +} + +fn pin(a: usize, n: usize, by: i32) { + let mut pins = PINS.lock().unwrap_or_else(|e| e.into_inner()); + for b in blocks(a, n) { + let e = pins.entry(b).or_insert(0); + *e = e.saturating_add_signed(by); + if *e == 0 { + pins.remove(&b); + } + } +} + +/// Pinned and writable while it lives: memory a call is about to write, commit, decommit or +/// give another protection. +pub struct Guard(usize, usize); + +impl Drop for Guard { + fn drop(&mut self) { + release(self.0, self.1); + } +} + +fn hold(a: usize, n: usize) { + if a != 0 && n != 0 { + pin(a, n, 1); + changed_now(a, n); + } +} + +fn release(a: usize, n: usize) { + if a != 0 && n != 0 { + pin(a, n, -1); + } +} + +/// `[a, a + n)` is about to be committed, decommitted or given another protection by the call +/// made while the guard lives. +pub fn guard(a: usize, n: usize) -> Guard { + if !on() || a == 0 || n == 0 { + return Guard(0, 0); + } + hold(a, n); + Guard(a, n) +} + +/// Before the title's ReadFile into `[buf, buf + n)`: the buffer, its byte count output `read` +/// and the OVERLAPPED `ov` (both written by the kernel too) pinned and writable. +pub fn read_start(buf: usize, n: usize, read: usize, ov: usize) { + if !on() || n == 0 { + return; + } + retire_reused(ov); + hold(buf, n); + hold(read, 4); + hold(ov, OVERLAPPED_LEN); +} + +/// A pending read whose OVERLAPPED the title is about to use for another call: that read is +/// over (an OVERLAPPED may be used again only then), and the new call replaces the status the +/// next look would have read, which kept the earlier buffer pinned until the new read ended. +/// It is unpinned and its buffer reported as written here. One whose status still says pending +/// (a title that breaks the rule) is left to the looks. +fn retire_reused(ov: usize) { + if ov == 0 { + return; + } + let over: Vec<(usize, usize, usize, usize)> = { + let mut p = PENDING.lock().unwrap_or_else(|e| e.into_inner()); + if !p.iter().any(|&(o, ..)| o == ov) || unsafe { overlapped_status(ov) } == Some(STATUS_PENDING) { + return; + } + let (over, still) = p.drain(..).partition(|&(o, ..)| o == ov); + *p = still; + over + }; + for (o, buf, n, read) in over { + REPORT.lock().unwrap_or_else(|e| e.into_inner()).push((buf, n)); + release(buf, n); + release(read, 4); + release(o, OVERLAPPED_LEN); + } +} + +/// After it: a pending read stays pinned until a look sees `ov` completed; a finished one is +/// unpinned and, if it succeeded, its buffer reported as written. +pub fn read_end(buf: usize, n: usize, read: usize, ov: usize, pending: bool, ok: bool) { + if !on() || n == 0 { + return; + } + if pending && ov != 0 { + PENDING.lock().unwrap_or_else(|e| e.into_inner()).push((ov, buf, n, read)); + return; + } + if ok { + REPORT.lock().unwrap_or_else(|e| e.into_inner()).push((buf, n)); + } + release(buf, n); + release(read, 4); + release(ov, OVERLAPPED_LEN); +} + +/// `OVERLAPPED::Internal` without faulting if the title has freed it. +unsafe fn overlapped_status(ov: usize) -> Option { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let (mut v, mut done) = (0usize, 0usize); + (ReadProcessMemory(GetCurrentProcess(), ov as *const c_void, &mut v as *mut usize as *mut c_void, 8, &mut done) != 0 && done == 8).then_some(v) +} + +/// The committed parts of `[a, a + n)` if all of them are plain read-write (modifiers kept), +/// with their protection. None parts (a hole: all of it reserved, nothing committed) is a cold +/// span too: nothing to protect, out of the looks until a commit in it (every commit path holds +/// a guard, which gives it back; one that did not would only delay the look, since the write +/// watch keeps its pages until they are read). +unsafe fn writable_parts(a: usize, n: usize) -> Option> { + let end = a + n; + let mut at = a; + let mut parts = Vec::new(); + while at < end { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 { + return None; + } + let next = (m.BaseAddress as usize + m.RegionSize).min(end); + if m.State == MEM_COMMIT { + if m.Protect & !MODIFIERS != PAGE_READWRITE { + return None; + } + parts.push((at, next - at, m.Protect)); + } else if m.State != MEM_RESERVE { + return None; + } + at = next; + } + Some(parts) +} + +/// Make `[a, a + n)` read-only unless a block of it is pinned; false if it stays as it is. +unsafe fn freeze(a: usize, n: usize) -> bool { + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + { + let pins = PINS.lock().unwrap_or_else(|e| e.into_inner()); + if blocks(a, n).any(|b| pins.contains_key(&b)) { + return false; + } + } + let Some(parts) = writable_parts(a, n) else { return false }; + for (i, &(p, len, prot)) in parts.iter().enumerate() { + if !protect(p, len, PAGE_READONLY | (prot & MODIFIERS)) { + for &(p, len, prot) in &parts[..i] { + protect(p, len, prot); + } + return false; + } + } + cold.insert(a, Cold { end: a + n, parts }); + EVER.lock().unwrap_or_else(|e| e.into_inner()).extend(blocks(a, n)); + true +} + +/// `ranges` minus the read-only spans, as pieces within one block each. +fn hot_pieces(ranges: &[(usize, usize)], cold: &BTreeMap) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + for &(base, size) in ranges { + let end = base + size; + let mut at = base; + while at < end { + let block_end = ((at & !(BLOCK - 1)) + BLOCK).min(end); + // the read-only span covering `at`, else the next one starting before `block_end` + if let Some((_, &e)) = cold.range(..=at).next_back().filter(|(_, &e)| e > at) { + at = e.min(end); + continue; + } + let stop = cold.range(at..block_end).next().map_or(block_end, |(&s, _)| s); + out.push((at, stop - at)); + at = stop; + } + } + out +} + +/// One look: `take(base, len, dirty)` is called on the watched pieces that are not read-only +/// (neighbours in one call), completed pending reads report their pages, clean blocks are made +/// read-only. +pub unsafe fn look(ranges: &[(usize, usize)], dirty: &mut Vec, page: usize, mut take: impl FnMut(usize, usize, &mut Vec)) { + install(); + // pending reads that are over: unpinned, their pages written + let done: Vec<(usize, usize, usize, usize)> = { + let mut p = PENDING.lock().unwrap_or_else(|e| e.into_inner()); + let (over, still): (Vec<_>, Vec<_>) = p.drain(..).partition(|&(ov, ..)| overlapped_status(ov) != Some(STATUS_PENDING)); + *p = still; + over + }; + let mut report = std::mem::take(&mut *REPORT.lock().unwrap_or_else(|e| e.into_inner())); + for &(ov, buf, n, read) in &done { + release(buf, n); + release(read, 4); + release(ov, OVERLAPPED_LEN); + report.push((buf, n)); + } + for (buf, n) in report { + dirty.extend((buf & !(page - 1)..buf + n).step_by(page)); + } + let cold: BTreeMap = COLD.lock().unwrap_or_else(|e| e.into_inner()).iter().map(|(&s, c)| (s, c.end)).collect(); + let pieces = hot_pieces(ranges, &cold); + let watched: usize = ranges.iter().map(|r| r.1).sum(); + let hot: usize = pieces.iter().map(|p| p.1).sum(); + STATS[3].fetch_add((watched - hot) as u64, Ordering::Relaxed); + // pieces that touch go in one call (a range lies in one allocation; pieces of two ranges + // never merge) + let mut written = std::collections::BTreeSet::new(); + let mut i = 0; + let range_of = |a: usize| ranges.partition_point(|&(b, _)| b <= a).saturating_sub(1); + while i < pieces.len() { + let (a, mut n) = pieces[i]; + let r = range_of(a); + let mut j = i + 1; + while j < pieces.len() && pieces[j].0 == a + n && range_of(pieces[j].0) == r { + n += pieces[j].1; + j += 1; + } + let from = dirty.len(); + take(a, n, dirty); + written.extend(dirty[from..].iter().map(|&p| p & !(BLOCK - 1))); + i = j; + } + let mut looks = LOOKS.lock().unwrap_or_else(|e| e.into_inner()); + looks.n += 1; + // the clean count of each block looked at (a block with two pieces is never made read-only) + let mut clean: BTreeMap = BTreeMap::new(); + let mut shared = std::collections::BTreeSet::new(); + for &(a, n) in &pieces { + let b = a & !(BLOCK - 1); + if clean.contains_key(&b) { + shared.insert(b); + continue; + } + let was = looks.clean.get(&b).filter(|(span, _)| *span == (a, n)).map_or(0, |&(_, k)| k); + clean.insert(b, ((a, n), if written.contains(&b) { 0 } else { was + 1 })); + } + let mut made = 0; + for (&b, ((a, n), k)) in clean.iter_mut() { + if made == PROTECTS_PER_LOOK { + break; + } + if *k < COLD_LOOKS || shared.contains(&b) || *n < 64 << 10 { + continue; + } + if freeze(*a, *n) { + made += 1; + // what was written between this look and the protection + take(*a, *n, dirty); + } else { + // pinned, nothing committed or not all read-write: tried again after another + // COLD_LOOKS looks, not at every look + *k = 0; + STATS[5].fetch_add(1, Ordering::Relaxed); + } + } + for b in shared { + clean.remove(&b); + } + looks.clean = clean; + STATS[1].fetch_add(made as u64, Ordering::Relaxed); + if looks.n.is_power_of_two() || looks.n % 4096 == 0 { + let c = COLD.lock().unwrap_or_else(|e| e.into_inner()); + let mb: usize = c.values().flat_map(|c| c.parts.iter().map(|p| p.1)).sum::() >> 20; + let holes = c.values().filter(|c| c.parts.is_empty()).count(); + let s: Vec = STATS.iter().map(|x| x.load(Ordering::Relaxed)).collect(); + crate::xlog_info!( + "watch trap: look {}, {} spans read-only ({mb} MB) or holes ({holes}), this look {} of {} MB looked at in {} pieces; so far {} faults, {} made read-only, {} given back by changes, {} pending reads, {} regions not given back, {} refused", + looks.n, c.len(), hot >> 20, watched >> 20, pieces.len(), s[0], s[1], s[2], PENDING.lock().unwrap_or_else(|e| e.into_inner()).len(), s[4], s[5] + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{GetWriteWatch, VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE}; + const WRITE_WATCH_FLAG_RESET: u32 = 1; + + #[test] + fn hot_pieces_skip_read_only_spans_and_split_at_blocks() { + let b = 0x4000_0000usize; + let ranges = [(b, 3 * BLOCK)]; + let cold = BTreeMap::from([(b + BLOCK, b + 2 * BLOCK)]); + assert_eq!(hot_pieces(&ranges, &cold), vec![(b, BLOCK), (b + 2 * BLOCK, BLOCK)]); + let cold = BTreeMap::from([(b + 0x1000, b + 0x3000)]); + assert_eq!(hot_pieces(&[(b, 0x5000)], &cold), vec![(b, 0x1000), (b + 0x3000, 0x2000)]); + } + + /// (from the top of the address space: tests that free an address and expect it to stay free + /// sit low) + const MEM_TOP_DOWN: u32 = 0x10_0000; + + /// The looks keep one state per process (one scanner in a title): tests that look take turns. + static SERIAL: Mutex<()> = Mutex::new(()); + + /// A test's turn, with the clean counts of an earlier test's blocks gone: `MEM_TOP_DOWN` can + /// give the next test the same base, which then started with a count already part way up. + fn serial() -> std::sync::MutexGuard<'static, ()> { + let g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + LOOKS.lock().unwrap_or_else(|e| e.into_inner()).clean.clear(); + g + } + + unsafe fn written(base: usize, n: usize) -> Vec { + let mut buf = vec![std::ptr::null_mut::(); 4096]; + let (mut k, mut g) = (buf.len(), 0u32); + assert_eq!(GetWriteWatch(WRITE_WATCH_FLAG_RESET, base as *const c_void, n, buf.as_mut_ptr(), &mut k, &mut g), 0); + buf[..k].iter().map(|&p| p as usize).collect() + } + + /// A block left clean goes read-only and out of the looks; a write to it faults once, is + /// seen by the next look, and the block is looked at again. A read into it (pinned) works. + #[test] + fn a_cold_block_traps_its_first_write_and_the_look_sees_it() { + let _serial = serial(); + unsafe { + const MEM_WRITE_WATCH: u32 = 0x20_0000; + let raw = VirtualAlloc(std::ptr::null(), 3 * BLOCK, MEM_RESERVE | MEM_WRITE_WATCH | MEM_TOP_DOWN, PAGE_READWRITE) as usize; + assert_ne!(raw, 0); + VirtualFree(raw as *mut c_void, 0, MEM_RELEASE); + let base = (raw + BLOCK - 1) & !(BLOCK - 1); + let at = VirtualAlloc(base as *const c_void, BLOCK, MEM_RESERVE | windows_sys::Win32::System::Memory::MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + assert_eq!(at, base); + let ranges = [(base, BLOCK)]; + let mut dirty = Vec::new(); + let take = |a: usize, n: usize, d: &mut Vec| d.extend(written(a, n)); + for _ in 0..COLD_LOOKS + 1 { + look(&ranges, &mut dirty, 0x1000, take); + } + assert!(dirty.is_empty()); + assert!(COLD.lock().unwrap().contains_key(&base), "clean block made read-only"); + std::ptr::write_volatile((base + 5 * 0x1000) as *mut u8, 9); + assert!(!COLD.lock().unwrap().contains_key(&base), "the write gave it back"); + look(&ranges, &mut dirty, 0x1000, take); + assert_eq!(dirty, vec![base + 5 * 0x1000]); + // a pinned read target is writable for the kernel and never made read-only + dirty.clear(); + for _ in 0..COLD_LOOKS + 1 { + look(&ranges, &mut dirty, 0x1000, take); + } + assert!(COLD.lock().unwrap().contains_key(&base)); + pin(base + 0x8000, 0x1000, 1); + changed_now(base + 0x8000, 0x1000); + assert!(!COLD.lock().unwrap().contains_key(&base)); + for _ in 0..COLD_LOOKS + 1 { + look(&ranges, &mut dirty, 0x1000, take); + } + assert!(!COLD.lock().unwrap().contains_key(&base), "pinned"); + pin(base + 0x8000, 0x1000, -1); + changed_now(base, BLOCK); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + + /// A clean block that cannot be made read-only (here: committed read-only by the title) is + /// tried once, then again only after another COLD_LOOKS looks, not at every look. + #[test] + fn a_block_that_cannot_be_made_read_only_waits_before_the_next_try() { + let _serial = serial(); + unsafe { + const MEM_WRITE_WATCH: u32 = 0x20_0000; + use windows_sys::Win32::System::Memory::MEM_COMMIT; + let raw = VirtualAlloc(std::ptr::null(), 3 * BLOCK, MEM_RESERVE | MEM_WRITE_WATCH | MEM_TOP_DOWN, PAGE_READWRITE) as usize; + assert_ne!(raw, 0); + let base = (raw + BLOCK - 1) & !(BLOCK - 1); + assert_eq!(VirtualAlloc(base as *const c_void, BLOCK, MEM_COMMIT, PAGE_READONLY) as usize, base); + let ranges = [(base, BLOCK)]; + let mut dirty = Vec::new(); + let take = |_: usize, _: usize, _: &mut Vec| {}; + let refused = || STATS[5].load(Ordering::Relaxed); + let before = refused(); + for _ in 0..COLD_LOOKS { + look(&ranges, &mut dirty, 0x1000, take); + } + assert_eq!(refused() - before, 1, "tried once it was clean for COLD_LOOKS looks"); + for _ in 1..COLD_LOOKS { + look(&ranges, &mut dirty, 0x1000, take); + } + assert_eq!(refused() - before, 1, "not tried again at every look"); + look(&ranges, &mut dirty, 0x1000, take); + assert_eq!(refused() - before, 2, "tried again after COLD_LOOKS more looks"); + assert!(!COLD.lock().unwrap().contains_key(&base)); + VirtualFree(raw as *mut c_void, 0, MEM_RELEASE); + } + } + + /// A clean block with nothing committed is a hole: out of the looks with nothing protected, + /// until a commit in it (through a guard) gives it back; the write after the commit is seen. + #[test] + fn a_reserved_block_leaves_the_looks_until_a_commit() { + let _serial = serial(); + unsafe { + const MEM_WRITE_WATCH: u32 = 0x20_0000; + use windows_sys::Win32::System::Memory::MEM_COMMIT; + let raw = VirtualAlloc(std::ptr::null(), 3 * BLOCK, MEM_RESERVE | MEM_WRITE_WATCH | MEM_TOP_DOWN, PAGE_READWRITE) as usize; + assert_ne!(raw, 0); + let base = (raw + BLOCK - 1) & !(BLOCK - 1); + let ranges = [(base, BLOCK)]; + let mut dirty = Vec::new(); + let looked = std::cell::Cell::new(0usize); + let take = |a: usize, n: usize, d: &mut Vec| { + looked.set(looked.get() + n); + d.extend(written(a, n)); + }; + for _ in 0..COLD_LOOKS { + look(&ranges, &mut dirty, 0x1000, take); + } + assert!(COLD.lock().unwrap().get(&base).is_some_and(|c| c.parts.is_empty()), "a hole"); + looked.set(0); + look(&ranges, &mut dirty, 0x1000, take); + assert_eq!(looked.get(), 0, "out of the looks"); + // what guard() does around a commit (it is a no-op here: the switch is off in tests) + hold(base + 0x3000, 0x1000); + assert_eq!(VirtualAlloc((base + 0x3000) as *const c_void, 0x1000, MEM_COMMIT, PAGE_READWRITE) as usize, base + 0x3000); + pin(base + 0x3000, 0x1000, -1); + assert!(!COLD.lock().unwrap().contains_key(&base), "the commit gave it back"); + std::ptr::write_volatile((base + 0x3000) as *mut u8, 7); + look(&ranges, &mut dirty, 0x1000, take); + assert_eq!(dirty, vec![base + 0x3000]); + changed_now(base, BLOCK); + VirtualFree(raw as *mut c_void, 0, MEM_RELEASE); + } + } + + /// A read-only block with 64 KiB decommitted inside it by a path that did not tell the trap + /// (VirtualProtect of the whole span then fails): giving it back still makes the pages that + /// are left writable, not read-only with no span to catch their writes. + #[test] + fn a_partly_decommitted_cold_block_is_given_back_where_committed() { + let _serial = serial(); + unsafe { + const MEM_WRITE_WATCH: u32 = 0x20_0000; + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_DECOMMIT}; + let raw = VirtualAlloc(std::ptr::null(), 3 * BLOCK, MEM_RESERVE | MEM_WRITE_WATCH | MEM_TOP_DOWN, PAGE_READWRITE) as usize; + assert_ne!(raw, 0); + VirtualFree(raw as *mut c_void, 0, MEM_RELEASE); + let base = (raw + BLOCK - 1) & !(BLOCK - 1); + assert_eq!(VirtualAlloc(base as *const c_void, BLOCK, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize, base); + let ranges = [(base, BLOCK)]; + let mut dirty = Vec::new(); + let take = |a: usize, n: usize, d: &mut Vec| d.extend(written(a, n)); + for _ in 0..COLD_LOOKS + 1 { + look(&ranges, &mut dirty, 0x1000, take); + } + assert!(COLD.lock().unwrap().contains_key(&base)); + assert_ne!(VirtualFree((base + 0x10000) as *mut c_void, 0x10000, MEM_DECOMMIT), 0); + changed_now(base, BLOCK); + for at in [base, base + 0x20000, base + BLOCK - 0x1000] { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + assert_ne!(VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)), 0); + assert_eq!(m.Protect, PAGE_READWRITE, "{at:#x} given back"); + } + std::ptr::write_volatile((base + 0x20000) as *mut u8, 1); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + + /// A pending read whose OVERLAPPED is used for the next read is over: its buffer is reported + /// and unpinned then, not when the second read ends. One still pending stays with the looks. + #[test] + fn an_overlapped_used_again_retires_its_earlier_read() { + let _serial = serial(); + let pinned = |a: usize| PINS.lock().unwrap().contains_key(&(a & !(BLOCK - 1))); + let pending = || PENDING.lock().unwrap().len(); + unsafe { + // two buffers in blocks of their own, an OVERLAPPED and a byte count in a third + let mem = VirtualAlloc(std::ptr::null(), 4 * BLOCK, MEM_RESERVE | windows_sys::Win32::System::Memory::MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(mem, 0); + let base = (mem + BLOCK - 1) & !(BLOCK - 1); + let (first, second, ov) = (base + 0x3000, base + BLOCK + 0x5000, base + 2 * BLOCK); + let read = ov + 0x100; + let start = |buf: usize| { + retire_reused(ov); + hold(buf, 0x2000); + hold(read, 4); + hold(ov, OVERLAPPED_LEN); + *(ov as *mut usize) = STATUS_PENDING; + PENDING.lock().unwrap().push((ov, buf, 0x2000, read)); + }; + start(first); + let mut dirty = Vec::new(); + look(&[], &mut dirty, 0x1000, |_, _, _| {}); + assert!(dirty.is_empty() && pinned(first) && pending() == 1, "a pending read stays pinned"); + // used again while its status says pending: nothing is retired + retire_reused(ov); + assert!(pinned(first) && pending() == 1); + // the first read ends, the title starts the second with the same OVERLAPPED + *(ov as *mut usize) = 0; + start(second); + assert!(!pinned(first) && pinned(second) && pending() == 1, "the first read is retired at the second's start"); + look(&[], &mut dirty, 0x1000, |_, _, _| {}); + assert_eq!(dirty, vec![first, first + 0x1000], "the first buffer is reported once, the second not yet"); + dirty.clear(); + *(ov as *mut usize) = 0; + look(&[], &mut dirty, 0x1000, |_, _, _| {}); + assert_eq!(dirty, vec![second, second + 0x1000]); + assert!(!pinned(second) && !pinned(ov) && pending() == 0); + VirtualFree(mem as *mut c_void, 0, MEM_RELEASE); + } + } +} diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 2ae4fe1b66..d397e37364 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -814,6 +814,8 @@ unsafe fn read_own(at: usize, out: *mut u8, len: usize) -> bool { fn writable(p: usize, n: usize) -> bool { let Some(end) = p.checked_add(n) else { return false }; crate::hle::kernelx::lazy::ensure(p, n); + // a read-only block of the watch trap is writable here: the copy into it faults and is let through + let _trap = crate::hle::d3d12x::watch_trap::guard(p, n); if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(p, n)) { return true; } diff --git a/crates/xcl/src/hle/dstorage/parallel.rs b/crates/xcl/src/hle/dstorage/parallel.rs index 198f4a86e8..651265be4b 100644 --- a/crates/xcl/src/hle/dstorage/parallel.rs +++ b/crates/xcl/src/hle/dstorage/parallel.rs @@ -462,6 +462,9 @@ impl<'a> Pipeline<'a> { let at = task.req.destination as usize; // The title can unmap the destination while a decoder runs. The late // check resolves lazy pages, and the kernel copy handles a subsequent unmap. + // (The kernel copy cannot be let through a watch-trap read-only block on its + // fault: the destination stays writable from the check to the end of the copy.) + let _trap = crate::hle::d3d12x::watch_trap::guard(at, n); if writable(at, n) && (n == 0 || write_destination(at, &payload.bytes[..n])) { Ok(()) } else { diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 4144a1144e..c5d5f2b40d 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -252,6 +252,7 @@ unsafe fn commit_sparse(a: usize, n: usize, p: u32) -> *mut c_void { } pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: u32, p: u32) -> *mut c_void { + let _trap = crate::hle::d3d12x::watch_trap::guard(addr as usize, size); 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; @@ -415,6 +416,7 @@ fn keep_last_error(f: impl FnOnce() -> R) -> R { /// 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 _trap = crate::hle::d3d12x::watch_trap::guard_free(addr as usize, size); if let Some(ok) = placeholders::free(addr, size, t) { return ok; } @@ -493,10 +495,12 @@ pub unsafe extern "system" fn VirtualAllocEx(proc_: HANDLE, addr: *const c_void, } pub unsafe extern "system" fn VirtualProtect(addr: *const c_void, size: usize, p: u32, old: *mut u32) -> BOOL { + let _trap = crate::hle::d3d12x::watch_trap::guard(addr as usize, size); mem::VirtualProtect(addr, size, sanitize_protect(p), old) } pub unsafe extern "system" fn VirtualProtectEx(proc_: HANDLE, addr: *const c_void, size: usize, p: u32, old: *mut u32) -> BOOL { + let _trap = crate::hle::d3d12x::watch_trap::guard(if proc_ == thr::GetCurrentProcess() { addr as usize } else { 0 }, size); mem::VirtualProtectEx(proc_, addr, size, sanitize_protect(p), old) } @@ -1065,6 +1069,7 @@ 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); } + let _trap = crate::hle::d3d12x::watch_trap::guard(start, end - start); mem::VirtualFree(start as *mut c_void, end - start, mem::MEM_DECOMMIT); } } @@ -1072,6 +1077,7 @@ unsafe fn give_back_homes(away: &mut Away) { /// The page's home, committed again if `move_home_away` gave it back (None: it could not be). unsafe fn home_again(home: usize) -> Option { if lazy_home(home) && !committed_page(home) { + let _trap = crate::hle::d3d12x::watch_trap::guard(home, PHYS_PAGE); if mem::VirtualAlloc(home as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { crate::xlog_warn!("physical page: its home {home:#x} could not be committed again"); return None; @@ -1093,6 +1099,7 @@ unsafe fn commit_homes(home: usize, n: usize) -> bool { if committed_range(home, len) { return true; } + let _trap = crate::hle::d3d12x::watch_trap::guard(home, len); if mem::VirtualAlloc(home as *const c_void, len, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { crate::xlog_warn!("physical pages: {n} at their home {home:#x} could not be committed"); return false; @@ -1208,6 +1215,7 @@ unsafe fn release_at(at: usize) { if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { crate::hle::d3d12x::sparse::decommitted(at, PHYS_PAGE); } + let _trap = crate::hle::d3d12x::watch_trap::guard(at, PHYS_PAGE); mem::VirtualFree(at as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT); } @@ -1223,6 +1231,7 @@ unsafe fn move_away(away: &mut Away, old: usize, at: usize, page: usize, in_uma: return Ok(false); } // (a destination that cannot be committed leaves the page where it was, mapped as before) + let _trap = crate::hle::d3d12x::watch_trap::guard(at, PHYS_PAGE); if !in_uma && mem::VirtualAlloc(at as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { return Err(()); } @@ -1418,6 +1427,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) away.page.insert(p, at); continue; } + let _trap = crate::hle::d3d12x::watch_trap::guard(at, PHYS_PAGE); if !in_uma(at) && mem::VirtualAlloc(at as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); return std::ptr::null_mut(); diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index fa750b9a48..e3952526a4 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -41,6 +41,7 @@ unsafe fn commit(page: usize) -> bool { if !g.remove(&page) { return false; } + let _trap = crate::hle::d3d12x::watch_trap::guard(page, PAGE); !VirtualAlloc(page as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null() } diff --git a/crates/xcl/src/vfs_hooks.rs b/crates/xcl/src/vfs_hooks.rs index 0767cf1e1c..4983b6cd3a 100644 --- a/crates/xcl/src/vfs_hooks.rs +++ b/crates/xcl/src/vfs_hooks.rs @@ -533,8 +533,15 @@ unsafe extern "system" fn hk_read_file(h: *mut c_void, buf: *mut c_void, n: u32, let orig = orig!(O_READ_FILE as F); if !buf.is_null() { crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); + crate::hle::d3d12x::watch_trap::read_start(buf as usize, n as usize, read as usize, ov as usize); } - orig(h, buf, n, read, ov) + let r = orig(h, buf, n, read, ov); + if !buf.is_null() { + let e = GetLastError(); + crate::hle::d3d12x::watch_trap::read_end(buf as usize, n as usize, read as usize, ov as usize, r == 0 && e == 997, r != 0); + SetLastError(e); + } + r } unsafe extern "system" fn hk_delete_file_w(n: *const u16) -> i32 { From c230aa1b206a93e6ee81f7edb7d71343c0d5c6cc Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:13:53 -0500 Subject: [PATCH 2/2] D3D12.X: the watch trap's look walks the read-only spans once A look copied the read-only spans into a new map and then made two map queries per span to find the pieces still to look at. In the late world of title ea3b5e4d that is about 9,000 spans a look and 20 looks a present. hot_pieces now walks the spans once, under the lock, while the ranges ascend (a look's are sorted and disjoint), and starts the walk again for a range that does not. Measured without a GPU, a look with a take that does nothing, 18 GiB watched in 64 ranges, 8,861 spans, 355 blocks left to look at: 336 us before, 40 us after (RTX 5070 Ti machine, release build). In the title, on a tree with the driver-heap windows of #2844 (one untimed run per arm): the write-watch part of a look 1.06 ms against 1.29 ms. Co-Authored-By: Claude Fable 5 --- crates/xcl/src/hle/d3d12x/watch_trap.rs | 85 ++++++++++++++++++++++--- 1 file changed, 77 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/watch_trap.rs b/crates/xcl/src/hle/d3d12x/watch_trap.rs index d87f3788f0..5471c7484e 100644 --- a/crates/xcl/src/hle/d3d12x/watch_trap.rs +++ b/crates/xcl/src/hle/d3d12x/watch_trap.rs @@ -363,20 +363,33 @@ unsafe fn freeze(a: usize, n: usize) -> bool { true } -/// `ranges` minus the read-only spans, as pieces within one block each. -fn hot_pieces(ranges: &[(usize, usize)], cold: &BTreeMap) -> Vec<(usize, usize)> { +/// `ranges` minus the read-only spans (`cold`: by start, `end_of` their ends), as pieces within +/// one block each. The spans are walked once while the ranges ascend, as a look's do: two map +/// queries per span were 0.2 ms a look with 9,000 spans. +fn hot_pieces(ranges: &[(usize, usize)], cold: &BTreeMap, end_of: impl Fn(&V) -> usize) -> Vec<(usize, usize)> { let mut out = Vec::new(); + let all = || cold.iter().map(|(&s, v)| (s, end_of(v))).peekable(); + // `last`: the span with the greatest start up to `seen`; `spans`: the ones after it + let (mut spans, mut last, mut seen) = (all(), None::<(usize, usize)>, 0); for &(base, size) in ranges { let end = base + size; let mut at = base; + if base < seen { + (spans, last) = (all(), None); + } while at < end { + seen = at; + while let Some(&span) = spans.peek().filter(|span| span.0 <= at) { + last = Some(span); + spans.next(); + } let block_end = ((at & !(BLOCK - 1)) + BLOCK).min(end); // the read-only span covering `at`, else the next one starting before `block_end` - if let Some((_, &e)) = cold.range(..=at).next_back().filter(|(_, &e)| e > at) { + if let Some((_, e)) = last.filter(|&(_, e)| e > at) { at = e.min(end); continue; } - let stop = cold.range(at..block_end).next().map_or(block_end, |(&s, _)| s); + let stop = spans.peek().map_or(block_end, |&(s, _)| s.min(block_end)); out.push((at, stop - at)); at = stop; } @@ -406,8 +419,7 @@ pub unsafe fn look(ranges: &[(usize, usize)], dirty: &mut Vec, page: usiz for (buf, n) in report { dirty.extend((buf & !(page - 1)..buf + n).step_by(page)); } - let cold: BTreeMap = COLD.lock().unwrap_or_else(|e| e.into_inner()).iter().map(|(&s, c)| (s, c.end)).collect(); - let pieces = hot_pieces(ranges, &cold); + let pieces = hot_pieces(ranges, &COLD.lock().unwrap_or_else(|e| e.into_inner()), |c| c.end); let watched: usize = ranges.iter().map(|r| r.1).sum(); let hot: usize = pieces.iter().map(|p| p.1).sum(); STATS[3].fetch_add((watched - hot) as u64, Ordering::Relaxed); @@ -490,9 +502,66 @@ mod tests { let b = 0x4000_0000usize; let ranges = [(b, 3 * BLOCK)]; let cold = BTreeMap::from([(b + BLOCK, b + 2 * BLOCK)]); - assert_eq!(hot_pieces(&ranges, &cold), vec![(b, BLOCK), (b + 2 * BLOCK, BLOCK)]); + assert_eq!(hot_pieces(&ranges, &cold, |&e| e), vec![(b, BLOCK), (b + 2 * BLOCK, BLOCK)]); let cold = BTreeMap::from([(b + 0x1000, b + 0x3000)]); - assert_eq!(hot_pieces(&[(b, 0x5000)], &cold), vec![(b, 0x1000), (b + 0x3000, 0x2000)]); + assert_eq!(hot_pieces(&[(b, 0x5000)], &cold, |&e| e), vec![(b, 0x1000), (b + 0x3000, 0x2000)]); + } + + /// The one walk over the spans gives the pieces a query per span gave: spans that start + /// before a range, end past it, lie between ranges or touch each other, and ranges that + /// ascend, overlap or come out of order. + #[test] + fn hot_pieces_walk_matches_a_query_per_span() { + fn by_query(ranges: &[(usize, usize)], cold: &BTreeMap) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + for &(base, size) in ranges { + let end = base + size; + let mut at = base; + while at < end { + let block_end = ((at & !(BLOCK - 1)) + BLOCK).min(end); + if let Some((_, &e)) = cold.range(..=at).next_back().filter(|(_, &e)| e > at) { + at = e.min(end); + continue; + } + let stop = cold.range(at..block_end).next().map_or(block_end, |(&s, _)| s); + out.push((at, stop - at)); + at = stop; + } + } + out + } + let mut x = 0x2545_F491_4F6C_DD1Du64; + let mut next = move |n: usize| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + (x % n as u64) as usize + }; + let b = 0x4000_0000usize; + for round in 0..200 { + // disjoint spans of 1..=600 pages, 0..=700 pages apart, from before the ranges on + let mut cold = BTreeMap::new(); + let mut at = b - 0x40_0000; + for _ in 0..next(60) { + at += next(701) * 0x1000; + let end = at + (1 + next(600)) * 0x1000; + cold.insert(at, end); + at = end; + } + let mut ranges = Vec::new(); + let mut at = b; + for _ in 0..1 + next(8) { + at += next(900) * 0x1000; + let size = (1 + next(1500)) * 0x1000; + ranges.push((at, size)); + // every third round the next range starts inside this one + at += if round % 3 == 2 { size / 2 } else { size }; + } + if round % 5 == 4 { + ranges.reverse(); + } + assert_eq!(hot_pieces(&ranges, &cold, |&e| e), by_query(&ranges, &cold), "round {round}: {ranges:x?} {cold:x?}"); + } } /// (from the top of the address space: tests that free an address and expect it to stay free