diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ada439cbaa..574e1ad38d 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1582,6 +1582,180 @@ mod tests { } } + unsafe fn read_texture_subresource(dev: &ID3D12Device, queue: &ID3D12CommandQueue, r: &ID3D12Resource, sub: u32) -> Vec { + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + + let rd = r.GetDesc(); + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let (mut rows, mut row_bytes, mut total) = (0u32, 0u64, 0u64); + dev.GetCopyableFootprints(&rd, sub, 1, 0, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut total)); + let mut rb: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut rb, + ) + .unwrap(); + let rb = rb.unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().unwrap(); + own_work(|| { + super::super::vram::before_execute(queue); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + texture::wait(dev, queue).unwrap(); + }); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let slice_pitch = fp.Footprint.RowPitch as usize * rows as usize; + let mut out = Vec::with_capacity(fp.Footprint.Depth as usize * rows as usize * row_bytes as usize); + for z in 0..fp.Footprint.Depth as usize { + for y in 0..rows as usize { + out.extend_from_slice(std::slice::from_raw_parts((p as *const u8).add(z * slice_pitch + y * fp.Footprint.RowPitch as usize), row_bytes as usize)); + } + } + rb.Unmap(0, None); + out + } + + /// A title requesting an address from MapTitlePhysicalPages receives the page at home. + /// Retaining that target and mapping the page at a chosen address must also share the tile. + #[test] + fn render_target_at_physical_page_home_inherits_texels_after_move() { + use crate::gpu::recomp::runner::skip_test; + use crate::hle::kernelx; + use std::mem::ManuallyDrop; + 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}; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); + const SIDE: usize = 128; + unsafe { + let Ok(factory) = CreateDXGIFactory1::() else { return skip_test("no GPU") }; + let Ok(adapter) = factory.EnumAdapters1(0) else { return skip_test("no GPU") }; + let info = adapter.GetDesc1().unwrap(); + if info.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { + return skip_test("no GPU"); + } + println!("GPU: {}", String::from_utf16_lossy(&info.Description).trim_end_matches('\0')); + let mut dev: Option = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev else { return skip_test("no GPU") }; + 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() { + return skip_test("D3D12 options unavailable"); + } + if opts.ResourceHeapTier.0 < D3D12_RESOURCE_HEAP_TIER_2.0 { + return skip_test("resource heap tier < 2"); + } + if std::env::var_os("XCL_VRAM_ARENAS").is_some() { + return skip_test("XCL_VRAM_ARENAS selects the arena backend"); + } + if opts.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0 { + return skip_test("tiled tier < 2"); + } + if crate::gpu::uma::get().is_none() { + return skip_test("no UMA"); + } + + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let mut desc = console_desc(3, SIDE as u64, SIDE as u32, 1, 1, 28, 0x109); + desc[0x30..0x34].copy_from_slice(&1u32.to_le_bytes()); // ALLOW_RENDER_TARGET + let space = VirtualAlloc(std::ptr::null(), 3 << 20, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(space, 0); + let (mut count, mut pages) = (2usize, [0usize; 2]); + assert_eq!(kernelx::AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut count, pages.as_mut_ptr()), 1); + assert_eq!(count, pages.len()); + let place = |va: usize, page: &mut usize| -> ID3D12Resource { + let mapped = kernelx::MapTitlePhysicalPages(va as *mut c_void, 1, 0, 4, page) as usize; + assert_ne!(mapped, 0); + if va != 0 { + assert_eq!(mapped, va); + } + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let mut p = std::ptr::null_mut(); + let hr = super::super::device_x::create_placed_resource_x(dev.as_raw(), mapped as u64, desc.as_ptr(), D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), riid, &mut p); + assert!(hr >= 0 && !p.is_null(), "CreatePlacedResourceX: {hr:#x}"); + let target = ID3D12Resource::from_raw(p); + assert_eq!(target.GetDesc().Layout, D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, "expected a reserved target"); + target + }; + let a = place(0, &mut pages[0]); + let b = place(space + (1 << 20), &mut pages[0]); + let c = place(space + (2 << 20), &mut pages[1]); + + // Submit tile mappings, full-subresource initializations and alias hand-offs on + // one direct queue. Each write/hand-off is fenced; both aliases are in COMMON. + let write = |r: &ID3D12Resource, seed: u8| -> Vec { + let data: Vec = (0..SIDE * SIDE).flat_map(|i| [seed, (i % SIDE) as u8, (i / SIDE) as u8, 255]).collect(); + let sub = Subresource { rows: SIDE, row_bytes: SIDE * 4, depth: 1, data: data.clone() }; + own_work(|| { + super::super::vram::before_execute(&queue); + texture::upload(&dev, &queue, r, &[sub], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COMMON).unwrap(); + }); + data + }; + let switch = |before: &ID3D12Resource, after: &ID3D12Resource| { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let barrier = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::transmute_copy(before), + pResourceAfter: std::mem::transmute_copy(after), + }), + }, + }; + list.ResourceBarrier(&[barrier]); + list.Close().unwrap(); + own_work(|| { + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + texture::wait(&dev, &queue).unwrap(); + }); + }; + let check = |label: &str, r: &ID3D12Resource, expected: &[u8]| { + let actual = read_texture_subresource(&dev, &queue, r, 0); + assert_eq!(actual.len(), SIDE * SIDE * 4); + let matches = actual.chunks_exact(4).zip(expected.chunks_exact(4)).filter(|(a, e)| a == e).count(); + println!("{label}: {matches}/{} matching texels, first RGBA {:?}, expected {:?}", SIDE * SIDE, &actual[..4], &expected[..4]); + matches == SIDE * SIDE + }; + let canary = write(&c, 0x33); + write(&b, 0x44); // Deterministic stale data if B has private backing. + switch(&b, &a); + let from_a = write(&a, 0x11); + let a_write = check("A direct", &a, &from_a); + switch(&a, &b); + let a_to_b = check("A to B", &b, &from_a); + let from_b = write(&b, 0x22); + let b_write = check("B direct", &b, &from_b); + switch(&b, &a); + let b_to_a = check("B to A", &a, &from_b); + let independent = check("independent", &c, &canary); + + drop((a, b, c)); + for va in [space + (1 << 20), space + (2 << 20)] { + let mut empty = 0usize; + assert_eq!(kernelx::MapTitlePhysicalPages(va as *mut c_void, 1, 0, 4, &mut empty) as usize, va); + } + assert_eq!(kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + assert_ne!(VirtualFree(space as *mut c_void, 0, MEM_RELEASE), 0); + assert!(a_write && b_write && independent, "direct writes and the independent page must survive"); + assert!(a_to_b && b_to_a, "writes through either physical alias must be visible through the other"); + } + } + fn console_desc(dim: u32, w: u64, h: u32, array_or_depth: u16, mips: u16, format: u32, layout: u32) -> [u8; 0x38] { let mut d = [0u8; 0x38]; d[0..4].copy_from_slice(&dim.to_le_bytes()); @@ -1649,6 +1823,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 @@ -1658,7 +1916,6 @@ mod tests { let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); let _guard = TEST_LOCK.lock().unwrap(); use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; - use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; use windows::Win32::Graphics::Dxgi::*; unsafe { let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); @@ -1740,45 +1997,7 @@ mod tests { } } }; - let read_sub = |r: &ID3D12Resource, sub: u32| -> Vec { - let rd = r.GetDesc(); - let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); - let (mut rows, mut row_bytes, mut total) = (0u32, 0u64, 0u64); - dev.GetCopyableFootprints(&rd, sub, 1, 0, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut total)); - let mut rb: Option = None; - dev.CreateCommittedResource( - &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, - D3D12_HEAP_FLAG_NONE, - &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }, - D3D12_RESOURCE_STATE_COPY_DEST, - None, - &mut rb, - ) - .unwrap(); - let rb = rb.unwrap(); - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); - let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; - let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub } }; - list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); - list.Close().unwrap(); - own_work(|| { - super::super::vram::before_execute(&queue); - queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); - texture::wait(&dev, &queue).unwrap(); - }); - let mut p = std::ptr::null_mut(); - rb.Map(0, None, Some(&mut p)).unwrap(); - let slice_pitch = fp.Footprint.RowPitch as usize * rows as usize; - let mut out = Vec::with_capacity(fp.Footprint.Depth as usize * rows as usize * row_bytes as usize); - for z in 0..fp.Footprint.Depth as usize { - for y in 0..rows as usize { - out.extend_from_slice(std::slice::from_raw_parts((p as *const u8).add(z * slice_pitch + y * fp.Footprint.RowPitch as usize), row_bytes as usize)); - } - } - rb.Unmap(0, None); - out - }; + let read_sub = |r: &ID3D12Resource, sub: u32| read_texture_subresource(&dev, &queue, r, sub); // 1. Streaming 512 unreleased 1 MiB textures (512 MiB placed) across 16 MiB stays bounded // with zero additional page growth after the 16 MiB working set is covered. diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 740b69ef9f..0c4b3367e5 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 c0b8c236ac..d2db08da6f 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -797,7 +797,8 @@ const PHYS_PAGE: usize = 0x1_0000; pub const PHYS_PAGE_SIZE: usize = PHYS_PAGE; /// first page index → (pages in the block, pages still allocated, the block's home) -static PHYS_BLOCKS: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); +type PhysicalBlocks = std::collections::BTreeMap; +static PHYS_BLOCKS: std::sync::Mutex = std::sync::Mutex::new(std::collections::BTreeMap::new()); /// the next page index handed out (page numbers are not addresses: a block's home is in a /// sparse window, the coherent one, or – without room there – plain reserved memory) @@ -808,10 +809,23 @@ static NEXT_PAGE_INDEX: AtomicUsize = AtomicUsize::new(0); struct Away { at: std::collections::BTreeMap, page: std::collections::HashMap, + /// Homes explicitly mapped by the title. An away mapping takes precedence while a + /// page is elsewhere; freeing or explicitly unmapping a home removes its entry. + mapped_homes: std::collections::HashMap, /// 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, } + +impl Away { + fn mapped_away(&mut self, at: usize, page: usize) { + // A new mapping at the same address displaces a previously requested home. + self.mapped_homes.remove(&at); + self.at.insert(at, page); + self.page.insert(page, at); + } +} + static AWAY: std::sync::Mutex> = std::sync::Mutex::new(None); /// Whether a physical page is mapped at the page holding `va` away from its home – committed @@ -820,6 +834,17 @@ 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 mapped physical page at each of the `n` 64 KiB addresses from `va`, including homes +/// requested by the title. A GPU resource retains the page it had at placement across a move. +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| { + let at = va.checked_add(i.checked_mul(PHYS_PAGE)?)?; + a.at.get(&at).copied().or_else(|| a.mapped_homes.get(&at).copied().filter(|p| !a.page.contains_key(p))) + }).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); @@ -850,8 +875,12 @@ fn page_index(page: usize) -> Option { /// The home address of page `page` if it belongs to a live allocation. fn page_home(page: usize) -> Option { - let index = page_index(page)?; let blocks = PHYS_BLOCKS.lock().ok()?; + page_home_in(&blocks, page) +} + +fn page_home_in(blocks: &PhysicalBlocks, page: usize) -> Option { + let index = page_index(page)?; let (&first, &(count, live, home)) = blocks.range(..=index).next_back()?; (live > 0 && index < first.checked_add(count)?).then(|| home.checked_add((index - first).checked_mul(PHYS_PAGE)?)).flatten() } @@ -1119,8 +1148,7 @@ unsafe fn move_away(away: &mut Away, old: usize, at: usize, page: usize, in_uma: crate::hle::d3d12x::sparse::committed(at, PHYS_PAGE); } release_at(old); - away.at.insert(at, page); - away.page.insert(page, at); + away.mapped_away(at, page); Ok(true) } @@ -1167,7 +1195,8 @@ 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 mappings = AWAY.lock().unwrap(); + if let Some(away) = mappings.as_mut() { for i in 0..n { if let Some(at) = away.page.remove(&*arr.add(i)) { away.at.remove(&at); @@ -1175,7 +1204,17 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: } } } + // A mapper takes AWAY, then validates its pages under PHYS_BLOCKS. Acquire that + // lock before dropping AWAY so a free cannot leave a newly reinserted home identity. let mut g = PHYS_BLOCKS.lock().unwrap(); + if let Some(away) = mappings.as_mut().filter(|a| !a.mapped_homes.is_empty()) { + for i in 0..n { + if let Some(home) = page_home_in(&g, *arr.add(i)) { + away.mapped_homes.remove(&home); + } + } + } + drop(mappings); for i in 0..n { let Some(page) = page_index(*arr.add(i)) else { continue }; // the block holding this page @@ -1239,6 +1278,14 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) unmap_away(away, at, &(home..home + n * PHYS_PAGE)); } } + for (i, &p) in pages.iter().enumerate() { + let at = home + i * PHYS_PAGE; + // Another physical page can still occupy this home. Follow the existing away + // mapping; remembering p here would resurrect it when that occupant moves on. + if !away.at.contains_key(&at) { + away.mapped_homes.insert(at, p); + } + } return home as *mut c_void; } let base = va as usize; @@ -1259,6 +1306,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) (at_run, home_run) = Default::default(); } if p == 0 { + away.mapped_homes.remove(&at); continue; } if let Some(&old) = away.page.get(&p) { @@ -1284,8 +1332,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) let plain = crate::gpu::uma::get().is_none_or(|u| !u.contains(at)); if fresh && plain && !committed_page_in(home, &mut home_run) { lazy::mark(at); - away.at.insert(at, p); - away.page.insert(p, at); + away.mapped_away(at, p); continue; } if !in_uma(at) && mem::VirtualAlloc(at as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { @@ -1303,8 +1350,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { crate::hle::d3d12x::sparse::committed(at, PHYS_PAGE); } - away.at.insert(at, p); - away.page.insert(p, at); + away.mapped_away(at, p); } va } @@ -2246,6 +2292,54 @@ mod tests { } } + /// The GPU asks which physical pages were explicitly mapped at each address. + /// Moving, unmapping and freeing part of an allocation must update that lookup. + #[test] + fn mapped_home_page_identity_follows_moves_and_partial_frees() { + unsafe { + if crate::gpu::uma::get().is_none() { + return crate::gpu::recomp::runner::skip_test("no UMA"); + } + let mut count = 2; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut count, pages.as_mut_ptr()), 1); + let home = page_home(pages[0]).unwrap(); + assert_eq!(physical_pages(home, 2), vec![None, None], "allocation alone does not map its home"); + assert_eq!(MapTitlePhysicalPages(std::ptr::null_mut(), 2, 0, 4, pages.as_mut_ptr()) as usize, home); + assert_eq!(physical_pages(home, 2), vec![Some(pages[0]), Some(pages[1])]); + let elsewhere = mem::VirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE); + assert!(!elsewhere.is_null()); + assert_eq!(MapTitlePhysicalPages(elsewhere, 1, 0, 4, pages.as_mut_ptr()), elsewhere); + assert_eq!(physical_pages(home, 2), vec![None, Some(pages[1])]); + assert_eq!(physical_pages(elsewhere as usize, 1), vec![Some(pages[0])]); + let mut nonconsecutive = [pages[1], pages[0]]; + assert!(MapTitlePhysicalPages(std::ptr::null_mut(), 2, 0, 4, nonconsecutive.as_mut_ptr()).is_null()); + assert_eq!(physical_pages(elsewhere as usize, 1), vec![Some(pages[0])]); + assert_eq!(physical_pages(home, 2), vec![None, Some(pages[1])]); + assert_eq!(MapTitlePhysicalPages(home as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, home); + assert_eq!(physical_pages(elsewhere as usize, 1), vec![None]); + assert_eq!(physical_pages(home, 2), vec![Some(pages[0]), Some(pages[1])]); + // Page 1 goes over page 0's former home and then moves onward. + let first = home as *mut c_void; + assert_eq!(MapTitlePhysicalPages(first, 1, 0, 4, pages.as_mut_ptr().add(1)), first); + assert_eq!(physical_pages(home, 2), vec![Some(pages[1]), None]); + // Requesting the first page at home while the second still occupies it does + // not evict that occupant in kernelx. Do not cache a conflicting GPU identity. + assert_eq!(MapTitlePhysicalPages(first, 1, 0, 4, pages.as_mut_ptr()), first); + assert_eq!(physical_pages(home, 2), vec![Some(pages[1]), None]); + assert_eq!(MapTitlePhysicalPages(elsewhere, 1, 0, 4, pages.as_mut_ptr().add(1)), elsewhere); + assert_eq!(physical_pages(home, 2), vec![None, None]); + assert_eq!(MapTitlePhysicalPages(std::ptr::null_mut(), 2, 0, 4, pages.as_mut_ptr()) as usize, home); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, pages.as_mut_ptr()), 1); + assert_eq!(physical_pages(home, 2), vec![None, Some(pages[1])]); + let second = (home + PHYS_PAGE) as *mut c_void; + assert_eq!(MapTitlePhysicalPages(second, 1, 0, 4, std::ptr::null_mut()), second); + assert_eq!(physical_pages(home, 2), vec![None, None]); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, pages.as_mut_ptr().add(1)), 1); + assert_ne!(mem::VirtualFree(elsewhere, 0, mem::MEM_RELEASE), 0); + } + } + /// A page mapped away from a home in a sparse window is committed once: the home gives its /// memory back while the page is away and has the page's contents again when it returns. #[test] @@ -2568,7 +2662,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());