From 5fa695050a0ccaa82298e45799224422f5e2781e Mon Sep 17 00:00:00 2001 From: 3L1A5-1 <276908492+3L1A5-1@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:35:57 +0100 Subject: [PATCH] D3D12.X: render targets on one physical page share its video memory A retail game maps one physical page under render targets at two addresses at once (aliasing targets that are never live together, as the console allows). kernelx keeps a page at one address (`map_pages` moves it), and `vram::Pages` keyed its video memory by title address, so each alias got pages of its own: in its first 40 s the game placed 422 targets (2.1 GB) whose pages it then mapped under 276 others (1.85 GB), and kept using both sets (barriers, views). The duplicate cost 1.85 GB of video memory, and what the GPU wrote through one alias never showed in the other. A GPU-owned texture's owned pages are now keyed by the physical page mapped at their address (`kernelx::physical_pages`, asked before `PAGES` is taken), else by the address as before. Sampled textures keep address keys. Measured on GTA VI, RTX 2060 SUPER 8 GB, 90 s at the menus, 3 runs each: target pages 3597 -> 1738 MB, local video memory 6652 -> 4796 MB. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/title_textures.rs | 84 +++++++++++++++++++++ crates/xcl/src/hle/d3d12x/vram.rs | 66 +++++++++++++--- crates/xcl/src/hle/kernelx.rs | 10 +++ 3 files changed, 149 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ada439cba..fdfc65fa6 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1649,6 +1649,90 @@ mod tests { assert!(!tbl.by_res.contains_key(&10) && !tbl.by_res.contains_key(&11) && tbl.by_res.contains_key(&12)); } + /// Real GPU: render targets at two addresses of one physical page (mapped at the second after + /// the first, as a retail game aliases its targets) share one page of video memory, as on the + /// console; a target on another physical page gets its own. + #[test] + fn render_targets_on_one_physical_page_share_its_video_memory() { + // (a test that panicked holding these locks does not fail this one too) + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use crate::hle::kernelx; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + const NAME: &str = "render_targets_on_one_physical_page_share_its_video_memory"; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let Ok(adapter) = factory.EnumAdapters1(0) else { return println!("SKIPPED {NAME}: no adapter") }; + if adapter.GetDesc1().is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) { + return println!("SKIPPED {NAME}: software adapter"); + } + let mut dev: Option = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev else { return println!("SKIPPED {NAME}: no D3D12 device") }; + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + if dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut opts as *mut _ as *mut c_void, std::mem::size_of_val(&opts) as u32).is_err() + || opts.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0 + { + return println!("SKIPPED {NAME}: tiled tier < 2"); + } + // (`vram::place` keeps no render target on pages below resource heap tier 2) + if opts.ResourceHeapTier.0 < 2 { + return println!("SKIPPED {NAME}: resource heap tier < 2"); + } + if crate::gpu::uma::get().is_none() { + return println!("SKIPPED {NAME}: no UMA"); + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + // a 128x128 R8G8B8A8 render target: one 64 KiB page on the console and on the PC + let mut rt = console_desc(3, 128, 128, 1, 1, 28, 0x109); + rt[0x30..0x34].copy_from_slice(&1u32.to_le_bytes()); + let place = |va: usize| -> ID3D12Resource { + let mut p = std::ptr::null_mut(); + let hr = super::super::device_x::create_placed_resource_x(dev.as_raw(), va as u64, rt.as_ptr(), D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32, std::ptr::null(), riid, &mut p); + assert!(hr >= 0 && !p.is_null(), "CreatePlacedResourceX at {va:#x}: {hr:#x}"); + assert!(super::super::vram::is_placed_texture(p as usize), "expected a vram::Pages target at {va:#x}"); + ID3D12Resource::from_raw(p) + }; + let dev_pages = || super::super::vram::page_bytes_for(dev.as_raw() as usize).0; + let lost = || super::super::vram::tiles_unaccounted_for(dev.as_raw() as usize); + let space = VirtualAlloc(std::ptr::null(), 4 << 20, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(space, 0); + let (a, b, c, d) = (space, space + (1 << 20), space + (2 << 20), space + (3 << 20)); + let (mut n, mut pages) = (3usize, [0usize; 3]); + assert_eq!(kernelx::AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let (before, lost_before) = (dev_pages(), lost()); + assert_eq!(kernelx::MapTitlePhysicalPages(a as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, a); + let first = place(a); + // the same page at a second address: the console's alias of `a` + assert_eq!(kernelx::MapTitlePhysicalPages(b as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, b); + let second = place(b); + let shared = dev_pages() - before; + // another physical page: video memory of its own + assert_eq!(kernelx::MapTitlePhysicalPages(c as *mut c_void, 1, 0, 4, pages.as_mut_ptr().add(1)) as usize, c); + let third = place(c); + let all = dev_pages() - before; + // a target at `d` with no page mapped (keyed by its address), then a page mapped there + // and a second target: its page is keyed by the physical page, which has none yet + let fourth = place(d); + assert_eq!(kernelx::MapTitlePhysicalPages(d as *mut c_void, 1, 0, 4, pages.as_mut_ptr().add(2)) as usize, d); + let fifth = place(d); + let lost_after = lost(); + drop((first, second, third, fourth, fifth)); + let mut none = [0usize; 1]; + kernelx::MapTitlePhysicalPages(b as *mut c_void, 1, 0, 4, none.as_mut_ptr()); + kernelx::MapTitlePhysicalPages(c as *mut c_void, 1, 0, 4, none.as_mut_ptr()); + kernelx::MapTitlePhysicalPages(d as *mut c_void, 1, 0, 4, none.as_mut_ptr()); + kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), 3, pages.as_mut_ptr()); + VirtualFree(space as *mut c_void, 0, MEM_RELEASE); + assert_eq!(shared, 0x1_0000, "two targets on one physical page: one page of video memory"); + assert_eq!(all, 0x2_0000, "a target on another physical page: a page of its own"); + assert_eq!(lost_after, lost_before, "every pool tile taken is a page's"); + } + } + /// Real GPU (#248): placed title textures share `vram::Pages` so streaming unreleased /// overlapping placements stays bounded in video memory, superseded textures never corrupt /// newer placements on shared tiles, 4 KiB-aligned neighbours never false-alias, and mip diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 740b69ef9..0c4b3367e 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -218,6 +218,8 @@ struct Target { mapped: bool, used: Vec, used_extra: Vec<(usize, usize)>, + /// placed as GPU-owned: its pages are keyed by the physical page under them (`page_key`) + gpu_owned: bool, } /// Per-heap free-tile allocator for `Pages`. @@ -552,8 +554,9 @@ impl Pages { } } - /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue. - unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>)> { + /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue + /// (`phys[i]`: the title's physical page at owned page i, if any – see `page_key`). + unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32, phys: &[Option]) -> Option<(Vec, Vec<(usize, usize)>)> { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); self.sweep(now); @@ -562,7 +565,7 @@ impl Pages { let mut preferred: Option = None; for i in 0..total as usize { let existing = if i < own { - self.pages.get(&(first + i * PAGE)).map(|p| p.tile.0) + self.pages.get(&page_key(first + i * PAGE, phys.get(i).copied().flatten())).map(|p| p.tile.0) } else { self.extra_pages.get(&(va, i)).map(|p| p.tile.0) }; @@ -587,7 +590,7 @@ impl Pages { let mut used_extra = Vec::new(); for i in 0..total as usize { let tile = if i < own { - let a = first + i * PAGE; + let a = page_key(first + i * PAGE, phys.get(i).copied().flatten()); let t = match self.pages.get_mut(&a) { Some(p) => { p.users += 1; @@ -694,6 +697,30 @@ unsafe fn reservable(dev: &ID3D12Device, desc: &D3D12_RESOURCE_DESC) -> bool { can_reserve(f.Support2.0, samples, m.NumQualityLevels) } +/// Keys of `Pages::pages` for the title's physical pages (title addresses never have bit 63). +const PHYS_KEY: usize = 1 << 63; + +/// The key of the page of video memory for title page address `a`: the physical page mapped +/// there (`phys`), else the address. A retail game maps one physical page under render targets +/// at two addresses (aliasing, as on the console): keyed by address, each got video memory of +/// its own (1.85 GB more in its first 40 s) and what the GPU wrote through one never showed in +/// the other. +fn page_key(a: usize, phys: Option) -> usize { + phys.map_or(a, |p| PHYS_KEY | p) +} + +/// The physical pages under a GPU-owned texture's owned pages (`require_aligned`), asked before +/// `PAGES` is taken; empty for others (keyed by address) and without the console size. +fn physical_pages_under(va: usize, console_bytes: Option, require_aligned: bool) -> Vec> { + if !require_aligned { + return Vec::new(); + } + match console_bytes.and_then(|b| owned_pages(va, Some(b), usize::MAX)) { + Some((first, n)) if n > 0 => crate::hle::kernelx::physical_pages(first, n), + _ => Vec::new(), + } +} + /// A texture at `va` as a reserved resource on the title's shared 64 KiB pages /// (`console_bytes`: its size on the console; tiles past the owned page boundaries are shared by /// `(va, tile_index)` so repeated placements at the same address do not leak). None: it cannot be. @@ -716,6 +743,7 @@ unsafe fn place_on_pages( if (require_aligned || console_bytes.is_none()) && va % PAGE != 0 { return None; } + let phys = physical_pages_under(va, console_bytes, require_aligned); // reserved textures have the PC's 64 KiB tiles let tiled = D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, ..*desc }; static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -748,8 +776,8 @@ unsafe fn place_on_pages( let bound = { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { - if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra }); + if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total, &phys) { + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, gpu_owned: require_aligned }); true } else { false @@ -796,15 +824,23 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { } let Some(dev) = dev else { return false }; let key = res.as_raw() as usize; - let mut g = PAGES.lock().unwrap(); - let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return false }; - let Some((va, console_bytes, total, mapped)) = pages.targets.get(&key).map(|t| (t.va, t.console_bytes, t.total, t.mapped)) else { - return false; + let target = |g: &mut std::sync::MutexGuard<'_, std::collections::BTreeMap>>| { + let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return None }; + pages.targets.get(&key).map(|t| (t.va, t.console_bytes, t.total, t.mapped, t.gpu_owned)) }; + // (the physical pages are asked without `PAGES` held) + let Some((va, console_bytes, _, mapped, gpu_owned)) = target(&mut PAGES.lock().unwrap()) else { return false }; if mapped { return true; } - let Some((used, used_extra)) = pages.bind(&dev, res, va, console_bytes, total) else { + let phys = physical_pages_under(va, console_bytes, gpu_owned); + let mut g = PAGES.lock().unwrap(); + let Some((va, console_bytes, total, mapped, _)) = target(&mut g) else { return false }; + if mapped { + return true; + } + let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return false }; + let Some((used, used_extra)) = pages.bind(&dev, res, va, console_bytes, total, &phys) else { return false; }; if let Some(t) = pages.targets.get_mut(&key) { @@ -854,6 +890,14 @@ pub(super) fn page_bytes_for(device: usize) -> (usize, usize) { ((p.pages.len() + p.extra_pages.len()) * PAGE, p.pools.len() * POOL_PAGES as usize * PAGE) } +/// Pool tiles of `device` that are neither free, cooling, nor any page's (taken and lost). +#[cfg(test)] +pub(super) fn tiles_unaccounted_for(device: usize) -> usize { + let g = PAGES.lock().unwrap(); + let Some(Some(p)) = g.get(&device) else { return 0 }; + (p.pools.len() * POOL_PAGES as usize).saturating_sub(p.pool.free_total + p.pool.cooling.len() + p.pages.len() + p.extra_pages.len()) +} + /// (bytes of pages in use by tiled textures, bytes of pool heaps) – `XCL_ACTIVITY` pub fn page_bytes() -> (usize, usize) { let g = PAGES.lock().unwrap(); diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index c0b8c236a..ef27065b4 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -820,6 +820,16 @@ pub fn physical_page_at(va: usize) -> bool { AWAY.lock().unwrap().as_ref().is_some_and(|a| a.at.contains_key(&(va & !(PHYS_PAGE - 1)))) } +/// The physical page mapped away from home at each of the `n` 64 KiB pages from `va` (None: none +/// there, or a page at its home). The console maps one page at several addresses at once; here it +/// is at one (`map_pages` moves it), so `d3d12x::vram` asks which page an address had to let +/// textures at two addresses of one page share its video memory. +pub fn physical_pages(va: usize, n: usize) -> Vec> { + let g = AWAY.lock().unwrap(); + let Some(a) = g.as_ref() else { return vec![None; n] }; + (0..n).map(|i| va.checked_add(i * PHYS_PAGE).and_then(|at| a.at.get(&at).copied())).collect() +} + /// Counts the calls that map or unmap physical pages in a GPU view (`mirrors`): what /// `physical_page_at` says there may have changed. static GPU_VIEW_MAP_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);