From c7eccd9d909d18f0137796cd14572173ab35b7d2 Mon Sep 17 00:00:00 2001 From: nathan Date: Sun, 29 Nov 2026 18:01:40 +0100 Subject: [PATCH 1/2] D3D12.X: look for superseded targets in every declared table range MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A superseded target bound through a descriptor table is remapped when a draw or dispatch binds the table (#3179), but only the first 256 slots of each table were read. A view further in – a bindless SRV range, or a range at an explicit offset past slot 256 – was never seen: the target kept no tiles, its writes were dropped and its reads returned zeros. The root signature's SRV and UAV ranges of each descriptor table (RTS0 1.0 and 1.1, appended and unbounded ones included) are now kept in the layout, and the scan reads those ranges and nothing else. An unbounded range ends with the view heap the table lies in (console_heap::view_heap_remaining_slots); outside any view heap it has no known extent and is not read. CBV and sampler ranges cannot name a placed target and are skipped. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/bind.rs | 130 ++++++++++++++++++---- crates/xcl/src/hle/d3d12x/console_heap.rs | 9 ++ crates/xcl/src/hle/d3d12x/console_list.rs | 76 ++++++++++++- 3 files changed, 192 insertions(+), 23 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 62d5549b14..b10a3902af 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -1302,35 +1302,75 @@ pub(super) fn bound_pso(this: *mut c_void) -> usize { with(this, |s| s.pso) } -/// Remap any superseded targets named in the first 256 slots of each descriptor table in `layout` -/// / `args`. Only called when `placements::any_superseded()` is true. +/// Remap any superseded targets named in the declared SRV/UAV descriptor ranges of `layout` / +/// `args`. Only called when `placements::any_superseded()` is true. unsafe fn note_superseded_in_tables(u: &crate::gpu::uma::Uma, layout: Option<&Layout>, args: &[u8]) { let Some(layout) = layout else { return }; - const TABLE_SLOTS: usize = 256; - let mut table = [0u8; TABLE_SLOTS * 32]; - for p in &layout.params { - let Param::Table { at } = *p else { continue }; - let at = at as usize; + scan_superseded_in_tables_with( + layout, + args, + u.base(), + super::console_heap::view_heap_remaining_slots, + |addr, len| u.in_committed_window(addr, len), + |addr, buf| super::title_textures::read_committed_into(addr, buf), + super::console_heap::named_by_index, + super::placements::note_use, + ); +} + +unsafe fn scan_superseded_in_tables_with( + layout: &Layout, + args: &[u8], + uma_base: usize, + mut heap_remaining: impl FnMut(usize) -> Option, + mut in_committed: impl FnMut(usize, usize) -> bool, + mut read_committed: impl FnMut(usize, &mut [u8]), + mut named_by_index: impl FnMut(u32) -> usize, + mut on_use: impl FnMut(usize), +) { + const CHUNK_SLOTS: usize = 256; + let mut chunk = [0u8; CHUNK_SLOTS * 32]; + for (at, ranges) in &layout.table_ranges { + let at = *at as usize; let Some(word) = args.get(at..at + 4) else { continue }; let offset = u32::from_le_bytes(word.try_into().unwrap()) as usize; if offset == 0 { continue; } - let addr = u.base() + offset; - if u.in_committed_window(addr, table.len()) { - std::ptr::copy_nonoverlapping(addr as *const u8, table.as_mut_ptr(), table.len()); - } else { - table.fill(0); - super::title_textures::read_committed_into(addr, &mut table); - } - for slot in table.chunks_exact(32) { - let index = u32::from_le_bytes(slot[..4].try_into().unwrap()); - if slot[15] >> 4 < 8 || index == 0 { - continue; - } - let res = super::console_heap::named_by_index(index); - if res != 0 && res != super::console_heap::GONE { - super::placements::note_use(res); + let Some(table_base) = uma_base.checked_add(offset) else { continue }; + let rem = heap_remaining(table_base); + for range in ranges { + let start = range.start as usize; + let total = match (rem, range.count) { + (Some(heap_rem), Some(c)) => (c as usize).min(heap_rem.saturating_sub(start)), + (Some(heap_rem), None) => heap_rem.saturating_sub(start), + (None, Some(c)) => c as usize, + // Unbounded range outside any registered view heap: no safe extent to scan. + (None, None) => 0, + }; + let mut done = 0usize; + while done < total { + let n = (total - done).min(CHUNK_SLOTS); + let bytes = n * 32; + let Some(addr) = start.checked_add(done).and_then(|s| s.checked_mul(32)).and_then(|b| table_base.checked_add(b)) else { break }; + let buf = &mut chunk[..bytes]; + if in_committed(addr, bytes) { + std::ptr::copy_nonoverlapping(addr as *const u8, buf.as_mut_ptr(), bytes); + } else { + buf.fill(0); + read_committed(addr, buf); + } + for slot in buf.chunks_exact(32) { + let index = u32::from_le_bytes(slot[..4].try_into().unwrap()); + if slot[15] >> 4 < 8 || index == 0 { + continue; + } + let res = named_by_index(index); + if res != 0 && res != super::console_heap::GONE { + on_use(res); + } + } + done += n; } } } @@ -5367,6 +5407,52 @@ mod tests { use std::sync::mpsc; use std::time::Duration; + /// A superseded target is looked for in the SRV / UAV ranges a table declares, however far + /// from the table's start (the first 256 slots only, before: a view at slot 300 was never + /// seen), and not in the slots between them. An unbounded range ends with the view heap the + /// table lies in; outside any view heap it is not read (no extent known). + #[test] + fn superseded_targets_are_found_in_every_declared_table_range() { + use console_list::TableRange; + const SLOTS: usize = 512; + let (uma_base, offset) = (0x1_0000_0000usize, 0x4000u32); + let table = uma_base + offset as usize; + // T#s (type nibble 8 in byte 15) naming shared-heap indexes 10 + k, at slots 10, 300 and 400 + let mut mem = vec![0u8; SLOTS * 32]; + for k in [10usize, 300, 400] { + mem[32 * k..32 * k + 4].copy_from_slice(&(10 + k as u32).to_le_bytes()); + mem[32 * k + 15] = 0x80; + } + let args = offset.to_le_bytes().to_vec(); + let found = |ranges: Vec, heap_slots: Option| { + let layout = Layout { table_ranges: vec![(0, ranges)], ..Default::default() }; + let mut used = Vec::new(); + unsafe { + scan_superseded_in_tables_with( + &layout, + &args, + uma_base, + |at| heap_slots.map(|n| n - (at - table) / 32), + |_, _| false, + |at, buf| buf.copy_from_slice(&mem[at - table..at - table + buf.len()]), + |index| 0x7000 + index as usize, + |res| used.push(res), + ); + } + used + }; + // an SRV range of 8 at slot 300: the target there, not the one at slot 10 + assert_eq!(found(vec![TableRange { start: 300, count: Some(8) }], Some(SLOTS)), vec![0x7000 + 310]); + // two ranges: both of their targets + assert_eq!(found(vec![TableRange { start: 0, count: Some(16) }, TableRange { start: 390, count: Some(16) }], Some(SLOTS)), vec![0x7000 + 20, 0x7000 + 410]); + // unbounded from 300: up to the view heap's end + assert_eq!(found(vec![TableRange { start: 300, count: None }], Some(SLOTS)), vec![0x7000 + 310, 0x7000 + 410]); + // unbounded outside any view heap: nothing read + assert!(found(vec![TableRange { start: 0, count: None }], None).is_empty()); + // a bounded range is cut at the view heap's end + assert_eq!(found(vec![TableRange { start: 300, count: Some(1000) }], Some(350)), vec![0x7000 + 310]); + } + #[test] fn aligned_list_addresses_reach_many_bind_shards() { let shards = (0..256).map(|index| state_shard_index(0x7100_0000 + index * 16)).collect::>(); diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 3c9dd506b8..3e44809a43 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -1083,6 +1083,15 @@ fn finish_view_slot(h: &Heap, k: u32, page: Option<(u32, u32)>) -> Slot { Slot { generation: h.generation, at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k, remaining: h.n - k } } +/// Remaining 32-byte view slots from `addr` to the end of the containing registered view heap, +/// without allocating shared-heap pages. Returns `None` if `addr` is not inside a view heap. +pub fn view_heap_remaining_slots(addr: usize) -> Option { + let heaps = HEAPS.lock().unwrap(); + let h = heaps.iter().find(|h| !h.sampler && addr >= h.shadow && addr < h.shadow + (h.n as usize) * (SLOT as usize))?; + let k = (addr - h.shadow) / (SLOT as usize); + Some((h.n as usize).saturating_sub(k)) +} + /// The slot behind a console CPU handle (None: not one of XCL's console heaps). A view slot /// of a heap in the shared heap gets its page's place there now if the page has none yet; one /// whose page finds no room there gets index 0, the null SRV / UAV pair. diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 7c12cdec05..99f42e9ea8 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -65,12 +65,22 @@ pub enum Param { Table { at: u32 }, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TableRange { + /// Descriptor slot offset from the start of the descriptor table. + pub start: u32, + /// Number of descriptors (`None` = unbounded, `u32::MAX` in RTS0). + pub count: Option, +} + /// Where a root signature's arguments go: all of them packed in order (`at`, `size` bytes); /// the first `inline` bytes of that are passed in user SGPRs (compute from s4, graphics /// stages from s8: `inline_gfx` bytes), the rest is the table. #[derive(Debug, Default)] pub struct Layout { pub params: Vec, + /// Declared SRV/UAV descriptor intervals per descriptor-table parameter (`(at, ranges)`). + pub table_ranges: Vec<(u32, Vec)>, pub size: u32, pub inline: u32, pub inline_gfx: u32, @@ -149,6 +159,7 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { None => blob.to_vec(), }; let r = |o: usize| rts0.get(o..o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); + let version = r(0)?; let (n, poff) = (r(4)? as usize, r(8)? as usize); let flags = r(20).unwrap_or(0); let mut l = Layout { heaps: [CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED, SAMPLER_HEAP_DIRECTLY_INDEXED].map(|f| flags & f != 0), ..Default::default() }; @@ -163,7 +174,34 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { let p = match ty { 1 => Param::Constants { at: l.size, count: r(pay + 8)? }, 2..=4 => Param::Descriptor { at: l.size }, - _ => Param::Table { at: l.size }, + _ => { + if ty == 0 { + let mut ranges = Vec::new(); + if let (Some(nr), Some(roff)) = (r(pay), r(pay + 4)) { + let stride = if version >= 2 { 24usize } else { 20usize }; + let off_field = if version >= 2 { 20usize } else { 16usize }; + let mut next_offset = 0u32; + for j in 0..nr as usize { + let Some(base) = (roff as usize).checked_add(j.checked_mul(stride).unwrap_or(usize::MAX)) else { break }; + let (Some(rty), Some(num), Some(raw_off)) = (r(base), r(base + 4), r(base + off_field)) else { break }; + let start = if raw_off == u32::MAX { next_offset } else { raw_off }; + let count = if num == u32::MAX { None } else { Some(num) }; + next_offset = match count { + Some(c) => start.saturating_add(c), + None => u32::MAX, + }; + // 0 = SRV, 1 = UAV (only views that can reference a placed target) + if (rty == 0 || rty == 1) && num != 0 { + ranges.push(TableRange { start, count }); + } + } + } + if !ranges.is_empty() { + l.table_ranges.push((l.size, ranges)); + } + } + Param::Table { at: l.size } + } }; let bytes = match p { Param::Constants { count, .. } => count.checked_mul(4)?, @@ -1310,6 +1348,42 @@ mod tests { assert_eq!(&got[16..], &[1, 2, 0x5000, 4, 0x80]); } + /// A root signature whose only parameter is a descriptor table, in RTS0 `version` (1: 1.0, + /// 2: 1.1), with `ranges` of (range type, descriptors, offset from the table start). + fn rts0_table(version: u32, ranges: &[(u32, u32, u32)]) -> Vec { + // header (24 B), one parameter (12 B), its table payload (8 B), then the ranges + let (param, pay, roff) = (24u32, 36u32, 44u32); + let mut r = vec![version, 1, param, 0, 0, 0, 0, 0, pay, ranges.len() as u32, roff]; + for &(ty, num, off) in ranges { + if version >= 2 { + r.extend([ty, num, 0, 0, 0, off]); + } else { + r.extend([ty, num, 0, 0, off]); + } + } + r.iter().flat_map(|w| w.to_le_bytes()).collect() + } + + /// A table's SRV and UAV ranges are kept with their offsets from the table start (appended + /// ones after the range before them, unbounded ones without a count); CBV and sampler ranges + /// cannot name a placed target and are left out. Both range layouts (1.0: 20 bytes, 1.1: 24). + #[test] + fn descriptor_tables_keep_their_srv_and_uav_ranges() { + const APPEND: u32 = u32::MAX; + for version in [1, 2] { + // SRV 4 at 0, CBV 2 appended (4..6), UAV unbounded appended (6..), sampler 1 at 0 + let blob = rts0_table(version, &[(0, 4, 0), (2, 2, APPEND), (1, u32::MAX, APPEND), (3, 1, 0)]); + let l = layout_from_blob(&blob).expect("layout"); + assert_eq!(l.table_ranges, vec![(0, vec![TableRange { start: 0, count: Some(4) }, TableRange { start: 6, count: None }])], "version {version}"); + // an SRV range past the first 256 slots, at an explicit offset + let blob = rts0_table(version, &[(1, 8, 300)]); + assert_eq!(layout_from_blob(&blob).expect("layout").table_ranges, vec![(0, vec![TableRange { start: 300, count: Some(8) }])], "version {version}"); + // a table of constant buffers only: nothing to look at + let blob = rts0_table(version, &[(2, 16, 0)]); + assert!(layout_from_blob(&blob).expect("layout").table_ranges.is_empty(), "version {version}"); + } + } + #[test] fn force_memory_based_abi_spills_all_parameters_and_strips_xbox_flags() { let mut blob = rts0(&[(1, 2), (2, 0), (0, 0)]); From 00ce5644ca0e353bfaeea07b819b994a1a1a1c17 Mon Sep 17 00:00:00 2001 From: John Howard <49204095+Royalflamejlh@users.noreply.github.com> Date: Tue, 1 Dec 2026 09:20:12 -0700 Subject: [PATCH 2/2] D3D12.X: read a view heap's slots in place when scanning for superseded targets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While any target is superseded, every draw and dispatch bound on XCL's ABI scans the descriptor ranges its layout declares for views of superseded targets (note_superseded_in_tables, #3443). A table outside the committed window, such as the title's view heaps in sparse window 0, was read with read_committed_into, one read for each declared range (about 41 a bind in that run), and under Wine each read asks VirtualQuery first (Windows reads it with one ReadProcessMemory). In a run in the title's world that VirtualQuery was the first call site of all, about 17 µs a call for a 32-byte slot. A range inside a registered view heap is already cut to the heap's end, and the heap's slots are committed while it is registered (XCL commits a heap it places in the sparse windows; one in the title's memory was committed when it was made): such a range is now copied where it is, under HEAPS as view_slot_words copies, so a heap unregistered on another thread since its lookup is not freed under the copy; it is then read with read_committed_into, as a range outside any view heap is. Measured with two other changes (one read of a few resident pages in read_committed_into under Wine, and the memory report reusing its commit sum) on a tree carrying other unmerged work, RTX 4060 Ti, Wine 11.21, 1 run each with the same options, the title in its world: 1.19 -> 3.70 frames a second. What each change gives on its own was not measured. Test: in-heap ranges are found without read_committed (red without the change); a bounded range outside any heap, or in one unregistered since its lookup, is read through it; a view heap's slots are copied only while it is registered. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/bind.rs | 32 ++++++++++++++++++++--- crates/xcl/src/hle/d3d12x/console_heap.rs | 25 ++++++++++++++++++ 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index b10a3902af..7f8908cbce 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -1311,6 +1311,7 @@ unsafe fn note_superseded_in_tables(u: &crate::gpu::uma::Uma, layout: Option<&La args, u.base(), super::console_heap::view_heap_remaining_slots, + super::console_heap::copy_view_heap_slots, |addr, len| u.in_committed_window(addr, len), |addr, buf| super::title_textures::read_committed_into(addr, buf), super::console_heap::named_by_index, @@ -1323,6 +1324,7 @@ unsafe fn scan_superseded_in_tables_with( args: &[u8], uma_base: usize, mut heap_remaining: impl FnMut(usize) -> Option, + mut copy_in_heap: impl FnMut(usize, &mut [u8]) -> bool, mut in_committed: impl FnMut(usize, usize) -> bool, mut read_committed: impl FnMut(usize, &mut [u8]), mut named_by_index: impl FnMut(u32) -> usize, @@ -1356,7 +1358,7 @@ unsafe fn scan_superseded_in_tables_with( let buf = &mut chunk[..bytes]; if in_committed(addr, bytes) { std::ptr::copy_nonoverlapping(addr as *const u8, buf.as_mut_ptr(), bytes); - } else { + } else if rem.is_none() || !copy_in_heap(addr, buf) { buf.fill(0); read_committed(addr, buf); } @@ -5415,15 +5417,18 @@ mod tests { fn superseded_targets_are_found_in_every_declared_table_range() { use console_list::TableRange; const SLOTS: usize = 512; - let (uma_base, offset) = (0x1_0000_0000usize, 0x4000u32); - let table = uma_base + offset as usize; // T#s (type nibble 8 in byte 15) naming shared-heap indexes 10 + k, at slots 10, 300 and 400 let mut mem = vec![0u8; SLOTS * 32]; for k in [10usize, 300, 400] { mem[32 * k..32 * k + 4].copy_from_slice(&(10 + k as u32).to_le_bytes()); mem[32 * k + 15] = 0x80; } + let offset = 0x4000u32; + let table = mem.as_ptr() as usize; + let uma_base = table - offset as usize; let args = offset.to_le_bytes().to_vec(); + let asked = std::cell::Cell::new(0); + let unregistered = std::cell::Cell::new(false); let found = |ranges: Vec, heap_slots: Option| { let layout = Layout { table_ranges: vec![(0, ranges)], ..Default::default() }; let mut used = Vec::new(); @@ -5433,8 +5438,19 @@ mod tests { &args, uma_base, |at| heap_slots.map(|n| n - (at - table) / 32), + |at, buf| { + if !unregistered.get() { + buf.copy_from_slice(&mem[at - table..at - table + buf.len()]); + } + !unregistered.get() + }, |_, _| false, - |at, buf| buf.copy_from_slice(&mem[at - table..at - table + buf.len()]), + |at, buf| { + asked.set(asked.get() + 1); + if !unregistered.get() { + buf.copy_from_slice(&mem[at - table..at - table + buf.len()]); + } + }, |index| 0x7000 + index as usize, |res| used.push(res), ); @@ -5451,6 +5467,14 @@ mod tests { assert!(found(vec![TableRange { start: 0, count: None }], None).is_empty()); // a bounded range is cut at the view heap's end assert_eq!(found(vec![TableRange { start: 300, count: Some(1000) }], Some(350)), vec![0x7000 + 310]); + assert_eq!(asked.get(), 0, "a view heap's slots are read where they are"); + // a bounded range outside any view heap: read through `read_committed` + assert_eq!(found(vec![TableRange { start: 300, count: Some(8) }], None), vec![0x7000 + 310]); + assert_eq!(asked.get(), 1); + // the view heap unregistered and decommitted after its lookup: read through `read_committed` + unregistered.set(true); + assert!(found(vec![TableRange { start: 300, count: Some(8) }], Some(SLOTS)).is_empty()); + assert_eq!(asked.get(), 2); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 3e44809a43..7be81d5f65 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -1092,6 +1092,17 @@ pub fn view_heap_remaining_slots(addr: usize) -> Option { Some((h.n as usize).saturating_sub(k)) } +/// Copy view slots at `addr` into `out` under `HEAPS` (false: not all inside one registered view +/// heap, and nothing copied). +pub fn copy_view_heap_slots(addr: usize, out: &mut [u8]) -> bool { + let heaps = HEAPS.lock().unwrap(); + if !heaps.iter().any(|h| !h.sampler && addr >= h.shadow && addr + out.len() <= h.shadow + (h.n as usize) * (SLOT as usize)) { + return false; + } + unsafe { std::ptr::copy_nonoverlapping(addr as *const u8, out.as_mut_ptr(), out.len()) }; + true +} + /// The slot behind a console CPU handle (None: not one of XCL's console heaps). A view slot /// of a heap in the shared heap gets its page's place there now if the page has none yet; one /// whose page finds no room there gets index 0, the null SRV / UAV pair. @@ -1742,6 +1753,20 @@ mod tests { assert_eq!(marks_passed(1 << 21, 1 << 21), 3, "no overflow at the largest heap"); } + #[test] + fn view_heap_slots_are_copied_only_while_the_heap_is_registered() { + let slots = vec![0xA5u8; 4 * SLOT as usize]; + let shadow = slots.as_ptr() as usize; + let generation = NEXT_HEAP_GENERATION.fetch_add(1, Ordering::Relaxed).wrapping_add(1); + HEAPS.lock().unwrap().push(Heap { generation, obj: shadow, shadow, n: 4, pc_cpu: 0, pc_gpu: 0, inc: 32, sampler: false, pages: Vec::new(), visible: true, memory: Memory::Uma }); + let mut out = [0u8; 2 * SLOT as usize]; + assert!(copy_view_heap_slots(shadow + SLOT as usize, &mut out)); + assert_eq!(out, [0xA5; 2 * SLOT as usize]); + assert!(!copy_view_heap_slots(shadow + 3 * SLOT as usize, &mut out), "past the heap's end"); + detach(shadow).unwrap(); + assert!(!copy_view_heap_slots(shadow, &mut out)); + } + #[test] fn exact_view_slot_lease_survives_detach_and_rejects_address_reuse() { const CHILD: &str = "XCL_TEST_VIEW_SLOT_LEASE_CHILD";