From 9b1b4aa29e9c29feb8d7fa8988fadbe7518cb833 Mon Sep 17 00:00:00 2001 From: Jesse Date: Mon, 23 Nov 2026 23:53:21 +0200 Subject: [PATCH 1/2] KernelX: GPU-visible title memory outside the windows is write-watched (retail menu text complete) A retail game reserves 24 GB of 64 KiB pages (VirtualAlloc flags 0x20402000) and commits 2.2 GB of large pages with a graphics protection (flags 0x20003000, protection 0x2404). Neither fits a sparse or the coherent window, so both fell through to plain memory without MEM_WRITE_WATCH. Textures the title places there are kept in step with the memory (d3d12x::title_textures), which relies on GetWriteWatch to see CPU writes: they were uploaded once, empty, and never again (128+ textures in the first 45 s). One of them is the game's 2048x2048 A8_UNORM glyph atlas, which the CPU fills as text is laid out. Its GPU copy stayed zero, so every glyph drawn from it (the x-height letters: a c e m n o r s u v w x z) was missing from the menus; letters drawn by the vector path (ascenders, descenders, capitals) were fine. Found by a GPU readback of the atlas (zero) against its CPU view (glyphs) while the menu was on screen. The fallback VirtualAlloc now adds MEM_WRITE_WATCH for GPU-visible reservations (MEM_GRAPHICS, MEM_LARGE_PAGES / MEM_64K_PAGES, or a PAGE_GRAPHICS_* protection) and records them with the graphics reservations, whose ranges title_textures watches. Test: gpu_visible_fallback_memory_is_write_watched. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/kernelx.rs | 49 +++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 0b8f2a3fa..920bdad2e 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -260,6 +260,21 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: } } } + // GPU-visible title memory the windows above had no room for (a retail game: a 24 GB + // reservation of 64 KiB pages, 2.2 GB of large pages with a graphics protection) is plain + // memory here. Textures the title places in it are kept in step with it + // (`d3d12x::title_textures`), which needs its CPU writes to be seen: it is write-watched + // like a graphics reservation. Without that such a texture was uploaded once, empty, and + // never again (the game's glyph atlas: its menus lost their x-height letters). + if addr.is_null() && t & 0x2000 != 0 && (t & (MEM_GRAPHICS | 0x2000_0000) != 0 || p & PAGE_GRAPHICS_ANY != 0) { + let q = mem::VirtualAlloc(addr, size, sanitize_alloc_type(t) | MEM_WRITE_WATCH, sanitize_protect(p)); + if !q.is_null() { + GRAPHICS_RESERVATIONS.lock().unwrap().insert(q as usize, size); + GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + trace_mem("VirtualAlloc (GPU-visible, write-watched)", addr as usize, size, t as u64, p, q as usize); + return q; + } + } let q = mem::VirtualAlloc(addr, size, sanitize_alloc_type(t), sanitize_protect(p)); trace_mem("VirtualAlloc", addr as usize, size, t as u64, p, q as usize); q @@ -2002,6 +2017,40 @@ mod tests { } } + /// GPU-visible title memory that falls back to plain memory (64 KiB pages, large pages, a + /// graphics protection) is write-watched: a texture placed there sees the CPU's writes. + #[test] + fn gpu_visible_fallback_memory_is_write_watched() { + unsafe { + // (MEM_64K_PAGES | MEM_RESERVE; MEM_LARGE_PAGES | MEM_RESERVE | MEM_COMMIT with a + // PAGE_GRAPHICS_* protection; MEM_GRAPHICS | MEM_RESERVE | MEM_COMMIT) + for (t, p) in [(0x2040_2000u32, mem::PAGE_READWRITE), (0x2000_3000, 0x2404), (MEM_GRAPHICS | 0x3000, mem::PAGE_READWRITE)] { + let size = 0x40_0000; + let q = VirtualAlloc(std::ptr::null(), size, t, p); + assert!(!q.is_null(), "flags {t:#x}"); + let a = q as usize; + if crate::gpu::uma::get().is_some_and(|u| u.contains(a) || u.is_sparse(a)) { + // a window had room: write-watched there (`uma::watch_regions`) + VirtualFree(q, 0, mem::MEM_RELEASE); + continue; + } + assert!(in_graphics_reservation(a), "flags {t:#x}: a fallback allocation is watched"); + if t & 0x1000 == 0 { + assert!(!VirtualAlloc((a + 0x2_0000) as *const c_void, 0x1_0000, 0x1000, mem::PAGE_READWRITE).is_null()); + } + let mut buf = [std::ptr::null_mut::(); 16]; + let (mut n, mut gran) = (buf.len(), 0u32); + assert_eq!(mem::GetWriteWatch(1, q, size, buf.as_mut_ptr(), &mut n, &mut gran), 0); + ((a + 0x2_1234) as *mut u8).write_volatile(7); + n = buf.len(); + assert_eq!(mem::GetWriteWatch(1, q, size, buf.as_mut_ptr(), &mut n, &mut gran), 0); + assert_eq!(&buf[..n], &[(a + 0x2_1000) as *mut c_void], "flags {t:#x}: the written page is reported"); + assert_eq!(VirtualFree(q, 0, mem::MEM_RELEASE), 1); + assert!(!in_graphics_reservation(a)); + } + } + } + #[test] fn virtual_free_ex_and_sparse_validation() { unsafe { From b8537b20f6a3c3cb042538d4df015a54abaed958 Mon Sep 17 00:00:00 2001 From: Robin Snyders Date: Tue, 24 Nov 2026 00:19:57 +0100 Subject: [PATCH 2/2] kernelx: textures in a GPU view read what is mapped in its CPU view A retail game reserves 24 GB of GPU-visible memory read-write and, right after it, 24 GB more with a graphics protection (0x801): the same memory as the GPU sees it. It maps its physical pages into the first reservation only and places the textures the CPU fills at the same offset in the second. Its movie frames are decoded on the CPU into the first; the R8 plane textures the movie shader samples are at +0x600000000 in the second. Here the second reservation is memory of its own that nothing is ever mapped into, so those textures were kept in step with reserved memory: zeros, and a YUV frame of zeros is a green screen. The game's first movie was green. A graphics-protected reservation made right after one of the same size without a graphics protection is now recorded as that one's GPU view (XCL_GPU_VIEWS=0 turns it off). title_textures reads the pages of a GPU view that hold nothing from its CPU view, watches the CPU view's pages of such textures, and uploads them again when those pages are written. Stacked on #252, which makes those reservations write-watched. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SKtJseucqXR6iuAE6HBtiA --- crates/xcl/src/hle/d3d12x/title_textures.rs | 44 ++++++++++- crates/xcl/src/hle/kernelx.rs | 88 +++++++++++++++++++++ 2 files changed, 129 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 2d8194e75..1046467ed 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -70,7 +70,7 @@ static REFRESH: Mutex<()> = Mutex::new(()); static TEXTURES_GEN: AtomicU64 = AtomicU64::new(0); static TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// cached `watch_ranges` keyed by `(sparse::mapped_gen, TEXTURES_GEN, graphics_reservations_gen)` -static WATCH_CACHE: Mutex>)>> = Mutex::new(None); +static WATCH_CACHE: Mutex>)>> = Mutex::new(None); /// the queue uploads go to, per device static QUEUES: Mutex> = Mutex::new(BTreeMap::new()); static UPLOADS: AtomicU64 = AtomicU64::new(0); @@ -272,6 +272,7 @@ fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc> { super::sparse::mapped_gen(), TEXTURES_GEN.load(Ordering::Acquire), crate::hle::kernelx::graphics_reservations_gen(), + crate::hle::kernelx::gpu_views_gen() as u64, ); { let g = WATCH_CACHE.lock().unwrap(); @@ -287,6 +288,9 @@ fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc> { regions.extend(crate::hle::kernelx::graphics_reservations()); let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().values().map(|e| (e.va & !0xFFF, (e.va + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect(); wanted.extend(super::sparse::mapped_ranges()); + // textures in a GPU view: what the CPU writes is in the CPU view (`kernelx::gpu_view_pages`) + let cpu_views: Vec<(usize, usize)> = TEXTURES.lock().unwrap().values().flat_map(|e| crate::hle::kernelx::gpu_view_pages(e.va, e.va + e.tex.size() as usize)).map(|(_, cpu)| (cpu, cpu + 0x1_0000)).collect(); + wanted.extend(cpu_views); let computed = Arc::new(watch_ranges(®ions, wanted)); *WATCH_CACHE.lock().unwrap() = Some((key, Arc::clone(&computed))); computed @@ -403,8 +407,12 @@ 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.va); - dirty.get(i).is_some_and(|&p| p < e.va + e.tex.size() as usize) + let written = |lo: usize, hi: usize| { + let i = dirty.partition_point(|&p| p + page as usize <= lo); + dirty.get(i).is_some_and(|&p| p < hi) + }; + let end = e.va + e.tex.size() as usize; + written(e.va, end) || crate::hle::kernelx::gpu_view_pages(e.va, end).iter().any(|&(_, cpu)| written(cpu, cpu + 0x1_0000)) }) .filter_map(|(&res, e)| { if e.pending { @@ -638,6 +646,15 @@ unsafe fn read_committed(at: usize, len: usize) -> Vec { let readable = m.State == MEM_COMMIT && m.Protect & 0xEE != 0 && m.Protect & 0x100 == 0; // R / RW / WC / X-R…, no guard if readable { std::ptr::copy_nonoverlapping(p as *const u8, out.as_mut_ptr().add(p - at), end - p); + } else { + // a GPU view, nothing mapped into it: what its CPU view holds (`kernelx::gpu_view_pages`) + for (g, cpu) in crate::hle::kernelx::gpu_view_pages(p, end) { + let (lo, hi) = (g.max(p), (g + 0x1_0000).min(end)); + let src = cpu + (lo - g); + if lo < hi && crate::gpu::shader::readable(src, hi - lo) { + std::ptr::copy_nonoverlapping(src as *const u8, out.as_mut_ptr().add(lo - at), hi - lo); + } + } } p = end; } @@ -668,6 +685,27 @@ unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { mod tests { use super::*; + /// A texture in a GPU view that nothing is mapped into reads what its CPU view holds. + #[test] + fn a_gpu_view_reads_its_cpu_view() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + unsafe { + let cpu = VirtualAlloc(std::ptr::null(), 0x4_0000, MEM_RESERVE, PAGE_READWRITE) as usize; + let gpu = VirtualAlloc(std::ptr::null(), 0x4_0000, MEM_RESERVE, PAGE_READWRITE) as usize; + assert!(cpu != 0 && gpu != 0); + assert!(!VirtualAlloc((cpu + 0x1_0000) as *const c_void, 0x1_0000, MEM_COMMIT, PAGE_READWRITE).is_null()); + let texels: Vec = (0..64u8).collect(); + std::ptr::copy_nonoverlapping(texels.as_ptr(), (cpu + 0x1_FFE0) as *mut u8, 32); + crate::hle::kernelx::add_gpu_view(gpu, 0x4_0000, cpu); + // 32 bytes at the end of the committed page, 32 past it (not committed: zeros) + let got = read_committed(gpu + 0x1_FFE0, 64); + assert_eq!(&got[..32], &texels[..32]); + assert!(got[32..].iter().all(|&b| b == 0)); + VirtualFree(cpu as *mut c_void, 0, MEM_RELEASE); + VirtualFree(gpu as *mut c_void, 0, MEM_RELEASE); + } + } + const SRV: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATES(D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE.0); const ALL: u32 = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 920bdad2e..9d4fac2d5 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -156,6 +156,67 @@ pub fn in_graphics_reservation(p: usize) -> bool { const MEM_WRITE_WATCH: u32 = 0x20_0000; +/// GPU views of title memory: (GPU view, size, CPU view). A retail game reserves 24 GB of +/// GPU-visible memory read-write and, right after it, 24 GB more with a graphics protection +/// (0x801): the same memory as the GPU sees it. It maps its physical pages into the first only and +/// places textures the CPU fills at the same offset in the second (its movie frames: the decoder +/// writes the first, the textures are in the second). Here the second is memory of its own that +/// nothing is mapped into, so those textures read zeros (a green movie). What is read of a GPU +/// view for the GPU comes from its CPU view instead (`gpu_view_pages`, `d3d12x::title_textures`). +static GPU_VIEWS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +static GPU_VIEWS_GEN: AtomicUsize = AtomicUsize::new(0); +/// the last reservation of GPU-visible memory, and whether it had a graphics protection +static LAST_GPU_VISIBLE: std::sync::Mutex> = std::sync::Mutex::new(None); + +/// A reservation of GPU-visible memory (`base`, `size` bytes, allocation type `t`, protection +/// `p`) after `last`: the view it is the GPU view of – one with a graphics protection right after +/// one of the same size without – as (GPU view, size, CPU view). +fn pair_gpu_view(last: &mut Option<(usize, usize, bool)>, base: usize, size: usize, t: u32, p: u32) -> Option<(usize, usize, usize)> { + if t & 0x1000 != 0 { + return None; // committed at once: not a view to map pages into + } + let graphics = p & PAGE_GRAPHICS_ANY != 0; + let before = last.replace((base, size, graphics)); + match before { + Some((cpu, n, false)) if graphics && n == size => Some((base, size, cpu)), + _ => None, + } +} + +fn note_gpu_view(base: usize, size: usize, t: u32, p: u32) { + let view = pair_gpu_view(&mut LAST_GPU_VISIBLE.lock().unwrap(), base, size, t, p); + if let Some((gpu, size, cpu)) = view.filter(|_| std::env::var("XCL_GPU_VIEWS").map_or(true, |v| v != "0")) { + add_gpu_view(gpu, size, cpu); + crate::xlog_info!("kernelx: {gpu:#x} ({size:#x} bytes, protection {p:#x}) is the GPU view of {cpu:#x}: textures placed there read what is mapped at {cpu:#x}"); + } +} + +pub(crate) fn add_gpu_view(gpu: usize, size: usize, cpu: usize) { + GPU_VIEWS.lock().unwrap().push((gpu, size, cpu)); + GPU_VIEWS_GEN.fetch_add(1, Ordering::AcqRel); +} + +/// Changes when a GPU view is added. +pub fn gpu_views_gen() -> usize { + GPU_VIEWS_GEN.load(Ordering::Acquire) +} + +/// The 64 KiB pages of `[lo, hi)` that lie in a GPU view, with the address of the CPU view each +/// shows: (GPU view page, CPU view page). +pub fn gpu_view_pages(lo: usize, hi: usize) -> Vec<(usize, usize)> { + if hi <= lo { + return Vec::new(); + } + let views = GPU_VIEWS.lock().unwrap(); + let lo = lo & !(PHYS_PAGE - 1); + let mut out = Vec::new(); + for &(gpu, size, cpu) in views.iter() { + let (a, b) = (lo.max(gpu), hi.min(gpu + size)); + out.extend((a..b).step_by(PHYS_PAGE).map(|g| (g, cpu + (g - gpu)))); + } + out +} + /// Graphics memory (MEM_GRAPHICS, committed, no fixed address) comes from the unified /// memory region the GPU uses directly (`gpu::uma`); a graphics reservation (no commit) is /// write-watched address space of Windows; everything else from Windows. @@ -272,6 +333,7 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: GRAPHICS_RESERVATIONS.lock().unwrap().insert(q as usize, size); GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); trace_mem("VirtualAlloc (GPU-visible, write-watched)", addr as usize, size, t as u64, p, q as usize); + note_gpu_view(q as usize, size, t, p); return q; } } @@ -1636,6 +1698,32 @@ pub unsafe extern "system" fn DisableThreadLibraryCalls(h: usize) -> BOOL { mod tests { use super::*; + /// A reservation with a graphics protection right after one of the same size without is + /// that one's GPU view; other sequences are not views. + #[test] + fn a_graphics_reservation_after_a_plain_one_of_its_size_is_its_gpu_view() { + const G: u32 = 0x2040_2000; // reserve, 64 KiB pages, graphics + let mut last = None; + assert_eq!(pair_gpu_view(&mut last, 0x1000_0000, 0x60_0000, G, 0x4), None); + assert_eq!(pair_gpu_view(&mut last, 0x2000_0000, 0x60_0000, G, 0x801), Some((0x2000_0000, 0x60_0000, 0x1000_0000))); + // a different size, two graphics ones in a row, a committed one: no view + assert_eq!(pair_gpu_view(&mut last, 0x3000_0000, 0x10_0000, G, 0x4), None); + assert_eq!(pair_gpu_view(&mut last, 0x4000_0000, 0x20_0000, G, 0x801), None); + assert_eq!(pair_gpu_view(&mut last, 0x5000_0000, 0x20_0000, G, 0x801), None); + assert_eq!(pair_gpu_view(&mut last, 0x6000_0000, 0x20_0000, G, 0x4), None); + assert_eq!(pair_gpu_view(&mut last, 0x7000_0000, 0x20_0000, G | 0x1000, 0x801), None); + } + + /// The pages of a range in a GPU view, with the CPU view's address of each. + #[test] + fn gpu_view_pages_name_the_cpu_view_of_each_page() { + let (gpu, cpu) = (0x7A00_0000_0000usize, 0x7900_0000_0000usize); + add_gpu_view(gpu, 0x40_0000, cpu); + assert_eq!(gpu_view_pages(gpu + 0x1_8000, gpu + 0x3_0000), vec![(gpu + 0x1_0000, cpu + 0x1_0000), (gpu + 0x2_0000, cpu + 0x2_0000)]); + assert!(gpu_view_pages(gpu - 0x2_0000, gpu).is_empty()); + assert_eq!(gpu_view_pages(gpu + 0x3F_0000, gpu + 0x50_0000), vec![(gpu + 0x3F_0000, cpu + 0x3F_0000)]); + } + #[test] fn affinity_masks_outside_the_process_are_fitted() { // a mask from the PC's processors is the title's choice