From 03ceddb0be3d06287ca21ae800dbb0d7f98049e7 Mon Sep 17 00:00:00 2001 From: Aditya Tripathi <9266227+adiologydev@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:39:31 +0530 Subject: [PATCH 1/7] kernelx: physical pages as section slices that can be mapped at many addresses On the console a physical page mapped at several addresses is one page. XCL keeps a page at one address at a time and copies it when the title maps it elsewhere (`move_away`), so the other addresses go stale; a retail title maps its streamed pages into a pool, into the CPU view of a 24 GB reservation and into that reservation's GPU view (#1031). `kernelx::sections` is the base for real aliasing: a block of physical pages is one pagefile-backed SEC_RESERVE section, and a page is mapped as a view of its 64 KiB slice into a placeholder (MapViewOfFile3 with MEM_REPLACE_PLACEHOLDER). Every view of a slice is the same memory and a page takes commit once, when it is committed through any view. Unmapping leaves a placeholder for the next view. Ordinary reserved memory (write-watched if asked) can replace part of a placeholder and go back to one. Nothing calls it yet. Measured in a standalone program on Windows 11 26200 over 200 000 pages: map 2.2 us, unmap 2.75 us, commit 0.9 us a page. GetWriteWatch refuses a range that holds a view (error 87), and one call cannot span two neighbouring reservations either. --- crates/xcl/src/hle/kernelx.rs | 2 + crates/xcl/src/hle/kernelx/sections.rs | 308 +++++++++++++++++++++++++ 2 files changed, 310 insertions(+) create mode 100644 crates/xcl/src/hle/kernelx/sections.rs diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index afa86c30c8..c7fb934db9 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -109,6 +109,8 @@ pub fn exports() -> Vec<(&'static str, usize)> { pub const MEM_GRAPHICS: u32 = 0x1000_0000; mod placeholders; pub mod lazy; +#[allow(dead_code)] // used once physical pages alias (`XCL_PAGE_ALIAS`) +pub mod sections; pub const MEM_TITLE: u32 = 0x4000_0000; const STD_ALLOC_MASK: u32 = 0x1000 | 0x2000 | 0x8_0000 | 0x10_0000 | 0x20_0000 | 0x100_0000; const STD_PROTECT_MASK: u32 = 0xFF | 0x100 | 0x200 | 0x400; diff --git a/crates/xcl/src/hle/kernelx/sections.rs b/crates/xcl/src/hle/kernelx/sections.rs new file mode 100644 index 0000000000..9935686253 --- /dev/null +++ b/crates/xcl/src/hle/kernelx/sections.rs @@ -0,0 +1,308 @@ +//! Physical pages that show at every address they are mapped at. +//! +//! On the console a physical page mapped at several addresses is one page: a write through one +//! address is read at all of them. A retail title maps its streamed pages into a pool, into the +//! CPU view of a 24 GB reservation and, through its queue, into that reservation's GPU view. +//! Here a block of physical pages is one pagefile-backed section, and mapping a page puts a view +//! of its 64 KiB slice into a placeholder at the address: every view of the slice is the same +//! memory, with no copy. The section is `SEC_RESERVE`, so a page takes commit only once it is +//! committed through one of its views, and then once for all of them. +//! +//! Address space that may hold such views is reserved as a placeholder (`reserve`). A view +//! replaces the placeholder at its address (`map`); unmapping it leaves a placeholder again +//! (`unmap`), ready for the next view. Ordinary memory can replace part of a placeholder too +//! (`replace_with_reservation`), write-watched if asked – but `GetWriteWatch` refuses a range +//! that holds a view, so the watch must ask about such reservations one by one. + +use std::ffi::c_void; + +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; +use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MapViewOfFile3, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQuery, MEMORY_BASIC_INFORMATION, + MEMORY_MAPPED_VIEW_ADDRESS, MEM_COMMIT, MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, + MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, PAGE_READWRITE, SEC_RESERVE, VIRTUAL_ALLOCATION_TYPE, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +/// One console physical page (64 KiB, the Windows allocation granularity too). +pub const PAGE: usize = 0x1_0000; + +const MEM_WRITE_WATCH: VIRTUAL_ALLOCATION_TYPE = 0x20_0000; + +/// A block of physical pages: one pagefile-backed section of `pages` 64 KiB pages. +pub struct Section { + handle: HANDLE, + pages: usize, +} + +// SAFETY: a section handle may be used from any thread; the section itself is kernel state. +unsafe impl Send for Section {} +unsafe impl Sync for Section {} + +impl Section { + /// A section of `pages` pages, none committed. None if Windows refuses it. + pub fn new(pages: usize) -> Option
{ + let bytes = pages.checked_mul(PAGE).filter(|&b| b > 0)?; + // SAFETY: a pagefile-backed mapping with no name and default security. + let handle = unsafe { CreateFileMappingW(INVALID_HANDLE_VALUE, std::ptr::null(), PAGE_READWRITE | SEC_RESERVE, (bytes >> 32) as u32, bytes as u32, std::ptr::null()) }; + (!handle.is_null()).then_some(Section { handle, pages }) + } + + pub fn pages(&self) -> usize { + self.pages + } + + /// Map pages `first..first + n` of the section at `at`, which must be a placeholder or lie in + /// one (`reserve`). The view is one Windows mapping: `unmap` takes all of it at once. + /// + /// # Safety + /// `[at, at + n * PAGE)` must be address space the caller owns as a placeholder. + pub unsafe fn map(&self, first: usize, n: usize, at: usize) -> bool { + if n == 0 || first.checked_add(n).is_none_or(|end| end > self.pages) || !at.is_multiple_of(PAGE) { + return false; + } + let len = n * PAGE; + if !split(at, len) { + return false; + } + let v = MapViewOfFile3(self.handle, GetCurrentProcess(), at as *const c_void, (first * PAGE) as u64, len, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, std::ptr::null_mut(), 0); + v.Value as usize == at + } +} + +impl Drop for Section { + fn drop(&mut self) { + // views still mapped keep the section alive until they are unmapped + // SAFETY: the handle is ours and closed once. + unsafe { CloseHandle(self.handle) }; + } +} + +/// Reserve `len` bytes of placeholder address space, at `at` if given. None if it is taken. +/// +/// # Safety +/// Only reserves address space; the caller releases it with `release`. +pub unsafe fn reserve(at: Option, len: usize) -> Option { + if len == 0 || !len.is_multiple_of(PAGE) { + return None; + } + let want = at.unwrap_or(0); + let p = VirtualAlloc2(GetCurrentProcess(), want as *const c_void, len, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, std::ptr::null_mut(), 0) as usize; + (p != 0 && (at.is_none() || p == want)).then_some(p) +} + +/// The allocation `p` lies in: (base, size, state, type), from one VirtualQuery. +fn allocation_at(p: usize) -> Option<(usize, usize, u32, u32)> { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: VirtualQuery only reads the address space description. + if unsafe { VirtualQuery(p as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 { + return None; + } + Some((m.AllocationBase as usize, m.RegionSize, m.State, m.Type)) +} + +/// Make `[at, at + len)` a placeholder of its own, splitting the placeholder it lies in. True if +/// it is one now (already exactly one, too). +/// +/// # Safety +/// `[at, at + len)` must lie in one placeholder the caller owns. +pub unsafe fn split(at: usize, len: usize) -> bool { + match allocation_at(at) { + // a placeholder is a reservation (MEM_RESERVE) with no protection; one that is already + // exactly this range cannot be split again – it is what was asked for + Some((base, size, MEM_RESERVE, _)) if base == at && size == len => true, + Some((_, _, MEM_RESERVE, _)) => VirtualFree(at as *mut c_void, len, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != 0, + _ => false, + } +} + +/// Unmap the view at `at` (all of it) and leave a placeholder in its place. +/// +/// # Safety +/// `at` must be the start of a view made by `Section::map`. +pub unsafe fn unmap(at: usize) -> bool { + UnmapViewOfFile2(GetCurrentProcess(), MEMORY_MAPPED_VIEW_ADDRESS { Value: at as *mut c_void }, MEM_PRESERVE_PLACEHOLDER) != 0 +} + +/// Commit `[at, at + len)` of a view: the section's pages there are committed for every view of +/// them. True if they are committed now. +/// +/// # Safety +/// The range must lie in views made by `Section::map`. +pub unsafe fn commit(at: usize, len: usize) -> bool { + !VirtualAlloc(at as *const c_void, len, MEM_COMMIT, PAGE_READWRITE).is_null() +} + +/// Ordinary reserved memory in place of `[at, at + len)` of a placeholder, write-watched if +/// `write_watch` (commit it with `VirtualAlloc` as usual). +/// +/// # Safety +/// `[at, at + len)` must lie in one placeholder the caller owns. +pub unsafe fn replace_with_reservation(at: usize, len: usize, write_watch: bool) -> bool { + if !split(at, len) { + return false; + } + let t = MEM_RESERVE | MEM_REPLACE_PLACEHOLDER | if write_watch { MEM_WRITE_WATCH } else { 0 }; + VirtualAlloc2(GetCurrentProcess(), at as *const c_void, len, t, PAGE_READWRITE, std::ptr::null_mut(), 0) as usize == at +} + +/// Turn the reservation `replace_with_reservation` made at `[at, at + len)` back into a +/// placeholder (what was committed there is gone). +/// +/// # Safety +/// `[at, at + len)` must be exactly such a reservation. +pub unsafe fn reservation_to_placeholder(at: usize, len: usize) -> bool { + VirtualFree(at as *mut c_void, len, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != 0 +} + +/// Release the placeholder at `at` (its whole extent; views in it must be unmapped first). +/// +/// # Safety +/// `at` must be the start of a placeholder the caller owns. +pub unsafe fn release(at: usize) -> bool { + VirtualFree(at as *mut c_void, 0, MEM_RELEASE) != 0 +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{GetWriteWatch, MEM_MAPPED}; + + /// Placeholder address space for a test, released at the end (views unmapped first by the test). + struct Space(usize, usize); + impl Space { + fn new(pages: usize) -> Space { + let len = pages * PAGE; + Space(unsafe { reserve(None, len) }.expect("placeholder"), len) + } + fn at(&self, i: usize) -> usize { + self.0 + i * PAGE + } + } + impl Drop for Space { + fn drop(&mut self) { + // the test leaves placeholders behind; release each piece + let mut p = self.0; + while p < self.0 + self.1 { + let (base, size, _, _) = allocation_at(p).unwrap(); + assert_eq!(base, p); + unsafe { release(p) }; + p += size; + } + } + } + + unsafe fn read(at: usize) -> u64 { + std::ptr::read_volatile(at as *const u64) + } + + unsafe fn write(at: usize, v: u64) { + std::ptr::write_volatile(at as *mut u64, v) + } + + #[test] + fn a_page_mapped_at_two_addresses_is_one_page() { + let s = Section::new(8).unwrap(); + let space = Space::new(16); + unsafe { + assert!(s.map(5, 1, space.at(2))); + assert!(s.map(5, 1, space.at(11))); + assert!(commit(space.at(2), PAGE)); + write(space.at(2) + 0x40, 0xDEAD_BEEF); + assert_eq!(read(space.at(11) + 0x40), 0xDEAD_BEEF, "a write at one address is read at the other"); + write(space.at(11) + 0x40, 7); + assert_eq!(read(space.at(2) + 0x40), 7); + assert_eq!(allocation_at(space.at(11)).unwrap().3, MEM_MAPPED); + assert!(unmap(space.at(2)) && unmap(space.at(11))); + } + } + + #[test] + fn committing_through_one_view_commits_the_page_for_all() { + let s = Section::new(2).unwrap(); + let space = Space::new(4); + unsafe { + assert!(s.map(1, 1, space.at(0))); + assert!(s.map(1, 1, space.at(3))); + assert_eq!(allocation_at(space.at(3)).unwrap().2, MEM_RESERVE, "a page is not committed before it is used"); + assert!(commit(space.at(0), PAGE)); + assert_eq!(allocation_at(space.at(3)).unwrap().2, MEM_COMMIT); + assert_eq!(read(space.at(3)), 0, "a new page reads zeros"); + assert!(unmap(space.at(0)) && unmap(space.at(3))); + } + } + + #[test] + fn unmapping_leaves_a_placeholder_for_the_next_page() { + let s = Section::new(4).unwrap(); + let space = Space::new(2); + unsafe { + assert!(s.map(0, 1, space.at(1)) && commit(space.at(1), PAGE)); + write(space.at(1), 1); + assert!(unmap(space.at(1))); + let (base, size, state, _) = allocation_at(space.at(1)).unwrap(); + assert_eq!((base, size, state), (space.at(1), PAGE, MEM_RESERVE), "a placeholder of the page's size is left"); + assert!(s.map(3, 1, space.at(1)) && commit(space.at(1), PAGE)); + assert_eq!(read(space.at(1)), 0, "the other page is there now"); + // the first page kept its contents while it was mapped nowhere + assert!(s.map(0, 1, space.at(0))); + assert_eq!(read(space.at(0)), 1); + assert!(unmap(space.at(0)) && unmap(space.at(1))); + } + } + + #[test] + fn a_run_of_pages_is_one_view() { + let s = Section::new(8).unwrap(); + let space = Space::new(8); + unsafe { + assert!(s.map(2, 4, space.at(1))); + assert_eq!(allocation_at(space.at(1)).unwrap().0, space.at(1)); + assert_eq!(allocation_at(space.at(4)).unwrap().0, space.at(1), "one view covers the run"); + assert!(commit(space.at(1), 4 * PAGE)); + assert!(s.map(4, 1, space.at(7))); + write(space.at(3), 42); // page 4 of the section, third of the run + assert_eq!(read(space.at(7)), 42); + assert!(!s.map(6, 4, space.at(0)), "pages past the end of the section are refused"); + assert!(unmap(space.at(1)) && unmap(space.at(7))); + } + } + + #[test] + fn write_watched_memory_lives_beside_views_in_one_placeholder() { + let s = Section::new(1).unwrap(); + let space = Space::new(8); + unsafe { + assert!(replace_with_reservation(space.at(0), 4 * PAGE, true)); + assert!(!VirtualAlloc(space.at(0) as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + assert!(s.map(0, 1, space.at(6)) && commit(space.at(6), PAGE)); + write(space.at(1), 1); + write(space.at(6), 2); + let mut out = [std::ptr::null_mut::(); 64]; + let (mut n, mut gran) = (out.len(), 0u32); + assert_eq!(GetWriteWatch(1, space.at(0) as *const c_void, 4 * PAGE, out.as_mut_ptr(), &mut n, &mut gran), 0); + assert_eq!((n, out[0] as usize), (1, space.at(1)), "the write-watched reservation reports its write"); + let mut n = out.len(); + assert_ne!(GetWriteWatch(0, space.at(0) as *const c_void, 8 * PAGE, out.as_mut_ptr(), &mut n, &mut gran), 0, "a range with a view in it is refused"); + assert!(reservation_to_placeholder(space.at(0), 4 * PAGE)); + assert_eq!(allocation_at(space.at(0)).unwrap().2, MEM_RESERVE); + assert!(unmap(space.at(6))); + } + } + + #[test] + fn splitting_a_range_that_is_already_a_placeholder_is_a_no_op() { + let space = Space::new(3); + unsafe { + assert!(split(space.at(1), PAGE)); + assert!(split(space.at(1), PAGE)); + assert_eq!(allocation_at(space.at(1)).unwrap().0, space.at(1)); + assert_eq!(allocation_at(space.at(2)).unwrap().0, space.at(2)); + } + } + + #[test] + fn a_section_of_no_pages_is_refused() { + assert!(Section::new(0).is_none()); + } +} From 6602a7020122f508f72fed942286f488e3bd1bb9 Mon Sep 17 00:00:00 2001 From: Aditya Tripathi <9266227+adiologydev@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:41:26 +0530 Subject: [PATCH 2/7] kernelx: catch CPU writes to the views of physical pages, page by page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The upload of title memory to video memory (`d3d12x::sparse`) and the textures kept in step with title memory learn what the CPU wrote from the write watch, and a view of a section (`kernelx::sections`) cannot be write-watched: GetWriteWatch refuses any range that holds one. `kernelx::guards` keeps the views of a physical page read-only. The first write through any of them faults; a vectored handler makes that view writable, notes the page and lets the write go on. `take_dirty` hands over the pages of every view of each page written – a write through one view is a write to all of them – and guards those views again before their bytes are read, so a later write is caught again and an earlier one is in what is read. Kernel calls do not fault into the handler, they fail: `lazy::ensure`, which XCL already calls before a kernel call or its own code writes title memory, opens the guards there first and counts the write. A view committed by the lazy handler is writable and counts as written. Both take no lock until a view has been watched. Nothing watches a view yet. --- crates/xcl/src/hle/kernelx.rs | 2 + crates/xcl/src/hle/kernelx/guards.rs | 352 +++++++++++++++++++++++++++ crates/xcl/src/hle/kernelx/lazy.rs | 9 +- 3 files changed, 362 insertions(+), 1 deletion(-) create mode 100644 crates/xcl/src/hle/kernelx/guards.rs diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index c7fb934db9..74cdf34294 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -111,6 +111,8 @@ mod placeholders; pub mod lazy; #[allow(dead_code)] // used once physical pages alias (`XCL_PAGE_ALIAS`) pub mod sections; +#[allow(dead_code)] // `watch` / `take_dirty` used once physical pages alias (`XCL_PAGE_ALIAS`) +pub mod guards; pub const MEM_TITLE: u32 = 0x4000_0000; const STD_ALLOC_MASK: u32 = 0x1000 | 0x2000 | 0x8_0000 | 0x10_0000 | 0x20_0000 | 0x100_0000; const STD_PROTECT_MASK: u32 = 0xFF | 0x100 | 0x200 | 0x400; diff --git a/crates/xcl/src/hle/kernelx/guards.rs b/crates/xcl/src/hle/kernelx/guards.rs new file mode 100644 index 0000000000..6f90b025b0 --- /dev/null +++ b/crates/xcl/src/hle/kernelx/guards.rs @@ -0,0 +1,352 @@ +//! CPU writes to the views of physical pages, caught page by page. +//! +//! The upload of title memory to video memory (`d3d12x::sparse`) learns what the CPU wrote from +//! the write watch, and a view of a section (`sections`) cannot be write-watched. So the views +//! of a physical page are kept read-only: the first write through any of them faults, the +//! handler makes that view writable again and notes the page, and the write goes on. Before the +//! title's next submit `take_dirty` hands over the pages of every view of each page written – +//! a write through one view is a write to all of them – and guards them again. +//! +//! A kernel call does not fault into the handler: it fails. Memory a kernel call or XCL is about +//! to write goes through `lazy::ensure`, which opens the guards there first (`open`). + +use std::collections::{HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, Once}; + +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_READONLY, PAGE_READWRITE}; + +const PAGE: usize = 0x1_0000; +const EXCEPTION_CONTINUE_EXECUTION: i32 = -1; +const EXCEPTION_CONTINUE_SEARCH: i32 = 0; + +#[derive(Default)] +struct State { + /// view page (64 KiB aligned) → the physical page it shows + at: HashMap, + /// physical page → the view pages that show it + views: HashMap>, + /// physical pages written since the last `take_dirty` + dirty: HashSet, +} + +static STATE: Mutex> = Mutex::new(None); + +/// Whether any view was ever watched: `open` and `committed` sit on the file-read and +/// DirectStorage paths and take no lock before then. +static WATCHING: AtomicBool = AtomicBool::new(false); + +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)) +} + +fn install() { + static ONCE: Once = Once::new(); + ONCE.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(handler)); + }); +} + +unsafe fn protect(view: usize, p: u32) -> bool { + let mut old = 0; + VirtualProtect(view as *const c_void, PAGE, p, &mut old) != 0 +} + +unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + let r = &*(*info).ExceptionRecord; + // a write (access 1) to a guarded view + if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 || r.ExceptionInformation[0] != 1 { + return EXCEPTION_CONTINUE_SEARCH; + } + let view = r.ExceptionInformation[1] & !(PAGE - 1); + // (a view not committed yet cannot be opened: that fault is `lazy`'s, which commits the page + // and counts it as written – claimed here, the write would fault again for ever) + let ours = with(|s| match s.at.get(&view) { + Some(&page) if unsafe { protect(view, PAGE_READWRITE) } => { + s.dirty.insert(page); + true + } + _ => false, + }); + // (another thread may have opened the view between the fault and here: writable now) + if ours || writable(view) { + EXCEPTION_CONTINUE_EXECUTION + } else { + EXCEPTION_CONTINUE_SEARCH + } +} + +/// Whether `view` is a guarded view that is writable now. +fn writable(view: usize) -> bool { + if !with(|s| s.at.contains_key(&view)) { + return false; + } + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: VirtualQuery only reads the address space description. + let n = unsafe { VirtualQuery(view as *const c_void, &mut m, std::mem::size_of_val(&m)) }; + n != 0 && m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE +} + +/// 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) { + install(); + WATCHING.store(true, Ordering::Release); + with(|s| { + if let Some(old) = s.at.insert(view, page).filter(|&old| old != page) { + if let Some(v) = s.views.get_mut(&old) { + v.retain(|&a| a != view); + } + } + let v = s.views.entry(page).or_default(); + if !v.contains(&view) { + v.push(view); + } + unsafe { protect(view, PAGE_READONLY) }; + }); +} + +/// `view` no longer shows a physical page (it was unmapped): its writes are not looked for. +pub fn forget(view: usize) { + with(|s| { + if let Some(page) = s.at.remove(&view) { + if let Some(v) = s.views.get_mut(&page) { + v.retain(|&a| a != view); + if v.is_empty() { + s.views.remove(&page); + s.dirty.remove(&page); + } + } + } + }); +} + +/// `view` was committed just now (it reads zeros and is writable): its page counts as written. +pub fn committed(view: usize) { + if !WATCHING.load(Ordering::Acquire) { + return; + } + with(|s| { + if let Some(&page) = s.at.get(&(view & !(PAGE - 1))) { + s.dirty.insert(page); + } + }); +} + +/// `[p, p + len)` is about to be written by a kernel call or XCL: the views there are made +/// writable and their pages count as written. +pub fn open(p: usize, len: usize) { + if len == 0 || !WATCHING.load(Ordering::Acquire) { + return; + } + with(|s| { + if s.at.is_empty() { + return; + } + let mut view = p & !(PAGE - 1); + while view < p.saturating_add(len) { + if let Some(&page) = s.at.get(&view) { + s.dirty.insert(page); + unsafe { protect(view, PAGE_READWRITE) }; + } + view += PAGE; + } + }); +} + +/// The pages written since the last call, as the `step`-sized pages (4 KiB for the write watch) +/// of every view of each, appended to `out`; those views are guarded again. +pub fn take_dirty(out: &mut Vec, step: usize) { + with(|s| { + for page in std::mem::take(&mut s.dirty) { + for &view in s.views.get(&page).map(Vec::as_slice).unwrap_or_default() { + // guarded before its bytes are read for the upload: a write from here on is + // caught again, one before this is in what the upload reads + unsafe { protect(view, PAGE_READONLY) }; + out.extend((view..view + PAGE).step_by(step)); + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::super::sections::{commit, reserve, unmap, Section}; + use super::*; + use std::sync::Mutex as TestLock; + + /// the guard state is one per process: tests that use it run one at a time + static SERIAL: TestLock<()> = TestLock::new(()); + + /// A section of `pages` pages and placeholder space for `views` views; page `i` of the + /// section at view slot `j` is `space + j * PAGE`. + struct Fixture { + section: Section, + space: usize, + mapped: Vec, + } + impl Fixture { + fn new(pages: usize, views: usize) -> Fixture { + Fixture { section: Section::new(pages).unwrap(), space: unsafe { reserve(None, views * PAGE) }.unwrap(), mapped: Vec::new() } + } + /// Section page `page` at view slot `slot`, committed and guarded; its physical page id is `page`. + fn show(&mut self, page: usize, slot: usize) -> usize { + let at = self.space + slot * PAGE; + unsafe { + assert!(self.section.map(page, 1, at)); + assert!(commit(at, PAGE)); + } + watch(page, at); + self.mapped.push(at); + at + } + } + impl Drop for Fixture { + fn drop(&mut self) { + for &at in &self.mapped { + forget(at); + unsafe { unmap(at) }; + } + } + } + + fn dirty() -> Vec { + let mut out = Vec::new(); + take_dirty(&mut out, PAGE); + out.sort_unstable(); + out + } + + unsafe fn write(at: usize, v: u64) { + std::ptr::write_volatile(at as *mut u64, v) + } + + #[test] + fn a_write_through_one_view_reports_every_view_of_the_page() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(4, 8); + let a = f.show(2, 1); + let b = f.show(2, 5); + let c = f.show(3, 6); + dirty(); + unsafe { write(b + 16, 9) }; + assert_eq!(unsafe { std::ptr::read_volatile((a + 16) as *const u64) }, 9); + assert_eq!(dirty(), vec![a, b], "both views of the written page, not the other page's"); + assert_eq!(dirty(), Vec::::new(), "nothing written since"); + unsafe { write(a, 1) }; + unsafe { write(c, 1) }; + assert_eq!(dirty(), vec![a, b, c], "the views are guarded again after a take"); + } + + #[test] + fn steps_of_4_kib_cover_the_view() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(1, 1); + let a = f.show(0, 0); + dirty(); + unsafe { write(a + 0x8000, 1) }; + let mut out = Vec::new(); + take_dirty(&mut out, 0x1000); + assert_eq!(out, (a..a + PAGE).step_by(0x1000).collect::>()); + } + + #[test] + fn open_makes_views_writable_for_a_kernel_call_and_counts_the_write() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(2, 4); + let a = f.show(0, 0); + let b = f.show(1, 1); + dirty(); + open(a + PAGE - 8, 16); // straddles both views + assert!(writable(a) && writable(b)); + assert_eq!(dirty(), vec![a, b]); + assert!(!writable(a), "guarded again after the take"); + } + + #[test] + fn a_forgotten_view_is_no_longer_reported() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(1, 2); + let a = f.show(0, 0); + let b = f.show(0, 1); + dirty(); + forget(b); + unsafe { write(a, 3) }; + assert_eq!(dirty(), vec![a]); + } + + #[test] + fn writes_from_many_threads_are_all_caught_and_kept() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + const PAGES: usize = 64; + const THREADS: usize = 8; + let mut f = Fixture::new(PAGES, PAGES); + let views: Vec = (0..PAGES).map(|i| f.show(i, i)).collect(); + dirty(); + let barrier = std::sync::Arc::new(std::sync::Barrier::new(THREADS)); + let handles: Vec<_> = (0..THREADS) + .map(|t| { + let (views, barrier) = (views.clone(), barrier.clone()); + std::thread::spawn(move || { + barrier.wait(); + for (i, &v) in views.iter().enumerate() { + unsafe { write(v + t * 64, (i * THREADS + t) as u64) }; + } + }) + }) + .collect(); + for h in handles { + h.join().unwrap(); + } + for (i, &v) in views.iter().enumerate() { + for t in 0..THREADS { + assert_eq!(unsafe { std::ptr::read_volatile((v + t * 64) as *const u64) }, (i * THREADS + t) as u64); + } + } + assert_eq!(dirty(), views); + } + + #[test] + fn a_write_to_a_view_not_committed_yet_is_left_to_the_next_handler() { + use windows_sys::Win32::System::Diagnostics::Debug::{CONTEXT, EXCEPTION_RECORD}; + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(2, 2); + // page 0 mapped but never committed; page 1 committed and guarded + let fresh = f.space; + unsafe { assert!(f.section.map(0, 1, fresh)) }; + watch(0, fresh); + f.mapped.push(fresh); + let used = f.show(1, 1); + let fault = |at: usize| unsafe { + let mut rec: EXCEPTION_RECORD = std::mem::zeroed(); + rec.ExceptionCode = EXCEPTION_ACCESS_VIOLATION as NTSTATUS; + rec.NumberParameters = 2; + rec.ExceptionInformation[0] = 1; + rec.ExceptionInformation[1] = at + 8; + let mut ctx: CONTEXT = std::mem::zeroed(); + let mut ptrs = EXCEPTION_POINTERS { ExceptionRecord: &mut rec, ContextRecord: &mut ctx }; + handler(&mut ptrs) + }; + assert_eq!(fault(fresh), EXCEPTION_CONTINUE_SEARCH, "not committed: left to the lazy handler"); + assert_eq!(fault(used), EXCEPTION_CONTINUE_EXECUTION, "committed and guarded: opened here"); + } + + #[test] + fn a_view_committed_later_counts_as_written() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let f = Fixture::new(1, 1); + let at = f.space; + unsafe { assert!(f.section.map(0, 1, at)) }; + watch(0, at); // not committed: cannot be guarded yet + dirty(); + unsafe { assert!(commit(at, PAGE)) }; + committed(at); + assert_eq!(dirty(), vec![at]); + forget(at); + unsafe { unmap(at) }; + } +} diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index fa750b9a48..02a6bf58eb 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -41,7 +41,12 @@ unsafe fn commit(page: usize) -> bool { if !g.remove(&page) { return false; } - !VirtualAlloc(page as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null() + if VirtualAlloc(page as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null() { + return false; + } + // (a view of a physical page committed here is writable, not guarded: count it as written) + super::guards::committed(page); + true } unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { @@ -88,6 +93,8 @@ pub fn ensure(p: usize, len: usize) { if len == 0 { return; } + // views of physical pages there are read-only until written: a kernel call cannot fault + super::guards::open(p, len); let pages: Vec = { let g = LAZY.read().unwrap_or_else(|e| e.into_inner()); if g.is_empty() { From d660e3070bef6e3ae095393dc134ecd517ab4a35 Mon Sep 17 00:00:00 2001 From: Aditya Tripathi <9266227+adiologydev@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:31:10 +0530 Subject: [PATCH 3/7] kernelx: views of physical pages stay open across a write that cannot fault MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A guarded view of a physical page (`kernelx::guards`) is read-only until it is written. Code of XCL's own that writes there faults into the guard and goes on, but a kernel call does not fault: ReadFile into such a view fails. `lazy::ensure` opened the views first, yet the submit thread's `take_dirty` could guard them again before the write – between DirectStorage's check of its destination and the copy, or before the kernel wrote a ReadFile buffer. `guards::open` now returns `Opened`, which keeps its views writable until it is dropped; `take_dirty` uploads a pinned view but does not guard it again, and the end of the write counts as a write. `lazy::ensure` returns it and its callers hold it across their write: the routed ReadFile for a synchronous read, and the destination checks of DirectStorage and the CPU-side bottom-of-pipe writes. An overlapped ReadFile writes after the call returns: its views stay open until its OVERLAPPED is no longer STATUS_PENDING, which `take_dirty` reads without faulting (the title may free it once done). A retail title reads 271 MB that way into the CPU view of its 24 GB reservation 8.5 s after start. `guards::written` counts a page as written through all its views when XCL writes it by page number. Nothing watches a view yet, so nothing changes without views. --- crates/xcl/src/hle/d3d12x/cpu_writes.rs | 3 +- crates/xcl/src/hle/dstorage.rs | 4 +- crates/xcl/src/hle/kernelx/guards.rs | 128 +++++++++++++++++++++--- crates/xcl/src/hle/kernelx/lazy.rs | 16 +-- crates/xcl/src/vfs_hooks.rs | 15 ++- 5 files changed, 142 insertions(+), 24 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 3fedb32253..85bdfcb726 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -127,7 +127,8 @@ pub(super) fn writable(va: usize, bytes: usize) -> bool { if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { return true; } - crate::hle::kernelx::lazy::ensure(va, bytes); + // (held while the protection is asked: a view of a physical page is not guarded again meanwhile) + let _open = crate::hle::kernelx::lazy::ensure(va, bytes); use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; let found = unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0; diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 5dd9d2e708..97755841df 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -806,7 +806,9 @@ unsafe fn read_own(at: usize, out: *mut u8, len: usize) -> bool { /// Whether `n` bytes at `p` are committed, writable memory. fn writable(p: usize, n: usize) -> bool { let Some(end) = p.checked_add(n) else { return false }; - crate::hle::kernelx::lazy::ensure(p, n); + // (held while the protection is asked: a view of a physical page is not guarded again + // meanwhile; the copy that follows faults into the guard if one is) + let _open = crate::hle::kernelx::lazy::ensure(p, n); if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(p, n)) { return true; } diff --git a/crates/xcl/src/hle/kernelx/guards.rs b/crates/xcl/src/hle/kernelx/guards.rs index 6f90b025b0..c91a13e379 100644 --- a/crates/xcl/src/hle/kernelx/guards.rs +++ b/crates/xcl/src/hle/kernelx/guards.rs @@ -31,6 +31,10 @@ struct State { views: HashMap>, /// physical pages written since the last `take_dirty` dirty: HashSet, + /// views opened for a write still going on (`Opened`): not guarded again until it ends + pinned: HashMap, + /// overlapped reads into views: (the OVERLAPPED, its views kept open until it is done) + pending: Vec<(usize, Opened)>, } static STATE: Mutex> = Mutex::new(None); @@ -137,36 +141,114 @@ pub fn committed(view: usize) { }); } +/// Physical page `page` was written other than through a view (XCL by page number, or the page +/// came back from an address outside the views): every view of it counts as written. +pub fn written(page: usize) { + if !WATCHING.load(Ordering::Acquire) { + return; + } + with(|s| { + if s.views.contains_key(&page) { + s.dirty.insert(page); + } + }); +} + +/// Views opened by `open` for a write: they stay writable until this is dropped, when the write +/// is over and their pages count as written again. +#[must_use = "the views stay open only while this lives"] +pub struct Opened(Vec); + +impl Drop for Opened { + fn drop(&mut self) { + if self.0.is_empty() { + return; + } + with(|s| { + for view in self.0.drain(..) { + if let Some(n) = s.pinned.get_mut(&view) { + *n -= 1; + if *n == 0 { + s.pinned.remove(&view); + } + } + if let Some(&page) = s.at.get(&view) { + s.dirty.insert(page); + } + } + }); + } +} + /// `[p, p + len)` is about to be written by a kernel call or XCL: the views there are made -/// writable and their pages count as written. -pub fn open(p: usize, len: usize) { +/// writable, stay so while the returned `Opened` lives (a kernel call fails on a view guarded +/// again under it), and their pages count as written. +pub fn open(p: usize, len: usize) -> Opened { if len == 0 || !WATCHING.load(Ordering::Acquire) { - return; + return Opened(Vec::new()); } with(|s| { + let mut opened = Vec::new(); if s.at.is_empty() { - return; + return Opened(opened); } let mut view = p & !(PAGE - 1); while view < p.saturating_add(len) { if let Some(&page) = s.at.get(&view) { s.dirty.insert(page); unsafe { protect(view, PAGE_READWRITE) }; + *s.pinned.entry(view).or_default() += 1; + opened.push(view); } view += PAGE; } - }); + Opened(opened) + }) +} + +/// An overlapped read (`ov`) writes into the views `opened` holds after its call returned: they +/// stay open until it is done (`take_dirty` looks). +pub fn open_until_done(opened: Opened, ov: usize) { + if !opened.0.is_empty() { + with(|s| s.pending.push((ov, opened))); + } +} + +/// 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 { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + const STATUS_PENDING: usize = 0x103; + let mut internal = 0usize; + let mut n = 0usize; + // SAFETY: ReadProcessMemory on our own process fails instead of faulting on an unreadable address. + let ok = unsafe { ReadProcessMemory(GetCurrentProcess(), ov as *const c_void, &mut internal as *mut usize as *mut c_void, std::mem::size_of::(), &mut n) } != 0; + ok && n == std::mem::size_of::() && internal == STATUS_PENDING } /// The pages written since the last call, as the `step`-sized pages (4 KiB for the write watch) /// of every view of each, appended to `out`; those views are guarded again. pub fn take_dirty(out: &mut Vec, step: usize) { + if !WATCHING.load(Ordering::Acquire) { + return; + } + // overlapped reads that are done let their views go (dropped outside the lock: it takes it) + let done: Vec<(usize, Opened)> = with(|s| { + let (done, pending) = std::mem::take(&mut s.pending).into_iter().partition(|&(ov, _)| !still_pending(ov)); + s.pending = pending; + done + }); + drop(done); with(|s| { for page in std::mem::take(&mut s.dirty) { for &view in s.views.get(&page).map(Vec::as_slice).unwrap_or_default() { // guarded before its bytes are read for the upload: a write from here on is - // caught again, one before this is in what the upload reads - unsafe { protect(view, PAGE_READONLY) }; + // caught again, one before this is in what the upload reads. A view opened for a + // write still going on stays open (`Opened` counts its page as written at the end) + if !s.pinned.contains_key(&view) { + unsafe { protect(view, PAGE_READONLY) }; + } out.extend((view..view + PAGE).step_by(step)); } } @@ -174,13 +256,13 @@ pub fn take_dirty(out: &mut Vec, step: usize) { } #[cfg(test)] -mod tests { +pub(super) mod tests { use super::super::sections::{commit, reserve, unmap, Section}; use super::*; use std::sync::Mutex as TestLock; - /// the guard state is one per process: tests that use it run one at a time - static SERIAL: TestLock<()> = TestLock::new(()); + /// the guard state is one per process: tests that use it (here and in `alias`) run one at a time + pub(in crate::hle::kernelx) static SERIAL: TestLock<()> = TestLock::new(()); /// A section of `pages` pages and placeholder space for `views` views; page `i` of the /// section at view slot `j` is `space + j * PAGE`. @@ -261,10 +343,29 @@ mod tests { let a = f.show(0, 0); let b = f.show(1, 1); dirty(); - open(a + PAGE - 8, 16); // straddles both views + let opened = open(a + PAGE - 8, 16); // straddles both views assert!(writable(a) && writable(b)); assert_eq!(dirty(), vec![a, b]); - assert!(!writable(a), "guarded again after the take"); + assert!(writable(a) && writable(b), "a take leaves views open while their write goes on"); + drop(opened); + assert_eq!(dirty(), vec![a, b], "the end of the write counts as a write"); + assert!(!writable(a), "guarded again after the take that follows"); + } + + #[test] + fn views_an_overlapped_read_writes_stay_open_until_it_is_done() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(1, 1); + let a = f.show(0, 0); + dirty(); + // an OVERLAPPED whose Internal says pending, then done + let mut ov = [0x103usize, 0, 0, 0]; + open_until_done(open(a, 16), ov.as_mut_ptr() as usize); + assert_eq!(dirty(), vec![a]); + assert!(writable(a), "still open while the read is pending"); + ov[0] = 0; + assert_eq!(dirty(), vec![a], "the end of the read counts as a write"); + assert!(!writable(a), "guarded again once the read is done"); } #[test] @@ -310,6 +411,9 @@ mod tests { assert_eq!(dirty(), views); } + /// A write to a guarded view that is not committed yet is not the guards' to handle (the + /// lazy handler commits it): claimed, it faulted again for ever whenever this handler ran + /// before the lazy one. #[test] fn a_write_to_a_view_not_committed_yet_is_left_to_the_next_handler() { use windows_sys::Win32::System::Diagnostics::Debug::{CONTEXT, EXCEPTION_RECORD}; diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index 02a6bf58eb..e92fa56b2d 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -88,23 +88,25 @@ pub(super) fn unmark(page: usize) -> bool { LAZY.write().unwrap_or_else(|e| e.into_inner()).remove(&page) } -/// The lazy pages of `[p, p + len)` committed – memory a kernel call or XCL writes. -pub fn ensure(p: usize, len: usize) { +/// The lazy pages of `[p, p + len)` committed – memory a kernel call or XCL writes. Views of +/// physical pages there are read-only until written and a kernel call cannot fault: they are +/// opened, and stay open while the returned value lives (hold it across the write). +pub fn ensure(p: usize, len: usize) -> super::guards::Opened { + let opened = super::guards::open(p, len); if len == 0 { - return; + return opened; } - // views of physical pages there are read-only until written: a kernel call cannot fault - super::guards::open(p, len); let pages: Vec = { let g = LAZY.read().unwrap_or_else(|e| e.into_inner()); if g.is_empty() { - return; + return opened; } g.range(p & !(PAGE - 1)..p.saturating_add(len)).copied().collect() }; for page in pages { unsafe { commit(page) }; } + opened } #[cfg(test)] @@ -124,7 +126,7 @@ mod tests { std::ptr::write_volatile((r + 8) as *mut u32, 7); assert_eq!(std::ptr::read_volatile((r + 8) as *const u32), 7); assert!(!unmark(r), "used: no longer lazy"); - ensure(r + PAGE + 4, 4); + let _open = ensure(r + PAGE + 4, 4); assert!(!LAZY.read().unwrap().contains(&(r + PAGE))); assert!(crate::gpu::shader::readable(r + PAGE, 4)); VirtualFree(r as *mut c_void, 0, MEM_RELEASE); diff --git a/crates/xcl/src/vfs_hooks.rs b/crates/xcl/src/vfs_hooks.rs index 0767cf1e1c..6af3e534d2 100644 --- a/crates/xcl/src/vfs_hooks.rs +++ b/crates/xcl/src/vfs_hooks.rs @@ -531,10 +531,19 @@ 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); - if !buf.is_null() { - crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); + if buf.is_null() { + return orig(h, buf, n, read, ov); + } + // (views of physical pages stay writable until the read is over: a synchronous one when it + // returns, an overlapped one – it writes after this returns – when its OVERLAPPED says done) + let open = crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); + let r = orig(h, buf, n, read, ov); + if ov.is_null() { + drop(open); + } else { + crate::hle::kernelx::guards::open_until_done(open, ov as usize); } - orig(h, buf, n, read, ov) + r } unsafe extern "system" fn hk_delete_file_w(n: *const u16) -> i32 { From f30ca3f037e474fe1ca1720835313db161b36004 Mon Sep 17 00:00:00 2001 From: Aditya Tripathi <9266227+adiologydev@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:35:24 +0530 Subject: [PATCH 4/7] kernelx: XCL_PAGE_ALIAS=1 shows a physical page at every address it is mapped at Without it XCL keeps a physical page at one address at a time and copies it when the title maps it elsewhere; the console shows the page at every address it is mapped at. A retail title maps its streamed pages into a pool, into the CPU view of a 24 GB reservation and into that reservation's GPU view (#1031). With `XCL_PAGE_ALIAS=1` (`kernelx::alias`): - a block of physical pages is a section (`kernelx::sections`) with a view of its own, through which XCL reads and writes pages by number (DirectStorage); the title never maps a page there; - the title's reservations of 64 KiB pages with no commit (its CPU view, GPU view and pool) are placeholders, and a page mapped there is a view of its slice, guarded (`kernelx::guards`) so that a write through one view is uploaded at all of them; `title_textures` adds those pages to what the write watch found; - a page mapped anywhere else (a placeholder region the title made in a sparse window) is moved there and back with its bytes, as before. Pages are committed on first use as before (`kernelx::lazy`); whether a page is committed is a bit per page: asking Windows walked the rest of a fresh block, and a title mapping 100 000 new pages one at a time took 20 s longer to its first frame. Measured in a traced run of a retail title: 3 blocks (11 360, 2 960 and 99 776 pages), 131 072 map calls in 150 s, nearly all single pages into its plain reservations, none at a page's home, no commit inside them. --- crates/xcl/src/hle/d3d12x/title_textures.rs | 3 + crates/xcl/src/hle/kernelx.rs | 70 ++- crates/xcl/src/hle/kernelx/alias.rs | 503 ++++++++++++++++++++ crates/xcl/src/hle/kernelx/lazy.rs | 1 + crates/xcl/src/hle/kernelx/sections.rs | 16 + 5 files changed, 591 insertions(+), 2 deletions(-) create mode 100644 crates/xcl/src/hle/kernelx/alias.rs diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ac38429be7..caa0083fe0 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -705,6 +705,9 @@ unsafe fn refresh_once(queue: *mut c_void) { take_written(base, size, &mut buf, &mut dirty, &mut page); } }); + // views of physical pages are not write-watched: their writes are caught by guards + // (`XCL_PAGE_ALIAS`), a write through one view counting for all of them + crate::hle::kernelx::guards::take_dirty(&mut dirty, page as usize); dirty.sort_unstable(); dirty.len() }); diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 74cdf34294..85b1d00a71 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -109,10 +109,10 @@ pub fn exports() -> Vec<(&'static str, usize)> { pub const MEM_GRAPHICS: u32 = 0x1000_0000; mod placeholders; pub mod lazy; -#[allow(dead_code)] // used once physical pages alias (`XCL_PAGE_ALIAS`) +#[allow(dead_code)] // `replace_with_reservation` and its inverse: not used yet pub mod sections; -#[allow(dead_code)] // `watch` / `take_dirty` used once physical pages alias (`XCL_PAGE_ALIAS`) pub mod guards; +pub mod alias; pub const MEM_TITLE: u32 = 0x4000_0000; const STD_ALLOC_MASK: u32 = 0x1000 | 0x2000 | 0x8_0000 | 0x10_0000 | 0x20_0000 | 0x100_0000; const STD_PROTECT_MASK: u32 = 0xFF | 0x100 | 0x200 | 0x400; @@ -252,6 +252,21 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: return q; } let uma = crate::gpu::uma::get(); + // physical page aliasing: the title's reservations of 64 KiB pages hold views of its pages, + // so it maps pages there and does not commit memory of its own (a retail title never does) + if alias::enabled() && !addr.is_null() && t & 0x1000 != 0 && alias::in_space(addr as usize) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("VirtualAlloc: a commit at {addr:p} in a reservation of 64 KiB pages that holds physical pages (XCL_PAGE_ALIAS) – refused")); + fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); + return std::ptr::null_mut(); + } + if alias::enabled() && addr.is_null() && t & 0x2000 != 0 && t & 0x1000 == 0 && t & MEM_64K_PAGES == MEM_64K_PAGES { + if let Some(q) = alias::reserve_space(size) { + mirrors::reserved(q, size, t, p); + trace_mem("VirtualAlloc (64K pages, physical page space)", 0, size, t as u64, p, q); + return q as *mut c_void; + } + } // committing inside one of the title's reservations in a sparse window if !addr.is_null() && t & 0x1000 != 0 && uma.is_some_and(|u| u.is_sparse(addr as usize)) { let q = commit_sparse(addr as usize, size, p); @@ -413,6 +428,14 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 if let Some(ok) = placeholders::free(addr, size, t) { return ok; } + if alias::enabled() { + if let Some(ok) = alias::free_space(addr as usize, size, t) { + if ok && t & mem::MEM_RELEASE != 0 { + mirrors::released(addr as usize); + } + return ok as BOOL; + } + } // the title's reservations in a sparse window: decommit (and on release give the address // space back); their video memory goes with it if let Some(u) = crate::gpu::uma::get().filter(|u| u.is_sparse(addr as usize)) { @@ -476,6 +499,7 @@ pub unsafe extern "system" fn VirtualFreeEx(proc_: HANDLE, addr: *mut c_void, si let a = addr as usize; if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(a) || u.contains(a)) || (t & 0x8000 != 0 && in_graphics_reservation(a)) + || alias::in_space(a) { return VirtualFree(addr, size, t); } @@ -897,6 +921,9 @@ static AWAY: std::sync::Mutex> = std::sync::Mutex::new(None); /// Whether a physical page is mapped at the page holding `va` away from its home – committed /// or not yet (`lazy`: a page never used is committed at its first access). pub fn physical_page_at(va: usize) -> bool { + if alias::enabled() { + return alias::physical_page_at(va); + } AWAY.lock().unwrap().as_ref().is_some_and(|a| a.at.contains_key(&(va & !(PHYS_PAGE - 1)))) } @@ -969,6 +996,9 @@ unsafe fn resolve_physical_pages(away: Option<&Away>, pages: &[usize], offset: u /// number from `AllocateTitlePhysicalPages`). Returns `false` if `offset >= PHYS_PAGE_SIZE`, /// `pages` is too short, or any page is not a live allocation. pub unsafe fn read_physical_pages(pages: &[usize], offset: usize, dst: &mut [u8]) -> bool { + if alias::enabled() { + return alias::read(pages, offset, dst); + } if dst.is_empty() { return offset < PHYS_PAGE; } @@ -988,6 +1018,9 @@ pub unsafe fn read_physical_pages(pages: &[usize], offset: usize, dst: &mut [u8] /// Copy `src` into `pages` starting at `offset` within the first page. Validates every page /// before writing so the destination gets all bytes or nothing. pub unsafe fn write_physical_pages(pages: &[usize], offset: usize, src: &[u8]) -> bool { + if alias::enabled() { + return alias::write(pages, offset, src); + } if src.is_empty() { return offset < PHYS_PAGE; } @@ -1220,6 +1253,13 @@ pub unsafe extern "system" fn AllocateTitlePhysicalPages(_p: HANDLE, _t: u32, nu fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); return 0; }; + if alias::enabled() { + if alias::allocate(n, arr) { + return 1; + } + fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); + return 0; + } let Some(u) = crate::gpu::uma::get() else { fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); return 0; @@ -1247,6 +1287,14 @@ pub unsafe extern "system" fn AllocateTitlePhysicalPages(_p: HANDLE, _t: u32, nu } pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: *mut usize) -> BOOL { + if alias::enabled() { + if arr.is_null() { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return 0; + } + alias::free(std::slice::from_raw_parts(arr, n)); + return 1; + } let Some(u) = crate::gpu::uma::get() else { return 0 }; if arr.is_null() { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); @@ -1286,6 +1334,9 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: } pub unsafe extern "system" fn MapTitlePhysicalPages(va: *mut c_void, n: usize, _t: u32, _p: u32, arr: *mut usize) -> *mut c_void { + if alias::enabled() { + return map_aliased(va, n, arr); + } let mut g = AWAY.lock().unwrap(); let away = g.get_or_insert_with(Away::default); let r = map_pages(away, va, n, arr); @@ -1293,6 +1344,18 @@ pub unsafe extern "system" fn MapTitlePhysicalPages(va: *mut c_void, n: usize, _ r } +/// `MapTitlePhysicalPages` with physical page aliasing (`alias`): the title always names the +/// address (a retail title never maps a page at its home, which is XCL's own view here). +unsafe fn map_aliased(va: *mut c_void, n: usize, arr: *mut usize) -> *mut c_void { + if va.is_null() || n == 0 { + fnd::SetLastError(if va.is_null() { fnd::ERROR_NOT_SUPPORTED } else { fnd::ERROR_INVALID_PARAMETER }); + return std::ptr::null_mut(); + } + note_mapping_at(va as usize); + let pages: Vec = if arr.is_null() { vec![0; n] } else { std::slice::from_raw_parts(arr, n).to_vec() }; + if alias::map(va as usize, &pages) { va } else { std::ptr::null_mut() } +} + /// `MapTitlePhysicalPages` with `AWAY` held; the homes it moves away are given back by the /// caller (`give_back_homes`). unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) -> *mut c_void { @@ -1413,6 +1476,9 @@ pub unsafe extern "system" fn XMemMapPhysicalPagesScatter(addresses: *const *mut fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; } + if alias::enabled() { + return (0..n).all(|i| !map_aliased(*addresses.add(i), 1, pages.add(i) as *mut usize).is_null()) as BOOL; + } if crate::gpu::uma::get().is_none() { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; diff --git a/crates/xcl/src/hle/kernelx/alias.rs b/crates/xcl/src/hle/kernelx/alias.rs new file mode 100644 index 0000000000..9963212807 --- /dev/null +++ b/crates/xcl/src/hle/kernelx/alias.rs @@ -0,0 +1,503 @@ +//! Physical pages that show at every address they are mapped at (`XCL_PAGE_ALIAS=1`). +//! +//! Without it a physical page is kept at one address at a time and moved (copied) when the +//! title maps it elsewhere. With it a block of physical pages is a section (`sections`): the +//! title's reservations of 64 KiB pages are placeholders ("spaces"), and mapping a page there +//! maps a view of its slice, so every address the title mapped it at shows the same memory. +//! The views are guarded (`guards`): a write through one is uploaded at all of them. +//! +//! Each block also has a view of its own (its home, never given to the title) through which +//! XCL reads and writes pages by number (DirectStorage destinations). A retail title never maps +//! a page at its home, so homes are plain address space, not the GPU-visible sparse windows. +//! +//! A page mapped at an address outside a space (a placeholder region the title made in a +//! sparse window) is moved there as before: its bytes are copied there and back again when it +//! is unmapped. While it is away its views show what it held when it left. + +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use windows_sys::Win32::Foundation as fnd; +use windows_sys::Win32::System::Memory as mem; + +use super::sections::{self, Section, PAGE}; +use super::{guards, lazy, page_index, page_number, NEXT_PAGE_INDEX}; + +/// `XCL_PAGE_ALIAS=1` turns physical page aliasing on (default: off). +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PAGE_ALIAS").is_ok_and(|v| v.trim() == "1")) +} + +struct Block { + section: Arc
, + /// XCL's own view of the whole block + home: usize, + /// pages not freed yet + live: usize, + /// one bit a page: committed (asking Windows walked the rest of a block's uncommitted run – + /// a retail title mapping 100 000 fresh pages one at a time waited 20 s for its first frame) + committed: Arc>, +} + +#[derive(Default)] +struct State { + /// first page index → block + blocks: BTreeMap, + /// the title's reservations kept as placeholders: base → size + spaces: BTreeMap, + /// address (64 KiB) in a space → (page number, its section, the page's index in it) + views: BTreeMap, usize)>, + /// pages moved to an address outside the spaces: page → address, and address → page + away: HashMap, + away_at: BTreeMap, +} + +static STATE: Mutex> = Mutex::new(None); + +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)) +} + +impl State { + /// (block's section, the page's index in it, its address in the home view) of page number `page` + fn page(&self, page: usize) -> Option<(Arc
, usize, usize)> { + let index = page_index(page)?; + let (&first, b) = self.blocks.range(..=index).next_back()?; + let i = index - first; + (i < b.section.pages()).then(|| (b.section.clone(), i, b.home + i * PAGE)) + } + + /// The commit bits of page number `page`'s block and its index there. + fn bits(&self, page: usize) -> Option<(Arc>, usize)> { + let index = page_index(page)?; + let (&first, b) = self.blocks.range(..=index).next_back()?; + (index - first < b.section.pages()).then(|| (b.committed.clone(), index - first)) + } + + fn in_space(&self, at: usize) -> bool { + self.spaces.range(..=at).next_back().is_some_and(|(&b, &n)| at < b + n) + } +} + +/// Whether page number `page` is committed (a page never used is not). +fn committed(page: usize) -> bool { + with(|s| s.bits(page)).is_some_and(|(b, i)| b[i / 64].load(Ordering::Acquire) & (1 << (i % 64)) != 0) +} + +/// Page number `page` is committed now. +fn note_committed(page: usize) { + if let Some((b, i)) = with(|s| s.bits(page)) { + b[i / 64].fetch_or(1 << (i % 64), Ordering::AcqRel); + } +} + +/// The view at `view` was committed by the lazy handler (its page's first use). +pub fn committed_at(view: usize) { + if let Some(page) = with(|s| s.views.get(&(view & !(PAGE - 1))).map(|v| v.0)) { + note_committed(page); + } +} + +/// A reservation of 64 KiB pages the title will map physical pages into: a space. None if +/// Windows refuses the address space. +pub fn reserve_space(size: usize) -> Option { + let len = size.checked_next_multiple_of(PAGE)?; + // SAFETY: only address space is reserved; `free_space` releases it. + let at = unsafe { sections::reserve(None, len) }?; + with(|s| s.spaces.insert(at, len)); + Some(at) +} + +/// Whether `p` lies in a space. +pub fn in_space(p: usize) -> bool { + enabled() && with(|s| s.in_space(p)) +} + +/// `VirtualFree` of an address in a space: release (the whole space) unmaps its pages and gives +/// the address space back; decommit unmaps the pages of the range. None: not a space. +pub unsafe fn free_space(addr: usize, size: usize, t: u32) -> Option { + let (base, len) = with(|s| s.spaces.range(..=addr).next_back().filter(|(&b, &n)| addr < b + n).map(|(&b, &n)| (b, n)))?; + if t & mem::MEM_RELEASE != 0 { + if addr != base || size != 0 { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return Some(false); + } + unmap_range(base, len); + with(|s| s.spaces.remove(&base)); + sections::release_all(base, len); + return Some(true); + } + let end = if size == 0 { base + len } else { addr.saturating_add(size).min(base + len) }; + unmap_range(addr & !(PAGE - 1), end - (addr & !(PAGE - 1))); + Some(true) +} + +unsafe fn unmap_range(at: usize, len: usize) { + let views: Vec = with(|s| s.views.range(at..at + len).map(|(&a, _)| a).collect()); + for a in views { + unmap_view(a); + } +} + +/// The view at `at` (if any) unmapped, leaving a placeholder. +unsafe fn unmap_view(at: usize) { + if with(|s| s.views.remove(&at)).is_some() { + guards::forget(at); + lazy::unmark(at); + sections::unmap(at); + } +} + +/// `count` physical pages for the title; their numbers in `arr`. +pub unsafe fn allocate(n: usize, arr: *mut usize) -> bool { + let Some(section) = Section::new(n) else { + crate::xlog_warn!("physical pages: a section of {n} pages could not be made"); + return false; + }; + let Some(home) = sections::reserve(None, n * PAGE) else { return false }; + if !section.map(0, n, home) { + sections::release(home); + return false; + } + let first = NEXT_PAGE_INDEX.fetch_add(n, Ordering::Relaxed); + for i in 0..n { + *arr.add(i) = page_number(first + i); + } + let committed = Arc::new((0..n.div_ceil(64)).map(|_| AtomicU64::new(0)).collect()); + with(|s| s.blocks.insert(first, Block { section: Arc::new(section), home, live: n, committed })); + true +} + +/// The title frees `pages`. Addresses that show one keep showing it (the title is meant to unmap +/// first); a block whose pages are all freed loses its home. +pub unsafe fn free(pages: &[usize]) { + let mut homes = Vec::new(); + with(|s| { + for &page in pages { + if let Some(at) = s.away.remove(&page) { + s.away_at.remove(&at); + } + let Some(index) = page_index(page) else { continue }; + let Some((&first, b)) = s.blocks.range_mut(..=index).next_back() else { continue }; + if index >= first + b.section.pages() { + continue; + } + b.live = b.live.saturating_sub(1); + if b.live == 0 { + homes.push(b.home); + s.blocks.remove(&first); + } + } + }); + for home in homes { + sections::unmap(home); + sections::release(home); + } +} + +/// Map `n` pages (`pages[i]`, 0: unmap) at `va`. Pages at an address in a space are views of +/// them; elsewhere they are moved there. False with the last error set if a page is not one of +/// the title's or Windows refuses. +pub unsafe fn map(va: usize, pages: &[usize]) -> bool { + if !va.is_multiple_of(PAGE) || pages.iter().any(|&p| p != 0 && with(|s| s.page(p)).is_none()) { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return false; + } + for (i, &page) in pages.iter().enumerate() { + let at = va + i * PAGE; + if !map_one(at, page) { + fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); + return false; + } + } + true +} + +unsafe fn map_one(at: usize, page: usize) -> bool { + // what was at `at` goes first + unmap_view(at); + unmap_away(at); + if page == 0 { + return true; + } + // a page moved elsewhere comes home first (it is at one address outside the spaces at most, + // as before): its views then show what it holds + if let Some(old) = with(|s| s.away.get(&page).copied()) { + unmap_away(old); + } + let (section, index, home) = with(|s| s.page(page)).unwrap(); + if with(|s| s.in_space(at)) { + if !section.map(index, 1, at) { + return false; + } + with(|s| s.views.insert(at, (page, section, index))); + guards::watch(page, at); + if !committed(page) { + // a page never used: committed at its first touch here (or through its home) + lazy::mark(at); + } + return true; + } + move_to(at, page, home) +} + +/// Page `page` moved to `at`, an address outside the spaces: committed there with its bytes. +unsafe fn move_to(at: usize, page: usize, home: usize) -> bool { + let u = crate::gpu::uma::get(); + let ok = if u.is_some_and(|u| u.is_committed(at)) { + true + } else if u.is_some_and(|u| u.is_sparse(at)) { + !super::commit_sparse(at, PAGE, mem::PAGE_READWRITE).is_null() + } else { + !mem::VirtualAlloc(at as *const c_void, PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() + }; + if !ok { + return false; + } + if committed(page) { + std::ptr::copy_nonoverlapping(home as *const u8, at as *mut u8, PAGE); + } else { + std::ptr::write_bytes(at as *mut u8, 0, PAGE); + } + with(|s| { + s.away.insert(page, at); + s.away_at.insert(at, page); + }); + true +} + +/// The page moved to `at` (if any) goes home with what `at` holds; `at` is decommitted. +unsafe fn unmap_away(at: usize) { + let Some((page, home)) = with(|s| { + let page = s.away_at.remove(&at)?; + s.away.remove(&page); + Some((page, s.page(page)?.2)) + }) else { + return; + }; + if sections::commit(home, PAGE) { + note_committed(page); + std::ptr::copy_nonoverlapping(at as *const u8, home as *mut u8, PAGE); + guards::written(page); + } + let u = crate::gpu::uma::get(); + if u.is_some_and(|u| u.is_committed(at)) { + return; + } + if u.is_some_and(|u| u.is_sparse(at)) { + crate::hle::d3d12x::sparse::decommitted(at, PAGE); + } + mem::VirtualFree(at as *mut c_void, PAGE, mem::MEM_DECOMMIT); +} + +/// Whether a physical page is mapped at the page holding `va` (a view, or a page moved there). +pub fn physical_page_at(va: usize) -> bool { + let at = va & !(PAGE - 1); + with(|s| s.views.contains_key(&at) || s.away_at.contains_key(&at)) +} + +/// Where page `page`'s bytes are now (committing its home if `write`), or None. +unsafe fn bytes_of(page: usize, write: bool) -> Option<(usize, bool)> { + let (away, home) = with(|s| (s.away.get(&page).copied(), s.page(page).map(|p| p.2))); + if let Some(at) = away { + return Some((at, true)); + } + let home = home?; + if committed(page) { + return Some((home, true)); + } + if write { + if !sections::commit(home, PAGE) { + return None; + } + note_committed(page); + return Some((home, true)); + } + Some((home, false)) +} + +/// `read_physical_pages` in alias mode. +pub unsafe fn read(pages: &[usize], offset: usize, dst: &mut [u8]) -> bool { + copy_pages(pages, offset, dst.len(), |addr, done, n| { + match addr { + Some(a) => std::ptr::copy_nonoverlapping(a as *const u8, dst.as_mut_ptr().add(done), n), + None => std::ptr::write_bytes(dst.as_mut_ptr().add(done), 0, n), + } + }, false) +} + +/// `write_physical_pages` in alias mode. +pub unsafe fn write(pages: &[usize], offset: usize, src: &[u8]) -> bool { + copy_pages(pages, offset, src.len(), |addr, done, n| { + if let Some(a) = addr { + std::ptr::copy_nonoverlapping(src.as_ptr().add(done), a as *mut u8, n); + } + }, true) +} + +/// Walk `len` bytes from `offset` in `pages`, calling `f(address or None for a page never used, +/// bytes done, bytes here)`. All pages are checked before any byte is touched. +unsafe fn copy_pages(pages: &[usize], offset: usize, len: usize, mut f: impl FnMut(Option, usize, usize), write: bool) -> bool { + if len == 0 { + return offset < PAGE; + } + let Some(need) = offset.checked_add(len).map(|end| end.div_ceil(PAGE)) else { return false }; + if offset >= PAGE || pages.len() < need { + return false; + } + let mut addrs = Vec::with_capacity(need); + for &p in &pages[..need] { + let Some(a) = bytes_of(p, write) else { return false }; + addrs.push((p, a)); + } + let (mut done, mut off) = (0, offset); + for (page, (addr, used)) in addrs { + let n = (PAGE - off).min(len - done); + f(used.then_some(addr + off), done, n); + if write && with(|s| !s.away.contains_key(&page)) { + guards::written(page); + } + done += n; + off = 0; + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + /// alias state and guards are one per process: these tests run one at a time, and not + /// beside the guards' own + use super::guards::tests::SERIAL; + + unsafe fn read64(at: usize) -> u64 { + std::ptr::read_volatile(at as *const u64) + } + + unsafe fn write64(at: usize, v: u64) { + std::ptr::write_volatile(at as *mut u64, v) + } + + fn pages(n: usize) -> Vec { + let mut arr = vec![0usize; n]; + assert!(unsafe { allocate(n, arr.as_mut_ptr()) }); + arr + } + + fn dirty() -> Vec { + let mut out = Vec::new(); + guards::take_dirty(&mut out, PAGE); + out.sort_unstable(); + out + } + + #[test] + fn a_page_mapped_into_two_spaces_is_one_page_and_writes_reach_both() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(4); + let cpu = reserve_space(8 * PAGE).unwrap(); + let gpu = reserve_space(8 * PAGE).unwrap(); + unsafe { + assert!(map(cpu + 2 * PAGE, &p[1..3])); + assert!(map(gpu + 5 * PAGE, &[p[2]])); + assert!(physical_page_at(gpu + 5 * PAGE + 123)); + write64(cpu + 3 * PAGE + 8, 0xABCD); // page p[2] through the first space + assert_eq!(read64(gpu + 5 * PAGE + 8), 0xABCD, "the other space shows the same page"); + dirty(); + write64(gpu + 5 * PAGE, 1); + assert_eq!(dirty(), vec![cpu + 3 * PAGE, gpu + 5 * PAGE], "a write through one view: both are uploaded"); + assert_eq!(free_space(cpu, 0, mem::MEM_RELEASE), Some(true)); + assert_eq!(read64(gpu + 5 * PAGE + 8), 0xABCD, "releasing one space leaves the page at the other"); + assert_eq!(free_space(gpu, 0, mem::MEM_RELEASE), Some(true)); + free(&p); + } + } + + #[test] + fn remapping_an_address_shows_the_new_page_and_keeps_the_old_one() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(2); + let s = reserve_space(2 * PAGE).unwrap(); + unsafe { + assert!(map(s, &[p[0]])); + write64(s, 11); + assert!(map(s, &[p[1]])); + assert_eq!(read64(s), 0, "a page never written reads zeros"); + assert!(map(s, &[0])); + assert!(!physical_page_at(s)); + assert!(map(s + PAGE, &[p[0]])); + assert_eq!(read64(s + PAGE), 11, "the first page kept what was written to it"); + free_space(s, 0, mem::MEM_RELEASE); + free(&p); + } + } + + #[test] + fn pages_read_and_written_by_number_are_the_pages_the_title_sees() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(3); + let s = reserve_space(3 * PAGE).unwrap(); + unsafe { + assert!(map(s, &p)); + dirty(); + // a DirectStorage destination: 16 bytes across the boundary of the first two pages + assert!(write(&p, PAGE - 8, &[7u8; 16])); + assert_eq!(read64(s + PAGE - 8), 0x0707_0707_0707_0707); + assert_eq!(read64(s + PAGE), 0x0707_0707_0707_0707); + assert_eq!(dirty(), vec![s, s + PAGE], "pages written by number are uploaded where they are mapped"); + write64(s + 2 * PAGE + 16, 5); + let mut back = [0u8; 8]; + assert!(read(&p[2..], 16, &mut back)); + assert_eq!(u64::from_le_bytes(back), 5); + let mut fresh = [1u8; 4]; + let q = pages(1); + assert!(read(&q, 0, &mut fresh)); + assert_eq!(fresh, [0; 4], "a page never used reads zeros without being committed"); + assert!(!read(&p, PAGE, &mut back), "an offset past the first page is refused"); + free_space(s, 0, mem::MEM_RELEASE); + free(&p); + free(&q); + } + } + + #[test] + fn a_page_moved_outside_the_spaces_goes_and_comes_back_with_its_bytes() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(1); + let s = reserve_space(PAGE).unwrap(); + // address space outside the spaces (as a title's own placeholder region would be) + let out = unsafe { mem::VirtualAlloc(std::ptr::null(), PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) } as usize; + unsafe { + assert!(map(s, &p)); + write64(s, 21); + assert!(map(out, &p)); + assert_eq!(read64(out), 21, "moved with its bytes"); + assert!(physical_page_at(out)); + write64(out, 22); + let mut b = [0u8; 8]; + assert!(read(&p, 0, &mut b)); + assert_eq!(u64::from_le_bytes(b), 22, "read by number where it is now"); + assert!(map(out, &[0])); + assert_eq!(read64(s), 22, "back home with what it held there"); + free_space(s, 0, mem::MEM_RELEASE); + mem::VirtualFree(out as *mut c_void, 0, mem::MEM_RELEASE); + free(&p); + } + } + + #[test] + fn a_page_not_from_the_title_is_refused() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let s = reserve_space(PAGE).unwrap(); + unsafe { + assert!(!map(s, &[page_number(1 << 40)])); + assert!(!map(s + 4, &[0]), "an address not on a page boundary is refused"); + free_space(s, 0, mem::MEM_RELEASE); + } + } +} diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index e92fa56b2d..fc0f11de8d 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -46,6 +46,7 @@ unsafe fn commit(page: usize) -> bool { } // (a view of a physical page committed here is writable, not guarded: count it as written) super::guards::committed(page); + super::alias::committed_at(page); true } diff --git a/crates/xcl/src/hle/kernelx/sections.rs b/crates/xcl/src/hle/kernelx/sections.rs index 9935686253..7af7bc4a02 100644 --- a/crates/xcl/src/hle/kernelx/sections.rs +++ b/crates/xcl/src/hle/kernelx/sections.rs @@ -155,6 +155,22 @@ pub unsafe fn reservation_to_placeholder(at: usize, len: usize) -> bool { VirtualFree(at as *mut c_void, len, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != 0 } +/// Release every placeholder in `[at, at + len)`, which splitting may have cut into many (views +/// in it must be unmapped first). True if all of it went. +/// +/// # Safety +/// `[at, at + len)` must be placeholders the caller owns. +pub unsafe fn release_all(at: usize, len: usize) -> bool { + let mut p = at; + while p < at + len { + match allocation_at(p) { + Some((base, size, MEM_RESERVE, _)) if base == p && release(p) => p += size, + _ => return false, + } + } + true +} + /// Release the placeholder at `at` (its whole extent; views in it must be unmapped first). /// /// # Safety From 4f34c8d0bb78f5fee5a9b62cd3c72fc9e064bf65 Mon Sep 17 00:00:00 2001 From: Xeltax <85458421+Xeltax@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:45:41 +0100 Subject: [PATCH 5/7] kernelx: queue CopyPageMappingsBatchX records the physical page each GPU-view page shows Queue method #31 (#29 of the older layout) maps pages of the title's memory into GPU views; it was a stub. Its batches are now decoded and checked against the batch count and the pool, and each 64 KiB page of a GPU view records the pool page it was given and the physical page the title had mapped there (kernelx::mirrors). A bad call records nothing; releasing a view drops its pages. XCL keeps a physical page's data where it was mapped last, and the title maps most streamed pages into the CPU view behind the GPU view too, so `mapped_source` answers where that page is now (`page_now`), else the pool page itself. Each title mapping is remembered per address (Away::title), written once the page is in place and forgotten when the reservation goes; a page freed while its allocation lives is no longer looked for (Away::freed). Nothing reads the record yet: textures are unchanged; the queue logs its counts. (#1031) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/real.rs | 29 +++ crates/xcl/src/hle/kernelx.rs | 346 +++++++++++++++++++++++++++++- 2 files changed, 367 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9241a3a18d..814cdc6399 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6123,6 +6123,7 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a f(this, a1) } 23 => q_signal_x(this, a1 as *mut c_void, a2 as u64, a3 as u32) as u32 as usize, + 29 => q_copy_page_mappings(a1 as u32, a2, a3, a4 as u32) as u32 as usize, 30 => super::present::present_x(this, a1 as u32, a2 as *const u8, a3 as *const u8) as u32 as usize, // the newer layout's #35: ExecuteCommandListsX(count, lists, a value, flags) – a retail // game submits all its command lists this way (flags 3; 0 for the one it recorded at @@ -6169,6 +6170,34 @@ macro_rules! queue_slots { } queue_slots!(14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35); +/// command queue #29 (#31 in the newer layout) `CopyPageMappingsBatchX(count, batches, pool, +/// pool pages, flags)`: the title maps pages of its memory into GPU views – a retail game the +/// pages its texture streaming fills (a 6 GB pool) into the GPU views its textures are in, +/// tens of thousands of them while its world loads. Recorded per page (`kernelx::mirrors`); +/// as a stub every mapping was dropped (#1031). +unsafe fn q_copy_page_mappings(count: u32, batches: usize, pool: usize, pool_pages: u32) -> HRESULT { + static CALLS: AtomicU64 = AtomicU64::new(0); + static MAPPED: AtomicU64 = AtomicU64::new(0); + static UNMAPPED: AtomicU64 = AtomicU64::new(0); + static ELSEWHERE: AtomicU64 = AtomicU64::new(0); + static PHYSICAL: AtomicU64 = AtomicU64::new(0); + let n = CALLS.fetch_add(1, Ordering::Relaxed) + 1; + match crate::hle::kernelx::mirrors::apply_batches(count, batches, pool, pool_pages) { + Some(d) => { + let add = |total: &AtomicU64, k: u64| total.fetch_add(k, Ordering::Relaxed) + k; + let (m, p, u, e) = (add(&MAPPED, d.mapped), add(&PHYSICAL, d.physical), add(&UNMAPPED, d.unmapped), add(&ELSEWHERE, d.elsewhere)); + if n == 1 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: queue CopyPageMappingsBatchX: {n} calls; GPU-view pages so far: {m} mapped ({p} to a physical page the title mapped there), {u} unmapped; {e} pages elsewhere ignored (pool {pool:#x}, {pool_pages} pages of 64 KiB)"); + } + } + None => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: queue CopyPageMappingsBatchX({count}, {batches:#x}, {pool:#x}, {pool_pages}): a batch or range is unreadable or leaves the pool – the call is ignored")); + } + } + S_OK +} + /// command queue #23 SignalX(fence, value, flush flags): Signal with the console's cache flush /// options – the PC's Signal makes the queue's writes visible itself. (A stub that signalled /// nothing left Fortnite's render fences pending: its render thread waited, textures were diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 85b1d00a71..71033f1b0b 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -217,8 +217,134 @@ pub mod mirrors { pub fn released(base: usize) { let mut s = STATE.lock().unwrap(); s.cpu.retain(|&(b, _)| b != base); - s.gpu.remove(&base); - s.gpu.retain(|_, &mut (_, c)| c != base); + // the GPU views that go with it, and the pages mapped into them + let gone: Vec<(usize, usize)> = s.gpu.iter().filter(|&(&g, &(_, c))| g == base || c == base).map(|(&g, &(n, _))| (g, n)).collect(); + for (g, n) in gone { + s.gpu.remove(&g); + let mut pages = PAGES.lock().unwrap(); + let keys: Vec = pages.range(g..g + n).map(|(&k, _)| k).collect(); + for k in keys { + pages.remove(&k); + } + } + } + + /// Bytes of a page the queue's page-mapping method maps (the console's 64 KiB pages). + pub const PAGE: usize = 0x1_0000; + + /// What a GPU-view page shows after the page-mapping method: the pool page it was given, + /// and the physical page the title had mapped there then (`None`: none). The console maps + /// that physical page, which the title often maps into the CPU view too – XCL keeps its + /// data where it was mapped last (`super::page_now`). + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub struct Shown { + pub pool: usize, + pub page: Option, + } + + /// Pages of GPU views the title pointed somewhere else with the queue's page-mapping + /// method (`CopyPageMappingsBatchX`, `apply_batches`): GPU-view page → what it shows, or + /// `None` for a page left unmapped. A page not listed shows its CPU view (`source`). + static PAGES: Mutex>> = Mutex::new(BTreeMap::new()); + + /// What the page-mapping method put under `va`: `Some(Some(a))` – `va` shows the bytes at + /// `a` (where XCL keeps the physical page now, else the pool page itself), `Some(None)` – + /// nothing (unmapped), `None` – the method never mapped that page. + pub fn mapped_source(va: usize) -> Option> { + let off = va & (PAGE - 1); + let shown = *PAGES.lock().unwrap().get(&(va - off))?; + Some(shown.map(|s| s.page.and_then(super::page_now).unwrap_or(s.pool) + off)) + } + + /// One call of the queue's page-mapping method, `CopyPageMappingsBatchX(count, batches, + /// pool, pool pages, flags)` (queue #29; #31 in the newer layout). `count` batches of 24 + /// bytes – the first destination address (u64), the number of ranges (u32), a pointer to + /// them at +16 – each range three u32: the kind (0: `count` pool pages from `start` on, + /// 1: pool page `start` at each of `count` pages, 2: unmapped, 3: left as they are), + /// `start` and `count`. Pages are 64 KiB; the pool is `pool_pages` of them at `pool`. + /// The layout as VIctory describes it (`crates/victory-gpu/src/queue.rs`, a reference + /// only: no code taken). Only pages of GPU views are recorded (the retail title maps into + /// nothing else). `None` – nothing recorded – when a batch or a range is not readable, a + /// range leaves the pool or has an unknown kind, or the call names over `MOST` pages. + pub unsafe fn apply_batches(count: u32, batches: usize, pool: usize, pool_pages: u32) -> Option { + const BATCH: usize = 24; + const RANGE: usize = 12; + const MOST: usize = 1 << 20; + let readable = crate::gpu::shader::readable; + let n = count as usize; + if n == 0 { + return Some(Mapped::default()); + } + if n > MOST || !readable(batches, n * BATCH) { + return None; + } + // checked whole first, so a bad call records nothing + let mut changes: Vec<(usize, Option)> = Vec::new(); + for b in 0..n { + let p = batches + b * BATCH; + let dest = (p as *const u64).read_unaligned() as usize & !(PAGE - 1); + let ranges_n = ((p + 8) as *const u32).read_unaligned() as usize; + let ranges = ((p + 16) as *const usize).read_unaligned(); + if ranges_n == 0 { + continue; + } + if ranges_n > MOST || !readable(ranges, ranges_n * RANGE) { + return None; + } + let mut at = dest; + for r in 0..ranges_n { + let q = (ranges + r * RANGE) as *const u32; + let (kind, start, len) = (q.read_unaligned(), q.add(1).read_unaligned() as usize, q.add(2).read_unaligned() as usize); + let inside = |k: usize| start.checked_add(k).is_some_and(|e| e <= pool_pages as usize); + if changes.len() + len > MOST || at.checked_add(len * PAGE).is_none() { + return None; + } + match kind { + 0 if inside(len) => changes.extend((0..len).map(|k| (at + k * PAGE, Some(pool + (start + k) * PAGE)))), + 1 if inside(1) => changes.extend((0..len).map(|k| (at + k * PAGE, Some(pool + start * PAGE)))), + 2 => changes.extend((0..len).map(|k| (at + k * PAGE, None))), + 3 => {} + _ => return None, + } + at += len * PAGE; + } + } + // the physical page the title has mapped at each pool page: what the console maps + let changes: Vec<(usize, Option)> = { + let away = super::AWAY.lock().unwrap(); + let title = |pool: usize| away.as_ref().and_then(|a| a.title_page(pool)); + changes.into_iter().map(|(va, to)| (va, to.map(|pool| Shown { pool, page: title(pool) }))).collect() + }; + let s = STATE.lock().unwrap(); + let in_view = |va: usize| s.gpu.range(..=va).next_back().is_some_and(|(&g, &(size, _))| va < g + size); + let mut out = Mapped::default(); + let mut pages = PAGES.lock().unwrap(); + for (va, to) in changes { + if !in_view(va) { + out.elsewhere += 1; + continue; + } + match to { + Some(s) => { + out.mapped += 1; + out.physical += s.page.is_some() as u64; + } + None => out.unmapped += 1, + } + pages.insert(va, to); + } + Some(out) + } + + /// What one `apply_batches` call did, in 64 KiB pages. + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] + pub struct Mapped { + pub mapped: u64, + /// of those, pages whose pool page had a physical page the title mapped there + pub physical: u64, + pub unmapped: u64, + /// pages outside any GPU view: not recorded + pub elsewhere: u64, } /// The CPU-view address behind `va` when `va` lies in a GPU view. @@ -474,6 +600,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 if release { u.sparse_release(a); mirrors::released(a); + forget_title_mappings(a, n); } return 1; } @@ -487,9 +614,13 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 return 1; } let ok = mem::VirtualFree(addr, size, t); - if ok != 0 && t & 0x8000 != 0 && GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)).is_some() { - GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); - mirrors::released(addr as usize); + if ok != 0 && t & 0x8000 != 0 { + let released = GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)); + if let Some(len) = released { + GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + mirrors::released(addr as usize); + forget_title_mappings(addr as usize, len); + } } ok } @@ -915,9 +1046,45 @@ struct Away { /// homes in a sparse window whose pages went away in this call, given back at its end in /// runs (`give_back_homes`): one page at a time, a retail game's start took 20 s gone: Vec, + /// address → the page the title mapped there last. On the console a page stays mapped at + /// every address it was mapped at; here its data is in one place (`page`), so an address it + /// moved away from still names it here (the queue's page-mapping method maps the pages of + /// such addresses: `mirrors::apply_batches`). + title: std::collections::HashMap, + /// pages the title freed while others of their allocation live (`page_home` still knows + /// the block): no page is behind such a number any more (numbers are never handed out + /// again), so `page_now` answers none for it + freed: std::collections::HashSet, +} + +impl Away { + /// The page the title mapped at `at` last, if the title has not freed it. + fn title_page(&self, at: usize) -> Option { + self.title.get(&at).copied().filter(|p| !self.freed.contains(p)) + } +} + +/// The title released `[base, base + len)`: the pages it mapped there are mapped there no more. +fn forget_title_mappings(base: usize, len: usize) { + if let Some(a) = AWAY.lock().unwrap().as_mut() { + a.title.retain(|&at, _| at < base || at >= base.saturating_add(len)); + } } static AWAY: std::sync::Mutex> = std::sync::Mutex::new(None); +/// Where page `page`'s data is now: the address it is mapped at away from home, else its home +/// (`None`: no allocated page has that number). +fn page_now(page: usize) -> Option { + let (freed, away) = match AWAY.lock().unwrap().as_ref() { + Some(a) => (a.freed.contains(&page), a.page.get(&page).copied()), + None => (false, None), + }; + if freed { + return None; + } + away.or_else(|| page_home(page)) +} + /// Whether a physical page is mapped at the page holding `va` away from its home – committed /// or not yet (`lazy`: a page never used is committed at its first access). pub fn physical_page_at(va: usize) -> bool { @@ -1301,14 +1468,22 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: return 0; } // freed pages mapped elsewhere: that address keeps whatever it holds, the mapping goes - if let Some(away) = AWAY.lock().unwrap().as_mut() { + { + let mut g = AWAY.lock().unwrap(); + let away = g.get_or_insert_with(Away::default); for i in 0..n { - if let Some(at) = away.page.remove(&*arr.add(i)) { + let page = *arr.add(i); + if let Some(at) = away.page.remove(&page) { away.at.remove(&at); note_mapping_at(at); } + if page_index(page).is_some() { + away.freed.insert(page); + } } } + // (blocks gone whole: their numbers need no `freed` entries) + let mut gone: Vec<(usize, usize)> = Vec::new(); let mut g = PHYS_BLOCKS.lock().unwrap(); for i in 0..n { let Some(page) = page_index(*arr.add(i)) else { continue }; @@ -1321,6 +1496,7 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: e.1 = e.1.saturating_sub(1); if e.1 == 0 { g.remove(&first); + gone.push((first, count)); if u.is_sparse(home) { crate::hle::d3d12x::sparse::free(home); } else if u.contains(home) { @@ -1330,6 +1506,12 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: } } } + drop(g); + if !gone.is_empty() { + if let Some(away) = AWAY.lock().unwrap().as_mut() { + away.freed.retain(|&p| page_index(p).is_none_or(|i| !gone.iter().any(|&(f, c)| i >= f && i < f + c))); + } + } 1 } @@ -1383,6 +1565,9 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) } // (pages this call moved away and back are home again, not given back) away.gone.retain(|&h| h < home || h >= home + n * PHYS_PAGE); + for (i, &p) in pages.iter().enumerate() { + away.title.insert(home + i * PHYS_PAGE, p); + } for &p in &pages { if let Some(&at) = away.page.get(&p) { unmap_away(away, at, &(home..home + n * PHYS_PAGE)); @@ -1404,6 +1589,8 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) let (mut at_run, mut home_run) = (StateRun::default(), StateRun::default()); for (i, &p) in pages.iter().enumerate() { let at = base + i * PHYS_PAGE; + // what was mapped at `at` goes; the new page is written down once it is in place + away.title.remove(&at); if unmap_away(away, at, &(0..0)) { (at_run, home_run) = Default::default(); } @@ -1416,6 +1603,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) match move_away(away, old, at, p, in_uma(at)) { Ok(true) => { (at_run, home_run) = Default::default(); + away.title.insert(at, p); continue; } // a lazy page is only unmarked: memory is as it was, the runs stay @@ -1435,6 +1623,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) lazy::mark(at); away.at.insert(at, p); away.page.insert(p, at); + away.title.insert(at, p); continue; } if !in_uma(at) && mem::VirtualAlloc(at as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { @@ -1454,6 +1643,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) } away.at.insert(at, p); away.page.insert(p, at); + away.title.insert(at, p); } va } @@ -2720,7 +2910,7 @@ mod tests { let at = mem::VirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; mem::VirtualFree(at as *mut c_void, 0, mem::MEM_RELEASE); let page = 0x7E57_0000usize; - let mut away = Away { at: Default::default(), page: Default::default(), gone: Vec::new() }; + let mut away = Away::default(); away.at.insert(old, page); away.page.insert(page, old); assert!(move_away(&mut away, old, at, page, false).is_err()); @@ -2975,6 +3165,146 @@ mod tests { mirrors::released(other); } + /// A batch of the queue's page-mapping method: the first destination, the number of ranges + /// (`kind, start, count` each) and a pointer to them. + #[repr(C)] + struct Batch { + dest: u64, + ranges_n: u32, + _pad: u32, + ranges: usize, + } + fn batch(dest: usize, r: &[[u32; 3]]) -> Batch { + Batch { dest: dest as u64, ranges_n: r.len() as u32, _pad: 0, ranges: r.as_ptr() as usize } + } + + /// A GPU-view page given a pool page shows the physical page the title mapped there, where + /// XCL keeps it: at the pool page, then – once the title maps it into another address too + /// (the CPU view of a retail title's streamed textures) – there. + #[test] + fn a_gpu_view_page_shows_the_physical_page_where_it_is_kept() { + use mirrors::{apply_batches, mapped_source, Mapped, PAGE}; + let null = std::ptr::null_mut(); + unsafe { + let mut n = 1usize; + let mut page = [0usize; 1]; + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, page.as_mut_ptr()), 1); + // used at its home first, so the moves below copy it (no lazy page) + let home = MapTitlePhysicalPages(null, 1, 0, 4, page.as_mut_ptr()) as usize; + assert_ne!(home, 0); + *(home as *mut u32) = 0x600D; + // the pool: a reservation of the title's, the page mapped at its page 1 + let pool = mem::VirtualAlloc(std::ptr::null(), 4 * PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_eq!(MapTitlePhysicalPages((pool + PAGE) as *mut c_void, 1, 0, 4, page.as_mut_ptr()) as usize, pool + PAGE); + let (cpu, gpu, size) = (0x7140_0000_0000usize, 0x7146_0000_0000usize, 0x125 * PAGE); + mirrors::reserved(cpu, size, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(gpu, size, 0x2040_2000, 0x801); + // pool pages 0 (nothing mapped there) and 1 at the GPU view's pages 2 and 3 + let r = [[0, 0, 2]]; + assert_eq!(apply_batches(1, [batch(gpu + 2 * PAGE, &r)].as_ptr() as usize, pool, 4), Some(Mapped { mapped: 2, physical: 1, ..Mapped::default() })); + assert_eq!(mapped_source(gpu + 2 * PAGE + 8), Some(Some(pool + 8)), "no physical page: the pool page itself"); + assert_eq!(mapped_source(gpu + 3 * PAGE + 8), Some(Some(pool + PAGE + 8))); + assert_eq!(*(pool as *const u8).add(PAGE).cast::(), 0x600D); + // the title maps the page at another address too: XCL moves its data there, and the + // GPU view shows it there + let other = mem::VirtualAlloc(std::ptr::null(), PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_eq!(MapTitlePhysicalPages(other as *mut c_void, 1, 0, 4, page.as_mut_ptr()) as usize, other); + assert_eq!(*(other as *const u32), 0x600D); + assert_eq!(mapped_source(gpu + 3 * PAGE + 8), Some(Some(other + 8))); + mirrors::released(cpu); + assert_eq!(FreeTitlePhysicalPages(null, 1, page.as_mut_ptr()), 1); + mem::VirtualFree(other as *mut c_void, 0, mem::MEM_RELEASE); + mem::VirtualFree(pool as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + /// A page the title frees while the rest of its allocation lives is no longer looked for: + /// the GPU-view page given its pool page reads the pool page, which keeps its bytes; a later + /// call naming that pool page records no physical page (review of #1055). + #[test] + fn a_freed_page_is_read_at_its_pool_page() { + use mirrors::{apply_batches, mapped_source, Mapped, PAGE}; + let null = std::ptr::null_mut(); + unsafe { + let mut n = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1); + let home = MapTitlePhysicalPages(null, 2, 0, 4, pages.as_mut_ptr()) as usize; + assert_ne!(home, 0); + *((home + PAGE) as *mut u32) = 0xBEEF; + let pool = mem::VirtualAlloc(std::ptr::null(), 4 * PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_eq!(MapTitlePhysicalPages((pool + 2 * PAGE) as *mut c_void, 1, 0, 4, pages.as_mut_ptr().add(1)) as usize, pool + 2 * PAGE); + let (cpu, gpu, size) = (0x7150_0000_0000usize, 0x7156_0000_0000usize, 0x126 * PAGE); + mirrors::reserved(cpu, size, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(gpu, size, 0x2040_2000, 0x801); + let r = [[0u32, 2, 1]]; + assert_eq!(apply_batches(1, [batch(gpu + PAGE, &r)].as_ptr() as usize, pool, 4), Some(Mapped { mapped: 1, physical: 1, ..Mapped::default() })); + assert_eq!(mapped_source(gpu + PAGE), Some(Some(pool + 2 * PAGE))); + // page 1 freed alone: its block lives on (page 0), the pool page keeps the bytes + assert_eq!(FreeTitlePhysicalPages(null, 1, pages.as_mut_ptr().add(1)), 1); + assert!(page_home(pages[1]).is_some(), "the block is still allocated"); + assert_eq!(mapped_source(gpu + PAGE + 4), Some(Some(pool + 2 * PAGE + 4)), "the pool page, not the page's home"); + assert_eq!(*((pool + 2 * PAGE) as *const u32), 0xBEEF); + assert_eq!(apply_batches(1, [batch(gpu + 2 * PAGE, &r)].as_ptr() as usize, pool, 4), Some(Mapped { mapped: 1, ..Mapped::default() }), "no physical page behind it now"); + mirrors::released(cpu); + assert_eq!(FreeTitlePhysicalPages(null, 1, pages.as_mut_ptr()), 1); + assert!(AWAY.lock().unwrap().as_ref().is_some_and(|a| !a.freed.contains(&pages[1])), "the whole block gone: its numbers are forgotten"); + mem::VirtualFree(pool as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + /// The queue's page-mapping method (`CopyPageMappingsBatchX`) points pages of a GPU view + /// at pool pages or at nothing; a bad call records nothing; releasing the view drops them. + #[test] + fn page_mappings_point_gpu_view_pages_at_pool_pages() { + use mirrors::{apply_batches, mapped_source, Mapped, PAGE}; + // (a size no other test uses, so the GPU view pairs with this CPU view) + let (cpu, gpu, size) = (0x7100_0000_0000usize, 0x7106_0000_0000usize, 0x123 * PAGE); + let (pool, pool_pages) = (0x7200_0000_0000usize, 64u32); + mirrors::reserved(cpu, size, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(gpu, size, 0x2040_2000, 0x801); + assert_eq!(mirrors::source(gpu), Some(cpu)); + unsafe { + // two pool pages from 10 on, one page kept, pool page 5 three times, one unmapped; + // then two pages outside any GPU view + let r1 = [[0, 10, 2], [3, 0, 1], [1, 5, 3], [2, 0, 1]]; + let r2 = [[0, 0, 2]]; + let b = [batch(gpu + 4 * PAGE + 0x1234, &r1), batch(0x7300_0000_0000, &r2)]; + assert_eq!(apply_batches(2, b.as_ptr() as usize, pool, pool_pages), Some(Mapped { mapped: 5, unmapped: 1, elsewhere: 2, ..Mapped::default() })); + assert_eq!(mapped_source(gpu + 4 * PAGE + 0x20), Some(Some(pool + 10 * PAGE + 0x20))); + assert_eq!(mapped_source(gpu + 5 * PAGE), Some(Some(pool + 11 * PAGE))); + assert_eq!(mapped_source(gpu + 6 * PAGE), None, "kept"); + for k in 7..10 { + assert_eq!(mapped_source(gpu + k * PAGE + 8), Some(Some(pool + 5 * PAGE + 8))); + } + assert_eq!(mapped_source(gpu + 10 * PAGE), Some(None), "unmapped"); + assert_eq!(mapped_source(gpu + 11 * PAGE), None, "past the ranges"); + assert_eq!(mapped_source(gpu + 3 * PAGE), None, "before the destination"); + assert_eq!(mapped_source(0x7300_0000_0000), None, "outside any GPU view"); + + // a later call maps the unmapped page + let r = [[1, 1, 1]]; + assert_eq!(apply_batches(1, [batch(gpu + 10 * PAGE, &r)].as_ptr() as usize, pool, pool_pages), Some(Mapped { mapped: 1, ..Mapped::default() })); + assert_eq!(mapped_source(gpu + 10 * PAGE), Some(Some(pool + PAGE))); + + // bad calls record nothing: a range leaving the pool (after a good one), an unknown + // kind, ranges that are not readable + let leaves = [[0, 0, 1], [0, 63, 2]]; + assert_eq!(apply_batches(1, [batch(gpu + 20 * PAGE, &leaves)].as_ptr() as usize, pool, pool_pages), None); + assert_eq!(mapped_source(gpu + 20 * PAGE), None); + let unknown = [[7, 0, 1]]; + assert_eq!(apply_batches(1, [batch(gpu + 20 * PAGE, &unknown)].as_ptr() as usize, pool, pool_pages), None); + let unreadable = Batch { dest: (gpu + 20 * PAGE) as u64, ranges_n: 1, _pad: 0, ranges: 0 }; + assert_eq!(apply_batches(1, [unreadable].as_ptr() as usize, pool, pool_pages), None); + assert_eq!(apply_batches(1, 0, pool, pool_pages), None, "batches not readable"); + assert_eq!(apply_batches(0, 0, pool, pool_pages), Some(Mapped::default()), "no batches"); + } + mirrors::released(cpu); + assert_eq!(mirrors::source(gpu), None); + assert_eq!(mapped_source(gpu + 4 * PAGE), None, "released with its GPU view"); + assert_eq!(mapped_source(gpu + 10 * PAGE), None); + } + /// GPU-visible title memory that reaches the plain-memory fallback (64 KiB pages, large /// pages, a graphics protection) is write-watched: a texture placed there sees the CPU's /// writes. The fallback is called directly: through `VirtualAlloc` these sizes land in a From 31fe59c037b3b43bf119f5ad7cff467211964b76 Mon Sep 17 00:00:00 2001 From: Aditya Tripathi <9266227+adiologydev@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:40:24 +0530 Subject: [PATCH 6/7] kernelx: the page-mapping method's decoding apart from its record `mirrors::decode_batches` checks and decodes one call of the queue's CopyPageMappingsBatchX into (GPU-view page, pool page or unmapped) pairs; `apply_batches` records them as before. No change in behaviour: the next commit maps the decoded pages for real when physical pages alias. --- crates/xcl/src/hle/kernelx.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 71033f1b0b..5770b2ecb7 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -267,13 +267,22 @@ pub mod mirrors { /// nothing else). `None` – nothing recorded – when a batch or a range is not readable, a /// range leaves the pool or has an unknown kind, or the call names over `MOST` pages. pub unsafe fn apply_batches(count: u32, batches: usize, pool: usize, pool_pages: u32) -> Option { + let changes = decode_batches(count, batches, pool, pool_pages)?; + record(changes) + } + + /// The mappings of one call of the page-mapping method (`apply_batches`), checked whole: + /// (GPU-view page, the pool page it is given or `None`: unmapped), in the call's order. + /// `None` when a batch or a range is not readable, a range leaves the pool or has an unknown + /// kind, or the call names over `MOST` pages. + pub unsafe fn decode_batches(count: u32, batches: usize, pool: usize, pool_pages: u32) -> Option)>> { const BATCH: usize = 24; const RANGE: usize = 12; const MOST: usize = 1 << 20; let readable = crate::gpu::shader::readable; let n = count as usize; if n == 0 { - return Some(Mapped::default()); + return Some(Vec::new()); } if n > MOST || !readable(batches, n * BATCH) { return None; @@ -309,6 +318,11 @@ pub mod mirrors { at += len * PAGE; } } + Some(changes) + } + + /// `apply_batches`'s record of the decoded mappings. + unsafe fn record(changes: Vec<(usize, Option)>) -> Option { // the physical page the title has mapped at each pool page: what the console maps let changes: Vec<(usize, Option)> = { let away = super::AWAY.lock().unwrap(); From 64ad64ce6bcae6a0b5847b54c24ff12d12d5324b Mon Sep 17 00:00:00 2001 From: Aditya Tripathi <9266227+adiologydev@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:42:10 +0530 Subject: [PATCH 7/7] kernelx: with XCL_PAGE_ALIAS=1 the queue's page mappings show real pages The queue's CopyPageMappingsBatchX maps pool pages into GPU views; on the console a GPU-view page then shows the physical page mapped at its pool page at the time of the call. #1055 decodes the calls and keeps a record of them; with physical pages aliasing (`kernelx::alias`) the GPU view is a reservation of views, so the decoded mappings are made for real: each GPU-view page becomes a view of the physical page mapped at its pool page now, or is unmapped (kind 2, or nothing mapped at the pool page). Textures in the GPU view then read the page at their own address (`title_textures` prefers an address with a physical page mapped), and a write through any view of the page is uploaded at all of them. Without the switch nothing changes: the call is recorded as in #1055. --- crates/xcl/src/hle/d3d12x/real.rs | 23 +++++++++ crates/xcl/src/hle/kernelx.rs | 6 +++ crates/xcl/src/hle/kernelx/alias.rs | 72 +++++++++++++++++++++++++++++ 3 files changed, 101 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 814cdc6399..89e013969c 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6182,6 +6182,29 @@ unsafe fn q_copy_page_mappings(count: u32, batches: usize, pool: usize, pool_pag static ELSEWHERE: AtomicU64 = AtomicU64::new(0); static PHYSICAL: AtomicU64 = AtomicU64::new(0); let n = CALLS.fetch_add(1, Ordering::Relaxed) + 1; + // physical pages alias (`XCL_PAGE_ALIAS`): the GPU-view pages show the pool pages' physical + // pages for real, instead of a record of them + if crate::hle::kernelx::alias::enabled() { + static EMPTY: AtomicU64 = AtomicU64::new(0); + let done = crate::hle::kernelx::mirrors::decode_batches(count, batches, pool, pool_pages).and_then(|changes| { + crate::hle::kernelx::note_gpu_view_mapping(changes.first().map_or(0, |c| c.0)); + crate::hle::kernelx::alias::apply_page_mappings(&changes) + }); + match done { + Some(d) => { + let add = |total: &AtomicU64, k: u64| total.fetch_add(k, Ordering::Relaxed) + k; + let (m, u, e) = (add(&MAPPED, d.mapped), add(&UNMAPPED, d.unmapped), add(&EMPTY, d.empty_pool)); + if n == 1 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: queue CopyPageMappingsBatchX: {n} calls; pages mapped so far: {m} showing a physical page, {u} unmapped ({e} of them for a pool page with nothing mapped; pool {pool:#x}, {pool_pages} pages of 64 KiB)"); + } + } + None => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: queue CopyPageMappingsBatchX({count}, {batches:#x}, {pool:#x}, {pool_pages}): a batch or range is unreadable or leaves the pool, or a page could not be mapped")); + } + } + return S_OK; + } match crate::hle::kernelx::mirrors::apply_batches(count, batches, pool, pool_pages) { Some(d) => { let add = |total: &AtomicU64, k: u64| total.fetch_add(k, Ordering::Relaxed) + k; diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 5770b2ecb7..9ba91c677c 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -1117,6 +1117,12 @@ pub fn gpu_view_map_gen() -> u64 { GPU_VIEW_MAP_GEN.load(Ordering::Acquire) } +/// The queue's page-mapping method mapped pages at `va`: a GPU view's mappings changed if it +/// lies in one (textures there look again). +pub fn note_gpu_view_mapping(va: usize) { + note_mapping_at(va); +} + /// Pages are mapped or unmapped at `va`: a GPU view's mappings changed if it lies in one. fn note_mapping_at(va: usize) { if mirrors::source(va).is_some() { diff --git a/crates/xcl/src/hle/kernelx/alias.rs b/crates/xcl/src/hle/kernelx/alias.rs index 9963212807..5cf51b7603 100644 --- a/crates/xcl/src/hle/kernelx/alias.rs +++ b/crates/xcl/src/hle/kernelx/alias.rs @@ -300,6 +300,45 @@ pub fn physical_page_at(va: usize) -> bool { with(|s| s.views.contains_key(&at) || s.away_at.contains_key(&at)) } +/// The physical page mapped at the page holding `va` (a view, or a page moved there), or None. +pub fn page_at(va: usize) -> Option { + let at = va & !(PAGE - 1); + with(|s| s.views.get(&at).map(|v| v.0).or_else(|| s.away_at.get(&at).copied())) +} + +/// What one call of the queue's page-mapping method did, in 64 KiB pages. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Applied { + /// destination pages that show a physical page now + pub mapped: u64, + /// destination pages unmapped (by the call, or because nothing was mapped at their pool page) + pub unmapped: u64, + /// of those, pages whose pool page had nothing mapped + pub empty_pool: u64, +} + +/// The queue's page-mapping method (`CopyPageMappingsBatchX`, decoded by +/// `mirrors::decode_batches`): each destination page shows the physical page mapped at its pool +/// page now – on the console the method copies the pool page's mapping – or nothing. +pub unsafe fn apply_page_mappings(changes: &[(usize, Option)]) -> Option { + let mut out = Applied::default(); + for &(dest, pool) in changes { + let page = pool.and_then(page_at); + if !map_one(dest & !(PAGE - 1), page.unwrap_or(0)) { + return None; + } + match (pool, page) { + (_, Some(_)) => out.mapped += 1, + (Some(_), None) => { + out.unmapped += 1; + out.empty_pool += 1; + } + (None, _) => out.unmapped += 1, + } + } + Some(out) +} + /// Where page `page`'s bytes are now (committing its home if `write`), or None. unsafe fn bytes_of(page: usize, write: bool) -> Option<(usize, bool)> { let (away, home) = with(|s| (s.away.get(&page).copied(), s.page(page).map(|p| p.2))); @@ -490,6 +529,39 @@ mod tests { } } + #[test] + fn the_queue_page_mapping_method_shows_the_pool_pages_physical_page_in_the_gpu_view() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(2); + let pool = reserve_space(4 * PAGE).unwrap(); + let cpu = reserve_space(4 * PAGE).unwrap(); + let gpu = reserve_space(4 * PAGE).unwrap(); + unsafe { + // a streamed page: in the pool and in the CPU view, written through the CPU view + assert!(map(pool + PAGE, &[p[0]])); + assert!(map(cpu + 2 * PAGE, &[p[0]])); + write64(cpu + 2 * PAGE, 0x5EED); + // kind 0 / 1: pool pages at GPU-view pages; pool page 3 holds nothing; kind 2: unmapped + let changes = [(gpu, Some(pool + PAGE)), (gpu + PAGE, Some(pool + PAGE)), (gpu + 2 * PAGE, Some(pool + 3 * PAGE)), (gpu + 3 * PAGE, None)]; + let done = apply_page_mappings(&changes).unwrap(); + assert_eq!(done, Applied { mapped: 2, unmapped: 2, empty_pool: 1 }); + assert_eq!(read64(gpu), 0x5EED, "the GPU view shows the page the CPU view wrote"); + assert_eq!(read64(gpu + PAGE), 0x5EED, "one pool page at two GPU-view pages"); + assert!(!physical_page_at(gpu + 2 * PAGE) && !physical_page_at(gpu + 3 * PAGE)); + dirty(); + write64(gpu + PAGE + 8, 1); + assert_eq!(dirty(), vec![pool + PAGE, cpu + 2 * PAGE, gpu, gpu + PAGE], "a write in the GPU view: every view of the page is uploaded"); + // the pool page is given another physical page later: the GPU view keeps the one it was given + assert!(map(pool + PAGE, &[p[1]])); + assert_eq!(read64(gpu), 0x5EED); + assert_eq!(page_at(gpu), Some(p[0])); + for s in [pool, cpu, gpu] { + free_space(s, 0, mem::MEM_RELEASE); + } + free(&p); + } + } + #[test] fn a_page_not_from_the_title_is_refused() { let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner());