From 42efa87bbd34b8b8fe0e0bf64b0c96c39f9e6660 Mon Sep 17 00:00:00 2001 From: Pipodi Date: Sun, 29 Nov 2026 00:55:05 +0100 Subject: [PATCH 1/4] 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 3311c24ede..e650534272 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); @@ -1145,6 +1146,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 @@ -2373,9 +2380,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, @@ -2387,6 +2440,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 { @@ -2471,6 +2525,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(); @@ -2480,12 +2557,12 @@ 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) { pages.keep_pools(dev, pages_role(desc.Flags.0 as u32), &used, &used_extra); 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 @@ -3091,7 +3168,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 @@ -3306,13 +3383,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); } } @@ -4277,6 +4355,7 @@ mod tests { levels: Some(levels), texels: None, recycle: None, + pair: None, }; assert_eq!(target_page_keys(&target), (vec![0x1000], vec![(0x2000, 1)])); @@ -4960,6 +5039,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 @@ -5678,6 +6020,7 @@ mod tests { Some(64 * 1024), false, false, + false, riid, &mut ppv, )?; From b383ccfb04c4dfb416df7afd3175952c5cb944e7 Mon Sep 17 00:00:00 2001 From: Pipodi Date: Sun, 29 Nov 2026 00:55:13 +0100 Subject: [PATCH 2/4] 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). The hashes of its pages are still those of the whole layout. 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). 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 | 388 ++++++++++++++++++-- crates/xcl/src/hle/d3d12x/vram.rs | 102 ++++- 3 files changed, 514 insertions(+), 43 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..4a8757f353 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,13 @@ 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. +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)).flatten() +} + /// 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 +2990,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); @@ -4297,14 +4336,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 +4360,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,9 +4375,9 @@ 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 @@ -4832,7 +4876,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 +5001,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 +5349,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 +5422,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 +5587,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 +5839,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 +5902,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 +6125,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 +6171,273 @@ 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) 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) -> u64, check: impl FnOnce(&ID3D12Device, &ID3D12CommandQueue, &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 written = place(&pc[0], written_bytes(&dev), 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()) { + 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, 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, |_| 0x38_4000, |dev, queue, written, extent, own| { + assert_eq!((extent, own), (Some(0x38_4000), Some(57)), "the view owns the written texture's pages"); + 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(), 1280 * 720 * 4); + let (mut mine, mut past) = (0usize, 0usize); + for (i, b) in texels.chunks_exact(4).enumerate() { + let tile = (i / 1280 / th) * across + (i % 1280) / tw; + if tile < 57 && b != [0x11; 4] { + mine += 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"); + }); + } + } + + /// `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) + 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).unwrap(); + per_slice.set(tiling(dev, &r.unwrap()).0); + (per_slice.get() as u64 + 1) * 0x1_0000 + }; + capped_view_first_upload(pc, console, cap, |dev, queue, written, 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); + for slice in 0..2u32 { + for level in packed.NumStandardMips as u32..9 { + let texels = read_sub(dev, queue, 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})"); + } + } + }); + } + } + /// 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 +6802,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 +6852,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 +6873,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 +6986,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 +7010,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 +7101,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 +7125,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 e650534272..140b4242e2 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) { @@ -1152,6 +1175,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 @@ -2393,7 +2420,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 @@ -2430,7 +2457,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, @@ -2528,6 +2555,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), @@ -2547,6 +2575,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 = { @@ -2557,12 +2586,12 @@ 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) { pages.keep_pools(dev, pages_role(desc.Flags.0 as u32), &used, &used_extra); 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 @@ -3134,7 +3163,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 } } @@ -4356,6 +4385,7 @@ mod tests { texels: None, recycle: None, pair: None, + capped: false, }; assert_eq!(target_page_keys(&target), (vec![0x1000], vec![(0x2000, 1)])); @@ -5041,7 +5071,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. @@ -5127,6 +5157,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 From a07d74036f0b6a174194898ff8f7b3e3b4273f01 Mon Sep 17 00:00:00 2001 From: KDenKC <125705260+KDenKC@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:25:12 -0700 Subject: [PATCH 3/4] D3D12.X: XCL_CAST_LIST=1 makes a written R32_UINT texture read as R9G9B9E5 one texture The retail title packs light as R9G9B9E5 into R32_UINT textures its compute programs write, and samples the same memory through an R9G9B9E5 texture it places at the same address. On the console that is one memory; here the sampled texture is a PC texture of its own that nothing writes. With XCL_CAST_LIST=1, where the device has relaxed format casting (OPTIONS12), ID3D12Device10 and samples R9G9B9E5, a GPU-written R32_UINT 2D texture on the title's pages is made with CreateReservedResource2 and [R32_UINT, R9G9B9E5_SHAREDEXP] as its cast list (a texture the title gives a cast list of its own, device #127, with that list). A view the title makes of a texture at the same address, of the same shape, in another format of the list, is made on the written texture. Its read-only legacy states (not COMMON) also take the shader-resource states the list type has (DIRECT both, COMPUTE the non-pixel one, COPY none), on both sides of every transition. The views go with the written texture (console_heap::resource_gone); a recycled sampled texture is forgotten before it is parked. It is made only in the initial states whose layout is the same state (COMMON, RENDER_TARGET, UNORDERED_ACCESS, COPY_DEST); a refused create is made as before. Off by default. Tests: the matching and the state widening (cast_list), and a GPU test of the route itself in a child process with the debug layer on: one texture written as R32_UINT through a UAV and read through an R9G9B9E5 SRV, committed and reserved (tiles mapped on a second queue), every texel compared with a CPU decode. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/runner.rs | 3 + .../xcl/src/gpu/recomp/runner/cast_tests.rs | 264 +++++++++++++ crates/xcl/src/hle/d3d12x/cast_list.rs | 353 ++++++++++++++++++ crates/xcl/src/hle/d3d12x/device_x.rs | 3 + crates/xcl/src/hle/d3d12x/list_x.rs | 12 + crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 24 +- crates/xcl/src/hle/d3d12x/vram.rs | 25 ++ 8 files changed, 683 insertions(+), 2 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/runner/cast_tests.rs create mode 100644 crates/xcl/src/hle/d3d12x/cast_list.rs diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index e71ac1975a..b38f760435 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1984,3 +1984,6 @@ fn dispatch_with( Ok((out, ms)) } } + +#[cfg(test)] +mod cast_tests; diff --git a/crates/xcl/src/gpu/recomp/runner/cast_tests.rs b/crates/xcl/src/gpu/recomp/runner/cast_tests.rs new file mode 100644 index 0000000000..fb44f7fdd6 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/runner/cast_tests.rs @@ -0,0 +1,264 @@ +//! Can ONE texture be written as R32_UINT through a UAV and +//! read as R9G9B9E5_SHAREDEXP through an SRV, by relaxed format casting (OPTIONS12, a cast list +//! at creation on ID3D12Device10)? The retail title packs light that way and gives its own cast +//! list at creation. Two routes, as XCL creates textures: committed (CreateCommittedResource3) +//! and reserved (CreateReservedResource2, 64KB_UNDEFINED_SWIZZLE, its tiles mapped by a second +//! queue that the work waits for, as XCL's tile queue does). Every texel is compared bit for bit +//! with a CPU decode, and the debug layer (where it exists) must report no error. It runs in a +//! child process, so the debug layer stays out of the other tests. This is the route +//! `hle::d3d12x::cast_list` takes. + +use super::*; + +const CHILD: &str = "XCL_TEST_CAST_CHILD"; +const W: u32 = 256; +const H: u32 = 256; + +const SRC: &str = r#" +#define RS "DescriptorTable(UAV(u0), SRV(t0, flags = DATA_VOLATILE)), UAV(u1)" +RWTexture2D words : register(u0); +Texture2D light : register(t0); +RWByteAddressBuffer res : register(u1); +uint word(uint2 p) { return ((p.x * 2u + 1u) & 511u) | (((p.y * 2u + 3u) & 511u) << 9) | ((((p.x ^ p.y) * 5u) & 511u) << 18) | (((p.x + p.y) % 32u) << 27); } +[RootSignature(RS)] [numthreads(8, 8, 1)] void write(uint3 id : SV_DispatchThreadID) { words[id.xy] = word(id.xy); } +[RootSignature(RS)] [numthreads(8, 8, 1)] void read(uint3 id : SV_DispatchThreadID) { res.Store3((id.y * 256u + id.x) * 12u, asuint(light.Load(int3(id.xy, 0)).rgb)); } +"#; + +/// The packed word of texel (x, y), as the shader's `word`. +fn word(x: u32, y: u32) -> u32 { + ((x * 2 + 1) & 511) | (((y * 2 + 3) & 511) << 9) | ((((x ^ y) * 5) & 511) << 18) | (((x + y) % 32) << 27) +} + +/// R9G9B9E5_SHAREDEXP decoded: each 9-bit mantissa · 2^(exponent − 15 − 9), exact in f32. +fn decode(w: u32) -> [f32; 3] { + let scale = 2f32.powi((w >> 27) as i32 - 24); + [(w & 511) as f32 * scale, ((w >> 9) & 511) as f32 * scale, ((w >> 18) & 511) as f32 * scale] +} + +#[test] +fn decode_matches_the_format() { + assert_eq!(decode(1 | (15 + 9) << 27), [1.0, 0.0, 0.0]); + assert_eq!(decode(128 << 9 | 16 << 27), [0.0, 0.5, 0.0]); +} + +#[test] +fn gpu_one_texture_written_r32_uint_reads_as_r9g9b9e5_by_its_cast_list() { + if std::env::var_os(CHILD).is_some() { + return unsafe { child() }; + } + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "gpu::recomp::runner::cast_tests::gpu_one_texture_written_r32_uint_reads_as_r9g9b9e5_by_its_cast_list", "--nocapture", "--test-threads=1"]) + .env(CHILD, "1") + .output() + .unwrap(); + let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + for l in text.lines().filter(|l| l.contains("CAST") || l.contains("SKIPPED") || l.contains("panicked")) { + println!("{l}"); + } + if let Some(l) = text.lines().find(|l| l.contains("SKIPPED")) { + return skip_test(l.split("SKIPPED").nth(1).unwrap_or("").trim_start_matches(|c: char| !c.is_alphanumeric())); + } + assert!(out.status.success(), "the child failed:\n{text}"); +} + +unsafe fn child() { + let debug = crate::gpu::agility::enable_debug_layer().is_ok(); + let Ok(factory) = CreateDXGIFactory1::() else { return skip_test("no DXGI factory") }; + let Ok(adapter) = factory.EnumAdapterByGpuPreference::(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE) else { return skip_test("no GPU") }; + let Ok(dev) = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0) else { return skip_test("no GPU") }; + let name = adapter.GetDesc1().map(|d| String::from_utf16_lossy(&d.Description).trim_end_matches('\0').to_string()).unwrap_or_default(); + let mut o12 = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default(); + let queried = dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, &mut o12 as *mut _ as *mut std::ffi::c_void, std::mem::size_of_val(&o12) as u32).is_ok(); + println!( + "CAST adapter {name}, Agility {:?}, debug layer {}, OPTIONS12 {}: RelaxedFormatCastingSupported {}, EnhancedBarriersSupported {}", + crate::gpu::agility::loaded().map(|(v, _)| v), + if debug { "on" } else { "not available" }, + if queried { "answered" } else { "NOT answered" }, + o12.RelaxedFormatCastingSupported.as_bool(), + o12.EnhancedBarriersSupported.as_bool() + ); + let Ok(dev10) = dev.cast::() else { return skip_test("no ID3D12Device10") }; + if !o12.RelaxedFormatCastingSupported.as_bool() { + return skip_test("no relaxed format casting (OPTIONS12)"); + } + if let Err(why) = super::super::dxc::location() { + return skip_test(&format!("no DXC: {why}")); + } + for reserved in [false, true] { + let route = if reserved { "reserved (CreateReservedResource2, 64KB_UNDEFINED_SWIZZLE, tiles on a second queue)" } else { "committed (CreateCommittedResource3)" }; + match run(&dev, &dev10, reserved) { + Ok(()) => println!("CAST {route}: all {} texels bit-exact", W * H), + Err(why) => panic!("CAST {route}: {why} (device: {:?})", dev.GetDeviceRemovedReason()), + } + } + if debug { + let errors = debug_errors(&dev); + println!("CAST debug layer: {} error/corruption message(s){}", errors.len(), errors.iter().map(|m| format!("\n CAST {m}")).collect::()); + assert!(errors.is_empty(), "the debug layer reported errors"); + } + assert!(dev.GetDeviceRemovedReason().is_ok(), "the device was removed"); + println!("CAST no device removal"); +} + +/// The debug layer's error and corruption messages so far. +unsafe fn debug_errors(dev: &ID3D12Device) -> Vec { + let Ok(q) = dev.cast::() else { return Vec::new() }; + let mut out = Vec::new(); + for i in 0..q.GetNumStoredMessages() { + let mut len = 0usize; + if q.GetMessage(i, None, &mut len).is_err() || len == 0 { + continue; + } + let mut buf = vec![0u64; len.div_ceil(8)]; + let m = buf.as_mut_ptr() as *mut D3D12_MESSAGE; + if q.GetMessage(i, Some(m), &mut len).is_ok() && matches!((*m).Severity, D3D12_MESSAGE_SEVERITY_ERROR | D3D12_MESSAGE_SEVERITY_CORRUPTION) { + let text = (*m).pDescription; + out.push(if text.is_null() { String::new() } else { std::ffi::CStr::from_ptr(text as *const std::ffi::c_char).to_string_lossy().into_owned() }); + } + } + out +} + +unsafe fn transition(r: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: transmute_copy(r), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, StateBefore: before, StateAfter: after }), + }, + } +} + +unsafe fn buffer(dev: &ID3D12Device, bytes: u64, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES, flags: D3D12_RESOURCE_FLAGS) -> Result { + let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() }; + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).map_err(|e| e.to_string())?; + r.ok_or_else(|| "buffer".into()) +} + +/// One route: the texture made with its cast list, written as words, read as RGB9E5, compared. +unsafe fn run(dev: &ID3D12Device, dev10: &ID3D12Device10, reserved: bool) -> Result<(), String> { + let e = |x: windows::core::Error| x.to_string(); + let casts = [DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R9G9B9E5_SHAREDEXP]; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: W as u64, + Height: H, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: if reserved { D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE } else { D3D12_TEXTURE_LAYOUT_UNKNOWN }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(e)?; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; + let mut tex: Option = None; + // (kept alive with the texture: its tiles' memory, and the tile queue until the work is done) + let mut _heap: Option = None; + let mut _tile_queue: Option = None; + if reserved { + dev10.CreateReservedResource2(&desc, D3D12_BARRIER_LAYOUT_COMMON, None, None::<&ID3D12ProtectedResourceSession>, Some(&casts[..]), &mut tex).map_err(|x| format!("CreateReservedResource2: {x}"))?; + let tex = tex.as_ref().ok_or("no texture")?; + let mut tiles = 0u32; + dev.GetResourceTiling(tex, Some(&mut tiles), None, None, None, 0, std::ptr::null_mut()); + let hdesc = D3D12_HEAP_DESC { SizeInBytes: tiles as u64 * 65536, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, Flags: D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES }; + dev.CreateHeap(&hdesc, &mut _heap).map_err(|x| format!("CreateHeap: {x}"))?; + // (the tile queue: a queue of its own, the work's queue waits for its mapping) + let tq: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(e)?; + let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let region = D3D12_TILE_REGION_SIZE { NumTiles: tiles, UseBox: false.into(), ..Default::default() }; + let (flag, offset) = (D3D12_TILE_RANGE_FLAG_NONE, 0u32); + tq.UpdateTileMappings(tex, 1, Some(&coord), Some(®ion), _heap.as_ref(), 1, Some(&flag), Some(&offset), Some(&tiles), D3D12_TILE_MAPPING_FLAG_NONE); + tq.Signal(&fence, 1).map_err(e)?; + queue.Wait(&fence, 1).map_err(e)?; + _tile_queue = Some(tq); + println!("CAST reserved texture: {tiles} tiles mapped on the tile queue"); + } else { + let desc1 = D3D12_RESOURCE_DESC1 { + Dimension: desc.Dimension, + Alignment: 0, + Width: desc.Width, + Height: desc.Height, + DepthOrArraySize: 1, + MipLevels: 1, + Format: desc.Format, + SampleDesc: desc.SampleDesc, + Layout: desc.Layout, + Flags: desc.Flags, + SamplerFeedbackMipRegion: Default::default(), + }; + dev10 + .CreateCommittedResource3(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc1, D3D12_BARRIER_LAYOUT_COMMON, None, None::<&ID3D12ProtectedResourceSession>, Some(&casts[..]), &mut tex) + .map_err(|x| format!("CreateCommittedResource3: {x}"))?; + } + let tex = tex.ok_or("no texture")?; + let bytes = (W * H * 12) as u64; + let res = buffer(dev, bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)?; + let readback = buffer(dev, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE)?; + + let heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 2, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, ..Default::default() }).map_err(e)?; + let step = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let cpu = heap.GetCPUDescriptorHandleForHeapStart(); + let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_UINT, ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 } } }; + dev.CreateUnorderedAccessView(&tex, None::<&ID3D12Resource>, Some(&uav), cpu); + let srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R9G9B9E5_SHAREDEXP, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, PlaneSlice: 0, ResourceMinLODClamp: 0.0 } }, + }; + dev.CreateShaderResourceView(&tex, Some(&srv), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu.ptr + step }); + + let write = super::super::dxc::compile(SRC, "write", "cs_6_6", &[])?; + let read = super::super::dxc::compile(SRC, "read", "cs_6_6", &[])?; + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &write).map_err(|x| format!("root signature: {x}"))?; + let pso = |cs: &[u8]| -> Result { + dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as _, BytecodeLength: cs.len() }, ..Default::default() }).map_err(|x| x.to_string()) + }; + let (pw, pr) = (pso(&write)?, pso(&read)?); + + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(e)?; + // (the SRV range is DATA_VOLATILE: the table is bound while the texture is still written) + let bind = || { + list.SetComputeRootDescriptorTable(0, heap.GetGPUDescriptorHandleForHeapStart()); + list.SetComputeRootUnorderedAccessView(1, res.GetGPUVirtualAddress()); + }; + list.SetDescriptorHeaps(&[Some(heap.clone())]); + list.SetComputeRootSignature(&rs); + list.ResourceBarrier(&[transition(&tex, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + bind(); + list.SetPipelineState(&pw); + list.Dispatch(W / 8, H / 8, 1); + list.ResourceBarrier(&[transition(&tex, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]); + bind(); + list.SetPipelineState(&pr); + list.Dispatch(W / 8, H / 8, 1); + list.ResourceBarrier(&[transition(&res, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyResource(&readback, &res); + list.Close().map_err(e)?; + queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]); + queue.Signal(&fence, 2).map_err(e)?; + crate::gpu::fence::wait(&fence, 2, dev, None, 10_000).map_err(|x| format!("{x}"))?; + + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).map_err(e)?; + let got = std::slice::from_raw_parts(p as *const u32, (W * H * 3) as usize).to_vec(); + readback.Unmap(0, None); + let mut bad = Vec::new(); + for y in 0..H { + for x in 0..W { + let want = decode(word(x, y)).map(f32::to_bits); + let at = ((y * W + x) * 3) as usize; + if got[at..at + 3] != want { + bad.push(format!("({x}, {y}) word {:#010x}: got {:08x?}, want {want:08x?}", word(x, y), &got[at..at + 3])); + } + } + } + if !bad.is_empty() { + return Err(format!("{} of {} texels differ; first: {}", bad.len(), W * H, bad.iter().take(3).cloned().collect::>().join("; "))); + } + Ok(()) +} diff --git a/crates/xcl/src/hle/d3d12x/cast_list.rs b/crates/xcl/src/hle/d3d12x/cast_list.rs new file mode 100644 index 0000000000..841f8e422a --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/cast_list.rs @@ -0,0 +1,353 @@ +//! One memory, two formats, by relaxed format casting. +//! +//! A retail title packs light as R9G9B9E5 into R32_UINT textures (its compute programs cannot +//! store R9G9B9E5) and samples the same memory through an R9G9B9E5 texture it places at the same +//! address. On the console the two are one memory; here they are two PC textures, +//! and what is read through the sampled one is not what the GPU wrote. +//! +//! Where the device has relaxed format casting (OPTIONS12) and ID3D12Device10, a GPU-written +//! R32_UINT 2D texture is made with [R32_UINT, R9G9B9E5_SHAREDEXP] as its cast list (and a +//! texture the title gives a cast list of its own, console device #127, with that list too). +//! A view the title makes of a sampled texture at the same address, of the same shape, in a +//! format of that list, is made on the written texture: one PC texture under both descriptions. +//! +//! The written texture's read-only legacy states also take the shader-resource states +//! (`widen`), so the views made on it are read in a state they may be read in. COMMON stays as it +//! is (a read promotes it). The title's views on it go with it (`console_heap::resource_gone`). +//! +//! Behind `XCL_CAST_LIST=1` (off by default); with it off nothing is kept and every hook stops +//! at one atomic load or a `OnceLock` read. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// The pair the title packs light in: written as the first, read as the second. +const LIGHT: [DXGI_FORMAT; 2] = [DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R9G9B9E5_SHAREDEXP]; +const NPS: u32 = 0x40; +const PS: u32 = 0x80; +/// RENDER_TARGET, UNORDERED_ACCESS, DEPTH_WRITE, STREAM_OUT, COPY_DEST, RESOLVE_DEST, the video +/// encode / decode / process writes +const WRITES: u32 = 0x4 | 0x8 | 0x10 | 0x100 | 0x400 | 0x1000 | 0x2_0000 | 0x8_0000 | 0x80_0000; + +/// `XCL_CAST_LIST=1` (read once). +pub(super) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_CAST_LIST").is_ok_and(|v| v.trim() == "1")) +} + +/// What a writer's views and barriers need. +#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] +struct Shape { + dimension: i32, + width: u64, + height: u32, + depth: u16, + mips: u16, +} + +impl Shape { + fn of(d: &D3D12_RESOURCE_DESC) -> Self { + Shape { dimension: d.Dimension.0, width: d.Width, height: d.Height, depth: d.DepthOrArraySize.max(1), mips: d.MipLevels.max(1) } + } +} + +struct Writer { + res: usize, + shape: Shape, + format: i32, + casts: Vec, +} + +#[derive(Default)] +struct Table { + /// by (device, canonical address) + writers: HashMap<(usize, usize), Writer>, + /// the cast-made textures: their barriers are widened + made: HashSet, + /// the title's other textures, by resource: (device, canonical address, shape, format) + readers: HashMap, +} + +static TABLE: Mutex> = Mutex::new(None); +/// Cast-made textures alive: the gate of every hook. +static MADE: AtomicUsize = AtomicUsize::new(0); +static VIEWS: AtomicU64 = AtomicU64::new(0); + +thread_local! { + /// The cast list of the title's create on this thread (#127), while it runs. + static TITLE: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// The title's create (#127) with `n` castable formats at `formats`: they are its texture's cast +/// list while the guard lives. +pub(super) struct TitleList; + +impl Drop for TitleList { + fn drop(&mut self) { + TITLE.with(|t| t.borrow_mut().clear()); + } +} + +pub(super) unsafe fn title_list(n: u32, formats: usize) -> Option { + if !on() || n == 0 || n > 16 || formats == 0 || !crate::gpu::shader::readable(formats, n as usize * 4) { + return None; + } + let list: Vec = (0..n as usize).map(|k| super::device_x::pc_view_format(((formats + 4 * k) as *const u32).read_unaligned()) as i32).filter(|&f| f != 0).collect(); + TITLE.with(|t| *t.borrow_mut() = list); + Some(TitleList) +} + +/// The barrier layout a writer is made in for the initial state `state`: only states `widen` +/// leaves as they are (None: made without a cast list). +fn layout_of(state: u32) -> Option { + Some(match state { + 0 => D3D12_BARRIER_LAYOUT_COMMON, + 0x4 => D3D12_BARRIER_LAYOUT_RENDER_TARGET, + 0x8 => D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + 0x400 => D3D12_BARRIER_LAYOUT_COPY_DEST, + _ => return None, + }) +} + +/// A state of a cast-made texture in a transition on a list of type `ty`: read-only ones (not +/// COMMON) take the shader-resource states that list type has (DIRECT both, COMPUTE the +/// non-pixel one). A COPY list has neither: its states are left as they are. +pub(super) fn widen_state(s: u32, ty: D3D12_COMMAND_LIST_TYPE) -> u32 { + let read = match ty { + D3D12_COMMAND_LIST_TYPE_DIRECT => NPS | PS, + D3D12_COMMAND_LIST_TYPE_COMPUTE => NPS, + _ => 0, + }; + if s != 0 && s & WRITES == 0 { s | read } else { s } +} + +/// A cast-made texture moved on a list that is not DIRECT: its widened states there leave out +/// what that list type cannot name, so a DIRECT list's state for it may be wider (logged). +pub(super) fn note_other_list(ty: D3D12_COMMAND_LIST_TYPE) { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: cast lists: a written texture moved on a list of type {} ({n} so far): its read states there have no PIXEL_SHADER_RESOURCE", ty.0); + } +} + +/// Whether `dev` casts a texture's formats and samples R9G9B9E5 (asked once per device). +unsafe fn device_can(dev: &ID3D12Device) -> bool { + static CAN: Mutex>> = Mutex::new(None); + let key = dev.as_raw() as usize; + if let Some(&c) = CAN.lock().unwrap().as_ref().and_then(|m| m.get(&key)) { + return c; + } + let mut o12 = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default(); + let relaxed = dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, &mut o12 as *mut _ as *mut c_void, std::mem::size_of_val(&o12) as u32).is_ok() && o12.RelaxedFormatCastingSupported.as_bool(); + let mut fs = D3D12_FEATURE_DATA_FORMAT_SUPPORT { Format: DXGI_FORMAT_R9G9B9E5_SHAREDEXP, ..Default::default() }; + let sample = dev.CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &mut fs as *mut _ as *mut c_void, std::mem::size_of_val(&fs) as u32).is_ok() + && (fs.Support1.0 & (D3D12_FORMAT_SUPPORT1_TEXTURE2D.0 | D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE.0)) == (D3D12_FORMAT_SUPPORT1_TEXTURE2D.0 | D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE.0); + let device10 = dev.cast::().is_ok(); + let can = relaxed && sample && device10; + crate::xlog_info!( + "D3D12.X: cast lists {}: relaxed format casting {relaxed}, R9G9B9E5 sampled {sample}, ID3D12Device10 {device10}{}", + if can { "on" } else { "off" }, + if can { " (XCL_CAST_LIST=1: a GPU-written R32_UINT texture is made with R9G9B9E5 in its cast list)" } else { "" } + ); + CAN.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, can); + can +} + +/// The layout and cast list to make the GPU-owned texture `desc` with, in `state` (None: made +/// as before). The light pair's written texture, and the title's own list (#127). +pub(super) unsafe fn for_writer(dev: &ID3D12Device, desc: &D3D12_RESOURCE_DESC, state: u32) -> Option<(D3D12_BARRIER_LAYOUT, Vec)> { + if !on() || desc.SampleDesc.Count > 1 { + return None; + } + let mut casts = TITLE.with(|t| t.borrow().clone()); + let light = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.Format == LIGHT[0] && desc.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0; + if light { + casts.extend(LIGHT.iter().map(|f| f.0)); + } + if casts.is_empty() { + return None; + } + let layout = layout_of(state)?; + if !device_can(dev) { + return None; + } + if !casts.contains(&desc.Format.0) { + casts.push(desc.Format.0); + } + casts.sort_unstable(); + casts.dedup(); + // (one format is no cast list: the texture is made as before) + (casts.len() >= 2).then_some((layout, casts)) +} + +/// `res` was made at the canonical address `va` with the cast list `casts` (`vram`). +pub(super) fn made(dev: usize, res: usize, va: usize, desc: &D3D12_RESOURCE_DESC, casts: Vec) { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(Table::default); + if t.made.insert(res) { + MADE.fetch_add(1, Ordering::Relaxed); + } + t.writers.insert((dev, va), Writer { res, shape: Shape::of(desc), format: desc.Format.0, casts }); +} + +/// The title placed `res` (PC description `desc`) at `va` (`device_x::create_placed_resource_x`). +pub(super) fn note_created(dev: usize, res: usize, va: usize, desc: &D3D12_RESOURCE_DESC) { + if on() { + keep_reader(dev, res, super::vram::canonical_va(va), desc); + } +} + +/// `note_created` without the switch (`va` canonical). Kept before any writer is made: a view is +/// put on its writer when it is made, in either order. +fn keep_reader(dev: usize, res: usize, va: usize, desc: &D3D12_RESOURCE_DESC) { + if res == 0 || va == 0 || desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count > 1 { + return; + } + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(Table::default); + if !t.made.contains(&res) { + t.readers.insert(res, (dev, va, Shape::of(desc), desc.Format.0)); + } +} + +/// Whether `res` was made with a cast list. +pub(super) fn is_writer(res: usize) -> bool { + MADE.load(Ordering::Relaxed) != 0 && TABLE.lock().unwrap().as_ref().is_some_and(|t| t.made.contains(&res)) +} + +/// The written texture to make the title's view `view` of `res` on, and the view (None: `res`'s +/// own): `res` is at a writer's address with its shape, in another format of its cast list. +pub(super) fn view_on_writer(res: usize, view: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> Option<(usize, D3D12_SHADER_RESOURCE_VIEW_DESC)> { + if MADE.load(Ordering::Relaxed) == 0 || res == 0 { + return None; + } + let (writer, v) = { + let g = TABLE.lock().unwrap(); + let t = g.as_ref()?; + let &(dev, va, shape, format) = t.readers.get(&res)?; + let w = t.writers.get(&(dev, va)).filter(|w| w.res != res && w.shape == shape && w.format != format)?; + let v = match view { + Some(v) => D3D12_SHADER_RESOURCE_VIEW_DESC { Format: if v.Format == DXGI_FORMAT_UNKNOWN { DXGI_FORMAT(format) } else { v.Format }, ..*v }, + None => whole_view(shape, format), + }; + if !w.casts.contains(&v.Format.0) || v.Format.0 == w.format { + return None; + } + (w.res, v) + }; + let n = VIEWS.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: cast lists: a format {} view of the texture {res:#x} is made on the written texture {writer:#x} at its address ({n} so far)", v.Format.0); + } + Some((writer, v)) +} + +/// The view of all of a 2D texture of `shape` in `format` (a null description's). +fn whole_view(shape: Shape, format: i32) -> D3D12_SHADER_RESOURCE_VIEW_DESC { + let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT(format), Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ..Default::default() }; + if shape.depth > 1 { + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + v.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_SRV { MipLevels: shape.mips as u32, ArraySize: shape.depth as u32, ..Default::default() }; + } else { + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.Anonymous.Texture2D = D3D12_TEX2D_SRV { MipLevels: shape.mips as u32, ..Default::default() }; + } + v +} + +/// The title's last reference to `res` went (before the object may be recycled: #2436). +pub(super) fn forget(res: usize) { + if on() { + drop_res(res); + } +} + +/// `forget` without the switch. +fn drop_res(res: usize) { + let mut g = TABLE.lock().unwrap(); + let Some(t) = g.as_mut() else { return }; + t.readers.remove(&res); + if t.made.remove(&res) { + MADE.fetch_sub(1, Ordering::Relaxed); + t.writers.retain(|_, w| w.res != res); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn widen_gives_read_only_states_the_shader_resource_states() { + let d = D3D12_COMMAND_LIST_TYPE_DIRECT; + assert_eq!(widen_state(0, d), 0, "COMMON: a read promotes it"); + assert_eq!(widen_state(0x8, d), 0x8); + assert_eq!(widen_state(0x4, d), 0x4); + assert_eq!(widen_state(0x400, d), 0x400); + assert_eq!(widen_state(0x800, d), 0x8C0); + assert_eq!(widen_state(0x40, d), 0xC0); + assert_eq!(widen_state(0xC0, d), 0xC0); + // every state a writer is made in is its own widened state + for s in [0, 0x4, 0x8, 0x400] { + assert!(layout_of(s).is_some()); + for ty in [D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_LIST_TYPE_COMPUTE, D3D12_COMMAND_LIST_TYPE_COPY] { + assert_eq!(widen_state(s, ty), s); + } + } + assert!(layout_of(0x800).is_none()); + } + + /// A COMPUTE list cannot name PIXEL_SHADER_RESOURCE, a COPY list neither shader-resource state: + /// each gets only what its type has. + #[test] + fn widen_gives_each_list_type_only_the_states_it_has() { + let (c, k) = (D3D12_COMMAND_LIST_TYPE_COMPUTE, D3D12_COMMAND_LIST_TYPE_COPY); + assert_eq!(widen_state(0x800, c), 0x840); + assert_eq!(widen_state(0x40, c), 0x40); + assert_eq!(widen_state(0x8, c), 0x8); + assert_eq!(widen_state(0x800, k), 0x800, "a copy list's states stay"); + assert_eq!(widen_state(0x400, k), 0x400); + assert_eq!(widen_state(0x800, D3D12_COMMAND_LIST_TYPE_BUNDLE), 0x800); + for ty in [c, k] { + assert_eq!(widen_state(0x800, ty) & 0x80, 0, "no PIXEL_SHADER_RESOURCE on list type {}", ty.0); + } + } + + /// A sampled R9G9B9E5 texture at a writer's address and shape is viewed on the writer; one + /// at another address, of another shape, in a format not in the list, or gone, is not. + #[test] + fn a_reader_at_a_writers_address_is_viewed_on_it() { + let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let tex = |w: u64, f: DXGI_FORMAT| D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: w, Height: 720, DepthOrArraySize: 1, MipLevels: 1, Format: f, ..Default::default() }; + let (dev, va) = (0xD0, 0x12_3a00_0000usize); + let (writer, reader, other, wide) = (0x7E57_C000_0010usize, 0x7E57_C000_0020usize, 0x7E57_C000_0030usize, 0x7E57_C000_0040usize); + made(dev, writer, va, &tex(1280, DXGI_FORMAT_R32_UINT), LIGHT.iter().map(|f| f.0).collect()); + keep_reader(dev, reader, va, &tex(1280, DXGI_FORMAT_R9G9B9E5_SHAREDEXP)); + keep_reader(dev, other, va + 0x40_0000, &tex(1280, DXGI_FORMAT_R9G9B9E5_SHAREDEXP)); + keep_reader(dev, wide, va, &tex(1920, DXGI_FORMAT_R9G9B9E5_SHAREDEXP)); + assert!(is_writer(writer) && !is_writer(reader)); + let (w, v) = view_on_writer(reader, None).expect("on the writer"); + assert_eq!((w, v.Format, v.ViewDimension), (writer, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_SRV_DIMENSION_TEXTURE2D)); + assert_eq!(unsafe { v.Anonymous.Texture2D.MipLevels }, 1); + let r32 = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT_R16G16_FLOAT, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, ..Default::default() }; + assert!(view_on_writer(reader, Some(&r32)).is_none(), "not in the cast list"); + assert!(view_on_writer(other, None).is_none() && view_on_writer(wide, None).is_none()); + drop_res(reader); + assert!(view_on_writer(reader, None).is_none(), "a recycled reader is resolved again"); + drop_res(writer); + keep_reader(dev, reader, va, &tex(1280, DXGI_FORMAT_R9G9B9E5_SHAREDEXP)); + assert!(!is_writer(writer) && view_on_writer(reader, None).is_none()); + drop_res(other); + drop_res(wide); + } + + static TEST_LOCK: Mutex<()> = Mutex::new(()); +} diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 8f2809df65..9eee98447f 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1290,6 +1290,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } real::note_title_address(*ppv as usize, va as usize); super::depth_uav::note_created(*ppv, &x, Some(va as usize), state); + super::cast_list::note_created(this as usize, *ppv as usize, va as usize, &std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC)); super::lut3d::created("CreatePlacedResourceX (GPU-owned: on the title's pages / an arena)", *ppv, Some(&x), Some(va as usize), false, state); } return hr; @@ -1313,6 +1314,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, Ok(()) => { real::note_title_address(*ppv as usize, va as usize); super::depth_uav::note_created(*ppv, &x, Some(va as usize), state); + super::cast_list::note_created(this as usize, *ppv as usize, va as usize, &std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC)); super::lut3d::created(if placed_hr.is_some() { "CreatePlacedResourceX (sampled: on shared pages)" } else if small_hr.is_some() { "CreatePlacedResourceX (sampled: 4 KiB placement)" } else { "CreatePlacedResourceX (sampled: committed)" }, *ppv, Some(&x), Some(va as usize), true, state); return hr; } @@ -1331,6 +1333,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, real::note_title_address(*ppv as usize, va as usize); if !buffer { super::depth_uav::note_created(*ppv, &x, Some(va as usize), state); + super::cast_list::note_created(this as usize, *ppv as usize, va as usize, &std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC)); super::lut3d::created("CreatePlacedResourceX (a resource of its own: not kept in step)", *ppv, Some(&x), Some(va as usize), false, state); } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 638b133d13..94787f218f 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -6440,6 +6440,18 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 b[5] &= !BUFFER_ONLY_STATES; b[6] &= !BUFFER_ONLY_STATES; } + // (a texture made with a cast list: its read-only states can be read through the views + // made on it, `cast_list`; both sides, so every list agrees on its state) + if super::cast_list::is_writer((b[2] as u64 | (b[3] as u64) << 32) as usize) { + // (the states this list's type has: a COMPUTE list no PIXEL_SHADER_RESOURCE, a + // COPY list no shader-resource state) + let ty = list_type(this); + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT { + super::cast_list::note_other_list(ty); + } + b[5] = super::cast_list::widen_state(b[5], ty); + b[6] = super::cast_list::widen_state(b[6], ty); + } if b[5] == b[6] { continue; } diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 943bfec115..ff4d447e85 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -19,6 +19,7 @@ mod capture; pub mod console_heap; pub mod console_list; pub mod clamp; +mod cast_list; mod depth_uav; mod gpu_awake; pub mod device_x; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a9dad2dd11..57deb1951c 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2546,6 +2546,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { } super::depth_uav::forget(this as usize); super::barrier_groups::forget(this as usize); + super::cast_list::forget(this as usize); let final_state = super::title_textures::forget(this as usize); super::lut3d::forget(this as usize); if !had_private_data { @@ -3270,6 +3271,15 @@ unsafe fn dev_create_srv_inner(this: *mut c_void, res: *mut c_void, desc: *const c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT; } } + // a texture in the memory of a written one, in a format of its cast list: viewed on that one + // (`cast_list`; the slot is noted as the written texture's, so its views go with it) + let res = match super::cast_list::view_on_writer(res as usize, copy.as_ref()) { + Some((writer, v)) => { + copy = Some(v); + writer as *mut c_void + } + None => res, + }; // a depth buffer's view in the formats the PC has for it (a D24S8 format itself, R16_UNORM of // a D16S8 buffer …: an invalid call, the device removed) if let Some(v) = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| pc_srv(&r.GetDesc(), copy.as_ref())) { @@ -3829,12 +3839,14 @@ unsafe extern "system" fn dev_create_committed_resource_layout_x( layout: u32, clear: usize, _protected: usize, - _castable: u32, - _formats: usize, + castable: u32, + formats: usize, riid: *const GUID, ppv: *mut *mut c_void, ) -> HRESULT { note_newer_device_method(127); + // (the title's cast list: a GPU-written texture on the title's pages is made with it) + let _casts = super::cast_list::title_list(castable, formats); let state = super::device_x::layout_state(layout) as usize; if flags & D3D12_HEAP_FLAG_ALLOW_DISPLAY.0 as u32 != 0 && desc != 0 && crate::gpu::shader::readable(desc, 0x38) { return create_display_target(this, props, desc, state, clear, riid, ppv); @@ -4602,6 +4614,7 @@ unsafe fn pc_allocation_size(device: *mut c_void, d: &[u8; 0x38]) -> u64 { creator!(dev_create_placed_resource1, "CreatePlacedResource1", Kind::Resource, [a1, a2, a3, a4, a5]); creator!(pc_create_reserved_resource, "CreateReservedResource", Kind::Resource, [a1, a2, a3]); creator!(pc_create_reserved_resource1, "CreateReservedResource1", Kind::Resource, [a1, a2, a3, a4]); +creator!(pc_create_reserved_resource2, "CreateReservedResource2", Kind::Resource, [a1, a2, a3, a4, a5, a6]); /// Resources made with CreateReservedResource(1), with their description: they have no heap, so /// `res_map` asks none of them (GetHeapProperties on one is an invalid call too, debug layer @@ -4637,6 +4650,13 @@ pub(super) unsafe extern "system" fn dev_create_reserved_resource1(this: *mut c_ reserved_3d(note_reserved(pc_create_reserved_resource1(this, a1, a2, a3, a4, riid, ppv), ppv), ppv, a2) } +/// CreateReservedResource2 (ID3D12Device10; `cast_list`): `desc` in `layout`, `casts` its cast +/// list. Only on a device that has ID3D12Device10. +pub(super) unsafe fn dev_create_reserved_resource2(this: *mut c_void, desc: usize, layout: u32, clear: usize, casts: &[i32], riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let hr = pc_create_reserved_resource2(this, desc, layout as usize, clear, 0, casts.len(), casts.as_ptr() as usize, riid, ppv); + reserved_3d(note_reserved(hr, ppv), ppv, 0) +} + /// `XCL_DUMP_TARGETS`: a reserved 3D texture (XCL's own for a placed one too: that placement's /// line follows) unsafe fn reserved_3d(hr: HRESULT, ppv: *mut *mut c_void, state: usize) -> HRESULT { diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 140b4242e2..62c3c778c5 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -2490,6 +2490,8 @@ pub(super) unsafe fn place_on_pages( let recycle_key = (!require_aligned && clear.is_null() && tiled.Flags.0 == 0 && reserved_pool_enabled()) .then(|| ReservedKey::from_desc(&tiled, state)); let mut pooled = None; + // (GPU-owned only: sampled ones are pooled by description and state, `recycle_key`) + let mut cast = if require_aligned { super::cast_list::for_writer(dev, desc, state) } else { None }; let is_reservable = { let mut g = PAGES.lock().unwrap(); let pages = g.entry(dev_key).or_insert_with(|| Pages::new(dev)).as_mut()?; @@ -2529,6 +2531,25 @@ pub(super) unsafe fn place_on_pages( (hr, None) } } else { + // a written texture read in another format at its address: one texture, by its cast list + if let Some((layout, casts)) = cast.as_ref() { + let hr = super::real::dev_create_reserved_resource2(this, &tiled as *const _ as usize, layout.0 as u32, clear as usize, casts, riid, ppv); + if hr >= 0 && !(*ppv).is_null() { + (hr, None) + } else { + static REFUSED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: cast lists: CreateReservedResource2 of a {}x{} format {} texture with formats {casts:?}: {hr:#x}; made without", desc.Width, desc.Height, desc.Format.0); + } + cast = None; + let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, ppv); + if hr < 0 || (*ppv).is_null() { + log(&format!("{hr:#x}")); + return None; + } + (hr, None) + } + } else { // CreateReservedResource and GetResourceTiling do not touch `PAGES`; keep them outside the // lock so concurrent streaming threads, `before_execute`, and `page_bytes` do not serialize. let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, ppv); @@ -2537,6 +2558,7 @@ pub(super) unsafe fn place_on_pages( return None; } (hr, None) + } }; let raw = *ppv; let res = ID3D12Resource::from_raw_borrowed(&raw)?; @@ -2606,6 +2628,9 @@ pub(super) unsafe fn place_on_pages( return None; } PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); + if let Some((_, casts)) = cast { + super::cast_list::made(dev_key, raw as usize, va, desc, casts); + } let (first, own) = owned_pages(va, console_bytes, total as usize).unwrap_or((va, 0)); let kind = if gpu_owned(desc.Flags.0 as u32) { super::placements::Kind::Target } else { super::placements::Kind::Sampled }; // (the older targets it supersedes leave the shared pages once the work before is done) From 4bb5c9a9f80f4e201e20fdf66445baef7c588b03 Mon Sep 17 00:00:00 2001 From: KDenKC <125705260+KDenKC@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:24:45 -0700 Subject: [PATCH 4/4] D3D12.X: keep cast-list states and views scoped Preserve the title's resource states, honor zero-mip full-chain views, and bind its cast list to the allocation being created. Exercise repeated reads and writes in the 2D route test. Checked: #3340 review 6143106973; #3491 follow-up 7331505470. --- .../xcl/src/gpu/recomp/runner/cast_tests.rs | 77 +++++++--- crates/xcl/src/hle/d3d12x/cast_list.rs | 131 ++++++++---------- crates/xcl/src/hle/d3d12x/list_x.rs | 12 -- crates/xcl/src/hle/d3d12x/real.rs | 1 + crates/xcl/src/hle/d3d12x/vram.rs | 2 +- 5 files changed, 121 insertions(+), 102 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/runner/cast_tests.rs b/crates/xcl/src/gpu/recomp/runner/cast_tests.rs index fb44f7fdd6..e4460fde62 100644 --- a/crates/xcl/src/gpu/recomp/runner/cast_tests.rs +++ b/crates/xcl/src/gpu/recomp/runner/cast_tests.rs @@ -129,6 +129,34 @@ unsafe fn transition(r: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D } } +/// Follow the resource states exactly as the title records them on a direct list. +unsafe fn move_tex(list: &ID3D12GraphicsCommandList, tex: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + if before != after { + list.ResourceBarrier(&[transition(tex, before, after)]); + } +} + +unsafe fn check(readback: &ID3D12Resource, when: &str) -> Result<(), String> { + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).map_err(|x| x.to_string())?; + let got = std::slice::from_raw_parts(p as *const u32, (W * H * 3) as usize).to_vec(); + readback.Unmap(0, None); + let mut bad = Vec::new(); + for y in 0..H { + for x in 0..W { + let want = decode(word(x, y)).map(f32::to_bits); + let at = ((y * W + x) * 3) as usize; + if got[at..at + 3] != want { + bad.push(format!("({x}, {y}) word {:#010x}: got {:08x?}, want {want:08x?}", word(x, y), &got[at..at + 3])); + } + } + } + if !bad.is_empty() { + return Err(format!("{when}: {} of {} texels differ; first: {}", bad.len(), W * H, bad.iter().take(3).cloned().collect::>().join("; "))); + } + Ok(()) +} + unsafe fn buffer(dev: &ID3D12Device, bytes: u64, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES, flags: D3D12_RESOURCE_FLAGS) -> Result { let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() }; let mut r: Option = None; @@ -159,7 +187,7 @@ unsafe fn run(dev: &ID3D12Device, dev10: &ID3D12Device10, reserved: bool) -> Res let mut _heap: Option = None; let mut _tile_queue: Option = None; if reserved { - dev10.CreateReservedResource2(&desc, D3D12_BARRIER_LAYOUT_COMMON, None, None::<&ID3D12ProtectedResourceSession>, Some(&casts[..]), &mut tex).map_err(|x| format!("CreateReservedResource2: {x}"))?; + dev10.CreateReservedResource2(&desc, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, None, None::<&ID3D12ProtectedResourceSession>, Some(&casts[..]), &mut tex).map_err(|x| format!("CreateReservedResource2: {x}"))?; let tex = tex.as_ref().ok_or("no texture")?; let mut tiles = 0u32; dev.GetResourceTiling(tex, Some(&mut tiles), None, None, None, 0, std::ptr::null_mut()); @@ -190,7 +218,7 @@ unsafe fn run(dev: &ID3D12Device, dev10: &ID3D12Device10, reserved: bool) -> Res SamplerFeedbackMipRegion: Default::default(), }; dev10 - .CreateCommittedResource3(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc1, D3D12_BARRIER_LAYOUT_COMMON, None, None::<&ID3D12ProtectedResourceSession>, Some(&casts[..]), &mut tex) + .CreateCommittedResource3(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc1, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, None, None::<&ID3D12ProtectedResourceSession>, Some(&casts[..]), &mut tex) .map_err(|x| format!("CreateCommittedResource3: {x}"))?; } let tex = tex.ok_or("no texture")?; @@ -228,11 +256,10 @@ unsafe fn run(dev: &ID3D12Device, dev10: &ID3D12Device10, reserved: bool) -> Res }; list.SetDescriptorHeaps(&[Some(heap.clone())]); list.SetComputeRootSignature(&rs); - list.ResourceBarrier(&[transition(&tex, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); bind(); list.SetPipelineState(&pw); list.Dispatch(W / 8, H / 8, 1); - list.ResourceBarrier(&[transition(&tex, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]); + move_tex(&list, &tex, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); bind(); list.SetPipelineState(&pr); list.Dispatch(W / 8, H / 8, 1); @@ -243,22 +270,34 @@ unsafe fn run(dev: &ID3D12Device, dev10: &ID3D12Device10, reserved: bool) -> Res queue.Signal(&fence, 2).map_err(e)?; crate::gpu::fence::wait(&fence, 2, dev, None, 10_000).map_err(|x| format!("{x}"))?; - let mut p = std::ptr::null_mut(); - readback.Map(0, None, Some(&mut p)).map_err(e)?; - let got = std::slice::from_raw_parts(p as *const u32, (W * H * 3) as usize).to_vec(); - readback.Unmap(0, None); - let mut bad = Vec::new(); - for y in 0..H { - for x in 0..W { - let want = decode(word(x, y)).map(f32::to_bits); - let at = ((y * W + x) * 3) as usize; - if got[at..at + 3] != want { - bad.push(format!("({x}, {y}) word {:#010x}: got {:08x?}, want {want:08x?}", word(x, y), &got[at..at + 3])); - } + check(&readback, "first submission")?; + + // Re-use the texture in the state the title left it in. The next submission samples it + // without a barrier; the last one moves it back to UAV, writes it again, and samples it. + let (nps, ua) = (D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + for round in 0..2u64 { + alloc.Reset().map_err(e)?; + list.Reset(&alloc, None).map_err(e)?; + list.SetDescriptorHeaps(&[Some(heap.clone())]); + list.SetComputeRootSignature(&rs); + list.ResourceBarrier(&[transition(&res, D3D12_RESOURCE_STATE_COMMON, ua)]); + bind(); + list.SetPipelineState(&pr); + list.Dispatch(W / 8, H / 8, 1); + if round == 0 { + move_tex(&list, &tex, nps, ua); + bind(); + list.SetPipelineState(&pw); + list.Dispatch(W / 8, H / 8, 1); + move_tex(&list, &tex, ua, nps); } - } - if !bad.is_empty() { - return Err(format!("{} of {} texels differ; first: {}", bad.len(), W * H, bad.iter().take(3).cloned().collect::>().join("; "))); + list.ResourceBarrier(&[transition(&res, ua, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyResource(&readback, &res); + list.Close().map_err(e)?; + queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?) ]); + queue.Signal(&fence, 3 + round).map_err(e)?; + crate::gpu::fence::wait(&fence, 3 + round, dev, None, 10_000).map_err(|x| format!("{x}"))?; + check(&readback, &format!("submission {}", 2 + round))?; } Ok(()) } diff --git a/crates/xcl/src/hle/d3d12x/cast_list.rs b/crates/xcl/src/hle/d3d12x/cast_list.rs index 841f8e422a..725a9cd74a 100644 --- a/crates/xcl/src/hle/d3d12x/cast_list.rs +++ b/crates/xcl/src/hle/d3d12x/cast_list.rs @@ -11,9 +11,8 @@ //! A view the title makes of a sampled texture at the same address, of the same shape, in a //! format of that list, is made on the written texture: one PC texture under both descriptions. //! -//! The written texture's read-only legacy states also take the shader-resource states -//! (`widen`), so the views made on it are read in a state they may be read in. COMMON stays as it -//! is (a read promotes it). The title's views on it go with it (`console_heap::resource_gone`). +//! The title's legacy resource states are preserved. The title's views on the written resource +//! go with it (`console_heap::resource_gone`). //! //! Behind `XCL_CAST_LIST=1` (off by default); with it off nothing is kept and every hook stops //! at one atomic load or a `OnceLock` read. @@ -30,11 +29,6 @@ use windows::Win32::Graphics::Dxgi::Common::*; /// The pair the title packs light in: written as the first, read as the second. const LIGHT: [DXGI_FORMAT; 2] = [DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R9G9B9E5_SHAREDEXP]; -const NPS: u32 = 0x40; -const PS: u32 = 0x80; -/// RENDER_TARGET, UNORDERED_ACCESS, DEPTH_WRITE, STREAM_OUT, COPY_DEST, RESOLVE_DEST, the video -/// encode / decode / process writes -const WRITES: u32 = 0x4 | 0x8 | 0x10 | 0x100 | 0x400 | 0x1000 | 0x2_0000 | 0x8_0000 | 0x80_0000; /// `XCL_CAST_LIST=1` (read once). pub(super) fn on() -> bool { @@ -54,7 +48,19 @@ struct Shape { impl Shape { fn of(d: &D3D12_RESOURCE_DESC) -> Self { - Shape { dimension: d.Dimension.0, width: d.Width, height: d.Height, depth: d.DepthOrArraySize.max(1), mips: d.MipLevels.max(1) } + let extent = match d.Dimension { + D3D12_RESOURCE_DIMENSION_TEXTURE1D => d.Width, + D3D12_RESOURCE_DIMENSION_TEXTURE3D => d.Width.max(d.Height as u64).max(d.DepthOrArraySize as u64), + _ => d.Width.max(d.Height as u64), + }; + let full_mips = (u64::BITS - extent.max(1).leading_zeros()) as u16; + Shape { + dimension: d.Dimension.0, + width: d.Width, + height: d.Height, + depth: d.DepthOrArraySize.max(1), + mips: if d.MipLevels == 0 { full_mips } else { d.MipLevels }, + } } } @@ -81,17 +87,19 @@ static MADE: AtomicUsize = AtomicUsize::new(0); static VIEWS: AtomicU64 = AtomicU64::new(0); thread_local! { - /// The cast list of the title's create on this thread (#127), while it runs. - static TITLE: RefCell> = const { RefCell::new(Vec::new()) }; + /// The cast list from #127, restricted to the resource at the title allocation's address. + static TITLE: RefCell = const { RefCell::new(TitleCasts { formats: Vec::new(), va: None }) }; } +struct TitleCasts { formats: Vec, va: Option } + /// The title's create (#127) with `n` castable formats at `formats`: they are its texture's cast /// list while the guard lives. pub(super) struct TitleList; impl Drop for TitleList { fn drop(&mut self) { - TITLE.with(|t| t.borrow_mut().clear()); + TITLE.with(|t| *t.borrow_mut() = TitleCasts { formats: Vec::new(), va: None }); } } @@ -100,12 +108,28 @@ pub(super) unsafe fn title_list(n: u32, formats: usize) -> Option { return None; } let list: Vec = (0..n as usize).map(|k| super::device_x::pc_view_format(((formats + 4 * k) as *const u32).read_unaligned()) as i32).filter(|&f| f != 0).collect(); - TITLE.with(|t| *t.borrow_mut() = list); + TITLE.with(|t| *t.borrow_mut() = TitleCasts { formats: list, va: None }); Some(TitleList) } -/// The barrier layout a writer is made in for the initial state `state`: only states `widen` -/// leaves as they are (None: made without a cast list). +/// Bind #127's cast list to the allocation that its committed-resource hook is about to place. +pub(super) fn title_address(va: usize) { + TITLE.with(|t| { + let mut t = t.borrow_mut(); + if !t.formats.is_empty() && t.va.is_none() { t.va = Some(super::vram::canonical_va(va)); } + }); +} + +fn take_title_formats(va: usize) -> Vec { + TITLE.with(|t| { + let mut t = t.borrow_mut(); + if t.va == Some(super::vram::canonical_va(va)) { + std::mem::take(&mut t.formats) + } else { Vec::new() } + }) +} + +/// The barrier layout a writer is made in for the initial state `state` (None: made without a cast list). fn layout_of(state: u32) -> Option { Some(match state { 0 => D3D12_BARRIER_LAYOUT_COMMON, @@ -116,28 +140,6 @@ fn layout_of(state: u32) -> Option { }) } -/// A state of a cast-made texture in a transition on a list of type `ty`: read-only ones (not -/// COMMON) take the shader-resource states that list type has (DIRECT both, COMPUTE the -/// non-pixel one). A COPY list has neither: its states are left as they are. -pub(super) fn widen_state(s: u32, ty: D3D12_COMMAND_LIST_TYPE) -> u32 { - let read = match ty { - D3D12_COMMAND_LIST_TYPE_DIRECT => NPS | PS, - D3D12_COMMAND_LIST_TYPE_COMPUTE => NPS, - _ => 0, - }; - if s != 0 && s & WRITES == 0 { s | read } else { s } -} - -/// A cast-made texture moved on a list that is not DIRECT: its widened states there leave out -/// what that list type cannot name, so a DIRECT list's state for it may be wider (logged). -pub(super) fn note_other_list(ty: D3D12_COMMAND_LIST_TYPE) { - static N: AtomicU64 = AtomicU64::new(0); - let n = N.fetch_add(1, Ordering::Relaxed) + 1; - if n <= 4 || n.is_power_of_two() { - crate::xlog_info!("D3D12.X: cast lists: a written texture moved on a list of type {} ({n} so far): its read states there have no PIXEL_SHADER_RESOURCE", ty.0); - } -} - /// Whether `dev` casts a texture's formats and samples R9G9B9E5 (asked once per device). unsafe fn device_can(dev: &ID3D12Device) -> bool { static CAN: Mutex>> = Mutex::new(None); @@ -163,11 +165,11 @@ unsafe fn device_can(dev: &ID3D12Device) -> bool { /// The layout and cast list to make the GPU-owned texture `desc` with, in `state` (None: made /// as before). The light pair's written texture, and the title's own list (#127). -pub(super) unsafe fn for_writer(dev: &ID3D12Device, desc: &D3D12_RESOURCE_DESC, state: u32) -> Option<(D3D12_BARRIER_LAYOUT, Vec)> { +pub(super) unsafe fn for_writer(dev: &ID3D12Device, desc: &D3D12_RESOURCE_DESC, state: u32, va: usize) -> Option<(D3D12_BARRIER_LAYOUT, Vec)> { if !on() || desc.SampleDesc.Count > 1 { return None; } - let mut casts = TITLE.with(|t| t.borrow().clone()); + let mut casts = take_title_formats(va); let light = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.Format == LIGHT[0] && desc.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0; if light { casts.extend(LIGHT.iter().map(|f| f.0)); @@ -219,7 +221,8 @@ fn keep_reader(dev: usize, res: usize, va: usize, desc: &D3D12_RESOURCE_DESC) { } /// Whether `res` was made with a cast list. -pub(super) fn is_writer(res: usize) -> bool { +#[cfg(test)] +fn is_writer(res: usize) -> bool { MADE.load(Ordering::Relaxed) != 0 && TABLE.lock().unwrap().as_ref().is_some_and(|t| t.made.contains(&res)) } @@ -286,39 +289,27 @@ mod tests { use super::*; #[test] - fn widen_gives_read_only_states_the_shader_resource_states() { - let d = D3D12_COMMAND_LIST_TYPE_DIRECT; - assert_eq!(widen_state(0, d), 0, "COMMON: a read promotes it"); - assert_eq!(widen_state(0x8, d), 0x8); - assert_eq!(widen_state(0x4, d), 0x4); - assert_eq!(widen_state(0x400, d), 0x400); - assert_eq!(widen_state(0x800, d), 0x8C0); - assert_eq!(widen_state(0x40, d), 0xC0); - assert_eq!(widen_state(0xC0, d), 0xC0); - // every state a writer is made in is its own widened state - for s in [0, 0x4, 0x8, 0x400] { - assert!(layout_of(s).is_some()); - for ty in [D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_LIST_TYPE_COMPUTE, D3D12_COMMAND_LIST_TYPE_COPY] { - assert_eq!(widen_state(s, ty), s); - } - } - assert!(layout_of(0x800).is_none()); + fn zero_mip_count_means_the_full_chain_for_the_texture_dimension() { + let mut d = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 128, Height: 32, DepthOrArraySize: 4, MipLevels: 0, ..Default::default() }; + assert_eq!(Shape::of(&d).mips, 8); + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + d.DepthOrArraySize = 16; + assert_eq!(Shape::of(&d).mips, 8); + d.MipLevels = 3; + assert_eq!(Shape::of(&d).mips, 3); } - /// A COMPUTE list cannot name PIXEL_SHADER_RESOURCE, a COPY list neither shader-resource state: - /// each gets only what its type has. #[test] - fn widen_gives_each_list_type_only_the_states_it_has() { - let (c, k) = (D3D12_COMMAND_LIST_TYPE_COMPUTE, D3D12_COMMAND_LIST_TYPE_COPY); - assert_eq!(widen_state(0x800, c), 0x840); - assert_eq!(widen_state(0x40, c), 0x40); - assert_eq!(widen_state(0x8, c), 0x8); - assert_eq!(widen_state(0x800, k), 0x800, "a copy list's states stay"); - assert_eq!(widen_state(0x400, k), 0x400); - assert_eq!(widen_state(0x800, D3D12_COMMAND_LIST_TYPE_BUNDLE), 0x800); - for ty in [c, k] { - assert_eq!(widen_state(0x800, ty) & 0x80, 0, "no PIXEL_SHADER_RESOURCE on list type {}", ty.0); - } + fn title_cast_list_is_limited_to_its_bound_resource_address() { + let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + TITLE.with(|t| *t.borrow_mut() = TitleCasts { formats: LIGHT.iter().map(|f| f.0).collect(), va: None }); + title_address(0x10000); + let other = take_title_formats(0x20000); + assert!(other.is_empty()); + let matching = take_title_formats(0x10000); + assert_eq!(matching.len(), 2); + drop(TitleList); + assert!(TITLE.with(|t| t.borrow().formats.is_empty())); } /// A sampled R9G9B9E5 texture at a writer's address and shape is viewed on the writer; one diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 94787f218f..638b133d13 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -6440,18 +6440,6 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 b[5] &= !BUFFER_ONLY_STATES; b[6] &= !BUFFER_ONLY_STATES; } - // (a texture made with a cast list: its read-only states can be read through the views - // made on it, `cast_list`; both sides, so every list agrees on its state) - if super::cast_list::is_writer((b[2] as u64 | (b[3] as u64) << 32) as usize) { - // (the states this list's type has: a COMPUTE list no PIXEL_SHADER_RESOURCE, a - // COPY list no shader-resource state) - let ty = list_type(this); - if ty != D3D12_COMMAND_LIST_TYPE_DIRECT { - super::cast_list::note_other_list(ty); - } - b[5] = super::cast_list::widen_state(b[5], ty); - b[6] = super::cast_list::widen_state(b[6], ty); - } if b[5] == b[6] { continue; } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 57deb1951c..27e5cba34f 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2026,6 +2026,7 @@ unsafe fn place_console_texture(this: *mut c_void, desc: usize, state: usize, cl return None; } let p = u.alloc(bytes, align)? as usize; + super::cast_list::title_address(p); let hr = super::device_x::create_placed_resource_x(this, p as u64, desc as *const u8, state as u32, clear as *const c_void, riid, ppv); if hr < 0 || (*ppv).is_null() { u.free(p); diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 62c3c778c5..d93aa0a937 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -2491,7 +2491,7 @@ pub(super) unsafe fn place_on_pages( .then(|| ReservedKey::from_desc(&tiled, state)); let mut pooled = None; // (GPU-owned only: sampled ones are pooled by description and state, `recycle_key`) - let mut cast = if require_aligned { super::cast_list::for_writer(dev, desc, state) } else { None }; + let mut cast = if require_aligned { super::cast_list::for_writer(dev, desc, state, va) } else { None }; let is_reservable = { let mut g = PAGES.lock().unwrap(); let pages = g.entry(dev_key).or_insert_with(|| Pages::new(dev)).as_mut()?;