From 1b11d3d54f2380d9a680192a8214246b97fc6ee8 Mon Sep 17 00:00:00 2001 From: MacieGx Date: Thu, 26 Nov 2026 13:42:19 +0100 Subject: [PATCH 1/2] D3D12.X: a placed sparse buffer can wait for its tiles until first use Preparation for buffers a title places outside the memory windows (#505), not called yet: `sparse::place_buffer_when(.., lazy)` makes the reserved resource without tiles and `sparse::use_range(va, len)` gives the lazily placed buffers there the window's video memory when a list is about to use an address of them. `place_buffer` is `place_buffer_when(.., false)` and behaves as before. The newer retail title places 128+ GPU-only buffers (~580 MB) at start; in a lab tree that gave them all video memory at once it ran out of RAM before the world, and lazily it had 108 / 526 MB in use 25 s into the world. `use_range` checks two atomics before it takes the sparse state's lock, so a call for an address outside every lazy buffer costs nothing. A lazy buffer released before its first use leaves the list in `forget_in`. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/sparse.rs | 154 ++++++++++++++++++++++++++-- 1 file changed, 145 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index b7560f861e..028830ae59 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -238,6 +238,9 @@ struct State { queue_fences: FxHashMap, /// placed buffers → the pool tiles they use buffers: FxHashMap>, + /// placed buffers whose tiles wait for their first use (`place_buffer_when`, `use_range`): + /// (resource, first tile address, bytes from there) + lazy: Vec<(usize, usize, usize)>, /// reused tiles / decommitted partial pages to clear: (address, bytes) to_zero: Vec<(usize, usize)>, /// ring-buffered upload staging heap (`STAGING` bytes, persistently mapped) @@ -559,6 +562,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { quarantined: VecDeque::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), + lazy: Vec::new(), to_zero: Vec::new(), staging: None, ring_write: 0, @@ -1645,6 +1649,13 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: /// description): a reserved resource over the window's tiles there, starting at the 64 KiB /// below `va` (returned: its distance from there). pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option<(crate::util::HRESULT, usize)> { + place_buffer_when(this, va, desc, state, riid, ppv, false) +} + +/// `place_buffer`; with `lazy` the buffer's tiles get no video memory until `use_range` names an +/// address of it (until then its unmapped tiles read 0 and drop writes). For buffers only the +/// GPU uses, which a title can place by the hundred long before it uses them. +pub unsafe fn place_buffer_when(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void, lazy: bool) -> Option<(crate::util::HRESULT, usize)> { let mut g = lock_state(); let s = g.as_mut()?; let start = va & !(TILE - 1); @@ -1668,21 +1679,84 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D if hr < 0 || ppv.is_null() || (*ppv).is_null() { return None; } - // its tiles: the window's video memory at the same addresses; probe actual OS commitment - // so uncommitted pages (e.g. [start, va) or reserved tails) stay marked as holes - s.ensure_mapped(start, delta + bytes, |t| query_tile_holes(t)); - 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); - for &(_, tile) in &tiles { - *s.pinned.entry(tile).or_default() += 1; + if lazy { + s.lazy.push((raw as usize, start, delta + bytes)); + publish_lazy_bounds(s); + return Some((hr, delta)); } - s.buffers.insert(raw as usize, tiles.iter().map(|x| x.1).collect()); + let res = ID3D12Resource::from_raw_borrowed(&raw)?.clone(); + s.back_buffer(&res, start, delta + bytes); s.signal(); Some((hr, delta)) } +/// (lowest, highest) address of the buffers waiting for their tiles (`State::lazy`; 0, 0: none): +/// what `use_range` checks before it takes the state's lock +static LAZY_BOUNDS: [std::sync::atomic::AtomicUsize; 2] = [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; + +fn publish_lazy_bounds(s: &State) { + let (lo, hi) = s.lazy_bounds(); + LAZY_BOUNDS[0].store(lo, Ordering::Release); + LAZY_BOUNDS[1].store(hi, Ordering::Release); +} + +/// `[va, va + len)` of the sparse windows is about to be used by the GPU (a view or root address +/// of a draw or dispatch, a copy, indirect arguments): the buffers of `place_buffer_when(.., lazy)` +/// there get their video memory now. Called while the list that uses them is recorded; the +/// title's queue waits for the tile mappings at its next submit (`before_execute`). An address +/// outside every such buffer returns without taking the state's lock. +pub unsafe fn use_range(va: usize, len: usize) { + let end = va.saturating_add(len.max(1)); + let (lo, hi) = (LAZY_BOUNDS[0].load(Ordering::Acquire), LAZY_BOUNDS[1].load(Ordering::Acquire)); + if va >= hi || end <= lo { + return; + } + let mut g = lock_state(); + let Some(s) = g.as_mut() else { return }; + let used = s.take_lazy(va, end); + if used.is_empty() { + return; + } + for (raw, start, bytes) in used { + let ptr = raw as *mut c_void; + if let Some(res) = ID3D12Resource::from_raw_borrowed(&ptr).cloned() { + s.back_buffer(&res, start, bytes); + } + } + publish_lazy_bounds(s); + s.signal(); +} + +impl State { + /// Placed buffer `res` from tile address `start`, `bytes` long, gets the window's video + /// memory at the same addresses; probing the OS commitment keeps uncommitted pages (e.g. + /// [start, va) or reserved tails) marked as holes. Its tiles stay pinned while it lives. + unsafe fn back_buffer(&mut self, res: &ID3D12Resource, start: usize, bytes: usize) { + self.ensure_mapped(start, bytes, |t| query_tile_holes(t)); + let tiles: Vec<(usize, (u32, u32))> = (start..start + bytes).step_by(TILE).filter_map(|t| self.mapped.get(&t).map(|e| (t, e.pool))).collect(); + self.map_tiles(res, start, &tiles); + for &(_, tile) in &tiles { + *self.pinned.entry(tile).or_default() += 1; + } + self.buffers.insert(res.as_raw() as usize, tiles.iter().map(|x| x.1).collect()); + } + + /// The buffers waiting for their tiles that overlap `[va, end)`, taken off the list. + fn take_lazy(&mut self, va: usize, end: usize) -> Vec<(usize, usize, usize)> { + let (used, rest): (Vec<_>, Vec<_>) = self.lazy.iter().partition(|&&(_, start, bytes)| va < start + bytes && start < end); + self.lazy = rest; + used + } + + /// (lowest, highest) address of the buffers waiting for their tiles; (0, 0) when none. + fn lazy_bounds(&self) -> (usize, usize) { + let lo = self.lazy.iter().map(|b| b.1).min().unwrap_or(0); + let hi = self.lazy.iter().map(|b| b.1 + b.2).max().unwrap_or(0); + (lo, hi) + } +} + /// Placed buffers released while `STATE` was held, let go by the next `lock_state`. Held only /// to push or take, never across a call out. static FORGOTTEN: Mutex> = Mutex::new(Vec::new()); @@ -1697,9 +1771,13 @@ fn lock_state() -> std::sync::MutexGuard<'static, Option> { fn forget_released(g: &mut Option) { let gone = std::mem::take(&mut *FORGOTTEN.lock().unwrap()); let Some(s) = g.as_mut() else { return }; + let lazy = s.lazy.len(); for res in gone { forget_in(s, res); } + if s.lazy.len() != lazy { + publish_lazy_bounds(s); + } } /// A placed buffer is gone: its tiles are not pinned by it any more. This runs from the @@ -1717,6 +1795,7 @@ pub fn forget_buffer(res: usize) { } fn forget_in(s: &mut State, res: usize) { + s.lazy.retain(|b| b.0 != res); let Some(tiles) = s.buffers.remove(&res) else { return }; for tile in tiles { if let Some(c) = s.pinned.get_mut(&tile) { @@ -1809,6 +1888,59 @@ mod tests { assert!(!FORGOTTEN.lock().unwrap().contains(&RES)); } + /// `use_range` is called for every view and root address of a draw: an address outside + /// every buffer waiting for its tiles returns without the sparse state's lock. + #[test] + fn use_range_outside_the_lazy_buffers_does_not_wait_for_the_state() { + assert!(returns_while_the_state_is_held(|| unsafe { use_range(0x7ff0_beef_0000, 256) }), "use_range waited for the sparse state's lock"); + } + + /// A buffer placed lazily has no tiles until an address of it is used; then the window's + /// tiles at its addresses, pinned while it lives. One released before its first use leaves + /// the list without ever getting tiles. + #[test] + fn a_lazy_buffer_gets_its_tiles_at_its_first_use() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(4); + let make = |s: &State| -> ID3D12Resource { + let mut r: Option = None; + s.dev.CreateReservedResource(&buffer_desc((2 * TILE) as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut r).expect("CreateReservedResource"); + r.expect("reserved buffer") + }; + let (used, unused) = (make(&s), make(&s)); + let (used_raw, unused_raw) = (used.as_raw() as usize, unused.as_raw() as usize); + // as `place_buffer_when(.., lazy)` leaves them + s.lazy.push((used_raw, base + TILE, 2 * TILE)); + s.lazy.push((unused_raw, base + 3 * TILE, TILE)); + assert_eq!(s.lazy_bounds(), (base + TILE, base + 4 * TILE)); + + assert!(s.take_lazy(base, base + TILE).is_empty(), "the tile before both buffers uses neither"); + assert!(s.mapped.is_empty() && s.buffers.is_empty()); + + let taken = s.take_lazy(base + 2 * TILE + 100, base + 2 * TILE + 104); + assert_eq!(taken, vec![(used_raw, base + TILE, 2 * TILE)], "an address in the second tile of the first buffer"); + s.back_buffer(&used, base + TILE, 2 * TILE); + let tiles = s.buffers[&used_raw].clone(); + assert_eq!(tiles, vec![s.mapped[&(base + TILE)].pool, s.mapped[&(base + 2 * TILE)].pool]); + assert!(tiles.iter().all(|t| s.pinned[t] == 1)); + assert!(!s.mapped.contains_key(&(base + 3 * TILE)), "the other buffer has no tiles yet"); + assert_eq!(s.lazy_bounds(), (base + 3 * TILE, base + 4 * TILE)); + + forget_in(&mut s, unused_raw); + assert!(s.lazy.is_empty() && s.lazy_bounds() == (0, 0), "a released lazy buffer leaves the list"); + assert!(!s.mapped.contains_key(&(base + 3 * TILE))); + forget_in(&mut s, used_raw); + assert!(tiles.iter().all(|t| !s.pinned.contains_key(t)), "a released buffer unpins its tiles"); + + s.wait_for(s.value); + drop((used, unused)); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + /// Freeing the last tile in use of a pool and taking a tile again takes the retired pool /// back, not a new 64 MB heap each time (#913: 288 pools, 18 GB asked of a 12 GB card). @@ -1850,6 +1982,7 @@ mod tests { quarantined: VecDeque::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), + lazy: Vec::new(), to_zero: Vec::new(), staging: None, ring_write: 0, @@ -2058,6 +2191,7 @@ mod tests { quarantined: VecDeque::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), + lazy: Vec::new(), to_zero: Vec::new(), staging: None, ring_write: 0, @@ -2155,6 +2289,7 @@ mod tests { quarantined: VecDeque::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), + lazy: Vec::new(), to_zero: Vec::new(), staging: None, ring_write: 0, @@ -2280,6 +2415,7 @@ mod tests { quarantined: VecDeque::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), + lazy: Vec::new(), to_zero: Vec::new(), staging: None, ring_write: 0, From 321ada6adef2953aeb0f49720b7f929fee1693a9 Mon Sep 17 00:00:00 2001 From: MacieGx Date: Thu, 26 Nov 2026 13:52:06 +0100 Subject: [PATCH 2/2] D3D12.X: GPU-only buffers placed outside the memory windows live in them A buffer the title places (CreatePlacedResourceX) outside every memory window became a committed resource of its own, and every view of it an empty V#: shaders read zeros and their writes were dropped. The newer retail title (#505) places all its compute buffers - light, ray and tile lists, BVH data, 128+ buffers, ~580 MB - in plain reservations above its GPU views, so its final gather had no tiles and wrote nothing, and its targets kept other targets' bytes. Such a buffer, at an address with no committed CPU pages (only the GPU uses it), now gets an address in the sparse windows, placed lazily (`sparse::place_buffer_when`): its views name that address, root CBV / SRV / UAV addresses into it are rewritten to it, and it gets video memory when a draw or dispatch names it (a root address or a buffer V# in the first 64 slots of a bound table), a copy or an ExecuteIndirect uses it. A range with committed pages is placed as before. Measured in a lab tree with the same logic (RTX 5080): "empty V#" warnings went from hundreds to 0, the final gather's tile list was filled, and 573 of 578 MB of these buffers were in use by 365 s. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/bind.rs | 89 +++++++++++++++++++- crates/xcl/src/hle/d3d12x/device_x.rs | 3 + crates/xcl/src/hle/d3d12x/list_x.rs | 2 + crates/xcl/src/hle/d3d12x/real.rs | 113 ++++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/sparse.rs | 5 ++ 5 files changed, 211 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 3f31c48b43..33221897ae 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -269,6 +269,8 @@ fn signature_dispatches(sig: usize) -> bool { pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); + super::real::use_buffer(args); + super::real::use_buffer(count_buf); let raw_pso = with(this, |s| s.pso); let unbuilt_compute = signature_dispatches(sig) && super::pso_async::is_pending(raw_pso) && super::real::is_console_compute(raw_pso); if unbuilt_compute && super::list_x::defer(this, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { @@ -1011,6 +1013,57 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis super::real::dispatch_chain::dispatch(list, pso, with(this, |s| s.allocator), [x, y, z]) } +/// The bound tables' addresses: a table argument is its 32-bit console address in window 0. +fn table_addresses(layout: &Layout, args: &[u8], base: usize) -> Vec { + let word = |at: usize| args.get(at..at + 4).map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap())); + layout + .params + .iter() + .filter_map(|p| match *p { + Param::Table { at } => Some(word(at as usize)), + _ => None, + }) + .filter(|&t| t != 0) + .map(|t| base + t as usize) + .collect() +} + +/// A root address in a buffer the title placed outside the memory windows names where that +/// buffer lives (`real::place_outside_buffer`), and the buffers waiting for their video memory +/// that a root address or a buffer V# of the bound tables' first 64 slots names get it now +/// (`sparse::use_range`). +unsafe fn outside_buffers_in_use(layout: &Layout, args: &mut [u8], base: usize, in_windows: impl Fn(usize) -> bool) { + for p in layout.params.iter() { + let Param::Descriptor { at } = *p else { continue }; + let at = at as usize; + let Some(b) = args.get_mut(at..at + 8) else { continue }; + let va = u64::from_le_bytes((&*b).try_into().unwrap()) as usize; + if va == 0 || in_windows(va) { + continue; + } + if let Some(q) = super::real::outside_buffer_address(va) { + b.copy_from_slice(&(q as u64).to_le_bytes()); + super::sparse::use_range(q, 1); + } + } + if !super::sparse::lazy_pending() { + return; + } + for table in table_addresses(layout, args, base) { + let slot = super::console_heap::SLOT as usize; + if !crate::gpu::shader::readable(table, slot * 64) { + continue; + } + for k in 0..64 { + let d = ((table + slot * k) as *const [u32; 4]).read_unaligned(); + // a V# (an image's T# has its type in the top bits of word 3) + if d[3] >> 30 == 0 && (d[0] | d[1]) != 0 { + super::sparse::use_range(((d[1] as usize & 0xFFFF) << 32) | d[0] as usize, 1); + } + } + } +} + /// XCL's ABI for a translated pipeline: its root signature, the user SGPRs (`io`, the kept /// arguments the console's way – compute or graphics) and the argument table in unified /// memory, u1 res, u2… the memory windows; then the pipeline. @@ -1019,7 +1072,10 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); let first = *windows.first().ok_or("unified memory is not open on the GPU")?; - let (layout, args) = with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) }); + let (layout, mut args) = with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) }); + if let Some(l) = layout.as_deref() { + outside_buffers_in_use(l, &mut args, u.base(), |va| u.contains(va)); + } // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) let copy = |bytes: &[u8]| -> Result { let p = with(this, |s| s.arena.take(u, bytes.len().max(16), 256, &mut s.uma)).ok_or("unified memory is full")?; @@ -1089,6 +1145,37 @@ mod tests { use super::*; use std::sync::atomic::AtomicUsize; + #[test] + fn table_addresses_follow_the_table_arguments() { + let layout = Layout { params: vec![Param::Table { at: 0 }, Param::Constants { at: 4, count: 2 }, Param::Descriptor { at: 12 }, Param::Table { at: 20 }, Param::Table { at: 24 }], size: 28, inline: 0, inline_gfx: 0 }; + let mut args = vec![0u8; 28]; + args[0..4].copy_from_slice(&0x4dbc_9a80u32.to_le_bytes()); + args[4..12].copy_from_slice(&[7; 8]); + args[12..20].copy_from_slice(&0x1234_5678_9abcu64.to_le_bytes()); + args[24..28].copy_from_slice(&0x0004_0000u32.to_le_bytes()); + let base = 0x7_0000_0000usize; + assert_eq!(table_addresses(&layout, &args, base), vec![base + 0x4dbc_9a80, base + 0x4_0000], "a table not set yet is skipped"); + assert!(table_addresses(&layout, &args[..2], base).is_empty(), "arguments not set yet"); + } + + /// A root address in a buffer the title placed outside the memory windows names where the + /// buffer lives; an address in the windows, in no such buffer, or 0 stays as it is. + #[test] + fn root_addresses_in_outside_buffers_name_their_address_in_the_windows() { + let (title, lives) = (0x15_7e57_0000usize, 0x4_7e57_0000usize); + real::note_outside_buffer(title, 0x2_0000, lives); + let layout = Layout { params: vec![Param::Descriptor { at: 0 }, Param::Constants { at: 8, count: 1 }, Param::Descriptor { at: 12 }, Param::Descriptor { at: 20 }, Param::Descriptor { at: 28 }], size: 36, inline: 0, inline_gfx: 0 }; + let mut args = vec![0u8; 36]; + args[0..8].copy_from_slice(&(title as u64 + 0x1240).to_le_bytes()); + args[8..12].copy_from_slice(&0x15_u32.to_le_bytes()); + args[12..20].copy_from_slice(&(title as u64 + 0x2_0000).to_le_bytes()); + args[20..28].copy_from_slice(&0x4_0000_1000u64.to_le_bytes()); + let before = args.clone(); + unsafe { outside_buffers_in_use(&layout, &mut args, 0, |va| va < 0x10_0000_0000) }; + assert_eq!(u64::from_le_bytes(args[0..8].try_into().unwrap()), lives as u64 + 0x1240); + assert_eq!(args[8..], before[8..], "constants, an address past the buffer, one in the windows and 0 are kept"); + } + /// A pipeline with the rect list GS draws its rect lists whole: draw_rects leaves them alone. #[test] fn rect_lists_with_the_rect_list_gs_are_not_expanded_on_the_cpu() { diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 57c30e0ffe..dc82fb9359 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1107,6 +1107,9 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, if let Some(hr) = real::place_at_title_address(this, va as usize, &d, state, clear, riid, ppv) { return hr; } + if let Some(hr) = real::place_outside_buffer(this, va as usize, &d, state, riid, ppv) { + return hr; + } } let state = if !buffer { pc_initial_state_for_desc( diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..b675b24c04 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -4250,6 +4250,8 @@ fn note_gpu_write(what: &str, va: usize, n: u64) { } pub(super) unsafe extern "system" fn copy_buffer_region_x(this: *mut c_void, dst: usize, dst_off: u64, src: usize, src_off: u64, n: u64) { + real::use_buffer(dst); + real::use_buffer(src); if super::present::trace_frame() { if let Some(a) = real::title_address(dst) { note_gpu_write("CopyBufferRegion", a + dst_off as usize, n); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 76f31d4daf..1866c78e09 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1505,6 +1505,79 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: Some(hr) } +/// Buffers the title placed outside the memory windows that live in the sparse windows +/// (`place_outside_buffer`): (title address, bytes, address in the windows) +static OUTSIDE_BUFFERS: Mutex> = Mutex::new(Vec::new()); + +/// A buffer the title places outside every memory window, at an address with no CPU pages (a +/// retail title puts its compute buffers – light, ray and tile lists, BVH data – in plain +/// reservations above its GPU views): only the GPU uses it. As a committed resource of its own +/// its views had an empty V#, so shaders read zeros and their writes were dropped. It gets an +/// address in the sparse windows instead, with video memory from its first use +/// (`sparse::use_range`); its views and root addresses name that address. +pub(super) unsafe fn place_outside_buffer(this: *mut c_void, va: usize, desc: &[u8; 0x38], state: u32, riid: *const GUID, ppv: *mut *mut c_void) -> Option { + let u = crate::gpu::uma::get()?; + let d: D3D12_RESOURCE_DESC = std::ptr::read_unaligned(desc.as_ptr() as *const D3D12_RESOURCE_DESC); + let bytes = d.Width as usize; + if !u.has_sparse() || bytes == 0 || u.contains(va) || has_cpu_pages(va, bytes) { + return None; + } + let (p, _) = u.sparse_alloc(bytes, 0x1_0000)?; + let Some((hr, _)) = super::sparse::place_buffer_when(this, p, &d, state, riid, ppv, true) else { + u.sparse_release(p); + return None; + }; + UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); + note_outside_buffer(va, bytes, p); + Some(hr) +} + +/// Whether any page of `[va, va + bytes)` is committed (the title may write the buffer there +/// with the CPU, which nothing would carry to an address in the sparse windows). +fn has_cpu_pages(va: usize, bytes: usize) -> bool { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + let end = va.saturating_add(bytes); + let mut at = va; + while at < end { + // SAFETY: VirtualQuery only reads the description of the process's address space + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + if unsafe { VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 { + return false; + } + if m.State == MEM_COMMIT { + return true; + } + let next = (m.BaseAddress as usize).saturating_add(m.RegionSize); + if next <= at { + return false; + } + at = next; + } + false +} + +pub(super) fn note_outside_buffer(va: usize, bytes: usize, p: usize) { + let mut g = OUTSIDE_BUFFERS.lock().unwrap(); + g.retain(|&(a, n, _)| a + n <= va || va + bytes <= a); + g.push((va, bytes, p)); +} + +/// Where title address `va` lives when it is in a buffer of `place_outside_buffer`. +pub fn outside_buffer_address(va: usize) -> Option { + OUTSIDE_BUFFERS.lock().unwrap().iter().find(|&&(a, n, _)| va >= a && va < a + n).map(|&(a, _, p)| p + (va - a)) +} + +/// Resource `res` is used by a call of the title (a copy, indirect arguments): a buffer still +/// waiting for its video memory gets it (`sparse::use_range`). +pub unsafe fn use_buffer(res: usize) { + if !super::sparse::lazy_pending() { + return; + } + if let Some((p, n)) = console_buffer(res) { + super::sparse::use_range(p, n); + } +} + /// buffers placed below their console address: resource → bytes before it static BUFFER_DELTA: Mutex>> = Mutex::new(None); @@ -1694,6 +1767,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { super::title_textures::forget(this as usize); let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { + OUTSIDE_BUFFERS.lock().unwrap().retain(|b| b.2 != p); if u.is_sparse(p) { super::sparse::free(p); } else { @@ -6458,6 +6532,45 @@ fn pc_topology_type(g: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC) { } } +#[cfg(test)] +mod outside_buffer_tests { + use super::*; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + + /// Only an address range with no committed page is taken for a GPU-only buffer. + #[test] + fn cpu_pages_are_found_anywhere_in_the_range() { + const PAGE: usize = 0x1000; + unsafe { + let base = VirtualAlloc(std::ptr::null(), 8 * PAGE, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert_ne!(base, 0); + assert!(!has_cpu_pages(base, 8 * PAGE), "reserved only"); + assert!(!VirtualAlloc((base + 5 * PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + assert!(has_cpu_pages(base, 8 * PAGE), "one committed page in the middle"); + assert!(has_cpu_pages(base + 5 * PAGE + 16, 4), "inside the committed page"); + assert!(!has_cpu_pages(base, 5 * PAGE), "the range before it"); + assert!(!has_cpu_pages(base + 6 * PAGE, 2 * PAGE), "the range after it"); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + /// Addresses in an outside buffer map to the same offset in its copy; a buffer placed again + /// over part of an older one replaces it. + #[test] + fn outside_buffer_addresses_keep_their_offset() { + let (title, lives) = (0x16_0000_0000usize, 0x4_8000_0000usize); + note_outside_buffer(title, 0x1_0000, lives); + assert_eq!(outside_buffer_address(title), Some(lives)); + assert_eq!(outside_buffer_address(title + 0xfff8), Some(lives + 0xfff8)); + assert_eq!(outside_buffer_address(title + 0x1_0000), None); + assert_eq!(outside_buffer_address(title - 1), None); + note_outside_buffer(title + 0x8000, 0x1_0000, lives + 0x10_0000); + assert_eq!(outside_buffer_address(title), None, "the older buffer overlapped by the new one is gone"); + assert_eq!(outside_buffer_address(title + 0x8000), Some(lives + 0x10_0000)); + OUTSIDE_BUFFERS.lock().unwrap().retain(|b| b.0 < title || b.0 >= title + 0x2_0000); + } +} + #[cfg(test)] mod pso_blend_and_tsharp_tests { use super::*; diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 028830ae59..89706fe001 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1695,6 +1695,11 @@ pub unsafe fn place_buffer_when(this: *mut c_void, va: usize, desc: &D3D12_RESOU /// what `use_range` checks before it takes the state's lock static LAZY_BOUNDS: [std::sync::atomic::AtomicUsize; 2] = [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; +/// Whether a placed buffer waits for its tiles (`use_range` has something to do). +pub fn lazy_pending() -> bool { + LAZY_BOUNDS[1].load(Ordering::Acquire) != 0 +} + fn publish_lazy_bounds(s: &State) { let (lo, hi) = s.lazy_bounds(); LAZY_BOUNDS[0].store(lo, Ordering::Release);