From 7c60a35aa9ba861a633206ae05cb5df17922673e Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:05:05 -0500 Subject: [PATCH] D3D12.X: a superseded target the title binds, clears or moves is mapped again A render target or depth buffer placed on title pages loses its tiles when a newer placement covers other pages of it (placements: superseded), and gets them back when the title uses it again. A use was only seen in a legacy ResourceBarrier or a copy. A title that moves its textures with the barrier groups of list #146 and then clears and draws into such a target was never seen: the target stayed without tiles, every write to it was dropped and every read of it returned 0. A use is now also: - a texture barrier in the groups of list #146 (the groups are read only while the title holds a superseded target, then all groups of the call and all barriers of a group), - OMSetRenderTargets with its RTVs (the handles the list keeps, so a single range is stepped by the device's increment) or its DSV, - ClearRenderTargetView and ClearDepthStencilView of it. The RTV and DSV handles of placed textures are kept for this in one table of addresses (placements::note_view). present's table of RTVs is not used: it holds a reference for each view and is empty with present = "off". A view the title copies (CopyDescriptorsSimple, CopyDescriptors) names what its source names: a bind or clear through a copied view would otherwise look up what its handle named earlier. All of these are calls that record into a list, so the mapping is queued before the list's submit waits for the tile mappings (vram::before_execute). Tests: the textures named by barrier groups, a 257th group and a 4097th barrier among them; the handle table; on a GPU with tiled resources, a superseded R32_FLOAT target and a superseded D16 depth buffer are mapped again by each of the calls above and hold the value they are then cleared to, one bind through a copied RTV and one clear through a copied DSV among them, the RTVs with nothing in present's table. Co-Authored-By: Claude Fable 5 --- crates/xcl/src/hle/d3d12x/depth_uav.rs | 2 +- crates/xcl/src/hle/d3d12x/list_x.rs | 72 +++++++ crates/xcl/src/hle/d3d12x/placements.rs | 89 +++++++- crates/xcl/src/hle/d3d12x/real.rs | 275 ++++++++++++++++++++++++ 4 files changed, 435 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs index 959d7faa85..7f6b10b202 100644 --- a/crates/xcl/src/hle/d3d12x/depth_uav.rs +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -1017,7 +1017,7 @@ pub(super) unsafe fn dsv_ranges_copied(dev: *mut c_void, nd: u32, dsts: *const u } /// Destination and source ranges cut where either one ends: (dst, src, n) runs. -fn pieces(dsts: &[(u64, u32)], srcs: &[(u64, u32)], inc: u64) -> Vec<(u64, u64, u32)> { +pub(super) fn pieces(dsts: &[(u64, u32)], srcs: &[(u64, u32)], inc: u64) -> Vec<(u64, u64, u32)> { let (mut out, mut d, mut s, mut dk, mut sk) = (Vec::new(), 0, 0, 0u32, 0u32); while d < dsts.len() && s < srcs.len() { let n = (dsts[d].1 - dk).min(srcs[s].1 - sk); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 4f3dae2265..78d9ecbf4c 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -5012,6 +5012,30 @@ pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u3 super::bind::dispatch_flags(this, x, y, z, flags); } +/// The textures of the texture barriers in the `n` barrier groups at `groups` (list #146), in +/// their order; groups and barrier arrays that are not readable memory are passed over. +unsafe fn barrier_group_textures(n: u32, groups: *const c_void) -> Vec { + let (mut out, mut seen) = (Vec::new(), HashSet::new()); + let count = n as usize; + if count == 0 || groups.is_null() || !crate::gpu::shader::readable(groups as usize, count * std::mem::size_of::()) { + return out; + } + for g in std::slice::from_raw_parts(groups as *const D3D12_BARRIER_GROUP, count) { + let m = g.NumBarriers as usize; + let p = g.Anonymous.pTextureBarriers; + if g.Type != D3D12_BARRIER_TYPE_TEXTURE || m == 0 || p.is_null() || !crate::gpu::shader::readable(p as usize, m * std::mem::size_of::()) { + continue; + } + for b in std::slice::from_raw_parts(p, m) { + let r: usize = transmute_copy(&b.pResource); + if r != 0 && seen.insert(r) { + out.push(r); + } + } + } + out +} + unsafe fn emit_uav_barrier_pc(this: *mut c_void) { let b = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, @@ -5029,6 +5053,12 @@ unsafe fn emit_uav_barrier_pc(this: *mut c_void) { /// (`barrier_groups`) routed through `resource_barrier_x`. pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, n: u32, barriers: *const c_void) { let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ListBarrier); + // (a superseded target the title moves is used again: `placements`) + if super::placements::any_superseded() { + for r in barrier_group_textures(n, barriers) { + super::placements::note_use(r); + } + } emit_uav_barrier_pc(this); if super::barrier_groups::enabled() { let moves = super::barrier_groups::transitions(n, barriers, list_type(this) == D3D12_COMMAND_LIST_TYPE_DIRECT); @@ -7119,6 +7149,8 @@ pub(super) unsafe extern "system" fn clear_depth_stencil_x(this: *mut c_void, ds ); } } + // (a superseded target the title clears is used again: `placements`) + super::placements::note_view_use(dsv); pc::(this, PC_CLEAR_DEPTH_STENCIL_VIEW)(this, dsv, flags, depth, stencil, n, rects) } @@ -12389,4 +12421,44 @@ mod tests { assert!(got.iter().all(|&v| v == 0xDEAD_BEEF), "the UAV was not cleared: {:x?}", &got[..4]); } } + + /// List #146's groups: the textures of the texture barriers, each once, and nothing of the + /// buffer and global groups or of a group without an array. + #[test] + fn the_texture_barriers_of_barrier_groups_name_their_textures() { + unsafe { + let tex = |r: usize| { + let mut b: D3D12_TEXTURE_BARRIER = std::mem::zeroed(); + std::ptr::write(&mut b.pResource as *mut _ as *mut usize, r); + b + }; + let first = [tex(0x1000), tex(0), tex(0x2000)]; + let second = [tex(0x2000), tex(0x3000)]; + let mut buffer: D3D12_BUFFER_BARRIER = std::mem::zeroed(); + std::ptr::write(&mut buffer.pResource as *mut _ as *mut usize, 0x9000); + let global: D3D12_GLOBAL_BARRIER = std::mem::zeroed(); + let groups = [ + D3D12_BARRIER_GROUP { Type: D3D12_BARRIER_TYPE_TEXTURE, NumBarriers: 3, Anonymous: D3D12_BARRIER_GROUP_0 { pTextureBarriers: first.as_ptr() } }, + D3D12_BARRIER_GROUP { Type: D3D12_BARRIER_TYPE_BUFFER, NumBarriers: 1, Anonymous: D3D12_BARRIER_GROUP_0 { pBufferBarriers: &buffer } }, + D3D12_BARRIER_GROUP { Type: D3D12_BARRIER_TYPE_GLOBAL, NumBarriers: 1, Anonymous: D3D12_BARRIER_GROUP_0 { pGlobalBarriers: &global } }, + D3D12_BARRIER_GROUP { Type: D3D12_BARRIER_TYPE_TEXTURE, NumBarriers: 2, Anonymous: D3D12_BARRIER_GROUP_0 { pTextureBarriers: second.as_ptr() } }, + D3D12_BARRIER_GROUP { Type: D3D12_BARRIER_TYPE_TEXTURE, NumBarriers: 4, Anonymous: D3D12_BARRIER_GROUP_0 { pTextureBarriers: std::ptr::null() } }, + ]; + let at = groups.as_ptr() as *const c_void; + assert_eq!(barrier_group_textures(5, at), vec![0x1000, 0x2000, 0x3000]); + assert_eq!(barrier_group_textures(3, at), vec![0x1000, 0x2000], "the groups past the count are not read"); + assert!(barrier_group_textures(0, at).is_empty()); + assert!(barrier_group_textures(5, std::ptr::null()).is_empty()); + + // (no limit on the groups of a call or the barriers of a group: the 257th and the 4097th) + let none = D3D12_BARRIER_GROUP { Type: D3D12_BARRIER_TYPE_TEXTURE, NumBarriers: 0, Anonymous: D3D12_BARRIER_GROUP_0 { pTextureBarriers: std::ptr::null() } }; + let mut many: Vec = (0..256).map(|_| none).collect(); + many.push(D3D12_BARRIER_GROUP { Type: D3D12_BARRIER_TYPE_TEXTURE, NumBarriers: 2, Anonymous: D3D12_BARRIER_GROUP_0 { pTextureBarriers: second.as_ptr() } }); + assert_eq!(barrier_group_textures(257, many.as_ptr() as *const c_void), vec![0x2000, 0x3000]); + let mut long: Vec = (0..4096).map(|_| tex(0x1000)).collect(); + long.push(tex(0x4000)); + let group = D3D12_BARRIER_GROUP { Type: D3D12_BARRIER_TYPE_TEXTURE, NumBarriers: 4097, Anonymous: D3D12_BARRIER_GROUP_0 { pTextureBarriers: long.as_ptr() } }; + assert_eq!(barrier_group_textures(1, &group as *const _ as *const c_void), vec![0x1000, 0x4000]); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/placements.rs b/crates/xcl/src/hle/d3d12x/placements.rs index 5dda38c2d4..18dc21a650 100644 --- a/crates/xcl/src/hle/d3d12x/placements.rs +++ b/crates/xcl/src/hle/d3d12x/placements.rs @@ -9,8 +9,10 @@ //! A placement over other pages of a live target supersedes it (`supersedes`; `XCL_PLACE_RETIRE=0` //! turns it off): what is uploaded into or drawn to the newer one then no longer shows in the //! older one's tiles. Its tiles leave the shared pages once the queues are past the work submitted -//! before (`late_release::hold_unmap`), and come back when the title uses it again (a barrier or a -//! copy of it: `note_use`) or releases the newer ones over it while it still holds it. +//! before (`late_release::hold_unmap`), and come back when the title uses it again (`note_use`: a +//! barrier of it, also a texture barrier in list #146's groups; a copy of it; its view bound as a +//! render target or depth buffer, or cleared) or releases the newer ones over it while it still +//! holds it. use std::collections::{BTreeMap, HashMap}; use std::ffi::c_void; @@ -579,11 +581,94 @@ pub(super) fn note_use(res: usize) { drop(held); } +/// RTV or DSV handle → the placed texture it names (`note_view`; the two kinds of handle are in +/// different heaps). The view is made long before a newer placement supersedes its texture, so +/// the handles of all placed ones are kept; an entry whose texture is gone names no live +/// placement and does nothing (`Registry::use_again`). Addresses only, no reference: `present` +/// keeps one for each RTV, and keeps none with `present = "off"`. +static VIEWS: Mutex>> = Mutex::new(None); + +/// CreateRenderTargetView or CreateDepthStencilView of `res` at `handle`: kept when `res` is a +/// placed texture. +pub(super) fn note_view(handle: usize, res: usize) { + let placed = res != 0 && REGISTRY.lock().unwrap().as_ref().is_some_and(|r| r.live.contains_key(&res)); + let mut g = VIEWS.lock().unwrap(); + if placed { + g.get_or_insert_with(HashMap::new).insert(handle, res); + } else if let Some(m) = g.as_mut() { + m.remove(&handle); + } +} + +/// `n` RTVs or DSVs copied from `src` to `dst` (handles `inc` apart): each destination names the +/// placed texture its source names, or none. +pub(super) fn views_copied(n: u32, dst: u64, src: u64, inc: u64) { + let mut g = VIEWS.lock().unwrap(); + let Some(m) = g.as_mut() else { return }; + for k in 0..n as u64 { + let to = (dst + k * inc) as usize; + match m.get(&((src + k * inc) as usize)).copied() { + Some(res) => m.insert(to, res), + None => m.remove(&to), + }; + } +} + +/// The placed texture the RTV or DSV at `handle` names. +fn view_texture(handle: usize) -> Option { + VIEWS.lock().unwrap().as_ref()?.get(&handle).copied() +} + +/// The title binds or clears the target of the RTV or DSV at `handle`: a use of it (`note_use`). +pub(super) fn note_view_use(handle: usize) { + if !any_superseded() { + return; + } + if let Some(res) = view_texture(handle) { + note_use(res); + } +} + #[cfg(test)] mod tests { use super::*; const K64: usize = 0x1_0000; + + /// A view is kept for a placed texture only, and a handle written again (made there, or + /// copied there) names the new one. + #[test] + fn a_view_handle_names_the_placed_texture_it_was_last_made_of() { + // (addresses and handles no other test uses: the registry and the table are the module's) + let (a, b, other) = (0x7e57_0000_1000usize, 0x7e57_0000_2000usize, 0x7e57_0000_3000usize); + let (h1, h2) = (0x7e57_d000usize, 0x7e57_d020usize); + { + let mut g = REGISTRY.lock().unwrap(); + let r = g.get_or_insert_with(Registry::default); + r.place(a, 0x7e57_4000_0000, (0x7e57_4000_0000, 0x7e57_4000_0000 + 6 * K64), Backing::Pages(0x7e57), Kind::Target, Desc::default(), Instant::now(), false, false); + r.place(b, 0x7e57_5000_0000, (0x7e57_5000_0000, 0x7e57_5000_0000 + 8 * K64), Backing::Pages(0x7e57), Kind::Target, Desc::default(), Instant::now(), false, false); + } + note_view(h1, a); + note_view(h2, other); + assert_eq!((view_texture(h1), view_texture(h2)), (Some(a), None), "a view of a texture that is not placed is not kept"); + note_view(h1, b); + assert_eq!(view_texture(h1), Some(b)); + // (copies: two handles 0x20 apart from h1, then from a handle that names nothing) + let (h3, nothing) = (0x7e57_d100usize, 0x7e57_d200usize); + note_view(h2, a); + views_copied(2, h3 as u64, h1 as u64, 0x20); + assert_eq!((view_texture(h3), view_texture(h3 + 0x20)), (Some(b), Some(a))); + views_copied(1, h3 as u64, nothing as u64, 0x20); + assert_eq!((view_texture(h3), view_texture(h3 + 0x20)), (None, Some(a)), "a copy of a view that names no placed texture"); + note_view(h2, other); + note_view(h3 + 0x20, other); + note_view(h1, other); + assert_eq!(view_texture(h1), None, "the handle names a texture that is not placed now"); + let mut g = REGISTRY.lock().unwrap(); + let r = g.as_mut().unwrap(); + r.remove(a); + r.remove(b); + } const MIB: usize = 1 << 20; /// A placement looked at, not retiring: (its sequence number, its cases). diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e70e3d9e85..33151da83c 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2900,6 +2900,20 @@ fn note_mixed_copy() { } } +/// RTVs or DSVs copied, destination and source ranges (start, length) walked in step: each +/// destination names the target its source names, as if the view were made there +/// (`placements::note_view_use`). +unsafe fn target_views_copied(dev: *mut c_void, ty: u32, dsts: &[(u64, u32)], srcs: &[(u64, u32)]) { + if ty != D3D12_DESCRIPTOR_HEAP_TYPE_RTV.0 as u32 && ty != D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 { + return; + } + // (the handles' step is asked for only when a range holds more than one view) + let inc = if dsts.iter().chain(srcs).any(|r| r.1 > 1) { dev_increment_size_x(dev, ty) as u64 } else { 0 }; + for (dst, src, n) in super::depth_uav::pieces(dsts, srcs, inc) { + super::placements::views_copied(n, dst, src, inc); + } +} + /// #24 CopyDescriptorsSimple(n, dst, src, type) unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) { let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); @@ -2916,6 +2930,7 @@ unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u3 if ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 { super::depth_uav::dsvs_copied(this, n, dst, src); } + target_views_copied(this, ty, &[(dst, n)], &[(src, n)]); let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24)); f(this, n, dst, src, ty); } @@ -2937,6 +2952,12 @@ unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dst if ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 { super::depth_uav::dsv_ranges_copied(this, nd, dsts, dsizes, ns, srcs, ssizes); } + if (ty == D3D12_DESCRIPTOR_HEAP_TYPE_RTV.0 as u32 || ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32) && !dsts.is_null() && !srcs.is_null() { + let ranges = |starts: *const u64, sizes: *const u32, n: u32| -> Vec<(u64, u32)> { + (0..n as usize).map(|r| (*starts.add(r), if sizes.is_null() { 1 } else { *sizes.add(r) })).collect() + }; + target_views_copied(this, ty, &ranges(dsts, dsizes, nd), &ranges(srcs, ssizes, ns)); + } type F = unsafe extern "system" fn(*mut c_void, u32, *const u64, *const u32, u32, *const u64, *const u32, u32); let f: F = std::mem::transmute(orig_fn(this, 23)); return f(this, nd, dsts, dsizes, ns, srcs, ssizes, ty); @@ -3145,6 +3166,7 @@ unsafe extern "system" fn dev_create_dsv_x(this: *mut c_void, res: *mut c_void, } let flags = copy.as_ref().map_or(0, |c| c.Flags.0 as u32); f(this, res, copy.as_ref().map_or(desc, |c| c as *const _), cpu); + super::placements::note_view(cpu as usize, res as usize); super::depth_uav::note_dsv(cpu as usize, res as usize, flags); } @@ -11315,6 +11337,7 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de let desc = copy.as_ref().map_or(desc, |c| c as *const _ as *const c_void); f(this, res, desc, handle); super::present::note_rtv(handle, res); + super::placements::note_view(handle, res as usize); if super::capture::enabled() { super::capture::note_view(handle, res as usize, false, (!desc.is_null()).then(|| (desc as *const [u32; 6]).read_unaligned())); } @@ -11355,6 +11378,8 @@ unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *co super::lut3d::wrote(r, false, || format!("ClearRenderTargetView {rtv:#x} to {:?}, {n} rects", color.as_ref())); } } + // (a superseded target the title clears is used again: `placements`) + super::placements::note_view_use(rtv); f(this, rtv, color, n, rects) } @@ -11368,6 +11393,15 @@ unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rt let f: F = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "OMSetRenderTargets"))); f(this, n, rtvs, single, dsv); super::list_x::note_render_targets(this, n, rtvs, single, dsv); + // (a superseded target the title binds is used again: `placements`) + if super::placements::any_superseded() { + if !dsv.is_null() { + super::placements::note_view_use(*dsv); + } + for h in super::list_x::bound_render_targets(this) { + super::placements::note_view_use(h); + } + } let _ = super::capture::op(this, || Some(super::capture::targets_op(this))); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); @@ -15124,6 +15158,247 @@ mod depth_uav_twin_tests { } } +#[cfg(test)] +mod superseded_target_tests { + use super::super::{device_x, late_release, list_x, present, vram}; + use super::*; + use std::mem::ManuallyDrop; + use std::time::{Duration, Instant}; + use windows::Win32::Graphics::Dxgi::Common::*; + + const K64: usize = 0x1_0000; + + /// `obj` as the PC made it. The adapter's device is one object for the process, and a test + /// before this one may have left it adopted: what it makes then is a title's, and a title's + /// queue is kept for the process once it executes (`present::note_execute`). + unsafe fn pc(obj: T) -> T { + let p = obj.as_raw(); + if is_adopted(p) { + *(p as *mut usize) = *(*(p as *const *const usize)).sub(1); + } + obj + } + + /// A device as a title's (the default adapter's, else WARP's; `XCL_ADAPTER=warp`: WARP's) + /// with a queue, a list and four RTV and DSV handles of the PC's. + struct Gpu { + dev: ID3D12Device, + queue: ID3D12CommandQueue, + _alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + _heaps: [ID3D12DescriptorHeap; 2], + rtv: [usize; 4], + dsv: [usize; 4], + } + + impl Gpu { + /// None: skipped, there is no device. + unsafe fn new() -> Option { + let warp_only = crate::gpu::adapter::Selector::from_env_or("auto") == crate::gpu::adapter::Selector::Warp; + let mut dev: Option = None; + if warp_only || D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + dev = None; + if let Ok(warp) = CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()) { + let _ = D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev); + } + } + let Some(dev) = dev else { + crate::gpu::recomp::runner::skip_test("no D3D12 device"); + return None; + }; + // the view heaps, the queue and the list are the PC's; then the device as a title's + let heap = |ty| -> (ID3D12DescriptorHeap, [usize; 4]) { + let h: ID3D12DescriptorHeap = pc(dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: ty, NumDescriptors: 4, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0 }).unwrap()); + let (at, step) = (h.GetCPUDescriptorHandleForHeapStart().ptr, dev.GetDescriptorHandleIncrementSize(ty) as usize); + (h, std::array::from_fn(|k| at + k * step)) + }; + let ((rtvs, rtv), (dsvs, dsv)) = (heap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV), heap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV)); + let queue: ID3D12CommandQueue = pc(dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap()); + let alloc: ID3D12CommandAllocator = pc(dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap()); + let list: ID3D12GraphicsCommandList = pc(dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap()); + adopt(dev.as_raw(), Kind::Device); + Some(Gpu { dev, queue, _alloc: alloc, list, _heaps: [rtvs, dsvs], rtv, dsv }) + } + + unsafe fn mapped(&self, r: &ID3D12Resource) -> bool { + vram::mapped_tiles_for(self.dev.as_raw() as usize, r.as_raw() as usize).is_some() + } + + /// A 512x512 target the title places at `va` (CreatePlacedResourceX) and a 128x128 one it + /// then places on the last of the first one's pages: the newer one supersedes the older, + /// whose tiles are off the shared pages when this returns. None: skipped, the adapter + /// makes no reserved texture of the format. + unsafe fn superseded(&self, va: usize, format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS, state: D3D12_RESOURCE_STATES) -> Option<(ID3D12Resource, ID3D12Resource)> { + let d = self.dev.as_raw(); + let place = |va: usize, side: u32| { + let console = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: side as u64, + Height: side, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: flags, + ..Default::default() + }; + let mut raw = std::ptr::null_mut(); + let hr = device_x::create_placed_resource_x(d, va as u64, &console as *const _ as *const u8, state.0 as u32, std::ptr::null(), &ID3D12Resource::IID as *const _ as *const GUID, &mut raw); + assert!(hr >= 0 && !raw.is_null(), "a {side}x{side} target at {va:#x}: {hr:#x}"); + ID3D12Resource::from_raw(raw) + }; + let older = place(va, 512); + let Some((pages, _)) = vram::mapped_tiles_for(d as usize, older.as_raw() as usize).filter(|(pages, _)| pages.len() >= 2) else { + crate::gpu::recomp::runner::skip_test("no tiled resources"); + return None; + }; + let newer = place(va + (pages.len() - 1) * K64, 128); + // (its tiles leave once the queues are past the work submitted before: `late_release::hold_unmap`) + let start = Instant::now(); + while self.mapped(&older) && start.elapsed() < Duration::from_secs(10) { + late_release::drain_known(true); + std::thread::sleep(Duration::from_millis(5)); + } + assert!(!self.mapped(&older), "the older target is superseded: its tiles are off the shared pages"); + assert!(self.mapped(&newer)); + Some((older, newer)) + } + + /// The list's own table back after the title's calls on it (`adopt`), then level 0 of + /// `res` (in state `before`) copied out and read: its rows of `row` bytes. + unsafe fn read_back(&self, res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, row: usize) -> Vec { + let l = self.list.as_raw(); + *(l as *mut usize) = *(*(l as *const *const usize)).sub(1); + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0u64; + self.dev.GetCopyableFootprints(&res.GetDesc(), 0, 1, 0, Some(&mut fp), None, None, Some(&mut total)); + let buffer = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: total, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut rb: Option = None; + self.dev + .CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb) + .expect("readback buffer"); + let rb = rb.unwrap(); + self.list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(res), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: D3D12_RESOURCE_STATE_COPY_SOURCE, + }), + }, + }]); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(res), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + self.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + self.list.Close().expect("close list"); + // (as a title's submit: the queue waits for the tile mappings made so far) + vram::before_execute(&self.queue); + self.queue.ExecuteCommandLists(&[Some(self.list.cast().unwrap())]); + let fence: ID3D12Fence = self.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + self.queue.Signal(&fence, 1).expect("signal"); + crate::gpu::fence::wait(&fence, 1, &self.dev, None, 5000).expect("the list completes"); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).expect("map readback"); + let pitch = fp.Footprint.RowPitch as usize; + let rows = (0..fp.Footprint.Height as usize).flat_map(|y| std::slice::from_raw_parts((p as *const u8).add(fp.Offset as usize + y * pitch), row).to_vec()).collect(); + rb.Unmap(0, None); + rows + } + } + + /// A render target under a newer placement gets its tiles back when the title binds it + /// (OMSetRenderTargets, also through an RTV it copied: CopyDescriptorsSimple), clears it + /// (ClearRenderTargetView) or names it in a texture barrier of list #146's groups, and the + /// clear is in it. Before, only a legacy barrier or a copy gave them back: the target stayed + /// without tiles, what was drawn to it was dropped. + #[test] + fn gpu_a_superseded_render_target_the_title_binds_clears_or_moves_is_mapped_again() { + let _vram = vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Some(g) = Gpu::new() else { return }; + let at = 0x13_5e00_0000usize; + let target = |va| g.superseded(va, DXGI_FORMAT_R32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_RENDER_TARGET); + let Some((bound, _b)) = target(at) else { return }; + let Some((cleared, _c)) = target(at + (2 << 20)) else { return }; + let Some((moved, _m)) = target(at + (4 << 20)) else { return }; + let Some((copied, _k)) = target(at + (6 << 20)) else { return }; + let d = g.dev.as_raw(); + dev_create_rtv(d, bound.as_raw(), std::ptr::null(), g.rtv[0]); + dev_create_rtv(d, cleared.as_raw(), std::ptr::null(), g.rtv[1]); + dev_create_rtv(d, copied.as_raw(), std::ptr::null(), g.rtv[2]); + dev_copy_descriptors_simple_x(d, 1, g.rtv[3] as u64, g.rtv[2] as u64, D3D12_DESCRIPTOR_HEAP_TYPE_RTV.0 as u32); + // (`present`'s table names none of them, as with `present = "off"`: the uses below do + // not go through it) + for h in g.rtv { + present::note_rtv(h, std::ptr::null_mut()); + } + + // the title's calls, on the adopted list + let l = g.list.as_raw(); + adopt(l, Kind::CommandList); + cl_om_set_render_targets(l, 2, [g.rtv[0], g.rtv[3]].as_ptr(), 0, std::ptr::null()); + cl_clear_rtv(l, g.rtv[1], &[0.25; 4], 0, std::ptr::null()); + let mut barrier: D3D12_TEXTURE_BARRIER = std::mem::zeroed(); + std::ptr::write(&mut barrier.pResource as *mut _ as *mut usize, moved.as_raw() as usize); + let group = D3D12_BARRIER_GROUP { Type: D3D12_BARRIER_TYPE_TEXTURE, NumBarriers: 1, Anonymous: D3D12_BARRIER_GROUP_0 { pTextureBarriers: &barrier } }; + list_x::uav_barrier_x(l, 1, &group as *const _ as *const c_void); + let uses = [("OMSetRenderTargets", &bound), ("OMSetRenderTargets with a copied RTV", &copied), ("ClearRenderTargetView", &cleared), ("a texture barrier in list #146's groups", &moved)]; + let left: Vec<&str> = uses.into_iter().filter(|(_, r)| !g.mapped(r)).map(|(what, _)| what).collect(); + assert!(left.is_empty(), "still without tiles after {left:?}"); + + let got = g.read_back(&cleared, D3D12_RESOURCE_STATE_RENDER_TARGET, 512 * 4); + assert!(got.chunks_exact(4).all(|t| f32::from_le_bytes(t.try_into().unwrap()) == 0.25), "the clear is not in the target: {:x?}", &got[..8]); + } + } + + /// A depth buffer under a newer placement gets its tiles back when the title binds it + /// (OMSetRenderTargets) or clears it (ClearDepthStencilView, also through a DSV it copied: + /// CopyDescriptors), and the clear is in it. + #[test] + fn gpu_a_superseded_depth_buffer_the_title_binds_or_clears_is_mapped_again() { + let _vram = vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Some(g) = Gpu::new() else { return }; + let at = 0x13_6e00_0000usize; + let buffer = |va| g.superseded(va, DXGI_FORMAT_D16_UNORM, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, D3D12_RESOURCE_STATE_DEPTH_WRITE); + let Some((bound, _b)) = buffer(at) else { return }; + let Some((cleared, _c)) = buffer(at + (2 << 20)) else { return }; + let Some((copied, _k)) = buffer(at + (4 << 20)) else { return }; + let d = g.dev.as_raw(); + let view = D3D12_DEPTH_STENCIL_VIEW_DESC { Format: DXGI_FORMAT_D16_UNORM, ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, ..Default::default() }; + dev_create_dsv_x(d, bound.as_raw(), &view, g.dsv[0] as u64); + dev_create_dsv_x(d, cleared.as_raw(), &view, g.dsv[1] as u64); + dev_create_dsv_x(d, copied.as_raw(), &view, g.dsv[2] as u64); + let (to, from) = (g.dsv[3] as u64, g.dsv[2] as u64); + dev_copy_descriptors_x(d, 1, &to, std::ptr::null(), 1, &from, std::ptr::null(), D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32); + + // the title's calls, on the adopted list + let l = g.list.as_raw(); + adopt(l, Kind::CommandList); + cl_om_set_render_targets(l, 0, std::ptr::null(), 0, &g.dsv[0]); + list_x::clear_depth_stencil_x(l, g.dsv[1], D3D12_CLEAR_FLAG_DEPTH.0 as u32, 1.0, 0, 0, std::ptr::null()); + list_x::clear_depth_stencil_x(l, g.dsv[3], D3D12_CLEAR_FLAG_DEPTH.0 as u32, 1.0, 0, 0, std::ptr::null()); + let left: Vec<&str> = [("OMSetRenderTargets", &bound), ("ClearDepthStencilView", &cleared), ("ClearDepthStencilView with a copied DSV", &copied)].into_iter().filter(|(_, r)| !g.mapped(r)).map(|(what, _)| what).collect(); + assert!(left.is_empty(), "still without tiles after {left:?}"); + + let got = g.read_back(&cleared, D3D12_RESOURCE_STATE_DEPTH_WRITE, 512 * 2); + assert!(got.iter().all(|&b| b == 0xFF), "the clear is not in the buffer: {:x?}", &got[..8]); + } + } +} + #[cfg(test)] mod uma_heap_tests { use super::*;