From f532d33d695a360bf5701650374dd87a4566c499 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 1/2] 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 5b01e8569..c0b0ae760 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5007,6 +5007,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 @@ -5053,6 +5054,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 8aa3bc200..93478824b 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -203,8 +203,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. @@ -430,6 +556,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 } if release { u.sparse_release(a); + forget_title_mappings(a, n); } return 1; } @@ -443,9 +570,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 } @@ -810,9 +941,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 { @@ -1166,14 +1333,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 }; @@ -1186,6 +1361,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) { @@ -1195,6 +1371,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 } @@ -1233,6 +1415,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)); @@ -1254,6 +1439,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(); } @@ -1266,6 +1453,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 @@ -1285,6 +1473,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() { @@ -1304,6 +1493,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 } @@ -2435,7 +2625,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()); @@ -2685,6 +2875,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 c387de21fa81d09269bd311b3be6a3afe6598daf Mon Sep 17 00:00:00 2001 From: Xeltax <85458421+Xeltax@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:25:47 +0100 Subject: [PATCH 2/2] D3D12.X: a texture in a GPU view reads the pages the page-mapping method put under it Each 64 KiB page of a texture in a GPU view is read from what queue XCL keeps it, zeros for an unmapped page, the CPU view for a page the method never mapped (`source_of`, `Source::Pages`). The textures on the pages a call changes, or whose physical page moved, are looked at again at the next submit (`mirrors::take_changed`, `page_moved`), not all of them. Their writes are watched where the pages are. (#1031) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/title_textures.rs | 274 ++++++++++++++++---- crates/xcl/src/hle/kernelx.rs | 77 +++++- 2 files changed, 297 insertions(+), 54 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ada439cba..fcdea0adb 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -38,17 +38,71 @@ extern "system" { fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; } -/// (device, address its bytes are read from, layout, states) of an upload -type Upload = (usize, usize, Arc, Vec); +/// (device, where its bytes are read from, layout, states) of an upload +type Upload = (usize, Source, Arc, Vec); + +/// Where a texture's bytes are read from and its CPU writes watched (`source_of`). +#[derive(Clone, Debug, PartialEq, Eq)] +enum Source { + /// all of them at this address: `va`, or – for a texture in a GPU view of the title's CPU + /// memory with nothing mapped there – the same offset in the CPU view (`kernelx::mirrors`) + At(usize), + /// a texture in a GPU view whose pages the queue's page-mapping method mapped + /// (`kernelx::mirrors::mapped_source`): runs of its bytes, `(offset, length, address)`, + /// read from that address – 0: an unmapped page, zeros + Pages(Arc<[(usize, usize, usize)]>), +} + +impl Source { + /// The texture's `len` bytes from offset `off` (unreadable memory reads as zeros). + unsafe fn bytes(&self, off: usize, len: usize) -> std::borrow::Cow<'static, [u8]> { + match self { + Source::At(a) => title_bytes(a + off, len), + Source::Pages(runs) => { + let mut out = vec![0u8; len]; + for &(r_off, r_len, at) in runs.iter() { + let (s, e) = (r_off.max(off), (r_off + r_len).min(off + len)); + if at != 0 && s < e { + out[s - off..e - off].copy_from_slice(&title_bytes(at + (s - r_off), e - s)); + } + } + std::borrow::Cow::Owned(out) + } + } + } + + /// The memory its `size` bytes are read from, `(start, end)` each. + fn ranges(&self, size: usize) -> impl Iterator + '_ { + let (at, runs): (Option, &[(usize, usize, usize)]) = match self { + Source::At(a) => (Some(*a), &[]), + Source::Pages(runs) => (None, runs), + }; + at.map(|a| (a, a + size)).into_iter().chain(runs.iter().filter(|r| r.2 != 0).map(|&(_, n, a)| (a, a + n))) + } + + /// Whether a page of `dirty` (sorted, `page` bytes each) holds some of its `size` bytes. + fn written(&self, size: usize, dirty: &[usize], page: usize) -> bool { + self.ranges(size).any(|(s, e)| { + let i = dirty.partition_point(|&p| p + page <= s); + dirty.get(i).is_some_and(|&p| p < e) + }) + } + + /// Where its first byte is read from, for logs (0: an unmapped page). + fn first(&self) -> usize { + match self { + Source::At(a) => *a, + Source::Pages(runs) => runs.first().map_or(0, |r| r.2), + } + } +} struct Entry { device: usize, /// the title's address of the texture va: usize, - /// where its bytes are read and its CPU writes watched: `va`, or – for a texture in a GPU - /// view of the title's CPU memory with nothing mapped there – the same offset in the CPU - /// view (`kernelx::mirrors`) - src: usize, + /// where its bytes are read and its CPU writes watched + src: Source, /// `va` lies in a GPU view: `src` is checked again when that view's mappings change in_gpu_view: bool, tex: Arc, @@ -360,12 +414,16 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, if ID3D12Resource::from_raw_borrowed(&res).is_none() { return Err("no resource".into()); } - let src = mirror_source(va); - if src != va { + let src = source_of(va, tex.size() as usize); + if src != Source::At(va) { static N: AtomicU64 = AtomicU64::new(0); let n = N.fetch_add(1, Ordering::Relaxed) + 1; if n <= 2 || n.is_power_of_two() { - crate::xlog_info!("D3D12.X: a texture at {va:#x} lies in a GPU view of the title's CPU memory: kept in step with {src:#x} ({n} so far)"); + let how = match &src { + Source::At(a) => format!("{a:#x}"), + Source::Pages(runs) => format!("its pages ({} runs, from {:#x})", runs.len(), src.first()), + }; + crate::xlog_info!("D3D12.X: a texture at {va:#x} lies in a GPU view of the title's CPU memory: kept in step with {how} ({n} so far)"); } } let in_gpu_view = crate::hle::kernelx::mirrors::source(va).is_some(); @@ -410,21 +468,71 @@ fn mirror_source(va: usize) -> usize { if mapped { va } else { src } } -/// Physical pages were mapped or unmapped in a GPU view since the last look: textures there -/// whose source changed (a page now mapped under one, or gone from it) read from the new one, -/// uploaded again at this submit. +/// Where the `len` bytes of a texture at `va` are read from: page by page when the queue's +/// page-mapping method mapped any of its pages (a retail title's streamed textures: each page +/// shows a physical page, kept where the title mapped it last – often not the CPU view's same +/// offset), else `mirror_source`. A page the method never mapped reads `mirror_source`; the +/// method's mapping goes before a physical page mapped at the GPU-view address itself. +fn source_of(va: usize, len: usize) -> Source { + use crate::hle::kernelx::mirrors::{self, mapped_source, PAGE}; + let end = va.saturating_add(len); + if mirrors::source(va).is_none() || !(va & !(PAGE - 1)..end).step_by(PAGE).any(|p| mapped_source(p).is_some()) { + return Source::At(mirror_source(va)); + } + let mut runs: Vec<(usize, usize, usize)> = Vec::new(); + let mut at = va; + while at < end { + let n = (PAGE - (at & (PAGE - 1))).min(end - at); + let from = match mapped_source(at) { + Some(Some(a)) => a, + Some(None) => 0, + None => mirror_source(at), + }; + match runs.last_mut() { + Some((_, len, a)) if (*a == 0 && from == 0) || (*a != 0 && from == *a + *len) => *len += n, + _ => runs.push((at - va, n, from)), + } + at += n; + } + match runs[..] { + [(_, _, a)] if a != 0 => Source::At(a), + _ => Source::Pages(runs.into()), + } +} + +/// Physical pages were mapped or unmapped in a GPU view since the last look, or the queue's +/// page-mapping method changed what some of its pages show: textures there whose source +/// changed (a page now mapped under one, or gone from it) read from the new one, uploaded again +/// at this submit. After the method only the textures on the pages it changed are looked at +/// (all of a retail title's 64k textures took 225 ms, its calls come by the hundred). fn recheck_gpu_view_sources() { static SEEN: AtomicU64 = AtomicU64::new(0); + let pages = crate::hle::kernelx::mirrors::take_changed(); let gen = crate::hle::kernelx::gpu_view_map_gen(); - if SEEN.swap(gen, Ordering::AcqRel) == gen { + let all = SEEN.swap(gen, Ordering::AcqRel) != gen; + if !all && pages.is_empty() { return; } let mut changed = false; // (the shadowed textures too: one comes back when the texture over it goes) let mut g = TEXTURES.lock().unwrap(); let t = &mut *g; - for e in t.by_res.values_mut().chain(t.shadowed.values_mut()) { - changed |= recheck_source(e); + if all { + for e in t.by_res.values_mut().chain(t.shadowed.values_mut()) { + changed |= recheck_source(e); + } + } else { + let mut on: Vec = Vec::new(); + for &(a, b) in &pages { + on.extend(t.active_overlaps(a, b).into_iter().chain(t.shadowed_overlaps(a, b)).map(|(_, res, _)| res)); + } + on.sort_unstable(); + on.dedup(); + for res in on { + if let Some(e) = t.get_mut(res) { + changed |= recheck_source(e); + } + } } drop(g); if changed { @@ -438,7 +546,7 @@ fn recheck_source(e: &mut Entry) -> bool { if !e.in_gpu_view { return false; } - let src = mirror_source(e.va); + let src = source_of(e.va, e.tex.size() as usize); if src == e.src { return false; } @@ -632,7 +740,7 @@ fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc> { // write-watched regions) only when the set of textures, tiles, or reservations changed. let mut regions = u.watch_regions(); regions.extend(crate::hle::kernelx::graphics_reservations()); - let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().by_res.values().map(|e| (e.src & !0xFFF, (e.src + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect(); + let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().by_res.values().flat_map(|e| e.src.ranges(e.tex.size() as usize).map(|(s, e)| (s & !0xFFF, (e + 0xFFF) & !0xFFF)).collect::>()).collect(); wanted.extend(super::sparse::mapped_ranges()); let computed = Arc::new(watch_ranges(®ions, wanted)); *WATCH_CACHE.lock().unwrap() = Some((key, Arc::clone(&computed))); @@ -719,11 +827,7 @@ unsafe fn refresh_once(queue: *mut c_void) { // level 0 last) let content = |e: &Entry| -> usize { let size = e.tex.size() as usize; - (0..16usize) - .map(|k| e.src + (size.saturating_sub(4096)) * k / 15) - .filter(|&a| crate::gpu::shader::readable(a, 4096)) - .map(|a| std::slice::from_raw_parts(a as *const u8, 4096).iter().filter(|&&b| b != 0).count()) - .sum() + (0..16usize).map(|k| e.src.bytes(size.saturating_sub(4096) * k / 15, size.min(4096)).iter().filter(|&&b| b != 0).count()).sum() }; let (mut with, mut without) = (0, 0); let mut shown = 0; @@ -763,8 +867,7 @@ unsafe fn refresh_once(queue: *mut c_void) { if e.gpu_written { return false; } - let i = dirty.partition_point(|&p| p + page as usize <= e.src); - dirty.get(i).is_some_and(|&p| p < e.src + e.tex.size() as usize) + e.src.written(e.tex.size() as usize, &dirty, page as usize) }) .filter_map(|(&res, e)| { if e.pending { @@ -772,7 +875,7 @@ unsafe fn refresh_once(queue: *mut c_void) { PENDING.fetch_sub(1, Ordering::Relaxed); } let p = res as *mut c_void; - ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.src, Arc::clone(&e.tex), e.states.clone()))) + ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.src.clone(), Arc::clone(&e.tex), e.states.clone()))) }) .collect() }); @@ -834,13 +937,13 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { if !picked.is_empty() && (bytes + tex.size() as usize > BATCH_BYTES || *dev != device) { break; } - let (r, (dev, va, tex, states)) = todo.next().unwrap(); + let (r, (dev, src, tex, states)) = todo.next().unwrap(); // The same bytes as at this texture's last upload: nothing to do. The write watch is // per page and a title writes next to its textures (and rewrites what it wrote): a // retail title's video planes and UI targets went up again for every submit, ~25 MB // a presented frame where ~3 MB had changed, and the submits waited here. if unchanged_skip() { - let h = content_hash(&title_bytes(va, tex.size() as usize)); + let h = content_hash(&src.bytes(0, tex.size() as usize)); if same_as_last_upload(r.as_raw() as usize, h) { let n = UNCHANGED.fetch_add(1, Ordering::Relaxed) + 1; if n == 1 || (n.is_power_of_two() && n >= 1024) { @@ -851,13 +954,13 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { } device = dev; bytes += tex.size() as usize; - picked.push((r, va, tex, states)); + picked.push((r, src, tex, states)); } let subs = subresources_of_all(&picked, bytes); let mut batch = Vec::with_capacity(picked.len()); - for ((r, va, _, states), subs) in picked.into_iter().zip(subs) { + for ((r, src, _, states), subs) in picked.into_iter().zip(subs) { if super::present::trace_frame() { - note_content(va, &r, &subs); + note_content(src.first(), &r, &subs); } batch.push((r, subs, states)); } @@ -916,7 +1019,7 @@ pub unsafe fn probe_gpu_content(res: usize) { } g.push(res); } - let Some((device, va, tex, gpu_written)) = TEXTURES.lock().unwrap().by_res.get(&res).map(|e| (e.device, e.src, Arc::clone(&e.tex), e.gpu_written)) else { return }; + let Some((device, va, src, tex, gpu_written)) = TEXTURES.lock().unwrap().by_res.get(&res).map(|e| (e.device, e.va, e.src.clone(), Arc::clone(&e.tex), e.gpu_written)) else { return }; let d = device as *mut c_void; let r = res as *mut c_void; let (Some(dev), Some(r)) = (ID3D12Device::from_raw_borrowed(&d), ID3D12Resource::from_raw_borrowed(&r)) else { return }; @@ -974,7 +1077,7 @@ pub unsafe fn probe_gpu_content(res: usize) { rb.Unmap(0, None); Ok(out) }); - let cpu = subresources(va, &tex).into_iter().next().map(|s| s.data).unwrap_or_default(); + let cpu = subresources_of(&src, &tex).into_iter().next().map(|s| s.data).unwrap_or_default(); match result { Ok(gpu) => { let nonzero = gpu.iter().filter(|&&b| b != 0).count(); @@ -1118,17 +1221,17 @@ const PARALLEL_BYTES: usize = 1 << 20; /// `subresources` of every texture of a batch (`bytes` of them), in order: on several threads /// when the batch is big. They were read and detiled one after another in the title's own /// submit – most of a retail game's render thread while it streamed textures the CPU writes. -unsafe fn subresources_of_all(picked: &[(ID3D12Resource, usize, Arc, Vec)], bytes: usize) -> Vec> { - let picked: Vec<(usize, &xg::Texture)> = picked.iter().map(|(_, va, tex, _)| (*va, &**tex)).collect(); +unsafe fn subresources_of_all(picked: &[(ID3D12Resource, Source, Arc, Vec)], bytes: usize) -> Vec> { + let picked: Vec<(&Source, &xg::Texture)> = picked.iter().map(|(_, src, tex, _)| (src, &**tex)).collect(); let threads = if bytes < PARALLEL_BYTES { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get() / 2).clamp(1, 8) }; subresources_on(&picked, threads) } /// `subresources` of each (address, texture), in order, on up to `threads` threads. -unsafe fn subresources_on(picked: &[(usize, &xg::Texture)], threads: usize) -> Vec> { +unsafe fn subresources_on(picked: &[(&Source, &xg::Texture)], threads: usize) -> Vec> { let threads = threads.min(picked.len()); if threads <= 1 { - return picked.iter().map(|&(va, tex)| subresources(va, tex)).collect(); + return picked.iter().map(|&(src, tex)| subresources_of(src, tex)).collect(); } // the next texture to take; each thread hands back (index, subresources) let next = std::sync::atomic::AtomicUsize::new(0); @@ -1140,9 +1243,9 @@ unsafe fn subresources_on(picked: &[(usize, &xg::Texture)], threads: usize) -> V let mut mine = Vec::new(); loop { let k = next.fetch_add(1, Ordering::Relaxed); - let Some(&(va, tex)) = picked.get(k) else { break }; + let Some(&(src, tex)) = picked.get(k) else { break }; // SAFETY: as in the serial path – the title's memory is only read - mine.push((k, unsafe { subresources(va, tex) })); + mine.push((k, unsafe { subresources_of(src, tex) })); } mine }) @@ -1167,17 +1270,23 @@ unsafe fn title_bytes(at: usize, len: usize) -> std::borrow::Cow<'static, [u8]> } /// Every subresource (D3D12 order) of a texture from the title's memory at `va`. +#[cfg(test)] unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { + subresources_of(&Source::At(va), tex) +} + +/// Every subresource (D3D12 order) of a texture from where its bytes are (`src`). +unsafe fn subresources_of(src: &Source, tex: &xg::Texture) -> Vec { let Some(tex) = tex.texels() else { return Vec::new() }; let c = &tex.chain; let bpe = tex.bpe as usize; if tex.depth > 0 { - let mem = title_bytes(va, tex.size() as usize); + let mem = src.bytes(0, tex.size() as usize); return c.levels.iter().enumerate().map(|(i, l)| Subresource { depth: l.depth, rows: l.height, row_bytes: l.width * bpe, data: c.detile_volume(&mem, i) }).collect(); } let mut out = Vec::with_capacity(tex.array as usize * c.levels.len()); for s in 0..tex.array as usize { - let slice = title_bytes(va + s * c.slice_bytes, c.slice_bytes); + let slice = src.bytes(s * c.slice_bytes, c.slice_bytes); for (i, l) in c.levels.iter().enumerate() { out.push(Subresource { depth: 1, rows: l.height, row_bytes: l.width * bpe, data: c.detile_level(&slice, i, s) }); } @@ -1352,10 +1461,82 @@ mod tests { refresh(queue.as_raw()); assert_eq!(read_r8(dev, &queue, &texture), vec![0x9A; 64 * 64], "unmapping restores the earlier CPU view"); assert_eq!(address(key), Some(va)); + + // The queue's page-mapping method puts a pool page under the texture (#1031): the + // GPU sees the physical page the title mapped at that pool page … + let pool = Reservation(kernelx::VirtualAlloc(std::ptr::null(), 4 * PAGE, 0x2040_2000, mem::PAGE_READWRITE) as usize); + assert_ne!(pool.0, 0); + let (mut count, mut id) = (1usize, 0usize); + assert_eq!(kernelx::AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut count, &mut id), 1); + let mut pooled = PhysicalPage { id, at: pool.0 + PAGE }; + assert_eq!(kernelx::MapTitlePhysicalPages(pooled.at as *mut c_void, 1, 0, 4, &mut pooled.id) as usize, pooled.at); + std::ptr::write_bytes(pooled.at as *mut u8, 0x5E, PAGE); + let r = [[1u32, 1, 1]]; + assert!(kernelx::mirrors::apply_batches(1, [page_batch(va, &r)].as_ptr() as usize, pool.0, 4).is_some()); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &texture), vec![0x5E; 64 * 64], "the pool page under the texture"); + // … and follows that page when the title maps it into the CPU view too (XCL keeps + // its data there now), with the CPU's writes there + let mut again = id; + assert_eq!(kernelx::MapTitlePhysicalPages(src as *mut c_void, 1, 0, 4, &mut again) as usize, src); + pooled.at = src; + std::ptr::write_bytes(src as *mut u8, 0x71, PAGE); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &texture), vec![0x71; 64 * 64], "the page moved to the CPU view, written there"); + // unmapped by the method: zeros + let r = [[2u32, 0, 1]]; + assert!(kernelx::mirrors::apply_batches(1, [page_batch(va, &r)].as_ptr() as usize, pool.0, 4).is_some()); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &texture), vec![0; 64 * 64], "an unmapped page reads as zeros"); dev.GetDeviceRemovedReason().unwrap(); } } + /// A batch of the queue's page-mapping method (`kernelx::mirrors::apply_batches`). + #[repr(C)] + struct PageBatch { + dest: u64, + ranges_n: u32, + _pad: u32, + ranges: usize, + } + fn page_batch(dest: usize, r: &[[u32; 3]]) -> PageBatch { + PageBatch { dest: dest as u64, ranges_n: r.len() as u32, _pad: 0, ranges: r.as_ptr() as usize } + } + + /// A texture in a GPU view whose pages the queue's page-mapping method mapped is read page + /// by page: a mapped page from its pool page, an unmapped one as zeros, one the method + /// never mapped from the CPU view; pages in one run of the pool are one address. + #[test] + fn a_page_mapped_texture_is_read_page_by_page() { + use crate::hle::kernelx::mirrors::{self, apply_batches, PAGE}; + // (addresses far above anything Windows hands out, and a size no other test uses) + let (cpu, gpu, size) = (0x7180_0000_0000usize, 0x7186_0000_0000usize, 0x127 * PAGE); + mirrors::reserved(cpu, size, 0x2040_2000, 0x04); + mirrors::reserved(gpu, size, 0x2040_2000, 0x801); + let pool: Vec = (0..4 * PAGE).map(|i| (i / PAGE * 0x40 + i % 7) as u8).collect(); + let p = pool.as_ptr() as usize; + unsafe { + // pool pages 1 and 2 at pages 2 and 3, page 4 unmapped, page 5 left alone + let r = [[0, 1, 2], [2, 0, 1]]; + assert!(apply_batches(1, [page_batch(gpu + 2 * PAGE, &r)].as_ptr() as usize, p, 4).is_some()); + let src = source_of(gpu + 2 * PAGE, 4 * PAGE); + assert_eq!(src, Source::Pages(vec![(0, 2 * PAGE, p + PAGE), (2 * PAGE, PAGE, 0), (3 * PAGE, PAGE, cpu + 5 * PAGE)].into())); + let b = src.bytes(0x100, 3 * PAGE - 0x100); + assert_eq!(&b[..2 * PAGE - 0x100], &pool[PAGE + 0x100..3 * PAGE]); + assert!(b[2 * PAGE - 0x100..].iter().all(|&x| x == 0), "the unmapped page reads as zeros"); + assert_eq!(src.ranges(4 * PAGE).collect::>(), vec![(p + PAGE, p + 3 * PAGE), (cpu + 5 * PAGE, cpu + 6 * PAGE)]); + assert!(src.written(4 * PAGE, &[p + 2 * PAGE + 0x3000], 0x1000), "a write to a pool page it shows"); + assert!(!src.written(4 * PAGE, &[p + 3 * PAGE], 0x1000), "a pool page it does not show"); + // a texture on one run of the pool: one address + assert_eq!(source_of(gpu + 2 * PAGE + 0x40, PAGE), Source::At(p + PAGE + 0x40)); + // the method never mapped these pages: the CPU view, as before + assert_eq!(source_of(gpu + 8 * PAGE, PAGE), Source::At(cpu + 8 * PAGE)); + } + mirrors::released(cpu); + assert_eq!(source_of(gpu + 2 * PAGE, PAGE), Source::At(gpu + 2 * PAGE), "the view is gone"); + } + /// A physical page mapped into a GPU view but not used yet (reserved until its first /// access, `kernelx::lazy`) is that address's own source, not the CPU view behind it. /// (Test by Kalmarv, review of PR #283.) @@ -1385,13 +1566,13 @@ mod tests { d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); d[0x2C..0x30].copy_from_slice(&0x105u32.to_le_bytes()); let tex = Arc::new(xg::Texture::new(&d).unwrap()); - let mut e = Entry { device: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, placed: false, unmapped: false, seq: 0 }; - assert_eq!(e.src, cpu + 0x2_0000); + let mut e = Entry { device: 0, va: at, src: Source::At(mirror_source(at)), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, placed: false, unmapped: false, seq: 0 }; + assert_eq!(e.src, Source::At(cpu + 0x2_0000)); assert!(!recheck_source(&mut e), "nothing changed yet"); assert_eq!(kernelx::MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, at); // … and the page mapped under it later, uploaded again assert!(recheck_source(&mut e)); - assert_eq!(e.src, at); + assert_eq!(e.src, Source::At(at)); assert!(e.pending); PENDING.fetch_sub(1, Ordering::Relaxed); let before = mirror_source(at); @@ -1483,7 +1664,7 @@ mod tests { assert_eq!(subresource_count(&tex), 6); // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it let (res, other, l1, l2) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize, 0x7E57_0000_3000usize, 0x7E57_0000_4000usize); - TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, placed: false, unmapped: false, seq: 0 }); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, src: Source::At(0x7E57_0000_0000), in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, placed: false, unmapped: false, seq: 0 }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().by_res.get(&res).unwrap().states.clone(); let (p1, p2) = (l1 as *mut c_void, l2 as *mut c_void); @@ -1572,7 +1753,8 @@ mod tests { let textures: Vec = descs.iter().map(|d| xg::Texture::new(d).unwrap()).collect(); // each texture's console memory: distinct bytes per texture let mems: Vec> = textures.iter().enumerate().map(|(t, x)| (0..x.size() as usize).map(|i| (i * 7 + t * 61) as u8).collect()).collect(); - let picked: Vec<(usize, &xg::Texture)> = mems.iter().zip(&textures).map(|(m, x)| (m.as_ptr() as usize, x)).collect(); + let sources: Vec = mems.iter().map(|m| Source::At(m.as_ptr() as usize)).collect(); + let picked: Vec<(&Source, &xg::Texture)> = sources.iter().zip(&textures).collect(); unsafe { let one = subresources_on(&picked, 1); assert!(one.iter().all(|s| !s.is_empty()), "a texture gave no subresources"); @@ -1606,7 +1788,7 @@ mod tests { let entry = |va: usize, tex: &Arc, pending: bool, placed: bool| Entry { device: 0, va, - src: va, + src: Source::At(va), in_gpu_view: false, tex: Arc::clone(tex), states: vec![D3D12_RESOURCE_STATE_COMMON], diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 93478824b..3946fb9ae 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -165,7 +165,7 @@ const MEM_WRITE_WATCH: u32 = 0x20_0000; /// video was its colour of zero luma and chroma, a green screen. `source` names the CPU view /// behind an address of such a GPU view, which `d3d12x::title_textures` reads and watches. pub mod mirrors { - use std::collections::BTreeMap; + use std::collections::{BTreeMap, BTreeSet}; use std::sync::Mutex; /// MEM_LARGE_PAGES | MEM_PHYSICAL: the console's 64 KiB pages @@ -208,10 +208,12 @@ pub mod mirrors { 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(); + let keys: Vec = pages.at.range(g..g + n).map(|(&k, _)| k).collect(); for k in keys { - pages.remove(&k); + pages.set(k, None); + pages.at.remove(&k); } + pages.changed.retain(|&(a, _)| a < g || a >= g + n); } } @@ -229,19 +231,72 @@ pub mod mirrors { } /// 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()); + /// method (`CopyPageMappingsBatchX`, `apply_batches`). + struct Pages { + /// GPU-view page → what it shows, or `None` for a page left unmapped. A page not + /// listed shows its CPU view (`source`). + at: BTreeMap>, + /// physical page → the GPU-view pages that show it + by_page: BTreeMap>, + /// GPU-view ranges whose bytes are elsewhere since the last `take_changed`: mapped or + /// unmapped, or their physical page was moved + changed: Vec<(usize, usize)>, + } + static PAGES: Mutex = Mutex::new(Pages { at: BTreeMap::new(), by_page: BTreeMap::new(), changed: Vec::new() }); + + impl Pages { + /// GPU-view page `va` shows `to` from now on: `by_page` follows. + fn set(&mut self, va: usize, to: Option) { + let old = self.at.insert(va, to); + if let Some(p) = old.flatten().and_then(|s| s.page) { + if let Some(set) = self.by_page.get_mut(&p) { + set.remove(&va); + if set.is_empty() { + self.by_page.remove(&p); + } + } + } + if let Some(p) = to.and_then(|s| s.page) { + self.by_page.entry(p).or_default().insert(va); + } + self.note(va); + } + + /// The page at `va` changed (runs of pages kept together). + fn note(&mut self, va: usize) { + match self.changed.last_mut() { + Some((_, end)) if *end == va => *end += PAGE, + _ => self.changed.push((va, va + PAGE)), + } + } + } /// 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))?; + let shown = *PAGES.lock().unwrap().at.get(&(va - off))?; Some(shown.map(|s| s.page.and_then(super::page_now).unwrap_or(s.pool) + off)) } + /// Physical page `page` was mapped, unmapped, moved or freed: the GPU-view pages that show + /// it read it elsewhere now (`take_changed`). + pub(super) fn page_moved(page: usize) { + let mut g = PAGES.lock().unwrap(); + let Some(vas) = g.by_page.get(&page) else { return }; + let vas: Vec = vas.iter().copied().collect(); + for va in vas { + g.note(va); + } + } + + /// The GPU-view ranges whose bytes are elsewhere since the last call (`d3d12x::title_textures` + /// reads the textures there again). + pub fn take_changed() -> Vec<(usize, usize)> { + std::mem::take(&mut PAGES.lock().unwrap().changed) + } + /// 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 @@ -317,7 +372,7 @@ pub mod mirrors { } None => out.unmapped += 1, } - pages.insert(va, to); + pages.set(va, to); } Some(out) } @@ -1227,6 +1282,7 @@ thread_local! { unsafe fn unmap_away(away: &mut Away, at: usize, committed: &std::ops::Range) -> bool { if let Some(page) = away.at.remove(&at) { away.page.remove(&page); + mirrors::page_moved(page); // never used where it was mapped: its home still holds the page (zeros) if lazy::unmark(at) { return false; @@ -1338,6 +1394,7 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: let away = g.get_or_insert_with(Away::default); for i in 0..n { let page = *arr.add(i); + mirrors::page_moved(page); if let Some(at) = away.page.remove(&page) { away.at.remove(&at); note_mapping_at(at); @@ -1441,6 +1498,10 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) 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 p != 0 { + // (read where it lands, by the GPU views that show it) + mirrors::page_moved(p); + } if unmap_away(away, at, &(0..0)) { (at_run, home_run) = Default::default(); }