From 1b6f6748d9563ce7d5eae97499a48c849e97ff98 Mon Sep 17 00:00:00 2001 From: Enrique Villa Date: Wed, 2 Dec 2026 01:36:56 +0800 Subject: [PATCH 1/2] KernelX, D3D12.X, DirectStorage: opt-in XCL_GUEST_WRITE_GUARD for XCL-protected title pages --- crates/xcl/src/eh.rs | 6 +- crates/xcl/src/hle/d3d12x/cpu_writes.rs | 20 +- crates/xcl/src/hle/d3d12x/frame.rs | 4 +- crates/xcl/src/hle/dstorage.rs | 10 +- crates/xcl/src/hle/dstorage/parallel.rs | 8 +- crates/xcl/src/hle/kernelx.rs | 1 + crates/xcl/src/hle/kernelx/guards.rs | 8 +- crates/xcl/src/hle/kernelx/guest_write.rs | 547 ++++++++++++++++++++++ crates/xcl/src/host.rs | 1 + crates/xcl/src/vfs_hooks.rs | 6 +- crates/xcl/tests/guest_write_probe.rs | 407 ++++++++++++++++ 11 files changed, 997 insertions(+), 21 deletions(-) create mode 100644 crates/xcl/src/hle/kernelx/guest_write.rs create mode 100644 crates/xcl/tests/guest_write_probe.rs diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 3b85cfac35..9c32d28f8d 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -528,10 +528,12 @@ fn is_writable(va: usize, bytes: usize) -> bool { } 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 + (found && m.State == MEM_COMMIT && m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) != 0 - && m.BaseAddress as usize + m.RegionSize >= va + bytes + && m.BaseAddress as usize + m.RegionSize >= va + bytes) + // (pages XCL made read-only: the zeroing faults and is let through, `XCL_GUEST_WRITE_GUARD=1`) + || crate::hle::kernelx::guest_write::writable(va, bytes) } const ILLEGAL_INSTRUCTION: u32 = 0xC000_001D; diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index f92fc5dafd..cf3e30bde9 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -141,10 +141,12 @@ unsafe fn write_now_in(va: usize, words: &[u32], run: &dyn Fn(usize, usize) -> O if !crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); - if VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT { - return; - } - if m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 || (m.BaseAddress as usize + m.RegionSize) < va + bytes { + let rw = VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 + && m.State == MEM_COMMIT + && m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) != 0 + && (m.BaseAddress as usize + m.RegionSize) >= va + bytes; + // (pages XCL made read-only: the store faults and is let through, `XCL_GUEST_WRITE_GUARD=1`) + if !rw && !crate::hle::kernelx::guest_write::writable(va, bytes) { return; } } @@ -181,9 +183,10 @@ unsafe fn u64_writable_now(va: usize) -> bool { if VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT { return false; } - m.Protect & PAGE_GUARD == 0 + (m.Protect & PAGE_GUARD == 0 && m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) != 0 - && (m.BaseAddress as usize).saturating_add(m.RegionSize) >= end + && (m.BaseAddress as usize).saturating_add(m.RegionSize) >= end) + || crate::hle::kernelx::guest_write::writable(va, 8) } /// An 8-byte aligned 64-bit value at `va`, if the memory is still there and writable. @@ -220,10 +223,11 @@ pub(super) fn writable(va: usize, bytes: usize) -> bool { 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; - found + (found && m.State == MEM_COMMIT && m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) != 0 - && m.BaseAddress as usize + m.RegionSize >= va + bytes + && m.BaseAddress as usize + m.RegionSize >= va + bytes) + || crate::hle::kernelx::guest_write::writable(va, bytes) } /// Receipt published only after the worker has applied every deferred store in a submission. diff --git a/crates/xcl/src/hle/d3d12x/frame.rs b/crates/xcl/src/hle/d3d12x/frame.rs index 11f2c9efa9..bbf7a2798e 100644 --- a/crates/xcl/src/hle/d3d12x/frame.rs +++ b/crates/xcl/src/hle/d3d12x/frame.rs @@ -376,7 +376,9 @@ unsafe fn note_signaled(block: *const u8, index: i32) { return; } let out = (block.add(0x10) as *const usize).read_unaligned(); - if writable(out, 4) { + // (pages XCL made read-only or no-access count too, `XCL_GUEST_WRITE_GUARD=1`: the store + // faults and is opened by the protector's handler) + if writable(out, 4) || crate::hle::kernelx::guest_write::writable(out, 4) { (out as *mut i32).write_unaligned(index); } } diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 64fdcd35a7..462dc3f47a 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -893,8 +893,11 @@ unsafe fn write_title(p: usize, bytes: &[u8]) -> bool { fn NtWriteVirtualMemory(process: HANDLE, at: *mut c_void, data: *const c_void, len: usize, done: *mut usize) -> i32; } let mut done = 0usize; - let st = NtWriteVirtualMemory(windows_sys::Win32::System::Threading::GetCurrentProcess(), p as *mut c_void, bytes.as_ptr().cast(), bytes.len(), &mut done); - st >= 0 && done == bytes.len() + crate::hle::kernelx::guest_write::kernel_write("DirectStorage", p, bytes.len(), || { + // SAFETY: the kernel copy returns a status instead of faulting + let st = unsafe { NtWriteVirtualMemory(windows_sys::Win32::System::Threading::GetCurrentProcess(), p as *mut c_void, bytes.as_ptr().cast(), bytes.len(), &mut done) }; + st >= 0 && done == bytes.len() + }) } /// Where the CPU reads or writes `[p, p + n)` of the title's memory for a request: a GPU view of @@ -934,7 +937,8 @@ fn writable(p: usize, n: usize) -> bool { } let rw = 0x04 | 0x08 | 0x40 | 0x80; // PAGE_READWRITE / WRITECOPY / EXECUTE_READWRITE / EXECUTE_WRITECOPY if m.State != MEM_COMMIT || m.Protect & rw == 0 || m.Protect & 0x100 != 0 { - return false; + // (pages XCL made read-only count, `XCL_GUEST_WRITE_GUARD=1`) + return crate::hle::kernelx::guest_write::writable(p, n); } at = m.BaseAddress as usize + m.RegionSize; } diff --git a/crates/xcl/src/hle/dstorage/parallel.rs b/crates/xcl/src/hle/dstorage/parallel.rs index c645beb572..950b179cd4 100644 --- a/crates/xcl/src/hle/dstorage/parallel.rs +++ b/crates/xcl/src/hle/dstorage/parallel.rs @@ -488,10 +488,10 @@ extern "system" { fn write_destination(at: usize, bytes: &[u8]) -> bool { let mut done = 0; // Use the current-process handle so an access fault is returned as a status. - let status = unsafe { - NtWriteVirtualMemory(GetCurrentProcess(), at as *mut c_void, bytes.as_ptr().cast(), bytes.len(), &mut done) - }; - status >= 0 && done == bytes.len() + crate::hle::kernelx::guest_write::kernel_write("DirectStorage", at, bytes.len(), || { + let status = unsafe { NtWriteVirtualMemory(GetCurrentProcess(), at as *mut c_void, bytes.as_ptr().cast(), bytes.len(), &mut done) }; + status >= 0 && done == bytes.len() + }) } #[cfg(test)] diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 27f1489099..d9e1cc30f6 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -112,6 +112,7 @@ pub mod alias; pub mod guards; mod sections; pub mod lazy; +pub mod guest_write; pub const MEM_TITLE: u32 = 0x4000_0000; const STD_ALLOC_MASK: u32 = 0x1000 | 0x2000 | 0x8_0000 | 0x10_0000 | 0x20_0000 | 0x100_0000; /// Standard Win32 page access + PAGE_GUARD (0x100). Strips console PAGE_GRAPHICS_* bits as well diff --git a/crates/xcl/src/hle/kernelx/guards.rs b/crates/xcl/src/hle/kernelx/guards.rs index 309adc18df..0c7f1b7856 100644 --- a/crates/xcl/src/hle/kernelx/guards.rs +++ b/crates/xcl/src/hle/kernelx/guards.rs @@ -95,6 +95,12 @@ fn writable(view: usize) -> bool { n != 0 && m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE } +/// Whether the 64 KiB page at `at` is a guarded view (`guest_write`: XCL may have made it +/// read-only, and its handler opens it on a write fault). One atomic load while nothing is watched. +pub(super) fn is_view(at: usize) -> bool { + WATCHING.load(Ordering::Acquire) && with(|s| s.at.contains_key(&(at & !(PAGE - 1)))) +} + /// Physical page `page` is shown at `view` (64 KiB aligned): writes there are caught from now on. /// A view not committed yet cannot be guarded; `committed` notes it when it is. pub fn watch(page: usize, view: usize) { @@ -224,7 +230,7 @@ pub fn open_until_done(opened: Opened, ov: usize) { /// Whether the overlapped I/O at `ov` is still going on (its `Internal` is STATUS_PENDING). The /// title may have freed the OVERLAPPED once it is done, so it is read without faulting. -fn still_pending(ov: usize) -> bool { +pub(super) fn still_pending(ov: usize) -> bool { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; const STATUS_PENDING: usize = 0x103; diff --git a/crates/xcl/src/hle/kernelx/guest_write.rs b/crates/xcl/src/hle/kernelx/guest_write.rs new file mode 100644 index 0000000000..81cca1a119 --- /dev/null +++ b/crates/xcl/src/hle/kernelx/guest_write.rs @@ -0,0 +1,547 @@ +//! Writes into the title's memory by XCL or by a kernel call, where XCL itself may have made the +//! pages read-only or no-access (`XCL_GUEST_WRITE_GUARD=1`; default off). +//! +//! XCL protects title pages to learn about CPU writes (`guards`, `XCL_PAGE_ALIAS=1`) and may do +//! so for more memory (read-only cold blocks, no-access GPU-written pages). A user-mode store +//! there faults and the protector's handler opens the page. A kernel call does not fault: on a +//! read-only or no-access page `ReadFile` (buffered, NO_BUFFERING, overlapped) and +//! `WriteProcessMemory` fail with ERROR_NOACCESS, `NtReadFile` with STATUS_ACCESS_VIOLATION, +//! `NtWriteVirtualMemory` with STATUS_PARTIAL_COPY and `recv`/`recvfrom` with WSAEFAULT; nothing +//! lands and no handler runs (`tests/guest_write_probe.rs`, Windows 11). So, behind the switch: +//! +//! - `writable` answers "can XCL write here" for the pre-checks that asked `VirtualQuery` for a +//! writable protection: a page XCL protected counts as writable (a store faults and is opened); +//! - `open` brackets a kernel call's (or XCL's) write: lazy pages are committed and guarded views +//! opened (`lazy::ensure`, as without the switch), and pages of ranges a protector registered +//! are pinned (the protector must not protect them again) and touched by a no-op atomic RMW, +//! so the protector's fault handler runs before the kernel writes; +//! - `kernel_write` is `open` around a write that returns a status, with one retry; +//! - `bounce` lets a call that writes a buffer write XCL's own buffer first (sockets). +//! +//! A protector (the future read-only cold blocks) calls `register` / `unregister` for the ranges +//! whose pages it may protect, asks `is_pinned` before protecting a page again, and makes a page +//! writable from its vectored handler on a write fault (access 1) there. Off, every function +//! here does what the code did before: `writable` is false, `open` is `lazy::ensure`. + +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock, RwLock}; + +use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE}; + +/// the protection granule (`VirtualProtect` works on 4 KiB pages) +pub const STEP: usize = 0x1000; + +/// `XCL_GUEST_WRITE_GUARD=1` turns the guest-write guard on (default: off). +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_GUEST_WRITE_GUARD").is_ok_and(|v| v.trim() == "1")) +} + +/// ranges a protector registered: start → end +static RANGES: RwLock> = RwLock::new(BTreeMap::new()); +/// Whether any range was ever registered: `open` takes no lock before then. +static ANY: AtomicBool = AtomicBool::new(false); +/// 4 KiB pages pinned writable by a write going on → how many writes +static PINS: Mutex>> = Mutex::new(None); +/// overlapped reads into registered ranges: (the OVERLAPPED, its pins), released when done +static PENDING: Mutex)>> = Mutex::new(Vec::new()); +/// calls a retry repaired, and calls that still failed (logged, a few each) +static REPAIRED: AtomicUsize = AtomicUsize::new(0); +static FAILED: AtomicUsize = AtomicUsize::new(0); + +/// `[p, p + len)` may hold pages a protector makes read-only or no-access. +pub fn register(p: usize, len: usize) { + if len == 0 { + return; + } + ANY.store(true, Ordering::Release); + let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner()); + insert_range(&mut g, p, p.saturating_add(len)); +} + +/// `[p, p + len)` is no longer protected (call it before the memory is freed or decommitted). +pub fn unregister(p: usize, len: usize) { + let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner()); + remove_range(&mut g, p, p.saturating_add(len)); +} + +fn insert_range(m: &mut BTreeMap, mut lo: usize, mut hi: usize) { + // merge with every range that touches [lo, hi) + let touching: Vec<(usize, usize)> = m.range(..=hi).rev().take_while(|&(_, &e)| e >= lo).map(|(&s, &e)| (s, e)).collect(); + for (s, e) in touching { + m.remove(&s); + lo = lo.min(s); + hi = hi.max(e); + } + m.insert(lo, hi); +} + +fn remove_range(m: &mut BTreeMap, lo: usize, hi: usize) { + let hit: Vec<(usize, usize)> = m.range(..hi).rev().take_while(|&(_, &e)| e > lo).map(|(&s, &e)| (s, e)).collect(); + for (s, e) in hit { + m.remove(&s); + if s < lo { + m.insert(s, lo); + } + if e > hi { + m.insert(hi, e); + } + } +} + +fn in_ranges(m: &BTreeMap, at: usize) -> bool { + m.range(..=at).next_back().is_some_and(|(_, &e)| at < e) +} + +/// Whether XCL may have protected the page at `at` (a registered range or a guarded view). +pub fn xcl_protected(at: usize) -> bool { + (ANY.load(Ordering::Acquire) && in_ranges(&RANGES.read().unwrap_or_else(|e| e.into_inner()), at)) || super::guards::is_view(at) +} + +/// Whether a protector must leave the 4 KiB page at `at` writable: a write is going on there. +pub fn is_pinned(at: usize) -> bool { + release_done(); + PINS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(&(at & !(STEP - 1)))) +} + +/// One region `VirtualQuery` describes: [base, end), committed?, protection. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Region { + pub base: usize, + pub end: usize, + pub committed: bool, + pub protect: u32, +} + +fn query(at: usize) -> Option { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: VirtualQuery only reads the address space description. + if unsafe { VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 { + return None; + } + let base = m.BaseAddress as usize; + Some(Region { base, end: base.saturating_add(m.RegionSize), committed: m.State == MEM_COMMIT, protect: m.Protect }) +} + +const WRITES: u32 = PAGE_READWRITE | PAGE_EXECUTE_READWRITE | 0x08 | 0x80; // + WRITECOPY, EXECUTE_WRITECOPY +const PROTECTED: u32 = PAGE_READONLY | PAGE_NOACCESS | PAGE_EXECUTE_READ; + +/// Whether every byte of `[p, p + n)` is committed and either writable now or on a page XCL +/// protected (`xcl`). `query` describes the region at an address. +pub(crate) fn covers(p: usize, n: usize, mut query: impl FnMut(usize) -> Option, xcl: impl Fn(usize) -> bool) -> bool { + let Some(end) = p.checked_add(n) else { return false }; + let mut at = p; + while at < end { + let Some(r) = query(at) else { return false }; + if !r.committed || r.protect & PAGE_GUARD != 0 || r.end <= at { + return false; + } + let stop = r.end.min(end); + if r.protect & WRITES == 0 { + if r.protect & PROTECTED == 0 { + return false; + } + let mut page = at & !(STEP - 1); + while page < stop { + if !xcl(page) { + return false; + } + let Some(next) = page.checked_add(STEP) else { break }; + page = next; + } + } + at = stop; + } + true +} + +/// With the switch on: whether XCL may write `[p, p + n)` – committed, and writable or protected +/// by XCL (a store there faults and is opened; a kernel call goes through `open`). Off: false, so +/// a pre-check `old || writable(..)` is the old one. +pub fn writable(p: usize, n: usize) -> bool { + enabled() && n > 0 && covers(p, n, query, xcl_protected) +} + +/// A write to `[p, p + n)` going on: lazy pages committed and guarded views open (`lazy::ensure`), +/// pins on pages of registered ranges. Dropped when the write is over. +#[must_use = "the pages stay open only while this lives"] +pub struct Bracket { + opened: Option, + pins: Vec, +} + +impl Drop for Bracket { + fn drop(&mut self) { + unpin(std::mem::take(&mut self.pins)); + } +} + +impl Bracket { + /// An overlapped read (`ov`) writes after its call returned: the pages stay open until done. + pub fn keep_until_done(mut self, ov: usize) { + if let Some(o) = self.opened.take() { + super::guards::open_until_done(o, ov); + } + let pins = std::mem::take(&mut self.pins); + if !pins.is_empty() { + PENDING.lock().unwrap_or_else(|e| e.into_inner()).push((ov, pins)); + } + } + + /// pages of registered ranges this write holds open + pub fn pinned(&self) -> usize { + self.pins.len() + } +} + +fn unpin(pins: Vec) { + if pins.is_empty() { + return; + } + let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + for p in pins { + if let Some(c) = m.get_mut(&p) { + *c -= 1; + if *c == 0 { + m.remove(&p); + } + } + } +} + +fn release_done() { + let done: Vec> = { + let mut g = PENDING.lock().unwrap_or_else(|e| e.into_inner()); + if g.is_empty() { + return; + } + let (done, pending): (Vec<_>, Vec<_>) = std::mem::take(&mut *g).into_iter().partition(|&(ov, _)| !super::guards::still_pending(ov)); + *g = pending; + done.into_iter().map(|(_, p)| p).collect() + }; + for p in done { + unpin(p); + } +} + +/// Make each committed 4 KiB page of `[p, p + n)` that is not writable now and lies in `pins` +/// take a write fault in user mode: a no-op atomic RMW, so the protector's handler opens it. +unsafe fn touch(p: usize, n: usize, pins: &[usize]) { + for &page in pins { + let Some(r) = query(page) else { continue }; + if r.committed && r.protect & WRITES == 0 && r.protect & PROTECTED != 0 { + let at = page.max(p); + debug_assert!(at < p + n); + (*(at as *const AtomicU8)).fetch_add(0, Ordering::Relaxed); + } + } +} + +/// `[p, p + n)` is about to be written by a kernel call or by XCL (see the module's comment). +pub fn open(p: usize, n: usize) -> Bracket { + open_with(enabled(), p, n) +} + +pub(crate) fn open_with(on: bool, p: usize, n: usize) -> Bracket { + let opened = Some(super::lazy::ensure(p, n)); + if !on || n == 0 || !ANY.load(Ordering::Acquire) { + return Bracket { opened, pins: Vec::new() }; + } + release_done(); + let end = p.saturating_add(n); + let pins: Vec = { + let g = RANGES.read().unwrap_or_else(|e| e.into_inner()); + let mut v = Vec::new(); + let mut page = p & !(STEP - 1); + while page < end { + if in_ranges(&g, page) { + v.push(page); + } + let Some(next) = page.checked_add(STEP) else { break }; + page = next; + } + v + }; + if !pins.is_empty() { + let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + for &page in &pins { + *m.entry(page).or_default() += 1; + } + } + // pinned first: the protector cannot protect a page again between its fault and the write + unsafe { touch(p, n, &pins) }; + Bracket { opened, pins } +} + +/// A write into `[p, p + n)` that returns whether it worked (`NtWriteVirtualMemory`). With the +/// switch on it is bracketed by `open` (which also closes the window in which `guards` could +/// guard a view again between a caller's `writable` check and the write), and a failure over +/// pages XCL protected is retried once after touching them again, and logged. Off: `write()`. +pub fn kernel_write(what: &str, p: usize, n: usize, mut write: impl FnMut() -> bool) -> bool { + kernel_write_with(enabled(), what, p, n, &mut write) +} + +pub(crate) fn kernel_write_with(on: bool, what: &str, p: usize, n: usize, write: &mut dyn FnMut() -> bool) -> bool { + if !on { + // (off: the call alone, as before the switch) + return write(); + } + let b = open_with(on, p, n); + if write() { + return true; + } + if !((p & !(STEP - 1))..p.saturating_add(n)).step_by(STEP).any(xcl_protected) { + return false; + } + unsafe { touch(p, n, &b.pins) }; + let ok = write(); + let count = if ok { &REPAIRED } else { &FAILED }; + if count.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("guest write: {what} into {p:#x}+{n:#x} failed over pages XCL protected; retried: {}", if ok { "written" } else { "failed again" }); + } + drop(b); + ok +} + +/// A call that writes up to `n` bytes at `buf` (a socket receive): when the buffer lies on pages +/// XCL protected, `call` writes XCL's own buffer instead and the bytes it reports are copied in +/// by a user-mode store (which faults and is opened). Returns `call`'s result. +pub unsafe fn bounce(buf: *mut u8, n: usize, call: impl FnOnce(*mut u8) -> i32) -> i32 { + bounce_with(enabled(), buf, n, call) +} + +pub(crate) unsafe fn bounce_with(on: bool, buf: *mut u8, n: usize, call: impl FnOnce(*mut u8) -> i32) -> i32 { + let p = buf as usize; + if !on || buf.is_null() || n == 0 || !((p & !(STEP - 1))..p.saturating_add(n)).step_by(STEP).any(xcl_protected) { + return call(buf); + } + let mut own = vec![0u8; n]; + let r = call(own.as_mut_ptr()); + if r > 0 { + let got = (r as usize).min(n); + let _b = open_with(on, p, got); + std::ptr::copy_nonoverlapping(own.as_ptr(), buf, got); + } + r +} + +static O_RECV: AtomicUsize = AtomicUsize::new(0); +static O_RECVFROM: AtomicUsize = AtomicUsize::new(0); + +type Recv = unsafe extern "system" fn(usize, *mut u8, i32, i32) -> i32; +type RecvFrom = unsafe extern "system" fn(usize, *mut u8, i32, i32, *mut c_void, *mut i32) -> i32; + +/// ws2_32!recv (the title imports it by ordinal 16): into XCL's buffer over protected pages. +unsafe extern "system" fn hk_recv(s: usize, buf: *mut u8, len: i32, flags: i32) -> i32 { + let orig: Recv = std::mem::transmute::(O_RECV.load(Ordering::Acquire)); + if len <= 0 { + return orig(s, buf, len, flags); + } + bounce(buf, len as usize, |b| unsafe { orig(s, b, len, flags) }) +} + +/// ws2_32!recvfrom (ordinal 17), as `hk_recv`. +unsafe extern "system" fn hk_recvfrom(s: usize, buf: *mut u8, len: i32, flags: i32, from: *mut c_void, fromlen: *mut i32) -> i32 { + let orig: RecvFrom = std::mem::transmute::(O_RECVFROM.load(Ordering::Acquire)); + if len <= 0 { + return orig(s, buf, len, flags, from, fromlen); + } + bounce(buf, len as usize, |b| unsafe { orig(s, b, len, flags, from, fromlen) }) +} + +/// With the switch on: hook `recv` / `recvfrom` process-wide (the socket receives the title +/// imports straight from ws2_32; a kernel write into a protected page fails with WSAEFAULT). +/// Call once, before the title runs. Off: nothing. +pub fn install() { + if !enabled() { + return; + } + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| unsafe { + let mut failed = Vec::new(); + for (name, detour, orig) in [("recv", hk_recv as usize, &O_RECV), ("recvfrom", hk_recvfrom as usize, &O_RECVFROM)] { + if let Err(e) = crate::hooks::hook("ws2_32.dll", name, detour, orig) { + failed.push(e); + } + } + if failed.is_empty() { + crate::xlog_info!("XCL_GUEST_WRITE_GUARD=1: XCL's and the kernel's writes into pages XCL protected are bracketed; recv/recvfrom bounce through XCL's buffer there"); + } else { + crate::xlog_warn!("XCL_GUEST_WRITE_GUARD=1: socket receive hooks missing – {}", failed.join("; ")); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; + use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, RemoveVectoredExceptionHandler, EXCEPTION_POINTERS}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, VirtualProtect, MEM_RELEASE, MEM_RESERVE}; + + /// the registry is one per process: the tests that register run one at a time + static SERIAL: Mutex<()> = Mutex::new(()); + + fn r(base: usize, end: usize, protect: u32) -> Region { + Region { base, end, committed: true, protect } + } + + fn regions(list: Vec) -> impl FnMut(usize) -> Option { + move |at| list.iter().copied().find(|r| (r.base..r.end).contains(&at)) + } + + #[test] + fn writable_memory_counts_and_read_only_counts_only_where_xcl_protected_it() { + let rw = || regions(vec![r(0x10000, 0x20000, PAGE_READWRITE)]); + assert!(covers(0x10000, 0x10000, rw(), |_| false)); + assert!(!covers(0x10000, 0x10001, rw(), |_| false), "past the region: nothing there"); + let mixed = || regions(vec![r(0x10000, 0x12000, PAGE_READWRITE), r(0x12000, 0x14000, PAGE_READONLY), r(0x14000, 0x15000, PAGE_NOACCESS)]); + assert!(!covers(0x11000, 0x2000, mixed(), |_| false), "read-only, not XCL's"); + assert!(covers(0x11000, 0x4000, mixed(), |a| (0x12000..0x15000).contains(&a))); + assert!(!covers(0x11000, 0x4000, mixed(), |a| a == 0x12000), "one 4 KiB page of the read-only run is not XCL's"); + let guard = regions(vec![r(0x10000, 0x20000, PAGE_READWRITE | PAGE_GUARD)]); + assert!(!covers(0x10000, 8, guard, |_| true), "a guard page is never written for the title"); + let reserved = regions(vec![Region { base: 0x10000, end: 0x20000, committed: false, protect: 0 }]); + assert!(!covers(0x10000, 8, reserved, |_| true), "not committed: unmapped stays unmapped"); + assert!(!covers(usize::MAX - 2, 8, |_| None, |_| true)); + } + + #[test] + fn ranges_merge_and_split() { + let mut m = BTreeMap::new(); + insert_range(&mut m, 0x1000, 0x3000); + insert_range(&mut m, 0x3000, 0x5000); + insert_range(&mut m, 0x8000, 0x9000); + assert_eq!(m.iter().map(|(&a, &b)| (a, b)).collect::>(), vec![(0x1000, 0x5000), (0x8000, 0x9000)]); + remove_range(&mut m, 0x2000, 0x8800); + assert_eq!(m.iter().map(|(&a, &b)| (a, b)).collect::>(), vec![(0x1000, 0x2000), (0x8800, 0x9000)]); + assert!(in_ranges(&m, 0x1fff) && !in_ranges(&m, 0x2000) && in_ranges(&m, 0x8800) && !in_ranges(&m, 0x9000)); + } + + /// A stand-in protector: read-only pages in `[LO, LO + SIZE)`, opened by a write fault. + static LO: AtomicUsize = AtomicUsize::new(0); + static FAULTS: AtomicUsize = AtomicUsize::new(0); + const SIZE: usize = 0x1_0000; + + unsafe extern "system" fn protector(info: *mut EXCEPTION_POINTERS) -> i32 { + let r = &*(*info).ExceptionRecord; + let lo = LO.load(Ordering::Acquire); + if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1 && lo != 0 && (lo..lo + SIZE).contains(&r.ExceptionInformation[1]) { + FAULTS.fetch_add(1, Ordering::AcqRel); + let mut old = 0; + VirtualProtect((r.ExceptionInformation[1] & !(STEP - 1)) as *const c_void, STEP, PAGE_READWRITE, &mut old); + return -1; + } + 0 + } + + struct Protected(usize, *mut c_void); + impl Protected { + unsafe fn new(p: u32) -> Protected { + let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + let mut old = 0; + VirtualProtect(base as *const c_void, SIZE, p, &mut old); + FAULTS.store(0, Ordering::Release); + LO.store(base, Ordering::Release); + register(base, SIZE); + Protected(base, AddVectoredExceptionHandler(1, Some(protector))) + } + } + impl Drop for Protected { + fn drop(&mut self) { + unregister(self.0, SIZE); + LO.store(0, Ordering::Release); + unsafe { + RemoveVectoredExceptionHandler(self.1); + VirtualFree(self.0 as *mut c_void, 0, MEM_RELEASE); + } + } + } + + #[link(name = "ntdll", kind = "raw-dylib")] + extern "system" { + fn NtWriteVirtualMemory(process: *mut c_void, at: *mut c_void, data: *const c_void, len: usize, done: *mut usize) -> i32; + } + + unsafe fn nt_write(at: usize, bytes: &[u8]) -> bool { + let mut done = 0; + let st = NtWriteVirtualMemory(windows_sys::Win32::System::Threading::GetCurrentProcess(), at as *mut c_void, bytes.as_ptr().cast(), bytes.len(), &mut done); + st >= 0 && done == bytes.len() + } + + #[test] + fn a_kernel_write_into_a_protected_page_lands_once_bracketed() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + for prot in [PAGE_READONLY, PAGE_NOACCESS] { + let pg = Protected::new(prot); + let at = pg.0 + 0x2010; + let bytes = [0x5Au8; 0x1800]; // two 4 KiB pages + assert!(!nt_write(at, &bytes), "the probe: a kernel write into a protected page fails"); + assert!(!kernel_write_with(false, "test", at, bytes.len(), &mut || nt_write(at, &bytes)), "off: as before"); + assert!(!writable(at, 8), "off (no env): the old answer"); + assert!(covers(at, bytes.len(), query, xcl_protected), "on: XCL's protected pages count as writable"); + assert!(kernel_write_with(true, "test", at, bytes.len(), &mut || nt_write(at, &bytes))); + assert_eq!(FAULTS.load(Ordering::Acquire), 2, "one touch per 4 KiB page, in user mode"); + assert_eq!(std::slice::from_raw_parts(at as *const u8, bytes.len()), &bytes[..]); + } + } + } + + #[test] + fn pages_stay_pinned_while_the_write_goes_on() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let pg = Protected::new(PAGE_READONLY); + let b = open_with(true, pg.0 + 0x1000, 0x2000); + assert_eq!(b.pinned(), 2); + assert!(is_pinned(pg.0 + 0x1000) && is_pinned(pg.0 + 0x2fff) && !is_pinned(pg.0 + 0x3000) && !is_pinned(pg.0)); + let c = open_with(true, pg.0 + 0x2000, 0x10); + drop(b); + assert!(is_pinned(pg.0 + 0x2000) && !is_pinned(pg.0 + 0x1000), "counted per write"); + drop(c); + assert!(!is_pinned(pg.0 + 0x2000)); + assert_eq!(open_with(false, pg.0, SIZE).pinned(), 0, "off: no pins"); + } + } + + #[test] + fn a_pin_of_an_overlapped_write_lasts_until_it_is_done() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let pg = Protected::new(PAGE_READONLY); + // an OVERLAPPED whose Internal is STATUS_PENDING, then done + let mut ov = [0x103usize, 0, 0, 0]; + open_with(true, pg.0, 0x10).keep_until_done(ov.as_mut_ptr() as usize); + assert!(is_pinned(pg.0)); + std::ptr::write_volatile(&mut ov[0], 0); + assert!(!is_pinned(pg.0), "released once the read is done"); + } + } + + #[test] + fn a_receive_into_protected_pages_goes_through_xcl_s_buffer() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let pg = Protected::new(PAGE_NOACCESS); + let at = (pg.0 + 0x0ff0) as *mut u8; + let r = bounce_with(true, at, 0x40, |b| { + assert_ne!(b, at, "the call writes XCL's buffer"); + assert!(nt_write(b as usize, &[7u8; 0x30])); + 0x30 + }); + assert_eq!(r, 0x30); + assert_eq!(std::slice::from_raw_parts(at, 0x30), &[7u8; 0x30][..]); + let unprotected = vec![0u8; 16]; + let p = unprotected.as_ptr() as *mut u8; + assert_eq!(bounce_with(true, p, 16, |b| if b == p { 1 } else { -1 }), 1, "elsewhere: straight through"); + let r = bounce_with(false, at.add(0x1000), 0x10, |b| if b == at.add(0x1000) { -1 } else { 1 }); + assert_eq!(r, -1, "off: straight through"); + } + } +} diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 1b0dfd86a8..d0a8bd1231 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -293,6 +293,7 @@ pub fn host_main(boot_path: &Path) -> i32 { if let Err(e) = crate::vfs_hooks::install() { crate::xlog_error!("VFS: not all hooks installed: {e}"); } + crate::hle::kernelx::guest_write::install(); if let Err(e) = crate::eh::install_pc_hook() { crate::xlog_error!("hook RtlPcToFileHeader: {e} – C++ exceptions in the game may not work"); } diff --git a/crates/xcl/src/vfs_hooks.rs b/crates/xcl/src/vfs_hooks.rs index c6a87a9101..c87bf23b94 100644 --- a/crates/xcl/src/vfs_hooks.rs +++ b/crates/xcl/src/vfs_hooks.rs @@ -532,11 +532,13 @@ unsafe extern "system" fn hk_remove_dir_w(n: *const u16) -> i32 { unsafe extern "system" fn hk_read_file(h: *mut c_void, buf: *mut c_void, n: u32, read: *mut u32, ov: *mut c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut u32, *mut c_void) -> i32; let orig = orig!(O_READ_FILE as F); - let opened = (!buf.is_null()).then(|| crate::hle::kernelx::lazy::ensure(buf as usize, n as usize)); + // (pages XCL protected are opened and pinned too, `XCL_GUEST_WRITE_GUARD=1`: the kernel's + // write, a copy or the disk's DMA for NO_BUFFERING, fails there rather than faulting) + let opened = (!buf.is_null()).then(|| crate::hle::kernelx::guest_write::open(buf as usize, n as usize)); let r = orig(h, buf, n, read, ov); let error = windows_sys::Win32::Foundation::GetLastError(); if !ov.is_null() && r == 0 && error == windows_sys::Win32::Foundation::ERROR_IO_PENDING { - if let Some(opened) = opened { crate::hle::kernelx::guards::open_until_done(opened, ov as usize); } + if let Some(opened) = opened { opened.keep_until_done(ov as usize); } } crate::hle::d3d12x::file_reads::returned(r != 0, error, buf, n, read, ov); SetLastError(error); diff --git a/crates/xcl/tests/guest_write_probe.rs b/crates/xcl/tests/guest_write_probe.rs new file mode 100644 index 0000000000..0c2ac49aba --- /dev/null +++ b/crates/xcl/tests/guest_write_probe.rs @@ -0,0 +1,407 @@ +//! What Windows does when the kernel (or the GPU) writes into a page the process made read-only +//! or no-access: the evidence the T6 layering rests on (`hle::kernelx::guest_write`). +//! +//! For each destination state (read-write, read-only, no-access, read-write under the write +//! watch) every call below writes one 4 KiB page; the table records its return value, error / +//! NTSTATUS, whether the bytes landed, whether a vectored handler saw a fault there (it would +//! repair one: a user-mode copy inside the call), the page's protection afterwards, and for the +//! write-watched page whether the write watch saw the write. +//! +//! Run with `cargo test --test guest_write_probe -- --nocapture --test-threads=1`. The D3D12 case +//! (`gpu_copy_into_an_imported_heap`) needs a GPU and is ignored by default. + +use std::ffi::c_void; +use std::io::Write as _; +use std::net::{TcpListener, TcpStream, UdpSocket}; +use std::os::windows::ffi::OsStrExt; +use std::os::windows::io::AsRawSocket; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +use windows_sys::Win32::Foundation::{CloseHandle, GetLastError, SetLastError, EXCEPTION_ACCESS_VIOLATION, GENERIC_READ, HANDLE, INVALID_HANDLE_VALUE, NTSTATUS}; +use windows_sys::Win32::Storage::FileSystem::{CreateFileW, ReadFile, FILE_FLAG_NO_BUFFERING, FILE_FLAG_OVERLAPPED, FILE_SHARE_READ, OPEN_EXISTING}; +use windows_sys::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; +use windows_sys::Win32::System::IO::{CancelIo, GetOverlappedResult, OVERLAPPED}; +use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, RemoveVectoredExceptionHandler, WriteProcessMemory, EXCEPTION_POINTERS}; +use windows_sys::Win32::System::Memory::{ + GetWriteWatch, ResetWriteWatch, VirtualAlloc, VirtualFree, VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, + PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +/// (not in windows-sys: a VIRTUAL_ALLOCATION_TYPE flag) +const MEM_WRITE_WATCH: u32 = 0x20_0000; +const REGION: usize = 0x1_0000; +const N: usize = 4096; +const FILL: u8 = 0xEE; + +#[link(name = "ntdll", kind = "raw-dylib")] +extern "system" { + fn NtWriteVirtualMemory(process: HANDLE, at: *mut c_void, data: *const c_void, len: usize, done: *mut usize) -> NTSTATUS; + fn NtReadFile(h: HANDLE, event: HANDLE, apc: *const c_void, ctx: *const c_void, iosb: *mut [usize; 2], buf: *mut c_void, len: u32, offset: *const i64, key: *const u32) -> NTSTATUS; +} + +#[link(name = "ws2_32", kind = "raw-dylib")] +extern "system" { + fn recv(s: usize, buf: *mut u8, len: i32, flags: i32) -> i32; + fn recvfrom(s: usize, buf: *mut u8, len: i32, flags: i32, from: *mut u8, fromlen: *mut i32) -> i32; + fn WSAGetLastError() -> i32; +} + +/// the probed page: faults there are counted and repaired (made read-write), as a tracker would +static LO: AtomicUsize = AtomicUsize::new(0); +static FAULTS: AtomicUsize = AtomicUsize::new(0); +static SERIAL: Mutex<()> = Mutex::new(()); + +unsafe extern "system" fn veh(info: *mut EXCEPTION_POINTERS) -> i32 { + let r = &*(*info).ExceptionRecord; + let lo = LO.load(Ordering::Acquire); + if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && r.NumberParameters >= 2 && lo != 0 { + let at = r.ExceptionInformation[1]; + if (lo..lo + REGION).contains(&at) { + FAULTS.fetch_add(1, Ordering::AcqRel); + let mut old = 0; + VirtualProtect((at & !0xFFF) as *const c_void, 0x1000, PAGE_READWRITE, &mut old); + return -1; // EXCEPTION_CONTINUE_EXECUTION + } + } + 0 +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum State { + Rw, + Ro, + NoAccess, + WatchedRw, +} + +struct Page { + base: usize, + watched: bool, +} + +impl Page { + unsafe fn new(state: State) -> Page { + let watched = state == State::WatchedRw; + let flags = MEM_RESERVE | MEM_COMMIT | if watched { MEM_WRITE_WATCH } else { 0 }; + let base = VirtualAlloc(std::ptr::null(), REGION, flags, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + std::ptr::write_bytes(base as *mut u8, FILL, REGION); + if watched { + ResetWriteWatch(base as *const c_void, REGION); + } + let p = match state { + State::Ro => PAGE_READONLY, + State::NoAccess => PAGE_NOACCESS, + _ => PAGE_READWRITE, + }; + let mut old = 0; + assert_ne!(VirtualProtect(base as *const c_void, REGION, p, &mut old), 0); + FAULTS.store(0, Ordering::Release); + LO.store(base, Ordering::Release); + Page { base, watched } + } + + fn ptr(&self) -> *mut u8 { + self.base as *mut u8 + } + + unsafe fn protect_now(&self) -> u32 { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery(self.base as *const c_void, &mut m, std::mem::size_of_val(&m)); + m.Protect + } + + /// (landed, protection after, write-watch hits) – read after making the page readable + unsafe fn outcome(&self, want: &[u8]) -> (String, u32, Option) { + LO.store(0, Ordering::Release); + let prot = self.protect_now(); + let mut ww = None; + if self.watched { + let mut hits = [std::ptr::null_mut::(); 16]; + let mut count = hits.len(); + let mut gran = 0u32; + GetWriteWatch(0, self.base as *const c_void, REGION, hits.as_mut_ptr(), &mut count, &mut gran); + ww = Some(count); + } + let mut old = 0; + VirtualProtect(self.base as *const c_void, REGION, PAGE_READWRITE, &mut old); + let got = std::slice::from_raw_parts(self.ptr(), N); + let same = got.iter().zip(want).filter(|(a, b)| a == b).count(); + let landed = if same == N { + "all".to_string() + } else if got.iter().all(|&b| b == FILL) { + "none".to_string() + } else { + format!("partial {same}") + }; + (landed, prot, ww) + } +} + +impl Drop for Page { + fn drop(&mut self) { + LO.store(0, Ordering::Release); + unsafe { VirtualFree(self.base as *mut c_void, 0, MEM_RELEASE) }; + } +} + +fn pattern() -> Vec { + (0..N).map(|i| (i * 7 + 3) as u8).collect() +} + +fn prot_name(p: u32) -> &'static str { + match p { + PAGE_READWRITE => "RW", + PAGE_READONLY => "RO", + PAGE_NOACCESS => "NA", + 0x40 => "XRW", + _ => "?", + } +} + +fn wide(s: &std::path::Path) -> Vec { + s.as_os_str().encode_wide().chain([0]).collect() +} + +struct Probe { + file: std::path::PathBuf, + rows: Vec, +} + +impl Probe { + unsafe fn row(&mut self, api: &str, state: State, call: impl FnOnce(&Page) -> String) { + let page = Page::new(state); + let ret = call(&page); + let faults = FAULTS.load(Ordering::Acquire); + let (landed, prot, ww) = page.outcome(&pattern()); + let ww = ww.map_or("-".to_string(), |n| if n > 0 { format!("yes ({n})") } else { "no".into() }); + let row = format!("| {api} | {state:?} | {ret} | {landed} | {faults} | {} | {ww} |", prot_name(prot)); + eprintln!("{row}"); + self.rows.push(row); + } + + unsafe fn open(&self, flags: u32) -> HANDLE { + let h = CreateFileW(wide(&self.file).as_ptr(), GENERIC_READ, FILE_SHARE_READ, std::ptr::null(), OPEN_EXISTING, flags, std::ptr::null_mut()); + assert_ne!(h, INVALID_HANDLE_VALUE); + h + } +} + +unsafe fn read_file(h: HANDLE, at: *mut u8) -> String { + let mut got = 0u32; + SetLastError(0); + let r = ReadFile(h, at, N as u32, &mut got, std::ptr::null_mut()); + let e = GetLastError(); + CloseHandle(h); + format!("ret {r}, err {e}, got {got}") +} + +#[test] +fn kernel_writes_into_protected_pages() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("xcl-guest-write-probe-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("data.bin"); + let mut whole = pattern(); + whole.resize(REGION, 0); + std::fs::File::create(&file).unwrap().write_all(&whole).unwrap(); + let mut p = Probe { file, rows: Vec::new() }; + let src = pattern(); + unsafe { + let h = AddVectoredExceptionHandler(1, Some(veh)); + for state in [State::Rw, State::Ro, State::NoAccess, State::WatchedRw] { + p.row("memcpy (user mode, in process)", state, |pg| { + std::ptr::copy_nonoverlapping(src.as_ptr(), pg.ptr(), N); + "done".to_string() + }); + let fh = p.open(FILE_FLAG_OVERLAPPED); + p.row("ReadFile (OVERLAPPED)", state, |pg| { + let mut ov: OVERLAPPED = std::mem::zeroed(); + ov.hEvent = CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()); + SetLastError(0); + let r = ReadFile(fh, pg.ptr(), N as u32, std::ptr::null_mut(), &mut ov); + let e = GetLastError(); + let mut got = 0u32; + // (bounded: a read that never completes is a result too) + let waited = WaitForSingleObject(ov.hEvent, 2000); + let w = if waited == 0 { GetOverlappedResult(fh, &ov, &mut got, 0) } else { CancelIo(fh); -1 }; + let e2 = GetLastError(); + CloseHandle(ov.hEvent); + CloseHandle(fh); + format!("ret {r}, err {e}; result {w}, err {e2}, got {got}") + }); + let fh = p.open(0); + p.row("ReadFile (buffered)", state, |pg| read_file(fh, pg.ptr())); + let fh = p.open(FILE_FLAG_NO_BUFFERING); + p.row("ReadFile (NO_BUFFERING)", state, |pg| read_file(fh, pg.ptr())); + let fh = p.open(0); + p.row("NtReadFile", state, |pg| { + let mut iosb = [0usize; 2]; + let off = 0i64; + let st = NtReadFile(fh, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), &mut iosb, pg.ptr().cast(), N as u32, &off, std::ptr::null()); + CloseHandle(fh); + format!("0x{:08X}, iosb.info {}", st as u32, iosb[1]) + }); + let fh = p.open(FILE_FLAG_NO_BUFFERING); + p.row("NtReadFile (NO_BUFFERING)", state, |pg| { + let mut iosb = [0usize; 2]; + let off = 0i64; + let st = NtReadFile(fh, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), &mut iosb, pg.ptr().cast(), N as u32, &off, std::ptr::null()); + CloseHandle(fh); + format!("0x{:08X}, iosb.info {}", st as u32, iosb[1]) + }); + p.row("WriteProcessMemory (self)", state, |pg| { + let mut done = 0usize; + SetLastError(0); + let r = WriteProcessMemory(GetCurrentProcess(), pg.ptr().cast(), src.as_ptr().cast(), N, &mut done); + format!("ret {r}, err {}, done {done}", GetLastError()) + }); + p.row("NtWriteVirtualMemory (self)", state, |pg| { + let mut done = 0usize; + let st = NtWriteVirtualMemory(GetCurrentProcess(), pg.ptr().cast(), src.as_ptr().cast(), N, &mut done); + format!("0x{:08X}, done {done}", st as u32) + }); + p.row("recv (TCP loopback)", state, |pg| { + let l = TcpListener::bind("127.0.0.1:0").unwrap(); + let mut tx = TcpStream::connect(l.local_addr().unwrap()).unwrap(); + let (rx, _) = l.accept().unwrap(); + rx.set_read_timeout(Some(std::time::Duration::from_secs(2))).unwrap(); + tx.write_all(&src).unwrap(); + tx.flush().unwrap(); + std::thread::sleep(std::time::Duration::from_millis(50)); + let r = recv(rx.as_raw_socket() as usize, pg.ptr(), N as i32, 0x8 /* MSG_WAITALL */); + let e = if r < 0 { WSAGetLastError() } else { 0 }; + format!("ret {r}, wsa {e}") + }); + p.row("recvfrom (UDP loopback)", state, |pg| { + let rx = UdpSocket::bind("127.0.0.1:0").unwrap(); + rx.set_read_timeout(Some(std::time::Duration::from_secs(2))).unwrap(); + let tx = UdpSocket::bind("127.0.0.1:0").unwrap(); + tx.send_to(&src, rx.local_addr().unwrap()).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(50)); + let mut from = [0u8; 32]; + let mut fl = from.len() as i32; + let r = recvfrom(rx.as_raw_socket() as usize, pg.ptr(), N as i32, 0, from.as_mut_ptr(), &mut fl); + let e = if r < 0 { WSAGetLastError() } else { 0 }; + format!("ret {r}, wsa {e}") + }); + } + RemoveVectoredExceptionHandler(h); + } + let _ = std::fs::remove_dir_all(&dir); + println!("| call | destination | result | bytes landed | VEH faults | protection after | write watch saw it |"); + println!("|---|---|---|---|---|---|---|"); + for r in &p.rows { + println!("{r}"); + } + // the read-write rows are the control: every call must have landed its bytes there + for r in p.rows.iter().filter(|r| r.contains("| Rw |")) { + assert!(r.contains("| all |"), "{r}"); + } +} + +/// A GPU copy into a heap imported from process memory (`OpenExistingHeapFromAddress`, as +/// `gpu::uma` imports the coherent window), with the CPU pages made read-only or no-access +/// before the import, or after it and before the copy. +#[test] +#[ignore = "needs a D3D12 GPU: cargo test --test guest_write_probe -- --ignored --nocapture"] +fn gpu_copy_into_an_imported_heap() { + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let src = pattern(); + let mut rows = Vec::new(); + unsafe { + let mut dev: Option = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("D3D12 device"); + let dev = dev.unwrap(); + let dev3: ID3D12Device3 = dev.cast().unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let buf_desc = |w: u64, flags| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: w, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let mut up: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &buf_desc(N as u64, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut up, + ) + .unwrap(); + let up = up.unwrap(); + let mut m = std::ptr::null_mut(); + up.Map(0, None, Some(&mut m)).unwrap(); + std::ptr::copy_nonoverlapping(src.as_ptr(), m as *mut u8, N); + up.Unmap(0, None); + let mut value = 0u64; + for state in [State::Rw, State::Ro, State::NoAccess] { + for after_import in [false, true] { + if state == State::Rw && after_import { + continue; + } + let page = Page::new(if after_import { State::Rw } else { state }); + let when = if after_import { "protected after import" } else { "protected before import" }; + let heap: Result = dev3.OpenExistingHeapFromAddress(page.base as *const c_void); + let heap = match heap { + Ok(h) => h, + Err(e) => { + let (landed, prot, _) = page.outcome(&src); + rows.push(format!("| GPU copy, imported heap | {state:?}, {when} | import failed {e} | {landed} | 0 | {} | - |", prot_name(prot))); + continue; + } + }; + let mut vp_note = String::new(); + if after_import { + let p = if state == State::Ro { PAGE_READONLY } else { PAGE_NOACCESS }; + let mut old = 0; + SetLastError(0); + let ok = VirtualProtect(page.base as *const c_void, REGION, p, &mut old); + vp_note = format!("vp ret {ok} err {}; ", GetLastError()); + } + let mut dst: Option = None; + let placed = dev.CreatePlacedResource(&heap, 0, &buf_desc(REGION as u64, D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER), D3D12_RESOURCE_STATE_COMMON, None, &mut dst); + let ret = match placed { + Err(e) => format!("placed failed {e}"), + Ok(()) => { + let dst = dst.unwrap(); + alloc.Reset().unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.CopyBufferRegion(&dst, 0, &up, 0, N as u64); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + value += 1; + queue.Signal(&fence, value).unwrap(); + let t = std::time::Instant::now(); + while fence.GetCompletedValue() < value && t.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + let removed = dev.GetDeviceRemovedReason(); + format!("fence {}, removed {:?}", fence.GetCompletedValue() >= value, removed) + } + }; + let faults = FAULTS.load(Ordering::Acquire); + let (landed, prot, _) = page.outcome(&src); + rows.push(format!("| GPU copy, imported heap | {state:?}, {when} | {vp_note}{ret} | {landed} | {faults} | {} | - |", prot_name(prot))); + } + } + } + for r in &rows { + println!("{r}"); + } +} From 6950d2e5fc225c3aac564d87f957b10176881816 Mon Sep 17 00:00:00 2001 From: Enrique Villa Date: Wed, 2 Dec 2026 02:10:25 +0800 Subject: [PATCH 2/2] D3D12.X: opt-in XCL_COPY_BACK=fault for GPU-written kept and RT/DS/UAV textures Adds fault-driven GPU -> CPU texture copy-back behind opt-in XCL_COPY_BACK=fault (default off, requires XCL_GUEST_WRITE_GUARD=1 from #3597) to address #2663 for GPU-owned RT/DS/UAV textures without paying eager per-submit download cost. - Tracks GPU-owned placed textures (vram::place: RTV/DSV/UAV binds, clears, UAV barriers, and resource state transitions touching RENDER_TARGET|UNORDERED_ACCESS|DEPTH_WRITE|COPY_DEST|RESOLVE_DEST) alongside kept sampled textures, arming whole committed title pages PAGE_NOACCESS behind a native per-queue fence after submission. - On CPU access violation, waits for the writing submit fence on XCL's upload queue, downloads from tracked post-submit resource states (gpu::texture::download), opens the pages, and re-tiles changed 4 KiB pages into console layout (title_textures::write_subresources). - Skips imported coherent UMA ranges (!uma.shadowed() && uma.in_committed_window) upfront in O(1), avoiding Windows OpenExistingHeapFromAddress VirtualProtect error 87 and ~20 ms VirtualQuery PTE walks. - Coexists deadlock-free with title_textures's eager Copy/Resolve download publisher via copy_back::disarm_overlapping before write_changed_pages, and serializes page-protection against pinned kernel writes via guest_write::while_unpinned. - Adds unit and GPU tests covering kept textures, end-to-end adopted-hook GPU-owned RT clear + state transitions, write_changed_pages coexistence, multi-plane DS skip, coherent UMA skip, and guest_write::while_unpinned. --- crates/xcl/src/gpu/texture.rs | 88 +++ crates/xcl/src/hle/d3d12x/copy_back.rs | 769 ++++++++++++++++++++ crates/xcl/src/hle/d3d12x/device_x.rs | 8 +- crates/xcl/src/hle/d3d12x/list_x.rs | 32 +- crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/present.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 30 +- crates/xcl/src/hle/d3d12x/submit_cost.rs | 3 + crates/xcl/src/hle/d3d12x/title_textures.rs | 678 ++++++++++++++++- crates/xcl/src/hle/kernelx/guest_write.rs | 75 ++ 10 files changed, 1676 insertions(+), 9 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/copy_back.rs diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index 0371295e6e..6469013a5a 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -202,6 +202,94 @@ pub unsafe fn upload(dev: &ID3D12Device, queue: &ID3D12CommandQueue, res: &ID3D1 r } +/// Every subresource (D3D12 order) of `res` as linear rows, copied out on `queue` (the +/// reverse of `upload`, waited for): `res` is in `states` (one for all subresources, or one per +/// subresource) and is left in them. The work that wrote it must be done, or ordered before +/// `queue`'s. +pub unsafe fn download(dev: &ID3D12Device, queue: &ID3D12CommandQueue, res: &ID3D12Resource, states: &[D3D12_RESOURCE_STATES]) -> Result, String> { + let rd = res.GetDesc(); + let arrays = match rd.Dimension { + D3D12_RESOURCE_DIMENSION_TEXTURE1D | D3D12_RESOURCE_DIMENSION_TEXTURE2D => rd.DepthOrArraySize as usize, + D3D12_RESOURCE_DIMENSION_TEXTURE3D => 1, + _ => return Err("texture download requires a texture resource".into()), + }; + // A format of several planes (depth+stencil, planar video) has subresources per plane: + // refuse rather than returning plane 0 alone. + let mut info = D3D12_FEATURE_DATA_FORMAT_INFO { Format: rd.Format, PlaneCount: 0 }; + dev.CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO, &mut info as *mut _ as *mut std::ffi::c_void, std::mem::size_of_val(&info) as u32).map_err(err)?; + if info.PlaneCount != 1 { + return Err(format!("texture download of a format with {} planes", info.PlaneCount)); + } + if rd.SampleDesc.Count != 1 { + return Err(format!("texture download of a texture of {} samples", rd.SampleDesc.Count)); + } + let n = rd.MipLevels as usize * arrays; + if states.len() != 1 && states.len() != n { + return Err(format!("{} subresource states for {n} subresources", states.len())); + } + let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n]; + let mut rows = vec![0u32; n]; + let mut row_bytes = vec![0u64; n]; + let mut total = 0u64; + dev.GetCopyableFootprints(&rd, 0, n as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), Some(&mut total)); + let rb_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: total.max(256), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut rb: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rb_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb) + .map_err(|x| format!("texture readback buffer: {x}"))?; + let rb = rb.ok_or("texture readback buffer")?; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(err)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?; + let to_copy = transitions(res, states, &[D3D12_RESOURCE_STATE_COPY_SOURCE], n); + if !to_copy.is_empty() { + list.ResourceBarrier(&to_copy); + } + for (k, fp) in fps.iter().enumerate() { + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(res), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + let back = transitions(res, &[D3D12_RESOURCE_STATE_COPY_SOURCE], states, n); + if !back.is_empty() { + list.ResourceBarrier(&back); + } + list.Close().map_err(err)?; + let cl: ID3D12CommandList = windows::core::Interface::cast(&list).map_err(err)?; + crate::hle::d3d12x::real::native_queue_execute(queue, &cl); + if let Err(e) = wait(dev, queue) { + // The copy is queued and may still run: retain its objects rather than releasing them under it. + std::mem::forget((rb, alloc, list, cl, res.clone())); + return Err(e); + } + let mut p: *mut std::ffi::c_void = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).map_err(err)?; + let out = fps + .iter() + .zip(rows.iter().zip(&row_bytes)) + .map(|(fp, (&nrows, &nbytes))| { + let (nrows, nbytes, depth, pitch) = (nrows as usize, nbytes as usize, fp.Footprint.Depth as usize, fp.Footprint.RowPitch as usize); + let mut data = Vec::with_capacity(depth * nrows * nbytes); + // Depth slices are NumRows rows apart (rows of 4x4 blocks for BCn). + for z in 0..depth { + for y in 0..nrows { + data.extend_from_slice(std::slice::from_raw_parts((p as *const u8).add(fp.Offset as usize + (z * nrows + y) * pitch), nbytes)); + } + } + Subresource { rows: nrows, row_bytes: nbytes, depth, data } + }) + .collect(); + rb.Unmap(0, None); + Ok(out) +} + /// What `upload_batch` keeps for a queue between batches: its allocator and list, a fence, and /// one persistently mapped upload buffer the batches' texels go through. Making them for every /// batch – an upload buffer per texture, an allocator, a list and a fence per batch – cost a diff --git a/crates/xcl/src/hle/d3d12x/copy_back.rs b/crates/xcl/src/hle/d3d12x/copy_back.rs new file mode 100644 index 0000000000..cb725e9b4e --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/copy_back.rs @@ -0,0 +1,769 @@ +//! Fault-driven GPU → CPU copy-back of GPU-written title textures (#2663): `XCL_COPY_BACK=fault` +//! (default `0`, off). +//! +//! On the console the CPU and GPU share memory, so a title can read on the CPU what its GPU work +//! wrote into a texture. On PC, XCL backs sampled title textures with separate PC textures +//! (`title_textures`) and GPU-owned render targets, depth buffers, and UAV textures with +//! video-memory placements (`vram::place`). `title_textures` eagerly downloads `Copy*` / `Resolve*` +//! writes on title fence `Signal`, but direct rendering/compute/clear writes into GPU-owned +//! RT/DS/UAV textures cannot be downloaded eagerly on every submit without transferring hundreds +//! of megabytes per frame that the CPU never reads. +//! +//! With `XCL_COPY_BACK=fault` (requiring `XCL_GUEST_WRITE_GUARD=1`), when a submission writes a +//! tracked texture — either a kept sampled texture or a single-plane non-MSAA GPU-owned RT/DS/UAV +//! texture — the 4 KiB pages wholly inside its title memory become `PAGE_NOACCESS` right after the +//! submit, paired with a native fence signalled on the writing queue. A CPU read or write faults; +//! the vectored handler GPU-waits for that fence on XCL's upload queue, downloads the texture from +//! its tracked post-submit resource state, restores `PAGE_READWRITE`, and re-tiles changed pages +//! into console layout (`title_textures::download_and_write_after` / `read_back_after`). Textures +//! the CPU never touches pay zero GPU downloads. +//! +//! Windows D3D12 imported-heap boundary: pages inside XCL's imported coherent UMA window +//! (`!uma.shadowed() && uma.in_committed_window`, backed by `OpenExistingHeapFromAddress`) are +//! locked by `dxgkrnl`, so `VirtualProtect(..., PAGE_NOACCESS)` always fails with error 87 +//! (`ERROR_INVALID_PARAMETER`) and `VirtualQuery` walks ~500k contiguous RW PTEs (~18–23 ms). +//! `arm` skips imported coherent-UMA ranges upfront (counted in `uma`) in O(1). +//! +//! Scope & safety boundaries: +//! - Requires `XCL_GUEST_WRITE_GUARD=1`: armed ranges are registered with `guest_write` so kernel +//! writes (`ReadFile`, DirectStorage, `NtWriteVirtualMemory`, `recv`) open the page before +//! writing. Kernel *reads* (`WriteFile` / `send`) from armed pages are not hooked. +//! - Coexists cleanly with `title_textures`'s eager `Copy*` / `Resolve*` download publisher: +//! `disarm_overlapping` opens any armed overlapping pages before `publish_download` reads or +//! publishes via `write_changed_pages`, preventing fence deadlocks. +//! - Partial first/last pages shared with adjacent allocations stay readable until a fault on an +//! inner whole page writes the full texture back. Textures smaller than one whole page are +//! skipped (`small`). + +use std::cell::Cell; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +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, PAGE_NOACCESS, PAGE_READWRITE}; + +use crate::hle::kernelx::guest_write; +use crate::hle::xg; + +const PAGE: usize = 0x1000; +const EXCEPTION_CONTINUE_SEARCH: i32 = 0; +const EXCEPTION_CONTINUE_EXECUTION: i32 = -1; + +/// D3D12 resource states that imply a GPU write into a texture (`RENDER_TARGET`, +/// `UNORDERED_ACCESS`, `DEPTH_WRITE`, `COPY_DEST`, `RESOLVE_DEST`). +const GPU_WRITE_STATES: u32 = 0x4 | 0x8 | 0x10 | 0x400 | 0x1000; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Mode { + Off, + Fault, +} + +/// Test override: 0 = env, 1 = off, 2 = fault. +static FORCE: AtomicU8 = AtomicU8::new(0); + +fn mode() -> Mode { + match FORCE.load(Ordering::Relaxed) { + 1 => return Mode::Off, + 2 => return Mode::Fault, + _ => {} + } + static MODE: OnceLock = OnceLock::new(); + *MODE.get_or_init(|| { + let v = std::env::var("XCL_COPY_BACK").unwrap_or_default(); + match v.trim() { + "" | "0" => Mode::Off, + "fault" => { + if !guest_write::enabled() { + crate::xlog_warn!("copy back: XCL_COPY_BACK=fault needs XCL_GUEST_WRITE_GUARD=1 (kernel writes into no-access pages would fail); left off"); + Mode::Off + } else { + crate::xlog_info!("copy back: on (fault): GPU-written kept and RT/DS/UAV textures outside imported coherent UMA become no-access after the submit; a CPU touch reads them back"); + Mode::Fault + } + } + other => { + crate::xlog_warn!("copy back: XCL_COPY_BACK={other} is not 0 or fault; left off"); + Mode::Off + } + } + }) +} + +/// Whether `XCL_COPY_BACK=fault` (and its guard prerequisite) is active. +pub fn on() -> bool { + mode() == Mode::Fault +} + +/// Whether `[a, a + n)` lies inside an imported host coherent UMA window (`OpenExistingHeapFromAddress`), +/// where `dxgkrnl` rejects `VirtualProtect(..., PAGE_NOACCESS)` with error 87 and `VirtualQuery` +/// walks ~500k contiguous RW PTEs (~20 ms). +fn in_imported_uma(a: usize, n: usize) -> bool { + crate::gpu::uma::get().is_some_and(|u| !u.shadowed() && u.in_committed_window(a, n)) +} + +/// Whether DXGI format `fmt` has multiple planes (depth+stencil or planar video) which +/// `texture::download` refuses to copy back. +fn is_multi_plane_format(fmt: i32) -> bool { + matches!(fmt, 19..=22 | 44..=47 | 103..=114) +} + +/// A COM object kept in a static (the fault handler and the submit path run on any thread). +struct Shared(T); +unsafe impl Send for Shared {} + +/// A GPU-owned placed texture (`vram::place`: RT / DS / UAV) tracked for fault-driven copy-back. +struct GpuOwned { + device: usize, + /// CPU-accessible title memory VA (`mirror_source(va)`). + src: usize, + tex: Arc, + states: Vec, + flags: u32, + downloadable: bool, +} + +/// A texture whose whole title pages are `PAGE_NOACCESS` until the CPU touches them. +struct Armed { + res: usize, + gpu_owned: bool, + /// Whole pages of its title memory (`[lo, hi)`). + lo: usize, + hi: usize, + /// Committed RW page runs made `PAGE_NOACCESS` (`(start, bytes)`). + runs: Vec<(usize, usize)>, + /// Fence signalled on the title's queue after the submit that wrote it last. + fence: Shared, + value: u64, +} + +#[derive(Default)] +struct State { + /// Armed textures keyed by `lo`; ranges do not overlap. + armed: BTreeMap, + by_res: HashMap, + /// Registered GPU-owned RT/DS/UAV textures (`vram::place`). + gpu_owned: HashMap, + /// Textures whose read-back failed: never armed again. + refused: HashSet, + /// PC list → textures its GPU work writes (since creation or reset). + list_writes: HashMap>, + /// PC list → transitions of GPU-owned textures recorded on it. + list_transitions: HashMap>, + /// Queue → its fence and last signalled value. + fences: HashMap, u64)>, +} + +static STATE: Mutex> = Mutex::new(None); +/// Any texture armed now (the fault handler takes no lock for unrelated access violations). +static ANY_ARMED: AtomicBool = AtomicBool::new(false); +/// Any GPU-owned texture registered now (fast-path guard for barrier / copy hooks). +static HAS_GPU_OWNED: AtomicBool = AtomicBool::new(false); +/// Serializes fault read-backs and overlapping disarms; lock order is strictly `HANDLER` → `STATE`. +static HANDLER: Mutex<()> = Mutex::new(()); +static INSTALLED: AtomicBool = AtomicBool::new(false); + +thread_local! { + static IN_HANDLER: Cell = const { Cell::new(false) }; +} + +const ARMS: usize = 0; +const ARMS_GPU: usize = 1; +const FAULTS: usize = 2; +const READ_BACK_BYTES: usize = 3; +const FAILED: usize = 4; +const HANDLER_NS: usize = 5; +const NO_LIST: usize = 6; +const SKIPPED_UMA: usize = 7; +const SKIPPED_UNSUP: usize = 8; +const SKIPPED_SMALL: usize = 9; +const SKIPPED_OVERLAP: usize = 10; +const SKIPPED_PROT: usize = 11; +const RACES: usize = 12; +const NSTATS: usize = 13; +static STATS: [AtomicU64; NSTATS] = [const { AtomicU64::new(0) }; NSTATS]; + +/// Cumulative GPU-owned texture placement census (counts and console bytes by VA region). +const C_UMA: usize = 0; +const C_SPARSE: usize = 1; +const C_OTHER: usize = 2; +const C_UNSUP: usize = 3; +const C_UMA_BYTES: usize = 4; +const C_SPARSE_BYTES: usize = 5; +const C_OTHER_BYTES: usize = 6; +const NCENSUS: usize = 7; +static CENSUS: [AtomicU64; NCENSUS] = [const { AtomicU64::new(0) }; NCENSUS]; + +fn with(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +/// Register a GPU-owned placed texture (`CreatePlacedResourceX` → `vram::place`) so its GPU writes +/// and subresource states are tracked when `XCL_COPY_BACK=fault` is on. +pub(super) fn register_gpu_owned( + device: usize, + res: usize, + va: usize, + tex: xg::Texture, + pc_desc: &D3D12_RESOURCE_DESC, + flags: u32, + initial_state: u32, +) { + if !on() || res == 0 || va == 0 { + return; + } + let src = super::title_textures::mirror_source_of(va); + let size = tex.size(); + let downloadable = pc_desc.SampleDesc.Count == 1 + && pc_desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER + && !is_multi_plane_format(pc_desc.Format.0) + && tex.texels().is_some() + && size != 0 + && size != u64::MAX + && usize::try_from(size).is_ok(); + let len = usize::try_from(size).ok().filter(|_| size != u64::MAX).unwrap_or(0); + if in_imported_uma(src, len.max(1)) { + CENSUS[C_UMA].fetch_add(1, Ordering::Relaxed); + CENSUS[C_UMA_BYTES].fetch_add(len as u64, Ordering::Relaxed); + } else if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(src)) { + CENSUS[C_SPARSE].fetch_add(1, Ordering::Relaxed); + CENSUS[C_SPARSE_BYTES].fetch_add(len as u64, Ordering::Relaxed); + } else { + CENSUS[C_OTHER].fetch_add(1, Ordering::Relaxed); + CENSUS[C_OTHER_BYTES].fetch_add(len as u64, Ordering::Relaxed); + } + if !downloadable { + CENSUS[C_UNSUP].fetch_add(1, Ordering::Relaxed); + } + let entry = GpuOwned { + device, + src, + tex: Arc::new(tex), + states: vec![D3D12_RESOURCE_STATES(initial_state as i32)], + flags, + downloadable, + }; + with(|s| { + s.refused.remove(&res); + s.gpu_owned.insert(res, entry); + HAS_GPU_OWNED.store(true, Ordering::Release); + }); +} + +/// Whether `res` is a registered GPU-owned texture. +#[cfg(test)] +pub(super) fn is_gpu_owned(res: usize) -> bool { + if !on() || !HAS_GPU_OWNED.load(Ordering::Relaxed) { + return false; + } + with(|s| s.gpu_owned.contains_key(&res)) +} + +/// Resource state transitions recorded on PC list `list`: `(res, subresource, before, after)`. +/// Tracks post-submit states of registered GPU-owned textures and marks any transition touching a +/// GPU-write state (`RENDER_TARGET`, `UNORDERED_ACCESS`, `DEPTH_WRITE`, `COPY_DEST`, +/// `RESOLVE_DEST`) as a GPU write on `list`. +pub(super) fn note_transitions(list: usize, transitions: &[(usize, u32, u32, u32)]) { + if !on() || !HAS_GPU_OWNED.load(Ordering::Relaxed) || list == 0 || transitions.is_empty() { + return; + } + with(|s| { + for &(res, sub, before, after) in transitions { + if !s.gpu_owned.contains_key(&res) { + continue; + } + s.list_transitions.entry(list).or_default().push((res, sub, D3D12_RESOURCE_STATES(after as i32))); + if (before | after) & GPU_WRITE_STATES != 0 { + let v = s.list_writes.entry(list).or_default(); + if !v.contains(&res) { + v.push(res); + } + } + } + }); +} + +/// The GPU work recorded on PC list `list` writes title texture `res` (either kept in step or +/// GPU-owned RT/DS/UAV). List 0: no list known (the write is not armed). +pub fn note_write(list: usize, res: usize) { + if !on() || res == 0 { + return; + } + if list == 0 { + STATS[NO_LIST].fetch_add(1, Ordering::Relaxed); + return; + } + with(|s| { + let v = s.list_writes.entry(list).or_default(); + if !v.contains(&res) { + v.push(res); + } + }); +} + +/// PC list `list` records anew (or is released): drop its pending writes and recorded transitions. +pub fn list_reset(list: usize) { + if !on() { + return; + } + with(|s| { + s.list_writes.remove(&list); + s.list_transitions.remove(&list); + }); +} + +/// Queue `queue` was retired: drop its cached signal fence so a reused pointer starts fresh. +pub fn forget_queue(queue: usize) { + if !on() { + return; + } + with(|s| { + s.fences.remove(&queue); + }); +} + +/// `lists` went to `queue`: apply GPU-owned transitions in submit order and arm every texture +/// whose GPU work writes it behind a native fence signalled now on `queue`. +pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) { + if !on() || queue.is_null() { + return; + } + let mut writes: Vec = with(|s| { + if !s.list_transitions.is_empty() { + let notes: Vec<(usize, u32, D3D12_RESOURCE_STATES)> = + lists.iter().filter_map(|&l| s.list_transitions.get(&(l as usize))).flatten().copied().collect(); + for (res, sub, after) in notes { + if let Some(g) = s.gpu_owned.get_mut(&res) { + let n = super::title_textures::subresource_count(&g.tex); + super::title_textures::apply_transition(&mut g.states, n, sub, after); + } + } + } + lists.iter().filter_map(|&l| s.list_writes.get(&(l as usize))).flatten().copied().collect() + }); + if writes.is_empty() { + return; + } + writes.sort_unstable(); + writes.dedup(); + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let Some((fence, value)) = signal(q) else { return }; + for res in writes { + arm(res, &fence, value); + } +} + +/// Signal a per-queue fence natively (bypassing title-facing `Signal` hooks) and return `(fence, value)`. +unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> { + let key = q.as_raw() as usize; + let have = with(|s| s.fences.get(&key).map(|(f, v)| (f.0.clone(), *v))); + let (fence, last) = match have { + Some(x) => x, + None => { + let mut dev: Option = None; + q.GetDevice(&mut dev).ok()?; + let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + (f, 0) + } + }; + let value = last + 1; + super::real::native_queue_signal(q, &fence, value).ok()?; + with(|s| s.fences.insert(key, (Shared(fence.clone()), value))); + Some((fence, value)) +} + +/// Resolve `(src_va, byte_len, downloadable, is_gpu_owned, flags)` for `res`. +/// Returns `None` if `res` is neither a registered GPU-owned texture nor a kept title texture +/// (e.g. a buffer passed to `ClearUnorderedAccessView` or a swapchain backbuffer). +fn target_info(res: usize) -> Option<(usize, usize, bool, bool, u32)> { + if HAS_GPU_OWNED.load(Ordering::Relaxed) { + if let Some(info) = with(|s| { + s.gpu_owned.get(&res).map(|g| (g.src, g.tex.size() as usize, g.downloadable, true, g.flags)) + }) { + return Some(info); + } + } + super::title_textures::copy_back_range(res).map(|(va, len)| (va, len, true, false, 0)) +} + +/// Make the whole pages of `res`'s title memory `PAGE_NOACCESS` until the CPU touches them; the +/// work that wrote it ends at `value` on `fence`. +unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) { + let Some((va, len, downloadable, is_gpu, flags)) = target_info(res) else { + return; + }; + if !downloadable { + STATS[SKIPPED_UNSUP].fetch_add(1, Ordering::Relaxed); + return; + } + let Some(lo) = va.checked_add(PAGE - 1).map(|v| v & !(PAGE - 1)) else { + STATS[SKIPPED_SMALL].fetch_add(1, Ordering::Relaxed); + return; + }; + let Some(hi) = va.checked_add(len).map(|v| v & !(PAGE - 1)) else { + STATS[SKIPPED_SMALL].fetch_add(1, Ordering::Relaxed); + return; + }; + if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) { + STATS[SKIPPED_SMALL].fetch_add(1, Ordering::Relaxed); + return; + } + // Skip imported coherent UMA ranges upfront: `dxgkrnl` rejects `PAGE_NOACCESS` with error 87 + // and `VirtualQuery` walks ~500k contiguous RW PTEs (~18–23 ms). + if in_imported_uma(lo, hi - lo) { + let k = STATS[SKIPPED_UMA].fetch_add(1, Ordering::Relaxed); + if k < 8 { + crate::xlog_info!( + "copy back: skipped {} texture {res:#x} at {va:#x} ({len} B, flags {flags:#x}) inside imported coherent UMA window (PAGE_NOACCESS impossible)", + if is_gpu { "GPU-owned" } else { "kept" } + ); + } + return; + } + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let s = g.get_or_insert_with(State::default); + if s.refused.contains(&res) { + return; + } + if let Some(&at) = s.by_res.get(&res) { + // Still armed (the CPU did not touch it since): wait for the newer write. + if let Some(a) = s.armed.get_mut(&at) { + a.fence = Shared(fence.clone()); + a.value = value; + } + return; + } + if let Some((&other_lo, other)) = s.armed.range(..hi).next_back() { + if other.hi > lo { + if other_lo == lo && other.hi == hi { + // Exact-VA alias overwritten by a newer GPU writer: retarget armed entry in place. + let old_res = other.res; + s.by_res.remove(&old_res); + if let Some(a) = s.armed.get_mut(&other_lo) { + a.res = res; + a.gpu_owned = is_gpu; + a.fence = Shared(fence.clone()); + a.value = value; + } + s.by_res.insert(res, lo); + STATS[ARMS].fetch_add(1, Ordering::Relaxed); + if is_gpu { + STATS[ARMS_GPU].fetch_add(1, Ordering::Relaxed); + } + return; + } + STATS[SKIPPED_OVERLAP].fetch_add(1, Ordering::Relaxed); + return; + } + } + // Register with `guest_write` first so a concurrent kernel write faults here and opens the page. + if guest_write::enabled() { + guest_write::register(lo, hi - lo); + } + let runs = protect_rw_runs(lo, hi); + if runs.is_empty() { + if guest_write::enabled() { + guest_write::unregister(lo, hi - lo); + } + STATS[SKIPPED_PROT].fetch_add(1, Ordering::Relaxed); + return; + } + install(); + s.by_res.insert(res, lo); + s.armed.insert(lo, Armed { res, gpu_owned: is_gpu, lo, hi, runs, fence: Shared(fence.clone()), value }); + ANY_ARMED.store(true, Ordering::Release); + STATS[ARMS].fetch_add(1, Ordering::Relaxed); + if is_gpu { + STATS[ARMS_GPU].fetch_add(1, Ordering::Relaxed); + } +} + +/// Protect committed read-write pages in `[lo, hi)` as `PAGE_NOACCESS` (leaving pinned writes alone). +unsafe fn protect_rw_runs(lo: usize, hi: usize) -> Vec<(usize, usize)> { + let mut runs = Vec::new(); + let mut at = lo; + while at < hi { + 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 || m.RegionSize == 0 { + break; + } + let end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi); + if end <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE { + let n = end - at; + let done = if guest_write::enabled() { + guest_write::while_unpinned(at, n, || protect(at, n, PAGE_NOACCESS)) + } else { + protect(at, n, PAGE_NOACCESS) + }; + if done { + runs.push((at, n)); + } + } + at = end; + } + runs +} + +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 +} + +/// Restore `PAGE_READWRITE` on runs still marked `PAGE_NOACCESS` (pages freed or re-protected by +/// the title since arming are left untouched). +unsafe fn open_runs(runs: &[(usize, usize)]) { + for &(a, n) in runs { + let end = a.saturating_add(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 || m.RegionSize == 0 { + break; + } + let next = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(end); + if next <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == PAGE_NOACCESS { + protect(at, next - at, PAGE_READWRITE); + } + at = next; + } + } +} + +/// Disarm any armed textures overlapping `[va, va + len)` without removing their GPU-owned +/// metadata. Called before `title_textures::publish_download` reads or writes title memory so +/// eager `Copy*`/`Resolve*` download publication never hits `PAGE_NOACCESS` or holds back a fence. +/// Takes `HANDLER` first so any in-flight fault read-back completes and opens its pages first. +pub(super) fn disarm_overlapping(va: usize, len: usize) { + if !on() || !ANY_ARMED.load(Ordering::Acquire) || len == 0 { + return; + } + let hi = va.saturating_add(len); + let _one = HANDLER.lock().unwrap_or_else(|e| e.into_inner()); + let to_disarm: Vec = with(|s| { + if s.armed.is_empty() { + return Vec::new(); + } + let keys: Vec = s + .armed + .range(..hi) + .filter(|(_, a)| a.hi > va) + .map(|(&lo, _)| lo) + .collect(); + let mut out = Vec::with_capacity(keys.len()); + for lo in keys { + if let Some(a) = s.armed.remove(&lo) { + s.by_res.remove(&a.res); + out.push(a); + } + } + if !out.is_empty() { + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + } + out + }); + for a in &to_disarm { + disarm(a); + } +} + +/// Texture `res` was released or retired: open its armed pages unread and forget its metadata. +pub fn forget(res: usize) { + if !on() { + return; + } + let a = with(|s| { + s.refused.remove(&res); + if s.gpu_owned.remove(&res).is_some() { + HAS_GPU_OWNED.store(!s.gpu_owned.is_empty(), Ordering::Release); + } + let at = s.by_res.remove(&res)?; + let a = s.armed.remove(&at); + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + a + }); + if let Some(a) = a { + disarm(&a); + } +} + +fn disarm(a: &Armed) { + unsafe { open_runs(&a.runs) }; + if guest_write::enabled() { + guest_write::unregister(a.lo, a.hi - a.lo); + } +} + +fn install() { + if !INSTALLED.swap(true, Ordering::AcqRel) { + unsafe { AddVectoredExceptionHandler(1, Some(handler)) }; + } +} + +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 || !ANY_ARMED.load(Ordering::Acquire) { + return EXCEPTION_CONTINUE_SEARCH; + } + if IN_HANDLER.with(|h| h.get()) { + return EXCEPTION_CONTINUE_SEARCH; + } + let (write, at) = (r.ExceptionInformation[0] == 1, r.ExceptionInformation[1]); + if fault(at) || accessible(at, write) { + EXCEPTION_CONTINUE_EXECUTION + } else { + EXCEPTION_CONTINUE_SEARCH + } +} + +/// Handle a CPU access violation at `at`: if it falls inside an armed texture, download and +/// re-tile the texture back into title memory and restore `PAGE_READWRITE`. +fn fault(at: usize) -> bool { + let _one = HANDLER.lock().unwrap_or_else(|e| e.into_inner()); + let taken = with(|s| { + let (&lo, a) = s.armed.range(..=at).next_back()?; + if at >= a.hi { + return None; + } + s.by_res.remove(&a.res); + let a = s.armed.remove(&lo)?; + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + let gpu_info = if a.gpu_owned { + s.gpu_owned.get(&a.res).and_then(|g| { + let p = a.res as *mut c_void; + let r = unsafe { ID3D12Resource::from_raw_borrowed(&p) }?.clone(); + Some((g.device, g.src, Arc::clone(&g.tex), g.states.clone(), r)) + }) + } else { + None + }; + Some((a, gpu_info)) + }); + let Some((a, gpu_info)) = taken else { return false }; + IN_HANDLER.with(|h| h.set(true)); + let t0 = std::time::Instant::now(); + let r = unsafe { + if a.gpu_owned { + match gpu_info { + Some((device, src, tex, states, res)) => { + super::title_textures::download_and_write_after(device, src, &tex, &states, &res, &a.fence.0, a.value, || open_runs(&a.runs)) + } + None => Err("GPU-owned texture released before read-back".into()), + } + } else { + super::title_textures::read_back_after(a.res, &a.fence.0, a.value, || open_runs(&a.runs)) + } + }; + // Always open the pages whether or not read-back succeeded so the title can continue. + disarm(&a); + IN_HANDLER.with(|h| h.set(false)); + STATS[FAULTS].fetch_add(1, Ordering::Relaxed); + STATS[HANDLER_NS].fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed); + match r { + Ok(n) => { + STATS[READ_BACK_BYTES].fetch_add(n as u64, Ordering::Relaxed); + } + Err(e) => { + let k = STATS[FAILED].fetch_add(1, Ordering::Relaxed); + with(|s| s.refused.insert(a.res)); + if k < 8 { + crate::xlog_warn!( + "copy back: {} texture {:#x} at {:#x}: read-back failed ({e}); its pages are open, it is not armed again", + if a.gpu_owned { "GPU-owned" } else { "kept" }, + a.res, + a.lo + ); + } + } + } + true +} + +/// Whether the page at `at` already allows the access (lost a race against another thread that +/// faulted on the same texture and opened it meanwhile). +fn accessible(at: usize, write: bool) -> bool { + 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.State != MEM_COMMIT { + return false; + } + let p = m.Protect & 0xFF; + let ok = if write { matches!(p, 0x04 | 0x08 | 0x40 | 0x80) } else { !matches!(p, 0x01) && m.Protect & 0x100 == 0 }; + if ok { + STATS[RACES].fetch_add(1, Ordering::Relaxed); + } + ok +} + +/// Periodic diagnostic counter line (logged alongside `submit_cost` every 1024 submits when on). +pub fn line() -> Option { + if !on() { + return None; + } + static LAST: Mutex<[u64; NSTATS]> = Mutex::new([0; NSTATS]); + let now: [u64; NSTATS] = std::array::from_fn(|i| STATS[i].load(Ordering::Relaxed)); + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + let d: [u64; NSTATS] = std::array::from_fn(|i| now[i] - last[i]); + *last = now; + let (armed, armed_gpu, gpu_live) = with(|s| { + let ag = s.armed.values().filter(|a| a.gpu_owned).count(); + (s.armed.len(), ag, s.gpu_owned.len()) + }); + let skipped = d[SKIPPED_UMA] + d[SKIPPED_UNSUP] + d[SKIPPED_SMALL] + d[SKIPPED_OVERLAP] + d[SKIPPED_PROT]; + let c: [u64; NCENSUS] = std::array::from_fn(|i| CENSUS[i].load(Ordering::Relaxed)); + Some(format!( + "copy back: {} textures armed ({} gpu-owned), {} faults ({:.1} MB read back, {} failed, {:.2} ms in the handler), {} races, {} skipped (uma {} unsup {} small {} overlap {} prot {}), {} writes with no list; now {armed} armed ({armed_gpu} gpu); gpu-owned census: {} live, reg uma {} ({:.1} MB) sparse {} ({:.1} MB) other {} ({:.1} MB) unsup {}", + d[ARMS], + d[ARMS_GPU], + d[FAULTS], + d[READ_BACK_BYTES] as f64 / 1e6, + d[FAILED], + d[HANDLER_NS] as f64 / 1e6, + d[RACES], + skipped, + d[SKIPPED_UMA], + d[SKIPPED_UNSUP], + d[SKIPPED_SMALL], + d[SKIPPED_OVERLAP], + d[SKIPPED_PROT], + d[NO_LIST], + gpu_live, + c[C_UMA], + c[C_UMA_BYTES] as f64 / 1e6, + c[C_SPARSE], + c[C_SPARSE_BYTES] as f64 / 1e6, + c[C_OTHER], + c[C_OTHER_BYTES] as f64 / 1e6, + c[C_UNSUP], + )) +} + +#[cfg(test)] +pub(super) fn force(on: bool) { + FORCE.store(if on { 2 } else { 1 }, Ordering::Relaxed); +} + +#[cfg(test)] +pub(super) fn is_armed(res: usize) -> bool { + with(|s| s.by_res.contains_key(&res)) +} + +#[cfg(test)] +pub(super) fn stats() -> (u64, u64, u64) { + (STATS[ARMS].load(Ordering::Relaxed), STATS[FAULTS].load(Ordering::Relaxed), STATS[FAILED].load(Ordering::Relaxed)) +} + +#[cfg(test)] +pub(super) fn skip_stats() -> (u64, u64) { + (STATS[SKIPPED_UMA].load(Ordering::Relaxed), STATS[SKIPPED_UNSUP].load(Ordering::Relaxed)) +} diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index cc99c0f778..f5344977a8 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1267,7 +1267,8 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, let mut placed_hr = None; if !buffer { let pc = std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC); - let console_bytes = crate::hle::xg::Texture::new(&x).ok().map(|t| t.size()).filter(|&s| s != u64::MAX && s != 0); + let console_tex = crate::hle::xg::Texture::new(&x).ok(); + let console_bytes = console_tex.as_ref().map(|t| t.size()).filter(|&s| s != u64::MAX && s != 0); if super::vram::gpu_owned(flags) { if let Some(hr) = super::vram::place(this, va as usize, &pc, state, clear, console_bytes, riid, ppv) { if hr >= 0 && !(*ppv).is_null() { @@ -1276,6 +1277,11 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, super::title_textures::retire_overlapping(va as usize, bytes as usize); } } + if super::copy_back::on() { + if let Some(tex) = console_tex { + super::copy_back::register_gpu_owned(this as usize, *ppv as usize, va as usize, tex, &pc, flags, state); + } + } real::note_title_address(*ppv as usize, va as usize); super::depth_uav::note_created(*ppv, &x, Some(va as usize), state); super::format_alias::register_title_texture(this as usize, *ppv as usize, va as usize, &pc, flags, state); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index e4ccbf9bb8..e9bbe2ff29 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1694,7 +1694,9 @@ impl<'a> SubmissionChunk<'a> { for trace in self.traces.iter().flatten() { mark_trace(trace, ListEvent::Executed); } - submit_segment_effects(queue, self.effects, self.needs_cpu_completion) + let completion = submit_segment_effects(queue, self.effects, self.needs_cpu_completion); + super::copy_back::after_submit(queue, self.lists); + completion } } @@ -1956,6 +1958,7 @@ pub(super) unsafe fn on_create_with_backing(list: *mut c_void, alloc: usize, bac drop(old); super::lut3d::list_reset(key); super::format_alias::list_reset(key); + super::copy_back::list_reset(key); // Dynamic-depth-bias PSOs ignore baked RasterizerState depth bias; seed the list with the // initial PSO's static bias if non-zero (CreateCommandList resets RSSetDepthBias to 0). if ty != D3D12_COMMAND_LIST_TYPE_BUNDLE && pso != 0 { @@ -1977,6 +1980,7 @@ pub(super) fn on_release(list: usize) { super::real::dispatch_chain::list_reset(list); super::lut3d::list_reset(list); super::format_alias::list_reset(list); + super::copy_back::list_reset(list); let old = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)); if let Some(old) = old { if old.has_sparse() { @@ -2002,6 +2006,7 @@ pub(super) fn clear_segment_state(list: usize) { trace_list(list, ListEvent::Reset); super::lut3d::list_reset(list); super::format_alias::list_reset(list); + super::copy_back::list_reset(list); let old_generations = { let mut g = LISTS.lock().unwrap(); let Some(s) = g.as_mut().and_then(|m| m.get_mut(&list)) else { return }; @@ -2173,6 +2178,9 @@ fn note_write(list: usize, producer: WriteProducer, va: u64, size: u64) { } fn note_texture_write(list: usize, res: usize, subresource: u32) { + if super::copy_back::on() { + super::copy_back::note_write(list, res); + } let Some(write) = super::title_textures::capture_gpu_write(res, subresource) else { return }; LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().texture_writes.push(write); } @@ -4875,6 +4883,7 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - drop(old_next); super::bind::install_prepared_split(next_bindings); super::lut3d::list_reset(next_pc as usize); + super::copy_back::list_reset(next_pc as usize); restore_bindings(next_pc, bindings, ty); if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { @@ -5626,6 +5635,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { super::lut3d::submitted(&submitted); for &p in &submitted { super::lut3d::list_reset(p as usize); + super::copy_back::list_reset(p as usize); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(p as usize))) { s.texture_transitions.clear(); } @@ -5665,6 +5675,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { super::format_alias::list_reset(this as usize); copy_scratch_submitted(q_raw, &one); super::title_textures::publish_submission_effects(queue_identity(q_raw as usize), &texture_writes, &texture_transitions); + super::copy_back::after_submit(q_raw, &one); + super::copy_back::list_reset(this as usize); if let Some(w) = kickoff_wrapper { super::title_textures::forget_list_closed(w as usize); } @@ -6665,6 +6677,7 @@ unsafe fn reset_pc_inner(this: *mut c_void, alloc: usize, pso: usize) -> i32 { prepared.commit(this, on); super::lut3d::list_reset(this as usize); super::format_alias::list_reset(this as usize); + super::copy_back::list_reset(this as usize); super::dred::reset(this); if pso != 0 && resolved != 0 { super::dred::mark_pipeline(this, pso, resolved); @@ -6755,6 +6768,9 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 uav_global = true; } else { uav_targets.push(uav_res); + if super::copy_back::on() { + super::copy_back::note_write(this as usize, uav_res); + } } b[2..4].fill(0); if any_uav { @@ -6810,6 +6826,11 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 note_texture_transitions(this as usize, &t); super::lut3d::note_transitions(this as usize, &t); } + if super::copy_back::on() && out.iter().any(|b| b[0] == 0) { + let cb: Vec<(usize, u32, u32, u32)> = + out.iter().filter(|b| b[0] == 0).map(|b| ((b[2] as u64 | (b[3] as u64) << 32) as usize, b[4], b[5], b[6])).collect(); + super::copy_back::note_transitions(this as usize, &cb); + } // (a superseded target the title moves is used again: `placements`) for b in out.iter().filter(|b| b[0] == 0) { super::placements::note_use((b[2] as u64 | (b[3] as u64) << 32) as usize); @@ -7477,6 +7498,11 @@ pub(super) unsafe extern "system" fn clear_depth_stencil_x(this: *mut c_void, ds ); } } + if super::copy_back::on() { + if let Some(r) = super::present::rtv_resource(dsv) { + super::copy_back::note_write(this as usize, r); + } + } pc::(this, PC_CLEAR_DEPTH_STENCIL_VIEW)(this, dsv, flags, depth, stencil, n, rects) } @@ -7549,7 +7575,11 @@ unsafe fn clear_uav(this: *mut c_void, slot: usize, gpu: u64, cpu: u64, res: usi } return refused(); } + let orig_res = res; let Some(res) = uav_clear_resource(res, gpu_slot) else { return refused() }; + if super::copy_back::on() { + super::copy_back::note_write(this as usize, orig_res); + } // (a clear of a depth twin writes it) depth_twins_before_work(this, false); pc::(this, slot)(this, gpu, cpu, res, values, n, rects) diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index c5ad298957..3548dbf798 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -25,6 +25,7 @@ mod depth_uav; mod format_alias; pub mod device_x; pub mod dxgi_device; +mod copy_back; mod cpu_writes; pub mod dred; mod fence_x; diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index b81280f6a2..9b24b8fbda 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -699,6 +699,7 @@ pub(super) fn invalidate_queue_caches(id: QueueId) { super::sparse::forget_queue(id); super::title_textures::forget_queue(id); super::vram::forget_queue(id); + super::copy_back::forget_queue(raw); } fn retirement_worker() -> Option<&'static mpsc::Sender<()>> { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 92957368ab..c3526eaaa4 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2736,6 +2736,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { super::format_alias::forget(this as usize); super::ambient::forget_resource(this as usize); let final_state = super::title_textures::forget(this as usize); + super::copy_back::forget(this as usize); super::lut3d::forget(this as usize); if !had_private_data { if let (Some(info), Some(state)) = (recycle, final_state) { @@ -3498,9 +3499,9 @@ unsafe extern "system" fn dev_create_dsv_x(this: *mut c_void, res: *mut c_void, if copy.is_none() { copy = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| default_dsv(&r.GetDesc())); } - // `XCL_DUMP_TARGETS`: the depth buffer a DSV names, kept with the RTVs' resources (DSV - // and RTV handles are in different heaps) - if super::targets::enabled() { + // `XCL_DUMP_TARGETS` / `XCL_COPY_BACK`: the depth buffer a DSV names, kept with the RTVs' + // resources (DSV and RTV handles are in different heaps) + if super::targets::enabled() || super::copy_back::on() { super::present::note_rtv(cpu as usize, res); } if super::capture::enabled() { @@ -12439,6 +12440,11 @@ unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *co super::lut3d::wrote(r, false, || format!("ClearRenderTargetView {rtv:#x} to {:?}, {n} rects", color.as_ref())); } } + if super::copy_back::on() { + if let Some(r) = super::present::rtv_resource(rtv) { + super::copy_back::note_write(this as usize, r); + } + } f(this, rtv, color, n, rects) } @@ -12462,15 +12468,29 @@ unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rt } if n > 0 && !rtvs.is_null() { super::present::note_rt0(this as usize, *rtvs); - if super::present::trace_uses() { + if super::present::trace_uses() || super::copy_back::on() { + let cb = super::copy_back::on(); + let tu = super::present::trace_uses(); for k in 0..n as usize { let h = if single != 0 { *rtvs + k * 32 } else { *rtvs.add(k) }; if let Some(r) = super::present::rtv_resource(h) { - super::present::note_use(r, super::present::USE_RT); + if tu { + super::present::note_use(r, super::present::USE_RT); + } + if cb { + super::copy_back::note_write(this as usize, r); + } } } } } + if super::copy_back::on() { + if let Some(h) = dsv.as_ref().copied() { + if let Some(r) = super::present::rtv_resource(h) { + super::copy_back::note_write(this as usize, r); + } + } + } } /// Bind an already-selected exact native generation without sending its raw pointer back through diff --git a/crates/xcl/src/hle/d3d12x/submit_cost.rs b/crates/xcl/src/hle/d3d12x/submit_cost.rs index f0da57f19a..27d288e7bf 100644 --- a/crates/xcl/src/hle/d3d12x/submit_cost.rs +++ b/crates/xcl/src/hle/d3d12x/submit_cost.rs @@ -189,6 +189,9 @@ pub(super) fn done(t0: Instant) { 1024.0 / l.at.elapsed().as_secs_f64().max(1e-3), outside_part(&ms) ); + if let Some(line) = super::copy_back::line() { + crate::xlog_info!("{line}"); + } } *g = Some(Last { sum: now, parts, tex, at: Instant::now() }); } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 9b1f2ec4c1..5a89f81078 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1018,6 +1018,11 @@ fn mirror_source(va: usize) -> usize { if mapped { va } else { src } } +/// CPU-accessible title memory VA for `va` (`mirror_source`). +pub(super) fn mirror_source_of(va: usize) -> usize { + mirror_source(va) +} + /// Where a texture at `va` of `size` bytes is read, and whether through a table of its pages: a /// texture over pages of a GPU view the queue's page mappings named is read at `va`, each page /// where it is kept (no lock of AWAY, no VirtualQuery); any other as `mirror_source` says. @@ -1373,12 +1378,15 @@ pub(super) fn publish_submission_effects(queue: Option, writes: & /// (`format_alias`) Texture `res` is written by GPU work XCL itself recorded, with no title /// submit to publish it through (`publish_submission_effects`): its CPU view is stale from now on /// and is not uploaded again. `_list` is kept for the caller's form (0: none). -pub fn note_gpu_write(_list: usize, res: usize) { +pub fn note_gpu_write(list: usize, res: usize) { let marked = TEXTURES.lock().unwrap().mark_gpu_written(res); if marked { GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); STREAM_RECHECK.lock().unwrap().remove(&res); } + if super::copy_back::on() { + super::copy_back::note_write(list, res); + } } /// (`XCL_HEAP_COUNT=1`) What the texture upload buffers hold now, for the periodic log line. @@ -1439,6 +1447,7 @@ pub(super) unsafe fn retire_overlapping(va: usize, len: usize) { /// when all subresources shared a single state (used by `vram` to recycle reserved textures safely). pub fn forget(res: usize) -> Option { STREAM_RECHECK.lock().unwrap().remove(&res); + super::copy_back::forget(res); let (removed, to_remap, state) = { let mut t = TEXTURES.lock().unwrap(); let (removed, delta, remap_ptrs, state) = t.remove(res); @@ -1687,7 +1696,7 @@ pub(super) fn capture_transitions(transitions: &[(usize, u32, D3D12_RESOURCE_STA } /// Subresources of a texture kept in step (as `subresources` makes them). -fn subresource_count(tex: &xg::Texture) -> usize { +pub(super) fn subresource_count(tex: &xg::Texture) -> usize { tex.texels().map_or(1, |s| s.array as usize * s.chain.levels.len()) } @@ -4202,6 +4211,165 @@ unsafe fn subresources_in(va: usize, tex: &xg::Texture, pages: Option<&texture_u } /// The bounded part of a mapped D3D12 readback buffer which holds one subresource. +/// Write `subs` (every subresource, D3D12 order, as `subresources` gives them) into the title's +/// memory at `va` in the console layout of `tex`: the reverse of `subresources`. Only the 4 KiB +/// pages whose bytes change are written, and of them only the committed, writable ones. +/// Returns the bytes written. +unsafe fn write_subresources(va: usize, tex: &xg::Texture, subs: &[Subresource]) -> Result { + let Some(t) = tex.texels() else { return Err("a texture without texels".into()) }; + let c = &t.chain; + let bpe = t.bpe as usize; + let volume = t.depth > 0; + let slices = if volume { 1 } else { t.array as usize }; + if subs.len() != slices * c.levels.len() { + return Err(format!("{} subresources, the console layout has {}", subs.len(), slices * c.levels.len())); + } + for (k, s) in subs.iter().enumerate() { + let l = &c.levels[k % c.levels.len()]; + let depth = if volume { l.depth } else { 1 }; + if (s.row_bytes, s.rows, s.depth) != (l.width * bpe, l.height, depth) || s.data.len() < s.row_bytes * s.rows * s.depth { + return Err(format!("subresource {k} is {}x{}x{} B, the console layout's {}x{}x{} B", s.row_bytes, s.rows, s.depth, l.width * bpe, l.height, depth)); + } + } + let len = if volume { tex.size() as usize } else { slices * c.slice_bytes }; + // Owned copy, page-safe (`read_committed`): a borrowed view of title memory could fault if a + // title thread unmaps a page concurrently. + let old = read_committed(va, len); + let mut mem = old.clone(); + if volume { + for (i, s) in subs.iter().enumerate() { + c.tile_volume(&mut mem, i, &s.data); + } + } else { + for (s, slice) in mem.chunks_exact_mut(c.slice_bytes).enumerate() { + for (i, sub) in subs[s * c.levels.len()..][..c.levels.len()].iter().enumerate() { + c.tile_level(slice, i, s, &sub.data); + } + } + } + // Coalesce changed 4 KiB pages into contiguous runs. + let mut runs: Vec<(usize, usize)> = Vec::new(); + let mut p = va; + while p < va + len { + let end = ((p & !0xFFF) + 0x1000).min(va + len); + if mem[p - va..end - va] != old[p - va..end - va] { + match runs.last_mut() { + Some((_, b)) if *b == p => *b = end, + _ => runs.push((p, end)), + } + } + p = end; + } + let mut written = 0; + for (a, b) in runs { + written += write_writable(a, &mem[a - va..b - va]); + } + Ok(written) +} + +/// Write `bytes` into title memory at `at`, on its committed writable pages only (unmapped, +/// read-only, and guard pages are left untouched). Returns the bytes written. +unsafe fn write_writable(at: usize, bytes: &[u8]) -> usize { + use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory; + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let limit = at.saturating_add(bytes.len()); + let mut written = 0; + let mut p = at; + while p < limit { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(p as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.RegionSize == 0 { + break; + } + let end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(limit); + if end <= p { + break; + } + // RW / WC / X-RW / X-WC, no guard (WriteProcessMemory would otherwise alter RO pages). + if m.State == MEM_COMMIT && m.Protect & 0xCC != 0 && m.Protect & 0x100 == 0 { + let mut n = 0usize; + WriteProcessMemory(GetCurrentProcess(), p as *const c_void, bytes[p - at..].as_ptr() as *const c_void, end - p, &mut n); + written += n; + } + p = end; + } + written +} + +/// Copy what the GPU holds in title texture `res` back into title memory (`Entry::src`) in console +/// layout (#2663). The GPU work that wrote it must already be complete. Returns bytes written. +#[allow(dead_code)] // tests; `read_back_after` / `download_and_write_after` are used by `copy_back` +pub(super) unsafe fn read_back(res: usize) -> Result { + let (device, src, tex, states, r) = { + let t = TEXTURES.lock().unwrap(); + let e = t.by_res.get(&res).ok_or("not a title texture")?; + let p = res as *mut c_void; + let r = ID3D12Resource::from_raw_borrowed(&p).cloned().ok_or("no resource")?; + (e.device, e.src, Arc::clone(&e.tex), e.states.clone(), r) + }; + let d = device as *mut c_void; + let dev = ID3D12Device::from_raw_borrowed(&d).ok_or("no device")?; + let subs = own_work(|| -> Result, String> { + let queue = upload_queue(dev, device)?; + super::vram::before_execute(&queue); + texture::download(dev, &queue, &r, &states) + })?; + write_subresources(src, &tex, &subs) +} + +/// Shared GPU-wait + download + re-tile back into title memory at `src` for both kept +/// (`title_textures`) and GPU-owned (`copy_back::register_gpu_owned`) textures. +pub(super) unsafe fn download_and_write_after( + device: usize, + src: usize, + tex: &xg::Texture, + states: &[D3D12_RESOURCE_STATES], + r: &ID3D12Resource, + fence: &ID3D12Fence, + value: u64, + before_write: impl FnOnce(), +) -> Result { + let d = device as *mut c_void; + let dev = ID3D12Device::from_raw_borrowed(&d).ok_or("no device")?; + let subs = own_work(|| -> Result, String> { + let queue = upload_queue(dev, device)?; + super::real::native_queue_wait(&queue, fence, value).map_err(|e| e.to_string())?; + super::vram::before_execute(&queue); + texture::download(dev, &queue, r, states) + }); + before_write(); + write_subresources(src, tex, &subs?) +} + +/// `read_back` for `XCL_COPY_BACK=fault` (`copy_back`), from the fault handler of the thread that +/// touched the texture's pages: XCL's copy waits on the GPU for `value` on `fence` (the title's +/// submit that wrote it), `before_write` runs between the copy and the write (opening the pages), +/// and `TEXTURES` is taken with a bounded retry in case the faulting thread holds it. +pub(super) unsafe fn read_back_after(res: usize, fence: &ID3D12Fence, value: u64, before_write: impl FnOnce()) -> Result { + let t0 = std::time::Instant::now(); + let (device, src, tex, states, r) = loop { + match TEXTURES.try_lock() { + Ok(t) => { + let e = t.by_res.get(&res).ok_or("not a title texture")?; + let p = res as *mut c_void; + let r = ID3D12Resource::from_raw_borrowed(&p).cloned().ok_or("no resource")?; + break (e.device, e.src, Arc::clone(&e.tex), e.states.clone(), r); + } + Err(std::sync::TryLockError::Poisoned(_)) => return Err("the texture registry is poisoned".into()), + Err(std::sync::TryLockError::WouldBlock) if t0.elapsed() < std::time::Duration::from_millis(200) => std::thread::yield_now(), + Err(std::sync::TryLockError::WouldBlock) => return Err("the texture registry stayed busy (held by the faulting thread?)".into()), + } + }; + download_and_write_after(device, src, &tex, &states, &r, fence, value, before_write) +} + +/// `XCL_COPY_BACK`: the title memory of texture `res` kept in step (`(start, bytes)`). +pub(super) fn copy_back_range(res: usize) -> Option<(usize, usize)> { + let t = TEXTURES.lock().unwrap(); + let e = t.by_res.get(&res)?; + Some((e.src, e.tex.size() as usize)) +} + /// `width`, `height`, and `depth` are texels (not format blocks); `size` bounds all reads. #[derive(Clone, Copy, Debug)] #[allow(dead_code)] // Stage 3 seam; queue/readback activation is a later change. @@ -4752,6 +4920,7 @@ pub(super) unsafe fn tie_downloads(fence: *mut c_void, value: u64, downloads: Ve fn publish_download(download: &ReadyDownload) -> Result { let Some(readback) = (unsafe { download.ticket.readback_bytes()? }) else { return Ok(false) }; let size = usize::try_from(download.ticket.layout().size()).map_err(|_| "texture download destination is too large")?; + super::copy_back::disarm_overlapping(download.target, size); let current = unsafe { with_title_bytes(download.target, size, <[u8]>::to_vec) }; let mut console = Vec::new(); console.try_reserve_exact(size).map_err(|_| "cannot allocate texture download destination")?; @@ -8491,4 +8660,509 @@ pub(super) mod tests { assert!(ok.is_ok()); assert_eq!((drops.get(), released.get()), (1, 1), "successful wait must drop and recycle submitted resources"); } + + /// A page of the texture's memory that the title unmapped is read as zeros and not written + /// (nor mapped again); the others get their texels. + #[test] + fn written_subresources_skip_a_page_the_title_unmapped() { + use windows_sys::Win32::System::Memory as mem; + let tex = xg::Texture::new(&console_desc(3, 256, 256, 1, 1, 28, 0x105)).unwrap(); + let size = tex.size() as usize; + assert!(size >= 3 * 4096); + let want_mem: Vec = (0..size).map(|i| (i * 7 + i / 4096) as u8).collect(); + unsafe { + let want = subresources(want_mem.as_ptr() as usize, &tex); + let va = mem::VirtualAlloc(std::ptr::null(), size, mem::MEM_COMMIT | mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_ne!(va, 0); + // The title unmapped its second page. + assert_ne!(mem::VirtualFree((va + 4096) as *mut c_void, 4096, mem::MEM_DECOMMIT), 0); + let n = write_subresources(va, &tex, &want).unwrap(); + assert_eq!(n, size - 4096, "every page but the unmapped one written"); + let mut info: mem::MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + assert_ne!(mem::VirtualQuery((va + 4096) as *const c_void, &mut info, std::mem::size_of_val(&info)), 0); + assert_eq!(info.State, mem::MEM_RESERVE, "the unmapped page stays unmapped"); + let mut tiled = vec![0u8; size]; + let c = &tex.texels().unwrap().chain; + c.tile_level(&mut tiled, 0, 0, &want[0].data); + for p in [0, 2] { + let got = std::slice::from_raw_parts((va + p * 4096) as *const u8, 4096); + assert!(got == &tiled[p * 4096..(p + 1) * 4096], "page {p}"); + } + assert_ne!(mem::VirtualFree(va as *mut c_void, 0, mem::MEM_RELEASE), 0); + } + } + + /// `write_subresources` round-trips 2D arrays, non-power-of-two mip chains, 3D volumes, BC7 + /// textures, and tiny sub-page textures, writes only changed pages, and rejects mismatched sizes. + #[test] + fn written_subresources_round_trip() { + let descs = [ + console_desc(3, 64, 64, 2, 3, 28, 0x105), + console_desc(3, 200, 72, 1, 5, 28, 0x105), + console_desc(4, 40, 24, 6, 3, 28, 0x105), + console_desc(3, 256, 256, 1, 9, 98, 0x10A), + console_desc(3, 4, 4, 1, 1, 28, 0x105), + ]; + unsafe { + for d in descs { + let tex = xg::Texture::new(&d).unwrap(); + let size = tex.size() as usize; + let src_mem: Vec = (0..size).map(|i| (i * 11 + i / 4096 + 3) as u8).collect(); + let want = subresources(src_mem.as_ptr() as usize, &tex); + let mut title = vec![0x5Au8; size + 4096]; + let at = title.as_mut_ptr() as usize; + let n = write_subresources(at, &tex, &want).unwrap(); + assert!(n > 0, "{d:02x?}: nothing written"); + assert!(subresources(at, &tex) == want, "{d:02x?}: the written memory reads back as other texels"); + assert!(title[size..].iter().all(|&b| b == 0x5A), "{d:02x?}: bytes past the texture written"); + assert_eq!(write_subresources(at, &tex, &want).unwrap(), 0, "{d:02x?}: unchanged pages written again"); + let mut wrong = want.clone(); + wrong[0].rows += 1; + assert!(write_subresources(at, &tex, &wrong).is_err()); + assert!(write_subresources(at, &tex, &want[1..]).is_err()); + } + } + } + + /// #2663: a GPU copy into a kept title texture leaves title memory stale without a download; + /// with `XCL_COPY_BACK=fault`, the submit arms its pages and a plain CPU read faults, waits on + /// the submit fence, downloads, and re-tiles the GPU's texels into console layout. + #[test] + fn copy_back_a_cpu_read_of_a_gpu_written_texture_sees_the_gpu_texels() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + use windows_sys::Win32::System::Memory as mem; + use super::super::copy_back; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + struct Done(usize, usize); + impl Drop for Done { + fn drop(&mut self) { + forget(self.0); + unsafe { mem::VirtualFree(self.1 as *mut c_void, 0, mem::MEM_RELEASE) }; + copy_back::force(false); + } + } + unsafe fn protection(at: usize) -> u32 { + let mut m: mem::MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + assert_ne!(mem::VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)), 0); + m.Protect + } + let console = console_desc(3, 64, 64, 2, 3, 28, 0x105); + let tex = xg::Texture::new(&console).unwrap(); + let size = tex.size() as usize; + assert!(size >= 2 * 4096, "{size}"); + let list = 0x7E57_0001usize; + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let pages = size.div_ceil(4096) + 1; + let va = mem::VirtualAlloc(std::ptr::null(), pages * 4096, mem::MEM_COMMIT | mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_ne!(va, 0); + std::ptr::write_bytes(va as *mut u8, 0x5A, pages * 4096); + let mut texture: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 2, MipLevels: 3, Format: DXGI_FORMAT(28), SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut texture, + ).unwrap(); + let texture = texture.unwrap(); + let key = texture.as_raw() as usize; + register(raw_device, texture.as_raw(), va, &console, D3D12_RESOURCE_STATE_COMMON).unwrap(); + let _done = Done(key, va); + let (arms0, faults0, failed0) = copy_back::stats(); + for (round, seed) in [(0usize, 13usize), (1, 29)] { + let gpu_mem: Vec = (0..size).map(|i| (i * seed + i / 4096 + round + 1) as u8).collect(); + let want = subresources(gpu_mem.as_ptr() as usize, &tex); + texture::upload(dev, &queue, &texture, &want, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COMMON).unwrap(); + copy_back::force(false); + note_gpu_write(list, key); + copy_back::after_submit(queue.as_raw(), &[list as *mut c_void]); + assert!(!copy_back::is_armed(key)); + assert!(subresources(va, &tex) != want, "round {round}: the title's memory already holds the GPU's texels"); + + copy_back::force(true); + note_gpu_write(list, key); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + if round == 1 { + queue.Wait(&gate, 1).unwrap(); + let g = gate.as_raw() as usize; + let g2 = gate.clone(); + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(200)); + let p = g as *mut c_void; + ID3D12Fence::from_raw_borrowed(&p).unwrap().Signal(1).unwrap(); + }); + std::mem::forget(g2); + } + let t_submit = std::time::Instant::now(); + copy_back::after_submit(queue.as_raw(), &[list as *mut c_void]); + assert!(copy_back::is_armed(key), "round {round}: not armed"); + assert_eq!(protection(va), mem::PAGE_NOACCESS, "round {round}"); + if size % 4096 != 0 { + assert_eq!(protection(va + (size & !0xFFF)), mem::PAGE_READWRITE, "round {round}: partial last page must stay readable"); + } + let first = std::ptr::read_volatile((va + 4) as *const u8); + if round == 1 { + assert!(t_submit.elapsed() >= std::time::Duration::from_millis(150), "the read did not wait for the title's submit: {:?}", t_submit.elapsed()); + } + assert_eq!(protection(va), mem::PAGE_READWRITE, "round {round}: open after the read"); + assert!(!copy_back::is_armed(key)); + let mut tiled = vec![0u8; size]; + std::ptr::copy_nonoverlapping(va as *const u8, tiled.as_mut_ptr(), size); + assert_eq!(first, tiled[4]); + assert!(subresources(va, &tex) == want, "round {round}: the CPU read other texels than the GPU wrote"); + assert!(std::slice::from_raw_parts((va + size) as *const u8, pages * 4096 - size).iter().all(|&b| b == 0x5A), "bytes past the texture written"); + note_gpu_write(list, key); + copy_back::list_reset(list); + copy_back::after_submit(queue.as_raw(), &[list as *mut c_void]); + assert!(!copy_back::is_armed(key)); + } + let (arms, faults, failed) = copy_back::stats(); + assert!(arms - arms0 >= 2 && faults - faults0 >= 2, "arms {} faults {}", arms - arms0, faults - faults0); + assert_eq!(failed, failed0, "a read-back failed"); + note_gpu_write(list, key); + copy_back::after_submit(queue.as_raw(), &[list as *mut c_void]); + assert!(copy_back::is_armed(key)); + copy_back::forget(key); + assert!(!copy_back::is_armed(key)); + assert_eq!(protection(va), mem::PAGE_READWRITE); + dev.GetDeviceRemovedReason().unwrap(); + } + } + + /// GPU-owned RT/DS/UAV copy-back (`#2663` render-target / UAV case): a GPU-owned render + /// target cleared by the GPU and transitioned through `RENDER_TARGET -> PIXEL_SHADER_RESOURCE` + /// / `COMMON` via real adopted D3D12 hooks is armed after submit, downloaded from its tracked + /// post-submit state on CPU touch, and re-tiled into console memory. Also verifies multi-plane + /// DS skip, imported coherent UMA skip, and coexistence with `write_changed_pages` via + /// `disarm_overlapping`. + #[test] + fn copy_back_gpu_owned_rt_and_uav_texture_reads_back_on_cpu_touch() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + use windows_sys::Win32::System::Memory as mem; + use super::super::copy_back; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + struct Done(Vec, usize); + impl Drop for Done { + fn drop(&mut self) { + for &k in &self.0 { + copy_back::forget(k); + } + unsafe { mem::VirtualFree(self.1 as *mut c_void, 0, mem::MEM_RELEASE) }; + copy_back::force(false); + } + } + unsafe fn protection(at: usize) -> u32 { + let mut m: mem::MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + assert_ne!(mem::VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)), 0); + m.Protect + } + // 2D RGBA8 64x64, 1 slice, 1 mip, console tiling (flags = ALLOW_RENDER_TARGET | ALLOW_UNORDERED_ACCESS) + let mut console = console_desc(3, 64, 64, 1, 1, 28, 0x105); + console[0x30..0x34].copy_from_slice(&0x5u32.to_le_bytes()); + let tex = xg::Texture::new(&console).unwrap(); + let size = tex.size() as usize; + assert!(size >= 2 * 4096, "{size}"); + let list_id = 0x7E57_00A1usize; + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let pages = size.div_ceil(4096) + 1; + let va = mem::VirtualAlloc(std::ptr::null(), pages * 4096, mem::MEM_COMMIT | mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_ne!(va, 0); + std::ptr::write_bytes(va as *mut u8, 0x5A, pages * 4096); + let rt_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT(28), + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut texture: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &rt_desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut texture, + ).unwrap(); + let texture = texture.unwrap(); + let key = texture.as_raw() as usize; + let rtv_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 1, + ..Default::default() + }).unwrap(); + let rtv_handle = rtv_heap.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(&texture, None, rtv_handle); + + let ds_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT(19), // R32G8X24_TYPELESS (2 planes) + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let mut ds_tex: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &ds_desc, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + None, + &mut ds_tex, + ).unwrap(); + let ds_tex = ds_tex.unwrap(); + let ds_key = ds_tex.as_raw() as usize; + let _done = Done(vec![key, ds_key], va); + + // Round 0a (switch OFF): GPU clears the RT -> memory stays 0x5A (#2663 repro). + copy_back::force(false); + let run_clear = |before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES, color: [f32; 4]| { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let mk = |b, a| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(&texture), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: b, + StateAfter: a, + }), + }, + ..Default::default() + }; + if before != D3D12_RESOURCE_STATE_RENDER_TARGET { + list.ResourceBarrier(&[mk(before, D3D12_RESOURCE_STATE_RENDER_TARGET)]); + } + list.ClearRenderTargetView(rtv_handle, &color, None); + if after != D3D12_RESOURCE_STATE_RENDER_TARGET { + list.ResourceBarrier(&[mk(D3D12_RESOURCE_STATE_RENDER_TARGET, after)]); + } + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + std::mem::forget((alloc, list)); + }; + + let c0 = [64.0 / 255.0, 128.0 / 255.0, 191.0 / 255.0, 1.0]; + run_clear(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COMMON, c0); + assert!(!copy_back::is_armed(key)); + assert_eq!(std::ptr::read_volatile(va as *const u8), 0x5A, "switch off: title memory should stay stale (#2663)"); + + // Switch ON: register GPU-owned (NOT in title_textures!) and exercise real D3D12 + // ClearRenderTargetView + ResourceBarrier + ExecuteCommandLists hooks end-to-end. + copy_back::force(true); + copy_back::register_gpu_owned(raw_device as usize, key, va, xg::Texture::new(&console).unwrap(), &rt_desc, 0x5, 0); + assert!(copy_back::is_gpu_owned(key)); + copy_back::register_gpu_owned(raw_device as usize, ds_key, va, xg::Texture::new(&console).unwrap(), &ds_desc, 0x2, 0x10); + + let (arms0, faults0, failed0) = copy_back::stats(); + let (_, unsup0) = copy_back::skip_stats(); + + // Round 0b: COMMON -> RENDER_TARGET (clear c0) -> PIXEL_SHADER_RESOURCE + run_clear(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, c0); + assert!(copy_back::is_armed(key), "round 0: GPU-owned RT not armed by real hooks"); + assert_eq!(protection(va), mem::PAGE_NOACCESS); + + // CPU read faults, downloads from PIXEL_SHADER_RESOURCE, re-tiles into console memory. + let _ = std::ptr::read_volatile((va + 16) as *const u8); + assert_eq!(protection(va), mem::PAGE_READWRITE); + assert!(!copy_back::is_armed(key)); + let subs0 = subresources(va, &tex); + assert_eq!(subs0.len(), 1); + assert_eq!(&subs0[0].data[0..4], &[64, 128, 191, 255], "round 0: pixel 0 mismatch"); + assert!(subs0[0].data.chunks_exact(4).all(|px| px == [64, 128, 191, 255]), "round 0: not all texels match RT clear"); + assert!(std::slice::from_raw_parts((va + size) as *const u8, pages * 4096 - size).iter().all(|&b| b == 0x5A), "bytes past texture written"); + + // Round 1: PIXEL_SHADER_RESOURCE -> RENDER_TARGET (new clear c1) -> COMMON + let c1 = [1.0, 0.0, 64.0 / 255.0, 128.0 / 255.0]; + run_clear(D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON, c1); + assert!(copy_back::is_armed(key), "round 1: GPU-owned RT not re-armed by real hooks"); + let _ = std::ptr::read_volatile((va + 32) as *const u8); + assert!(!copy_back::is_armed(key)); + let subs1 = subresources(va, &tex); + assert!(subs1[0].data.chunks_exact(4).all(|px| px == [255, 0, 64, 128]), "round 1: not all texels match second RT clear"); + + // Coexistence with `publish_download` / `write_changed_pages`: an armed texture blocks + // `write_changed_pages` until `disarm_overlapping` opens it without removing metadata. + copy_back::list_reset(list_id); + copy_back::note_write(list_id, key); + copy_back::after_submit(queue.as_raw(), &[list_id as *mut c_void]); + assert!(copy_back::is_armed(key)); + assert_eq!(protection(va), mem::PAGE_NOACCESS); + let old_pub = vec![0x11u8; 4096]; + let new_pub = vec![0x22u8; 4096]; + assert!(!write_changed_pages(va, &old_pub, &new_pub), "armed PAGE_NOACCESS page must fail closed before disarm"); + copy_back::disarm_overlapping(va, size); + assert!(!copy_back::is_armed(key), "disarm_overlapping must disarm armed pages"); + assert!(copy_back::is_gpu_owned(key), "disarm_overlapping must retain gpu_owned metadata"); + assert_eq!(protection(va), mem::PAGE_READWRITE); + assert!(write_changed_pages(va, &old_pub, &new_pub), "write_changed_pages must succeed after disarm_overlapping"); + assert_eq!(std::ptr::read_volatile(va as *const u8), 0x22); + + // Multi-plane depth-stencil texture is cleanly skipped (not armed). + copy_back::list_reset(list_id); + copy_back::note_write(list_id, ds_key); + copy_back::after_submit(queue.as_raw(), &[list_id as *mut c_void]); + assert!(!copy_back::is_armed(ds_key), "multi-plane DS should not be armed"); + let (_, unsup1) = copy_back::skip_stats(); + assert!(unsup1 > unsup0, "expected skipped_unsup increment"); + + // Coherent UMA window check: a GPU-owned texture whose VA sits inside the imported + // coherent UMA window is skipped upfront (SKIPPED_UMA) without VirtualProtect error 87. + if let Some(u) = crate::gpu::uma::get().filter(|u| !u.shadowed()) { + let (uma0, _) = copy_back::skip_stats(); + let mut uma_tex: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &rt_desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut uma_tex, + ).unwrap(); + let uma_tex = uma_tex.unwrap(); + let uma_key = uma_tex.as_raw() as usize; + let uma_va = (0..u.windows()) + .find(|&k| u.is_committed_window(k)) + .map(|k| u.window(k).0) + .unwrap_or(0); + if uma_va != 0 && u.in_committed_window(uma_va, size) { + copy_back::register_gpu_owned(raw_device as usize, uma_key, uma_va, xg::Texture::new(&console).unwrap(), &rt_desc, 0x5, 0); + copy_back::list_reset(list_id); + copy_back::note_write(list_id, uma_key); + copy_back::after_submit(queue.as_raw(), &[list_id as *mut c_void]); + assert!(!copy_back::is_armed(uma_key), "imported coherent UMA texture must not be armed"); + let (uma1, _) = copy_back::skip_stats(); + assert!(uma1 > uma0, "expected SKIPPED_UMA increment for imported coherent UMA texture"); + copy_back::forget(uma_key); + } + } + + let (arms1, faults1, failed1) = copy_back::stats(); + assert!(arms1 - arms0 >= 2 && faults1 - faults0 >= 2, "arms {} faults {}", arms1 - arms0, faults1 - faults0); + assert_eq!(failed1, failed0, "GPU-owned read-back failed"); + + // forget disarms and removes GPU-owned entry. + copy_back::list_reset(list_id); + copy_back::note_write(list_id, key); + copy_back::after_submit(queue.as_raw(), &[list_id as *mut c_void]); + assert!(copy_back::is_armed(key)); + copy_back::forget(key); + assert!(!copy_back::is_armed(key)); + assert!(!copy_back::is_gpu_owned(key)); + assert_eq!(protection(va), mem::PAGE_READWRITE); + dev.GetDeviceRemovedReason().unwrap(); + } + } + + /// What the GPU wrote into a title texture reaches the title's memory in the console's layout + /// (`read_back`), and pages the title cannot write are left alone. + #[test] + fn read_back_writes_what_the_gpu_holds_into_the_title_memory() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + use windows_sys::Win32::System::Memory as mem; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + struct Registered(usize, usize); + impl Drop for Registered { + fn drop(&mut self) { + forget(self.0); + unsafe { mem::VirtualFree(self.1 as *mut c_void, 0, mem::MEM_RELEASE) }; + } + } + let cases = [ + (console_desc(3, 64, 64, 2, 3, 28, 0x105), D3D12_RESOURCE_DIMENSION_TEXTURE2D, 64u64, 64u32, 2u16, 3u16, 28), + (console_desc(4, 40, 24, 6, 3, 28, 0x105), D3D12_RESOURCE_DIMENSION_TEXTURE3D, 40, 24, 6, 3, 28), + (console_desc(3, 256, 256, 1, 9, 98, 0x10A), D3D12_RESOURCE_DIMENSION_TEXTURE2D, 256, 256, 1, 9, 98), + ]; + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + for (console, dim, w, h, n, mips, format) in cases { + let tex = xg::Texture::new(&console).unwrap(); + let size = tex.size() as usize; + let pages = size.div_ceil(4096) + 1; + let va = mem::VirtualAlloc(std::ptr::null(), pages * 4096, mem::MEM_COMMIT | mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_ne!(va, 0); + std::ptr::write_bytes(va as *mut u8, 0x5A, pages * 4096); + let gpu_mem: Vec = (0..size).map(|i| (i * 13 + i / 4096 + 1) as u8).collect(); + let want = subresources(gpu_mem.as_ptr() as usize, &tex); + let mut texture: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: dim, Width: w, Height: h, DepthOrArraySize: n, MipLevels: mips, Format: DXGI_FORMAT(format), SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut texture, + ).unwrap(); + let texture = texture.unwrap(); + let key = texture.as_raw() as usize; + register(raw_device, texture.as_raw(), va, &console, D3D12_RESOURCE_STATE_COMMON).unwrap(); + let _registered = Registered(key, va); + texture::upload(dev, &queue, &texture, &want, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COMMON).unwrap(); + note_gpu_write(0, key); + assert!(subresources(va, &tex) != want, "the title's memory starts out different"); + let written = read_back(key).unwrap(); + assert!(written > 0 && written <= size, "{written} of {size} bytes written"); + assert!(subresources(va, &tex) == want, "dimension {} format {format}: the title's memory holds other texels", dim.0); + assert!(std::slice::from_raw_parts((va + size) as *const u8, pages * 4096 - size).iter().all(|&b| b == 0x5A), "bytes past the texture written"); + assert_eq!(read_back(key).unwrap(), 0, "nothing changed: nothing written"); + std::ptr::write_bytes(va as *mut u8, 0x5A, size); + let mut old = 0; + assert_ne!(mem::VirtualProtect(va as *const c_void, 4096, mem::PAGE_READONLY, &mut old), 0); + let written = read_back(key).unwrap(); + assert!(std::slice::from_raw_parts(va as *const u8, 4096).iter().all(|&b| b == 0x5A), "a read-only page written"); + if size > 4096 { + assert!(written > 0, "the writable pages not written"); + } + assert_ne!(mem::VirtualProtect(va as *const c_void, 4096, mem::PAGE_READWRITE, &mut old), 0); + dev.GetDeviceRemovedReason().unwrap(); + } + let mut depth: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D24_UNORM_S8_UINT, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, ..Default::default() }, + D3D12_RESOURCE_STATE_DEPTH_WRITE, None, &mut depth, + ).unwrap(); + let e = texture::download(dev, &queue, &depth.unwrap(), &[D3D12_RESOURCE_STATE_DEPTH_WRITE]).unwrap_err(); + assert!(e.contains("2 planes"), "{e}"); + let mut msaa: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT(28), SampleDesc: DXGI_SAMPLE_DESC { Count: 4, Quality: 0 }, Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, ..Default::default() }, + D3D12_RESOURCE_STATE_RENDER_TARGET, None, &mut msaa, + ).unwrap(); + let e = texture::download(dev, &queue, &msaa.unwrap(), &[D3D12_RESOURCE_STATE_RENDER_TARGET]).unwrap_err(); + assert!(e.contains("4 samples"), "{e}"); + dev.GetDeviceRemovedReason().unwrap(); + } + } } diff --git a/crates/xcl/src/hle/kernelx/guest_write.rs b/crates/xcl/src/hle/kernelx/guest_write.rs index 81cca1a119..631dead891 100644 --- a/crates/xcl/src/hle/kernelx/guest_write.rs +++ b/crates/xcl/src/hle/kernelx/guest_write.rs @@ -106,6 +106,55 @@ pub fn is_pinned(at: usize) -> bool { PINS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(&(at & !(STEP - 1)))) } +/// Range a protector is currently transitioning (`FREEZE_END == 0`: none), published under `PINS` +/// so a concurrent `open_with` that pins an overlapping page waits until `protect` completes +/// before touching it. `FREEZE_LOCK` serializes concurrent protectors without holding `PINS` +/// across `VirtualProtect`. +static FREEZE_LOCK: Mutex<()> = Mutex::new(()); +static FREEZE_AT: AtomicUsize = AtomicUsize::new(0); +static FREEZE_END: AtomicUsize = AtomicUsize::new(0); +static FREEZES_DONE: AtomicUsize = AtomicUsize::new(0); + +/// Run `protect` on `[p, p + n)` only if no 4 KiB page in it is currently pinned by a kernel +/// write. The pin check and active-range mark happen under `PINS`; `protect` itself runs after +/// `PINS` is released, and any concurrent `open` that pins an overlapping page waits until +/// `protect` finishes before touching the page. Returns `false` if any page was pinned. +pub fn while_unpinned(p: usize, n: usize, protect: impl FnOnce() -> bool) -> bool { + let _serial = FREEZE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + release_done(); + let (lo, hi) = (p & !(STEP - 1), p.saturating_add(n)); + { + let g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(m) = g.as_ref().filter(|m| !m.is_empty()) { + let pinned = if m.len() < n / STEP { + m.keys().any(|&k| k >= lo && k < hi) + } else { + (lo..hi).step_by(STEP).any(|k| m.contains_key(&k)) + }; + if pinned { + return false; + } + } + FREEZE_AT.store(lo, Ordering::Release); + FREEZE_END.store(hi, Ordering::Release); + } + struct Done; + impl Drop for Done { + fn drop(&mut self) { + FREEZE_END.store(0, Ordering::Release); + FREEZES_DONE.fetch_add(1, Ordering::AcqRel); + } + } + let _done = Done; + protect() +} + +/// Whether `[p, p + n)` intersects a guarded view (`XCL_PAGE_ALIAS`): another protector owns it. +pub fn meets_guarded_view(p: usize, n: usize) -> bool { + const VIEW: usize = 0x10000; + (p & !(VIEW - 1)..p.saturating_add(n)).step_by(VIEW).any(super::guards::is_view) +} + /// One region `VirtualQuery` describes: [base, end), committed?, protection. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct Region { @@ -265,12 +314,22 @@ pub(crate) fn open_with(on: bool, p: usize, n: usize) -> Bracket { } v }; + let mut wait_for = None; if !pins.is_empty() { let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner()); let m = g.get_or_insert_with(HashMap::new); for &page in &pins { *m.entry(page).or_default() += 1; } + let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire)); + if fe != 0 && fa < end && p < fe { + wait_for = Some(FREEZES_DONE.load(Ordering::Acquire)); + } + } + if let Some(done) = wait_for { + while FREEZES_DONE.load(Ordering::Acquire) == done { + std::thread::yield_now(); + } } // pinned first: the protector cannot protect a page again between its fault and the write unsafe { touch(p, n, &pins) }; @@ -544,4 +603,20 @@ mod tests { assert_eq!(r, -1, "off: straight through"); } } + + #[test] + fn while_unpinned_skips_pinned_pages_and_runs_when_unpinned() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let pg = Protected::new(PAGE_READONLY); + let b = open_with(true, pg.0 + 0x1000, 0x10); + let mut ran = false; + assert!(!while_unpinned(pg.0, SIZE, || { ran = true; true }), "pinned page must skip protect"); + assert!(!ran, "closure must not run when a page is pinned"); + drop(b); + assert!(while_unpinned(pg.0, SIZE, || { ran = true; true }), "unpinned range must run protect"); + assert!(ran); + assert_eq!(FREEZE_END.load(Ordering::Acquire), 0, "freeze range must clear after protect"); + } + } }