Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 108 additions & 22 deletions crates/xcl/src/hle/d3d12x/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize>,
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;
}
}
}
Expand Down Expand Up @@ -5327,6 +5367,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<TableRange>, heap_slots: Option<usize>| {
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::<HashSet<_>>();
Expand Down
9 changes: 9 additions & 0 deletions crates/xcl/src/hle/d3d12x/console_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize> {
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.
Expand Down
76 changes: 75 additions & 1 deletion crates/xcl/src/hle/d3d12x/console_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32>,
}

/// 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<Param>,
/// Declared SRV/UAV descriptor intervals per descriptor-table parameter (`(at, ranges)`).
pub table_ranges: Vec<(u32, Vec<TableRange>)>,
pub size: u32,
pub inline: u32,
pub inline_gfx: u32,
Expand Down Expand Up @@ -149,6 +159,7 @@ pub fn layout_from_blob(blob: &[u8]) -> Option<Layout> {
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() };
Expand All @@ -163,7 +174,34 @@ pub fn layout_from_blob(blob: &[u8]) -> Option<Layout> {
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)?,
Expand Down Expand Up @@ -1306,6 +1344,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<u8> {
// 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)]);
Expand Down
Loading