diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index b8e1816be4..b86d4a6ea8 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -138,6 +138,8 @@ pub struct Uma { /// 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. pool: Mutex<(usize, usize, Vec)>, + /// windows remade as driver heaps (`hle::d3d12x::uma_driver`), one bit each + driver: std::sync::atomic::AtomicU32, } /// bytes of XCL's arena pool (`Uma::new`) @@ -406,6 +408,7 @@ impl Uma { views: Mutex::new(views), shadowed: AtomicBool::new(false), pool: Mutex::new((0, 0, Vec::new())), + driver: Default::default(), }; u.reserve_pool(POOL); return Some(u); @@ -520,6 +523,16 @@ impl Uma { self.window_of(p).is_some_and(|k| self.is_committed_window(k)) } + /// Window `k` is a driver heap now (`hle::d3d12x::uma_driver`). + pub fn set_driver_window(&self, k: usize) { + self.driver.fetch_or(1 << k, std::sync::atomic::Ordering::Relaxed); + } + + /// Whether window `k` is a driver heap (`set_driver_window`). + pub fn is_driver_window(&self, k: usize) -> bool { + k < 32 && self.driver.load(std::sync::atomic::Ordering::Relaxed) & (1 << k) != 0 + } + /// Whether `[p, p + len)` lies in a committed coherent window – memory that is committed and /// read-write as a whole, so it needs no `VirtualQuery` (which walks a region to its end to /// size it: on a 4 GiB window ~40 ms a call, a retail game's DirectStorage requests crawled). @@ -685,6 +698,7 @@ impl Uma { views: Mutex::new(Default::default()), shadowed: AtomicBool::new(false), pool: Mutex::new((0, 0, Vec::new())), + driver: Default::default(), }); } for p in got { diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index e113fa9e05..ec7e29961a 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -116,6 +116,19 @@ fn unpin(s: &mut State, list: usize) { } } +/// `list` (a closed segment) is parked as a spare: its recording is over and it is reset before +/// it records again, so it no longer holds its allocator. Its last submit stays (`in_flight`) +/// and the allocator's own submit marks still keep it until the GPU is past them. +pub(super) fn park_list(list: usize) { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if let Some(backing) = s.of_list.remove(&list) { + if let Some(b) = s.backings.get_mut(&backing) { + b.users.remove(&list); + } + } +} + /// Reset `list` on the title's allocator `alloc`, committing its new recording association /// only after native Reset succeeds. No pool lock is held across the driver call. pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) -> HRESULT) -> HRESULT { @@ -510,6 +523,24 @@ mod tests { assert!(s.backings[&other].users.contains(&elsewhere)); } + /// A parked spare stops holding its allocator: once nothing else records on it and no submit + /// is pending, the allocator is free again. + #[test] + fn a_parked_spare_no_longer_holds_its_allocator() { + let mut ids = Box::new([0u8; 2]); + let alloc = ids.as_mut_ptr() as usize; + let spare = alloc + 1; + created_on(spare, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + let held = |l: usize| STATE.lock().unwrap().as_ref().unwrap().backings[&alloc].users.contains(&l); + assert!(held(spare), "the new list records on the allocator"); + park_list(spare); + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert!(!s.of_list.contains_key(&spare) && unsafe { s.backings[&alloc].free() }, "a parked spare must not pin the allocator"); + drop(g); + ids[0] = 0; + } + #[test] fn a_spare_whose_reset_fails_stays_available_for_retry() { let (alloc, spare, list) = (0x1000usize, 0x2000usize, 0x3000usize); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 19eccb57af..fd3f0d441d 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3907,6 +3907,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { for seg in reclaimed { super::bind::reset(seg as *mut c_void, 0, 0); clear_segment_state(seg); + // a spare now: it does not hold its allocator until it records again (after both + // submits above, so the allocator keeps their marks) + super::alloc_pool::park_list(seg); } if let Some(s) = recording(primary as usize).lock().unwrap().as_mut().and_then(|m| m.get_mut(&(primary as usize))) { s.allocator = alloc; diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index bbfa841051..7ca4e88f41 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -51,6 +51,7 @@ mod submit_cost; mod texture_upload; pub mod title_textures; pub mod view_want; +mod uma_driver; pub mod vram; mod worker_pool; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 570ef64a10..a5bcb770c1 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -402,6 +402,21 @@ unsafe fn open_uma(device: &ID3D12Device) { if !u.is_committed_window(k) { continue; } + // on NVIDIA the window becomes a driver CUSTOM write-back L0 heap at its own address: the + // GPU's loads and atomics on imported pages are an order of magnitude slower (`uma_driver`) + if shadow_choice() != Some(true) && super::uma_driver::wanted(device) { + let (base, size) = u.window(k); + match super::uma_driver::remake(device, base, size) { + Ok((heap, buf)) => { + u.set_driver_window(k); + let (buf_raw, va, heap_raw) = super::uma_driver::raw(heap, buf); + bufs[k] = (buf_raw, va); + heaps[k] = Some(heap_raw); + continue; + } + Err(e) => crate::xlog_warn!("D3D12.X: coherent window {k} stays imported: {e}"), + } + } let made = open(k).and_then(|heap| { let shadowed = heap.is_none(); let heap = match heap { @@ -1639,11 +1654,12 @@ fn uma_shadowed() -> bool { /// Sanitize a console buffer description and initial state for placement in a coherent /// cross-adapter UMA heap (`OpenExistingHeapFromAddress`). -fn sanitize_coherent_buffer(desc: &D3D12_RESOURCE_DESC, state: usize) -> (D3D12_RESOURCE_DESC, u32) { +fn sanitize_coherent_buffer(desc: &D3D12_RESOURCE_DESC, state: usize, cross_adapter: bool) -> (D3D12_RESOURCE_DESC, u32) { let mut d = *desc; d.Flags = D3D12_RESOURCE_FLAGS(d.Flags.0 & 0xFF); - // a shadowed window's heap is video memory, not a cross-adapter heap over process memory - if !uma_shadowed() { + // a shadowed window's heap is video memory, not a cross-adapter heap over process memory; + // nor is a driver heap (`uma_driver`) + if cross_adapter && !uma_shadowed() { d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; } d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; @@ -1682,8 +1698,8 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta return None; }; // the heap from OpenExistingHeapFromAddress is cross-adapter: row-major + sanitized flags & state - let (d, st) = sanitize_coherent_buffer(&d, state); let k = u.window_of(p)?; + let (d, st) = sanitize_coherent_buffer(&d, state, !u.is_driver_window(k)); 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, st as usize, clear, riid, ppv); if hr < 0 || (*ppv).is_null() { @@ -1773,7 +1789,7 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: return Some(hr); } let heap = (*UMA_HEAPS.lock().unwrap().get(k)?)?; - if !u.shadowed() { + if !u.shadowed() && !u.is_driver_window(k) { d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; } d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; @@ -9785,7 +9801,7 @@ mod readback_routing_tests { }; let console_state = 0x0010_0000usize | (D3D12_RESOURCE_STATE_COPY_DEST.0 as usize); - let (clean, st) = sanitize_coherent_buffer(&raw_desc, console_state); + let (clean, st) = sanitize_coherent_buffer(&raw_desc, console_state, true); assert_eq!(clean.Alignment, 0); assert_eq!(clean.Layout, D3D12_TEXTURE_LAYOUT_ROW_MAJOR); assert_eq!( diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 2eef4403a4..28f7b84d74 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -196,6 +196,13 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: for seg in moved { super::bind::reset(seg as *mut c_void, 0, 0); super::list_x::clear_segment_state(seg); + // a spare records again only after its next Reset: it does not hold its + // allocator meanwhile + super::alloc_pool::park_list(seg); + } + // nor does the previous recording a stand-in now replaces: it is not reset here either + if stand_in.is_some() { + super::alloc_pool::park_list(primary as usize); } } *((this as usize + F_RING_AT) as *mut usize) = 0; diff --git a/crates/xcl/src/hle/d3d12x/uma_driver.rs b/crates/xcl/src/hle/d3d12x/uma_driver.rs new file mode 100644 index 0000000000..8b0dab9887 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/uma_driver.rs @@ -0,0 +1,249 @@ +//! A coherent UMA window in the driver's memory instead of the title's own pages opened with +//! `OpenExistingHeapFromAddress`. On NVIDIA, GPU loads and atomics on the imported pages ran 8-22x +//! slower than on a driver CUSTOM L0 heap, and a whole-frame replay ran window 3's programs 4-270x +//! faster from such a heap. The title keeps its addresses: the window's pages are copied out, the +//! window is released, every other large free stretch of address space is reserved for a moment, +//! so the driver's CPU mapping of the new heap can only land in the hole the window left, and the +//! pages go back. When the mapping lands anywhere else, the window is made again and imported as +//! before. The heap is made with write watch (`D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH`), so the window +//! stays in `Uma::watch_regions` and the title's CPU writes reach its textures as before; a driver +//! that refuses it, or whose mapping `GetWriteWatch` cannot read, keeps the import. +//! +//! `XCL_UMA_DRIVER`: `custom` or `1` on, `0` off; unset: on for an NVIDIA adapter outside Wine. + +use std::ffi::c_void; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows_sys::Win32::System::Memory::{ + VirtualAlloc, VirtualFree, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_FREE, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, + PAGE_READWRITE, +}; + +const MEM_WRITE_WATCH: u32 = 0x20_0000; + +#[link(name = "kernel32")] +extern "system" { + fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; +} + +/// Whether the coherent windows of `device` become driver heaps (see the module's comment). +pub(super) fn wanted(device: &ID3D12Device) -> bool { + decide(std::env::var("XCL_UMA_DRIVER").ok().as_deref(), crate::util::under_wine, || vendor(device)) +} + +/// `wanted` from the switch's value, whether the process runs under Wine and the adapter's vendor. +fn decide(switch: Option<&str>, wine: impl FnOnce() -> bool, vendor: impl FnOnce() -> Option) -> bool { + match switch.map(str::trim) { + Some("custom" | "1") => true, + Some("0") => false, + _ => !wine() && vendor() == Some(0x10DE), + } +} + +/// PCI vendor id of `device`'s adapter. +fn vendor(device: &ID3D12Device) -> Option { + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory4}; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let adapter: IDXGIAdapter = factory.EnumAdapterByLuid(device.GetAdapterLuid()).ok()?; + Some(adapter.GetDesc().ok()?.VendorId) + } +} + +/// The written pages of `[base, base + size)` that hold anything but zeros, with their bytes. +unsafe fn written_pages(base: usize, size: usize) -> Result)>, String> { + let mut out = Vec::new(); + let mut buf: Vec<*mut c_void> = vec![std::ptr::null_mut(); 1 << 16]; + let end = base + size; + let mut at = base; + while at < end { + let (mut n, mut page) = (buf.len(), 0u32); + let status = GetWriteWatch(0, at as *const c_void, end - at, buf.as_mut_ptr(), &mut n, &mut page); + if status != 0 { + return Err(format!("GetWriteWatch at {at:#x} failed ({status})")); + } + for &p in &buf[..n] { + let s = std::slice::from_raw_parts(p as *const u8, page as usize); + if s.iter().any(|&b| b != 0) { + out.push((p as usize, s.to_vec())); + } + } + if n < buf.len() { + break; + } + at = buf[n - 1] as usize + page as usize; + } + Ok(out) +} + +/// Reserves every free stretch of 1 GiB or more (but its first 256 MiB, room for the driver's own +/// small mappings) outside `[hole, hole + len)`. +unsafe fn groom(hole: usize, len: usize) -> Vec { + let (top, mut a, mut got) = (0x7FFF_FFFE_0000usize, 0x1_0000usize, Vec::new()); + while a < top { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(a as *const c_void, &mut m, std::mem::size_of::()) == 0 { + break; + } + let (base, end) = (m.BaseAddress as usize, (m.BaseAddress as usize + m.RegionSize).min(top)); + a = end; + if m.State != MEM_FREE || m.RegionSize < 1 << 30 { + continue; + } + let s = ((base + 0xFFFF) & !0xFFFF) + (256 << 20); + for (s, e) in [(s, end.min(hole)), (s.max(hole + len), end)] { + let mut s = s; + while s < e { + let n = (e - s).min(1 << 40); + let p = VirtualAlloc(s as *const c_void, n, MEM_RESERVE, PAGE_NOACCESS); + if !p.is_null() { + got.push(p as usize); + } + s += n; + } + } + } + got +} + +unsafe fn ungroom(got: Vec) { + for p in got { + VirtualFree(p as *mut c_void, 0, MEM_RELEASE); + } +} + +/// Window `[base, base + size)` (a whole `VirtualAlloc` allocation of its own) remade as a driver +/// heap mapped at `base`, its pages as they were and write-watched: the heap and a buffer over all +/// of it, mapped for good. On failure the window is the title's memory again, its pages as they +/// were. +pub(super) unsafe fn remake(device: &ID3D12Device, base: usize, size: usize) -> Result<(ID3D12Heap, ID3D12Resource), String> { + let t0 = std::time::Instant::now(); + let pages = written_pages(base, size)?; + let kept: usize = pages.iter().map(|p| p.1.len()).sum(); + if VirtualFree(base as *mut c_void, 0, MEM_RELEASE) == 0 { + return Err(format!("VirtualFree of the window at {base:#x} failed")); + } + let restore = |why: String| -> String { + let p = VirtualAlloc(base as *const c_void, size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE); + if p as usize != base { + return format!("{why}; and the window could not be made again at {base:#x} (got {p:?})"); + } + for (a, bytes) in &pages { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), *a as *mut u8, bytes.len()); + } + why + }; + let groomed = groom(base, size); + let reservations = groomed.len(); + let made = (|| -> Result<(ID3D12Heap, ID3D12Resource, usize), String> { + let properties = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + // write-watched as the title's own window was: its CPU writes to textures there are found so + let flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS | D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH; + let desc = D3D12_HEAP_DESC { SizeInBytes: size as u64, Properties: properties, Alignment: 0x1_0000, Flags: flags }; + let mut heap: Option = None; + device.CreateHeap(&desc, &mut heap).map_err(|e| format!("CreateHeap (write-watched): {e}"))?; + let heap = heap.ok_or("CreateHeap")?; + let buf_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size as u64, + 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, + ..Default::default() + }; + let mut buf: Option = None; + device.CreatePlacedResource(&heap, 0, &buf_desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("CreatePlacedResource: {e}"))?; + let buf = buf.ok_or("CreatePlacedResource")?; + let mut p: *mut c_void = std::ptr::null_mut(); + buf.Map(0, Some(&D3D12_RANGE::default()), Some(&mut p)).map_err(|e| format!("Map: {e}"))?; + Ok((heap, buf, p as usize)) + })(); + ungroom(groomed); + // (`GetWriteWatch` reads the mapping: the window can stay in `Uma::watch_regions`) + let watched = || { + let (mut one, mut n, mut page) = ([std::ptr::null_mut::(); 1], 1usize, 0u32); + GetWriteWatch(0, base as *const c_void, size, one.as_mut_ptr(), &mut n, &mut page) == 0 + }; + match made { + Ok((heap, buf, p)) if p == base && watched() => { + for (a, bytes) in &pages { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), *a as *mut u8, bytes.len()); + } + crate::xlog_info!( + "D3D12.X: the coherent window at {base:#x} ({} MB) is a driver CUSTOM write-back L0 heap mapped at its address, write-watched ({reservations} reservations, {} pages kept, {} KB, {} ms)", + size >> 20, + pages.len(), + kept >> 10, + t0.elapsed().as_millis() + ); + Ok((heap, buf)) + } + Ok((heap, buf, p)) => { + buf.Unmap(0, None); + drop((buf, heap)); + Err(restore(if p == base { + "GetWriteWatch cannot read the heap's mapping".to_string() + } else { + format!("Map gave {p:#x}, not the window's {base:#x} ({reservations} reservations)") + })) + } + Err(e) => Err(restore(e)), + } +} + +/// `heap` and `buf` as the raw pointers `open_uma` keeps. +pub(super) fn raw(heap: ID3D12Heap, buf: ID3D12Resource) -> (usize, u64, usize) { + let va = unsafe { buf.GetGPUVirtualAddress() }; + (buf.into_raw() as usize, va, heap.into_raw() as usize) +} + +#[cfg(test)] +mod tests { + use super::decide; + + /// On by default for NVIDIA outside Wine only; the switch overrides either way. + #[test] + fn driver_windows_by_default_on_nvidia_outside_wine() { + assert!(decide(None, || false, || Some(0x10DE))); + assert!(!decide(None, || true, || Some(0x10DE))); + assert!(!decide(None, || false, || Some(0x1002))); + assert!(!decide(None, || false, || None)); + assert!(!decide(Some("0"), || false, || Some(0x10DE))); + assert!(decide(Some("custom"), || true, || Some(0x1002))); + assert!(decide(Some(" 1 "), || false, || None)); + } + + #[test] + fn failed_write_watch_does_not_release_the_original_window() { + use super::*; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + const SIZE: usize = 1 << 16; + unsafe { + let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + std::ptr::write_bytes(base as *mut u8, 0x5a, SIZE); + let mut dev = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + return crate::gpu::recomp::runner::skip_test("no D3D12 device"); + } + // A regular VirtualAlloc block lacks MEM_WRITE_WATCH, forcing GetWriteWatch to fail. + assert!(remake(&dev.unwrap(), base, SIZE).is_err()); + let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + assert_ne!(VirtualQuery(base as *const c_void, &mut info, std::mem::size_of_val(&info)), 0); + assert_eq!(info.AllocationBase as usize, base); + assert_eq!(info.State, MEM_COMMIT); + assert!(std::slice::from_raw_parts(base as *const u8, SIZE).iter().all(|&b| b == 0x5a)); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } +}