diff --git a/README.md b/README.md index bdb207620..03ac5d2e0 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder - With `XCL_DRED=1`, a D3D12 device removal logs GPU breadcrumbs in `xcl.log`. XCL examines up to 4,096 command lists and reports up to 64 unfinished lists, starting with those on which the GPU completed at least one operation. +- `XCL_SPARSE_DIRECT=1` commits each sparse unified-memory window whole, in one allocation the GPU + reads directly (`OpenExistingHeapFromAddress`), so buffers the title places there need no tiles + and no CPU→GPU copy. It charges the whole window at start; a layout the host cannot commit falls + back to the tiled windows. - `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib requests with virtual destinations. Defaults: four workers and a shared 32 MiB staging budget (`XCL_DSTORAGE_WORKERS`, `XCL_DSTORAGE_MEMORY_BUDGET_MIB`). Requests retire in queue order. diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 527dc4e64..89954c02c 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -4213,6 +4213,70 @@ fn gpu_arena_partial_commit_probe() { } } +/// A whole-committed write-watched window imports as a heap and buffers placed in it sit at the +/// window's GPU address plus their offset (`hle::d3d12x::sparse`, the direct sparse windows). +#[test] +fn gpu_buffers_placed_on_an_imported_window_heap_stay_at_the_window_offset() { + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Direct3D12::*; + use windows_sys::Win32::System::Memory::*; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + let mb = crate::gpu::uma::MAX_SIZE >> 20; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let Ok(dev3) = dev.cast::() else { + runner::skip_test("no ID3D12Device3"); + return; + }; + let p = VirtualAlloc(std::ptr::null(), crate::gpu::uma::MAX_SIZE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE); + assert!(!p.is_null(), "no {} MB of commit", mb); + let heap: ID3D12Heap = match dev3.OpenExistingHeapFromAddress(p) { + Ok(h) => h, + Err(e) => { + VirtualFree(p, 0, MEM_RELEASE); + panic!("OpenExistingHeapFromAddress of a {} MB write-watched window: {e}", mb); + } + }; + assert_eq!(heap.GetDesc().SizeInBytes as usize, crate::gpu::uma::MAX_SIZE, "the heap is not the whole window"); + let buf = |w: u64| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: w, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER, + ..Default::default() + }; + let mut keep: Vec = Vec::new(); + let mut placed = |offset: u64, w: u64| -> Result { + let mut r: Option = None; + match dev.CreatePlacedResource(&heap, offset, &buf(w), D3D12_RESOURCE_STATE_COMMON, None, &mut r) { + Ok(()) => { + let res = r.unwrap(); + let va = res.GetGPUVirtualAddress(); + keep.push(res); + Ok(va) + } + Err(e) => Err(format!("{e}")), + } + }; + let base = placed(0, crate::gpu::uma::MAX_SIZE as u64).expect("a buffer over the whole window"); + assert_eq!(placed(0x1_0000, 0x2_0000).unwrap(), base + 0x1_0000, "a placed buffer is not at its address in the window"); + assert_eq!(placed(0x2_0000, 0x2_0000).unwrap(), base + 0x2_0000, "a placement may overlap one already there (the title aliases)"); + assert!(placed(0x1_8000, 0x2_0000).is_err(), "a placed buffer needs a 64 KiB-aligned offset"); + drop(heap); + VirtualFree(p, 0, MEM_RELEASE); + } +} + /// Decoded GFX10 T#s give resource descriptions the driver accepts. #[test] fn gpu_tsharp_to_d3d12_resources() { diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 7592d044b..581c2776c 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -76,6 +76,12 @@ fn slot_limit(windows: usize) -> usize { if windows > MAX_WINDOWS { 1 << (40 - 32) } else { 512 } } +/// Whether each sparse window is one whole-committed allocation, so `sparse.rs` can import it as a +/// heap and skip the CPU→GPU copy (`XCL_SPARSE_DIRECT=1`). +pub(crate) fn sparse_direct_wanted() -> bool { + std::env::var("XCL_SPARSE_DIRECT").ok().as_deref() == Some("1") +} + /// Requested runtime UMA window count (`XCL_UMA_WINDOWS=4|8|16`, default 4). /// Layouts wider than 4 windows require `XCL_HEAP_WINDOWS=1`. pub(crate) fn configured_runtime_windows() -> usize { @@ -112,6 +118,8 @@ pub struct Uma { inner: Mutex, /// free ranges of the sparse windows (address → length) and the reservations in them sparse_free: Mutex<(BTreeMap, BTreeMap)>, + /// usable bytes in a sparse window: 4 GiB, or `MAX_SIZE` when each is whole-committed for import + sparse_len: usize, /// XCL's own pool in window 0 for `Arena` blocks: (start, end, free blocks). The title /// cannot take it – a title that commits all of unified memory at start (Unicorn /// Overlord: 2046 of 2048 MB) left no room for draw arguments, and draws were skipped. @@ -249,23 +257,57 @@ impl Uma { Self::reserve_runtime(size, coherent, windows) } + /// The runtime layout the environment asks for; a direct layout the host cannot commit falls + /// back to the tiled one. fn reserve_runtime(size: usize, coherent: usize, windows: usize) -> Option { + let direct = sparse_direct_wanted(); + Self::reserve_runtime_layout(size, coherent, windows, direct) + .or_else(|| direct.then(|| Self::reserve_runtime_layout(size, coherent, windows, false)).flatten()) + } + + fn reserve_runtime_layout(size: usize, coherent: usize, windows: usize, direct: bool) -> Option { let coh_sizes = coherent_window_sizes(size, coherent, windows); let coh_wins = coh_sizes.len(); let sparse_wins = (windows - coh_wins).min(MAX_RUNTIME_SPARSE_WINDOWS); - let sparse_len = sparse_wins * WINDOW; + let sparse_len = sparse_wins * if direct { MAX_SIZE } else { WINDOW }; for slot in (windows..slot_limit(windows)).step_by(windows) { let base = slot << 32; - let sp = unsafe { VirtualAlloc(base as *const std::ffi::c_void, sparse_len, MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) }; - if sp as usize != base { - if !sp.is_null() { - unsafe { VirtualFree(sp, 0, MEM_RELEASE) }; + let mut win_allocs = Vec::with_capacity(1 + coh_wins); + let mut sparse_free: (BTreeMap, BTreeMap) = Default::default(); + let mut ok = true; + if direct { + // one whole-committed allocation per window: the 1 MiB left of each is not address space + for k in 0..sparse_wins { + let w = base + k * WINDOW; + let sp = unsafe { VirtualAlloc(w as *const std::ffi::c_void, MAX_SIZE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }; + if sp as usize != w { + if !sp.is_null() { + unsafe { VirtualFree(sp, 0, MEM_RELEASE) }; + } + ok = false; + break; + } + win_allocs.push(w); + sparse_free.0.insert(w, MAX_SIZE); + } + } else if sparse_wins > 0 { + let sp = unsafe { VirtualAlloc(base as *const std::ffi::c_void, sparse_len, MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) }; + if sp as usize == base { + win_allocs.push(base); + sparse_free.0.insert(base, sparse_len); + } else { + if !sp.is_null() { + unsafe { VirtualFree(sp, 0, MEM_RELEASE) }; + } + ok = false; + } + } + if !ok { + for p in win_allocs { + unsafe { VirtualFree(p as *mut std::ffi::c_void, 0, MEM_RELEASE) }; } continue; } - let mut win_allocs = Vec::with_capacity(1 + coh_wins); - win_allocs.push(base); - let mut ok = true; for (c, &c_size) in coh_sizes.iter().enumerate() { let c_base = base + (sparse_wins + c) * WINDOW; let cp = unsafe { VirtualAlloc(c_base as *const std::ffi::c_void, c_size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }; @@ -292,13 +334,12 @@ impl Uma { inner.free.insert(k * WINDOW, c_size); kinds[k] = WindowKind::Committed(c_size); } - let mut sparse_free: (BTreeMap, BTreeMap) = Default::default(); - sparse_free.0.insert(base, sparse_len); let u = Uma { base, kinds, win_allocs, inner: Mutex::new(inner), + sparse_len: if direct { MAX_SIZE } else { WINDOW }, sparse_free: Mutex::new(sparse_free), pool: Mutex::new((0, 0, Vec::new())), }; @@ -510,6 +551,7 @@ impl Uma { kinds, win_allocs, inner: Mutex::new(inner), + sparse_len: WINDOW, sparse_free: Mutex::new(Default::default()), pool: Mutex::new((0, 0, Vec::new())), }); @@ -541,11 +583,16 @@ impl Uma { self.kinds.iter().filter(|w| matches!(w, WindowKind::Committed(_))).count() } - /// (address, bytes) of window `k` (a sparse window: all 4 GiB) + /// Whether the sparse windows are whole-committed allocations (`MAX_SIZE` each, not 4 GiB). + pub fn sparse_direct(&self) -> bool { + self.sparse_len < WINDOW + } + + /// (address, bytes) of window `k` (a sparse window: all 4 GiB, or `MAX_SIZE` when direct) pub fn window(&self, k: usize) -> (usize, usize) { let len = match self.kinds.get(k).copied().unwrap_or(WindowKind::None) { WindowKind::Committed(s) => s, - WindowKind::Sparse => WINDOW, + WindowKind::Sparse => self.sparse_len, WindowKind::None => 0, }; (self.base + k * WINDOW, len) @@ -553,7 +600,7 @@ impl Uma { /// 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. + /// (and each whole-committed sparse one) is its own allocation. pub fn watch_regions(&self) -> Vec<(usize, usize)> { let mut out: Vec<(usize, usize)> = Vec::with_capacity(self.kinds.len()); let mut k = 0; @@ -568,8 +615,11 @@ impl Uma { let start = self.base + k * WINDOW; let mut len = 0usize; while k < self.kinds.len() && matches!(self.kinds[k], WindowKind::Sparse) { - len += WINDOW; + len += self.sparse_len; k += 1; + if self.sparse_direct() { + break; + } } out.push((start, len)); } @@ -1105,6 +1155,35 @@ mod tests { assert_eq!(u.watch_regions(), vec![(u.base(), 3 * WINDOW), (u.base() + 3 * WINDOW, 16 << 20)]); } + #[test] + fn the_direct_layout_shortens_the_sparse_windows_and_gives_each_its_own_watch_region() { + let test = "the_direct_layout_shortens_the_sparse_windows_and_gives_each_its_own_watch_region"; + let Some(d) = Uma::reserve_runtime_layout(16 << 20, 16 << 20, MAX_WINDOWS, true) else { + eprintln!("SKIPPED {test}: the host refused {} MiB of committed memory", 3 * MAX_SIZE / (1 << 20)); + return; + }; + let b = d.base(); + assert!(d.sparse_direct()); + for k in 0..MAX_RUNTIME_SPARSE_WINDOWS { + assert_eq!(d.window(k), (b + k * WINDOW, MAX_SIZE), "sparse window {k} is one whole-committed allocation"); + assert!(d.is_sparse_window(k)); + } + assert_eq!(d.window_of(b + MAX_RUNTIME_SPARSE_WINDOWS * WINDOW - 1), None, "the 1 MiB at a window's end is not address space"); + let (a, la) = d.sparse_alloc_in(2, MAX_SIZE - GRAIN, GRAIN).expect("a direct window's whole length is allocatable"); + assert_eq!(d.window_of(a), Some(2)); + assert!(a + la <= b + 2 * WINDOW + MAX_SIZE, "an allocation stays inside its window"); + assert_eq!(d.sparse_release(a), Some(la)); + assert_eq!( + d.watch_regions(), + vec![(b, MAX_SIZE), (b + WINDOW, MAX_SIZE), (b + 2 * WINDOW, MAX_SIZE), (b + 3 * WINDOW, 16 << 20)], + "each whole-committed sparse window is its own write-watch region" + ); + let t = Uma::reserve_runtime_layout(16 << 20, 16 << 20, MAX_WINDOWS, false).expect("tiled layout"); + assert!(!t.sparse_direct()); + assert_eq!(t.window(0).1, WINDOW); + assert_eq!(t.watch_regions(), vec![(t.base(), 3 * WINDOW), (t.base() + 3 * WINDOW, 16 << 20)]); + } + #[test] fn runtime_layout_supports_eight_and_sixteen_heap_windows() { for windows in [8usize, MAX_HEAP_WINDOWS] { diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 91eb2ba35..4bfef5ed2 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -15,11 +15,14 @@ //! 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. +//! With `XCL_SPARSE_DIRECT=1` the windows are whole-committed CPU memory imported as heaps +//! (`gpu::uma::sparse_direct`): the GPU reads the title's pages at those addresses, so nothing +//! is mapped, uploaded or read back and there is no `State`. use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ffi::c_void; use std::hash::{BuildHasherDefault, Hasher}; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Mutex; use windows::core::Interface; @@ -405,6 +408,18 @@ static STATE: Mutex> = Mutex::new(None); /// (a list's `Reset`, with `XCL_DRED=1` on every start): the two then waited for each other. static QUEUE: Mutex> = Mutex::new(None); +/// The imported heaps of the whole-committed sparse windows: `(window base, heap)` (`init`). +/// With them there is no `State`: the windows are the title's own pages, so nothing is mapped, +/// uploaded or read back. +static DIRECT: Mutex> = Mutex::new(Vec::new()); + +/// Set once the sparse windows are the title's own pages: no tiles, no upload, no `State`. +static DIRECT_ON: AtomicBool = AtomicBool::new(false); + +fn direct() -> bool { + DIRECT_ON.load(Ordering::Relaxed) +} + /// (bytes of video memory in pool heaps, of those mapped) – `XCL_ACTIVITY` pub fn pool_bytes() -> (usize, usize) { let g = lock_state(); @@ -488,10 +503,65 @@ fn buffer_desc(bytes: u64) -> D3D12_RESOURCE_DESC { } } +/// The whole-committed sparse windows (`gpu::uma::sparse_direct`) imported as heaps, one placed +/// buffer over each at identity offset: the buffer IS the title's memory there, so nothing is +/// mapped, uploaded or read back and there is no `State`. Empty: the driver will not import them +/// (or they are gone), and `init` tiles them as today. +unsafe fn direct_windows(dev: &ID3D12Device, u: &crate::gpu::uma::Uma) -> Vec<(usize, usize, u64)> { + let dev3: ID3D12Device3 = match dev.cast() { + Ok(d) => d, + Err(e) => { + crate::xlog_warn!("sparse windows: ID3D12Device3: {e}"); + return Vec::new(); + } + }; + let mut out = Vec::new(); + let mut heaps = Vec::new(); + for k in 0..u.shader_windows() { + if !u.is_sparse_window(k) { + continue; + } + let (base, size) = u.window(k); + let heap: ID3D12Heap = match dev3.OpenExistingHeapFromAddress(base as *const c_void) { + Ok(h) => h, + Err(e) => { + crate::xlog_warn!("sparse window {k}: OpenExistingHeapFromAddress: {e} – tiled instead"); + return Vec::new(); + } + }; + let mut d = buffer_desc(size as u64); + d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + let mut r: Option = None; + if let Err(e) = dev.CreatePlacedResource(&heap, 0, &d, D3D12_RESOURCE_STATE_COMMON, None, &mut r) { + crate::xlog_warn!("sparse window {k}: CreatePlacedResource: {e} – tiled instead"); + return Vec::new(); + } + let Some(r) = r else { return Vec::new() }; + let va = r.GetGPUVirtualAddress(); + out.push((k, r.into_raw() as usize, va)); + heaps.push((base, heap)); + } + if out.is_empty() { + return out; + } + crate::xlog_info!("D3D12.X: {} sparse window(s) hold the title's own pages: no tiles, no upload", out.len()); + *DIRECT.lock().unwrap() = heaps; + DIRECT_ON.store(true, Ordering::Relaxed); + *QUEUE.lock().unwrap() = None; + *STATE.lock().unwrap() = None; + out +} + /// The sparse windows' buffers on `dev`: `(window_index, buffer_raw, gpu_va)` for each /// sparse window in `gpu::uma` (empty: no sparse windows). pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { let Some(u) = crate::gpu::uma::get() else { return Vec::new() }; + if u.sparse_direct() { + let d = direct_windows(dev, u); + if !d.is_empty() { + return d; + } + } let mut out = Vec::new(); let mut windows = Vec::new(); for k in 0..u.shader_windows() { @@ -1217,6 +1287,11 @@ pub unsafe fn free(p: usize) -> bool { // decommitted before the address goes back: once released, another thread may get it, // commit it and write there let Some((start, len)) = u.sparse_reservation(p).filter(|&(start, _)| start == p) else { return false }; + if direct() { + // the pages back the imported heap and do not come back zeroed on their own + std::ptr::write_bytes(p as *mut u8, 0, len); + return u.sparse_release(p).is_some(); + } decommitted(start, len); VirtualFree(p as *mut c_void, len, MEM_DECOMMIT); u.sparse_release(p).is_some() @@ -1313,6 +1388,10 @@ pub unsafe fn committed(a: usize, n: usize) { if n == 0 { return; } + // whole-committed already: there are no tiles to map and no `State` to tell + if direct() { + return; + } let mut g = lock_state(); let Some(s) = g.as_mut() else { let (start, end) = page_span(a, n); @@ -1329,6 +1408,9 @@ pub unsafe fn decommitted(a: usize, n: usize) { if n == 0 { return; } + if direct() { + return; + } let mut g = lock_state(); let Some(s) = g.as_mut() else { let (start, end) = page_span(a, n); @@ -1446,12 +1528,22 @@ 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: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; +static WATCH_N: AtomicU64 = AtomicU64::new(0); /// [lock wait, chunk scan, upload] in µs, runs uploaded static PHASES: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; pub fn note_watch(t: std::time::Duration, pages: usize) { WATCH[0].fetch_add(t.as_micros() as u64, Ordering::Relaxed); WATCH[1].fetch_add(pages as u64, Ordering::Relaxed); + let n = WATCH_N.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() && n >= 16 { + crate::xlog_info!( + "write-watch: {n} looks, {} ms total ({} dirty pages), this look {} ms", + WATCH[0].load(Ordering::Relaxed) / 1000, + WATCH[1].load(Ordering::Relaxed), + t.as_millis() + ); + } } /// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB @@ -1548,14 +1640,35 @@ 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)> { - let mut g = lock_state(); - let s = g.as_mut()?; let start = va & !(TILE - 1); let delta = va - start; let bytes = desc.Width as usize; if bytes == 0 { return None; } + if direct() { + // the window is one buffer on an imported heap: place on that heap, at the same address + let u = crate::gpu::uma::get()?; + let k = u.window_of(start)?; + let (base, len) = u.window(k); + if !u.is_sparse_window(k) || start - base + bytes > len { + return None; + } + let heap = DIRECT.lock().unwrap().iter().find(|&&(b, _)| b == base)?.1.clone(); + let mut d = *desc; + d.Width = (delta + bytes) as u64; + d.Alignment = 0; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + // the imported heap is cross-adapter, so the buffer placed in it has to be + d.Flags = (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + if state & (D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32 | D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32) != 0 { + d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + } + let hr = super::real::dev_create_placed_resource(this, heap.into_raw() as usize, start - base, &d as *const _ as usize, state as usize, 0, riid, ppv); + return (hr >= 0 && !ppv.is_null() && !(*ppv).is_null()).then(|| (hr, delta)); + } + let mut g = lock_state(); + let s = g.as_mut()?; s.window_index(start)?; s.window_index(va.checked_add(bytes)?.checked_sub(1)?)?; let mut d = *desc;