Sparse VRAM: async ring-buffered uploads, cached write-watch ranges, and coherent headroom

Follow-up to PR #40 addressing the two remaining issues noted after merge:

1. Sparse window upload & write-watch overhead (XDefiant ~10 GB in 55 s):
   - Replace per-submit synchronous staging + wait_idle() in d3d12x::sparse with an asynchronous 64 MiB ring staging buffer, 16 upload command allocators/lists, a reusable Win32 fence event, and a dedicated 1 MiB pre-zeroed tile-clear buffer (zero CPU stall on uploads; title queues GPU-wait on the upload fence as before).
   - Unify mapped tile tracking into per-tile TileEntry (pool tile + u16 hole bitmask + lazy per-page sent hashes) backed by FxHashMap, replace the serial chunk hash with a 4-way parallel hash + compile-time ZERO_HASHES, and scan directly into a reusable dirty-run scratch buffer without per-page Vec/Box allocations on zero pages.
   - Batch UpdateTileMappings by pool heap with contiguous run merging in map_tiles/unmap_tiles, and eliminate per-run COM AddRef/Release clones in upload loops.
   - Cache watch_ranges in title_textures keyed by atomic generation counters (sparse mapped tiles, textures, graphics reservations), reuse thread-local GetWriteWatch/dirty buffers, merge contiguous sparse windows in Uma::watch_regions(), and skip refresh on empty ExecuteCommandLists(0, null).

2. Coherent Window 3 headroom (complementing bb9f0b5's COHERENT_KEPT for textures):
   - Stop blanket-routing D3D12_HEAP_TYPE_CUSTOM + D3D12_CPU_PAGE_PROPERTY_WRITE_BACK heaps and non-COPY_DEST buffers to coherent Window 3 (on Xbox UMA, CUSTOM+WRITE_BACK is general CPU-cached graphics memory); route them to sparse VRAM and spill oversized/excess readback allocations to sparse VRAM once coherent headroom reaches COHERENT_KEPT, while tracking SPARSE_READBACK so Map(0, NULL, ...) still syncs GPU writes back automatically.
   - Pack small AllocateUploadMemory (#148) calls into the command list Arena and route large ones to sparse VRAM instead of burning 64 KiB coherent grains per call.
This commit is contained in:
raylitebull
2026-11-22 21:34:53 +01:00
parent 5dd2d56b4e
commit afaf413f25
9 changed files with 1296 additions and 318 deletions
+29
View File
@@ -431,6 +431,33 @@ impl Uma {
(self.base + k * WINDOW, len)
}
/// Underlying write-watched `VirtualAlloc` regions `(base, size)` for `GetWriteWatch`:
/// contiguous sparse windows belong to a single reservation, while each committed window
/// is its own allocation.
pub fn watch_regions(&self) -> Vec<(usize, usize)> {
let mut out: Vec<(usize, usize)> = Vec::with_capacity(MAX_WINDOWS);
let mut k = 0;
while k < MAX_WINDOWS {
match self.kinds[k] {
WindowKind::None => k += 1,
WindowKind::Committed(s) => {
out.push((self.base + k * WINDOW, s));
k += 1;
}
WindowKind::Sparse => {
let start = self.base + k * WINDOW;
let mut len = 0usize;
while k < MAX_WINDOWS && matches!(self.kinds[k], WindowKind::Sparse) {
len += WINDOW;
k += 1;
}
out.push((start, len));
}
}
}
out
}
pub fn window_of(&self, p: usize) -> Option<usize> {
let k = p.checked_sub(self.base)? / WINDOW;
let (start, len) = self.window(k);
@@ -834,5 +861,7 @@ mod tests {
assert_eq!(u.sparse_release(y), Some(GRAIN));
assert_eq!(u.sparse_release(desc), Some(GRAIN));
assert_eq!(u.sparse_used(), 0);
// Contiguous sparse windows 0..2 are reported as one OS watch region; window 3 as another.
assert_eq!(u.watch_regions(), vec![(u.base(), 3 * WINDOW), (u.base() + 3 * WINDOW, 16 << 20)]);
}
}
+17 -3
View File
@@ -53,10 +53,11 @@ fn count(k: usize) {
if n.is_power_of_two() && n >= 64 {
let c: Vec<u64> = COUNTS.iter().map(|c| c.load(Ordering::Relaxed)).collect();
let (allocators, blocks) = console_list::pending_blocks();
let (coherent_used, coherent_total, sparse_used) = crate::gpu::uma::get()
.map_or((0, 0, 0), |u| (u.used() >> 20, u.size() >> 20, u.sparse_used() >> 20));
crate::xlog_info!(
"D3D12.X: console code so far: {} draws with translated pipelines ({} skipped, {} with PC pipelines), {} dispatches ({} skipped); unified memory {} MB used, {blocks} blocks held for {allocators} allocators",
"D3D12.X: console code so far: {} draws with translated pipelines ({} skipped, {} with PC pipelines), {} dispatches ({} skipped); coherent {coherent_used}/{coherent_total} MB, sparse {sparse_used} MB, {blocks} blocks held for {allocators} allocators",
c[DRAWS], c[DRAWS_SKIPPED], c[DRAWS_PC], c[DISPATCHES], c[DISPATCHES_SKIPPED],
crate::gpu::uma::get().map_or(0, |u| u.used() >> 20)
);
}
}
@@ -625,7 +626,20 @@ pub(super) unsafe extern "system" fn allocate_upload_memory(this: *mut c_void, s
let Some(u) = crate::gpu::uma::get() else {
return std::ptr::null_mut();
};
match u.alloc(size.max(16), align.max(16)) {
let size = size.max(16);
let align = align.max(16);
if size <= crate::gpu::uma::ARENA_BLOCK / 2 {
if let Some(p) = with(this, |s| s.arena.take(u, size, align, &mut s.uma)) {
return p;
}
}
if u.has_sparse() {
if let Some((p, _)) = super::sparse::alloc(size, align) {
with(this, |s| s.uma.push(p));
return p as *mut u8;
}
}
match u.alloc(size, align) {
Some(p) => {
with(this, |s| s.uma.push(p as usize));
p
+19 -2
View File
@@ -496,7 +496,20 @@ unsafe extern "system" fn cl_barrier(this: *mut c_void, _n: u32, _barriers: *con
}
unsafe extern "system" fn cl_allocate_upload_memory(this: *mut c_void, size: usize, align: usize) -> *mut u8 {
let Some(u) = crate::gpu::uma::get() else { return std::ptr::null_mut() };
match u.alloc(size.max(16), align.max(16)) {
let size = size.max(16);
let align = align.max(16);
if size <= crate::gpu::uma::ARENA_BLOCK / 2 {
if let Some(p) = with_list(this as usize, |st| st.arena.take(u, size, align, &mut st.uma)).flatten() {
return p;
}
}
if u.has_sparse() {
if let Some((p, _)) = super::sparse::alloc(size, align) {
with_list(this as usize, |st| st.uma.push(p));
return p as *mut u8;
}
}
match u.alloc(size, align) {
Some(p) => {
with_list(this as usize, |st| st.uma.push(p as usize));
p
@@ -580,7 +593,11 @@ pub fn pc_pso(pso: *mut c_void) -> *mut c_void {
unsafe fn free_uma(blocks: &[usize]) {
if let Some(u) = crate::gpu::uma::get() {
for &b in blocks {
u.free(b);
if u.is_sparse(b) {
super::sparse::free(b);
} else {
u.free(b);
}
}
}
}
+159 -47
View File
@@ -1025,12 +1025,62 @@ unsafe fn place_console_texture(this: *mut c_void, desc: usize, state: usize, cl
Some(hr)
}
/// Whether `props` asks for CPU-cached readback memory (`D3D12_HEAP_TYPE_READBACK`, or
/// `D3D12_HEAP_TYPE_CUSTOM` with `D3D12_CPU_PAGE_PROPERTY_WRITE_BACK`), which stays on the
/// coherent committed window so CPU reads after a fence wait need no copy-back.
fn is_readback_heap(props: &D3D12_HEAP_PROPERTIES) -> bool {
/// Largest single `D3D12_HEAP_TYPE_READBACK` allocation kept on the coherent window; larger
/// ones spill to sparse VRAM so one big readback heap/buffer cannot exhaust coherent headroom.
const COHERENT_READBACK_MAX: usize = 64 << 20;
/// Largest single `D3D12_HEAP_TYPE_CUSTOM` + `WRITE_BACK` `COPY_DEST` buffer kept on coherent RAM.
const COHERENT_CUSTOM_WB_MAX: usize = 16 << 20;
fn has_coherent_headroom(u: &crate::gpu::uma::Uma, rounded: usize) -> bool {
let headroom = COHERENT_KEPT.min(u.size() / 4);
u.size().saturating_sub(u.used()) >= headroom.saturating_add(rounded)
}
/// Sparse-backed buffers whose `Map(0, NULL, ...)` should read back their full range from VRAM
/// (readback buffers that spilled to sparse VRAM or `COPY_DEST` buffers in `CUSTOM + WRITE_BACK`).
static SPARSE_READBACK: Mutex<Option<HashSet<usize>>> = Mutex::new(None);
fn note_sparse_readback(res: usize) {
SPARSE_READBACK.lock().unwrap().get_or_insert_with(HashSet::new).insert(res);
}
/// Whether `props` asks for CPU-cached readback memory. On Xbox UMA, `D3D12_HEAP_TYPE_CUSTOM`
/// with `D3D12_CPU_PAGE_PROPERTY_WRITE_BACK` is the general CPU-cached graphics pool (used for
/// hundreds of MB of VBs/IBs/CBs/UAVs), so only explicit `D3D12_HEAP_TYPE_READBACK` heaps — or
/// small non-UAV `COPY_DEST` buffers — stay in the 512 MB coherent window.
fn is_coherent_readback_buffer(props: &D3D12_HEAP_PROPERTIES, state: u32, flags: D3D12_RESOURCE_FLAGS, bytes: usize) -> bool {
if props.Type == D3D12_HEAP_TYPE_READBACK {
return bytes <= COHERENT_READBACK_MAX;
}
props.Type == D3D12_HEAP_TYPE_CUSTOM
&& props.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK
&& state == D3D12_RESOURCE_STATE_COPY_DEST.0 as u32
&& (flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0) == 0
&& bytes <= COHERENT_CUSTOM_WB_MAX
}
fn is_cpu_readback_buffer(props: &D3D12_HEAP_PROPERTIES, state: u32, flags: D3D12_RESOURCE_FLAGS) -> bool {
props.Type == D3D12_HEAP_TYPE_READBACK
|| (props.Type == D3D12_HEAP_TYPE_CUSTOM && props.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK)
|| (props.Type == D3D12_HEAP_TYPE_CUSTOM
&& props.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK
&& state == D3D12_RESOURCE_STATE_COPY_DEST.0 as u32
&& (flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0) == 0)
}
unsafe fn place_console_buffer_sparse(this: *mut c_void, d: &D3D12_RESOURCE_DESC, bytes: usize, state: u32, readback_on_null_map: bool, riid: *const GUID, ppv: *mut *mut c_void) -> Option<HRESULT> {
let (p, _) = super::sparse::alloc(bytes, 0x1_0000)?;
if let Some((hr, delta)) = super::sparse::place_buffer(this, p, d, state, riid, ppv) {
UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true));
if delta != 0 {
BUFFER_DELTA.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64);
}
if readback_on_null_map {
note_sparse_readback(*ppv as usize);
}
return Some(hr);
}
super::sparse::free(p);
None
}
unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> Option<HRESULT> {
@@ -1043,29 +1093,30 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta
return None;
}
let bytes = d.Width as usize;
let readback = props != 0
&& crate::gpu::shader::readable(props, std::mem::size_of::<D3D12_HEAP_PROPERTIES>())
&& is_readback_heap(&std::ptr::read_unaligned(props as *const D3D12_HEAP_PROPERTIES));
// Non-readback committed console buffers live in sparse VRAM windows (write-watched CPU
// view + tiled VRAM backing); readback / write-back buffers stay on coherent committed RAM.
if !readback && u.has_sparse() {
if let Some((p, _)) = super::sparse::alloc(bytes, 0x1_0000) {
let st = state as u32 & PC_RESOURCE_STATES;
if let Some((hr, delta)) = super::sparse::place_buffer(this, p, &d, st, riid, ppv) {
UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true));
if delta != 0 {
BUFFER_DELTA.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64);
}
return Some(hr);
}
super::sparse::free(p);
let st = state as u32 & PC_RESOURCE_STATES;
let heap_props = (props != 0 && crate::gpu::shader::readable(props, std::mem::size_of::<D3D12_HEAP_PROPERTIES>()))
.then(|| std::ptr::read_unaligned(props as *const D3D12_HEAP_PROPERTIES));
let rounded = (bytes + 0xFFFF) & !0xFFFF;
let prefer_coherent = heap_props.as_ref().is_some_and(|hp| is_coherent_readback_buffer(hp, st, d.Flags, bytes))
&& has_coherent_headroom(u, rounded);
let readback_on_null_map = heap_props.as_ref().is_some_and(|hp| is_cpu_readback_buffer(hp, st, d.Flags));
// Non-readback (and general CUSTOM+WRITE_BACK) committed console buffers live in sparse VRAM
// windows; small genuine readback buffers prefer coherent committed RAM (spilling to sparse if full).
if !prefer_coherent && u.has_sparse() {
if let Some(hr) = place_console_buffer_sparse(this, &d, bytes, st, readback_on_null_map, riid, ppv) {
return Some(hr);
}
}
let Some(p) = u.alloc(rounded, 0x1_0000).map(|a| a as usize) else {
if prefer_coherent && u.has_sparse() {
return place_console_buffer_sparse(this, &d, bytes, st, readback_on_null_map, riid, ppv);
}
return None;
};
// the heap from OpenExistingHeapFromAddress is cross-adapter: row-major + this flag
d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER;
d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
d.Alignment = 0;
let p = u.alloc((bytes + 0xFFFF) & !0xFFFF, 0x1_0000)? as usize;
let k = u.window_of(p)?;
let heap = (*UMA_HEAPS.lock().unwrap().get(k)?)?;
let hr = dev_create_placed_resource(this, heap, p - u.window(k).0, &d as *const _ as usize, state, clear, riid, ppv);
@@ -1154,14 +1205,18 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v
// a resource in unified memory: its console address (no PC mapping – the PC's would be
// the start of the PC resource, before the address for a buffer placed below it)
if let Some((p, bytes)) = console_buffer(this as usize) {
if !range.is_null() && crate::gpu::uma::get().is_some_and(|u| u.is_sparse(p)) {
let r = *(range as *const D3D12_RANGE);
if r.End > r.Begin {
let begin = r.Begin.min(bytes);
let end = r.End.min(bytes);
if end > begin {
super::sparse::readback_now(p + begin, end - begin);
if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(p)) {
if !range.is_null() {
let r = *(range as *const D3D12_RANGE);
if r.End > r.Begin {
let begin = r.Begin.min(bytes);
let end = r.End.min(bytes);
if end > begin {
super::sparse::readback_now(p + begin, end - begin);
}
}
} else if SPARSE_READBACK.lock().unwrap().as_ref().is_some_and(|s| s.contains(&(this as usize))) {
super::sparse::readback_now(p, bytes);
}
}
if !data.is_null() {
@@ -1246,6 +1301,9 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 {
if let Some(s) = UNMAPPABLE.lock().unwrap().as_mut() {
s.remove(&(this as usize));
}
if let Some(s) = SPARSE_READBACK.lock().unwrap().as_mut() {
s.remove(&(this as usize));
}
if let Some(m) = BUFFER_DELTA.lock().unwrap().as_mut() {
m.remove(&(this as usize));
}
@@ -1902,10 +1960,16 @@ pub(super) unsafe extern "system" fn dev_create_placed_resource_x(this: *mut c_v
if desc != 0 && crate::gpu::shader::readable(desc, 0x38) {
let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned();
let is_buffer = u32::from_le_bytes(x[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32;
if let Some(block) = is_buffer.then(|| heap_block(heap)).flatten() {
if let Some((block, cpu_readback)) = is_buffer.then(|| heap_block(heap)).flatten() {
let d = super::device_x::pc_resource_desc(&x);
let st = state as u32 & PC_RESOURCE_STATES;
if let Some(hr) = place_at_title_address(this, block + offset, &d, st, clear as *const c_void, riid, ppv) {
if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && cpu_readback && crate::gpu::uma::get().is_some_and(|u| u.is_sparse(block + offset)) {
let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap());
if st == D3D12_RESOURCE_STATE_COPY_DEST.0 as u32 && (flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 as u32) == 0 {
note_sparse_readback(*ppv as usize);
}
}
return hr;
}
}
@@ -2031,12 +2095,16 @@ pub(super) unsafe extern "system" fn dev_create_heap1(this: *mut c_void, desc: u
struct HeapUma {
size: usize,
align: usize,
readback: bool,
/// Small explicit `D3D12_HEAP_TYPE_READBACK` heap: prefers coherent Window 3 RAM.
prefer_coherent: bool,
/// `READBACK` or `CUSTOM + WRITE_BACK`: if backed by sparse VRAM, `COPY_DEST` buffers placed
/// in it read back on `Map(0, NULL, ...)`.
cpu_readback: bool,
block: Option<usize>,
}
/// heap → its backing block (allocated lazily on the first placed buffer; sparse VRAM for
/// DEFAULT/UPLOAD/write-combine heaps, coherent committed window for READBACK/write-back)
/// DEFAULT/UPLOAD/CUSTOM heaps, coherent committed window for small explicit READBACK heaps)
static HEAP_UMA: Mutex<Option<HashMap<usize, HeapUma>>> = Mutex::new(None);
/// A heap the title made that may hold buffers: a block of unified memory as large stands for
@@ -2057,35 +2125,43 @@ unsafe fn note_heap_uma(desc: usize, ppv: *mut *mut c_void) {
if d.Flags.0 & DENY_BUFFERS != 0 || d.SizeInBytes == 0 || UMA_BUFFER.lock().unwrap().is_empty() {
return;
}
let size = d.SizeInBytes as usize;
let is_rb = d.Properties.Type == D3D12_HEAP_TYPE_READBACK;
let is_custom_wb = d.Properties.Type == D3D12_HEAP_TYPE_CUSTOM && d.Properties.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
HEAP_UMA.lock().unwrap().get_or_insert_with(HashMap::new).insert(
*ppv as usize,
HeapUma {
size: d.SizeInBytes as usize,
size,
align: (d.Alignment as usize).max(0x1_0000),
readback: is_readback_heap(&d.Properties),
prefer_coherent: is_rb && size <= COHERENT_READBACK_MAX,
cpu_readback: is_rb || is_custom_wb,
block: None,
},
);
}
/// The block of unified memory standing for `heap` (taken now if it has none yet; None: not a
/// heap that takes one, or unified memory is full).
fn heap_block(heap: usize) -> Option<usize> {
let (size, align, readback) = {
/// The block of unified memory standing for `heap` and whether it may hold CPU-readback buffers
/// (taken now if it has none yet; None: not a heap that takes one, or unified memory is full).
fn heap_block(heap: usize) -> Option<(usize, bool)> {
let (size, align, prefer_coherent, cpu_readback) = {
let g = HEAP_UMA.lock().unwrap();
let e = g.as_ref()?.get(&heap)?;
if let Some(p) = e.block {
return Some(p);
return Some((p, e.cpu_readback));
}
(e.size, e.align, e.readback)
(e.size, e.align, e.prefer_coherent, e.cpu_readback)
};
let u = crate::gpu::uma::get()?;
let p = if !readback && u.has_sparse() {
let rounded = size.div_ceil(0x1_0000) * 0x1_0000;
let use_coherent = prefer_coherent && has_coherent_headroom(u, rounded);
let p = if !use_coherent && u.has_sparse() {
unsafe { super::sparse::alloc(size, align) }
.map(|(a, _)| a)
.or_else(|| u.alloc(size.div_ceil(0x1_0000) * 0x1_0000, align).map(|a| a as usize))
.or_else(|| u.alloc(rounded, align).map(|a| a as usize))
} else {
u.alloc(size.div_ceil(0x1_0000) * 0x1_0000, align).map(|a| a as usize)
u.alloc(rounded, align)
.map(|a| a as usize)
.or_else(|| u.has_sparse().then(|| unsafe { super::sparse::alloc(size, align) }.map(|(a, _)| a)).flatten())
};
let Some(p) = p else {
static FULL: AtomicU64 = AtomicU64::new(0);
@@ -2109,13 +2185,14 @@ fn heap_block(heap: usize) -> Option<usize> {
return None;
};
if let Some(existing) = e.block {
let cr = e.cpu_readback;
drop(g);
if u.is_sparse(p) {
unsafe { super::sparse::free(p) };
} else {
u.free(p);
}
return Some(existing);
return Some((existing, cr));
}
e.block = Some(p);
drop(g);
@@ -2124,7 +2201,7 @@ fn heap_block(heap: usize) -> Option<usize> {
let kind = if u.is_sparse(p) { "sparse VRAM" } else { "coherent RAM" };
crate::xlog_info!("D3D12.X: heap {heap:#x} ({size:#x} bytes) holds buffers: in {kind} at {p:#x}");
}
Some(p)
Some((p, cpu_readback))
}
/// ID3D12Heap::Release: its block of unified memory goes with it.
@@ -3487,13 +3564,13 @@ unsafe extern "system" fn q_signal_x(this: *mut c_void, fence: *mut c_void, valu
unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lists: *const *mut c_void) {
type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void);
let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ExecuteCommandLists")));
// textures in title memory the CPU wrote since: uploaded again first
super::title_textures::refresh(this);
if n == 0 || lists.is_null() {
f(this, n, lists);
stop_if_device_removed();
return;
}
// textures in title memory the CPU wrote since: uploaded again first
super::title_textures::refresh(this);
// console-shaped lists run as the PC lists they were translated into
let mapped: Vec<*mut c_void> = std::slice::from_raw_parts(lists, n as usize)
.iter()
@@ -3593,3 +3670,38 @@ pub fn stop_if_device_removed() {
}
}
}
#[cfg(test)]
mod readback_routing_tests {
use super::*;
#[test]
fn custom_write_back_only_stays_coherent_for_small_copy_dest_buffers() {
let rb = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
let custom_wb = D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_CUSTOM,
CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
..Default::default()
};
let copy_dest = D3D12_RESOURCE_STATE_COPY_DEST.0 as u32;
let gen_read = D3D12_RESOURCE_STATE_GENERIC_READ.0 as u32;
let uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
let none = D3D12_RESOURCE_FLAG_NONE;
assert!(is_coherent_readback_buffer(&rb, copy_dest, none, 4 << 20));
assert!(!is_coherent_readback_buffer(&rb, copy_dest, none, COHERENT_READBACK_MAX + 0x1_0000));
assert!(is_cpu_readback_buffer(&rb, copy_dest, none));
// General CUSTOM+WRITE_BACK buffers route to sparse VRAM, not coherent Window 3.
assert!(!is_coherent_readback_buffer(&custom_wb, gen_read, none, 4 << 20));
assert!(!is_cpu_readback_buffer(&custom_wb, gen_read, none));
assert!(!is_coherent_readback_buffer(&custom_wb, copy_dest, uav, 4 << 20));
assert!(!is_cpu_readback_buffer(&custom_wb, copy_dest, uav));
// Small non-UAV COPY_DEST CUSTOM+WRITE_BACK buffers may use coherent Window 3; larger ones spill.
assert!(is_coherent_readback_buffer(&custom_wb, copy_dest, none, 4 << 20));
assert!(!is_coherent_readback_buffer(&custom_wb, copy_dest, none, COHERENT_CUSTOM_WB_MAX + 0x1_0000));
assert!(is_cpu_readback_buffer(&custom_wb, copy_dest, none));
}
}
File diff suppressed because it is too large Load Diff
+86 -33
View File
@@ -58,6 +58,10 @@ unsafe impl Send for Entry {}
/// PC texture → its place in the title's memory
static TEXTURES: Mutex<BTreeMap<usize, Entry>> = Mutex::new(BTreeMap::new());
static TEXTURES_GEN: AtomicU64 = AtomicU64::new(0);
static TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
/// cached `watch_ranges` keyed by `(sparse::mapped_gen, TEXTURES_GEN, graphics_reservations_gen)`
static WATCH_CACHE: Mutex<Option<((u64, u64, u64), Arc<Vec<(usize, usize)>>)>> = Mutex::new(None);
/// the queue uploads go to, per device
static QUEUES: Mutex<BTreeMap<usize, ID3D12CommandQueue>> = Mutex::new(BTreeMap::new());
static UPLOADS: AtomicU64 = AtomicU64::new(0);
@@ -82,11 +86,16 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize,
if crate::gpu::uma::get().is_some_and(|u| u.contains(va)) || crate::hle::kernelx::in_graphics_reservation(va) {
ResetWriteWatch(va as *const c_void, bytes);
}
if let Some(old) = TEXTURES.lock().unwrap().insert(res as usize, e) {
if old.pending {
PENDING.fetch_sub(1, Ordering::Relaxed);
{
let mut t = TEXTURES.lock().unwrap();
if let Some(old) = t.insert(res as usize, e) {
if old.pending {
PENDING.fetch_sub(1, Ordering::Relaxed);
}
}
TEXTURES_LEN.store(t.len(), Ordering::Relaxed);
}
TEXTURES_GEN.fetch_add(1, Ordering::Release);
PENDING.fetch_add(1, Ordering::Relaxed);
Ok(())
}
@@ -115,8 +124,17 @@ pub fn overlapping(va: usize, len: usize) -> Vec<(usize, usize)> {
/// The PC texture was released for good.
pub fn forget(res: usize) {
if TEXTURES.lock().unwrap().remove(&res).is_some_and(|e| e.pending) {
PENDING.fetch_sub(1, Ordering::Relaxed);
let removed = {
let mut t = TEXTURES.lock().unwrap();
let r = t.remove(&res);
TEXTURES_LEN.store(t.len(), Ordering::Relaxed);
r
};
if let Some(e) = removed {
if e.pending {
PENDING.fetch_sub(1, Ordering::Relaxed);
}
TEXTURES_GEN.fetch_add(1, Ordering::Release);
}
}
@@ -129,6 +147,35 @@ thread_local! {
/// XCL's own submits on this thread (texture uploads): they read no title memory on the GPU,
/// so they do not look for CPU writes first – that look is the title's submits' job
static BUSY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Reusable `GetWriteWatch` output buffer (avoids 128 KiB alloc+zero+free per submit).
static WATCH_BUF: std::cell::RefCell<Vec<*mut c_void>> = const { std::cell::RefCell::new(Vec::new()) };
/// Reusable dirty page list for `refresh_once`.
static DIRTY_BUF: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
}
fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc<Vec<(usize, usize)>> {
let key = (
super::sparse::mapped_gen(),
TEXTURES_GEN.load(Ordering::Acquire),
crate::hle::kernelx::graphics_reservations_gen(),
);
{
let g = WATCH_CACHE.lock().unwrap();
if let Some((k, ref ranges)) = *g {
if k == key {
return Arc::clone(ranges);
}
}
}
// Recompute the watched ranges (textures kept in step + mapped sparse tiles clipped to
// write-watched regions) only when the set of textures, tiles, or reservations changed.
let mut regions = u.watch_regions();
regions.extend(crate::hle::kernelx::graphics_reservations());
let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().values().map(|e| (e.va & !0xFFF, (e.va + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect();
wanted.extend(super::sparse::mapped_ranges());
let computed = Arc::new(watch_ranges(&regions, wanted));
*WATCH_CACHE.lock().unwrap() = Some((key, Arc::clone(&computed)));
computed
}
/// Run `f` as XCL's own GPU work: ExecuteCommandLists inside it does not refresh.
@@ -157,35 +204,37 @@ pub(super) unsafe fn refresh(queue: *mut c_void) {
unsafe fn refresh_once(queue: *mut c_void) {
let Some(u) = crate::gpu::uma::get() else { return };
let sparse = u.has_sparse();
if TEXTURES.lock().unwrap().is_empty() && !sparse {
if !sparse && TEXTURES_LEN.load(Ordering::Relaxed) == 0 {
return;
}
let watch_t0 = std::time::Instant::now();
let mut dirty: Vec<usize> = Vec::new();
let mut page = 0x1000u32;
// the write-watched regions (the committed windows, the sparse ones – the title's
// reservations – and other graphics reservations) …
let regions: Vec<(usize, usize)> = (0..u.shader_windows()).map(|k| u.window(k)).chain(crate::hle::kernelx::graphics_reservations()).collect();
// … where a CPU write matters: the textures kept in step and the sparse windows' tiles
// with video memory. A scan costs with the size it covers (GetWriteWatch walks the page
// tables), and the whole regions are 16 GiB and more – looked at before every submit.
let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().values().map(|e| (e.va & !0xFFF, (e.va + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect();
wanted.extend(super::sparse::mapped_ranges());
let mut buf = vec![std::ptr::null_mut::<c_void>(); 16384];
for (base, size) in watch_ranges(&regions, wanted) {
loop {
let mut n = buf.len();
if GetWriteWatch(WRITE_WATCH_FLAG_RESET, base as *const c_void, size, buf.as_mut_ptr(), &mut n, &mut page) != 0 {
break;
let ranges = cached_watch_ranges(u);
let dirty_len = DIRTY_BUF.with(|dcell| {
let mut dirty = dcell.borrow_mut();
dirty.clear();
WATCH_BUF.with(|wcell| {
let mut buf = wcell.borrow_mut();
if buf.len() < 16384 {
buf.resize(16384, std::ptr::null_mut());
}
dirty.extend(buf[..n].iter().map(|&p| p as usize));
if n < buf.len() {
break;
for &(base, size) in ranges.iter() {
loop {
let mut n = buf.len();
if GetWriteWatch(WRITE_WATCH_FLAG_RESET, base as *const c_void, size, buf.as_mut_ptr(), &mut n, &mut page) != 0 {
break;
}
dirty.extend(buf[..n].iter().map(|&p| p as usize));
if n < buf.len() {
break;
}
}
}
}
}
dirty.sort_unstable();
super::sparse::note_watch(watch_t0.elapsed(), dirty.len());
});
dirty.sort_unstable();
dirty.len()
});
super::sparse::note_watch(watch_t0.elapsed(), dirty_len);
if super::present::trace_frame() {
// every 600th look: what the CPU's view of a few textures holds now (does the title's
// data reach the address at all, and is the texture still kept in step?)
@@ -212,19 +261,23 @@ unsafe fn refresh_once(queue: *mut c_void) {
crate::xlog_info!("frame trace: title texture at {:#x} ({} bytes) has data in memory ({c} of 65536 sampled bytes); GPU-written {}", e.va, e.tex.size(), e.gpu_written);
}
}
crate::xlog_info!("frame trace: title textures: {with} with data in memory, {without} all zero; {} dirty pages this look", dirty.len());
crate::xlog_info!("frame trace: title textures: {with} with data in memory, {without} all zero; {dirty_len} dirty pages this look");
}
}
// the title's own memory: what the CPU wrote goes to its video memory first
if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) {
super::sparse::before_execute(q, &dirty, page as usize);
DIRTY_BUF.with(|dcell| {
let dirty = dcell.borrow();
super::sparse::before_execute(q, &dirty, page as usize);
});
}
if dirty.is_empty() && PENDING.load(Ordering::Relaxed) == 0 {
if dirty_len == 0 && PENDING.load(Ordering::Relaxed) == 0 {
return;
}
// textures made since the last submit and those with a written page; a reference each
// while they are uploaded
let todo: Vec<(ID3D12Resource, Upload)> = {
let todo: Vec<(ID3D12Resource, Upload)> = DIRTY_BUF.with(|dcell| {
let dirty = dcell.borrow();
let mut t = TEXTURES.lock().unwrap();
t.iter_mut()
.filter(|(_, e)| {
@@ -246,7 +299,7 @@ unsafe fn refresh_once(queue: *mut c_void) {
ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.va, Arc::clone(&e.tex), e.state)))
})
.collect()
};
});
upload_all(todo);
}
+9 -2
View File
@@ -131,6 +131,12 @@ pub fn sanitize_protect(p: u32) -> u32 {
/// – where it maps physical pages (a texture streaming pool): base → size. Write-watched, like
/// unified memory, so textures in it follow CPU writes (`d3d12x::title_textures`).
static GRAPHICS_RESERVATIONS: std::sync::Mutex<std::collections::BTreeMap<usize, usize>> = std::sync::Mutex::new(std::collections::BTreeMap::new());
static GRAPHICS_RESERVATIONS_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Generation counter incremented whenever `GRAPHICS_RESERVATIONS` changes.
pub fn graphics_reservations_gen() -> u64 {
GRAPHICS_RESERVATIONS_GEN.load(Ordering::Acquire)
}
/// The title's graphics reservations (base, size).
pub fn graphics_reservations() -> Vec<(usize, usize)> {
@@ -219,6 +225,7 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t:
let q = mem::VirtualAlloc(addr, size, mem::MEM_RESERVE | MEM_WRITE_WATCH, sanitize_protect(p));
if !q.is_null() {
GRAPHICS_RESERVATIONS.lock().unwrap().insert(q as usize, size);
GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release);
return q;
}
}
@@ -274,8 +281,8 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32
}
return 1;
}
if t & 0x8000 != 0 {
GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize));
if t & 0x8000 != 0 && GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)).is_some() {
GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release);
}
mem::VirtualFree(addr, size, t)
}
+220
View File
@@ -1502,3 +1502,223 @@ pub fn sparse_buffer_heap_coherence() -> Result<(), String> {
Ok(())
}
}
/// Coherent Window 3 headroom: general `CUSTOM + WRITE_BACK` buffer heaps and buffers must
/// route to sparse VRAM (windows 0..2), leaving Window 3 free for XCL's Arena pool and small
/// explicit readback buffers, while `COPY_DEST` buffers in a sparse `CUSTOM + WRITE_BACK` heap
/// (and oversized `READBACK` buffers that spill to sparse VRAM) still read back automatically
/// on `Map(0, NULL, ...)`.
pub fn coherent_window_headroom() -> Result<(), String> {
unsafe {
let dev = device()?;
let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).map_err(e)?;
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)?;
let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?;
let win = |va: u64| ((va >> 32) & 3) as u32;
let buf_desc = |bytes: u64| 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,
..Default::default()
};
// 1. General CUSTOM + WRITE_BACK buffer and heap (Xbox UMA pattern) must live in sparse VRAM.
let custom_wb = D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_CUSTOM,
CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
..Default::default()
};
let mut custom_buf: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(&custom_wb, D3D12_HEAP_FLAG_NONE, &buf_desc(0x10_0000), D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut custom_buf).map_err(e)?;
let custom_buf = custom_buf.ok_or("custom wb committed buffer")?;
let custom_va = custom_buf.GetGPUVirtualAddress();
ensure!(custom_va != 0 && win(custom_va) != 3, "general CUSTOM+WRITE_BACK buffer landed in window 3: {custom_va:#x}");
let heap_desc = D3D12_HEAP_DESC {
SizeInBytes: 0x10_0000,
Properties: custom_wb,
Alignment: 0x1_0000,
Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES,
};
let mut wb_heap: Option<ID3D12Heap> = None;
dev.CreateHeap(&heap_desc, &mut wb_heap).map_err(e)?;
let wb_heap = wb_heap.ok_or("CUSTOM+WRITE_BACK heap")?;
let mut src_buf: Option<ID3D12Resource> = None;
dev.CreatePlacedResource(&wb_heap, 0, &buf_desc(0x1_0000), D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut src_buf).map_err(e)?;
let src_buf = src_buf.ok_or("placed src in wb heap")?;
ensure!(win(src_buf.GetGPUVirtualAddress()) != 3, "CUSTOM+WRITE_BACK heap landed in window 3: {:#x}", src_buf.GetGPUVirtualAddress());
let mut dst_rb: Option<ID3D12Resource> = None;
dev.CreatePlacedResource(&wb_heap, 0x1_0000, &buf_desc(0x1_0000), D3D12_RESOURCE_STATE_COPY_DEST, None, &mut dst_rb).map_err(e)?;
let dst_rb = dst_rb.ok_or("placed COPY_DEST in wb heap")?;
// 2. Oversized READBACK buffer (> 64 MiB) spills cleanly to sparse VRAM and still reads back on Map(NULL).
let mut big_rb: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(
&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() },
D3D12_HEAP_FLAG_NONE,
&buf_desc(65 << 20),
D3D12_RESOURCE_STATE_COPY_DEST,
None,
&mut big_rb,
)
.map_err(e)?;
let big_rb = big_rb.ok_or("oversized READBACK buffer")?;
ensure!(win(big_rb.GetGPUVirtualAddress()) != 3, "oversized READBACK buffer (>64 MiB) landed in window 3: {:#x}", big_rb.GetGPUVirtualAddress());
let mut p_src = std::ptr::null_mut();
src_buf.Map(0, None, Some(&mut p_src)).map_err(e)?;
*(p_src as *mut u32) = 0x5EED_CAFE;
*((p_src as *mut u32).add(1)) = 0x1234_5678;
list.CopyBufferRegion(&dst_rb, 0, &src_buf, 0, 64);
list.CopyBufferRegion(&big_rb, 0, &src_buf, 0, 64);
list.Close().map_err(e)?;
queue.ExecuteCommandLists(&[Some(list.cast::<ID3D12CommandList>().map_err(e)?)]);
wait(&queue, &fence, 1)?;
// Map(0, NULL, ...) on both sparse readback buffers must automatically sync from VRAM.
let mut p_dst = std::ptr::null_mut();
dst_rb.Map(0, None, Some(&mut p_dst)).map_err(e)?;
let w0 = *(p_dst as *const u32);
let w1 = *((p_dst as *const u32).add(1));
ensure!(w0 == 0x5EED_CAFE && w1 == 0x1234_5678, "CUSTOM+WRITE_BACK COPY_DEST Map(NULL) readback mismatch: {w0:#x} {w1:#x}");
let mut p_big = std::ptr::null_mut();
big_rb.Map(0, None, Some(&mut p_big)).map_err(e)?;
let b0 = *(p_big as *const u32);
let b1 = *((p_big as *const u32).add(1));
ensure!(b0 == 0x5EED_CAFE && b1 == 0x1234_5678, "oversized READBACK Map(NULL) readback mismatch: {b0:#x} {b1:#x}");
Ok(())
}
}
/// Asynchronous ring-buffered sparse upload stress test: streams 80 MiB across 20 back-to-back
/// pipelined submits (wrapping both the 64 MiB staging ring and the 16 upload command slots
/// without CPU waits between submits), plus reused-tile zeroing before new CPU writes.
pub fn sparse_async_ring_upload_stress() -> Result<(), String> {
unsafe {
let dev = device()?;
let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).map_err(e)?;
let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?;
const SLICE_BYTES: usize = 4 << 20; // 4 MiB per submit
const SUBMITS: usize = 20; // 80 MiB total > 64 MiB staging ring, 20 > 16 upload slots
const TOTAL_BYTES: usize = SLICE_BYTES * SUBMITS;
let buf_desc = |bytes: u64| 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,
..Default::default()
};
let mut src: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(
&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() },
D3D12_HEAP_FLAG_NONE,
&buf_desc(TOTAL_BYTES as u64),
D3D12_RESOURCE_STATE_GENERIC_READ,
None,
&mut src,
)
.map_err(e)?;
let src = src.ok_or("stress upload buffer")?;
let mut rb: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(
&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() },
D3D12_HEAP_FLAG_NONE,
&buf_desc((SUBMITS * 64) as u64),
D3D12_RESOURCE_STATE_COPY_DEST,
None,
&mut rb,
)
.map_err(e)?;
let rb = rb.ok_or("stress readback buffer")?;
let mut p_src = std::ptr::null_mut();
src.Map(0, None, Some(&mut p_src)).map_err(e)?;
let mut p_rb = std::ptr::null_mut();
rb.Map(0, None, Some(&mut p_rb)).map_err(e)?;
let mut allocs = Vec::with_capacity(SUBMITS);
let mut lists = Vec::with_capacity(SUBMITS);
for _ in 0..SUBMITS {
let a: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?;
let l: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &a, None).map_err(e)?;
allocs.push(a);
lists.push(l);
}
// Write a disjoint 4 MiB slice on every submit (ring-buffer style) so all 80 MiB cross
// the 64 MiB staging ring and 16 upload slots back-to-back without waiting between submits.
let src_u32 = p_src as *mut u32;
let slice_words = SLICE_BYTES / 4;
for s in 0..SUBMITS {
let tag = 0xA500_0000u32 | (s as u32);
let base_word = s * slice_words;
// Touch every 64-byte chunk across this 4 MiB slice so all 4 MiB are genuinely uploaded
for off in (0..slice_words).step_by(16) {
*src_u32.add(base_word + off) = tag ^ (off as u32);
}
let list = &lists[s];
let slice_off = (s * SLICE_BYTES) as u64;
// Copy first 32 bytes + last 32 bytes of this 4 MiB slice into readback slot s
list.CopyBufferRegion(&rb, (s * 64) as u64, &src, slice_off, 32);
list.CopyBufferRegion(&rb, (s * 64 + 32) as u64, &src, slice_off + (SLICE_BYTES - 64) as u64, 32);
list.Close().map_err(e)?;
queue.ExecuteCommandLists(&[Some(list.cast::<ID3D12CommandList>().map_err(e)?)]);
}
wait(&queue, &fence, 1)?;
let rb_u32 = p_rb as *const u32;
let last_off = (slice_words - 16) as u32;
for s in 0..SUBMITS {
let tag = 0xA500_0000u32 | (s as u32);
let got_head = *rb_u32.add(s * 16);
let got_tail = *rb_u32.add(s * 16 + 8);
ensure!(got_head == tag, "submit {s} head mismatch: got {got_head:#x}, want {tag:#x}");
ensure!(got_tail == (tag ^ last_off), "submit {s} tail mismatch: got {got_tail:#x}, want {:#x}", tag ^ last_off);
}
// Release `src` so its tiles enter the free list, then allocate a new buffer reusing tiles
// and verify `zero_buf` clears untouched bytes before our new write lands.
drop(src);
let mut reused: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(
&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() },
D3D12_HEAP_FLAG_NONE,
&buf_desc(0x2_0000),
D3D12_RESOURCE_STATE_GENERIC_READ,
None,
&mut reused,
)
.map_err(e)?;
let reused = reused.ok_or("reused tile buffer")?;
let mut p_reused = std::ptr::null_mut();
reused.Map(0, None, Some(&mut p_reused)).map_err(e)?;
*(p_reused as *mut u32) = 0x7788_99AA;
allocs[0].Reset().map_err(e)?;
lists[0].Reset(&allocs[0], None).map_err(e)?;
lists[0].CopyBufferRegion(&rb, 0, &reused, 0, 128);
lists[0].Close().map_err(e)?;
queue.ExecuteCommandLists(&[Some(lists[0].cast::<ID3D12CommandList>().map_err(e)?)]);
wait(&queue, &fence, 2)?;
ensure!(*rb_u32.add(0) == 0x7788_99AA, "reused tile written word mismatch: {:#x}", *rb_u32.add(0));
ensure!(*rb_u32.add(16) == 0, "reused tile untouched chunk was not zeroed: {:#x}", *rb_u32.add(16));
Ok(())
}
}
+2
View File
@@ -618,6 +618,8 @@ fn main() {
check("D3D12.X: console device methods (placed title memory, DMA queue + list, page pools)", gpu::console_device_methods);
check("D3D12.X: console command list memory methods (writes, timestamp, fill, copy, KickoffX, Wait32/64)", gpu::console_list_methods);
check("D3D12.X: sparse VRAM buffer heaps (placed aliasing, persistent Map coherence, readback)", gpu::sparse_buffer_heap_coherence);
check("D3D12.X: coherent window headroom (CUSTOM+WRITE_BACK & oversized READBACK in sparse VRAM)", gpu::coherent_window_headroom);
check("D3D12.X: async ring-buffered sparse uploads (80 MiB across 20 submits + reused-tile zeroing)", gpu::sparse_async_ring_upload_stress);
check("D3D12.X: dynamic depth bias via RSSetDepthBiasX (#94)", gpu::dynamic_depth_bias);
check("D3D12.X: raytracing surface (OPTIONS5, AS SRV descriptor, #146/#148 BVH list slots)", gpu::raytracing_surface);
check("DirectStorage (xcrdapi): a file read into memory, status + D3D12 fence", gpu::direct_storage);