From 1a38d2c6f25b5d5d05f2cee6efd4e5cd9104c8ac Mon Sep 17 00:00:00 2001 From: Pipodi Date: Sun, 29 Nov 2026 00:55:05 +0100 Subject: [PATCH 1/2] D3D12.X: XCL_PAIR_PAGES=1 caps a texture in a live one's memory to its pages A title can place two descriptions at one address: a 1280x720 R32_UINT UAV and a 1280x720 R9G9B9E5 SRV. XG sizes them 0x384000 (57 pages) and 0x3c0000 (60 pages), so the one placed second owns 3 pages more than the first, and those are the shared pages of the texture the title put 0x390000 after them. The sampled alias then reads that neighbour's memory (a step in the captured frame), and placements sees it Around the target and supersedes it. With XCL_PAIR_PAGES=1 (off by default) place_on_pages caps a sampled texture placed at the address and tile count of a live mapped texture the GPU writes, and that it is a view of, to the smaller of the two (pair_bytes) and keeps the capped size in its Target, so the later texture shares exactly the written partner's pages and its other tiles are private (va, i) tiles. Placed first, the larger texture is not changed (its tiles are bound already). The cap is made before the range is handed to placements, so a capped pair is Same, not Around. The log line is printed for the first two and powers of two. Only a written texture is a partner (pair_partners), and only while it is the current placement: mapped, held by the title and not superseded in placements (placements::current_view; a superseded target stays mapped in vram until its deferred unmap, late_release::hold_unmap), to a sampled texture with the same size and levels and a texel of the same size (Desc::same_texels, the rule placements keeps the two on one memory by; a texture of another shape with as many tiles is something else the title put in that memory, and keeps its size), with the size CreatePlacedResourceX passes (console_bytes: XG's, or for a 3-D texture XG cannot lay out the bytes of its texels; not the least_texture_bytes lower bound). A sampled texture caps nothing, capped or not. A texture the GPU writes is never capped: on the console it has all of its own size, and its readback into the title's memory (title_textures::publish_download) goes by its whole layout. The registry is asked with PAGES released: its lock is the outer one of the two (placements::unmap_if_superseded). The cap is not the byte layout of the console. Measured with the GDK's XG library: the two layouts (0x102 and 2) put texel (x, y) at different offsets (first difference at (8,0); 920896 of 921600 texels differ), and the SRV's 3-page overrun is real on the console (36864 texels past the UAV's end). The cap is what the PC alias shows. Tests: pair_bytes on targets (a written partner; a sampled one or one of unknown size caps nothing and a written texture is not capped; a superseded partner before and after its unmap), placements::current and current_view on a registry (another shape, other levels and another texel size are not a view), a placements test that the capped pair is Same, and GPU tests with the real descriptions: a neighbour at +0x390000 (80 of 128 neighbour rows are overwritten without the cap, with pair_bytes returning its own size), and a written texture made after a smaller sampled one and then superseded (with every mapped texture a partner it is capped to 0x384000; with the registry not asked, the sampled texture made after it is capped to the superseded one; a sampled 720x1280 texture at the address of a written 1280x720 one has as many tiles and keeps its size). Assisted-by: Claude Code (Claude Sonnet 5.5) Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/placements.rs | 79 ++++++ crates/xcl/src/hle/d3d12x/vram.rs | 351 +++++++++++++++++++++++- 2 files changed, 426 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/placements.rs b/crates/xcl/src/hle/d3d12x/placements.rs index 5dda38c2d4..40d309fdd7 100644 --- a/crates/xcl/src/hle/d3d12x/placements.rs +++ b/crates/xcl/src/hle/d3d12x/placements.rs @@ -350,6 +350,21 @@ impl Registry { fn superseded(&self, res: usize) -> bool { self.live.get(&res).is_some_and(|p| !p.mapped && !p.released) } + + /// Whether the title holds `res` and no newer placement supersedes it. A superseded target is + /// not current from the placement over it on, though its tiles leave the shared pages later + /// (`late_release::hold_unmap`). + fn current(&self, res: usize) -> bool { + self.live.get(&res).is_some_and(|p| p.mapped && !p.released) + } + + /// Whether `res` is current and a texture of `view` at its address is a second description + /// of its texels (`Desc::same_texels`, the rule `place` keeps the two on one memory by). A + /// texture of another shape that only has as many tiles is not: it is something else the + /// title put in that memory. + fn current_view(&self, res: usize, view: &Desc) -> bool { + self.current(res) && self.live.get(&res).is_some_and(|p| view.same_texels(&p.desc)) + } } static REGISTRY: Mutex> = Mutex::new(None); @@ -538,6 +553,15 @@ pub(super) unsafe fn unmap_if_superseded(res: &ID3D12Resource) { } } +/// Whether placement `res` is current and a texture of `view` is a view of its texels +/// (`Registry::current_view`): one a sampled texture of `view` placed in its memory is paired +/// with (`vram::pair_bytes`). Takes the registry's lock, so it is not for a caller that holds +/// `vram`'s pages (`unmap_if_superseded` takes that lock under this one). +pub(super) fn current_view(res: usize, view: &D3D12_RESOURCE_DESC) -> bool { + let view = Desc::of(view); + REGISTRY.lock().unwrap().as_ref().is_some_and(|r| r.current_view(res, &view)) +} + /// Whether any live target is currently superseded (`SUPERSEDED != 0`). pub(super) fn any_superseded() -> bool { SUPERSEDED.load(Ordering::Relaxed) != 0 @@ -829,4 +853,59 @@ mod tests { assert!(!r.superseded(10)); assert_eq!(r.unmapped, 0); } + + /// `XCL_PAIR_PAGES=1`: a 1280x720 R9G9B9E5 view (60 pages) placed at the address of a live + /// R32_UINT target (57 pages) lies around it and supersedes it; capped to the target's pages it + /// is on the same pages, and the two are one memory under two descriptions. + #[test] + fn a_capped_pair_is_on_the_same_pages() { + let mut r = Registry::default(); + let x = 0x12_3a00_0000usize; + place(&mut r, 1, x, (x, x + 57 * K64), Kind::Target); + let (_, c) = place(&mut r, 2, x, (x, x + 60 * K64), Kind::Sampled); + assert_eq!(overlaps(&c), [(1, Overlap::Around)]); + assert!(supersedes(c[0].overlap, Kind::Target, Backing::Pages(1), false, true)); + let (_, c) = place(&mut r, 3, x, (x, x + 57 * K64), Kind::Sampled); + assert_eq!(overlaps(&c), [(1, Overlap::Same), (2, Overlap::Inside)]); + assert!(!supersedes(c[0].overlap, Kind::Target, Backing::Pages(1), false, true)); + } + + /// `XCL_PAIR_PAGES=1` pairs a sampled texture with a current target only: a superseded one is + /// not current from the placement over it on (before its tiles are unmapped), one the title + /// uses again is, and one it released is not. + #[test] + fn a_superseded_or_released_target_is_not_current() { + let mut r = Registry::default(); + let x = 0x12_3a00_0000usize; + retiring(&mut r, 1, x, 57 * K64, Kind::Target); + assert!(r.current(1)); + assert!(!r.current(9), "never placed"); + assert_eq!(retiring(&mut r, 2, x + 8 * K64, 4 * K64, Kind::Sampled).0, [1]); + assert!(!r.current(1), "superseded"); + assert!(r.current(2)); + assert_eq!(r.use_again(1), [2]); + assert!(r.current(1), "used again"); + assert!(r.release(1).is_empty()); + assert!(!r.current(1), "released"); + } + + /// `XCL_PAIR_PAGES=1` pairs a sampled texture with a current target it is a view of: the same + /// size and levels and a texel of the same size (R9G9B9E5 over R32_UINT). A texture of another + /// shape with as many tiles (720x1280 over 1280x720), with other levels or with another texel + /// size is not a view of it, and neither is any texture once the target is superseded. + #[test] + fn only_a_view_of_a_current_targets_texels_pairs_with_it() { + let mut r = Registry::default(); + let x = 0x12_3a00_0000usize; + let d = |width: u64, height: u32, mips: u16, format: i32| Desc { width, height, depth: 1, mips, format, flags: 0 }; + r.place(1, x, (x, x + 57 * K64), Backing::Pages(1), Kind::Target, d(1280, 720, 1, 42), Instant::now(), false, true); + assert!(r.current_view(1, &d(1280, 720, 1, 67))); + assert!(r.current_view(1, &d(1280, 720, 1, 42))); + assert!(!r.current_view(1, &d(720, 1280, 1, 67)), "another shape"); + assert!(!r.current_view(1, &d(1280, 720, 2, 67)), "other levels"); + assert!(!r.current_view(1, &d(1280, 720, 1, 10)), "a texel of another size"); + assert!(!r.current_view(9, &d(1280, 720, 1, 67)), "never placed"); + assert_eq!(retiring(&mut r, 2, x + 8 * K64, 4 * K64, Kind::Sampled).0, [1]); + assert!(!r.current_view(1, &d(1280, 720, 1, 67)), "superseded"); + } } diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 5281099647..8755ac4950 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -701,6 +701,7 @@ pub(super) fn is_placed_texture(resource: usize) -> bool { PLACED_TEXTURES.lock().unwrap().as_ref().is_some_and(|textures| textures.contains(&resource)) } + #[cfg(test)] pub(super) fn forget(resource: usize) { forget_tracked_srvs(resource); @@ -1061,6 +1062,12 @@ struct Target { /// virtual, resident, and SRV-sampled texel accounting for sampled placed textures (`None` for GPU-owned targets) texels: Option, recycle: Option, + /// `XCL_PAIR_PAGES=1`, a texture the GPU writes (`gpu_owned`) whose size on the console is + /// known (`console_bytes`, the one `CreatePlacedResourceX` passes: XG's, or for a 3-D texture + /// XG cannot lay out the bytes of its texels; not `least_texture_bytes`): that size, the one a + /// sampled texture placed in its memory is capped to (`pair_bytes`). None: no texture is + /// capped to this one's pages + pair: Option, } /// The tiles of a texture whose levels get video memory when an upload first has texels for @@ -2268,9 +2275,55 @@ pub(super) fn canonical_va(va: usize) -> usize { if mapped { va } else { src } } +/// `XCL_PAIR_PAGES=1`: a texture placed in the memory of a live one owns only the pages of the +/// smaller of the two (`pair_bytes`). Off by default. +fn pair_pages() -> bool { + #[cfg(test)] + if PAIR_PAGES_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed) { + return true; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PAIR_PAGES").is_ok_and(|v| v.trim() == "1")) +} + +/// `pair_pages` for a test (under `VRAM_TEST_LOCK`) +#[cfg(test)] +static PAIR_PAGES_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// The textures of `targets` a sampled one placed at `va` with `total` tiles can be paired with +/// (`pair_bytes`), each with its size on the console: the mapped ones at the same address and +/// tile count that the GPU writes and whose size is known (`Target::pair`). A sampled texture is +/// not one, capped or not, nor is a texture whose size is `least_texture_bytes`' lower bound. +/// A texture the GPU writes (`writer`) has none: on the console it has all of its own size, and +/// its readback into the title's memory goes by that (`title_textures::publish_download`). +fn pair_partners(targets: &std::collections::HashMap, va: usize, total: u32, writer: bool) -> Vec<(usize, u64)> { + if writer { + return Vec::new(); + } + targets.iter().filter(|(_, t)| t.mapped && t.va == va && t.total == total).filter_map(|(&res, t)| Some((res, t.pair?))).collect() +} + +/// The console size a sampled texture gets pages for when `partners` (`pair_partners`) are in +/// its memory: the smallest of its own `console_bytes` and of the `current` ones' (the title +/// holds them, no newer placement supersedes them and the sampled texture is a view of their +/// texels, `placements::current_view`: a superseded target stays mapped until the queues are +/// past it, `late_release::hold_unmap`, and a texture of another shape with as many tiles is +/// something else the title put there). Two +/// descriptions of the memory at one address (a sampled alias of a texture the title writes) +/// then share exactly the written texture's pages, and the larger one's last tiles are not the +/// pages of what the title put after it. This is what the PC's alias shows, not the byte layout +/// of the console: the two layouts do not put a texel at the same offset. +fn pair_bytes(partners: &[(usize, u64)], current: impl Fn(usize) -> bool, console_bytes: Option) -> Option { + let own = console_bytes?; + let least = partners.iter().filter(|&&(res, _)| current(res)).map(|&(_, bytes)| bytes).min(); + Some(least.map_or(own, |l| l.min(own))) +} + /// 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. +/// `pair`: `XCL_PAIR_PAGES=1` – a sampled texture is capped to a written one in its memory +/// (`pair_bytes`); for a texture the GPU writes, also that `console_bytes` is its known size. #[allow(clippy::too_many_arguments)] unsafe fn place_on_pages( dev: &ID3D12Device, @@ -2282,6 +2335,7 @@ unsafe fn place_on_pages( console_bytes: Option, require_aligned: bool, lazy: bool, + pair: bool, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void, ) -> Option { @@ -2366,6 +2420,29 @@ unsafe fn place_on_pages( dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); None }; + // (the size kept in the `Target` is the capped one: lazy levels, `unmap_levels` and the + // range handed to `placements` go by the same pages as `bind`) + let writer = gpu_owned(desc.Flags.0 as u32); + let console_bytes = if pair { + let partners = match PAGES.lock().unwrap().get(&dev_key) { + Some(Some(pages)) => pair_partners(&pages.targets, va, total, writer), + _ => Vec::new(), + }; + // (asked with `PAGES` released: the registry's lock is the outer one of the two, + // `placements::unmap_if_superseded`) + let capped = pair_bytes(&partners, |res| super::placements::current_view(res, desc), console_bytes); + if capped != console_bytes { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: pair pages: texture at {va:#x} ({total} tiles) owns {:#x} bytes of pages, not {:#x}: a live texture is in the same memory ({n} so far)", capped.unwrap_or(0), console_bytes.unwrap_or(0)); + } + } + capped + } else { + console_bytes + }; + let pair = if pair && writer { console_bytes } else { None }; let texels = (!require_aligned && super::memory_report::enabled()).then(|| TexelMeta::from_desc(desc, levels.is_none())); let bound = { let mut g = PAGES.lock().unwrap(); @@ -2375,11 +2452,11 @@ unsafe fn place_on_pages( LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); record_texel_insert(&texels); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels, texels, recycle: recycle_key }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels, texels, recycle: recycle_key, pair }); true } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { record_texel_insert(&texels); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None, texels, recycle: recycle_key }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None, texels, recycle: recycle_key, pair }); true } else { false @@ -2984,7 +3061,7 @@ pub unsafe fn place_pages( note_unknown_size(desc, least); least }); - place_on_pages(dev, this, va, desc, state, clear, console_bytes, false, lazy, riid, ppv) + place_on_pages(dev, this, va, desc, state, clear, console_bytes, false, lazy, pair_pages(), riid, ppv) } /// The levels `levels` of `res` (None: all of them) get their pages if they have none yet: a @@ -3199,13 +3276,14 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st // (a 3D render target's size on the console is not modelled: without one, every PC tile of // it went on the title's pages from `va` on – more of them than the console's texture takes, // so the last ones were the first pages of the title's next texture) + let known = console_bytes.is_some(); let console_bytes = console_bytes.or_else(|| { let least = least_texture_bytes(desc); note_unknown_size(desc, least); least }); if std::env::var_os("XCL_VRAM_ARENAS").is_none() { - if let Some(hr) = place_on_pages(dev, this, va, desc, state, clear, console_bytes, true, false, riid, ppv) { + if let Some(hr) = place_on_pages(dev, this, va, desc, state, clear, console_bytes, true, false, pair_pages() && known, riid, ppv) { return Some(hr); } } @@ -4130,6 +4208,7 @@ mod tests { levels: Some(levels), texels: None, recycle: None, + pair: None, }; assert_eq!(target_page_keys(&target), (vec![0x1000], vec![(0x2000, 1)])); @@ -4813,6 +4892,269 @@ mod tests { } } + /// A placed texture as `place_on_pages` keeps it; `pair`: its known size if the GPU writes it. + fn pair_target(va: usize, total: u32, console_bytes: Option, mapped: bool, pair: Option) -> Target { + Target { va, console_bytes, total, mapped, used: Vec::new(), used_extra: Vec::new(), levels: None, texels: None, recycle: None, pair } + } + + /// `pair_bytes` of a sampled texture, every partner in `targets` a current placement. + fn paired(targets: &std::collections::HashMap, va: usize, total: u32, console_bytes: Option) -> Option { + pair_bytes(&pair_partners(targets, va, total, false), |_| true, console_bytes) + } + + /// A texture in the memory of a live one (the title's view of a texture it writes, with the + /// sampled description of it) owns the pages of the smaller of the two, not three more that + /// belong to what the title put after it: 1280x720 at 4 bytes, 60 tiles, 57 pages on the + /// console for the written one and 60 for the other. + #[test] + fn a_texture_in_the_memory_of_a_live_one_owns_its_pages() { + let va = 0x12_3a00_0000usize; + let mut targets = std::collections::HashMap::new(); + targets.insert(1usize, pair_target(va, 60, Some(0x38_4000), true, Some(0x38_4000))); + assert_eq!(owned_pages(va, Some(0x3c_0000), 60), Some((va, 60)), "as it was"); + let capped = paired(&targets, va, 60, Some(0x3c_0000)); + assert_eq!(capped, Some(0x38_4000)); + assert_eq!(owned_pages(va, capped, 60), Some((va, 57))); + // another address or tile count, no size, a smaller one: unchanged + assert_eq!(paired(&targets, va + 0x10_0000, 60, Some(0x3c_0000)), Some(0x3c_0000)); + assert_eq!(paired(&targets, va, 59, Some(0x3c_0000)), Some(0x3c_0000)); + assert_eq!(paired(&targets, va, 60, None), None); + assert_eq!(paired(&targets, va, 60, Some(0x10_0000)), Some(0x10_0000)); + } + + /// Only a texture the GPU writes caps one placed in its memory, and only a sampled one is + /// capped. A written texture made after a smaller sampled one keeps its own size (its readback + /// into the title's memory goes by its whole layout), and so does a sampled one made after a + /// smaller sampled one, or after a written one whose size is only `least_texture_bytes`'. + #[test] + fn a_sampled_texture_caps_nothing_and_a_written_one_is_not_capped() { + let va = 0x12_3a00_0000usize; + let mut targets = std::collections::HashMap::new(); + targets.insert(1usize, pair_target(va, 60, Some(0x38_4000), true, None)); + // the written one made second + assert!(pair_partners(&targets, va, 60, true).is_empty()); + assert_eq!(pair_bytes(&pair_partners(&targets, va, 60, true), |_| true, Some(0x3c_0000)), Some(0x3c_0000)); + // a sampled one made second + assert_eq!(paired(&targets, va, 60, Some(0x3c_0000)), Some(0x3c_0000)); + // a written one of unknown size (kept with a lower bound) is not a partner + targets.insert(2usize, pair_target(va, 60, Some(0x30_0000), true, None)); + assert_eq!(paired(&targets, va, 60, Some(0x3c_0000)), Some(0x3c_0000)); + // one of known size is, to a sampled texture; a written one is still not capped + targets.insert(3usize, pair_target(va, 60, Some(0x39_0000), true, Some(0x39_0000))); + assert_eq!(pair_partners(&targets, va, 60, false), [(3, 0x39_0000)]); + assert_eq!(paired(&targets, va, 60, Some(0x3c_0000)), Some(0x39_0000)); + assert!(pair_partners(&targets, va, 60, true).is_empty()); + } + + /// A written texture a newer placement superseded is not a partner: not from that placement on + /// (`placements::current_view`), while its unmap waits for the queues and it is still mapped here + /// (`late_release::hold_unmap`), and not once it is unmapped. + #[test] + fn a_superseded_written_texture_is_not_a_partner() { + let va = 0x12_3a00_0000usize; + let mut targets = std::collections::HashMap::new(); + targets.insert(1usize, pair_target(va, 60, Some(0x38_4000), true, Some(0x38_4000))); + let partners = pair_partners(&targets, va, 60, false); + assert_eq!(pair_bytes(&partners, |res| res == 1, Some(0x3c_0000)), Some(0x38_4000), "current"); + assert_eq!(pair_bytes(&partners, |res| res != 1, Some(0x3c_0000)), Some(0x3c_0000), "superseded, its unmap held"); + targets.get_mut(&1).unwrap().mapped = false; + assert_eq!(paired(&targets, va, 60, Some(0x3c_0000)), Some(0x3c_0000), "unmapped"); + // mapped again (the title used it again): a partner again + targets.get_mut(&1).unwrap().mapped = true; + assert_eq!(paired(&targets, va, 60, Some(0x3c_0000)), Some(0x38_4000)); + } + + /// The other texture of the pair going away (or never mapped) leaves the one placed after it + /// with what it was given: its size in the `Target` is the capped one. + #[test] + fn forgetting_the_first_texture_keeps_the_seconds_tail_tiles() { + let va = 0x12_3a00_0000usize; + let mut targets = std::collections::HashMap::new(); + targets.insert(1usize, pair_target(va, 60, Some(0x38_4000), true, Some(0x38_4000))); + let capped = paired(&targets, va, 60, Some(0x3c_0000)); + targets.insert(2usize, pair_target(va, 60, capped, true, None)); + targets.remove(&1); + assert_eq!(targets[&2].console_bytes, Some(0x38_4000)); + assert_eq!(owned_pages(va, targets[&2].console_bytes, 60), Some((va, 57))); + // a third one with no written partner is not capped: the capped one does not pass its cap on + assert_eq!(paired(&targets, va, 60, Some(0x3c_0000)), Some(0x3c_0000)); + } + + /// On the GPU, through `place_on_pages`: a written texture made after a smaller sampled one at + /// its address keeps its own size, and a sampled one made after both is capped to the written + /// one, not to the first sampled one. A texture placed inside the written one then supersedes + /// it (`placements`), and a sampled one made after that is not capped to it, whether its + /// deferred unmap has run or not. + #[test] + fn gpu_a_written_texture_made_second_is_not_capped() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + if !tier2(&dev) { + return crate::gpu::recomp::runner::skip_test("no tier-2 reserved resources"); + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let sample = DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }; + let tex = |format: DXGI_FORMAT, w: u64, h: u32, flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: w, Height: h, DepthOrArraySize: 1, MipLevels: 1, Format: format, SampleDesc: sample, Flags: flags, ..Default::default() }; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let va = 0x12_3c00_0000usize; + let place_one = |va: usize, d: &D3D12_RESOURCE_DESC, bytes: u64, owned: bool| { + let mut p = std::ptr::null_mut(); + let state = D3D12_RESOURCE_STATE_COPY_DEST.0 as u32; + let hr = place_on_pages(&dev, dev.as_raw(), va, d, state, std::ptr::null(), Some(bytes), owned, false, true, riid, &mut p); + (hr.is_some_and(|hr| hr >= 0) && !p.is_null()).then(|| ID3D12Resource::from_raw(p)) + }; + // the size its `Target` keeps: what it owns pages for + let kept = |r: &ID3D12Resource| { + let g = PAGES.lock().unwrap(); + g.get(&(dev.as_raw() as usize)).and_then(|p| p.as_ref()).and_then(|p| p.targets.get(&(r.as_raw() as usize))).and_then(|t| t.console_bytes) + }; + let sampled_desc = tex(DXGI_FORMAT_R9G9B9E5_SHAREDEXP, 1280, 720, D3D12_RESOURCE_FLAG_NONE); + let written_desc = tex(DXGI_FORMAT_R32_UINT, 1280, 720, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + let (Some(first), Some(written), Some(third)) = ( + place_one(va, &sampled_desc, 0x38_4000, false), + place_one(va, &written_desc, 0x3a_0000, true), + place_one(va, &sampled_desc, 0x3c_0000, false), + ) else { + return crate::gpu::recomp::runner::skip_test("reserved textures not available"); + }; + assert_eq!(kept(&first), Some(0x38_4000)); + assert_eq!(kept(&written), Some(0x3a_0000), "the written one is not capped to the sampled one before it"); + assert_eq!(kept(&third), Some(0x3a_0000), "capped to the written one, not to the sampled one"); + // a sampled texture of another shape with as many tiles is not a view of a written + // one at its address: it keeps its size + let tiles = |r: &ID3D12Resource| PAGES.lock().unwrap().get(&(dev.as_raw() as usize)).and_then(|p| p.as_ref()).and_then(|p| p.targets.get(&(r.as_raw() as usize))).map(|t| t.total); + let (Some(written_too), Some(turned)) = ( + place_one(va + 0x100_0000, &written_desc, 0x38_4000, true), + place_one(va + 0x100_0000, &tex(DXGI_FORMAT_R9G9B9E5_SHAREDEXP, 720, 1280, D3D12_RESOURCE_FLAG_NONE), 0x3c_0000, false), + ) else { + return crate::gpu::recomp::runner::skip_test("reserved textures not available"); + }; + assert_eq!(tiles(&turned), tiles(&written_too), "as many tiles as the written one"); + assert_eq!(kept(&turned), Some(0x3c_0000), "another shape is not a view of the written one"); + if !super::super::placements::retire() { + return; + } + let Some(_inside) = place_one(va + 8 * PAGE, &tex(DXGI_FORMAT_R32_UINT, 128, 128, D3D12_RESOURCE_FLAG_NONE), 0x1_0000, false) else { + return crate::gpu::recomp::runner::skip_test("reserved textures not available"); + }; + assert!(!super::super::placements::current_view(written.as_raw() as usize, &written_desc), "superseded by the one inside it"); + let fourth = place_one(va, &sampled_desc, 0x3c_0000, false).unwrap(); + assert_eq!(kept(&fourth), Some(0x3c_0000), "a superseded written texture is not a partner"); + } + } + + /// On the GPU, the real descriptions: a 1280x720 R32_UINT target and a sampled R9G9B9E5 texture + /// at its address, a texture of the title 0x390000 after it. Uploading the whole sampled texture + /// leaves the neighbour as it was (its last 3 tiles were the neighbour's pages). + #[test] + fn gpu_a_sampled_pairs_last_tiles_are_not_the_next_textures() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + if !tier2(&dev) { + return crate::gpu::recomp::runner::skip_test("no tier-2 reserved resources"); + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let sample = DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }; + let tex = |format: DXGI_FORMAT, w: u64, h: u32, flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: w, Height: h, DepthOrArraySize: 1, MipLevels: 1, Format: format, SampleDesc: sample, Flags: flags, ..Default::default() }; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let va = 0x12_3a00_0000usize; + let place_one = |va: usize, d: &D3D12_RESOURCE_DESC, bytes: u64, owned: bool| { + let mut p = std::ptr::null_mut(); + let state = D3D12_RESOURCE_STATE_COPY_DEST.0 as u32; + let hr = place_on_pages(&dev, dev.as_raw(), va, d, state, std::ptr::null(), Some(bytes), owned, false, true, riid, &mut p); + if !hr.is_some_and(|hr| hr >= 0) || p.is_null() { + return None; + } + Some(ID3D12Resource::from_raw(p)) + }; + let neighbour_desc = tex(DXGI_FORMAT_R32_UINT, 128, 128, D3D12_RESOURCE_FLAG_NONE); + let written_desc = tex(DXGI_FORMAT_R32_UINT, 1280, 720, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + let sampled_desc = tex(DXGI_FORMAT_R9G9B9E5_SHAREDEXP, 1280, 720, D3D12_RESOURCE_FLAG_NONE); + let (Some(neighbour), Some(_written), Some(sampled)) = ( + place_one(va + 0x39_0000, &neighbour_desc, 0x1_0000, false), + place_one(va, &written_desc, 0x38_4000, true), + place_one(va, &sampled_desc, 0x3c_0000, false), + ) else { + return crate::gpu::recomp::runner::skip_test("reserved textures not available"); + }; + std::thread::sleep(Duration::from_millis(100)); + + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut fence_value = 0u64; + let buffer_on = |kind: D3D12_HEAP_TYPE, bytes: u64, state: D3D12_RESOURCE_STATES| { + let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: sample, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; + let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }; + let mut r: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap(); + r.unwrap() + }; + let mut run = |record: &dyn Fn(&ID3D12GraphicsCommandList)| { + 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(); + record(&list); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + fence_value += 1; + queue.Signal(&fence, fence_value).unwrap(); + fence.SetEventOnCompletion(fence_value, windows::Win32::Foundation::HANDLE::default()).unwrap(); + }; + let footprint = |d: &D3D12_RESOURCE_DESC| { + let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0u64; + dev.GetCopyableFootprints(d, 0, 1, 0, Some(&mut f), None, None, Some(&mut total)); + (f, total) + }; + let location = |r: &ID3D12Resource, f: Option| D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(r), + Type: if f.is_some() { D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT } else { D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX }, + Anonymous: match f { + Some(f) => D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f }, + None => D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }, + }; + let mut upload = |target: &ID3D12Resource, d: &D3D12_RESOURCE_DESC, byte: u8| { + let (f, total) = footprint(d); + let buffer = buffer_on(D3D12_HEAP_TYPE_UPLOAD, total, D3D12_RESOURCE_STATE_GENERIC_READ); + let mut p = std::ptr::null_mut(); + buffer.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::write_bytes(p as *mut u8, byte, total as usize); + buffer.Unmap(0, None); + run(&|list| list.CopyTextureRegion(&location(target, None), 0, 0, 0, &location(&buffer, Some(f)), None)); + }; + upload(&neighbour, &neighbour_desc, 0xAB); + upload(&sampled, &sampled_desc, 0xEE); + + // the neighbour, read back + let (f, total) = footprint(&neighbour_desc); + let readback = buffer_on(D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_STATE_COPY_DEST); + run(&|list| { + let t = D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(&neighbour), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, StateBefore: D3D12_RESOURCE_STATE_COPY_DEST, StateAfter: D3D12_RESOURCE_STATE_COPY_SOURCE }; + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(t) }, ..Default::default() }]); + list.CopyTextureRegion(&location(&readback, Some(f)), 0, 0, 0, &location(&neighbour, None), None); + }); + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).unwrap(); + let bytes = std::slice::from_raw_parts(p as *const u8, total as usize); + let pitch = f.Footprint.RowPitch as usize; + let wrong = (0..128).filter(|&y| bytes[y * pitch..y * pitch + 128 * 4].iter().any(|&b| b != 0xAB)).count(); + readback.Unmap(0, None); + assert_eq!(wrong, 0, "{wrong} of 128 rows of the neighbour hold the sampled texture's texels"); + } + } + /// Title textures placed one behind the other, 512 KiB apart: 3D render targets of 33 texels /// a side with 8-byte texels, whose size on the console XCL does not model. Each has the pages /// of its own texels and no page of the next one, however many tiles the PC's texture has @@ -5531,6 +5873,7 @@ mod tests { Some(64 * 1024), false, false, + false, riid, &mut ppv, )?; From b02b2c34f7ebec048158edb0b4872404efbfcd05 Mon Sep 17 00:00:00 2001 From: Pipodi Date: Sun, 29 Nov 2026 00:55:13 +0100 Subject: [PATCH 2/2] D3D12.X: XCL_PAIR_PAGES=1 caps the title_textures range of a capped view The title places an R9G9B9E5 view by address over a live R32_UINT texture (1280x720, 0x384000 bytes). XG sizes the view 0x3c0000 and the title's next resource starts at the view's address + 0x384000. Table::insert saw that resource inside the view's range, called the view superseded by a different range, and vram::unmap_superseded mapped all 60 of its tiles to NULL: the compute pass that read the view got zeros and wrote zeros over the R32_UINT. XCL_PAIR_PAGES=1 capped only the vram extent (pair_bytes), not the table's. The entry of a sampled texture now keeps the capped extent (vram::pair_capped_bytes reads it from the placed Target, so pair_bytes stays the one place that computes it) and insert, retire_range, remove, the source links and the hot range use it. So do the test for written pages (Entry::written_in), the pages a partial upload compares (dirty_on) and the fingerprint of a view whose memory is not watched: a write to the neighbour's first bytes is in a 1 MiB source piece of the view, and with the view's whole size it sent the view up again. Every upload of a capped view, its first whole one too, now stops at its cap (texture_upload::Item::own_tiles from vram::pair_capped_tiles, the tiles owned_pages gives it; texture_upload::owned_parts clips each piece to them). The view's tiles past the cap are the extra pages keyed (va, 57..59) it shares with the R32_UINT, whose last texels they hold: a whole upload of the view wrote the neighbour's bytes over them, and the view's first upload after register is always a whole one (pending; gpu_written is only set on the writer's entry). A level in the packed mips or a 3D level goes up whole when the view owns all of its tiles, else not at all. Each array slice has its own packed mips, D3D12_PACKED_MIP_INFO's start (slice 0's) plus the slice times the tiles of a slice, and a level from NumStandardMips on is packed: WARP gives the packed subresources of slice 1 slice 0's start and no tiles, not D3D12_PACKED_TILE (256x256, 2 slices, 9 mips: start 5, 0x0). A capped view whose tiles vram does not give owns none: nothing of it goes up rather than all of it. The hashes of its pages are still those of the whole layout. A capped view a list writes (gpu_written, as a copy destination) is read back into the title's memory up to its cap only (publish_download): past it is the next texture's memory, and its tiles there are the pages it shares with the written texture. The entry of a texture the GPU writes (register_gpu_owned) has no cap: vram never caps one, and publish_download writes its whole layout back into the title's memory, so its range in the table is its whole size. Only under XCL_PAIR_PAGES=1. Tests: gpu_register_takes_the_cap_from_the_pair (register's range stops at the capped extent, the written texture keeps its own size; skip_test without reserved textures); capped_placed_view_is_not_superseded_by_its_neighbour fails with the cap ignored (the insert at address + 0x384000 returns the view to unmap), and with the whole size in written_in (a written page at address + 0x384000 selects the view); a_capped_views_fingerprint_ends_at_its_cap fails with the whole size fingerprinted, in the baseline (seed_stream_recheck) or in the recheck (a write past the cap, in the end slice of a whole-size fingerprint, queues the view); gpu_a_capped_views_first_upload_leaves_the_tiles_past_its_cap places the pair on pages, registers the view, sends its first upload through upload_all and fails with the clip off or with no own_tiles from upload_all (the view writes 30720 texels of tiles 57..59 of the R32_UINT); gpu_a_capped_arrays_first_upload_stops_at_its_cap_in_a_later_slice caps a 2-slice array with packed mips one tile into slice 1 and fails with slice 0's packed start for every slice, with the packed levels taken from D3D12_PACKED_TILE alone, or with no own_tiles from upload_all (slice 1's packed mips get the view's bytes), and skips on an adapter that makes no reserved array with packed mips (GitHub's runner: E_INVALIDARG); a_capped_view_without_its_tiles_owns_none fails with a capped view without a Target uploaded whole; gpu_a_capped_views_download_ends_at_its_cap fails with the whole layout written back (the bytes past the cap get the GPU's). The GPU tests read a texture back through the one that wrote it, after an aliasing barrier; the 1280x720 one also reads the view's own tiles through the R32_UINT (both 32 bpp, standard tiles: the title's case). Packed mips of two descriptions are not compared: on PC their layout on the same tiles (64KB_UNDEFINED_SWIZZLE) is not guaranteed alike, and reading the view's packed mips through the R32_UINT failed about 2 runs in 30. Assisted-by: Claude Code (Claude Sonnet 5.5) Co-Authored-By: Claude Fable 5.2 Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/texture_upload.rs | 67 ++- crates/xcl/src/hle/d3d12x/title_textures.rs | 511 ++++++++++++++++++-- crates/xcl/src/hle/d3d12x/vram.rs | 102 +++- 3 files changed, 636 insertions(+), 44 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/texture_upload.rs b/crates/xcl/src/hle/d3d12x/texture_upload.rs index dfc1b7fce4..13f22f0398 100644 --- a/crates/xcl/src/hle/d3d12x/texture_upload.rs +++ b/crates/xcl/src/hle/d3d12x/texture_upload.rs @@ -40,6 +40,10 @@ pub(super) struct Item { pub known: Option, /// where its pages are read, for a texture in a GPU view whose pages the title mapped pub pages: Option>, + /// `XCL_PAIR_PAGES=1`: the tiles `[0, n)` (in the resource's tile order) a capped texture owns + /// (`vram::pair_capped_tiles`); those after them are the pages of the texture the title placed + /// there, and none of its texels go up into them (`owned_parts`). None: all of it + pub own_tiles: Option, } // --------------------------------------------------------------------------------------- @@ -468,7 +472,9 @@ unsafe fn plan_item(dev: &ID3D12Device, k: usize, it: &Item, at: &mut u64, out: dev.GetCopyableFootprints(&rd, 0, 1, 0, Some(&mut fp), None, None, None); } let format: DXGI_FORMAT = fp.Footprint.Format; - let mut push = |slice: usize, level: usize, rect: Rect, depth: usize| { + // (a capped texture: only the parts on its own tiles) + let own = it.own_tiles.and_then(|own| owned_parts(dev, &it.res, own, n, s.side)); + let mut push_part = |slice: usize, level: usize, rect: Rect, depth: usize| { let (w, h) = (rect.x1 - rect.x0, rect.y1 - rect.y0); let pitch = (w * bpe).next_multiple_of(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT as usize); *at = at.next_multiple_of(D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT as u64); @@ -484,6 +490,16 @@ unsafe fn plan_item(dev: &ID3D12Device, k: usize, it: &Item, at: &mut u64, out: }); *at += (pitch * h * depth) as u64; }; + let mut push = |slice: usize, level: usize, rect: Rect, depth: usize| match &own { + None => push_part(slice, level, rect, depth), + // (a 3D level goes up whole or not at all) + Some(own) => own.get(slice * mips + level).into_iter().flatten().for_each(|o| { + let r = Rect { x0: rect.x0.max(o.x0), y0: rect.y0.max(o.y0), x1: rect.x1.min(o.x1), y1: rect.y1.min(o.y1) }; + if r.x0 < r.x1 && r.y0 < r.y1 && (!volume || r == rect) { + push_part(slice, level, r, depth); + } + }), + }; if volume { for (i, l) in c.levels.iter().enumerate() { push(0, i, Rect { x0: 0, y0: 0, x1: l.width, y1: l.height }, l.depth); @@ -526,6 +542,49 @@ unsafe fn plan_item(dev: &ID3D12Device, k: usize, it: &Item, at: &mut u64, out: Ok(()) } +/// The parts of each of the `subs` subresources of reserved `res` on its tiles `[0, own)` +/// (`Item::own_tiles`), in elements of `side` texels: its rows of tiles before the first tile it +/// does not own, then the tiles of that row before it. A subresource with more than one layer of +/// tiles (3D) or in the packed mips is all of it when it owns all of their tiles, else nothing. +/// None: `res` has no tiles (not reserved), so it shares none. +unsafe fn owned_parts(dev: &ID3D12Device, res: &ID3D12Resource, own: u32, subs: usize, side: u32) -> Option>> { + const ALL: Rect = Rect { x0: 0, y0: 0, x1: usize::MAX, y1: usize::MAX }; + let (mut total, mut packed, mut shape, mut n) = (0u32, D3D12_PACKED_MIP_INFO::default(), D3D12_TILE_SHAPE::default(), subs as u32); + let mut tilings = vec![D3D12_SUBRESOURCE_TILING::default(); subs]; + dev.GetResourceTiling(res, Some(&mut total), Some(&mut packed), Some(&mut shape), Some(&mut n), 0, tilings.as_mut_ptr()); + if total == 0 { + return None; + } + let (w, h) = ((shape.WidthInTexels / side.max(1)) as usize, (shape.HeightInTexels / side.max(1)) as usize); + // (`packed` is slice 0's; each array slice has its own packed mips, at the same place in its run + // of tiles) + let mips = (res.GetDesc().MipLevels as usize).max(1); + let per_slice = total as u64 / (subs / mips).max(1) as u64; + let packed_owned = |slice: usize| packed.StartTileIndexInOverallResource as u64 + slice as u64 * per_slice + packed.NumTilesForPackedMips as u64 <= own as u64; + // (a level from `NumStandardMips` on is in its slice's packed mips: WARP gives those of slice 1 on + // a start of slice 0's and no tiles, not D3D12_PACKED_TILE) + let parts = (0..subs).map(|i| match tilings.get(i).filter(|t| i < n as usize && i % mips < packed.NumStandardMips as usize && t.StartTileIndexInOverallResource != u32::MAX) { + // (u32::MAX: D3D12_PACKED_TILE, in the packed mips) + None => if packed_owned(i / mips) { vec![ALL] } else { Vec::new() }, + Some(t) => { + let (across, tiles) = (t.WidthInTiles as usize, t.WidthInTiles as usize * t.HeightInTiles as usize * t.DepthInTiles as usize); + let k = own.saturating_sub(t.StartTileIndexInOverallResource) as usize; + if k >= tiles { + vec![ALL] + } else if t.DepthInTiles > 1 || across == 0 { + Vec::new() + } else { + let (rows, more) = (k / across, k % across); + [Rect { x0: 0, y0: 0, x1: usize::MAX, y1: rows * h }, Rect { x0: 0, y0: rows * h, x1: more * w, y1: (rows + 1) * h }] + .into_iter() + .filter(|r| r.x0 < r.x1 && r.y0 < r.y1) + .collect() + } + } + }); + Some(parts.collect()) +} + /// What a worker does at a time. enum Work { /// blocks of one row of them @@ -1028,7 +1087,7 @@ mod tests { let want = super::super::title_textures::subresources(mem.as_ptr() as usize, &m.tex); for round in 0..5 { let changed = (round > 0).then(|| some_ranges(size, n * 11 + round)); - let items = [Item { res: m.res.clone(), src: mem.as_ptr() as usize, tex: Arc::clone(&m.tex), states: vec![D3D12_RESOURCE_STATE_COMMON], changed: changed.clone(), known: None, pages: None }]; + let items = [Item { res: m.res.clone(), src: mem.as_ptr() as usize, tex: Arc::clone(&m.tex), states: vec![D3D12_RESOURCE_STATE_COMMON], changed: changed.clone(), known: None, pages: None, own_tiles: None }]; let (mut pieces, mut bytes) = (Vec::new(), 0u64); plan_item(&dev, 0, &items[0], &mut bytes, &mut pieces).unwrap_or_else(|e| panic!("{kind:?}: {e}")); if round == 0 { @@ -1081,7 +1140,7 @@ mod tests { let s = m.tex.texels().unwrap(); let size = m.tex.size() as usize; let first = random_bytes(size, n as u64 * 31 + 3); - let item = |mem: &[u8], changed| Item { res: m.res.clone(), src: mem.as_ptr() as usize, tex: Arc::clone(&m.tex), states: vec![D3D12_RESOURCE_STATE_COMMON], changed, known: None, pages: None }; + let item = |mem: &[u8], changed| Item { res: m.res.clone(), src: mem.as_ptr() as usize, tex: Arc::clone(&m.tex), states: vec![D3D12_RESOURCE_STATE_COMMON], changed, known: None, pages: None, own_tiles: None }; let (_, all) = run(&[item(&first, None)]); let mut want = super::super::title_textures::subresources(first.as_ptr() as usize, &m.tex); assert!(read_back(&dev, &queue, &m.res, want.len()) == want.iter().map(|w| w.data.clone()).collect::>(), "{kind:?}: all of it"); @@ -1171,7 +1230,7 @@ mod tests { let pages: Vec = (0..size / PAGE).map(|k| src + k * PAGE).collect(); let look = |of: &[usize]| changed(&[Written { src, size, dirty: of, known: &known, pages: None }], true).0.remove(0); let upload = |changed: Option>| { - let it = [Item { res: m.res.clone(), src, tex: Arc::clone(&m.tex), states: vec![D3D12_RESOURCE_STATE_COMMON], changed, known: Some(Arc::clone(&known)), pages: None }]; + let it = [Item { res: m.res.clone(), src, tex: Arc::clone(&m.tex), states: vec![D3D12_RESOURCE_STATE_COMMON], changed, known: Some(Arc::clone(&known)), pages: None, own_tiles: None }]; let (mut p, mut bytes) = (Vec::new(), 0u64); plan_item(&dev, 0, &it[0], &mut bytes, &mut p).unwrap(); let mut buf = vec![0u8; bytes as usize]; diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d809b1c2a2..0df36caa93 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -45,6 +45,9 @@ struct Due { device: usize, /// where its bytes are read src: usize, + /// the bytes from `src` it owns (`Entry::extent`): its written pages and its fingerprint are + /// taken there + extent: usize, tex: Arc, states: Vec, known: texture_upload::Known, @@ -98,6 +101,11 @@ struct Entry { /// and each upload reads its pages where they are kept (`texture_upload::PageMap`) paged: bool, tex: Arc, + /// `XCL_PAIR_PAGES=1`: the bytes of `va` the texture owns when that is less than `tex.size()` + /// (`vram::pair_capped_bytes`); a texture the title places after it does not supersede it. + /// The memory past it is that texture's: this one's range and its watch for CPU writes + /// (`link_src`) end at the cap + cap: Option, /// the state the title's submitted work leaves the texture in (uploads leave it there): /// the creation state, then what its transitions give – one state for every subresource, /// or one per subresource (D3D12 order) while they differ @@ -136,6 +144,27 @@ static PENDING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize: // raw COM pointers of the title's objects; uploads hold a reference while they run unsafe impl Send for Entry {} +impl Entry { + /// the bytes of memory from `va` the entry owns (`cap`, else the whole texture) + fn extent(&self) -> usize { + let size = self.tex.size() as usize; + self.cap.map_or(size, |c| c.min(size)) + } + + /// whether a written page of `dirty` (sorted, `page` bytes each) lies on the memory the entry + /// owns (`extent`): a write past a capped view's cap is to the texture the title put there + fn written_in(&self, dirty: &[usize], page: usize) -> bool { + let i = dirty.partition_point(|&p| p + page <= self.src); + dirty.get(i).is_some_and(|&p| p < self.src + self.extent()) + } +} + +/// The pages of `dirty` (sorted, `page` bytes each) on `[src, src + extent)`. +fn dirty_on(dirty: &[usize], page: usize, src: usize, extent: usize) -> &[usize] { + let (from, to) = (dirty.partition_point(|&p| p + page <= src), dirty.partition_point(|&p| p < src + extent)); + &dirty[from..to.max(from)] +} + struct Table { /// Active PC textures (newest at each range) → its place in the title's memory by_res: BTreeMap, @@ -294,7 +323,7 @@ impl Table { for (ova, ores, _) in self.active_overlaps(va, end) { self.by_va.remove(&(ova, ores)); if let Some(old) = self.by_res.remove(&ores) { - self.unlink_src(ores, old.src, old.tex.size() as usize); + self.unlink_src(ores, old.src, old.extent()); if old.pending { pending_delta -= 1; } @@ -326,11 +355,11 @@ impl Table { /// exact same-range entries stay mapped because they already share every tile. fn insert(&mut self, res: usize, mut entry: Entry) -> (isize, Vec) { let va = entry.va; - let end = va.saturating_add(entry.tex.size() as usize); + let end = va.saturating_add(entry.extent()); let mut pending_delta = 0isize; let mut to_unmap = Vec::new(); if let Some(old) = self.by_res.remove(&res) { - self.unlink_src(res, old.src, old.tex.size() as usize); + self.unlink_src(res, old.src, old.extent()); self.by_va.remove(&(old.va, res)); if old.pending { pending_delta -= 1; @@ -345,7 +374,7 @@ impl Table { } self.by_va.remove(&(ova, ores)); if let Some(mut old) = self.by_res.remove(&ores) { - self.unlink_src(ores, old.src, old.tex.size() as usize); + self.unlink_src(ores, old.src, old.extent()); if old.pending { pending_delta -= 1; } @@ -380,7 +409,7 @@ impl Table { self.pending_res.insert(res); } self.by_va.insert((va, res), end); - let (src, size) = (entry.src, entry.tex.size() as usize); + let (src, size) = (entry.src, entry.extent()); self.link_src(res, src, size); self.by_res.insert(res, entry); (pending_delta, to_unmap) @@ -398,12 +427,12 @@ impl Table { return (true, 0, Vec::new(), st); } let Some(old) = self.by_res.remove(&res) else { return (false, 0, Vec::new(), None) }; - self.unlink_src(res, old.src, old.tex.size() as usize); + self.unlink_src(res, old.src, old.extent()); let st = (old.states.len() == 1).then(|| old.states[0]); self.by_va.remove(&(old.va, res)); let mut pending_delta = if old.pending { -1 } else { 0 }; let va = old.va; - let end = va.saturating_add(old.tex.size() as usize); + let end = va.saturating_add(old.extent()); let mut cands: Vec<(u64, usize, usize, usize)> = self .shadowed_overlaps(va, end) .into_iter() @@ -430,7 +459,7 @@ impl Table { pending_delta += 1; } self.by_va.insert((sva, sres), send); - let (src, size) = (e.src, e.tex.size() as usize); + let (src, size) = (e.src, e.extent()); self.link_src(sres, src, size); if e.pending { self.pending_res.insert(sres); @@ -573,6 +602,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, } let in_gpu_view = crate::hle::kernelx::mirrors::source(va).is_some(); let placed = super::vram::is_placed_texture(res as usize); + let cap = super::vram::pair_capped_bytes(res as usize).map(|b| b as usize).filter(|&b| b < tex.size() as usize); let e = Entry { device: device as usize, committed_bytes: committed_allocation_bytes(device, res, placed), @@ -581,6 +611,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, in_gpu_view, paged, tex: Arc::new(tex), + cap, states: vec![state], pending: true, gpu_written: false, @@ -593,7 +624,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, known: Default::default(), target: u32::from_le_bytes(desc[0x30..0x34].try_into().unwrap()) & 0x7 != 0, }; - let (hot_src, hot_bytes) = (e.src, e.tex.size() as usize); + let (hot_src, hot_bytes) = (e.src, e.extent()); let to_unmap = { let mut t = TEXTURES.lock().unwrap(); let (delta, unmap_ptrs) = t.insert(res as usize, e); @@ -667,6 +698,8 @@ pub(super) unsafe fn register_gpu_owned( src, in_gpu_view: crate::hle::kernelx::mirrors::source(va).is_some(), tex: Arc::new(tex), + // (a texture the GPU writes is never capped: `publish_download` reads all of it back) + cap: None, states: vec![state], pending: false, gpu_written: true, @@ -816,7 +849,7 @@ fn recheck_gpu_view_sources() { let mut again: Vec = Vec::new(); let Table { by_res, shadowed, .. } = t; let mut look = |res: usize, e: &mut Entry, active: bool| { - let (old, size) = (e.src, e.tex.size() as usize); + let (old, size) = (e.src, e.extent()); if recheck_source(e) { changed = true; if active { @@ -2130,10 +2163,7 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut e.cpu_backed, e.pending || again != texture_upload::Change::None, e.gpu_written, - || { - 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.written_in(&dirty, page as usize), ); if !wanted { continue; @@ -2154,6 +2184,7 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut res: r.clone(), device: e.device, src: e.src, + extent: e.extent(), tex: Arc::clone(&e.tex), states: e.states.clone(), known: Arc::clone(&e.known), @@ -2380,7 +2411,7 @@ unsafe fn seed_stream_recheck(todo: &[Due], watched: &[(usize, usize)], frame: u let mut seeded = Vec::new(); let mut unsent = Vec::new(); for d in todo { - let size = d.tex.size() as usize; + let size = d.extent; // (a texture read through its pages counts as watched: they are found written where they // are kept, and a fingerprint of the view's own address would read zeros) if size == 0 || d.pages.is_some() || range_is_fully_watched(d.src, size, watched) { @@ -2449,7 +2480,7 @@ unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) Some(e) if e.gpu_written => prune.push(res), Some(e) if e.pending => {} Some(e) => { - let size = e.tex.size() as usize; + let size = e.extent(); if e.paged || range_is_fully_watched(e.src, size, watched) { prune.push(res); } else { @@ -2787,9 +2818,9 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option .iter() .filter(|d| !d.whole) .map(|d| { - let size = d.tex.size() as usize; - let (from, to) = (dirty.partition_point(|&p| p + page <= d.src), dirty.partition_point(|&p| p < d.src + size)); - let mine = &dirty[from..to.max(from)]; + // (the pages it owns; the hashes below are still those of its whole layout) + let size = d.extent; + let mine = dirty_on(dirty, page, d.src, size); // (a look takes the blocks written lately: the others' pages of this texture too, or // it would go up in part as it was and in part as it is; not for one read through // its pages, whose own address is not watched) @@ -2865,7 +2896,8 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option note_content(d.src, &d.res, &subresources_in(d.src, &d.tex, d.pages.as_deref())); } generations.push(d.generation); - items.push(texture_upload::Item { res: d.res, src: d.src, tex: d.tex, states: d.states, changed, known: Some(Arc::clone(&d.known)), pages: d.pages }); + let own_tiles = own_tiles_of(&d.res, d.extent, &d.tex); + items.push(texture_upload::Item { res: d.res, src: d.src, tex: d.tex, states: d.states, changed, known: Some(Arc::clone(&d.known)), pages: d.pages, own_tiles }); known.push(d.known); } let p = device as *mut c_void; @@ -2918,6 +2950,14 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option } } +/// The tiles a capped view (`extent` below its size) owns (`vram::pair_capped_tiles`): each of its +/// uploads, its first whole one too, stops before the tiles past them, the pages of the texture the +/// title placed after it. None: all of its tiles. A capped one whose tiles vram does not give owns +/// none: nothing of it goes up, rather than all of it over the pages past its cap. +fn own_tiles_of(res: &ID3D12Resource, extent: usize, tex: &xg::Texture) -> Option { + (extent < tex.size() as usize).then(|| super::vram::pair_capped_tiles(res.as_raw() as usize).unwrap_or(0)) +} + /// textures of batches that could not be uploaded, with their registration generation, and when /// they are tried again static RETRY: Mutex> = Mutex::new(Vec::new()); @@ -2951,7 +2991,7 @@ pub unsafe fn upload_and_wait(dev: &ID3D12Device, queue: &ID3D12CommandQueue, re if mem.len() < tex.size() as usize { return Err(format!("{} bytes of {}", mem.len(), tex.size())); } - let item = texture_upload::Item { res: res.clone(), src: mem.as_ptr() as usize, tex, states, changed, known: None, pages: None }; + let item = texture_upload::Item { res: res.clone(), src: mem.as_ptr() as usize, tex, states, changed, known: None, pages: None, own_tiles: None }; let (failed, job, _) = own_work(|| texture_upload::submit(dev, queue, &[item]))?; texture::wait(dev, queue)?; job.into_iter().for_each(texture_upload::give_back); @@ -3997,7 +4037,10 @@ fn publish_download(download: &ReadyDownload) -> Result { let mut table = TEXTURES.lock().unwrap(); let Some(entry) = table.by_res.get_mut(&download.res) else { return Ok(true) }; if !download_current(entry, download.generation, download.target, &download.writes) { return Ok(true) } - if !unsafe { write_changed_pages(download.target, ¤t, &console) } { return Ok(false) } + // (a capped view (`XCL_PAIR_PAGES=1`) ends at its cap: its layout past it is the next texture's + // memory, and its tiles there are the extra pages it shares with the one it is capped to) + let mine = entry.extent().min(size); + if !unsafe { write_changed_pages(download.target, ¤t[..mine], &console[..mine]) } { return Ok(false) } let n = subresource_count(&entry.tex); if entry.gpu_writers.len() != n { entry.gpu_writers = vec![entry.gpu_writers.first().copied().flatten(); n]; @@ -4297,14 +4340,19 @@ pub(super) mod tests { fn r8_item(texture: &ID3D12Resource, value: u8) -> (texture_upload::Item, Vec) { let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 61, 1)).unwrap()); let mem = vec![value; tex.size() as usize]; - (texture_upload::Item { res: texture.clone(), src: mem.as_ptr() as usize, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], changed: None, known: None, pages: None }, mem) + (texture_upload::Item { res: texture.clone(), src: mem.as_ptr() as usize, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], changed: None, known: None, pages: None, own_tiles: None }, mem) } unsafe fn read_r8(dev: &ID3D12Device, queue: &ID3D12CommandQueue, texture: &ID3D12Resource) -> Vec { + read_sub(dev, queue, texture, 0) + } + + /// The bytes of subresource `sub` of `texture`, row after row. + unsafe fn read_sub(dev: &ID3D12Device, queue: &ID3D12CommandQueue, texture: &ID3D12Resource, sub: u32) -> Vec { own_work(|| { let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); - let mut total = 0; - dev.GetCopyableFootprints(&texture.GetDesc(), 0, 1, 0, Some(&mut footprint), None, None, Some(&mut total)); + let (mut total, mut rows, mut row_bytes) = (0, 0u32, 0u64); + dev.GetCopyableFootprints(&texture.GetDesc(), sub, 1, 0, Some(&mut footprint), Some(&mut rows), Some(&mut row_bytes), Some(&mut total)); let mut readback = None; dev.CreateCommittedResource( &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, @@ -4316,12 +4364,12 @@ pub(super) mod tests { let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); let barrier = |before, after| D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, - Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(texture), Subresource: 0, StateBefore: before, StateAfter: after }) }, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(texture), Subresource: sub, StateBefore: before, StateAfter: after }) }, ..Default::default() }; list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint } }; - let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(texture), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(texture), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub } }; list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); list.Close().unwrap(); @@ -4331,15 +4379,31 @@ pub(super) mod tests { crate::gpu::fence::wait(&fence, 1, dev, None, 5_000).unwrap(); let mut data = std::ptr::null_mut(); readback.Map(0, None, Some(&mut data)).unwrap(); - let mut out = Vec::with_capacity(64 * 64); - for y in 0..64 { - out.extend_from_slice(std::slice::from_raw_parts((data as *const u8).add(footprint.Offset as usize + y * footprint.Footprint.RowPitch as usize), 64)); + let mut out = Vec::with_capacity(rows as usize * row_bytes as usize); + for y in 0..rows as usize { + out.extend_from_slice(std::slice::from_raw_parts((data as *const u8).add(footprint.Offset as usize + y * footprint.Footprint.RowPitch as usize), row_bytes as usize)); } readback.Unmap(0, None); out }) } + /// `texture` the one of the resources on its tiles the next work on `queue` uses (an aliasing + /// barrier): what one wrote is read back through the one that wrote it, after it. + unsafe fn alias_to(dev: &ID3D12Device, queue: &ID3D12CommandQueue, texture: &ID3D12Resource) { + own_work(|| { + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { pResourceBefore: std::mem::ManuallyDrop::new(None), pResourceAfter: std::mem::transmute_copy(texture) }) }, + ..Default::default() + }]); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + }) + } + /// The title queue's upload state for a test: none left by an earlier queue at the same address, /// and none left behind. struct DirectQueueUploads(usize); @@ -4832,7 +4896,7 @@ pub(super) 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, committed_bytes: 0, va: at, src: mirror_source(at), in_gpu_view: true, paged: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, written_call: 0, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0, known: Default::default(), target: false }; + let mut e = Entry { device: 0, committed_bytes: 0, va: at, src: mirror_source(at), in_gpu_view: true, paged: false, tex, cap: None, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, written_call: 0, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0, known: Default::default(), target: false }; assert_eq!(e.src, 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); @@ -4957,7 +5021,7 @@ pub(super) mod tests { let res = 0x7E57_0000_5000usize; let known: texture_upload::Known = Default::default(); texture_upload::all_sent(&known, gpu, PAGE); - let e = Entry { device: 0, va: gpu, src: gpu, in_gpu_view: true, paged: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, written_call: 0, placed: false, unmapped: false, generation: 0, known: Arc::clone(&known), target: false, committed_bytes: 0, gpu_writers: Vec::new(), cpu_backed: true }; + let e = Entry { device: 0, va: gpu, src: gpu, in_gpu_view: true, paged: true, tex, cap: None, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, written_call: 0, placed: false, unmapped: false, generation: 0, known: Arc::clone(&known), target: false, committed_bytes: 0, gpu_writers: Vec::new(), cpu_backed: true }; TEXTURES.lock().unwrap().insert(res, e); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let state = || TEXTURES.lock().unwrap().by_res.get(&res).map(|e| (e.gpu_written, e.written_call)).unwrap(); @@ -5305,7 +5369,7 @@ pub(super) mod tests { 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; - static TEST_LOCK: Mutex<()> = Mutex::new(()); + pub(in crate::hle::d3d12x) static TEST_LOCK: Mutex<()> = Mutex::new(()); #[test] fn gpu_owned_metadata_accepts_exact_colour_layouts_only() { @@ -5378,6 +5442,7 @@ pub(super) mod tests { src: 0x7E57_1000_0000, in_gpu_view: false, tex: Arc::clone(tex), + cap: None, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, @@ -5542,7 +5607,7 @@ pub(super) mod tests { assert_eq!(subresource_count(&tex), 6); // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it let (res, other) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize); - TEXTURES.lock().unwrap().insert(res, Entry { device: 0, committed_bytes: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, paged: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, written_call: 0, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0, known: Default::default(), target: false }); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, committed_bytes: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, paged: false, tex, cap: None, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, written_call: 0, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0, known: Default::default(), target: false }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().by_res.get(&res).unwrap().states.clone(); let e1 = capture_transitions(&[(res, ALL, SRV), (other, ALL, D3D12_RESOURCE_STATE_RENDER_TARGET), (res, 4, D3D12_RESOURCE_STATE_COPY_SOURCE)]); @@ -5794,6 +5859,7 @@ pub(super) mod tests { src: 0x1000, in_gpu_view: false, tex: Arc::clone(&tex), + cap: None, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written, @@ -5856,6 +5922,7 @@ pub(super) mod tests { src: va, in_gpu_view: false, tex: Arc::clone(&tex), + cap: None, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, @@ -6078,6 +6145,7 @@ pub(super) mod tests { in_gpu_view: false, paged: false, tex: Arc::clone(tex), + cap: None, states: vec![D3D12_RESOURCE_STATE_COMMON], pending, gpu_written: false, @@ -6123,6 +6191,374 @@ pub(super) mod tests { assert!(!tbl.by_res.contains_key(&10) && !tbl.by_res.contains_key(&11) && tbl.by_res.contains_key(&12)); } + /// `XCL_PAIR_PAGES=1`: a 1280x720 R9G9B9E5 view placed over a live R32_UINT one is 0x3c0000 + /// bytes by XG, the title's next resource starts 0x384000 on; the view's range is capped to the + /// pages it owns, so that neighbour does not supersede (and unmap) it. + #[test] + fn capped_placed_view_is_not_superseded_by_its_neighbour() { + let f67 = Arc::new(xg::Texture::new(&console_desc(3, 1280, 720, 1, 1, 67, 0x2)).unwrap()); + let f42 = Arc::new(xg::Texture::new(&console_desc(3, 1280, 720, 1, 1, 42, 0x102)).unwrap()); + assert_eq!((f67.size(), f42.size()), (0x3c_0000, 0x38_4000)); + let entry = |va: usize, tex: &Arc, cap: Option| Entry { + device: 0, + committed_bytes: 0, + va, + src: va, + in_gpu_view: false, + paged: false, + tex: Arc::clone(tex), + cap, + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: true, + gpu_written: false, + written_call: 0, + gpu_writers: Vec::new(), + cpu_backed: true, + placed: true, + unmapped: false, + generation: 0, + known: Default::default(), + target: false, + }; + let va = 0x1_0700_0000; + // uncapped: the neighbour's range starts inside the view's, which is unmapped + let mut tbl = Table::new(); + assert_eq!(tbl.insert(1, entry(va, &f67, None)), (1, vec![])); + assert_eq!(tbl.insert(2, entry(va + 0x38_4000, &f42, None)).1, vec![1]); + // capped to the live texture's size: nothing to unmap, both stay active + let mut tbl = Table::new(); + assert_eq!(tbl.insert(1, entry(va, &f67, Some(0x38_4000))), (1, vec![])); + assert_eq!(tbl.insert(2, entry(va + 0x38_4000, &f42, None)), (1, vec![])); + assert!(tbl.by_res.contains_key(&1) && tbl.by_res.contains_key(&2) && tbl.shadowed.is_empty()); + assert!(!tbl.by_res[&1].unmapped); + // the cap is the range the entry owns: it still covers its own pages, not the neighbour's + assert_eq!(tbl.overlapping(va + 0x38_3000, 0x1000), vec![(1, va)]); + assert_eq!(tbl.overlapping(va + 0x38_4000, 0x1000), vec![(2, va + 0x38_4000)]); + // a write to the neighbour's first page is in a source piece of the view (`touched_by` + // names it), but not on the memory the view owns: it does not send the view up again, + // and a partial upload of the view does not take that page + let (own, next, last) = (va + 0x38_3000, va + 0x38_4000, va + 0x3b_f000); + assert!(tbl.touched_by(&[next]).contains(&1)); + assert!(!tbl.by_res[&1].written_in(&[next, last], 0x1000), "the neighbour's pages"); + assert!(tbl.by_res[&1].written_in(&[own, next], 0x1000), "its own last page"); + assert!(entry(va, &f67, None).written_in(&[next], 0x1000), "no cap: all of its size"); + assert_eq!(dirty_on(&[va - 0x1000, own, next, last], 0x1000, va, tbl.by_res[&1].extent()), [own]); + assert_eq!(dirty_on(&[va - 0x1000, own, next, last], 0x1000, va, 0x3c_0000), [own, next, last]); + } + + /// `XCL_PAIR_PAGES=1`: the fingerprint of a capped view whose memory is not watched covers + /// the memory it owns. What the title writes past the cap (its next texture) does not queue + /// the view for a whole upload; a write below the cap does. + #[test] + fn a_capped_views_fingerprint_ends_at_its_cap() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + // (software adapter only: the resource only gives the Due its key) + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Ok(warp) = factory.EnumWarpAdapter::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let mut dev: Option = None; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 0x1_0000, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + let r = r.unwrap(); + let res = r.as_raw() as usize; + let tex = Arc::new(xg::Texture::new(&console_desc(3, 256, 256, 1, 1, 28, 0x109)).unwrap()); + let size = tex.size() as usize; + let cap = size - 0x1_0000; + let mut backing = vec![0u8; size]; + let va = backing.as_ptr() as usize; + let e = Entry { device: 0, committed_bytes: 0, va, src: va, in_gpu_view: false, paged: false, tex: Arc::clone(&tex), cap: Some(cap), states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, written_call: 0, gpu_writers: Vec::new(), cpu_backed: true, placed: true, unmapped: false, generation: 0, known: Default::default(), target: false }; + let (extent, generation) = { + let mut t = TEXTURES.lock().unwrap(); + let delta = t.insert(res, e).0; + adjust_pending(delta); + (t.by_res[&res].extent(), t.by_res[&res].generation) + }; + // the whole upload at frame 0 sets the baseline, through the extent `refresh_parts` gives + let due = Due { res: r.clone(), device: 0, src: va, extent, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], known: Default::default(), whole: true, again: texture_upload::Change::None, target: false, pages: None, generation }; + seed_stream_recheck(&[due], &[], 0); + let pending = || TEXTURES.lock().unwrap().by_res[&res].pending; + // (past the cap, in the end slice of a whole-size fingerprint) + backing[size - 16] = 0xCD; + recheck_streamed_unwatched_at(&[], STREAM_RECHECK_MILESTONES[0]); + let (queued, stage) = (pending(), STREAM_RECHECK.lock().unwrap().get(&res).map(|s| s.stage)); + backing[cap - 16] = 0xCD; + recheck_streamed_unwatched_at(&[], STREAM_RECHECK_MILESTONES[1]); + let queued_below = pending(); + if queued || queued_below { + TEXTURES.lock().unwrap().by_res.get_mut(&res).unwrap().pending = false; + PENDING.fetch_sub(1, Ordering::Relaxed); + } + STREAM_RECHECK.lock().unwrap().remove(&res); + forget(res); + assert!(!queued, "a write past the cap is not a write to the view"); + assert_eq!(stage, Some(1), "and its schedule moves on"); + assert!(queued_below, "a write below the cap queues it"); + } + } + + /// `XCL_PAIR_PAGES=1`, on the GPU: an R32_UINT UAV `written` (`written_bytes(dev)` on the + /// console; None: the adapter makes no such texture) and a sampled view placed at one address, the view capped to the written one. + /// `written` gets 0x77 in all of its layout, then the registered view's first upload, a whole one, + /// goes through `upload_all` from memory full of 0x11; `check` gets `written` and the view's + /// extent and own tiles. + unsafe fn capped_view_first_upload(pc: [D3D12_RESOURCE_DESC; 2], console: [[u8; 0x38]; 2], written_bytes: impl FnOnce(&ID3D12Device) -> Option, check: impl FnOnce(&ID3D12Device, &ID3D12CommandQueue, &ID3D12Resource, &ID3D12Resource, Option, Option)) { + use super::super::vram; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + if !vram::tier2(&dev) { + return crate::gpu::recomp::runner::skip_test("no tier-2 reserved resources"); + } + 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; + let va = 0x12_3c00_0000usize; + let place = |d: &D3D12_RESOURCE_DESC, bytes: u64, owned: bool| { + let mut p = std::ptr::null_mut(); + let hr = vram::place_on_pages(&dev, dev.as_raw(), va, d, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), Some(bytes), owned, false, true, riid, &mut p); + (hr.is_some_and(|hr| hr >= 0) && !p.is_null()).then(|| ID3D12Resource::from_raw(p)) + }; + let (written_tex, view_tex) = (Arc::new(xg::Texture::new(&console[0]).unwrap()), Arc::new(xg::Texture::new(&console[1]).unwrap())); + let Some(written_bytes) = written_bytes(&dev) else { + return crate::gpu::recomp::runner::skip_test("this adapter makes no reserved texture of this shape"); + }; + let written = place(&pc[0], written_bytes, true); + let view = place(&pc[1], view_tex.size(), false); + let (Some(written), Some(view)) = (written, view) else { + return crate::gpu::recomp::runner::skip_test("reserved textures not available"); + }; + // (the switch for this test only, off again when an assert below fails) + struct PairPages; + impl Drop for PairPages { + fn drop(&mut self) { + super::super::vram::PAIR_PAGES_FOR_TEST.store(false, Ordering::Relaxed); + } + } + vram::PAIR_PAGES_FOR_TEST.store(true, Ordering::Relaxed); + let on = PairPages; + let registered = register(dev.as_raw(), view.as_raw(), va, &console[1], D3D12_RESOURCE_STATE_COMMON); + let extent = TEXTURES.lock().unwrap().by_res.get(&(view.as_raw() as usize)).map(|e| e.extent()); + let own = extent.and_then(|extent| own_tiles_of(&view, extent, &view_tex)); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let _queue_uploads = DirectQueueUploads::new(&queue); + // what the GPU wrote, then the view's first upload as a submit sends it + let written_mem = vec![0x77u8; written_tex.size() as usize]; + let item = texture_upload::Item { res: written.clone(), src: written_mem.as_ptr() as usize, tex: written_tex, states: vec![D3D12_RESOURCE_STATE_COMMON], changed: None, known: None, pages: None, own_tiles: None }; + let wrote = own_work(|| submit_on(&dev, &queue, &[item])); + let view_mem = vec![0x11u8; view_tex.size() as usize]; + if let Some(extent) = extent.filter(|_| wrote.is_ok()) { + alias_to(&dev, &queue, &view); + let due = Due { res: view.clone(), device: dev.as_raw() as usize, src: view_mem.as_ptr() as usize, extent, tex: view_tex, states: vec![D3D12_RESOURCE_STATE_COMMON], known: Default::default(), whole: true, again: texture_upload::Change::None, target: false, pages: None, generation: 0 }; + upload_all(vec![due], &[], 0x1000, Some(&queue)); + } + drop(on); + forget(view.as_raw() as usize); + registered.unwrap(); + wrote.unwrap(); + check(&dev, &queue, &written, &view, extent, own); + } + + /// `XCL_PAIR_PAGES=1`, on the GPU: a 1280x720 R9G9B9E5 view capped to the R32_UINT texture it is + /// placed over owns 57 of its 60 tiles; tiles 57..59 are the written texture's last ones (the + /// extra pages they share). The view's first upload, a whole one, stops at its cap and leaves + /// the written texels there. + #[test] + fn gpu_a_capped_views_first_upload_leaves_the_tiles_past_its_cap() { + 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 windows::Win32::Graphics::Dxgi::Common::*; + let desc = |format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 1280, Height: 720, DepthOrArraySize: 1, MipLevels: 1, Format: format, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Flags: flags, ..Default::default() }; + let pc = [desc(DXGI_FORMAT_R32_UINT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), desc(DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_RESOURCE_FLAG_NONE)]; + let console = [console_desc(3, 1280, 720, 1, 1, 42, 0x102), console_desc(3, 1280, 720, 1, 1, 67, 0x2)]; + unsafe { + capped_view_first_upload(pc, console, |_| Some(0x38_4000), |dev, queue, written, view, extent, own| { + assert_eq!((extent, own), (Some(0x38_4000), Some(57)), "the view owns the written texture's pages"); + // (the view's upload through the view, then all of it through the written texture, + // each after an aliasing barrier) + let uploaded = read_r8(dev, queue, view); + alias_to(dev, queue, written); + let texels = read_r8(dev, queue, written); + let mut shape = D3D12_TILE_SHAPE::default(); + dev.GetResourceTiling(written, None, None, Some(&mut shape), None, 0, std::ptr::null_mut()); + let (tw, th) = (shape.WidthInTexels as usize, shape.HeightInTexels as usize); + let across = 1280usize.div_ceil(tw); + assert_eq!((texels.len(), uploaded.len()), (1280 * 720 * 4, 1280 * 720 * 4)); + let (mut mine, mut shared, mut past) = (0usize, 0usize, 0usize); + for (i, (b, u)) in texels.chunks_exact(4).zip(uploaded.chunks_exact(4)).enumerate() { + let tile = (i / 1280 / th) * across + (i % 1280) / tw; + if tile < 57 && u != [0x11; 4] { + mine += 1; + } + if tile < 57 && b != [0x11; 4] { + shared += 1; + } + if tile >= 57 && b != [0x77; 4] { + past += 1; + } + } + assert_eq!(past, 0, "the tiles past the cap keep the written texels"); + assert_eq!(mine, 0, "the view's own tiles get its upload"); + // (the title's case: both 32 bpp on the same standard tiles, read through the other) + assert_eq!(shared, 0, "the written texture reads the view's upload on the view's own tiles"); + }); + } + } + + /// `XCL_PAIR_PAGES=1`, on the GPU: a 256x256 R8G8B8A8 array of 2 slices and 9 mips, capped to an + /// R32_UINT one of the same shape one tile into slice 1. Each slice has its own packed mips, at + /// the end of its run of tiles: slice 0's are the view's, slice 1's are past the cap (the extra + /// pages it shares with the written texture) and keep the written texels. + #[test] + fn gpu_a_capped_arrays_first_upload_stops_at_its_cap_in_a_later_slice() { + 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 windows::Win32::Graphics::Dxgi::Common::*; + let desc = |format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 256, Height: 256, DepthOrArraySize: 2, MipLevels: 9, Format: format, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Flags: flags, ..Default::default() }; + let pc = [desc(DXGI_FORMAT_R32_UINT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), desc(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)]; + let console = [console_desc(3, 256, 256, 2, 9, 42, 0x105), console_desc(3, 256, 256, 2, 9, 28, 0x105)]; + // (the tiles of a slice, and slice 0's packed mips) + let tiling = |dev: &ID3D12Device, res: &ID3D12Resource| { + let (mut total, mut packed) = (0u32, D3D12_PACKED_MIP_INFO::default()); + unsafe { dev.GetResourceTiling(res, Some(&mut total), Some(&mut packed), None, None, 0, std::ptr::null_mut()) }; + (total / 2, packed) + }; + let per_slice = std::cell::Cell::new(0u32); + unsafe { + // (the cap: one tile into slice 1; an adapter that reports tier 2 but refuses a reserved + // array with packed mips, as GitHub's runner does, gives E_INVALIDARG) + let cap = |dev: &ID3D12Device| { + let mut r: Option = None; + let tiled = D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, ..pc[1] }; + dev.CreateReservedResource(&tiled, D3D12_RESOURCE_STATE_COMMON, None, &mut r).ok()?; + per_slice.set(tiling(dev, &r?).0); + Some((per_slice.get() as u64 + 1) * 0x1_0000) + }; + capped_view_first_upload(pc, console, cap, |dev, queue, written, view, extent, own| { + let (n, packed) = tiling(dev, written); + assert_eq!((n, own, extent), (per_slice.get(), Some(n + 1), Some((n as usize + 1) * 0x1_0000)), "the view owns slice 0 and one tile of slice 1"); + assert!(packed.NumPackedMips > 0 && packed.NumStandardMips > 0, "mips from {} on packed", packed.NumStandardMips); + // (each read through the texture that wrote it: packed mips of two descriptions are + // not laid out alike) + for slice in 0..2u32 { + alias_to(dev, queue, if slice == 0 { view } else { written }); + for level in packed.NumStandardMips as u32..9 { + let texels = read_sub(dev, queue, if slice == 0 { view } else { written }, slice * 9 + level); + let (want, what) = if slice == 0 { (0x11, "slice 0's packed mips get the view's upload") } else { (0x77, "slice 1's packed mips are past the cap and keep the written texels") }; + assert!(!texels.is_empty() && texels.iter().all(|&b| b == want), "{what} (level {level}: {} of {} bytes are {want:#x}, first {:?})", texels.iter().filter(|&&b| b == want).count(), texels.len(), texels.first()); + } + } + }); + } + } + + /// `XCL_PAIR_PAGES=1`: a capped view whose tiles vram does not give (no `Target`) owns none, so + /// none of it goes up over the pages past its cap; an uncapped one owns all of its tiles. + #[test] + fn a_capped_view_without_its_tiles_owns_none() { + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let mut res: Option = None; + let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 1280, Height: 720, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R9G9B9E5_SHAREDEXP, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut res).unwrap(); + let res = res.unwrap(); + let tex = xg::Texture::new(&console_desc(3, 1280, 720, 1, 1, 67, 0x2)).unwrap(); + struct PairPages; + impl Drop for PairPages { + fn drop(&mut self) { + super::super::vram::PAIR_PAGES_FOR_TEST.store(false, Ordering::Relaxed); + } + } + super::super::vram::PAIR_PAGES_FOR_TEST.store(true, Ordering::Relaxed); + let _on = PairPages; + assert_eq!(own_tiles_of(&res, 0x38_4000, &tex), Some(0), "a capped view vram has no tiles for owns none"); + assert_eq!(own_tiles_of(&res, tex.size() as usize, &tex), None, "an uncapped one owns all of its tiles"); + } + } + + /// `XCL_PAIR_PAGES=1`, on the GPU: a capped view a list wrote is read back into the title's + /// memory up to its cap only; past it is the next texture's memory and keeps its bytes. + #[test] + fn gpu_a_capped_views_download_ends_at_its_cap() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let tex = Arc::new(xg::Texture::new(&console_desc(3, 256, 256, 1, 1, 61, 1)).unwrap()); + let size = tex.size() as usize; + let mut texture: Option = None; + let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 256, Height: 256, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut texture).unwrap(); + let texture = texture.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let _queue_uploads = DirectQueueUploads::new(&queue); + super::super::list_x::on_queue_create(queue.as_raw() as usize, dev.as_raw() as usize, D3D12_COMMAND_LIST_TYPE_DIRECT); + // what the GPU wrote: 0x22 + let wrote = vec![0x22u8; size]; + let item = texture_upload::Item { res: texture.clone(), src: wrote.as_ptr() as usize, tex: Arc::clone(&tex), states: vec![D3D12_RESOURCE_STATE_COMMON], changed: None, known: None, pages: None, own_tiles: None }; + own_work(|| submit_on(&dev, &queue, &[item])).unwrap(); + // the title's memory: the view up to its cap, then the next texture + let cap = size / 2; + let mut mem = vec![0xAAu8; size]; + let (res, src) = (texture.as_raw() as usize, mem.as_mut_ptr() as usize); + let generation = { + let mut t = TEXTURES.lock().unwrap(); + t.insert(res, Entry { device: dev.as_raw() as usize, committed_bytes: 0, va: 0x7E58_0000_0000, src, in_gpu_view: false, paged: false, tex, cap: Some(cap), states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, written_call: 0, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0, known: Default::default(), target: false }); + t.by_res[&res].generation + }; + let id = super::super::list_x::queue_identity(queue.as_raw() as usize).unwrap(); + publish_gpu_writes(id, &[GpuWrite { res, generation, subresource: 0 }]); + let prepared = prepare_downloads(queue.as_raw()); + let ready = match submit_prepared_downloads(queue.as_raw(), prepared) { + Ok(ready) => ready, + Err(_) => Vec::new(), + }; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 5_000).unwrap(); + let published = ready.iter().map(publish_download).collect::>(); + ready.iter().for_each(unschedule); + forget(res); + super::super::list_x::on_queue_release(queue.as_raw() as usize); + assert_eq!(published.len(), 1, "one download"); + assert!(matches!(published[0], Ok(true)), "it is published"); + assert!(mem[..cap].iter().all(|&b| b == 0x22), "the view's memory gets what the GPU wrote"); + assert!(mem[cap..].iter().all(|&b| b == 0xAA), "the memory past its cap keeps its bytes"); + } + } + /// 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 @@ -6487,6 +6923,7 @@ pub(super) mod tests { src: 0x20_0000, in_gpu_view: false, tex: Arc::clone(&tex), + cap: None, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: !cpu_backed, @@ -6536,6 +6973,7 @@ pub(super) mod tests { in_gpu_view: false, paged: false, tex: Arc::clone(&tex), + cap: None, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, @@ -6556,6 +6994,7 @@ pub(super) mod tests { in_gpu_view: false, paged: false, tex: Arc::clone(&tex), + cap: None, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, @@ -6668,6 +7107,7 @@ pub(super) mod tests { in_gpu_view: false, paged: false, tex: Arc::clone(&tex), + cap: None, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, @@ -6691,6 +7131,7 @@ pub(super) mod tests { res: res.clone(), device: 0, src: va, + extent: size, tex: Arc::clone(&tex), states: vec![D3D12_RESOURCE_STATE_COMMON], known: Default::default(), @@ -6781,6 +7222,7 @@ pub(super) mod tests { in_gpu_view: false, paged: false, tex: Arc::clone(&tex), + cap: None, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, @@ -6804,6 +7246,7 @@ pub(super) mod tests { res: res.clone(), device: 0, src: va, + extent: size, tex: Arc::clone(&tex), states: vec![D3D12_RESOURCE_STATE_COMMON], known: Default::default(), diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 8755ac4950..42405b7ed9 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -701,6 +701,29 @@ pub(super) fn is_placed_texture(resource: usize) -> bool { PLACED_TEXTURES.lock().unwrap().as_ref().is_some_and(|textures| textures.contains(&resource)) } +/// The console bytes a placed sampled texture owns pages for when `XCL_PAIR_PAGES=1` capped them +/// below its own size (`pair_bytes`, kept in its `Target`): `title_textures` keeps the same +/// extent. None for a texture no pair capped, whatever size it was placed with; a texture the GPU +/// writes is never capped (`pair_partners`). +pub(super) fn pair_capped_bytes(resource: usize) -> Option { + if !pair_pages() { + return None; + } + let g = PAGES.lock().unwrap(); + g.values().flatten().find_map(|pages| pages.targets.get(&resource)).filter(|t| t.capped).and_then(|t| t.console_bytes) +} + +/// The tiles `[0, n)` a texture `pair_capped_bytes` capped has pages of its own for (`owned_pages`): +/// its tiles after them are the extra pages it shares with the texture the title placed after it, +/// and its uploads stop before them (`texture_upload::Item::own_tiles`). None for one no pair capped. +pub(super) fn pair_capped_tiles(resource: usize) -> Option { + if !pair_pages() { + return None; + } + let g = PAGES.lock().unwrap(); + let t = g.values().flatten().find_map(|pages| pages.targets.get(&resource)).filter(|t| t.capped)?; + owned_pages(t.va, t.console_bytes, t.total as usize).map(|(_, n)| n as u32) +} #[cfg(test)] pub(super) fn forget(resource: usize) { @@ -1068,6 +1091,10 @@ struct Target { /// sampled texture placed in its memory is capped to (`pair_bytes`). None: no texture is /// capped to this one's pages pair: Option, + /// `XCL_PAIR_PAGES=1`: `console_bytes` is not the size the texture was placed with but a + /// written one's in its memory (`pair_bytes`), which `title_textures` keeps as its extent + /// (`pair_capped_bytes`) + capped: bool, } /// The tiles of a texture whose levels get video memory when an upload first has texels for @@ -2288,7 +2315,7 @@ fn pair_pages() -> bool { /// `pair_pages` for a test (under `VRAM_TEST_LOCK`) #[cfg(test)] -static PAIR_PAGES_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +pub(super) static PAIR_PAGES_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// The textures of `targets` a sampled one placed at `va` with `total` tiles can be paired with /// (`pair_bytes`), each with its size on the console: the mapped ones at the same address and @@ -2325,7 +2352,7 @@ fn pair_bytes(partners: &[(usize, u64)], current: impl Fn(usize) -> bool, consol /// `pair`: `XCL_PAIR_PAGES=1` – a sampled texture is capped to a written one in its memory /// (`pair_bytes`); for a texture the GPU writes, also that `console_bytes` is its known size. #[allow(clippy::too_many_arguments)] -unsafe fn place_on_pages( +pub(super) unsafe fn place_on_pages( dev: &ID3D12Device, this: *mut c_void, va: usize, @@ -2423,6 +2450,7 @@ unsafe fn place_on_pages( // (the size kept in the `Target` is the capped one: lazy levels, `unmap_levels` and the // range handed to `placements` go by the same pages as `bind`) let writer = gpu_owned(desc.Flags.0 as u32); + let given_bytes = console_bytes; let console_bytes = if pair { let partners = match PAGES.lock().unwrap().get(&dev_key) { Some(Some(pages)) => pair_partners(&pages.targets, va, total, writer), @@ -2442,6 +2470,7 @@ unsafe fn place_on_pages( } else { console_bytes }; + let capped = console_bytes != given_bytes; let pair = if pair && writer { console_bytes } else { None }; let texels = (!require_aligned && super::memory_report::enabled()).then(|| TexelMeta::from_desc(desc, levels.is_none())); let bound = { @@ -2452,11 +2481,11 @@ unsafe fn place_on_pages( LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); record_texel_insert(&texels); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels, texels, recycle: recycle_key, pair }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels, texels, recycle: recycle_key, pair, capped }); true } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { record_texel_insert(&texels); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None, texels, recycle: recycle_key, pair }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None, texels, recycle: recycle_key, pair, capped }); true } else { false @@ -3027,7 +3056,7 @@ pub fn page_bytes() -> (usize, usize) { } /// Heaps of every kind of resource in one (resource heap tier 2) – else no arenas. -fn tier2(dev: &ID3D12Device) -> bool { +pub(super) fn tier2(dev: &ID3D12Device) -> bool { let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); unsafe { dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut o as *mut _ as *mut c_void, std::mem::size_of_val(&o) as u32).is_ok() && o.ResourceHeapTier.0 >= 2 } } @@ -4209,6 +4238,7 @@ mod tests { texels: None, recycle: None, pair: None, + capped: false, }; assert_eq!(target_page_keys(&target), (vec![0x1000], vec![(0x2000, 1)])); @@ -4894,7 +4924,7 @@ mod tests { /// A placed texture as `place_on_pages` keeps it; `pair`: its known size if the GPU writes it. fn pair_target(va: usize, total: u32, console_bytes: Option, mapped: bool, pair: Option) -> Target { - Target { va, console_bytes, total, mapped, used: Vec::new(), used_extra: Vec::new(), levels: None, texels: None, recycle: None, pair } + Target { va, console_bytes, total, mapped, used: Vec::new(), used_extra: Vec::new(), levels: None, texels: None, recycle: None, pair, capped: false } } /// `pair_bytes` of a sampled texture, every partner in `targets` a current placement. @@ -4980,6 +5010,66 @@ mod tests { assert_eq!(paired(&targets, va, 60, Some(0x3c_0000)), Some(0x3c_0000)); } + /// `register` takes the extent a view owns from `pair_capped_bytes` (the `Target` the pair cap + /// shrank), so its range in `title_textures` stops where the written texture's pages do. + /// Without the cap passed through, the view's range (0x3c0000) covers the neighbour's first + /// bytes. + #[test] + fn gpu_register_takes_the_cap_from_the_pair() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = super::super::title_textures::tests::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + if !tier2(&dev) { + return crate::gpu::recomp::runner::skip_test("no tier-2 reserved resources"); + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let sample = DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }; + let tex = |format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 1280, Height: 720, DepthOrArraySize: 1, MipLevels: 1, Format: format, SampleDesc: sample, Flags: flags, ..Default::default() }; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let va = 0x12_3b00_0000usize; + let place_one = |va: usize, d: &D3D12_RESOURCE_DESC, bytes: u64, owned: bool| { + let mut p = std::ptr::null_mut(); + let state = D3D12_RESOURCE_STATE_COPY_DEST.0 as u32; + let hr = place_on_pages(&dev, dev.as_raw(), va, d, state, std::ptr::null(), Some(bytes), owned, false, true, riid, &mut p); + (hr.is_some_and(|hr| hr >= 0) && !p.is_null()).then(|| ID3D12Resource::from_raw(p)) + }; + let written = place_one(va, &tex(DXGI_FORMAT_R32_UINT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), 0x38_4000, true); + let view = place_one(va, &tex(DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_RESOURCE_FLAG_NONE), 0x3c_0000, false); + // (a sampled texture with no written one in its memory, placed with less than XG's size) + let alone = place_one(va + 0x100_0000, &tex(DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_RESOURCE_FLAG_NONE), 0x38_4000, false); + let (Some(written), Some(view), Some(alone)) = (written, view, alone) else { + return crate::gpu::recomp::runner::skip_test("reserved textures not available"); + }; + // (the switch for this test only, off again when an assert below fails) + struct PairPages; + impl Drop for PairPages { + fn drop(&mut self) { + PAIR_PAGES_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + } + } + PAIR_PAGES_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + let on = PairPages; + assert_eq!(pair_capped_bytes(view.as_raw() as usize), Some(0x38_4000)); + assert_eq!(pair_capped_bytes(written.as_raw() as usize), None, "a written texture is not capped"); + assert_eq!(pair_capped_bytes(alone.as_raw() as usize), None, "the size a texture was placed with is not a cap"); + let console = super::super::title_textures::tests::console_desc(3, 1280, 720, 1, 1, 67, 0x2); + let registered = super::super::title_textures::register(dev.as_raw(), view.as_raw(), va, &console, D3D12_RESOURCE_STATE_COPY_DEST); + drop(on); + let at = |off: usize| super::super::title_textures::overlapping(va + off, 0x1000).into_iter().filter(|&(r, _)| r == view.as_raw() as usize).count(); + let (inside, past) = (at(0x38_3000), at(0x38_4000)); + super::super::title_textures::forget(view.as_raw() as usize); + registered.unwrap(); + assert_eq!(inside, 1, "the view's range covers its own pages"); + assert_eq!(past, 0, "and stops where the written texture's pages do"); + } + } + /// On the GPU, through `place_on_pages`: a written texture made after a smaller sampled one at /// its address keeps its own size, and a sampled one made after both is capped to the written /// one, not to the first sampled one. A texture placed inside the written one then supersedes