From 8d36887d0545c1d2927302287a80e072e785d087 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:30:13 -0500 Subject: [PATCH] D3D12.X: coherent UMA windows in a driver heap at the title's address on NVIDIA The title's GPU code reads and writes the coherent window (4 GiB of host memory) through a heap opened with OpenExistingHeapFromAddress. On an RTX 5070 Ti, GPU loads from such imported pages ran 8-24x and atomics 13-22x slower than from a driver CUSTOM write-back L0 heap in host memory, at the same CPU caching. A whole-frame replay of a captured title frame took 172 ms of GPU time with the window in a CUSTOM L0 heap and 1,427 ms with it imported as XCL does, the hot compute programs 18-39x slower each. At open_uma the window's written pages are copied out, the window is released, every other free stretch of 1 GiB or more is reserved for a moment so that the driver's CPU mapping of a new CUSTOM L0 heap can only land in the hole the window left, and the pages are copied back. The title keeps its pointers. If the mapping lands anywhere else, or a step fails, the window is made again at its address with its pages and imported as before; if the snapshot of its written pages fails, the window is not released at all (found in review by thehollowedone, with the test failed_write_watch_does_not_release_the_original_window). Buffers placed in it drop ALLOW_CROSS_ADAPTER. The heap is made with D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH, and GetWriteWatch reads the mapped window on an RTX 5070 Ti (driver 610.74), so the window stays in the write-watched regions and the title's CPU writes reach its textures as with the import; a driver that refuses the flag, or whose mapping GetWriteWatch cannot read, keeps the import. On by default for an NVIDIA adapter outside Wine; XCL_UMA_DRIVER=0 turns it off, XCL_UMA_DRIVER=1 (or custom) turns it on elsewhere. Ported to nvidia-dev (joeypercia): the driver heap is tried in open_uma's per-window loop before nvidia-dev's import / video-memory shadow, and not with XCL_UMA_SHADOW=1; a shadowed or driver-heap window gets no ALLOW_CROSS_ADAPTER. --- crates/xcl/src/gpu/uma.rs | 14 ++ crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 28 ++- crates/xcl/src/hle/d3d12x/uma_driver.rs | 249 ++++++++++++++++++++++++ 4 files changed, 286 insertions(+), 6 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/uma_driver.rs 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/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/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); + } + } +}