diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 9480182..0e06eb4 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -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 { 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)]); } } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 9a7c8bf..93260a0 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -53,10 +53,11 @@ fn count(k: usize) { if n.is_power_of_two() && n >= 64 { let c: Vec = 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 diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index e8f1abb..81dbef7 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -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); + } } } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a49d695..73db7e5 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -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>> = 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 { + 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 { @@ -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::()) - && 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::())) + .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, } /// 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>> = 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 { - 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 { 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 { 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)); + } +} diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 32c3aa7..8917811 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -3,24 +3,27 @@ //! A console title keeps GPU data in memory it reserves and commits itself (XDefiant: one //! 8 GB reservation of 64 KiB pages it commits in steps and places buffers in) – on the //! console all of it is GPU-visible at the same addresses. XCL gives such reservations -//! addresses in the *sparse windows* of the unified-memory block (`gpu::uma`: windows after -//! the committed one, reserved only), so translated shaders reach them through `mem1`…`mem3` -//! like any unified memory. On the GPU each sparse window is a reserved (tiled) buffer of -//! 4 GiB whose 64 KiB tiles are mapped onto video-memory heaps as the title commits pages. +//! addresses in the *sparse windows* of the unified-memory block (`gpu::uma`: windows 0..2 +//! in `for_runtime`), so translated shaders reach them through `mem`…`mem2` like any unified +//! memory. On the GPU each sparse window is a reserved (tiled) buffer of 4 GiB whose 64 KiB +//! tiles are mapped onto video-memory heaps as the title commits pages. //! The CPU's view stays the title's memory: what the CPU wrote (write-watch) is copied into -//! the tiles before the title's next ExecuteCommandLists, and its queues wait for that copy. +//! the tiles before the title's next ExecuteCommandLists via an asynchronous ring-buffered +//! staging upload queue, and the title's queues GPU-wait on the upload fence (no CPU stall). //! Only the bytes the CPU changed go (64-byte chunks against a hash of what was sent last, //! `changed_chunks`): the rest of a written page may hold what the GPU wrote there (counters, //! indirect arguments) and must not be overwritten with the CPU's stale view of it. //! Buffers the title places there get reserved resources over the same tiles, so PC-side -//! copies, views and barriers see the same memory. GPU writes are not copied back to the -//! CPU's view (not needed by rendering so far). +//! copies, views and barriers see the same memory. -use std::collections::{HashMap, HashSet}; +use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; +use std::hash::{BuildHasherDefault, Hasher}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Mutex; use windows::core::Interface; +use windows::Win32::Foundation::{CloseHandle, HANDLE}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_DECOMMIT, PAGE_READWRITE}; @@ -28,16 +31,80 @@ use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, const TILE: usize = 0x1_0000; /// tiles of a video-memory pool heap (64 MiB) const POOL_TILES: u32 = 1024; -/// bytes of the upload staging buffer +/// bytes of the ring-buffered upload staging buffer const STAGING: usize = 64 << 20; +/// alignment of sub-allocations inside the upload staging ring (write-combined cacheline) +const RING_ALIGN: usize = 64; +/// number of in-flight upload command allocators / lists +const UPLOAD_SLOTS: usize = 16; +/// bytes of the dedicated pre-zeroed buffer for tile/hole clears (1 MiB) +const ZERO_BUF: usize = 1 << 20; /// bytes of the GPU→CPU readback staging buffer const READBACK_STAGING: usize = 16 << 20; +const PAGE: usize = 0x1000; +const PAGES_PER_TILE: usize = TILE / PAGE; +const CHUNK: usize = 64; +const CHUNKS: usize = PAGE / CHUNK; + +/// Fast non-cryptographic integer hasher for page/tile lookup maps on the hot submit path. +#[derive(Default)] +struct FxHasher(u64); + +impl Hasher for FxHasher { + #[inline] + fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.0 = (self.0.rotate_left(5) ^ b as u64).wrapping_mul(0x517C_C1B7_2722_0A95); + } + } + #[inline] + fn write_usize(&mut self, i: usize) { + self.0 = (self.0.rotate_left(5) ^ i as u64).wrapping_mul(0x517C_C1B7_2722_0A95); + } + #[inline] + fn write_u32(&mut self, i: u32) { + self.0 = (self.0.rotate_left(5) ^ i as u64).wrapping_mul(0x517C_C1B7_2722_0A95); + } + #[inline] + fn write_u64(&mut self, i: u64) { + self.0 = (self.0.rotate_left(5) ^ i).wrapping_mul(0x517C_C1B7_2722_0A95); + } + #[inline] + fn finish(&self) -> u64 { + self.0 + } +} + +type FxHashMap = HashMap>; + +struct TileEntry { + pool: (u32, u32), + /// bit `i` set => 4 KiB page `i` of this 64 KiB tile is uncommitted (a hole) + holes: u16, + /// per-4 KiB-page hashes of the 64-byte chunks last sent to the GPU (`None` = all zero) + sent: [Option>; PAGES_PER_TILE], +} + +impl TileEntry { + fn new(pool: (u32, u32)) -> Self { + Self { pool, holes: 0, sent: std::array::from_fn(|_| None) } + } +} + +struct UploadSlot { + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence_val: u64, +} + struct State { dev: ID3D12Device, queue: ID3D12CommandQueue, fence: ID3D12Fence, value: u64, + /// reusable auto-reset Win32 event for fence waits (no per-wait CreateEventW/CloseHandle) + event: HANDLE, /// fence signalled on title queues so `queue` waits before copying GPU writes back to CPU rb_fence: ID3D12Fence, rb_value: u64, @@ -45,44 +112,142 @@ struct State { windows: Vec<(usize, ID3D12Resource)>, pools: Vec, free: Vec<(u32, u32)>, - /// tile address → (pool, tile in it) - mapped: HashMap, + /// tile address → pool tile + uncommitted page hole mask + per-page sent chunk hashes + mapped: FxHashMap, /// pool tiles also used by placed buffers (not freed while they are) - pinned: HashMap<(u32, u32), u32>, + pinned: FxHashMap<(u32, u32), u32>, /// placed buffers → the pool tiles they use - buffers: HashMap>, - /// reused tiles to clear: (address, bytes) + buffers: FxHashMap>, + /// reused tiles / decommitted partial pages to clear: (address, bytes) to_zero: Vec<(usize, usize)>, + /// ring-buffered upload staging heap (`STAGING` bytes, persistently mapped) staging: Option<(ID3D12Resource, *mut u8)>, + /// monotonic ring-buffer write/submitted/retired byte cursors + ring_write: u64, + ring_submitted: u64, + ring_free: u64, + /// submitted ring chunks awaiting GPU completion: `(fence_val, ring_end_pos)` + inflight: VecDeque<(u64, u64)>, + /// dedicated 1 MiB pre-zeroed buffer for tile/hole clears (zero staging bandwidth) + zero_buf: Option, + /// ring of async upload command allocators + lists + slots: Vec, + next_slot: usize, + /// dedicated readback staging buffer + command allocator / list readback: Option<(ID3D12Resource, *mut u8)>, - alloc: ID3D12CommandAllocator, - list: ID3D12GraphicsCommandList, + rb_alloc: ID3D12CommandAllocator, + rb_list: ID3D12GraphicsCommandList, + rb_last_fence: u64, /// the fence value each title queue last waited for - waited: HashMap, - /// 4 KiB page → hash of each 64-byte chunk the GPU got from the CPU (absent: all zero) - sent: HashMap>, + waited: FxHashMap, /// `mapped` as sorted (start, end) runs (None: to be made again) runs: Option>, - /// 4 KiB pages of mapped tiles the title has not committed (a tile mapped for part of it, - /// a page decommitted inside one): no memory to read there - holes: HashSet, + /// reusable buffer for dirty runs in `before_execute` (avoids per-submit heap alloc) + scratch_runs: Vec<(usize, usize)>, } -const PAGE: usize = 0x1000; -const CHUNK: usize = 64; -const CHUNKS: usize = PAGE / CHUNK; +impl Drop for State { + fn drop(&mut self) { + if !self.event.is_invalid() { + unsafe { + let _ = CloseHandle(self.event); + } + } + } +} + +const K0: u64 = 0x9E37_79B9_7F4A_7C15; +const K1: u64 = 0xBF58_476D_1CE4_E5B9; +const K2: u64 = 0x94D0_49BB_1331_11EB; +const K3: u64 = 0x243F_6A88_85A3_08D3; + +/// 4-way parallel hash over 8 `u64` words (64 bytes): breaks serial multiply latency chain. +#[inline(always)] +const fn hash_words(w: [u64; 8]) -> u64 { + let a = (w[0] ^ K3).wrapping_mul(K0) ^ w[4].wrapping_mul(K1); + let b = (w[1] ^ K0).wrapping_mul(K1) ^ w[5].wrapping_mul(K2); + let c = (w[2] ^ K1).wrapping_mul(K2) ^ w[6].wrapping_mul(K3); + let d = (w[3] ^ K2).wrapping_mul(K3) ^ w[7].wrapping_mul(K0); + let h = a.rotate_left(27).wrapping_add(b.rotate_left(13)) ^ c.rotate_left(41).wrapping_add(d.rotate_left(53)); + h.wrapping_mul(K0) ^ (h >> 32) +} + +const ZERO_HASH: u64 = hash_words([0; 8]); +const ZERO_HASHES: [u64; CHUNKS] = [ZERO_HASH; CHUNKS]; + +#[inline(always)] +fn read_chunk_words(c: &[u8]) -> [u64; 8] { + debug_assert_eq!(c.len(), CHUNK); + let p = c.as_ptr() as *const [u8; 8]; + unsafe { + [ + u64::from_le_bytes(p.add(0).read_unaligned()), + u64::from_le_bytes(p.add(1).read_unaligned()), + u64::from_le_bytes(p.add(2).read_unaligned()), + u64::from_le_bytes(p.add(3).read_unaligned()), + u64::from_le_bytes(p.add(4).read_unaligned()), + u64::from_le_bytes(p.add(5).read_unaligned()), + u64::from_le_bytes(p.add(6).read_unaligned()), + u64::from_le_bytes(p.add(7).read_unaligned()), + ] + } +} /// hash of 64 bytes +#[inline(always)] fn chunk_hash(c: &[u8]) -> u64 { - let mut h = 0x243F_6A88_85A3_08D3u64; - for w in c.chunks_exact(8) { - h = (h ^ u64::from_le_bytes(w.try_into().unwrap())).wrapping_mul(0x9E37_79B9_7F4A_7C15).rotate_left(29); - } - h + hash_words(read_chunk_words(c)) } -fn zero_hashes() -> [u64; CHUNKS] { - [chunk_hash(&[0u8; CHUNK]); CHUNKS] +#[inline(always)] +fn push_run(out: &mut Vec<(usize, usize)>, addr: usize, len: usize) { + match out.last_mut() { + Some(last) if last.0 + last.1 == addr => last.1 += len, + _ => out.push((addr, len)), + } +} + +/// Scan a 4 KiB page at `pg`, appending any changed 64-byte chunk runs directly to `out` +/// (zero per-page heap allocation; skips allocating `slot` completely when a fresh zero page +/// is still all zeros). +#[inline] +fn scan_page(page: &[u8], pg: usize, slot: &mut Option>, out: &mut Vec<(usize, usize)>) { + if let Some(sent) = slot.as_deref_mut() { + for (k, c) in page.chunks_exact(CHUNK).enumerate() { + let h = chunk_hash(c); + if h == sent[k] { + continue; + } + sent[k] = h; + push_run(out, pg + k * CHUNK, CHUNK); + } + return; + } + // Page has never had non-zero data sent: skip zero chunks with a cheap OR-reduction and + // allocate the hash array only if at least one chunk is non-zero. + let mut chunks = page.chunks_exact(CHUNK).enumerate(); + while let Some((k, c)) = chunks.next() { + let w = read_chunk_words(c); + if (w[0] | w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7]) == 0 { + continue; + } + let h = hash_words(w); + if h == ZERO_HASH { + continue; + } + let sent = slot.insert(Box::new(ZERO_HASHES)); + sent[k] = h; + push_run(out, pg + k * CHUNK, CHUNK); + for (k2, c2) in chunks { + let h2 = chunk_hash(c2); + if h2 == ZERO_HASH { + continue; + } + sent[k2] = h2; + push_run(out, pg + k2 * CHUNK, CHUNK); + } + break; + } } /// The byte ranges (offset, length) of `page` whose 64-byte chunks differ from `sent` @@ -95,20 +260,43 @@ pub fn changed_chunks(page: &[u8], sent: &mut [u64; CHUNKS]) -> Vec<(usize, usiz continue; } sent[k] = h; - match out.last_mut() { - Some(last) if last.0 + last.1 == k * CHUNK => last.1 += CHUNK, - _ => out.push((k * CHUNK, CHUNK)), - } + push_run(&mut out, k * CHUNK, CHUNK); } out } -// D3D12 objects are free-threaded; the staging pointer is only used under the lock +/// Plan a contiguous sub-allocation `(aligned_pos, chunk_len)` inside a ring buffer of `cap` +/// bytes starting at monotonic cursor `ring_write`, keeping each chunk `<= cap / 2` and +/// avoiding mid-copy wrap-around without wasting large tail gaps. +#[inline] +fn plan_ring_chunk(ring_write: u64, want: usize, cap: usize) -> (u64, usize) { + let mut chunk = want.min(cap / 2); + let mut aligned = (ring_write + (RING_ALIGN as u64 - 1)) & !(RING_ALIGN as u64 - 1); + let off = (aligned as usize) % cap; + if off + chunk > cap { + let tail = cap - off; + if tail >= PAGE { + chunk = tail; + } else { + aligned += tail as u64; + } + } + (aligned, chunk) +} + +// D3D12 objects are free-threaded; staging pointers and event handle are only used under STATE lock unsafe impl Send for State {} static STATE: Mutex> = Mutex::new(None); /// commits before the device existed static EARLY: Mutex> = Mutex::new(Vec::new()); +/// generation counter incremented whenever the set of mapped tiles changes (for watch_ranges cache) +static MAPPED_GEN: AtomicU64 = AtomicU64::new(0); + +/// Generation counter of `mapped_ranges()` (changes only when tiles are mapped or unmapped). +pub fn mapped_gen() -> u64 { + MAPPED_GEN.load(Ordering::Acquire) +} fn buffer_desc(bytes: u64) -> D3D12_RESOURCE_DESC { D3D12_RESOURCE_DESC { @@ -151,31 +339,47 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)?; - list.Close()?; + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None)?; + let mut slots = Vec::with_capacity(UPLOAD_SLOTS); + for _ in 0..UPLOAD_SLOTS { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)?; + list.Close()?; + slots.push(UploadSlot { alloc, list, fence_val: 0 }); + } + let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None)?; + rb_list.Close()?; Ok(State { dev: dev.clone(), queue, fence, value: 0, + event, rb_fence, rb_value: 0, windows, pools: Vec::new(), free: Vec::new(), - mapped: HashMap::new(), - pinned: HashMap::new(), - buffers: HashMap::new(), + mapped: FxHashMap::default(), + pinned: FxHashMap::default(), + buffers: FxHashMap::default(), to_zero: Vec::new(), staging: None, + ring_write: 0, + ring_submitted: 0, + ring_free: 0, + inflight: VecDeque::new(), + zero_buf: None, + slots, + next_slot: 0, readback: None, - alloc, - list, - waited: HashMap::new(), - sent: HashMap::new(), + rb_alloc, + rb_list, + rb_last_fence: 0, + waited: FxHashMap::default(), runs: None, - holes: HashSet::new(), + scratch_runs: Vec::new(), }) })(); match made { @@ -195,8 +399,9 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { } impl State { - fn window(&self, a: usize) -> Option<(usize, &ID3D12Resource)> { - self.windows.iter().find(|(b, _)| a >= *b && a < *b + crate::gpu::uma::WINDOW).map(|(b, r)| (*b, r)) + #[inline] + fn window_index(&self, a: usize) -> Option { + self.windows.iter().position(|(b, _)| a >= *b && a < *b + crate::gpu::uma::WINDOW) } unsafe fn take_tile(&mut self) -> Option<((u32, u32), bool)> { @@ -220,23 +425,92 @@ impl State { Some(((h, 0), false)) } - /// map `tiles` (tile addresses) of `res` (starting at `res_base`) onto pool tiles + /// Map `tiles` (tile addresses) of `res` (starting at `res_base`) onto pool tiles, + /// batched per pool heap with contiguous runs merged into single regions. unsafe fn map_tiles(&self, res: &ID3D12Resource, res_base: usize, tiles: &[(usize, (u32, u32))]) { + if tiles.is_empty() { + return; + } + let mut by_heap: FxHashMap> = FxHashMap::default(); for &(a, (h, t)) in tiles { - let start = D3D12_TILED_RESOURCE_COORDINATE { X: ((a - res_base) / TILE) as u32, ..Default::default() }; - let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, UseBox: false.into(), ..Default::default() }; - let (flags, n) = (D3D12_TILE_RANGE_FLAG_NONE, 1u32); - self.queue.UpdateTileMappings(res, 1, Some(&start), Some(®ion), &self.pools[h as usize], 1, Some(&flags), Some(&t), Some(&n), D3D12_TILE_MAPPING_FLAG_NONE); + by_heap.entry(h).or_default().push((((a - res_base) / TILE) as u32, t)); + } + for (h, mut pairs) in by_heap { + pairs.sort_unstable_by_key(|&(x, _)| x); + let mut coords: Vec = Vec::with_capacity(pairs.len()); + let mut regions: Vec = Vec::with_capacity(pairs.len()); + let mut flags: Vec = Vec::with_capacity(pairs.len()); + let mut offsets: Vec = Vec::with_capacity(pairs.len()); + let mut counts: Vec = Vec::with_capacity(pairs.len()); + let mut i = 0; + while i < pairs.len() { + let (x0, t0) = pairs[i]; + let mut run = 1u32; + while i + (run as usize) < pairs.len() { + let (nx, nt) = pairs[i + run as usize]; + if nx == x0 + run && nt == t0 + run { + run += 1; + } else { + break; + } + } + coords.push(D3D12_TILED_RESOURCE_COORDINATE { X: x0, ..Default::default() }); + regions.push(D3D12_TILE_REGION_SIZE { NumTiles: run, UseBox: false.into(), ..Default::default() }); + flags.push(D3D12_TILE_RANGE_FLAG_NONE); + offsets.push(t0); + counts.push(run); + i += run as usize; + } + self.queue.UpdateTileMappings( + res, + coords.len() as u32, + Some(coords.as_ptr()), + Some(regions.as_ptr()), + &self.pools[h as usize], + flags.len() as u32, + Some(flags.as_ptr()), + Some(offsets.as_ptr()), + Some(counts.as_ptr()), + D3D12_TILE_MAPPING_FLAG_NONE, + ); } } unsafe fn unmap_tiles(&self, res: &ID3D12Resource, res_base: usize, tiles: &[usize]) { - for &a in tiles { - let start = D3D12_TILED_RESOURCE_COORDINATE { X: ((a - res_base) / TILE) as u32, ..Default::default() }; - let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, UseBox: false.into(), ..Default::default() }; - let flags = D3D12_TILE_RANGE_FLAG_NULL; - self.queue.UpdateTileMappings(res, 1, Some(&start), Some(®ion), None, 1, Some(&flags), None, None, D3D12_TILE_MAPPING_FLAG_NONE); + if tiles.is_empty() { + return; } + let mut xs: Vec = tiles.iter().map(|&a| ((a - res_base) / TILE) as u32).collect(); + xs.sort_unstable(); + let mut coords: Vec = Vec::with_capacity(xs.len()); + let mut regions: Vec = Vec::with_capacity(xs.len()); + let mut flags: Vec = Vec::with_capacity(xs.len()); + let mut counts: Vec = Vec::with_capacity(xs.len()); + let mut i = 0; + while i < xs.len() { + let x0 = xs[i]; + let mut run = 1u32; + while i + (run as usize) < xs.len() && xs[i + run as usize] == x0 + run { + run += 1; + } + coords.push(D3D12_TILED_RESOURCE_COORDINATE { X: x0, ..Default::default() }); + regions.push(D3D12_TILE_REGION_SIZE { NumTiles: run, UseBox: false.into(), ..Default::default() }); + flags.push(D3D12_TILE_RANGE_FLAG_NULL); + counts.push(run); + i += run as usize; + } + self.queue.UpdateTileMappings( + res, + coords.len() as u32, + Some(coords.as_ptr()), + Some(regions.as_ptr()), + None, + flags.len() as u32, + Some(flags.as_ptr()), + None, + Some(counts.as_ptr()), + D3D12_TILE_MAPPING_FLAG_NONE, + ); } /// tiles of `[a, a + n)` get video memory (mapped in their window) @@ -245,9 +519,9 @@ impl State { let mut new: Vec<(usize, (u32, u32))> = Vec::new(); let mut t = first; while t < a + n { - if !self.mapped.contains_key(&t) && self.window(t).is_some() { + if !self.mapped.contains_key(&t) && self.window_index(t).is_some() { let Some((tile, reused)) = self.take_tile() else { break }; - self.mapped.insert(t, tile); + self.mapped.insert(t, TileEntry::new(tile)); self.runs = None; if reused { self.to_zero.push((t, TILE)); @@ -256,49 +530,142 @@ impl State { } t += TILE; } + if new.is_empty() { + return; + } + MAPPED_GEN.fetch_add(1, Ordering::Release); // per window - let mut by_window: HashMap> = HashMap::new(); + let mut by_window: FxHashMap> = FxHashMap::default(); for x in new { - if let Some((b, _)) = self.window(x.0) { - by_window.entry(b).or_default().push(x); + if let Some(wi) = self.window_index(x.0) { + by_window.entry(wi).or_default().push(x); } } - for (b, tiles) in by_window { - if let Some((_, r)) = self.window(b) { - let r = r.clone(); - self.map_tiles(&r, b, &tiles); - } + for (wi, tiles) in by_window { + let (b, r) = (self.windows[wi].0, self.windows[wi].1.clone()); + self.map_tiles(&r, b, &tiles); } self.signal(); } + #[inline] unsafe fn signal(&mut self) { self.value += 1; let _ = self.queue.Signal(&self.fence, self.value); } - unsafe fn wait_idle(&self) { - if self.fence.GetCompletedValue() < self.value { - if let Ok(ev) = windows::Win32::System::Threading::CreateEventW(None, false, false, None) { - let _ = self.fence.SetEventOnCompletion(self.value, ev); - windows::Win32::System::Threading::WaitForSingleObject(ev, 5000); - let _ = windows::Win32::Foundation::CloseHandle(ev); + #[inline] + unsafe fn wait_for(&self, target: u64) { + if target == 0 || self.fence.GetCompletedValue() >= target { + return; + } + let _ = self.fence.SetEventOnCompletion(target, self.event); + windows::Win32::System::Threading::WaitForSingleObject(self.event, 5000); + } + + #[inline] + unsafe fn reclaim_ring(&mut self) { + if self.inflight.is_empty() { + return; + } + let completed = self.fence.GetCompletedValue(); + while let Some(&(fv, end_pos)) = self.inflight.front() { + if fv <= completed { + self.ring_free = end_pos; + self.inflight.pop_front(); + } else { + break; } } } - unsafe fn staging(&mut self) -> Option<(ID3D12Resource, *mut u8)> { + /// Acquire the next upload command slot, waiting only if that slot's previous submission is + /// still executing on the GPU, then reset its allocator and list. + unsafe fn begin_slot(&mut self) -> usize { + let idx = self.next_slot; + self.next_slot = (self.next_slot + 1) % self.slots.len(); + let fv = self.slots[idx].fence_val; + if fv > 0 && self.fence.GetCompletedValue() < fv { + self.wait_for(fv); + self.reclaim_ring(); + } + let slot = &self.slots[idx]; + let _ = slot.alloc.Reset(); + let _ = slot.list.Reset(&slot.alloc, None); + idx + } + + /// Close and submit upload slot `idx` asynchronously (NO CPU wait — callers order GPU work + /// via `queue.Wait(&self.fence, self.value)`). + unsafe fn submit_slot(&mut self, idx: usize) { + let closed = self.slots[idx].list.Close().is_ok(); + if closed { + if let Ok(l) = self.slots[idx].list.cast::() { + super::title_textures::own_work(|| { + self.queue.ExecuteCommandLists(&[Some(l)]); + }); + } + } + self.signal(); + self.slots[idx].fence_val = self.value; + if self.ring_write > self.ring_submitted { + self.inflight.push_back((self.value, self.ring_write)); + self.ring_submitted = self.ring_write; + } + } + + unsafe fn staging_ptr(&mut self) -> Option<*mut u8> { if self.staging.is_none() { let mut r: Option = None; let mut d = buffer_desc(STAGING as u64); d.Flags = D3D12_RESOURCE_FLAG_NONE; - self.dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut r).ok()?; + self.dev + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &d, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut r, + ) + .ok()?; let r = r?; let mut p = std::ptr::null_mut(); r.Map(0, None, Some(&mut p)).ok()?; self.staging = Some((r, p as *mut u8)); } - self.staging.clone() + self.staging.as_ref().map(|&(_, p)| p) + } + + unsafe fn ensure_zero_buf(&mut self) -> bool { + if self.zero_buf.is_none() { + let mut r: Option = None; + let mut d = buffer_desc(ZERO_BUF as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + if self + .dev + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &d, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut r, + ) + .is_err() + { + return false; + } + let Some(r) = r else { return false }; + let mut p = std::ptr::null_mut(); + if r.Map(0, None, Some(&mut p)).is_err() { + return false; + } + std::ptr::write_bytes(p as *mut u8, 0, ZERO_BUF); + r.Unmap(0, None); + self.zero_buf = Some(r); + } + true } unsafe fn readback_buf(&mut self) -> Option<(ID3D12Resource, *mut u8)> { @@ -324,6 +691,24 @@ impl State { self.readback.clone() } + /// Clear `sent` hashes for every page overlapping `[a, a + n)`. + fn clear_sent_range(&mut self, a: usize, n: usize) { + let mut pg = a & !(PAGE - 1); + let end = a + n; + while pg < end { + let t = pg & !(TILE - 1); + let tile_end = (t + TILE).min(end); + if let Some(entry) = self.mapped.get_mut(&t) { + let mut p = pg; + while p < tile_end { + entry.sent[(p - t) / PAGE] = None; + p += PAGE; + } + } + pg = tile_end; + } + } + /// Update `sent` hashes for all 64-byte chunks overlapping `[va, va + len)` so the CPU /// copy-back we just wrote to `va` is not re-uploaded by the next `before_execute`. unsafe fn sync_sent_range(&mut self, va: usize, len: usize) { @@ -333,16 +718,25 @@ impl State { let mut pg = va & !(PAGE - 1); let end = va + len; while pg < end { - if !self.holes.contains(&pg) { - let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); - let sent = self.sent.entry(pg).or_insert_with(|| Box::new(zero_hashes())); - let lo = va.saturating_sub(pg) / CHUNK; - let hi = (end.min(pg + PAGE) - pg).div_ceil(CHUNK).min(CHUNKS); - for k in lo..hi { - sent[k] = chunk_hash(&bytes[k * CHUNK..(k + 1) * CHUNK]); + let t = pg & !(TILE - 1); + let tile_end = (t + TILE).min(end); + if let Some(entry) = self.mapped.get_mut(&t) { + let mut p = pg; + while p < tile_end { + let idx = (p - t) / PAGE; + if entry.holes & (1u16 << idx) == 0 { + let bytes = std::slice::from_raw_parts(p as *const u8, PAGE); + let sent = entry.sent[idx].get_or_insert_with(|| Box::new(ZERO_HASHES)); + let lo = va.saturating_sub(p) / CHUNK; + let hi = (end.min(p + PAGE) - p).div_ceil(CHUNK).min(CHUNKS); + for k in lo..hi { + sent[k] = chunk_hash(&bytes[k * CHUNK..(k + 1) * CHUNK]); + } + } + p += PAGE; } } - pg += PAGE; + pg = tile_end; } } @@ -354,7 +748,20 @@ impl State { let mut used = 0usize; let mut open = false; let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize)>, used: &mut usize, p: *mut u8| { - s.flush(open); + if *open { + *open = false; + if s.rb_list.Close().is_ok() { + if let Ok(l) = s.rb_list.cast::() { + super::title_textures::own_work(|| { + s.queue.ExecuteCommandLists(&[Some(l)]); + }); + } + } + s.signal(); + s.rb_last_fence = s.value; + s.wait_for(s.value); + s.reclaim_ring(); + } for &(dst, off, len) in pending.iter() { // copy only committed (non-hole) bytes let mut at = dst; @@ -362,8 +769,10 @@ impl State { let end = dst + len; while at < end { let pg = at & !(PAGE - 1); + let t = pg & !(TILE - 1); + let idx = (pg - t) / PAGE; let step = (pg + PAGE).min(end) - at; - if !s.holes.contains(&pg) { + if s.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << idx) == 0) { std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); } at += step; @@ -382,7 +791,8 @@ impl State { while done < n { let cur = a + done; let tile = cur & !(TILE - 1); - let Some((b, r)) = self.window(cur).map(|(b, r)| (b, r.clone())) else { break }; + let Some(wi) = self.window_index(cur) else { break }; + let b = self.windows[wi].0; let to_tile_end = (tile + TILE) - cur; if !self.mapped.contains_key(&tile) { done += (n - done).min(to_tile_end); @@ -394,12 +804,12 @@ impl State { let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; let chunk = (n - done).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); if !open { - self.wait_idle(); - let _ = self.alloc.Reset(); - let _ = self.list.Reset(&self.alloc, None); + self.wait_for(self.rb_last_fence); + let _ = self.rb_alloc.Reset(); + let _ = self.rb_list.Reset(&self.rb_alloc, None); open = true; } - self.list.CopyBufferRegion(&rb, used as u64, &r, (cur - b) as u64, chunk as u64); + self.rb_list.CopyBufferRegion(&rb, used as u64, &self.windows[wi].1, (cur - b) as u64, chunk as u64); pending.push((cur, used, chunk)); used += chunk; done += chunk; @@ -410,57 +820,99 @@ impl State { } } - /// copy `runs` (address, bytes) of the CPU's view into the tiles (`zero`: clear instead) - unsafe fn upload(&mut self, runs: &[(usize, usize, bool)]) { - let Some((staging, p)) = self.staging() else { return }; - let mut used = 0usize; - let mut open = false; - for &(a, n, zero) in runs { - let mut done = 0; + /// Asynchronously zero `runs` (address, bytes) in sparse VRAM using the pre-zeroed `zero_buf` + /// (zero staging ring bytes consumed, zero CPU stall). + unsafe fn upload_zeros(&mut self, runs: &[(usize, usize)]) { + if runs.is_empty() || !self.ensure_zero_buf() { + return; + } + let slot_idx = self.begin_slot(); + let mut last_wi: Option = None; + let zero_buf = self.zero_buf.as_ref().unwrap(); + let list = &self.slots[slot_idx].list; + for &(a, n) in runs { + let mut done = 0usize; while done < n { - if used == STAGING { - self.flush(&mut open); - used = 0; - } - let Some((b, r)) = self.window(a + done).map(|(b, r)| (b, r.clone())) else { break }; - let to_win_end = (b + crate::gpu::uma::WINDOW) - (a + done); - let chunk = (n - done).min(STAGING - used).min(to_win_end); - if !open { - self.wait_idle(); - let _ = self.alloc.Reset(); - let _ = self.list.Reset(&self.alloc, None); - open = true; - } - if zero { - std::ptr::write_bytes(p.add(used), 0, chunk); - } else { - std::ptr::copy_nonoverlapping((a + done) as *const u8, p.add(used), chunk); - } - self.list.CopyBufferRegion(&r, (a + done - b) as u64, &staging, used as u64, chunk as u64); - used += chunk; + let cur = a + done; + let wi = match last_wi { + Some(i) if cur >= self.windows[i].0 && cur < self.windows[i].0 + crate::gpu::uma::WINDOW => i, + _ => match self.window_index(cur) { + Some(i) => { + last_wi = Some(i); + i + } + None => break, + }, + }; + let b = self.windows[wi].0; + let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; + let chunk = (n - done).min(ZERO_BUF).min(to_win_end); + list.CopyBufferRegion(&self.windows[wi].1, (cur - b) as u64, zero_buf, 0, chunk as u64); done += chunk; } } - if open { - self.flush(&mut open); - } + self.submit_slot(slot_idx); } - unsafe fn flush(&mut self, open: &mut bool) { - if !*open { + /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via + /// the 64 MiB ring staging buffer (zero CPU stall on the common path). + unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) { + if runs.is_empty() { return; } - *open = false; - if self.list.Close().is_ok() { - if let Ok(l) = self.list.cast::() { - super::title_textures::own_work(|| { - self.queue.ExecuteCommandLists(&[Some(l)]); - }); + let Some(p) = self.staging_ptr() else { return }; + let mut open_slot: Option = None; + let mut last_wi: Option = None; + for &(a, n) in runs { + let mut done = 0usize; + while done < n { + let cur = a + done; + let wi = match last_wi { + Some(i) if cur >= self.windows[i].0 && cur < self.windows[i].0 + crate::gpu::uma::WINDOW => i, + _ => match self.window_index(cur) { + Some(i) => { + last_wi = Some(i); + i + } + None => break, + }, + }; + let b = self.windows[wi].0; + let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; + let (aligned, chunk) = plan_ring_chunk(self.ring_write, (n - done).min(to_win_end), STAGING); + if (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { + self.reclaim_ring(); + if (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { + if let Some(slot_idx) = open_slot.take() { + self.submit_slot(slot_idx); + self.reclaim_ring(); + } + while (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { + let Some(&(fv, _)) = self.inflight.front() else { break }; + self.wait_for(fv); + self.reclaim_ring(); + } + } + } + let slot_idx = match open_slot { + Some(idx) => idx, + None => { + let idx = self.begin_slot(); + open_slot = Some(idx); + idx + } + }; + let dst_off = (aligned as usize) % STAGING; + std::ptr::copy_nonoverlapping(cur as *const u8, p.add(dst_off), chunk); + let staging_res = &self.staging.as_ref().unwrap().0; + self.slots[slot_idx].list.CopyBufferRegion(&self.windows[wi].1, (cur - b) as u64, staging_res, dst_off as u64, chunk as u64); + self.ring_write = aligned + chunk as u64; + done += chunk; } } - self.signal(); - // the staging buffer is written again only after this - self.wait_idle(); + if let Some(slot_idx) = open_slot { + self.submit_slot(slot_idx); + } } } @@ -512,7 +964,7 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz } let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { return }; - let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window(a).is_some()).collect(); + let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); if filtered.is_empty() { return; } @@ -536,47 +988,47 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz } /// Synchronize `[va, va + len)` in a sparse window for a CPU read (`ID3D12Resource::Map` with -/// a non-empty read range): flushes pending tile clears and unsubmitted CPU-changed chunks -/// first so CPU writes are preserved, then copies the range back from VRAM into CPU memory. +/// a non-empty read range, or `Map(0, NULL)` on a sparse readback resource): flushes pending +/// tile clears and unsubmitted CPU-changed chunks first so CPU writes are preserved, then +/// copies the range back from VRAM into CPU memory. pub unsafe fn readback_now(va: usize, len: usize) { if len == 0 { return; } let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { return }; - if s.window(va).is_none() { + if s.window_index(va).is_none() { return; } let zeroed = std::mem::take(&mut s.to_zero); if !zeroed.is_empty() { for &(a, n) in &zeroed { - for pg in (a..a + n).step_by(PAGE) { - s.sent.remove(&pg); - } + s.clear_sent_range(a, n); } - let zruns: Vec<(usize, usize, bool)> = zeroed.into_iter().map(|(a, n)| (a, n, true)).collect(); - s.upload(&zruns); + s.upload_zeros(&zeroed); } // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` - let mut dirty_runs: Vec<(usize, usize, bool)> = Vec::new(); + let mut dirty_runs: Vec<(usize, usize)> = Vec::new(); let mut pg = va & !(PAGE - 1); let end = va + len; while pg < end { - let tile = pg & !(TILE - 1); - if s.mapped.contains_key(&tile) && !s.holes.contains(&pg) { - let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); - let sent = s.sent.entry(pg).or_insert_with(|| Box::new(zero_hashes())); - for (o, n) in changed_chunks(bytes, sent) { - match dirty_runs.last_mut() { - Some(last) if last.0 + last.1 == pg + o => last.1 += n, - _ => dirty_runs.push((pg + o, n, false)), + let t = pg & !(TILE - 1); + let tile_end = (t + TILE).min(end); + if let Some(entry) = s.mapped.get_mut(&t) { + let mut p = pg; + while p < tile_end { + let idx = (p - t) / PAGE; + if entry.holes & (1u16 << idx) == 0 { + let bytes = std::slice::from_raw_parts(p as *const u8, PAGE); + scan_page(bytes, p, &mut entry.sent[idx], &mut dirty_runs); } + p += PAGE; } } - pg += PAGE; + pg = tile_end; } if !dirty_runs.is_empty() { - s.upload(&dirty_runs); + s.upload_dirty(&dirty_runs); } s.readback_ranges(&[(va, len)]); } @@ -591,11 +1043,31 @@ pub unsafe fn committed(a: usize, n: usize) { }; let tiles: Vec = (a & !(TILE - 1)..a + n).step_by(TILE).filter(|t| !s.mapped.contains_key(t)).collect(); s.ensure_mapped(a, n); - for t in tiles.into_iter().filter(|t| s.mapped.contains_key(t)) { - s.holes.extend((t..t + TILE).step_by(PAGE).filter(|&pg| pg + PAGE <= a || pg >= a + n)); + for t in tiles { + if let Some(entry) = s.mapped.get_mut(&t) { + let mut mask = 0u16; + for i in 0..PAGES_PER_TILE { + let pg = t + i * PAGE; + if pg + PAGE <= a || pg >= a + n { + mask |= 1u16 << i; + } + } + entry.holes |= mask; + } } - for pg in (a & !(PAGE - 1)..a + n).step_by(PAGE) { - s.holes.remove(&pg); + let mut pg = a & !(PAGE - 1); + let end = a + n; + while pg < end { + let t = pg & !(TILE - 1); + let tile_end = (t + TILE).min(end); + if let Some(entry) = s.mapped.get_mut(&t) { + let mut p = pg; + while p < tile_end { + entry.holes &= !(1u16 << ((p - t) / PAGE)); + p += PAGE; + } + } + pg = tile_end; } } @@ -609,46 +1081,59 @@ pub unsafe fn decommitted(a: usize, n: usize) { }; let first = (a + TILE - 1) & !(TILE - 1); let tiles: Vec = (first..(a + n) & !(TILE - 1)).step_by(TILE).filter(|t| s.mapped.contains_key(t)).collect(); - let mut by_window: HashMap> = HashMap::new(); + let mut by_window: FxHashMap> = FxHashMap::default(); for &t in &tiles { - if let Some((b, _)) = s.window(t) { - by_window.entry(b).or_default().push(t); + if let Some(wi) = s.window_index(t) { + by_window.entry(wi).or_default().push(t); } } - for (b, ts) in by_window { - if let Some((_, r)) = s.window(b) { - let r = r.clone(); - s.unmap_tiles(&r, b, &ts); - } - } - // pages of tiles that stay mapped: holes, their video memory cleared (sent: absent = zero; - // the title finds zeros there when it commits them again) - for pg in (a & !(PAGE - 1)..a + n).step_by(PAGE) { - s.sent.remove(&pg); - if s.mapped.contains_key(&(pg & !(TILE - 1))) && !tiles.contains(&(pg & !(TILE - 1))) && s.holes.insert(pg) { - s.to_zero.push((pg, PAGE)); - } - } - for &t in &tiles { - for pg in (t..t + TILE).step_by(PAGE) { - s.holes.remove(&pg); - } + for (wi, ts) in by_window { + let (b, r) = (s.windows[wi].0, s.windows[wi].1.clone()); + s.unmap_tiles(&r, b, &ts); } + let unmapped_any = !tiles.is_empty(); for t in tiles { - if let Some(tile) = s.mapped.remove(&t) { + if let Some(entry) = s.mapped.remove(&t) { s.runs = None; - if !s.pinned.contains_key(&tile) { - s.free.push(tile); + if !s.pinned.contains_key(&entry.pool) { + s.free.push(entry.pool); } } } - s.signal(); + if unmapped_any { + MAPPED_GEN.fetch_add(1, Ordering::Release); + } + // pages of tiles that stay mapped: holes, their video memory cleared (sent: None = zero; + // the title finds zeros there when it commits them again) + let mut pg = a & !(PAGE - 1); + let end = a + n; + while pg < end { + let t = pg & !(TILE - 1); + let tile_end = (t + TILE).min(end); + if let Some(entry) = s.mapped.get_mut(&t) { + let mut p = pg; + while p < tile_end { + let idx = (p - t) / PAGE; + entry.sent[idx] = None; + let bit = 1u16 << idx; + if entry.holes & bit == 0 { + entry.holes |= bit; + s.to_zero.push((p, PAGE)); + } + p += PAGE; + } + } + pg = tile_end; + } + if unmapped_any { + s.signal(); + } } impl State { /// a pool tile no window maps and no buffer uses goes back to the free list fn release_if_unused(&mut self, tile: (u32, u32)) { - if !self.pinned.contains_key(&tile) && !self.mapped.values().any(|&x| x == tile) { + if !self.pinned.contains_key(&tile) && !self.mapped.values().any(|e| e.pool == tile) { self.free.push(tile); } } @@ -675,34 +1160,30 @@ pub fn mapped_ranges() -> Vec<(usize, usize)> { } /// time spent and pages found by the write-watch scans (`refresh_once`), for the timing line -static WATCH: [std::sync::atomic::AtomicU64; 2] = [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; +static WATCH: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; /// [lock wait, chunk scan, upload] in µs, runs uploaded -static PHASES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; +static PHASES: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; pub fn note_watch(t: std::time::Duration, pages: usize) { - use std::sync::atomic::Ordering::Relaxed; - WATCH[0].fetch_add(t.as_micros() as u64, Relaxed); - WATCH[1].fetch_add(pages as u64, Relaxed); + WATCH[0].fetch_add(t.as_micros() as u64, Ordering::Relaxed); + WATCH[1].fetch_add(pages as u64, Ordering::Relaxed); } /// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB -/// pages from the write-watch, sorted) and the reused tiles are copied into video memory, and -/// `queue` waits for that and for new tile mappings. +/// pages from the write-watch, sorted) and the reused tiles are copied asynchronously into video +/// memory, and `queue` GPU-waits for that and for new tile mappings. pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) { - use std::sync::atomic::Ordering::Relaxed; let t0 = std::time::Instant::now(); let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { return }; let t_locked = std::time::Instant::now(); - PHASES[0].fetch_add((t_locked - t0).as_micros() as u64, Relaxed); - let zeroed = std::mem::take(&mut s.to_zero); - for &(a, n) in &zeroed { - for pg in (a..a + n).step_by(PAGE) { - s.sent.remove(&pg); - } + PHASES[0].fetch_add((t_locked - t0).as_micros() as u64, Ordering::Relaxed); + let zero_runs = std::mem::take(&mut s.to_zero); + for &(a, n) in &zero_runs { + s.clear_sent_range(a, n); } - let zero_runs: Vec<(usize, usize, bool)> = zeroed.into_iter().map(|(a, n)| (a, n, true)).collect(); - let mut dirty_runs: Vec<(usize, usize, bool)> = Vec::new(); + let mut dirty_runs = std::mem::take(&mut s.scratch_runs); + dirty_runs.clear(); let mut i = 0; while i < dirty.len() { let a = dirty[i]; @@ -717,21 +1198,13 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: while x < a + n { let t = x & !(TILE - 1); let end = (t + TILE).min(a + n); - if s.mapped.contains_key(&t) { - // per page: only the chunks the CPU changed since they were sent + if let Some(entry) = s.mapped.get_mut(&t) { let mut pg = x & !(PAGE - 1); while pg < end { - if s.holes.contains(&pg) { - pg += PAGE; - continue; - } - let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); - let sent = s.sent.entry(pg).or_insert_with(|| Box::new(zero_hashes())); - for (o, n) in changed_chunks(bytes, sent) { - match dirty_runs.last_mut() { - Some(last) if last.0 + last.1 == pg + o => last.1 += n, - _ => dirty_runs.push((pg + o, n, false)), - } + let idx = (pg - t) / PAGE; + if entry.holes & (1u16 << idx) == 0 { + let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); + scan_page(bytes, pg, &mut entry.sent[idx], &mut dirty_runs); } pg += PAGE; } @@ -740,39 +1213,40 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: } } let t_scanned = std::time::Instant::now(); - PHASES[1].fetch_add((t_scanned - t_locked).as_micros() as u64, Relaxed); - PHASES[3].fetch_add((zero_runs.len() + dirty_runs.len()) as u64, Relaxed); - // Flush tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. + PHASES[1].fetch_add((t_scanned - t_locked).as_micros() as u64, Ordering::Relaxed); + PHASES[3].fetch_add((zero_runs.len() + dirty_runs.len()) as u64, Ordering::Relaxed); + // Submit tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. if !zero_runs.is_empty() { - s.upload(&zero_runs); + s.upload_zeros(&zero_runs); } if !dirty_runs.is_empty() { - s.upload(&dirty_runs); + s.upload_dirty(&dirty_runs); } - PHASES[2].fetch_add(t_scanned.elapsed().as_micros() as u64, Relaxed); + PHASES[2].fetch_add(t_scanned.elapsed().as_micros() as u64, Ordering::Relaxed); { - use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; static CALLS: AtomicU64 = AtomicU64::new(0); static BYTES: AtomicU64 = AtomicU64::new(0); static MICROS: AtomicU64 = AtomicU64::new(0); let bytes: usize = zero_runs.iter().chain(dirty_runs.iter()).map(|r| r.1).sum(); - let n = CALLS.fetch_add(1, Relaxed) + 1; - let b = BYTES.fetch_add(bytes as u64, Relaxed) + bytes as u64; - let us = MICROS.fetch_add(t0.elapsed().as_micros() as u64, Relaxed) + t0.elapsed().as_micros() as u64; + let n = CALLS.fetch_add(1, Ordering::Relaxed) + 1; + let b = BYTES.fetch_add(bytes as u64, Ordering::Relaxed) + bytes as u64; + let us = MICROS.fetch_add(t0.elapsed().as_micros() as u64, Ordering::Relaxed) + t0.elapsed().as_micros() as u64; if n.is_power_of_two() && n >= 16 { crate::xlog_info!("sparse windows: {n} submits, {} MB of CPU writes uploaded, {} ms spent, {} tiles mapped", b >> 20, us / 1000, s.mapped.len()); - let ms = |x: &std::sync::atomic::AtomicU64| x.load(Relaxed) / 1000; + let ms = |x: &AtomicU64| x.load(Ordering::Relaxed) / 1000; crate::xlog_info!( "sparse windows timing: write-watch {} ms ({} dirty pages), lock wait {} ms, chunk scan {} ms, upload {} ms ({} runs)", ms(&WATCH[0]), - WATCH[1].load(Relaxed), + WATCH[1].load(Ordering::Relaxed), ms(&PHASES[0]), ms(&PHASES[1]), ms(&PHASES[2]), - PHASES[3].load(Relaxed) + PHASES[3].load(Ordering::Relaxed) ); } } + dirty_runs.clear(); + s.scratch_runs = dirty_runs; let q = queue.as_raw() as usize; if s.value > 0 && s.waited.get(&q).copied().unwrap_or(0) < s.value { let _ = queue.Wait(&s.fence, s.value); @@ -789,8 +1263,8 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D let start = va & !(TILE - 1); let delta = va - start; let bytes = desc.Width as usize; - s.window(start)?; - s.window(va + bytes - 1)?; + s.window_index(start)?; + s.window_index(va + bytes - 1)?; let mut d = *desc; d.Width = (delta + bytes) as u64; d.Alignment = 0; @@ -806,7 +1280,7 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D } // its tiles: the window's video memory at the same addresses s.ensure_mapped(start, delta + bytes); - let tiles: Vec<(usize, (u32, u32))> = (start..va + bytes).step_by(TILE).filter_map(|t| s.mapped.get(&t).map(|&x| (t, x))).collect(); + let tiles: Vec<(usize, (u32, u32))> = (start..va + bytes).step_by(TILE).filter_map(|t| s.mapped.get(&t).map(|e| (t, e.pool))).collect(); let raw = *ppv; let res = ID3D12Resource::from_raw_borrowed(&raw)?.clone(); s.map_tiles(&res, start, &tiles); @@ -843,7 +1317,7 @@ mod tests { #[test] fn only_changed_chunks_are_sent() { let mut page = vec![0u8; PAGE]; - let mut sent = zero_hashes(); + let mut sent = ZERO_HASHES; assert!(changed_chunks(&page, &mut sent).is_empty(), "a zero page is what the GPU has"); page[10] = 1; page[200] = 2; @@ -855,4 +1329,54 @@ mod tests { page[200] = 9; assert_eq!(changed_chunks(&page, &mut sent), vec![(192, 128)]); } + + /// `scan_page` skips allocating a hash box on all-zero pages, allocates on the first write, + /// and coalesces adjacent dirty chunks across consecutive pages. + #[test] + fn scan_page_lazy_alloc_and_coalesce() { + let mut page = vec![0u8; PAGE]; + let mut slot: Option> = None; + let mut out = Vec::new(); + scan_page(&page, 0x1_0000, &mut slot, &mut out); + assert!(slot.is_none(), "all-zero page must not allocate hash box"); + assert!(out.is_empty()); + + page[PAGE - 64] = 0xAA; + scan_page(&page, 0x1_0000, &mut slot, &mut out); + assert!(slot.is_some()); + assert_eq!(out, vec![(0x1_0FC0, 64)]); + + // Adjacent chunk at the start of the next page coalesces into a single run. + let mut next = vec![0u8; PAGE]; + next[0] = 0xBB; + let mut next_slot: Option> = None; + scan_page(&next, 0x1_1000, &mut next_slot, &mut out); + assert_eq!(out, vec![(0x1_0FC0, 128)]); + } + + /// Ring-buffer planner keeps every chunk contiguous, 64-byte aligned, <= cap/2, and splits + /// cleanly across the end of the ring buffer without wrapping mid-copy. + #[test] + fn ring_planner_handles_wrap_and_large_chunks() { + let cap = 64 << 20; + // Normal aligned chunk + let (a, n) = plan_ring_chunk(0, 4096, cap); + assert_eq!((a, n), (0, 4096)); + // Unaligned cursor aligns up to 64 + let (a, n) = plan_ring_chunk(17, 256, cap); + assert_eq!((a, n), (64, 256)); + // Oversized chunk capped at cap / 2 + let (a, n) = plan_ring_chunk(0, cap * 2, cap); + assert_eq!((a, n), (0, cap / 2)); + // Near end of ring with >= 4 KiB left: shrinks to fill tail + let near = (cap - 8192) as u64; + let (a, n) = plan_ring_chunk(near, 16384, cap); + assert_eq!((a, n), (near, 8192)); + assert_eq!((a as usize % cap) + n, cap); + // Tiny tail (< 4 KiB): wraps cleanly to 0 of next cycle + let tiny = (cap - 512) as u64; + let (a, n) = plan_ring_chunk(tiny, 4096, cap); + assert_eq!((a, n), (cap as u64, 4096)); + assert_eq!(a as usize % cap, 0); + } } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 108b65a..e4caf3f 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -58,6 +58,10 @@ unsafe impl Send for Entry {} /// PC texture → its place in the title's memory static TEXTURES: Mutex> = 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>)>> = Mutex::new(None); /// the queue uploads go to, per device static QUEUES: Mutex> = 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 = const { std::cell::Cell::new(false) }; + /// Reusable `GetWriteWatch` output buffer (avoids 128 KiB alloc+zero+free per submit). + static WATCH_BUF: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + /// Reusable dirty page list for `refresh_once`. + static DIRTY_BUF: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc> { + 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(®ions, 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 = 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::(); 16384]; - for (base, size) in watch_ranges(®ions, 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); } diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index dd1ce7d..d5b41f8 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -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::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) } diff --git a/tests/testtitle/src/gpu.rs b/tests/testtitle/src/gpu.rs index b75298b..03acb9a 100644 --- a/tests/testtitle/src/gpu.rs +++ b/tests/testtitle/src/gpu.rs @@ -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 = 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 = 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 = 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 = 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 = 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::().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 = 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 = 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::().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 = 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::().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(()) + } +} diff --git a/tests/testtitle/src/main.rs b/tests/testtitle/src/main.rs index 31f5a3b..533e44d 100644 --- a/tests/testtitle/src/main.rs +++ b/tests/testtitle/src/main.rs @@ -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);