From 956a476bf738a098f39df4f4c8acef682e43030f Mon Sep 17 00:00:00 2001 From: ivall Date: Mon, 23 Nov 2026 19:11:12 +0100 Subject: [PATCH] Retail game reaches 30 fps: frame events sharing a deadline, ExecuteCommandListsX, big pipelines in the background The frame clock fired one event type per deadline; a title scheduling the origin and type 2 at the same offset waited on type 2 for ever after two frames. Now every type due fires. Newer console layout: queue #35 is ExecuteCommandListsX, list #61 is ExecuteIndirect (the shift by two from #59 on). Bottom-of-pipe writes into memory the GPU does not see are done by the CPU after the queue's work, waits there read it on the CPU. Compute pipelines of 256 KB of DXIL or more are built in the background (2 at a time), a bind of one not started builds it itself. DXC -O1 from 1 MB of HLSL. `xcl shaders --precompile --pipelines` warms the driver's cache. --- HANDOFF.md | 14 +++ README.md | 2 +- crates/xcl/src/gpu/recomp/dxc.rs | 31 ++++- crates/xcl/src/hle/d3d12x/cpu_writes.rs | 157 ++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/frame.rs | 60 +++++---- crates/xcl/src/hle/d3d12x/list_x.rs | 30 ++++- crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/pso_async.rs | 67 ++++++---- crates/xcl/src/hle/d3d12x/real.rs | 61 ++++++++- crates/xcl/src/host.rs | 3 +- crates/xcl/src/shaders.rs | 107 +++++++++++++++- 11 files changed, 471 insertions(+), 62 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/cpu_writes.rs diff --git a/HANDOFF.md b/HANDOFF.md index a8d8a75..62998eb 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1759,6 +1759,20 @@ to an outside server at every crash (`hle/netoff.rs`: the title's WinHTTP / Wins holds an MS container (`MSNC_VS_TransformUnlit_*`, NGG) – the console's subobject numbering around AS / MS is to be checked (the message now lists the stream's subobject types and both hashes); translation failures are each logged once (the first five hid this one). +- Then: 30 fps (1 449 frames in 60 s), image black. Why it showed 2 frames: its present thread waits on frame event + type 2, scheduled at offset 0 like the origin; the clock picked one event per deadline (`min_by_key`: the + origin) – now every type due at a deadline fires (`frame.rs`). On the way: queue #35 of the newer layout is + ExecuteCommandListsX(count, lists, value, flags) – all its command lists went through the stub; list #61 is + ExecuteIndirect (the shift by two from #59 on; #61 went to FillMemoryWith32BitValueX); bottom-of-pipe writes into + memory outside unified memory are done by the CPU after the queue's work (`cpu_writes.rs`), waits there read it on + the CPU; compute pipelines of 256 KB of DXIL or more are built in the background (the driver takes ~30 s for + its 1 MB ray-tracing resolve programs; 2 at a time, within `wait_for_memory`), and a bind of one not started + builds it itself (`pso_async`); DXC -O1 from 1 MB of HLSL; `xcl shaders --precompile --pipelines` makes the + compute pipelines on the GPU too (the driver's cache: 41.6 s then 0.2 s; 4 at a time, `XCL_PIPELINE_THREADS`); + `XCL_TRACE_FRAME_EVENTS`; the end of a timed run logs the PresentX calls. +- Measured: the memory-window `switch` of every memory access doubles DXC + driver time (one 21 000-instruction CS: + 41.6 s with 4 windows, 22.5 s with 1); heap-indexed windows would remove it but a raw buffer view cannot cover a + 4 GiB window – a redesign of how shaders reach title memory. - XDefiant, Fortnite, Unicorn Overlord and Minecraft were **not** run after these changes (only the test suites). ## Next steps (priority) diff --git a/README.md b/README.md index d6e16c6..055dfe6 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ next steps: | **Unicorn Overlord** | `SEGAofAmericaInc.Pa253b0c1Y` 1.0.0.6 | ✅ | fully playable | – | | **Fortnite** | `436609B6.FortniteClient` 2.0.1461.7919 | ✅ | works fully, as far as the game allows without its online services | the game itself is online-only (multiplayer servers) | | **XDefiant** | `Ubisoft.XDefiant-Game` 1.0.0.186 | ✅ | works fully, as far as the game allows without its servers | the game's own servers have been shut down | -| **A newer retail game** | – | 🚧 | starts, presents its first frames after ~4 s and runs for ~3 minutes without a crash (2 frames shown, then it loads its ~3 500 shaders) | stops after ~3 minutes at mesh pipelines it creates; its image has not been checked yet | +| **A newer retail game** | – | 🚧 | starts in ~4 s and runs at a steady 30 fps (1 449 frames in 60 s, no crash) | the image is still black (a loading screen of 3 draws a frame); mesh pipelines with an AS slot are not supported yet | ## Highlights diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 894a967..0840dce 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -130,6 +130,15 @@ pub fn compile_threads() -> usize { }) } +/// GB of commit `wait_for_memory` keeps free besides the compiles: 6 for a running title (its +/// own allocations), less without one (`set_memory_reserve`: `xcl shaders --precompile`). +static RESERVE_GB: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(6); + +/// The commit `wait_for_memory` keeps free besides the compiles (no title running: less). +pub fn set_memory_reserve(gb: u64) { + RESERVE_GB.store(gb, std::sync::atomic::Ordering::Relaxed); +} + /// Compiles running on the DXC workers (`wait_for_memory` lets them in). static WORKING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); @@ -154,7 +163,7 @@ pub fn wait_for_memory() -> MemorySlot { loop { let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; m.dwLength = std::mem::size_of::() as u32; - let need = (6u64 << 30) + ((WORKING.load(Ordering::Acquire) as u64) << 30); + let need = (RESERVE_GB.load(Ordering::Relaxed) << 30) + ((WORKING.load(Ordering::Acquire) as u64) << 30); let plenty = unsafe { GlobalMemoryStatusEx(&mut m) } == 0 || m.ullAvailPageFile >= need; if plenty || start.elapsed().as_secs() >= 60 { WORKING.fetch_add(1, Ordering::AcqRel); @@ -208,8 +217,14 @@ fn compile_here(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result // With branch-free emission (select / and / or) it is fast: that shader 0.3 s, a // 15 720-instruction one 6 s (585 KB DXIL vs 1.6 MB at -O0, which the driver could not // compile). -O0 only as a safety net for enormous sources. - if src.len() > 8 * 1024 * 1024 && !extra.iter().any(|a| a.starts_with("-O")) { - args.push(crate::util::wide("-O0")); + // -O1 from 1 MB on: the same DXIL size at a quarter less time (a retail game's 4.8 MB HLSL of + // a 19 600-instruction CS: 13.5 s instead of 17.7 at -O3; -O0 10.6 s, but twice the DXIL) + if !extra.iter().any(|a| a.starts_with("-O")) { + if src.len() > 8 * 1024 * 1024 { + args.push(crate::util::wide("-O0")); + } else if src.len() > 1024 * 1024 { + args.push(crate::util::wide("-O1")); + } } args.extend(extra.iter().map(|a| crate::util::wide(a))); let ptrs: Vec = args.iter().map(|a| PCWSTR(a.as_ptr())).collect(); @@ -598,6 +613,16 @@ pub fn cached_only(f: impl FnOnce() -> R) -> (R, bool) { (r, MISSED.with(|m| m.replace(false))) } +/// Inside `cached_only`: what is being made is deferred as if its DXIL were missing (the +/// driver's compile of a big program is the slow part then). False outside `cached_only`. +pub fn defer() -> bool { + let inside = CACHED_ONLY.with(|c| c.get()); + if inside { + MISSED.with(|m| m.set(true)); + } + inside +} + /// Inside `cached_only`. pub fn in_cached_only() -> bool { CACHED_ONLY.with(|c| c.get()) diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs new file mode 100644 index 0000000..6aafc66 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -0,0 +1,157 @@ +//! Write32/64BitValueBottomOfPipeX into memory the GPU does not see: done by the CPU once the GPU +//! has finished the work before them. +//! +//! A console title marks its GPU progress with bottom-of-pipe writes into its own memory and +//! waits on them (a retail game: plain `VirtualAlloc` memory, outside XCL's unified memory). +//! The PC GPU cannot write there; dropped, the title waited for ever after its second frame. +//! Here each queue gets a fence of XCL's: after a submission whose lists carry such writes the +//! queue signals it, and a worker thread does the writes, in submission order, when the GPU is +//! there – what bottom of pipe means. + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{mpsc, Mutex, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Foundation::HANDLE; +use windows::Win32::Graphics::Direct3D12::*; +use windows_sys::Win32::System::Threading as th; + +/// (address, the dwords from there) +pub(super) type Write = (usize, Vec); + +struct Job { + fence: ID3D12Fence, + value: u64, + writes: Vec, +} + +// SAFETY: the fence is a free-threaded COM object; the writes are plain data +unsafe impl Send for Job {} + +/// queue → its fence and the last value signalled +struct QueueFence { + fence: ID3D12Fence, + value: u64, +} + +unsafe impl Send for QueueFence {} + +static FENCES: Mutex>> = Mutex::new(None); + +/// how long the worker waits for one submission before writing anyway (a removed device, a +/// queue that never gets there) +const WAIT_MS: u32 = 10_000; + +fn worker() -> &'static Mutex> { + static W: OnceLock>> = OnceLock::new(); + W.get_or_init(|| { + let (tx, rx) = mpsc::channel::(); + let spawned = std::thread::Builder::new().name("xcl-cpu-writes".into()).spawn(move || unsafe { + let event = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()); + for job in rx { + if job.fence.GetCompletedValue() < job.value && job.fence.SetEventOnCompletion(job.value, HANDLE(event as *mut c_void)).is_ok() { + th::WaitForSingleObject(event, WAIT_MS); + } + for (va, words) in &job.writes { + write_now(*va, words); + } + } + }); + if let Err(e) = spawned { + crate::xlog_error!("D3D12.X: no thread for the writes after the GPU: {e}"); + } + Mutex::new(tx) + }) +} + +/// The dwords at `va`, if the memory is still there and writable. +unsafe fn write_now(va: usize, words: &[u32]) { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT { + return; + } + if m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 || (m.BaseAddress as usize + m.RegionSize) < va + 4 * words.len() { + return; + } + for (i, &w) in words.iter().enumerate() { + (*((va + 4 * i) as *const AtomicU32)).store(w, Ordering::Release); + } +} + +/// Whether `[va, va + bytes)` is memory the CPU can write for the GPU later. +pub(super) fn writable(va: usize, bytes: usize) -> bool { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + let found = unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0; + found + && m.State == MEM_COMMIT + && m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) != 0 + && m.BaseAddress as usize + m.RegionSize >= va + bytes +} + +/// `writes` of lists just submitted to `queue`: done when the GPU has finished them. +pub(super) unsafe fn after(queue: *mut c_void, writes: Vec) { + if writes.is_empty() || queue.is_null() { + return; + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let job = { + let mut g = FENCES.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + let entry = match m.entry(queue as usize) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(v) => { + let mut dev: Option = None; + if q.GetDevice(&mut dev).is_err() { + return; + } + let Some(dev) = dev else { return }; + let Ok(fence) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return }; + v.insert(QueueFence { fence, value: 0 }) + } + }; + entry.value += 1; + if q.Signal(&entry.fence, entry.value).is_err() { + return; + } + Job { fence: entry.fence.clone(), value: entry.value, writes } + }; + static FIRST: std::sync::Once = std::sync::Once::new(); + FIRST.call_once(|| crate::xlog_info!("D3D12.X: bottom-of-pipe writes outside unified memory are done by the CPU after the GPU ({} in the first submission)", job.writes.len())); + let _ = worker().lock().unwrap().send(job); +} + +#[cfg(test)] +mod tests { + use super::*; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + /// The value lands after the queue has done what came before it. + #[test] + fn writes_land_after_the_queue() { + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let factory: IDXGIFactory4 = CreateDXGIFactory1().unwrap(); + let warp: IDXGIAdapter = factory.EnumWarpAdapter().unwrap(); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.unwrap(); + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let cell = Box::new([0u32; 2]); + let va = cell.as_ptr() as usize; + assert!(writable(va, 8)); + after(q.as_raw(), vec![(va, vec![7, 9])]); + let t = std::time::Instant::now(); + while (*(va as *const AtomicU32)).load(Ordering::Acquire) != 7 { + assert!(t.elapsed().as_secs() < 5, "never written"); + std::thread::yield_now(); + } + assert_eq!(*cell, [7, 9]); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/frame.rs b/crates/xcl/src/hle/d3d12x/frame.rs index c2fecf4..a97cee5 100644 --- a/crates/xcl/src/hle/d3d12x/frame.rs +++ b/crates/xcl/src/hle/d3d12x/frame.rs @@ -228,6 +228,7 @@ unsafe fn note_signaled(block: *const u8, index: i32) { /// device #79 ScheduleFrameEventX(type, offset µs, ancillary, flags) pub unsafe extern "system" fn schedule_frame_event_x(_this: *mut std::ffi::c_void, ty: u32, offset_us: u32, block: *const u8, flags: u32) -> HRESULT { + trace_calls(format_args!("ScheduleFrameEventX(type {ty}, offset {offset_us} µs, block {block:p}, flags {flags:#x})")); let unschedule = flags & UNSCHEDULE != 0; let invalid = with(|c| c.interval_us == 0 || ty as usize >= TYPES || (!c.active && ty != 0) || (unschedule && (ty == 0 || !c.kinds[0].scheduled))); if invalid { @@ -286,7 +287,17 @@ pub fn activity() -> [u64; 4] { } /// device #80 WaitFrameEventX(type, timeout ms, ancillary, flags, token in/out) +/// `XCL_TRACE_FRAME_EVENTS`: the title's frame-event calls (the first 40) +fn trace_calls(what: std::fmt::Arguments) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + static N: AtomicU64 = AtomicU64::new(0); + if *ON.get_or_init(|| std::env::var_os("XCL_TRACE_FRAME_EVENTS").is_some()) && N.fetch_add(1, Ordering::Relaxed) < 40 { + crate::xlog_info!("frame events: {what}"); + } +} + pub unsafe extern "system" fn wait_frame_event_x(_this: *mut std::ffi::c_void, ty: u32, timeout_ms: u32, block: *const u8, flags: u32, token: *mut u64) -> HRESULT { + trace_calls(format_args!("WaitFrameEventX(type {ty}, timeout {timeout_ms} ms, block {block:p}, flags {flags:#x}, token in {:#x})", if token.is_null() { 0 } else { *token })); let internal = with(|c| ((ty as usize) < TYPES && c.kinds[ty as usize].scheduled).then(|| c.kinds[ty as usize].internal as usize)); let Some(internal) = internal else { return E_INVALIDARG }; let token_in = if token.is_null() { 0 } else { *token }; @@ -411,14 +422,18 @@ fn clock_thread() { } let mut last = [i64::MIN / 2; TYPES]; loop { - // the next event of the current schedule + // the next events of the current schedule: every type due at the earliest deadline + // (types at the same point of the frame fire together – a retail game schedules the + // origin and type 2 both at offset 0 and waits on type 2; picking one, the origin + // always won and type 2 never came) let plan = with(|c| { if !c.active || c.interval_us == 0 { return None; } let interval = ticks(c.interval_us as i64); let now = qpc(); - c.kinds + let due: Vec<(i64, usize, usize, Arc)> = c + .kinds .iter() .enumerate() .filter(|(_, k)| k.scheduled) @@ -429,34 +444,37 @@ fn clock_thread() { } (d, i, k.internal as usize, Arc::clone(&k.extra)) }) - .min_by_key(|e| e.0) - .map(|e| (c.generation, e)) + .collect(); + let first = due.iter().map(|e| e.0).min()?; + Some((c.generation, first, due.into_iter().filter(|e| e.0 == first).collect::>())) }); - let Some((generation, (deadline, ty, internal, extra))) = plan else { + let Some((generation, deadline, due)) = plan else { WaitForMultipleObjects(1, &wake(), 0, INFINITE); continue; }; if !sleep_until(timer, deadline) || !with(|c| c.generation == generation) { continue; } - last[ty] = deadline; - if ty == 0 { - let now = qpc(); - LAST_ORIGIN.store(now, Ordering::Relaxed); - // an origin the semaphore cannot hold (ORIGIN_SEMAPHORE_MAX pending) is lost to the title too - if ReleaseSemaphore(internal as HANDLE, 1, std::ptr::null_mut()) != 0 { - let mut o = ORIGINS.lock().unwrap(); - o.push_back(now); - while o.len() > ORIGIN_SEMAPHORE_MAX as usize { - o.pop_front(); + for (_, ty, internal, extra) in due { + last[ty] = deadline; + if ty == 0 { + let now = qpc(); + LAST_ORIGIN.store(now, Ordering::Relaxed); + // an origin the semaphore cannot hold (ORIGIN_SEMAPHORE_MAX pending) is lost to the title too + if ReleaseSemaphore(internal as HANDLE, 1, std::ptr::null_mut()) != 0 { + let mut o = ORIGINS.lock().unwrap(); + o.push_back(now); + while o.len() > ORIGIN_SEMAPHORE_MAX as usize { + o.pop_front(); + } } + } else { + SetEvent(internal as HANDLE); } - } else { - SetEvent(internal as HANDLE); - } - for &h in &extra.0 { - if SetEvent(h) == 0 { - ReleaseSemaphore(h, 1, std::ptr::null_mut()); + for &h in &extra.0 { + if SetEvent(h) == 0 { + ReleaseSemaphore(h, 1, std::ptr::null_mut()); + } } } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index e246f1c..68cfd4d 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -526,6 +526,8 @@ struct ListState { sparse_writes: Vec<(usize, usize)>, /// External memory waits recorded on this list pending_waits: Vec, + /// bottom-of-pipe writes into memory the GPU does not see (`cpu_writes`) + cpu_writes: Vec, /// state a PC Reset clears (restored after KickoffX) bindings: Bindings, } @@ -877,6 +879,16 @@ pub(super) unsafe fn readback_sparse_writes(queue: *mut c_void, lists: &[*mut c_ } } +/// After `lists` went to `queue`: their writes into memory the GPU does not see (`cpu_writes`). +pub(super) unsafe fn cpu_writes_after(queue: *mut c_void, lists: &[*mut c_void]) { + let writes: Vec = { + let g = LISTS.lock().unwrap(); + let Some(m) = g.as_ref() else { return }; + lists.iter().filter_map(|&l| m.get(&(l as usize))).flat_map(|s| s.cpu_writes.iter().cloned()).collect() + }; + super::cpu_writes::after(queue, writes); +} + /// Submit `lists` through `submit`, splitting the batch before any list whose `Wait32/64BitValueX` /// condition is not yet satisfied so earlier lists in the same batch can run on the GPU first. pub(super) unsafe fn execute_with_waits(lists: &[*mut c_void], mut submit: impl FnMut(&[*mut c_void])) { @@ -1043,6 +1055,13 @@ unsafe fn write(list: *mut c_void, va: u64, words: &[u32], mode: D3D12_WRITEBUFF return warn(&N, what, format_args!("{va:#x} is not {n}-byte aligned")); } let (Some((d, _)), Some(at)) = (real::uma_window_buffer(va as usize, n as usize), real::uma_va_of(va as usize)) else { + // the title's own memory: written by the CPU once the GPU is there + if super::cpu_writes::writable(va as usize, n as usize) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.cpu_writes.push((va as usize, words.to_vec())); + return; + } + } return warn(&N, what, format_args!("{va:#x} is not in unified memory")); }; note_write(list as usize, va, n); @@ -1115,8 +1134,9 @@ unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, va if !va.is_multiple_of(n) { return warn(&N, what, format_args!("{va:#x} is not {n}-byte aligned")); } - if real::uma_window_buffer(va as usize, width as usize).is_none() { - return warn(&N, what, format_args!("{va:#x} is not in unified memory")); + // (the wait reads the memory on the CPU: the title's own memory too, which `cpu_writes` fills) + if real::uma_window_buffer(va as usize, width as usize).is_none() && !crate::gpu::shader::readable(va as usize, width as usize) { + return warn(&N, what, format_args!("{va:#x} is not readable memory")); } if compare_u64(comparison, 0, 0).is_none() { return warn(&N, what, format_args!("unknown comparison op {comparison}")); @@ -1257,8 +1277,10 @@ pub(super) unsafe extern "system" fn kickoff_x(this: *mut c_void) { }; let sparse_writes = s.clear_sparse_writes(); s.written_ranges.clear(); - (s.allocator, q, s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, active_query, waits, sparse_writes) + let cpu_writes = std::mem::take(&mut s.cpu_writes); + (s.allocator, q, s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, active_query, waits, (sparse_writes, cpu_writes)) }; + let (sparse_writes, cpu_writes) = sparse_writes; // End any active occlusion query before Close (PC forbids closing with an open query). if let Some(((h, i), qty)) = active_query { @@ -1287,6 +1309,7 @@ pub(super) unsafe extern "system" fn kickoff_x(this: *mut c_void) { super::sparse::readback_after_execute(q, &sparse_writes); } } + super::cpu_writes::after(q_raw, cpu_writes); let ext_closed = *(this as *const usize); let init_pso = super::pso_async::resolve_for_bind(bound_pso); @@ -1674,6 +1697,7 @@ pub(super) unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, ps s.written_ranges.clear(); s.clear_sparse_writes(); s.clear_waits(); + s.cpu_writes.clear(); s.bindings = Bindings::default(); s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) }; diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 1d4e766..3d06198 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -14,6 +14,7 @@ pub mod console_heap; pub mod console_list; pub mod device_x; pub mod dxgi_device; +mod cpu_writes; mod fence_x; pub mod frame; pub mod guard; diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index a8cc75d..ff4a30f 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -12,6 +12,8 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; struct Pending { + /// the build, until a worker – or a bind that cannot wait for the queue – takes it + job: Mutex>, /// the real pipeline state (raw pointer), 0 while building or when building failed real: AtomicUsize, done: Mutex, @@ -23,6 +25,29 @@ struct Pending { /// stand-in handed to the title → its real pipeline static PENDING: Mutex>>> = Mutex::new(None); + +/// The build is done (`real`: its pipeline, 0 = failed). +fn complete(p: &Pending, real: usize) { + if real == 0 { + FAILED.fetch_add(1, Ordering::Relaxed); + } else { + BUILT.fetch_add(1, Ordering::Relaxed); + } + let orphan = { + let mut done = p.done.lock().unwrap(); + let orphan = p.orphan.load(Ordering::Acquire); + if !orphan { + p.real.store(real, Ordering::Release); + } + *done = true; + p.cv.notify_all(); + orphan + }; + // outside `done`: the Release override takes PENDING (`counts` takes PENDING, then `done`) + if orphan { + release(real); + } +} static BUILT: AtomicUsize = AtomicUsize::new(0); static FAILED: AtomicUsize = AtomicUsize::new(0); @@ -33,10 +58,10 @@ pub fn enabled() -> bool { /// Builds the real pipeline: its raw pointer, 0 = failed. pub type Job = Box usize + Send>; -fn queue() -> &'static Mutex, Job)>> { - static Q: OnceLock, Job)>>> = OnceLock::new(); +fn queue() -> &'static Mutex>> { + static Q: OnceLock>>> = OnceLock::new(); Q.get_or_init(|| { - let (tx, rx) = mpsc::channel::<(Arc, Job)>(); + let (tx, rx) = mpsc::channel::>(); let rx = Arc::new(Mutex::new(rx)); // translation recurses deeply on big programs; DXC itself runs on its own pool let n = crate::gpu::recomp::dxc::compile_threads(); @@ -44,26 +69,11 @@ fn queue() -> &'static Mutex, Job)>> { let rx = rx.clone(); let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop { let next = rx.lock().unwrap().recv(); - let Ok((p, job)) = next else { return }; - let real = job(); - if real == 0 { - FAILED.fetch_add(1, Ordering::Relaxed); - } else { - BUILT.fetch_add(1, Ordering::Relaxed); - } - let orphan = { - let mut done = p.done.lock().unwrap(); - let orphan = p.orphan.load(Ordering::Acquire); - if !orphan { - p.real.store(real, Ordering::Release); - } - *done = true; - p.cv.notify_all(); - orphan - }; - // outside `done`: the Release override takes PENDING (`counts` takes PENDING, then `done`) - if orphan { - release(real); + let Ok(p) = next else { return }; + // (None: a bind took it and builds it itself) + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + complete(&p, job()); } }); } @@ -80,13 +90,13 @@ pub fn release(p: usize) { /// `standin` went to the title; `job` builds the real pipeline on a worker. pub fn submit(standin: usize, compute: bool, job: Job) { - let p = Arc::new(Pending { real: AtomicUsize::new(0), done: Mutex::new(false), cv: Condvar::new(), compute, orphan: Default::default() }); + let p = Arc::new(Pending { job: Mutex::new(Some(job)), real: AtomicUsize::new(0), done: Mutex::new(false), cv: Condvar::new(), compute, orphan: Default::default() }); PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); }); - let _ = queue().lock().unwrap().send((p, job)); + let _ = queue().lock().unwrap().send(p); } fn entry(pso: usize) -> Option> { @@ -101,9 +111,14 @@ pub fn resolve(pso: usize) -> usize { } } -/// `resolve`, waiting for a pipeline still being built. +/// `resolve`, waiting for a pipeline still being built – built here if no worker has started +/// it yet (a queue of a title's hundreds of pipelines must not hold up the one it binds now). pub fn resolve_wait(pso: usize) -> usize { let Some(p) = entry(pso) else { return pso }; + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + complete(&p, job()); + } let mut done = p.done.lock().unwrap(); while !*done { done = p.cv.wait(done).unwrap(); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 3e7a44f..4089016 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2833,6 +2833,38 @@ unsafe fn abi_rs_raw(this: *mut c_void) -> Option<*mut c_void> { /// A compute pipeline with a console CS: `None` = not a console shader, `Some(Err)` = console /// shader the recompiler could not take, `Some(Ok(hr))` = translated pipeline created (or the /// driver's verdict on it). +/// DXIL size from which a compute pipeline's driver compile goes to the background +const BIG_DRIVER_COMPILE: usize = 256 << 10; + +/// A counting semaphore: background driver compiles of big programs at once. +struct Slots { + n: Mutex, + cv: std::sync::Condvar, + most: usize, +} + +struct SlotGuard(&'static Slots); + +impl Slots { + fn acquire(&'static self) -> SlotGuard { + let mut n = self.n.lock().unwrap(); + while *n >= self.most { + n = self.cv.wait(n).unwrap(); + } + *n += 1; + SlotGuard(self) + } +} + +impl Drop for SlotGuard { + fn drop(&mut self) { + *self.0.n.lock().unwrap() -= 1; + self.0.cv.notify_one(); + } +} + +static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 2 }; + unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option> { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { @@ -2851,12 +2883,21 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi } }; let dxil = compiled.dxil; + // a big program: the driver's compile takes it seconds to a minute (a retail game's 1 MB + // ray-tracing resolve programs ~30 s each, ~600 of them): built in the background like one + // whose DXIL is missing – the title's loading does not wait for it, its first bind does + let big = dxil.len() >= BIG_DRIVER_COMPILE; + if big && crate::gpu::recomp::dxc::defer() { + return Some(Err(())); + } let Some(rs) = abi_rs_for(this, &compiled.samplers) else { return Some(Err(())) }; LAST_COMPUTE_RS.with(|c| c.set(rs as usize)); let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(d); copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); copy.CS = bytecode(&dxil); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + // in the background, a few at a time and within the commit left (each ~1.5 GB in the driver) + let _slot = (big && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso"))).then(|| (BIG_COMPILES.acquire(), crate::gpu::recomp::dxc::wait_for_memory())); let hr = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); if hr < 0 { note_translation_error(format!("the driver rejected the compute PSO with the translated CS ({hr:#x})")); @@ -3969,8 +4010,10 @@ unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { // texture uploads with CopyTextureRegionX at #85 (the older layout's #83; its #85 is // SetPredicationBufferX, which dropped them – every texture stayed zero). From #85 on the // list's console methods sit two slots later (`NEWER_LIST_SLOTS`), and from #72 on as well: a retail game -// calls Write64BitValueBottomOfPipeX at #72 and Wait64BitValueX at #74. Where the shift starts -// below #72 is not known. The newer layout's #139 is a Reset with one argument more (the same +// calls Write64BitValueBottomOfPipeX at #72 and Wait64BitValueX at #74, Write32BitValueBottomOfPipeX +// at #71 (address, value, 0, 0) and ExecuteIndirect at #61 (signature, 1, argument buffer, offset, +// NULL, 0) – sent to FillMemoryWith32BitValueX, the title's indirect draws and dispatches never ran. +// So the shift starts at #59 or below; where is not known. The newer layout's #139 is a Reset with one argument more (the same // title: (allocator, NULL, 0) on each list it takes from its pool before recording – as a stub // the list stayed closed, the debug layer saw every call on it refused, and Close failed). @@ -3983,7 +4026,7 @@ pub(super) static QUEUE_SHIFTED: AtomicBool = AtomicBool::new(false); static QUEUE_OLDER: AtomicBool = AtomicBool::new(false); /// command list slots of the newer layout → the older layout's slot of the same method -const NEWER_LIST_SLOTS: [(usize, usize); 14] = [(72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (139, 10)]; +const NEWER_LIST_SLOTS: [(usize, usize); 21] = [(61, 59), (62, 60), (63, 61), (64, 62), (65, 63), (70, 68), (71, 69), (72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (139, 10)]; /// The title called device method `slot`, which only runtimes with the newer layouts have (a retail game /// records its first lists before any queue call could tell). @@ -4058,6 +4101,15 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a } 23 => q_signal_x(this, a1 as *mut c_void, a2 as u64, a3 as u32) as u32 as usize, 30 => super::present::present_x(this, a1 as u32, a2 as *const u8, a3 as *const u8) as u32 as usize, + // the newer layout's #35: ExecuteCommandListsX(count, lists, a value, flags) – a retail + // game submits all its command lists this way (flags 3; 0 for the one it recorded at + // start); as a stub nothing the title recorded ran on the GPU but its first two frames + 33 if shifted => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_info!("D3D12.X: queue #35 ExecuteCommandListsX ({} lists, value {a3:#x}, flags {a4:#x})", a1)); + q_execute_command_lists(this, a1 as u32, a2 as *const *mut c_void); + 0 + } _ => { // a console method not modelled: logged once, S_OK (as the stubs it replaces; frame // pacing on queue methods keeps working for titles without PresentX) @@ -4092,7 +4144,7 @@ macro_rules! queue_slots { }),*]; }; } -queue_slots!(14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34); +queue_slots!(14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35); /// command queue #23 SignalX(fence, value, flush flags): Signal with the console's cache flush /// options – the PC's Signal makes the queue's writes visible itself. (A stub that signalled @@ -4135,6 +4187,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis super::list_x::execute_with_waits(&mapped, |chunk| { f(this, chunk.len() as u32, chunk.as_ptr()); super::list_x::readback_sparse_writes(this, chunk); + super::list_x::cpu_writes_after(this, chunk); }); super::present::note_execute(this, &mapped); stop_if_device_removed(); diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 15d4918..22b9c82 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -70,7 +70,8 @@ pub fn host_main(boot_path: &Path) -> i32 { 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)); - crate::xlog_info!("XCL_RUN_SECONDS: {secs} s – ending the title ({} frames shown)", crate::hle::d3d12x::present::presents()); + 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); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index ed2f78a..9cdbcd0 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -714,7 +714,8 @@ pub fn run(path: &Path, args: &[String]) -> i32 { }; if args.iter().any(|a| a == "--precompile") { let only = args.iter().position(|a| a == "--only").and_then(|i| args.get(i + 1)).map(|s| s.to_ascii_lowercase()); - return precompile(&input, opt("--limit").unwrap_or(usize::MAX), opt("--windows").unwrap_or(4) as u32, opt("--split").map(|v| v != 0), only.as_deref(), t0); + let pipelines = args.iter().any(|a| a == "--pipelines"); + return precompile(&input, opt("--limit").unwrap_or(usize::MAX), opt("--windows").unwrap_or(4) as u32, opt("--split").map(|v| v != 0), only.as_deref(), pipelines, t0); } let agg = analyze(&input, recomp_on, compile, iface_on); drop(input); @@ -732,13 +733,105 @@ pub fn run(path: &Path, args: &[String]) -> i32 { /// no split form, so a title asked for other HLSL and compiled everything again. Still /// different at run time: a PS's static samplers after its VS's (sampler base 0 here) and the /// mesh pass-through, which the runtime builds for its pixel shader. -fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, t0: std::time::Instant) -> i32 { +/// `--pipelines`: each compute program's pipeline made on the GPU as a title's would be (XCL's +/// ABI root signature with its static samplers): the driver keeps what it compiled in its own +/// cache, which the title then finds – a retail game's 1 MB-DXIL programs kept its loading +/// waiting for the driver's compiler for minutes. Nothing runs on the GPU. +struct Pipelines { + dev: windows::Win32::Graphics::Direct3D12::ID3D12Device, + signatures: Mutex, windows::Win32::Graphics::Direct3D12::ID3D12RootSignature>>, + made: AtomicUsize, + refused: AtomicUsize, + /// driver compiles running and the most at once (`XCL_PIPELINE_THREADS`, 4): each of the + /// biggest takes ~1.5 GB in the driver – fifteen at once took 24 GB + running: (Mutex, std::sync::Condvar), + most: usize, +} + +// D3D12 devices and root signatures are free-threaded +unsafe impl Sync for Pipelines {} + +impl Pipelines { + fn new() -> Result { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| e.to_string())?; + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?; + let most = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4usize).max(1); + Ok(Pipelines { dev, signatures: Mutex::new(Default::default()), made: AtomicUsize::new(0), refused: AtomicUsize::new(0), running: (Mutex::new(0), std::sync::Condvar::new()), most }) + } + } + + /// The compute pipeline of `c` (made and released). + fn make(&self, c: &recomp::pso::Compiled) { + use windows::Win32::Graphics::Direct3D12::*; + let key: Vec = c.samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect(); + let rs = { + let mut g = self.signatures.lock().unwrap(); + match g.get(&key) { + Some(rs) => rs.clone(), + None => match recomp::pso::abi_root_signature_with(&self.dev, true, &c.samplers) { + Ok(rs) => { + g.insert(key, rs.clone()); + rs + } + Err(_) => { + self.refused.fetch_add(1, Ordering::Relaxed); + return; + } + }, + } + }; + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs)), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: c.dxil.as_ptr() as *const _, BytecodeLength: c.dxil.len() }, + ..Default::default() + }; + { + let mut n = self.running.0.lock().unwrap(); + while *n >= self.most { + n = self.running.1.wait(n).unwrap(); + } + *n += 1; + } + let r: windows::core::Result = unsafe { self.dev.CreateComputePipelineState(&desc) }; + *self.running.0.lock().unwrap() -= 1; + self.running.1.notify_one(); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + let done = match r { + Ok(_) => self.made.fetch_add(1, Ordering::Relaxed) + 1, + Err(_) => self.refused.fetch_add(1, Ordering::Relaxed) + 1, + }; + if done % 25 == 0 { + eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)); + } + } +} + +fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, t0: std::time::Instant) -> i32 { + let pipelines = if pipelines { + match Pipelines::new() { + Ok(p) => Some(p), + Err(e) => { + eprintln!("xcl shaders --pipelines: no GPU device: {e}"); + return 2; + } + } + } else { + None + }; + let pipelines = pipelines.as_ref(); let n = input.len().min(limit); let next = AtomicUsize::new(0); let (done, compiled, cached, failed, skipped) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); let errors: Mutex> = Mutex::new(Vec::new()); // the compiles run on the DXC pool; these threads translate and keep it fed let threads = recomp::dxc::compile_threads() + 2; + // no title runs: only a little commit is kept free besides the compiles + recomp::dxc::set_memory_reserve(2); let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w)); println!( "precompiling {n} shaders into {} ({} compile threads; {windows} memory windows{})", @@ -764,7 +857,12 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // into the translation cache too, so the title does not translate it again if sh.fssm.iter().any(|f| matches!(recomp::interface(&blob, &sh, f), Some(recomp::Mode::Compute(_)))) { match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { - Ok(_) => compiled.fetch_add(1, Ordering::Relaxed), + Ok(c) => { + if let Some(p) = pipelines { + p.make(&c); + } + compiled.fetch_add(1, Ordering::Relaxed) + } Err(e) => { let mut g = errors.lock().unwrap(); if g.len() < 10 { @@ -830,6 +928,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on skipped.into_inner(), t0.elapsed().as_secs_f64() ); + if let Some(p) = pipelines { + println!("pipelines made on the GPU {}, refused {}", p.made.load(Ordering::Relaxed), p.refused.load(Ordering::Relaxed)); + } for e in errors.into_inner().unwrap() { println!(" {e}"); }