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 0b8f2a3fa..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. @@ -260,6 +321,22 @@ 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); + note_gpu_view(q as usize, size, t, p); + 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 @@ -1621,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 @@ -2002,6 +2105,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 {