diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 7592d044b0..8341c61ed3 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -116,6 +116,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`) @@ -301,6 +303,7 @@ impl Uma { inner: Mutex::new(inner), sparse_free: Mutex::new(sparse_free), pool: Mutex::new((0, 0, Vec::new())), + driver: Default::default(), }; u.reserve_pool(POOL); return Some(u); @@ -377,6 +380,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). @@ -512,6 +525,7 @@ impl Uma { inner: Mutex::new(inner), sparse_free: Mutex::new(Default::default()), 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 8886624632..b7c2e38c14 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -32,6 +32,7 @@ pub mod sparse; mod standin; pub mod title_list; pub mod title_textures; +mod uma_driver; pub mod vram; use std::ffi::c_void; @@ -72,15 +73,16 @@ pub enum Backend { } /// Decided once: the real backend unless disabled or the driver refuses. -pub fn backend() -> Backend { - static B: OnceLock = OnceLock::new(); - *B.get_or_init(|| { +static BACKEND: OnceLock = OnceLock::new(); + +fn backend_with_remap(allow_driver_remap: bool) -> Backend { + *BACKEND.get_or_init(|| { let cfg = crate::state::config(); if cfg.graphics.eq_ignore_ascii_case("null") { crate::xlog_info!("D3D12.X: backend 'null' (from the config)"); return Backend::Null; } - match real::init() { + match real::init_with_remap(allow_driver_remap) { Ok(desc) => { crate::xlog_info!("D3D12.X: backend 'real' – {desc}"); Backend::Real @@ -93,6 +95,14 @@ pub fn backend() -> Backend { }) } +pub fn backend() -> Backend { + backend_with_remap(false) +} + +pub(crate) fn backend_before_guest() -> Backend { + backend_with_remap(true) +} + /// Call a function of the system d3d12.dll by name. unsafe fn sys(name: &str) -> Option { crate::resolver::system_proc("d3d12.dll", &crate::pe::ImportName::Name { hint: 0, name: name.into() }) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9692cc4c59..19eedfe6ac 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -298,13 +298,22 @@ unsafe fn check_uma_import(device: &ID3D12Device, u: &crate::gpu::uma::Uma, bufs Ok(format!("ok, {} window(s), {} µs", probes.len(), t0.elapsed().as_micros())) } -unsafe fn open_uma(device: &ID3D12Device) { +unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) { let Some(u) = crate::gpu::uma::get() else { *UMA_ERROR.lock().unwrap() = "no UMA region".into(); return; }; let open = |k: usize| -> Result<(usize, u64, usize), String> { let (base, size) = u.window(k); + if allow_driver_remap && super::uma_driver::wanted(device) { + match super::uma_driver::remake(device, base, size) { + Ok((heap, buf)) => { + u.set_driver_window(k); + return Ok(super::uma_driver::raw(heap, buf)); + } + Err(e) => crate::xlog_warn!("D3D12.X: coherent window {k} stays imported: {e}"), + } + } let dev3: ID3D12Device3 = device.cast().map_err(|e| format!("ID3D12Device3: {e}"))?; let heap: ID3D12Heap = dev3.OpenExistingHeapFromAddress(base as *const c_void).map_err(|e| format!("OpenExistingHeapFromAddress (window {k}): {e}"))?; let desc = D3D12_RESOURCE_DESC { @@ -469,6 +478,10 @@ fn graphics_wave32(device: *mut c_void) -> bool { /// by default the high-performance GPU → WARP); once – later calls /// return the existing device's adapter. pub fn init() -> Result { + init_with_remap(false) +} + +pub(super) fn init_with_remap(allow_driver_remap: bool) -> Result { if !device_raw().is_null() { return Ok(ADAPTER.lock().map(|a| a.clone()).unwrap_or_default()); } @@ -545,7 +558,7 @@ pub fn init() -> Result { let _ = q.RegisterMessageCallback(Some(debug_message), D3D12_MESSAGE_CALLBACK_FLAG_NONE, std::ptr::null_mut(), &mut cookie); } } - open_uma(&device); + open_uma(&device, allow_driver_remap); super::device_x::probe_dynamic_depth_bias(&device); let raw = device.into_raw(); // one reference kept for the process lifetime adopt(raw, Kind::Device); @@ -1393,9 +1406,12 @@ unsafe fn place_console_buffer_sparse(this: *mut c_void, d: &D3D12_RESOURCE_DESC /// 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) | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + d.Flags = D3D12_RESOURCE_FLAGS(d.Flags.0 & 0xFF); + if cross_adapter { + d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + } d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Alignment = 0; (d, state as u32 & PC_RESOURCE_STATES) @@ -1432,8 +1448,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() { @@ -1490,7 +1506,9 @@ 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)?)?; - d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + if !u.is_driver_window(k) { + d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + } d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Alignment = 0; d.Width = (delta + bytes) as u64; @@ -7810,7 +7828,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_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 6d97bc6e4e..a33d3c7e6e 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -766,8 +766,7 @@ unsafe fn refresh_once(queue: *mut c_void) { let size = e.tex.size() as usize; (0..16usize) .map(|k| e.src + (size.saturating_sub(4096)) * k / 15) - .filter(|&a| crate::gpu::shader::readable(a, 4096)) - .map(|a| std::slice::from_raw_parts(a as *const u8, 4096).iter().filter(|&&b| b != 0).count()) + .map(|a| with_title_bytes(a, 4096, |s| s.iter().filter(|&&b| b != 0).count())) .sum() }; let (mut with, mut without) = (0, 0); @@ -1110,7 +1109,7 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { // retail title's video planes and UI targets went up again for every submit, ~25 MB // a presented frame where ~3 MB had changed, and the submits waited here. if unchanged_skip() { - let h = content_hash(&title_bytes(va, tex.size() as usize)); + let h = with_title_bytes(va, tex.size() as usize, content_hash); if same_as_last_upload(r.as_raw() as usize, h) { let n = UNCHANGED.fetch_add(1, Ordering::Relaxed) + 1; if n == 1 || (n.is_power_of_two() && n >= 1024) { @@ -1344,11 +1343,11 @@ fn watch_ranges(regions: &[(usize, usize)], mut wanted: Vec<(usize, usize)>) -> out } -/// Copy `[src, src + len)` into `dst` (pre-zeroed) without faulting if another thread unmaps or +/// Copy `[src, src + len)` into `dst` without faulting if another thread unmaps or /// decommits a page concurrently: `ReadProcessMemory` catches the fault in kernel mode and returns /// `0`. Because Windows may return `read == 0` when a fault occurs later in the span, binary-split /// failed multi-page ranges at 4 KiB boundaries so all still-committed pages are copied in O(log N) -/// calls and only unreadable pages stay zeroed. +/// calls and only unreadable pages are zeroed. unsafe fn copy_committed_region(src: usize, dst: *mut u8, len: usize) { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; @@ -1368,6 +1367,7 @@ unsafe fn copy_committed_region(src: usize, dst: *mut u8, len: usize) { let len = len - read; let page_end = (src & !(PAGE - 1)).saturating_add(PAGE).min(src + len); if page_end == src + len { + std::ptr::write_bytes(dst, 0, len); return; } let mid = ((src + len / 2) & !(PAGE - 1)).max(page_end); @@ -1382,15 +1382,38 @@ unsafe fn copy_committed_region(src: usize, dst: *mut u8, len: usize) { /// `len` bytes at `at`: the committed, readable pages copied, the rest zero (a streaming pool /// has only some of its pages mapped). unsafe fn read_committed(at: usize, len: usize) -> Vec { - use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; let mut out = vec![0u8; len]; - let Some(limit) = at.checked_add(len) else { return out }; + read_committed_into(at, &mut out); + out +} + +/// `read_committed` of `out.len()` bytes at `at` into `out` (every byte of it written). +unsafe fn read_committed_into(at: usize, out: &mut [u8]) { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let len = out.len(); + let Some(limit) = at.checked_add(len) else { return out.fill(0) }; // (the coherent window is committed as a whole: no `VirtualQuery`, which sizes a region by // walking it) if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)) { std::ptr::copy_nonoverlapping(at as *const u8, out.as_mut_ptr(), len); - return out; + return; + } + // All of it readable (the usual case): one copy. `VirtualQuery` scans from the page asked + // about to the end of its run of like pages, and the title's memory is a few runs of hundreds + // of MiB – a 16 KiB texture cost ~120 µs at the start of a 64 MiB run, ~1.3 ms of 512 MiB. + // `ReadProcessMemory` refuses a range with a page that is not committed, no-access or a guard + // page (and leaves the guard in place: `title_bytes_leave_guard_pages_alone`). Under Wine + // that test fails with it (#2844), so there it is region by region. + let mut read = 0usize; + if len == 0 { + return; } + if !crate::util::under_wine() && ReadProcessMemory(GetCurrentProcess(), at as *const c_void, out.as_mut_ptr() as *mut c_void, len, &mut read) != 0 { + return; + } + // with holes: region by region (a refused `ReadProcessMemory` costs more than the walk) let mut p = at; while p < limit { let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); @@ -1404,10 +1427,12 @@ unsafe fn read_committed(at: usize, len: usize) -> Vec { let readable = m.State == MEM_COMMIT && m.Protect & 0xEE != 0 && m.Protect & 0x100 == 0; // R / RW / WC / X-R…, no guard if readable { copy_committed_region(p, out.as_mut_ptr().add(p - at), end - p); + } else { + out[p - at..end - at].fill(0); } p = end; } - out + out[p - at..].fill(0); } /// Batches of at least this many bytes are detiled on several threads (`subresources_of_all`) @@ -1454,14 +1479,40 @@ unsafe fn subresources_on(picked: &[(usize, &xg::Texture)], threads: usize) -> V out } -/// The title's bytes at `at`: where they are when all of them are readable (a copy first cost -/// as much as the detile of a video frame), else read page run by page run. -unsafe fn title_bytes(at: usize, len: usize) -> std::borrow::Cow<'static, [u8]> { - if crate::gpu::shader::readable(at, len) { - std::borrow::Cow::Borrowed(std::slice::from_raw_parts(at as *const u8, len)) - } else { - std::borrow::Cow::Owned(read_committed(at, len)) +thread_local! { + /// Reusable copy of title bytes for `with_title_bytes` (a fresh one per texture cost its + /// allocation and page faults – as much as the detile of a video frame). + static TITLE_BYTES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// A `TITLE_BYTES` buffer grown past this is let go after its read (a thread does not keep the +/// size of the largest texture it ever read) +const TITLE_BYTES_KEPT: usize = 64 << 20; + +/// `f` of the title's `len` bytes at `at`: where they are in the coherent window (committed as a +/// whole, never decommitted), else as `read_committed` reads them, into a buffer reused on this +/// thread – the title can decommit its other memory from another thread at any moment, and a +/// read in place then faults. +unsafe fn with_title_bytes(at: usize, len: usize, f: impl FnOnce(&[u8]) -> R) -> R { + if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)) { + return f(std::slice::from_raw_parts(at as *const u8, len)); } + TITLE_BYTES.with(|b| match b.try_borrow_mut() { + Ok(mut buf) => { + if buf.len() < len { + buf.resize(len, 0); + } + // (`read_committed_into` writes every byte: what an earlier read left does not show + // through a hole) + read_committed_into(at, &mut buf[..len]); + let r = f(&buf[..len]); + if buf.capacity() > TITLE_BYTES_KEPT { + *buf = Vec::new(); + } + r + } + Err(_) => f(&read_committed(at, len)), + }) } /// Every subresource (D3D12 order) of a texture from the title's memory at `va`. @@ -1470,15 +1521,15 @@ unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { let c = &tex.chain; let bpe = tex.bpe as usize; if tex.depth > 0 { - let mem = title_bytes(va, tex.size() as usize); - return c.levels.iter().enumerate().map(|(i, l)| Subresource { depth: l.depth, rows: l.height, row_bytes: l.width * bpe, data: c.detile_volume(&mem, i) }).collect(); + return with_title_bytes(va, tex.size() as usize, |mem| c.levels.iter().enumerate().map(|(i, l)| Subresource { depth: l.depth, rows: l.height, row_bytes: l.width * bpe, data: c.detile_volume(mem, i) }).collect()); } let mut out = Vec::with_capacity(tex.array as usize * c.levels.len()); for s in 0..tex.array as usize { - let slice = title_bytes(va + s * c.slice_bytes, c.slice_bytes); - for (i, l) in c.levels.iter().enumerate() { - out.push(Subresource { depth: 1, rows: l.height, row_bytes: l.width * bpe, data: c.detile_level(&slice, i, s) }); - } + with_title_bytes(va + s * c.slice_bytes, c.slice_bytes, |slice| { + for (i, l) in c.levels.iter().enumerate() { + out.push(Subresource { depth: 1, rows: l.height, row_bytes: l.width * bpe, data: c.detile_level(slice, i, s) }); + } + }); } out } @@ -1813,28 +1864,55 @@ mod tests { assert!(LIST_NOTES.lock().unwrap().get(&l1).is_none()); } - /// The title's bytes are used where they are when all of them are readable, and read with the - /// pages that are not committed as zeros otherwise – the same bytes either way. + /// The title's bytes outside the coherent window are read as `read_committed` reads them (the + /// pages that are not committed as zeros, never what an earlier read on the thread left); + /// inside it they are used where they are. #[test] - fn title_bytes_are_used_in_place_when_all_are_readable() { - use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + fn title_bytes_are_copied_outside_the_coherent_window() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; unsafe { let base = VirtualAlloc(std::ptr::null(), 3 << 12, MEM_RESERVE, PAGE_READWRITE) as usize; assert_ne!(base, 0); - for page in [0usize, 2] { - VirtualAlloc((base + (page << 12)) as *const c_void, 1 << 12, MEM_COMMIT, PAGE_READWRITE); + assert!(!VirtualAlloc(base as *const c_void, 3 << 12, MEM_COMMIT, PAGE_READWRITE).is_null()); + for page in 0..3usize { std::ptr::write_bytes((base + (page << 12)) as *mut u8, 0xA0 + page as u8, 1 << 12); } - let whole = title_bytes(base, 1 << 12); - assert!(matches!(whole, std::borrow::Cow::Borrowed(_)), "a committed page is not copied"); - assert_eq!(whole.as_ptr() as usize, base); - assert!(whole.iter().all(|&b| b == 0xA0)); - let holed = title_bytes(base, 3 << 12); - assert!(matches!(holed, std::borrow::Cow::Owned(_)), "a range with a reserved page is read"); - assert_eq!(&holed[..], &read_committed(base, 3 << 12)[..]); - assert!(holed[..1 << 12].iter().all(|&b| b == 0xA0) && holed[1 << 12..2 << 12].iter().all(|&b| b == 0) && holed[2 << 12..].iter().all(|&b| b == 0xA2)); + with_title_bytes(base, 3 << 12, |b| { + assert_ne!(b.as_ptr() as usize, base, "memory outside the coherent window is not read in place"); + assert_eq!(b, &read_committed(base, 3 << 12)[..]); + assert!((0..3usize).all(|p| b[p << 12..(p + 1) << 12].iter().all(|&x| x == 0xA0 + p as u8))); + }); + VirtualFree((base + (1 << 12)) as *mut c_void, 1 << 12, MEM_DECOMMIT); + // the hole reads as zeros, not as the page the last (as large) read copied + with_title_bytes(base, 3 << 12, |b| { + assert_eq!(b, &read_committed(base, 3 << 12)[..]); + assert!(b[..1 << 12].iter().all(|&x| x == 0xA0) && b[1 << 12..2 << 12].iter().all(|&x| x == 0) && b[2 << 12..].iter().all(|&x| x == 0xA2)); + }); + // a shorter read after a longer one: its hole too, and only its length + with_title_bytes(base + (1 << 12), 1 << 12, |b| assert!(b.len() == 1 << 12 && b.iter().all(|&x| x == 0))); VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + // a read of more than `TITLE_BYTES_KEPT` does not stay with the thread + let big = (65 << 20) + 1; + let at = VirtualAlloc(std::ptr::null(), big, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + if at != 0 { + std::ptr::write_bytes(at as *mut u8, 0x6D, big); + with_title_bytes(at, big, |b| assert!(b.len() == big && b.iter().all(|&x| x == 0x6D))); + assert!(TITLE_BYTES.with(|b| b.borrow().capacity()) <= TITLE_BYTES_KEPT, "the buffer of a large read is let go"); + VirtualFree(at as *mut c_void, 0, MEM_RELEASE); + } } + let Some(u) = crate::gpu::uma::get() else { return println!("title_bytes_are_copied_outside_the_coherent_window: no UMA, in-place read not checked") }; + let Some(p) = u.committed_window().and_then(|k| u.alloc_in(k, 1 << 16, 1 << 16)) else { + return println!("title_bytes_are_copied_outside_the_coherent_window: no coherent window, in-place read not checked"); + }; + unsafe { + std::ptr::write_bytes(p, 0x5C, 1 << 16); + with_title_bytes(p as usize, 1 << 16, |b| { + assert_eq!(b.as_ptr(), p as *const u8, "the coherent window is read in place"); + assert!(b.len() == 1 << 16 && b.iter().all(|&x| x == 0x5C)); + }); + } + u.free(p as usize); } /// Only the wanted parts of the watched regions are scanned, merged, one region each. @@ -2630,4 +2708,90 @@ mod tests { // Different device always starts a new batch. assert!(!batch_fits(1, 4096, 1, 2, 4096)); } + + /// Hashing the title's bytes must not fault with 0xC0000005 when another thread decommits + /// and commits pages of them meanwhile (memory outside the coherent window is not read in + /// place). + #[test] + fn title_bytes_survive_concurrent_decommit() { + use std::sync::atomic::AtomicBool; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + const PAGE: usize = 0x10000; + const PAGES: usize = 16; + unsafe { + let base = VirtualAlloc(std::ptr::null(), PAGES * PAGE, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + assert_ne!(VirtualAlloc(base as *const c_void, PAGES * PAGE, MEM_COMMIT, PAGE_READWRITE), std::ptr::null_mut()); + let stop = Arc::new(AtomicBool::new(false)); + let stop_w = Arc::clone(&stop); + // decommits made while the hashing ran (none: the test would prove nothing) + let decommits = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let decommits_w = Arc::clone(&decommits); + // each 4 KiB of the title's bytes holds its own number: a read sees it, or zeros where + // a page was decommitted (a recommitted page reads as zeros; a page decommitted while + // it was copied, its number then zeros) + let tag = |k: usize| 1 + (k % 255) as u8; + for k in 0..PAGES * PAGE / 4096 { + std::ptr::write_bytes((base + k * 4096) as *mut u8, tag(k), 4096); + } + let mutator = std::thread::spawn(move || { + let mut i = 0usize; + while !stop_w.load(Ordering::Relaxed) { + let p = (base + (1 + i % (PAGES - 2)) * PAGE) as *mut c_void; + let freed = VirtualFree(p, PAGE, MEM_DECOMMIT) != 0; + decommits_w.fetch_add(1, Ordering::Relaxed); + assert!(freed, "decommit"); + assert!(!VirtualAlloc(p, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null(), "recommit"); + i = i.wrapping_add(1); + } + }); + // (the mutator is running before the first hash) + while decommits.load(Ordering::Relaxed) == 0 && !mutator.is_finished() { + std::thread::yield_now(); + } + let before = decommits.load(Ordering::Relaxed); + for _ in 0..2000 { + let ok = with_title_bytes(base, PAGES * PAGE, |b| { + std::hint::black_box(content_hash(b)); + b.chunks(4096).enumerate().all(|(k, c)| { + let n = c.iter().position(|&x| x != tag(k)).unwrap_or(c.len()); + c[n..].iter().all(|&x| x == 0) + }) + }); + if !ok { + stop.store(true, Ordering::Relaxed); + let _ = mutator.join(); + panic!("a read returned bytes that were neither the title's nor zeros"); + } + } + let during = decommits.load(Ordering::Relaxed) - before; + stop.store(true, Ordering::Relaxed); + mutator.join().unwrap(); + assert!(during > 0, "no page was decommitted while the bytes were hashed"); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + + /// A guard or no-access page in the title's bytes reads as zeros, and the guard stays (a + /// title's guard page is its own: reading must not use it up). + #[test] + fn title_bytes_leave_guard_pages_alone() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READWRITE}; + unsafe { + let base = VirtualAlloc(std::ptr::null(), 3 << 12, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + std::ptr::write_bytes(base as *mut u8, 0x77, 3 << 12); + let mut old = 0; + assert_ne!(VirtualProtect((base + (1 << 12)) as *const c_void, 1 << 12, PAGE_READWRITE | PAGE_GUARD, &mut old), 0); + assert_ne!(VirtualProtect((base + (2 << 12)) as *const c_void, 1 << 12, PAGE_NOACCESS, &mut old), 0); + with_title_bytes(base, 3 << 12, |b| { + assert!(b[..1 << 12].iter().all(|&x| x == 0x77)); + assert!(b[1 << 12..].iter().all(|&x| x == 0), "guard and no-access pages read as zeros"); + }); + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery((base + (1 << 12)) as *const c_void, &mut m, std::mem::size_of_val(&m)); + assert_ne!(m.Protect & PAGE_GUARD, 0, "the guard page is still a guard page"); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } } 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..e68ac4d994 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/uma_driver.rs @@ -0,0 +1,305 @@ +//! 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> { + remake_with_after_release(device, base, size, || Ok(())) +} + +unsafe fn remake_with_after_release( + device: &ID3D12Device, + base: usize, + size: usize, + after_release: impl FnOnce() -> Result<(), String>, +) -> 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 { + let os_error = windows_sys::Win32::Foundation::GetLastError(); + crate::xlog_error!( + "D3D12.X: coherent window could not be restored at {base:#x} ({size} bytes, got {p:?}, Windows error {os_error}) after {why}; stopping before guest memory is used" + ); + crate::log::flush(); + windows_sys::Win32::System::Threading::TerminateProcess( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + 0x7C1_0003, + ); + std::process::abort(); + } + 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> { + after_release()?; + 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); + } + } + + #[test] + fn failed_restore_stops_before_importing_an_unbacked_window() { + use super::*; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + const SIZE: usize = 1 << 16; + const CODE: i32 = 0x7C1_0003; + if std::env::var_os("XCL_TEST_RESTORE_COLLISION").is_some() { + unsafe { + let mut dev = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).unwrap(); + let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + (base as *mut u8).write(0x5a); + let result = remake_with_after_release(&dev.unwrap(), base, SIZE, || { + let occupied = VirtualAlloc(base as *const c_void, SIZE, MEM_RESERVE, PAGE_NOACCESS); + assert_eq!(occupied as usize, base); + Err("synthetic post-release failure".into()) + }); + eprintln!("continued after failed restore: {result:?}"); + } + return; + } + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev) }.is_err() { + return crate::gpu::recomp::runner::skip_test("no D3D12 device"); + } + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::uma_driver::tests::failed_restore_stops_before_importing_an_unbacked_window", "--nocapture"]) + .env("XCL_TEST_RESTORE_COLLISION", "1") + .output() + .unwrap(); + let transcript = format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + assert_eq!(output.status.code(), Some(CODE), "{transcript}"); + assert!(transcript.contains("coherent window could not be restored"), "{transcript}"); + assert!(!transcript.contains("continued after failed restore"), "{transcript}"); + } +} diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index a9412c658c..1f5d3f4970 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -107,18 +107,6 @@ pub fn host_main(boot_path: &Path) -> i32 { } }); } - // `XCL_RUN_SECONDS=n`: the title ends itself after n seconds – the GPU drained, the log and - // report written (a process killed from outside with GPU work in flight can hang in the driver) - if let Some(secs) = std::env::var("XCL_RUN_SECONDS").ok().and_then(|v| v.parse::().ok()) { - std::thread::spawn(move || { - std::thread::sleep(std::time::Duration::from_secs(secs)); - let (shown, presented) = crate::hle::d3d12x::present::counters(); - crate::xlog_info!("XCL_RUN_SECONDS: {secs} s – ending the title ({shown} frames shown, {presented} PresentX calls)"); - crate::report::write_final(None); - crate::log::flush(); - crate::hle::d3d12x::real::end_title(0); - }); - } crate::stubs::init_db(&boot.config.stub_returns); crate::hle::init(&boot.config); crate::hle::kernelx::fine_timer(); @@ -144,8 +132,22 @@ pub fn host_main(boot_path: &Path) -> i32 { } crate::eh::install_crash_handler(); crate::eh::start_probes(); + crate::hle::d3d12x::backend_before_guest(); HOST_MODE.store(true, Ordering::Release); + // `XCL_RUN_SECONDS=n`: the title ends itself after n seconds – the GPU drained, the log and + // report written (a process killed from outside with GPU work in flight can hang in the driver) + if let Some(secs) = std::env::var("XCL_RUN_SECONDS").ok().and_then(|v| v.parse::().ok()) { + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_secs(secs)); + let (shown, presented) = crate::hle::d3d12x::present::counters(); + crate::xlog_info!("XCL_RUN_SECONDS: {secs} s – ending the title ({shown} frames shown, {presented} PresentX calls)"); + crate::report::write_final(None); + crate::log::flush(); + crate::hle::d3d12x::real::end_title(0); + }); + } + let main = match crate::loader::load_main(&boot.exe_path) { Ok(m) => m, Err(e) => { diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index 4f238248a9..8e7109f622 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -161,6 +161,9 @@ fn test_title_runs_and_game_folder_is_untouched() { assert!(out.status.success(), "exit code {:?}", out.status.code()); let log = std::fs::read_to_string(data.join("XCL.TestTitle/logs/xcl.log")).unwrap(); + let backend_init = log.find("D3D12.X: backend '").expect("backend initialized"); + let dll_init = log.find("DllMain(").expect("dependent DLL initialized"); + assert!(backend_init < dll_init, "D3D12 backend initialized after title DLL code ran"); let window = |tag| log.lines().find_map(|line| line.split_once(tag).map(|(_, hwnd)| hwnd)).unwrap(); assert_eq!(window("Shader preparation window "), window("present: swap chain window "));