diff --git a/crates/xcl/src/hle/d3d12x/frame.rs b/crates/xcl/src/hle/d3d12x/frame.rs index 38c073c0e..d4ea12c8b 100644 --- a/crates/xcl/src/hle/d3d12x/frame.rs +++ b/crates/xcl/src/hle/d3d12x/frame.rs @@ -453,6 +453,7 @@ pub unsafe extern "system" fn wait_frame_event_x(_this: *mut std::ffi::c_void, t /// `PresentX` flipped the frame of `token`. pub fn mark_flipped(token: u64) { + super::pso_async::on_frame_end(); if token == 0 { return; } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 7342be7b1..b0c798c60 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -892,8 +892,9 @@ pub(super) unsafe fn on_set_pipeline_state(list: *mut c_void, pso: usize) { let sync_target = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(key).or_default(); - // Keep the title-visible base PSO key when `bind_abi` re-binds its resolved background PSO. - if s.bound_pso == 0 || pso == s.bound_pso || super::pso_async::resolve(s.bound_pso) != pso { + // Keep the title-visible base PSO key when `bind_abi` re-binds its resolved background PSO, + // without triggering lazy compilation or recording usage for a bind-only pipeline. + if s.bound_pso == 0 || pso == s.bound_pso || super::pso_async::resolve_if_ready(s.bound_pso) != pso { s.bound_pso = pso; } let effective = s.bound_pso; diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index f3f035798..330996e3e 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -25,6 +25,7 @@ pub mod list_x; pub mod null; pub mod present; pub mod pso_async; +pub mod pso_library; pub mod real; mod shader_cache_session; pub mod sparse; diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 2958aa0e9..079c28f55 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -315,6 +315,7 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) match msg { WM_CLOSE => { crate::xlog_info!("XCL window closed – ending the game process"); + super::real::flush_pipeline_library(); crate::report::write_final(None); crate::log::flush(); windows::Win32::System::Threading::ExitProcess(0); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 13a9502dc..7a8174847 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -7,15 +7,18 @@ //! for at its first bind (a skipped dispatch would corrupt what it computes). //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. -use std::collections::HashMap; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; +use std::collections::{HashMap, VecDeque}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; +use std::time::{Duration, Instant}; struct Pending { - /// the build, until a worker – or a bind that cannot wait for the queue – takes it + /// the build, until a worker takes it job: Mutex>, /// the build went to the workers (a lazy one goes on its first `resolve`) - sent: std::sync::atomic::AtomicBool, + sent: AtomicBool, + /// pushed to the urgent front queue so a waited-for bind is not stuck behind background work + urgent_queued: AtomicBool, /// the real pipeline state (raw pointer), 0 while building or when building failed real: AtomicUsize, done: Mutex, @@ -24,22 +27,24 @@ struct Pending { /// of its shaders (`used`); 0 = none key: u64, /// it was used (`used::note` is told once) - used: std::sync::atomic::AtomicBool, + used: AtomicBool, /// the stand-in was released before the real pipeline was built - orphan: std::sync::atomic::AtomicBool, + orphan: AtomicBool, /// a bind waited for it longer than `wait_budget`: binds go on without it until it is built - late: std::sync::atomic::AtomicBool, + late: AtomicBool, /// its dispatches may be left out while it is built (`image_only`): binds do not wait for it - spared: std::sync::atomic::AtomicBool, + spared: AtomicBool, demand: Mutex, } -/// Whether one of the title's threads waits for the pipeline, and the preload worker building it. +/// Whether one of the title's threads waits for the pipeline, and the worker thread building it. #[derive(Default)] struct Demand { wanted: bool, - /// thread id of the preload worker (lowest priority) building it, 0 = none - preload_thread: u32, + /// active title threads currently blocked waiting on this pipeline + waiters: usize, + /// thread id of the worker building it (raised to normal priority when `wanted`), 0 = none + worker_thread: u32, } thread_local! { @@ -64,25 +69,25 @@ pub fn wanted_here() -> crate::gpu::recomp::dxc::Wanted { Box::new(move || own) } -/// A worker's build of `p` (`preload`: by one of the lowest-priority workers). -fn build(p: &Arc, job: Job, preload: bool) { - use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_NORMAL}; +/// A worker's build of `p` (`base_priority`: `THREAD_PRIORITY_BELOW_NORMAL` for normal workers, +/// `THREAD_PRIORITY_LOWEST` for preload workers). +fn build(p: &Arc, job: Job, base_priority: i32) { + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_NORMAL}; BUILDING.with(|b| *b.borrow_mut() = Some(p.clone())); - if preload { + { let mut d = p.demand.lock().unwrap(); - d.preload_thread = unsafe { GetCurrentThreadId() }; + d.worker_thread = unsafe { GetCurrentThreadId() }; if d.wanted { unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) }; } } complete(p, job()); - if preload { + { // (under the lock: `want` does not raise this thread after it) let mut d = p.demand.lock().unwrap(); - d.preload_thread = 0; - if d.wanted { - unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST) }; - } + d.worker_thread = 0; + // Restore unconditionally: a timed-out waiter can clear `wanted` after this worker was boosted. + unsafe { SetThreadPriority(GetCurrentThread(), base_priority) }; } BUILDING.with(|b| *b.borrow_mut() = None); } @@ -94,9 +99,9 @@ impl Pending { use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_PRIORITY_NORMAL, THREAD_SET_LIMITED_INFORMATION}; let mut d = self.demand.lock().unwrap(); - if !std::mem::replace(&mut d.wanted, true) && d.preload_thread != 0 { + if !std::mem::replace(&mut d.wanted, true) && d.worker_thread != 0 { unsafe { - let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, d.preload_thread); + let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, d.worker_thread); if !h.is_null() { SetThreadPriority(h, THREAD_PRIORITY_NORMAL); CloseHandle(h); @@ -105,6 +110,18 @@ impl Pending { } } + /// Begin an active wait on this pipeline, incrementing `waiters` and setting `wanted`. + /// Call `abandon()` on the returned guard if the wait times out or hits a frame budget so + /// deferred builds do not stay permanently `wanted` and bypass `big_compile_turn`'s commit gate. + fn begin_wait(&self) -> WaitWantGuard<'_> { + { + let mut d = self.demand.lock().unwrap(); + d.waiters += 1; + } + self.want(); + WaitWantGuard { pending: self, abandoned: false } + } + fn note_use(&self) { if self.key != 0 && !self.used.swap(true, Ordering::Relaxed) { used::note(self.key); @@ -112,6 +129,27 @@ impl Pending { } } +struct WaitWantGuard<'a> { + pending: &'a Pending, + abandoned: bool, +} + +impl WaitWantGuard<'_> { + fn abandon(mut self) { + self.abandoned = true; + } +} + +impl Drop for WaitWantGuard<'_> { + fn drop(&mut self) { + let mut d = self.pending.demand.lock().unwrap(); + d.waiters = d.waiters.saturating_sub(1); + if self.abandoned && d.waiters == 0 { + d.wanted = false; + } + } +} + /// stand-in handed to the title → its real pipeline static PENDING: Mutex>>> = Mutex::new(None); @@ -171,32 +209,74 @@ pub fn enabled() -> bool { /// Builds the real pipeline: its raw pointer, 0 = failed. pub type Job = Box usize + Send>; -fn queue() -> &'static Mutex>> { - static Q: OnceLock>>> = OnceLock::new(); - Q.get_or_init(|| { - let (tx, rx) = mpsc::channel::>(); - let rx = Arc::new(Mutex::new(rx)); +struct WorkerQueue { + /// Pipelines actively awaited by a title thread (`resolve_wait`), popped before background work. + urgent: VecDeque>, + /// Background pipelines (creation-time or graphics first-bind). + normal: VecDeque>, +} + +struct Workers { + q: Mutex, + cv: Condvar, +} + +fn workers() -> &'static Workers { + static W: OnceLock = OnceLock::new(); + static STARTED: std::sync::Once = std::sync::Once::new(); + let w = W.get_or_init(|| Workers { + q: Mutex::new(WorkerQueue { urgent: VecDeque::new(), normal: VecDeque::new() }), + cv: Condvar::new(), + }); + STARTED.call_once(|| { // translation recurses deeply on big programs; DXC itself runs on its own pool - let n = crate::gpu::recomp::dxc::compile_threads(); + let n = crate::gpu::recomp::dxc::compile_threads().max(2); for k in 0..n { - 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) = next else { return }; - // (released by the title meanwhile) - if p.orphan.load(Ordering::Acquire) { - let _ = p.job.lock().unwrap().take(); - continue; - } - // (None: a bind took it and builds it itself) - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - build(&p, job, false); + let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL}; + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL) }; + loop { + let p = { + let mut g = w.q.lock().unwrap(); + loop { + if let Some(p) = g.urgent.pop_front().or_else(|| g.normal.pop_front()) { + break p; + } + g = w.cv.wait(g).unwrap(); + } + }; + // (released by the title meanwhile) + if p.orphan.load(Ordering::Acquire) { + let _ = p.job.lock().unwrap().take(); + let mut done = p.done.lock().unwrap(); + *done = true; + p.cv.notify_all(); + continue; + } + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + build(&p, job, THREAD_PRIORITY_BELOW_NORMAL); + } } }); } - Mutex::new(tx) - }) + }); + w +} + +fn enqueue(p: &Arc, urgent: bool) { + if urgent { + p.sent.store(true, Ordering::Release); + if !p.urgent_queued.swap(true, Ordering::AcqRel) { + let w = workers(); + w.q.lock().unwrap().urgent.push_back(p.clone()); + w.cv.notify_one(); + } + } else if !p.sent.swap(true, Ordering::AcqRel) { + let w = workers(); + w.q.lock().unwrap().normal.push_back(p.clone()); + w.cv.notify_one(); + } } /// Release a pipeline state XCL owns (raw pointer, 0 = none). @@ -230,7 +310,8 @@ pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) { fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { let p = Arc::new(Pending { job: Mutex::new(Some(job)), - sent: std::sync::atomic::AtomicBool::new(send), + sent: AtomicBool::new(false), + urgent_queued: AtomicBool::new(false), real: AtomicUsize::new(0), done: Mutex::new(false), cv: Condvar::new(), @@ -248,11 +329,16 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); }); if send { - let _ = queue().lock().unwrap().send(p); + enqueue(&p, false); } else if used::known(key) { if let Some(q) = preload() { - q.list.lock().unwrap().push_back(p); - q.cv.notify_one(); + if q.claim(key, compute) { + PREWARM_QUEUED.fetch_add(1, Ordering::Relaxed); + q.list.lock().unwrap().push_back(p); + q.cv.notify_one(); + } else { + PREWARM_DEDUPED.fetch_add(1, Ordering::Relaxed); + } } } } @@ -337,24 +423,71 @@ mod used { } } -/// The workers that build the pipelines of an earlier run ahead of their first use -/// (`XCL_PSO_PRELOAD=0`: off). Apart from the ones a bind sends to (`queue`) and at the lowest -/// priority: a pipeline that is bound is not held up by the ones made ahead (whoever takes -/// `job` first builds it), and the title's own threads are not either. +/// The workers that prewarm only the pipelines an earlier run actually executed +/// (`XCL_PSO_PREWARM_USED=1|0`, falling back to `XCL_PSO_PRELOAD=0` off). Deduplicated by +/// `(shader_key, compute)` so thousands of state-variant PSOs sharing the same shader set do not +/// flood the preload queue during loading. struct Preload { - list: Mutex>>, + list: Mutex>>, + claimed: Mutex>, cv: Condvar, } +impl Preload { + /// Claim `(key, compute)` for startup prewarm; returns `false` if another state variant of the + /// same shader set has already been queued for prewarming in this run. + fn claim(&self, key: u64, compute: bool) -> bool { + key != 0 && self.claimed.lock().unwrap().insert((key, compute)) + } +} + +static PREWARM_QUEUED: AtomicUsize = AtomicUsize::new(0); +static PREWARM_BUILT: AtomicUsize = AtomicUsize::new(0); +static PREWARM_DEDUPED: AtomicUsize = AtomicUsize::new(0); + +/// `(queued, built, deduplicated_variants)` for used-only startup prewarm. +pub fn prewarm_stats() -> (usize, usize, usize) { + ( + PREWARM_QUEUED.load(Ordering::Relaxed), + PREWARM_BUILT.load(Ordering::Relaxed), + PREWARM_DEDUPED.load(Ordering::Relaxed), + ) +} + +fn parse_prewarm_used(prewarm_env: Option<&str>, preload_env: Option<&str>) -> bool { + if let Some(v) = prewarm_env { + match v.trim().to_ascii_lowercase().as_str() { + "0" | "false" | "off" | "no" => return false, + "1" | "true" | "on" | "yes" => return true, + _ => {} + } + } + preload_env.map_or(true, |v| v.trim() != "0") +} + +/// Whether used-only startup prewarming is enabled (`XCL_PSO_PREWARM_USED` / `XCL_PSO_PRELOAD`). +pub fn prewarm_used_enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + let prewarm = std::env::var("XCL_PSO_PREWARM_USED").ok(); + let preload = std::env::var("XCL_PSO_PRELOAD").ok(); + parse_prewarm_used(prewarm.as_deref(), preload.as_deref()) + }) +} + fn preload() -> Option<&'static Preload> { static Q: OnceLock> = OnceLock::new(); static STARTED: std::sync::Once = std::sync::Once::new(); let q = Q .get_or_init(|| { - if std::env::var("XCL_PSO_PRELOAD").is_ok_and(|v| v.trim() == "0") { + if !prewarm_used_enabled() { return None; } - Some(Preload { list: Mutex::new(Default::default()), cv: Condvar::new() }) + Some(Preload { + list: Mutex::new(Default::default()), + claimed: Mutex::new(Default::default()), + cv: Condvar::new(), + }) }) .as_ref()?; STARTED.call_once(|| { @@ -365,7 +498,6 @@ fn preload() -> Option<&'static Preload> { use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); } - static DONE: AtomicUsize = AtomicUsize::new(0); loop { let p = { let mut g = q.list.lock().unwrap(); @@ -378,15 +510,18 @@ fn preload() -> Option<&'static Preload> { }; // (released by the title meanwhile) if p.orphan.load(Ordering::Acquire) { + let mut done = p.done.lock().unwrap(); + *done = true; + p.cv.notify_all(); continue; } - // (None: a bind took it and builds it itself) + // (None: another worker already took it) let job = p.job.lock().unwrap().take(); if let Some(job) = job { - build(&p, job, true); - let n = DONE.fetch_add(1, Ordering::Relaxed) + 1; + build(&p, job, windows_sys::Win32::System::Threading::THREAD_PRIORITY_LOWEST); + let n = PREWARM_BUILT.fetch_add(1, Ordering::Relaxed) + 1; if n.is_power_of_two() { - crate::xlog_info!("D3D12.X: {n} pipelines built ahead of their first use"); + crate::xlog_info!("D3D12.X: {n} used-only pipelines prewarmed ahead of their first use"); } } } @@ -399,6 +534,7 @@ fn preload() -> Option<&'static Preload> { #[cfg(test)] mod used_tests { use super::*; + use std::sync::mpsc; /// While a bind waits for a pipeline still being built, the title is held (`title_held`): /// `kernelx::Sleep` does not count that time. @@ -579,7 +715,7 @@ mod used_tests { } } - let n = crate::gpu::recomp::dxc::compile_threads(); + let n = crate::gpu::recomp::dxc::compile_threads().max(2); let (started_tx, started_rx) = mpsc::channel(); let gate = Arc::new((Mutex::new(false), Condvar::new())); let mut blockers = Vec::with_capacity(n); @@ -631,12 +767,438 @@ mod used_tests { let _ = released(standin); } } + + #[test] + fn resolve_wait_never_runs_job_on_calling_thread() { + let standin = 0x7E57_B101usize; + let caller_tid = std::thread::current().id(); + let (tx, rx) = mpsc::channel(); + submit_lazy( + standin, + true, + Box::new(move || { + tx.send((std::thread::current().id(), std::thread::current().name().unwrap_or("").to_string())).unwrap(); + 0x6161 + }), + 0, + ); + assert_eq!(resolve_wait_for(standin, None), 0x6161); + let (worker_tid, worker_name) = rx.recv().unwrap(); + assert_ne!(worker_tid, caller_tid, "PSO build must run on a worker thread, not the calling title thread"); + assert!(worker_name.starts_with("xcl-pso-"), "expected xcl-pso worker thread, got {worker_name:?}"); + let _ = released(standin); + } + + #[test] + fn shared_frame_wait_budget_caps_concurrent_threads_and_resets_on_frame_end() { + let budget = Arc::new(FrameWaitBudget::new()); + let frame_limit = Some(Duration::from_millis(80)); + let (release_tx, release_rx) = mpsc::channel::<()>(); + let release_rx = Arc::new(Mutex::new(release_rx)); + let standins: Vec = (0..4usize).map(|i| 0x7E57_B200 + i).collect(); + for &s in &standins { + let rx = release_rx.clone(); + submit( + s, + true, + Box::new(move || { + // Stay blocked until test finishes waiting; return 0 so orphan cleanup does not + // COM-Release a synthetic pointer. + let _ = rx.lock().unwrap().recv_timeout(Duration::from_secs(2)); + 0 + }), + ); + } + + // Four threads enter simultaneously sharing ONE 80 ms frame budget: all four must bail well + // under 4 * 80 ms without marking pipelines permanently `late`. + let barrier = Arc::new(std::sync::Barrier::new(4)); + let t0 = Instant::now(); + let mut handles = Vec::new(); + for &s in &standins { + let b = barrier.clone(); + let fb = budget.clone(); + handles.push(std::thread::spawn(move || { + b.wait(); + resolve_wait_with_budgets(s, None, frame_limit, &fb) + })); + } + for (h, &s) in handles.into_iter().zip(&standins) { + assert_eq!(h.join().unwrap(), s, "must return stand-in once shared frame budget expires"); + let p = entry(s).unwrap(); + assert!(!p.late.load(Ordering::Acquire), "frame-budget skip must not permanently mark pipeline late"); + } + assert!(t0.elapsed() < Duration::from_millis(300), "shared budget stalled too long: {:?}", t0.elapsed()); + assert!(budget.exhausted_skips() >= 1); + + // Next call in the same frame returns immediately (budget already spent). + let t1 = Instant::now(); + assert_eq!(resolve_wait_with_budgets(standins[0], None, frame_limit, &budget), standins[0]); + assert!(t1.elapsed() < Duration::from_millis(20), "exhausted frame budget must skip immediately ({:?})", t1.elapsed()); + + // Frame boundary resets the shared budget cleanly. + budget.advance_frame(); + assert_eq!(budget.remaining(Duration::from_millis(80)).1, Duration::from_millis(80)); + + drop(release_tx); + for s in standins { + let _ = released(s); + } + } + + #[test] + fn frame_wait_budget_env_parsing() { + assert_eq!(parse_frame_wait_budget(Some("0"), Some(Duration::from_millis(500)), true), FrameBudgetPolicy::Disabled); + assert_eq!(parse_frame_wait_budget(Some("off"), Some(Duration::from_millis(500)), true), FrameBudgetPolicy::Disabled); + assert_eq!(parse_frame_wait_budget(Some("250"), None, true), FrameBudgetPolicy::Always(Duration::from_millis(250))); + assert_eq!(parse_frame_wait_budget(None, Some(Duration::from_millis(400)), true), FrameBudgetPolicy::Always(Duration::from_millis(400))); + assert_eq!(parse_frame_wait_budget(None, None, false), FrameBudgetPolicy::AfterFirstPresent(Duration::from_millis(500))); + assert_eq!(parse_frame_wait_budget(None, None, true), FrameBudgetPolicy::Disabled); + } + + #[test] + fn prewarm_used_env_parsing() { + assert!(parse_prewarm_used(Some("1"), Some("0"))); + assert!(!parse_prewarm_used(Some("0"), Some("1"))); + assert!(!parse_prewarm_used(Some("off"), None)); + assert!(parse_prewarm_used(None, None)); + assert!(!parse_prewarm_used(None, Some("0"))); + } + + #[test] + fn lazy_on_draw_defers_build_past_bind_until_first_draw_or_dispatch() { + let compute_standin = 0x7E57_B301usize; + let gfx_standin = 0x7E57_B302usize; + let compute_key = 0x5EED_B301u64; + let gfx_key = 0x5EED_B302u64; + let ran_compute = Arc::new(AtomicBool::new(false)); + let ran_gfx = Arc::new(AtomicBool::new(false)); + let rc = ran_compute.clone(); + let rg = ran_gfx.clone(); + + submit_lazy( + compute_standin, + true, + Box::new(move || { + rc.store(true, Ordering::SeqCst); + 0x6301 + }), + compute_key, + ); + submit_lazy( + gfx_standin, + false, + Box::new(move || { + rg.store(true, Ordering::SeqCst); + 0x6302 + }), + gfx_key, + ); + + // Bind-only calls (`SetPipelineState` / `Reset` / `ClearState`) must NOT compile or record + // usage when `lazy_on_draw` is active. + assert!(lazy_on_draw()); + assert_eq!(resolve_for_bind(compute_standin), compute_standin); + assert_eq!(resolve_for_bind(gfx_standin), gfx_standin); + std::thread::sleep(Duration::from_millis(20)); + assert!(!ran_compute.load(Ordering::SeqCst), "compute PSO must stay deferred until first dispatch"); + assert!(!ran_gfx.load(Ordering::SeqCst), "graphics PSO must stay deferred until first draw"); + assert!(!used::noted(compute_key) && !used::noted(gfx_key), "bind-only PSOs must not pollute used-pipelines ledger"); + + // First draw/dispatch (`resolve_wait`) compiles on a worker and records used keys. + assert_eq!(resolve_wait_for(compute_standin, None), 0x6301); + assert_eq!(resolve_wait_for(gfx_standin, None), 0x6302); + assert!(ran_compute.load(Ordering::SeqCst) && ran_gfx.load(Ordering::SeqCst)); + assert!(used::noted(compute_key) && used::noted(gfx_key)); + + // Once built, `resolve_for_bind` returns the real PSO immediately. + assert_eq!(resolve_for_bind(compute_standin), 0x6301); + assert_eq!(resolve_for_bind(gfx_standin), 0x6302); + + let _ = released(compute_standin); + let _ = released(gfx_standin); + } + + #[test] + fn switching_bound_pipelines_preserves_lazy_deferral() { + let list = 0x7E57_B501usize; + let pso_a = 0x7E57_B502usize; + let pso_b = 0x7E57_B503usize; + let key_a = 0x5EED_B502u64; + let key_b = 0x5EED_B503u64; + assert!(lazy_on_draw()); + submit_lazy(pso_a, false, Box::new(|| 0x6502), key_a); + submit_lazy(pso_b, false, Box::new(|| 0x6503), key_b); + + // Bind A then immediately switch to B without drawing: bookkeeping for the outgoing + // binding A must remain passive (neither queued nor recorded in the used ledger). + assert_eq!(resolve_for_bind(pso_a), pso_a); + unsafe { super::super::list_x::on_set_pipeline_state(list as *mut _, pso_a) }; + assert_eq!(resolve_for_bind(pso_b), pso_b); + unsafe { super::super::list_x::on_set_pipeline_state(list as *mut _, pso_b) }; + + let queued_a = entry(pso_a).unwrap().sent.load(Ordering::Acquire); + let queued_b = entry(pso_b).unwrap().sent.load(Ordering::Acquire); + let used_a = used::noted(key_a); + let used_b = used::noted(key_b); + + // First real draw/dispatch demand must still build both cleanly on workers. + let real_a = resolve_wait_for(pso_a, None); + let real_b = resolve_wait_for(pso_b, None); + assert_eq!(resolve_if_ready(pso_a), real_a); + assert_eq!(resolve_if_ready(pso_b), real_b); + + super::super::list_x::on_release(list); + let _ = released(pso_a); + let _ = released(pso_b); + + assert_eq!((real_a, real_b), (0x6502, 0x6503)); + assert_eq!((queued_a, queued_b), (false, false), "switching bound PSOs must not queue unused lazy pipelines"); + assert_eq!((used_a, used_b), (false, false), "switching bound PSOs must not pollute the used-pipelines ledger"); + } + + #[test] + fn releasing_orphaned_pending_pso_unblocks_unbounded_waiter() { + let standin = 0x7E57_B510usize; + let gate = Arc::new((Mutex::new(false), Condvar::new())); + let g_job = gate.clone(); + submit_lazy( + standin, + false, + Box::new(move || { + let (m, cv) = &*g_job; + let mut open = m.lock().unwrap(); + while !*open { + open = cv.wait(open).unwrap(); + } + 0 + }), + 0, + ); + let waiter = std::thread::spawn(move || resolve_wait_for(standin, None)); + std::thread::sleep(Duration::from_millis(15)); + assert_eq!(released(standin), 0); + // Waiter must unblock promptly even while the worker job is still gated. + let res = waiter.join().expect("waiter thread must not panic"); + assert_eq!(res, standin); + // Release the worker job so the test leaves no blocked background thread behind. + *gate.0.lock().unwrap() = true; + gate.1.notify_all(); + } + + #[test] + fn an_abandoned_wait_restores_worker_priority_before_its_next_job() { + use windows_sys::Win32::System::Threading::{ + GetCurrentThread, GetThreadPriority, SetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL, + THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_NORMAL, + }; + for (i, base) in [THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_LOWEST].into_iter().enumerate() { + let standin = 0x7E57_B530usize + 2 * i; + let (started, building) = mpsc::channel(); + let (go, finish) = mpsc::channel::<()>(); + submit_lazy( + standin, + false, + Box::new(move || { + started.send(unsafe { GetThreadPriority(GetCurrentThread()) }).unwrap(); + let _ = finish.recv_timeout(Duration::from_secs(10)); + 0 + }), + 0, + ); + submit_lazy(standin + 1, false, Box::new(|| 0), 0); + let p = entry(standin).unwrap(); + let q = entry(standin + 1).unwrap(); + let job = p.job.lock().unwrap().take().unwrap(); + let _ = q.job.lock().unwrap().take(); + let guard = p.begin_wait(); + let worker_p = p.clone(); + let worker = std::thread::spawn(move || unsafe { + assert_ne!(SetThreadPriority(GetCurrentThread(), base), 0); + let initial = GetThreadPriority(GetCurrentThread()); + build(&worker_p, job, base); + let after = GetThreadPriority(GetCurrentThread()); + let (tx, rx) = mpsc::channel(); + build( + &q, + Box::new(move || { + tx.send(GetThreadPriority(GetCurrentThread())).unwrap(); + 0 + }), + base, + ); + (initial, after, rx.recv().unwrap()) + }); + let during = building.recv_timeout(Duration::from_secs(10)).expect("boosted build started"); + guard.abandon(); + let abandoned = !p.demand.lock().unwrap().wanted; + let _ = go.send(()); + let (initial, after, next) = worker.join().unwrap(); + let _ = released(standin); + let _ = released(standin + 1); + assert_eq!(initial, base); + assert_eq!(during, THREAD_PRIORITY_NORMAL); + assert!(abandoned); + assert_eq!(after, base, "worker must restore base priority after abandoned wait"); + assert_eq!(next, base, "subsequent unwanted job must run at base priority"); + } + } + + #[test] + fn a_timed_out_waiter_does_not_cancel_an_unbounded_waiters_demand() { + let standin = 0x7E57_B540usize; + let (started, building) = mpsc::channel(); + let (go, finish) = mpsc::channel::<()>(); + submit_lazy( + standin, + false, + Box::new(move || { + started.send(wanted_here()).unwrap(); + let _ = finish.recv_timeout(Duration::from_secs(10)); + 0 + }), + 0, + ); + let bind = std::thread::spawn(move || resolve_wait_with_budgets(standin, None, None, &FrameWaitBudget::new())); + let wanted = building.recv_timeout(Duration::from_secs(10)).expect("worker started"); + let start = Instant::now(); + while !wanted() && start.elapsed() < Duration::from_secs(5) { + std::thread::yield_now(); + } + let initial = wanted(); + let timed = resolve_wait_with_budgets(standin, None, Some(Duration::from_millis(1)), &FrameWaitBudget::new()); + let pending = entry(standin).unwrap(); + let still_waiting = !bind.is_finished(); + let wanted_after_timeout = wanted(); + let waiters = pending.demand.lock().unwrap().waiters; + let _ = go.send(()); + let resolved = bind.join().unwrap(); + let _ = released(standin); + assert!(initial && still_waiting, "unbounded waiter must still be active during bounded timeout"); + assert_eq!((timed, resolved), (standin, standin)); + assert!(wanted_after_timeout, "unbounded waiter must keep wanted=true after bounded timeout"); + assert_eq!(waiters, 1); + assert_eq!(pending.demand.lock().unwrap().waiters, 0); + } + + #[test] + fn default_frame_budget_only_defers_graphics_and_never_leaves_skipped_psos_wanted() { + let cap = Duration::from_millis(500); + // Implicit default (`AfterFirstPresent`) defers graphics only, never compute dispatches. + assert_eq!(active_frame_budget_for(FrameBudgetPolicy::AfterFirstPresent(cap), false, 0), None); + assert_eq!(active_frame_budget_for(FrameBudgetPolicy::AfterFirstPresent(cap), false, 1), Some(cap)); + assert_eq!(active_frame_budget_for(FrameBudgetPolicy::AfterFirstPresent(cap), true, 1), None); + // Explicit `XCL_PSO_FRAME_WAIT_MS` (`Always`) applies to both graphics and compute. + assert_eq!(active_frame_budget_for(FrameBudgetPolicy::Always(cap), true, 0), Some(cap)); + assert_eq!(active_frame_budget_for(FrameBudgetPolicy::Always(cap), false, 0), Some(cap)); + + // Exhausted frame budget must defer without marking the skipped PSO as `wanted`, and a + // budget timeout must clear `wanted` once the waiter abandons the build. + let budget = FrameWaitBudget::new(); + let (ep, _) = budget.remaining(Duration::from_millis(20)); + budget.charge(ep, Duration::from_millis(25)); + + let gate = Arc::new((Mutex::new(false), Condvar::new())); + let standin_a = 0x7E57_B520usize; + let standin_b = 0x7E57_B521usize; + for s in [standin_a, standin_b] { + let g = gate.clone(); + submit_lazy( + s, + false, + Box::new(move || { + let (m, cv) = &*g; + let mut open = m.lock().unwrap(); + while !*open { + open = cv.wait(open).unwrap(); + } + 0 + }), + 0, + ); + } + // Frame budget already exhausted -> immediate skip, `wanted` stays false. + assert_eq!(resolve_wait_with_budgets(standin_a, None, Some(Duration::from_millis(20)), &budget), standin_a); + assert!(!entry(standin_a).unwrap().demand.lock().unwrap().wanted, "exhausted-budget skip must not set wanted"); + + // Fresh frame with short 25 ms budget -> waits briefly then times out and clears `wanted`. + budget.advance_frame(); + assert_eq!(resolve_wait_with_budgets(standin_b, None, Some(Duration::from_millis(25)), &budget), standin_b); + assert!(!entry(standin_b).unwrap().demand.lock().unwrap().wanted, "abandoned frame-budget wait must clear wanted"); + + *gate.0.lock().unwrap() = true; + gate.1.notify_all(); + let _ = released(standin_a); + let _ = released(standin_b); + } + + #[test] + fn prewarm_used_deduplicates_duplicate_shader_keys() { + let shared_key = 0x5EED_B400u64; + let unused_key = 0x5EED_B401u64; + used::earlier_run_used(shared_key); + + let before = prewarm_stats(); + let ran = Arc::new(AtomicUsize::new(0)); + let standins: Vec = (0..4usize).map(|i| 0x7E57_B400 + i).collect(); + for &s in &standins { + let r = ran.clone(); + submit_lazy( + s, + false, + Box::new(move || { + r.fetch_add(1, Ordering::SeqCst); + 0x6400 + (s & 0xF) + }), + shared_key, + ); + } + let unused_standin = 0x7E57_B410usize; + let unused_ran = Arc::new(AtomicBool::new(false)); + let ur = unused_ran.clone(); + submit_lazy( + unused_standin, + false, + Box::new(move || { + ur.store(true, Ordering::SeqCst); + 0x6410 + }), + unused_key, + ); + + let start = Instant::now(); + while is_pending(standins[0]) && start.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(5)); + } + std::thread::sleep(Duration::from_millis(25)); + assert!(!is_pending(standins[0]), "first variant of used key must prewarm"); + assert_eq!(ran.load(Ordering::SeqCst), 1, "duplicate state variants of the same shader key must not flood prewarm"); + assert!(is_pending(standins[1]) && is_pending(standins[2]) && is_pending(standins[3])); + assert!(is_pending(unused_standin) && !unused_ran.load(Ordering::SeqCst), "unused key must never prewarm"); + let after = prewarm_stats(); + assert!(after.0 >= before.0 + 1, "expected >=1 prewarm queued"); + assert!(after.2 >= before.2 + 3, "expected >=3 deduplicated variants"); + + for s in standins { + let _ = released(s); + } + let _ = released(unused_standin); + } } fn entry(pso: usize) -> Option> { PENDING.lock().unwrap().as_ref()?.get(&pso).cloned() } +/// Passive lookup of a pipeline's already-compiled real pointer without enqueueing a lazy build +/// or recording usage (for bind-time bookkeeping such as `list_x::on_set_pipeline_state`). +pub(super) fn resolve_if_ready(pso: usize) -> usize { + entry(pso).map_or(pso, |p| match p.real.load(Ordering::Acquire) { + 0 => pso, + r => r, + }) +} + /// The pipeline to use for `pso` now: the real one once built, else `pso` itself. pub fn resolve(pso: usize) -> usize { let Some(p) = entry(pso) else { return pso }; @@ -644,23 +1206,156 @@ pub fn resolve(pso: usize) -> usize { match p.real.load(Ordering::Acquire) { 0 => { // a lazy one is wanted now: to the workers - if !p.sent.swap(true, Ordering::AcqRel) { - let _ = queue().lock().unwrap().send(p); - } + enqueue(&p, false); pso } r => r, } } -/// `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). +/// Shared per-frame PSO wait budget across all title threads so N concurrent threads cannot each +/// burn the full timeout in the same frame. Reset on every frame boundary (`on_frame_end` / +/// `present::counters().1`). +struct FrameWaitBudget { + epoch: AtomicU64, + spent_us: AtomicU64, + last_boundaries: AtomicU64, + exhausted_skips: AtomicU64, +} + +impl FrameWaitBudget { + const fn new() -> Self { + Self { + epoch: AtomicU64::new(0), + spent_us: AtomicU64::new(0), + last_boundaries: AtomicU64::new(0), + exhausted_skips: AtomicU64::new(0), + } + } + + fn advance_frame(&self) { + self.epoch.fetch_add(1, Ordering::AcqRel); + self.spent_us.store(0, Ordering::Release); + } + + fn sync_present_boundary(&self, boundaries: u64) { + let prev = self.last_boundaries.load(Ordering::Acquire); + if boundaries > prev + && self + .last_boundaries + .compare_exchange(prev, boundaries, Ordering::AcqRel, Ordering::Relaxed) + .is_ok() + { + self.advance_frame(); + } + } + + fn remaining(&self, limit: Duration) -> (u64, Duration) { + let ep = self.epoch.load(Ordering::Acquire); + let spent = self.spent_us.load(Ordering::Acquire); + let cap = (limit.as_micros()).min(u64::MAX as u128) as u64; + (ep, Duration::from_micros(cap.saturating_sub(spent))) + } + + fn charge(&self, ep: u64, elapsed: Duration) { + if self.epoch.load(Ordering::Acquire) == ep { + let us = (elapsed.as_micros()).min(u64::MAX as u128) as u64; + self.spent_us.fetch_add(us, Ordering::AcqRel); + } + } + + fn note_skip(&self) -> u64 { + self.exhausted_skips.fetch_add(1, Ordering::Relaxed) + 1 + } + + #[cfg(test)] + fn exhausted_skips(&self) -> u64 { + self.exhausted_skips.load(Ordering::Relaxed) + } +} + +static FRAME_BUDGET: FrameWaitBudget = FrameWaitBudget::new(); + +/// Called at each frame boundary (`frame::mark_flipped`) to reset the shared per-frame PSO wait +/// budget across all threads. +pub fn on_frame_end() { + FRAME_BUDGET.advance_frame(); +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum FrameBudgetPolicy { + Disabled, + Always(Duration), + AfterFirstPresent(Duration), +} + +fn parse_frame_wait_budget(frame_env: Option<&str>, per_pso: Option, is_test: bool) -> FrameBudgetPolicy { + if let Some(raw) = frame_env { + let s = raw.trim().to_ascii_lowercase(); + if matches!(s.as_str(), "0" | "off" | "none" | "false") { + return FrameBudgetPolicy::Disabled; + } + if let Ok(ms) = s.parse::() { + return if ms == 0 { FrameBudgetPolicy::Disabled } else { FrameBudgetPolicy::Always(Duration::from_millis(ms)) }; + } + } + if let Some(d) = per_pso { + return FrameBudgetPolicy::Always(d); + } + if is_test { + FrameBudgetPolicy::Disabled + } else { + FrameBudgetPolicy::AfterFirstPresent(Duration::from_millis(500)) + } +} + +fn active_frame_budget_for(policy: FrameBudgetPolicy, compute: bool, boundaries: u64) -> Option { + match policy { + FrameBudgetPolicy::Disabled => None, + FrameBudgetPolicy::Always(d) => Some(d), + // The implicit default frame-wait cap defers cold graphics pipelines so presentation + // stays responsive, without skipping compute dispatches that write GPU sync/indirect data. + // An explicit `XCL_PSO_FRAME_WAIT_MS` (`Always`) still bounds both graphics and compute. + FrameBudgetPolicy::AfterFirstPresent(d) => (!compute && boundaries > 0).then_some(d), + } +} + +fn active_frame_budget(compute: bool) -> Option { + static POLICY: OnceLock = OnceLock::new(); + let policy = *POLICY.get_or_init(|| { + let env = std::env::var("XCL_PSO_FRAME_WAIT_MS").ok(); + parse_frame_wait_budget(env.as_deref(), wait_budget(), cfg!(test)) + }); + let boundaries = super::present::counters().1; + FRAME_BUDGET.sync_present_boundary(boundaries); + active_frame_budget_for(policy, compute, boundaries) +} + +fn allow_title_thread_build() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PSO_TITLE_BUILD").is_ok_and(|v| v.trim() == "1")) +} + +/// `resolve`, waiting for a pipeline still being built on the background worker pool (never built +/// on the title's own thread by default), bounded by `XCL_PSO_WAIT_MS` and the shared per-frame +/// `XCL_PSO_FRAME_WAIT_MS` budget. pub fn resolve_wait(pso: usize) -> usize { - resolve_wait_for(pso, wait_budget()) + let compute = entry(pso).is_some_and(|p| p.compute); + resolve_wait_with_budgets(pso, wait_budget(), active_frame_budget(compute), &FRAME_BUDGET) } -/// `resolve_wait`, waiting at most `budget` (None: until the pipeline is built). -fn resolve_wait_for(pso: usize, budget: Option) -> usize { +/// `resolve_wait`, waiting at most `budget` (None: until the pipeline is built on a worker). +#[cfg(test)] +fn resolve_wait_for(pso: usize, budget: Option) -> usize { + resolve_wait_with_budgets(pso, budget, None, &FRAME_BUDGET) +} + +fn resolve_wait_with_budgets( + pso: usize, + per_pso_budget: Option, + frame_budget: Option, + frame_tracker: &FrameWaitBudget, +) -> usize { let Some(p) = entry(pso) else { return pso }; p.note_use(); if p.spared.load(Ordering::Acquire) { @@ -668,14 +1363,18 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { } // (the title's thread is held from here until the pipeline is built or the budget is over) let _held = (!*p.done.lock().unwrap()).then(Held::new); - if let Some(budget) = budget { - return resolve_within(&p, pso, budget); + if per_pso_budget.is_some() || frame_budget.is_some() { + return resolve_within(&p, pso, per_pso_budget, frame_budget, frame_tracker); } - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - complete(&p, job()); + if allow_title_thread_build() { + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + complete(&p, job()); + } + } else { + enqueue(&p, true); } - p.want(); + let _want_guard = p.begin_wait(); let mut done = p.done.lock().unwrap(); while !*done { done = p.cv.wait(done).unwrap(); @@ -686,19 +1385,25 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { } } -/// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; unset or 0: until -/// it is built). A retail game builds compute programs on its own threads: the driver takes up to -/// 30 s for the biggest translated ones, and the title's watchdog ends it when its main thread -/// has been held 30 s. -fn wait_budget() -> Option { - static B: OnceLock> = OnceLock::new(); - *B.get_or_init(|| std::env::var("XCL_PSO_WAIT_MS").ok().and_then(|v| v.trim().parse::().ok()).filter(|&ms| ms > 0).map(std::time::Duration::from_millis)) +/// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; unset or 0: no +/// per-pipeline cap, though `XCL_PSO_FRAME_WAIT_MS` still bounds total wait per frame). +fn wait_budget() -> Option { + static B: OnceLock> = OnceLock::new(); + *B.get_or_init(|| std::env::var("XCL_PSO_WAIT_MS").ok().and_then(|v| v.trim().parse::().ok()).filter(|&ms| ms > 0).map(Duration::from_millis)) } -/// `resolve_wait` for at most `budget`: the build goes to the workers (not this thread), and a -/// pipeline not built by then is `late` – it and later binds of it get the stand-in (their -/// dispatches are skipped) until a worker has built it. -fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> usize { +/// `resolve_wait` bounded by an optional per-pipeline timeout and an optional shared per-frame +/// budget across all threads: the build always runs on background workers (urgent queue). +/// A per-pipeline timeout marks `p.late` so repeated binds skip immediately; a shared frame-budget +/// skip leaves `p.late` clear so the next frame can use or await the pipeline normally. +fn resolve_within( + p: &Arc, + pso: usize, + per_pso_budget: Option, + frame_budget: Option, + frame_tracker: &FrameWaitBudget, +) -> usize { + const SLICE: Duration = Duration::from_millis(20); let built = |p: &Pending| match p.real.load(Ordering::Acquire) { 0 => pso, r => r, @@ -706,25 +1411,69 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> if *p.done.lock().unwrap() { return built(p); } - if !p.sent.swap(true, Ordering::AcqRel) { - let _ = queue().lock().unwrap().send(p.clone()); - } + enqueue(p, true); if p.late.load(Ordering::Acquire) { return pso; } - p.want(); - let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), budget, |d| !*d).unwrap(); - if *done { - return built(p); + // If the shared frame budget is already exhausted, defer immediately without marking `p` as + // `wanted` so skipped cold pipelines do not bypass `big_compile_turn`'s commit/slot gate. + if frame_budget.is_some_and(|cap| frame_tracker.remaining(cap).1.is_zero()) { + let n = frame_tracker.note_skip(); + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: shared per-frame PSO wait budget ({} ms) exhausted: deferring bind to next frame ({n} skips so far)", + frame_budget.unwrap_or_default().as_millis() + ); + } + return pso; } - drop(done); - p.late.store(true, Ordering::Release); - static N: AtomicUsize = AtomicUsize::new(0); - let n = N.fetch_add(1, Ordering::Relaxed); - if n < 16 || n.is_power_of_two() { - crate::xlog_warn!("D3D12.X: a pipeline still being built after {} ms: its binds go on without it until it is built ({} so far)", budget.as_millis(), n + 1); + let want_guard = p.begin_wait(); + let per_pso_deadline = per_pso_budget.map(|b| Instant::now() + b); + let mut done = p.done.lock().unwrap(); + while !*done { + let per_pso_rem = per_pso_deadline.map(|d| d.saturating_duration_since(Instant::now())); + if per_pso_rem.is_some_and(|r| r.is_zero()) { + drop(done); + want_guard.abandon(); + p.late.store(true, Ordering::Release); + static N: AtomicUsize = AtomicUsize::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 16 || n.is_power_of_two() { + crate::xlog_warn!( + "D3D12.X: a pipeline still being built after {} ms: its binds go on without it until it is built ({} so far)", + per_pso_budget.unwrap_or_default().as_millis(), + n + 1 + ); + } + return pso; + } + let frame_rem = frame_budget.map(|cap| frame_tracker.remaining(cap)); + if frame_rem.is_some_and(|(_, r)| r.is_zero()) { + drop(done); + want_guard.abandon(); + let n = frame_tracker.note_skip(); + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: shared per-frame PSO wait budget ({} ms) exhausted: deferring bind to next frame ({n} skips so far)", + frame_budget.unwrap_or_default().as_millis() + ); + } + return pso; + } + let step = match (per_pso_rem, frame_rem) { + (Some(a), Some((_, b))) => a.min(b).min(SLICE), + (None, Some((_, b))) => b.min(SLICE), + (Some(a), None) => a, + (None, None) => unreachable!(), + }; + let t0 = Instant::now(); + let (g, _) = p.cv.wait_timeout_while(done, step, |d| !*d).unwrap(); + done = g; + if let Some((ep, _)) = frame_rem { + frame_tracker.charge(ep, t0.elapsed()); + } } - pso + built(p) } /// `XCL_PSO_IMAGE_SKIP=1`: a bind does not wait for a big compute program that writes nothing @@ -754,9 +1503,7 @@ pub fn image_only(standin: usize) { fn resolve_spared(p: &Arc, pso: usize) -> usize { match p.real.load(Ordering::Acquire) { 0 => { - if !p.sent.swap(true, Ordering::AcqRel) { - let _ = queue().lock().unwrap().send(p.clone()); - } + enqueue(p, false); if !*p.done.lock().unwrap() && !p.late.swap(true, Ordering::AcqRel) { static N: AtomicUsize = AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); @@ -770,9 +1517,22 @@ fn resolve_spared(p: &Arc, pso: usize) -> usize { } } -/// For binding: compute pipelines are waited for, graphics ones are not. +/// Defer cold lazy PSO compilation past `SetPipelineState`/`Reset`/`ClearState` until the first +/// actual Draw/Dispatch/ExecuteIndirect (`XCL_LAZY_ON_DRAW=0` restores eager compile-on-bind). +pub fn lazy_on_draw() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| lazy() && std::env::var("XCL_LAZY_ON_DRAW").map_or(true, |v| v.trim() != "0")) +} + +/// For binding (`SetPipelineState`, `Reset`, `ClearState`): when `lazy_on_draw` is active, return +/// the real PSO immediately if already built, or keep the lightweight stand-in until the first +/// actual draw/dispatch (`resolve_wait`) without compiling or polluting `used-pipelines.txt`. pub fn resolve_for_bind(pso: usize) -> usize { match entry(pso) { + Some(p) if lazy_on_draw() => match p.real.load(Ordering::Acquire) { + 0 => pso, + r => r, + }, Some(p) if p.compute => resolve_wait(pso), Some(_) => resolve(pso), None => pso, @@ -784,12 +1544,15 @@ pub fn resolve_for_bind(pso: usize) -> usize { /// the worker's result is then released when it arrives). pub fn released(pso: usize) -> usize { let Some(p) = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)) else { return 0 }; - let done = p.done.lock().unwrap(); + let mut done = p.done.lock().unwrap(); if *done { p.real.swap(0, Ordering::AcqRel) } else { - // the worker stores its result into a Pending nobody will read: mark it orphaned + // the worker stores its result into a Pending nobody will read: mark it orphaned and + // wake any unbounded waiter so releasing a pending PSO can never deadlock. p.orphan.store(true, Ordering::Release); + *done = true; + p.cv.notify_all(); 0 } } diff --git a/crates/xcl/src/hle/d3d12x/pso_library.rs b/crates/xcl/src/hle/d3d12x/pso_library.rs new file mode 100644 index 000000000..725b35073 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/pso_library.rs @@ -0,0 +1,604 @@ +//! Memory-mapped `ID3D12PipelineLibrary` persistence (`XCL_PSO_LIBRARY=0`: off). +//! +//! Backing a driver pipeline library with a read-only Windows file mapping kept open for the +//! lifetime of `ID3D12PipelineLibrary` avoids duplicating hundreds of megabytes to >1 GiB of +//! private heap commit on load, and writing new snapshots through a separate file-backed mapping +//! into a fresh generation file (`gen-NNNNNNNN.plib`) avoids both `Vec` serialize spikes and +//! in-place replacement of an actively mapped file (which fails on Windows or triggers driver +//! device removal). + +use std::ffi::c_void; +use std::os::windows::ffi::OsStrExt; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock, RwLock}; + +use windows::core::{Interface, HSTRING}; +use windows::Win32::Graphics::Direct3D12::*; +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; +use windows_sys::Win32::Storage::FileSystem::{ + CreateFileW, GetFileSizeEx, SetEndOfFile, SetFilePointerEx, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, + FILE_BEGIN, FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_SHARE_DELETE, FILE_SHARE_READ, + FILE_SHARE_WRITE, OPEN_EXISTING, +}; +use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, FILE_MAP_READ, FILE_MAP_WRITE, + MEMORY_MAPPED_VIEW_ADDRESS, PAGE_READONLY, PAGE_READWRITE, +}; + +const D3D12_ERROR_ADAPTER_NOT_FOUND_HR: i32 = 0x887E_0001u32 as i32; +const D3D12_ERROR_DRIVER_VERSION_MISMATCH_HR: i32 = 0x887E_0002u32 as i32; + +/// Whether the on-disk memory-mapped pipeline library is enabled (`XCL_PSO_LIBRARY=0` disables). +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PSO_LIBRARY").map_or(true, |v| v.trim() != "0")) +} + +fn wide_path(path: &Path) -> Vec { + path.as_os_str().encode_wide().chain(std::iter::once(0)).collect() +} + +/// A read-only Windows file mapping kept open (file + section + mapped view) with zero private +/// heap copy. Dropping unmaps the view and closes both handles in reverse order. +pub struct MappedBlob { + path: PathBuf, + file: HANDLE, + mapping: HANDLE, + view: *const u8, + len: usize, +} + +// The view is strictly read-only and backed by immutable OS handles owned uniquely by `MappedBlob`. +unsafe impl Send for MappedBlob {} +unsafe impl Sync for MappedBlob {} + +impl MappedBlob { + /// Open `path` read-only with shared read/write/delete access and map its entire contents. + /// Returns `None` when the file does not exist, is empty, or cannot be mapped. + pub fn open(path: &Path) -> Option { + let wide = wide_path(path); + unsafe { + let file = CreateFileW( + wide.as_ptr(), + FILE_GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + std::ptr::null(), + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + std::ptr::null_mut(), + ); + if file == INVALID_HANDLE_VALUE || file.is_null() { + return None; + } + let mut size = 0i64; + if GetFileSizeEx(file, &mut size) == 0 || size <= 0 { + CloseHandle(file); + return None; + } + let Ok(len) = usize::try_from(size) else { + CloseHandle(file); + return None; + }; + let mapping = CreateFileMappingW(file, std::ptr::null(), PAGE_READONLY, 0, 0, std::ptr::null()); + if mapping.is_null() { + CloseHandle(file); + return None; + } + let view = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0); + if view.Value.is_null() { + CloseHandle(mapping); + CloseHandle(file); + return None; + } + Some(Self { + path: path.to_path_buf(), + file, + mapping, + view: view.Value as *const u8, + len, + }) + } + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn as_ptr(&self) -> *const c_void { + self.view as *const c_void + } + + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + pub fn as_slice(&self) -> &[u8] { + unsafe { std::slice::from_raw_parts(self.view, self.len) } + } +} + +impl Drop for MappedBlob { + fn drop(&mut self) { + unsafe { + if !self.view.is_null() { + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: self.view as *mut c_void }); + } + if !self.mapping.is_null() { + CloseHandle(self.mapping); + } + if !self.file.is_null() && self.file != INVALID_HANDLE_VALUE { + CloseHandle(self.file); + } + } + } +} + +/// A read-write Windows file mapping for serializing a pipeline library directly into file-backed +/// pages without allocating a matching heap `Vec`. +pub struct MappedWriteFile { + path: PathBuf, + file: HANDLE, + mapping: HANDLE, + view: *mut u8, + len: usize, + committed: bool, +} + +impl MappedWriteFile { + /// Create (or truncate) `path` with exact byte length `len` and map it writable. + pub fn create(path: &Path, len: usize) -> Option { + if len == 0 { + return None; + } + let size = i64::try_from(len).ok()?; + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + let wide = wide_path(path); + unsafe { + let file = CreateFileW( + wide.as_ptr(), + FILE_GENERIC_READ | FILE_GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_DELETE, + std::ptr::null(), + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + std::ptr::null_mut(), + ); + if file == INVALID_HANDLE_VALUE || file.is_null() { + return None; + } + let mut new_pos = 0i64; + if SetFilePointerEx(file, size, &mut new_pos, FILE_BEGIN) == 0 || SetEndOfFile(file) == 0 { + CloseHandle(file); + let _ = std::fs::remove_file(path); + return None; + } + let mapping = CreateFileMappingW( + file, + std::ptr::null(), + PAGE_READWRITE, + ((len as u64) >> 32) as u32, + (len as u64 & 0xFFFF_FFFF) as u32, + std::ptr::null(), + ); + if mapping.is_null() { + CloseHandle(file); + let _ = std::fs::remove_file(path); + return None; + } + let view = MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, len); + if view.Value.is_null() { + CloseHandle(mapping); + CloseHandle(file); + let _ = std::fs::remove_file(path); + return None; + } + Some(Self { + path: path.to_path_buf(), + file, + mapping, + view: view.Value as *mut u8, + len, + committed: false, + }) + } + } + + pub fn as_mut_ptr(&mut self) -> *mut c_void { + self.view as *mut c_void + } + + pub fn as_mut_slice(&mut self) -> &mut [u8] { + unsafe { std::slice::from_raw_parts_mut(self.view, self.len) } + } + + /// Unmap and close the file cleanly, keeping the written file on disk. + pub fn finish(mut self) -> PathBuf { + self.committed = true; + self.close_handles(); + self.path.clone() + } + + fn close_handles(&mut self) { + unsafe { + if !self.view.is_null() { + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: self.view as *mut c_void }); + self.view = std::ptr::null_mut(); + } + if !self.mapping.is_null() { + CloseHandle(self.mapping); + self.mapping = std::ptr::null_mut(); + } + if !self.file.is_null() && self.file != INVALID_HANDLE_VALUE { + CloseHandle(self.file); + self.file = INVALID_HANDLE_VALUE; + } + } + } +} + +impl Drop for MappedWriteFile { + fn drop(&mut self) { + self.close_handles(); + if !self.committed { + let _ = std::fs::remove_file(&self.path); + } + } +} + +/// Generational `.plib` directory manager: each save writes a new `gen-NNNNNNNN.plib` through a +/// `.tmp` staging file so any earlier generation kept memory-mapped by `ID3D12PipelineLibrary` is +/// never truncated or replaced while open. +pub struct LibraryStore { + dir: PathBuf, + next_gen: AtomicU64, +} + +impl LibraryStore { + pub fn new(dir: PathBuf) -> Self { + let latest = latest_generation(&dir).map_or(0, |(g, _)| g); + Self { dir, next_gen: AtomicU64::new(latest + 1) } + } + + pub fn for_adapter(adapter_name: &str) -> Self { + let key = format!("{:016x}", crate::gpu::shader::fnv64(adapter_name.as_bytes())); + Self::new(crate::gpu::recomp::dxc::cache_dir().join("pso-library").join(key)) + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + /// Open the newest generation file as a read-only memory mapping and clean up older unmapped + /// generations from previous runs. + pub fn open_latest(&self) -> Option<(u64, MappedBlob)> { + let (gen, path) = latest_generation(&self.dir)?; + let blob = MappedBlob::open(&path)?; + self.next_gen.fetch_max(gen + 1, Ordering::AcqRel); + cleanup_older_generations(&self.dir, gen); + Some((gen, blob)) + } + + /// Write a fresh generation of `len` bytes using a file-backed writable mapping and commit it + /// atomically via rename. Never touches any earlier generation currently kept open. + pub fn write_generation(&self, len: usize, write_fn: impl FnOnce(&mut [u8]) -> bool) -> Option<(u64, PathBuf)> { + if len == 0 { + return None; + } + let gen = self.next_gen.fetch_add(1, Ordering::AcqRel); + let final_path = self.dir.join(generation_name(gen)); + let tmp_path = self.dir.join(format!("gen-{gen:08x}-{}.tmp", std::process::id())); + let mut mapped = MappedWriteFile::create(&tmp_path, len)?; + let ok = write_fn(mapped.as_mut_slice()); + if !ok { + drop(mapped); + return None; + } + let staged = mapped.finish(); + if std::fs::rename(&staged, &final_path).is_err() { + let _ = std::fs::remove_file(&staged); + return None; + } + Some((gen, final_path)) + } +} + +fn generation_name(gen: u64) -> String { + format!("gen-{gen:08x}.plib") +} + +fn parse_generation(file_name: &str) -> Option { + let hex = file_name.strip_prefix("gen-")?.strip_suffix(".plib")?; + if hex.is_empty() { + return None; + } + u64::from_str_radix(hex, 16).ok() +} + +fn latest_generation(dir: &Path) -> Option<(u64, PathBuf)> { + let entries = std::fs::read_dir(dir).ok()?; + let mut best: Option<(u64, PathBuf)> = None; + for entry in entries.flatten() { + let path = entry.path(); + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { continue }; + let Some(gen) = parse_generation(name) else { continue }; + if best.as_ref().is_none_or(|&(b, _)| gen > b) { + best = Some((gen, path)); + } + } + best +} + +fn cleanup_older_generations(dir: &Path, keep_gen: u64) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { continue }; + if parse_generation(name).is_some_and(|g| g < keep_gen) || name.ends_with(".tmp") { + let _ = std::fs::remove_file(path); + } + } +} + +/// Process-wide D3D12 pipeline library backed by a kept-open read-only `MappedBlob` and +/// generational zero-heap-copy serialization. +pub struct MmapPipelineLibrary { + lib: ID3D12PipelineLibrary1, + /// Kept alive for the lifetime of `lib` so file-backed driver pages stay valid with zero heap copy. + _backing: Option, + store: LibraryStore, + dirty: AtomicU64, + saving: AtomicBool, + save_lock: Mutex<()>, + /// Synchronizes concurrent `StorePipeline` (shared read lock) against `GetSerializedSize` + + /// `Serialize` (exclusive write lock) so serialization never races a concurrent size growth. + lib_rw: RwLock<()>, +} + +// `ID3D12PipelineLibrary1` methods are free-threaded per the D3D12 specification; `_backing` is +// read-only and `save_lock` serializes disk snapshots. +unsafe impl Send for MmapPipelineLibrary {} +unsafe impl Sync for MmapPipelineLibrary {} + +impl MmapPipelineLibrary { + /// Open the latest memory-mapped pipeline library on `device`, falling back to a fresh empty + /// library if none exists or if the driver rejects the cached generation (driver/adapter mismatch). + pub unsafe fn open_or_create(device: &ID3D12Device, adapter_name: &str) -> Option { + if !enabled() { + return None; + } + let dev1: ID3D12Device1 = device.cast().ok()?; + let store = LibraryStore::for_adapter(adapter_name); + if let Some((gen, blob)) = store.open_latest() { + match dev1.CreatePipelineLibrary::(blob.as_slice()) { + Ok(lib) => { + crate::xlog_info!( + "D3D12.X: opened memory-mapped pipeline library gen-{gen:08x} ({} MiB file-backed)", + blob.len() >> 20 + ); + return Some(Self { + lib, + _backing: Some(blob), + store, + dirty: AtomicU64::new(0), + saving: AtomicBool::new(false), + save_lock: Mutex::new(()), + lib_rw: RwLock::new(()), + }); + } + Err(e) => { + let stale_path = blob.path().to_path_buf(); + let code = e.code().0; + drop(blob); + // Remove any rejected generation (driver/adapter mismatch, corrupt E_INVALIDARG, + // etc.) so a broken file does not remain the latest generation on future boots. + let _ = std::fs::remove_file(&stale_path); + let _ = (D3D12_ERROR_DRIVER_VERSION_MISMATCH_HR, D3D12_ERROR_ADAPTER_NOT_FOUND_HR); + crate::xlog_info!( + "D3D12.X: pipeline library gen-{gen:08x} rejected ({code:#x}) – removed stale file and starting fresh library" + ); + } + } + } + // Pass an explicit NULL pointer with length 0 rather than `&[]`, whose dangling + // non-null slice pointer vkd3d-proton rejects with E_INVALIDARG. + let mut lib: Option = None; + (Interface::vtable(&dev1).CreatePipelineLibrary)( + Interface::as_raw(&dev1), + std::ptr::null(), + 0, + &ID3D12PipelineLibrary1::IID, + &mut lib as *mut _ as *mut _, + ) + .ok() + .ok()?; + let lib = lib?; + Some(Self { + lib, + _backing: None, + store, + dirty: AtomicU64::new(0), + saving: AtomicBool::new(false), + save_lock: Mutex::new(()), + lib_rw: RwLock::new(()), + }) + } + + pub unsafe fn load_compute(&self, key: &str, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> Option { + let name = HSTRING::from(key); + let _r = self.lib_rw.read().unwrap(); + self.lib.LoadComputePipeline(&name, desc).ok() + } + + pub unsafe fn load_graphics(&self, key: &str, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Option { + let name = HSTRING::from(key); + let _r = self.lib_rw.read().unwrap(); + self.lib.LoadGraphicsPipeline(&name, desc).ok() + } + + pub unsafe fn load_stream(&self, key: &str, desc: &D3D12_PIPELINE_STATE_STREAM_DESC) -> Option { + let name = HSTRING::from(key); + let _r = self.lib_rw.read().unwrap(); + self.lib.LoadPipeline(&name, desc).ok() + } + + pub unsafe fn store(&self, key: &str, pso: &ID3D12PipelineState) -> bool { + let name = HSTRING::from(key); + let _r = self.lib_rw.read().unwrap(); + if self.lib.StorePipeline(&name, pso).is_ok() { + self.dirty.fetch_add(1, Ordering::Relaxed); + true + } else { + false + } + } + + pub fn dirty_count(&self) -> u64 { + self.dirty.load(Ordering::Relaxed) + } + + /// Serialize under `save_lock` (already held by caller), taking `lib_rw.write()` so no + /// `StorePipeline` can grow the library between `GetSerializedSize` and `Serialize`. + unsafe fn save_locked(&self, min_dirty: u64) -> Option { + let dirty_before = self.dirty.load(Ordering::Acquire); + if dirty_before < min_dirty { + return None; + } + let (size, saved) = { + let _w = self.lib_rw.write().unwrap(); + let size = self.lib.GetSerializedSize(); + let saved = if size > 0 { + self.store.write_generation(size, |buf| self.lib.Serialize(buf).is_ok()) + } else { + None + }; + (size, saved) + }; + if let Some((gen, _)) = saved { + self.dirty.fetch_sub(dirty_before.min(self.dirty.load(Ordering::Relaxed)), Ordering::Relaxed); + crate::xlog_info!( + "D3D12.X: saved pipeline library gen-{gen:08x} ({} MiB, {} new pipelines)", + size >> 20, + dirty_before + ); + } + saved.map(|(_, p)| p) + } + + /// Non-blocking periodic save: skips if another save is already in progress. Never replaces or + /// truncates the open `_backing` file. + pub unsafe fn save_if_dirty(&self, min_dirty: u64) -> Option { + if self.dirty.load(Ordering::Relaxed) < min_dirty { + return None; + } + if self.saving.swap(true, Ordering::AcqRel) { + return None; + } + let _guard = self.save_lock.lock().unwrap(); + let saved = self.save_locked(min_dirty); + self.saving.store(false, Ordering::Release); + saved + } + + /// Blocking shutdown flush (e.g. `WM_CLOSE`): waits for any in-flight background save on + /// `save_lock` to complete cleanly before flushing remaining dirty entries. + pub unsafe fn flush(&self) -> Option { + let _guard = self.save_lock.lock().unwrap(); + self.save_locked(1) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct TempDir(PathBuf); + impl TempDir { + fn new(tag: &str) -> Self { + static SEQ: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!("xcl-pso-lib-{tag}-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + } + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn generation_parsing_and_latest_selection() { + assert_eq!(parse_generation("gen-00000001.plib"), Some(1)); + assert_eq!(parse_generation("gen-00000010.plib"), Some(0x10)); + assert_eq!(parse_generation("gen-00000002-1234.tmp"), None); + assert_eq!(parse_generation("gen-.plib"), None); + assert_eq!(parse_generation("other.plib"), None); + + let dir = TempDir::new("latest"); + std::fs::write(dir.0.join("gen-00000001.plib"), b"a").unwrap(); + std::fs::write(dir.0.join("gen-0000000a.plib"), b"bb").unwrap(); + std::fs::write(dir.0.join("gen-00000002.plib"), b"c").unwrap(); + std::fs::write(dir.0.join("gen-000000ff-99.tmp"), b"tmp").unwrap(); + let (gen, path) = latest_generation(&dir.0).unwrap(); + assert_eq!(gen, 0xA); + assert!(path.ends_with("gen-0000000a.plib")); + } + + #[test] + fn mapped_blob_rejects_empty_and_missing_files() { + let dir = TempDir::new("empty"); + assert!(MappedBlob::open(&dir.0.join("missing.plib")).is_none()); + let empty = dir.0.join("empty.plib"); + std::fs::write(&empty, b"").unwrap(); + assert!(MappedBlob::open(&empty).is_none()); + } + + #[test] + fn mapped_blob_reads_and_keeps_file_open_across_generation_save() { + let dir = TempDir::new("gen-save"); + let store = LibraryStore::new(dir.0.clone()); + + let payload1: Vec = (0..16_384usize).map(|i| (i.wrapping_mul(31) ^ 0x5A) as u8).collect(); + let (gen1, path1) = store + .write_generation(payload1.len(), |buf| { + buf.copy_from_slice(&payload1); + true + }) + .expect("gen1 write"); + assert_eq!(gen1, 1); + + // Open gen1 memory-mapped and keep its mapping open while saving gen2. + let (opened_gen, blob1) = store.open_latest().expect("open gen1"); + assert_eq!(opened_gen, 1); + assert_eq!(blob1.as_slice(), payload1.as_slice()); + + let payload2: Vec = (0..32_768usize).map(|i| (i.wrapping_mul(17) ^ 0xA5) as u8).collect(); + let (gen2, path2) = store + .write_generation(payload2.len(), |buf| { + buf.copy_from_slice(&payload2); + true + }) + .expect("gen2 write while gen1 mapped"); + assert_eq!(gen2, 2); + assert_ne!(path1, path2); + + // gen1 mapping MUST remain completely valid and unmodified while open. + assert_eq!(blob1.as_slice(), payload1.as_slice()); + drop(blob1); + + // Re-opening latest selects gen2 and cleans up stale gen1. + let (opened_gen2, blob2) = store.open_latest().expect("open gen2"); + assert_eq!(opened_gen2, 2); + assert_eq!(blob2.as_slice(), payload2.as_slice()); + assert!(!path1.exists(), "older generation should be cleaned up once unmapped"); + drop(blob2); + } +} diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 51016f38a..5a1754a9e 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4308,6 +4308,16 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); copy.CS = bytecode(&dxil); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + let lib_key = pso_lib::compute_key(&dxil, &compiled.samplers, copy.Flags.0); + if pso_lib::try_load_compute(this, &lib_key, ©, riid, ppv) { + TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + note_pso_rs(*ppv, rs); + if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + } + note_translated_compute(S_OK, ppv); + return Some(Ok(S_OK)); + } // A program built again gets the driver's own result of its first build: a retail title // made 14 big compute pipelines twice while loading, 13 - 30 s each the second time. let key = compute_blob_key(&dxil, rs as usize, copy.Flags.0); @@ -4375,6 +4385,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const return Some(Err(())); } TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + pso_lib::store_pipeline(this, &lib_key, *ppv); note_pso_rs(*ppv, rs); if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); @@ -4627,6 +4638,32 @@ mod compute_blob_tests { assert!(super::compute_blob(key).is_none()); assert_eq!(super::COMPUTE_BLOBS.lock().unwrap().as_ref().unwrap().1, before - 3); } + + #[test] + fn duplicate_blob_publishes_charge_budget_once_and_free_cleanly() { + let cache: super::Mutex>>, usize)>> = + super::Mutex::new(None); + // Four racing publishers of the same 16-byte key must charge 16 bytes, not 64. + assert!(super::insert_cached_blob(&cache, 64, 1, vec![0xAA; 16])); + for _ in 0..3 { + assert!(!super::insert_cached_blob(&cache, 64, 1, vec![0xBB; 16])); + } + assert_eq!(cache.lock().unwrap().as_ref().unwrap().1, 16); + // Three more distinct 16-byte keys must still fit inside the 64-byte budget. + for k in 2..=4 { + assert!(super::insert_cached_blob(&cache, 64, k, vec![k as u8; 16])); + } + assert_eq!(cache.lock().unwrap().as_ref().unwrap().1, 64); + assert!(!super::insert_cached_blob(&cache, 64, 5, vec![5; 16])); + // Removing all four keys returns accounted bytes to zero. + let mut g = cache.lock().unwrap(); + let (m, total) = g.as_mut().unwrap(); + for k in 1..=4 { + let b = m.remove(&k).unwrap(); + *total -= b.len(); + } + assert_eq!(*total, 0); + } } /// Read `GetCachedBlob` from either an adopted or raw PC `ID3D12PipelineState`. @@ -4652,6 +4689,28 @@ unsafe fn read_pso_cached_blob(pso: *mut c_void) -> Option> { (!bytes.is_empty()).then_some(bytes) } +fn insert_cached_blob( + cache: &Mutex>>, usize)>>, + limit: usize, + key: K, + bytes: Vec, +) -> bool { + if bytes.is_empty() { + return false; + } + let mut g = cache.lock().unwrap(); + let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); + let std::collections::hash_map::Entry::Vacant(slot) = m.entry(key) else { + return false; + }; + if *total + bytes.len() > limit { + return false; + } + *total += bytes.len(); + slot.insert(std::sync::Arc::new(bytes)); + true +} + /// The driver's blob of the PSO just built (works on both adopted title PSOs and raw PC compute /// passes owned by `TwoPassPso`). unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: usize) { @@ -4659,13 +4718,7 @@ unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: return; } let Some(bytes) = read_pso_cached_blob(pso) else { return }; - let mut g = COMPUTE_BLOBS.lock().unwrap(); - let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); - if bytes.is_empty() || *total + bytes.len() > COMPUTE_BLOBS_MAX { - return; - } - *total += bytes.len(); - m.insert(key, std::sync::Arc::new(bytes)); + insert_cached_blob(&COMPUTE_BLOBS, COMPUTE_BLOBS_MAX, key, bytes); } /// The driver's compiled form of translated graphics pipelines (`GetCachedBlob`), @@ -4690,13 +4743,7 @@ unsafe fn keep_graphics_blob(key: (u64, usize), pso: *mut c_void, dxil_len: usiz return; } let Some(bytes) = read_pso_cached_blob(pso) else { return }; - let mut g = GRAPHICS_BLOBS.lock().unwrap(); - let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); - if bytes.is_empty() || *total + bytes.len() > GRAPHICS_BLOBS_MAX { - return; - } - *total += bytes.len(); - m.insert(key, std::sync::Arc::new(bytes)); + insert_cached_blob(&GRAPHICS_BLOBS, GRAPHICS_BLOBS_MAX, key, bytes); } /// Deterministic FNV-1a digest of every field in a translated PC graphics PSO (shaders, static @@ -5099,6 +5146,20 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const } pc_topology_type(&mut copy); let ps_hash = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); + let debug_override = debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash) || debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash); + let lib_key = (!debug_override).then(|| pso_lib::graphics_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers)); + if let Some(key) = lib_key.as_deref() { + if pso_lib::try_load_graphics(this, key, ©, riid, ppv) { + let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + note_pso_rs(*ppv, rs); + TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); + if n < 5 || n % 1000 == 0 { + crate::xlog_info!("D3D12.X: graphics PSO loaded from memory-mapped pipeline library (#{})", n + 1); + } + return Some(S_OK); + } + } if debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash) { copy.DepthStencilState.StencilEnable = false.into(); } @@ -5147,6 +5208,14 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const return None; } let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + if let Some(key) = lib_key { + let final_key = if rect_gs.is_some() && copy.GS.pShaderBytecode.is_null() { + pso_lib::graphics_key(©, &vs_dxil, ps_dxil.as_deref(), None, &samplers) + } else { + key + }; + pso_lib::store_pipeline(this, &final_key, *ppv); + } note_pso_rs(*ppv, rs); TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); @@ -5767,6 +5836,8 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let Some(rs) = abi_rs_for(this, &tp.samplers) else { return E_INVALIDARG }; let fs: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); let desc: [usize; 2] = [stream.0.len(), stream.0.as_ptr() as usize]; + let mesh_lib_key = pso_lib::stream_key(&stream.0, mesh_rs as usize, stream.shader_bytes()); + let cs_lib_key = pso_lib::compute_key(&tp.cs, &tp.samplers, 0); // the mesh pass and its compute pass: one turn for both let bytes = stream.shader_bytes() + tp.cs.len(); let gate = bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); @@ -5775,12 +5846,30 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: if gate { crate::xlog_info!("D3D12.X: two-pass {kind} PSO ({bytes} B DXIL) gated, waited {} ms", waited.elapsed().as_millis()); } - let hr = driver_compile(kind, stream.shader_bytes(), false, || finish_pso(this, fs, desc.as_ptr() as *const c_void, riid, ppv)); + let mesh_loaded = pso_lib::try_load_stream(this, &mesh_lib_key, &stream.0, riid, ppv); + let hr = if mesh_loaded { + S_OK + } else { + driver_compile(kind, stream.shader_bytes(), false, || finish_pso(this, fs, desc.as_ptr() as *const c_void, riid, ppv)) + }; if hr < 0 || ppv.is_null() || (*ppv).is_null() { note_translation_error(format!("the driver rejected the mesh pipeline from the console {kind} ({hr:#x})")); return E_INVALIDARG; } let mesh_pso = *ppv; + if !mesh_loaded { + pso_lib::store_pipeline(this, &mesh_lib_key, mesh_pso); + } + if let Some(compute) = pso_lib::try_load_compute_raw(this, &cs_lib_key, rs, &tp.cs) { + drop(_slot); + note_pso_rs(mesh_pso, mesh_rs); + TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); + let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + if n < 5 || n % 1000 == 0 { + crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (loaded from memory-mapped library)"); + } + return hr; + } let fc: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); cdesc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); @@ -5832,6 +5921,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: *ppv = std::ptr::null_mut(); return E_INVALIDARG; } + pso_lib::store_pipeline(this, &cs_lib_key, compute); note_pso_rs(mesh_pso, mesh_rs); TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); @@ -6396,6 +6486,557 @@ mod pso_blend_and_tsharp_tests { } } +/// Flush any newly compiled pipelines in the memory-mapped `ID3D12PipelineLibrary1` to a fresh +/// generational `.plib` file (called on clean window close; never truncates the open mapping). +pub fn flush_pipeline_library() { + pso_lib::flush_now(); +} + +/// Runtime wiring for `pso_library::MmapPipelineLibrary`: deterministic cross-run pipeline keys, +/// kept-open per-device library lookup, load/store helpers, and debounced background generational +/// persistence (zero heap copy, never replaces an actively mapped `.plib`). +mod pso_lib { + use super::*; + use crate::hle::d3d12x::pso_library::MmapPipelineLibrary; + use std::sync::Arc; + use std::time::{Duration, Instant}; + + /// Minimum newly stored pipelines before triggering a periodic background generation save. + const SAVE_BATCH_THRESHOLD: u64 = 32; + /// Minimum spacing between periodic background saves while pipelines are streaming in. + const SAVE_MIN_INTERVAL: Duration = Duration::from_secs(15); + /// Idle delay after the last stored pipeline before flushing any remaining tail (`>= 1` dirty). + const SAVE_IDLE_FLUSH: Duration = Duration::from_secs(5); + + struct LibState { + device: usize, + lib: Option>, + stored_keys: HashSet, + hits: u64, + stores: u64, + } + + static LIB_STATE: Mutex> = Mutex::new(None); + static LAST_STORE_MS: AtomicU64 = AtomicU64::new(0); + static LAST_SAVE_MS: AtomicU64 = AtomicU64::new(0); + static SAVER_STARTED: std::sync::Once = std::sync::Once::new(); + static EPOCH: OnceLock = OnceLock::new(); + + fn now_ms() -> u64 { + EPOCH.get_or_init(Instant::now).elapsed().as_millis() as u64 + } + + /// Pure save-scheduling decision (unit-testable on CPU): + /// - Save immediately when `dirty >= SAVE_BATCH_THRESHOLD` and at least `SAVE_MIN_INTERVAL` + /// elapsed since the last save. + /// - Or save any tail (`dirty > 0`) once no new pipeline has been stored for `SAVE_IDLE_FLUSH`. + pub(super) fn should_background_save(dirty: u64, now_ms: u64, last_store_ms: u64, last_save_ms: u64) -> bool { + if dirty == 0 { + return false; + } + let since_save = now_ms.saturating_sub(last_save_ms); + let since_store = now_ms.saturating_sub(last_store_ms); + (dirty >= SAVE_BATCH_THRESHOLD && since_save >= SAVE_MIN_INTERVAL.as_millis() as u64) + || (last_store_ms > 0 && since_store >= SAVE_IDLE_FLUSH.as_millis() as u64 && since_save >= SAVE_IDLE_FLUSH.as_millis() as u64) + } + + fn ensure_saver_thread() { + SAVER_STARTED.call_once(|| { + let _ = std::thread::Builder::new().name("xcl-plib-save".into()).spawn(|| loop { + std::thread::sleep(Duration::from_secs(2)); + let lib = LIB_STATE.lock().unwrap().as_ref().and_then(|s| s.lib.clone()); + let Some(lib) = lib else { continue }; + let now = now_ms(); + let dirty = lib.dirty_count(); + if should_background_save(dirty, now, LAST_STORE_MS.load(Ordering::Acquire), LAST_SAVE_MS.load(Ordering::Acquire)) { + if unsafe { lib.save_if_dirty(1) }.is_some() { + LAST_SAVE_MS.store(now_ms(), Ordering::Release); + } + } + }); + }); + } + + unsafe fn library_for(device: *mut c_void) -> Option> { + if cfg!(test) || device.is_null() || !super::super::pso_library::enabled() { + return None; + } + let dev_key = device as usize; + { + let g = LIB_STATE.lock().unwrap(); + if let Some(s) = g.as_ref().filter(|s| s.device == dev_key) { + return s.lib.clone(); + } + } + let adapter = { + let s = ADAPTER.lock().unwrap().clone(); + if s.is_empty() { "default".to_string() } else { s } + }; + let opened = ID3D12Device::from_raw_borrowed(&device) + .and_then(|dev| MmapPipelineLibrary::open_or_create(dev, &adapter)) + .map(Arc::new); + let mut g = LIB_STATE.lock().unwrap(); + if let Some(s) = g.as_ref().filter(|s| s.device == dev_key) { + return s.lib.clone(); + } + let ret = opened.clone(); + *g = Some(LibState { + device: dev_key, + lib: opened, + stored_keys: HashSet::new(), + hits: 0, + stores: 0, + }); + if ret.is_some() { + ensure_saver_thread(); + } + ret + } + + pub(super) fn flush_now() { + let lib = LIB_STATE.lock().unwrap().as_ref().and_then(|s| s.lib.clone()); + if let Some(lib) = lib { + if unsafe { lib.flush() }.is_some() { + LAST_SAVE_MS.store(now_ms(), Ordering::Release); + } + } + } + + fn fnv_feed(h: &mut u64, bytes: &[u8]) { + for &b in bytes { + *h ^= b as u64; + *h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + } + + fn samplers_digest(samplers: &[crate::gpu::recomp::pso::StaticSampler]) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + fnv_feed(&mut h, &(samplers.len() as u64).to_le_bytes()); + for (w, cmp) in samplers { + for &x in w { + fnv_feed(&mut h, &x.to_le_bytes()); + } + fnv_feed(&mut h, &[*cmp as u8]); + } + h + } + + fn abi_rs_samplers_digest(rs: usize) -> u64 { + let g = ABI_RS_SAMPLERS.lock().unwrap(); + let Some(map) = g.as_ref() else { + return 0; + }; + let Some((words, _)) = map.iter().find(|(_, &v)| v == rs) else { + return 0; + }; + let mut h = 0xcbf2_9ce4_8422_2325u64; + fnv_feed(&mut h, &(words.len() as u64).to_le_bytes()); + for &w in words { + fnv_feed(&mut h, &w.to_le_bytes()); + } + h + } + + /// Deterministic cross-run key for a translated compute pipeline. + pub(super) fn compute_key(dxil: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], flags: i32) -> String { + format!( + "c-{:016x}-{:x}-{:016x}-{:x}", + crate::gpu::shader::fnv64(dxil), + dxil.len(), + samplers_digest(samplers), + flags as u32 + ) + } + + /// Deterministic cross-run key for a sanitized translated graphics pipeline (depends on effective + /// blend/rasterizer/depth-stencil state, input layout semantics, formats, shaders, and samplers). + pub(super) unsafe fn graphics_key( + copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + vs_dxil: &[u8], + ps_dxil: Option<&[u8]>, + rect_gs: Option<&[u8]>, + samplers: &[crate::gpu::recomp::pso::StaticSampler], + ) -> String { + let mut h = 0xcbf2_9ce4_8422_2325u64; + let feed_u32 = |h: &mut u64, v: u32| fnv_feed(h, &v.to_le_bytes()); + let feed_u64 = |h: &mut u64, v: u64| fnv_feed(h, &v.to_le_bytes()); + let feed_slice = |h: &mut u64, s: Option<&[u8]>| match s { + Some(b) => { + feed_u64(h, crate::gpu::shader::fnv64(b)); + feed_u64(h, b.len() as u64); + } + None => feed_u64(h, 0), + }; + feed_slice(&mut h, Some(vs_dxil)); + feed_slice(&mut h, ps_dxil); + feed_slice(&mut h, rect_gs); + feed_u64(&mut h, samplers_digest(samplers)); + + // Sanitized BlendState (effective integer-RT BlendEnable/LogicOpEnable already applied) + feed_u32(&mut h, copy.BlendState.AlphaToCoverageEnable.0 as u32); + feed_u32(&mut h, copy.BlendState.IndependentBlendEnable.0 as u32); + for rt in ©.BlendState.RenderTarget { + feed_u32(&mut h, rt.BlendEnable.0 as u32); + feed_u32(&mut h, rt.LogicOpEnable.0 as u32); + feed_u32(&mut h, rt.SrcBlend.0 as u32); + feed_u32(&mut h, rt.DestBlend.0 as u32); + feed_u32(&mut h, rt.BlendOp.0 as u32); + feed_u32(&mut h, rt.SrcBlendAlpha.0 as u32); + feed_u32(&mut h, rt.DestBlendAlpha.0 as u32); + feed_u32(&mut h, rt.BlendOpAlpha.0 as u32); + feed_u32(&mut h, rt.LogicOp.0 as u32); + fnv_feed(&mut h, &[rt.RenderTargetWriteMask]); + } + feed_u32(&mut h, copy.SampleMask); + + // RasterizerState + let r = ©.RasterizerState; + feed_u32(&mut h, r.FillMode.0 as u32); + feed_u32(&mut h, r.CullMode.0 as u32); + feed_u32(&mut h, r.FrontCounterClockwise.0 as u32); + feed_u32(&mut h, r.DepthBias as u32); + feed_u32(&mut h, r.DepthBiasClamp.to_bits()); + feed_u32(&mut h, r.SlopeScaledDepthBias.to_bits()); + feed_u32(&mut h, r.DepthClipEnable.0 as u32); + feed_u32(&mut h, r.MultisampleEnable.0 as u32); + feed_u32(&mut h, r.AntialiasedLineEnable.0 as u32); + feed_u32(&mut h, r.ForcedSampleCount); + feed_u32(&mut h, r.ConservativeRaster.0 as u32); + + // DepthStencilState + let ds = ©.DepthStencilState; + feed_u32(&mut h, ds.DepthEnable.0 as u32); + feed_u32(&mut h, ds.DepthWriteMask.0 as u32); + feed_u32(&mut h, ds.DepthFunc.0 as u32); + feed_u32(&mut h, ds.StencilEnable.0 as u32); + fnv_feed(&mut h, &[ds.StencilReadMask, ds.StencilWriteMask]); + for face in [&ds.FrontFace, &ds.BackFace] { + feed_u32(&mut h, face.StencilFailOp.0 as u32); + feed_u32(&mut h, face.StencilDepthFailOp.0 as u32); + feed_u32(&mut h, face.StencilPassOp.0 as u32); + feed_u32(&mut h, face.StencilFunc.0 as u32); + } + + // InputLayout + let il = ©.InputLayout; + feed_u32(&mut h, il.NumElements); + if il.NumElements > 0 && !il.pInputElementDescs.is_null() { + for e in std::slice::from_raw_parts(il.pInputElementDescs, il.NumElements as usize) { + if !e.SemanticName.0.is_null() { + let s = std::ffi::CStr::from_ptr(e.SemanticName.0 as *const std::ffi::c_char); + fnv_feed(&mut h, s.to_bytes_with_nul()); + } else { + fnv_feed(&mut h, &[0]); + } + feed_u32(&mut h, e.SemanticIndex); + feed_u32(&mut h, e.Format.0 as u32); + feed_u32(&mut h, e.InputSlot); + feed_u32(&mut h, e.AlignedByteOffset); + feed_u32(&mut h, e.InputSlotClass.0 as u32); + feed_u32(&mut h, e.InstanceDataStepRate); + } + } + + feed_u32(&mut h, copy.IBStripCutValue.0 as u32); + feed_u32(&mut h, copy.PrimitiveTopologyType.0 as u32); + feed_u32(&mut h, copy.NumRenderTargets); + for f in ©.RTVFormats { + feed_u32(&mut h, f.0 as u32); + } + feed_u32(&mut h, copy.DSVFormat.0 as u32); + feed_u32(&mut h, copy.SampleDesc.Count); + feed_u32(&mut h, copy.SampleDesc.Quality); + feed_u32(&mut h, copy.NodeMask); + feed_u32(&mut h, copy.Flags.0 as u32); + + let total = vs_dxil.len() + ps_dxil.map_or(0, <[u8]>::len) + rect_gs.map_or(0, <[u8]>::len); + format!("g-{h:016x}-{total:x}") + } + + /// Deterministic cross-run key for a translated mesh/GS pipeline state stream: hashes shader + /// bytecodes by content, root signature by static-sampler digest, and pointer-bearing subobjects + /// (`INPUT_LAYOUT`, `STREAM_OUTPUT`, `VIEW_INSTANCING`) by pointed-to content (never raw pointers). + pub(super) unsafe fn stream_key(stream_bytes: &[u8], mesh_rs: usize, shader_bytes: usize) -> String { + let mut h = 0xcbf2_9ce4_8422_2325u64; + fnv_feed(&mut h, &abi_rs_samplers_digest(mesh_rs).to_le_bytes()); + if let Some(subs) = stream_subobjects(stream_bytes) { + for (ty, payload) in subs { + fnv_feed(&mut h, &ty.to_le_bytes()); + if ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE.0 as u32 + || ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO.0 as u32 + { + continue; + } + if SHADER_SUBOBJECTS.iter().any(|t| t.0 as u32 == ty) { + if let Some(code) = payload_shader(payload) { + fnv_feed(&mut h, &crate::gpu::shader::fnv64(code).to_le_bytes()); + fnv_feed(&mut h, &(code.len() as u64).to_le_bytes()); + } else { + fnv_feed(&mut h, &0u64.to_le_bytes()); + } + continue; + } + if ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0 as u32 + && payload.len() >= std::mem::size_of::() + { + let il = std::ptr::read_unaligned(payload.as_ptr() as *const D3D12_INPUT_LAYOUT_DESC); + fnv_feed(&mut h, &il.NumElements.to_le_bytes()); + if il.NumElements > 0 && !il.pInputElementDescs.is_null() { + for e in std::slice::from_raw_parts(il.pInputElementDescs, il.NumElements as usize) { + if !e.SemanticName.0.is_null() { + fnv_feed(&mut h, std::ffi::CStr::from_ptr(e.SemanticName.0 as *const i8).to_bytes()); + } + fnv_feed(&mut h, &[0u8]); + fnv_feed(&mut h, &e.SemanticIndex.to_le_bytes()); + fnv_feed(&mut h, &e.Format.0.to_le_bytes()); + fnv_feed(&mut h, &e.InputSlot.to_le_bytes()); + fnv_feed(&mut h, &e.AlignedByteOffset.to_le_bytes()); + fnv_feed(&mut h, &e.InputSlotClass.0.to_le_bytes()); + fnv_feed(&mut h, &e.InstanceDataStepRate.to_le_bytes()); + } + } + continue; + } + if ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT.0 as u32 + && payload.len() >= std::mem::size_of::() + { + let so = std::ptr::read_unaligned(payload.as_ptr() as *const D3D12_STREAM_OUTPUT_DESC); + fnv_feed(&mut h, &so.NumEntries.to_le_bytes()); + fnv_feed(&mut h, &so.NumStrides.to_le_bytes()); + fnv_feed(&mut h, &so.RasterizedStream.to_le_bytes()); + if so.NumEntries > 0 && !so.pSODeclaration.is_null() { + for d in std::slice::from_raw_parts(so.pSODeclaration, so.NumEntries as usize) { + fnv_feed(&mut h, &d.Stream.to_le_bytes()); + if !d.SemanticName.0.is_null() { + fnv_feed(&mut h, std::ffi::CStr::from_ptr(d.SemanticName.0 as *const i8).to_bytes()); + } + fnv_feed(&mut h, &[0u8, d.StartComponent, d.ComponentCount, d.OutputSlot]); + fnv_feed(&mut h, &d.SemanticIndex.to_le_bytes()); + } + } + if so.NumStrides > 0 && !so.pBufferStrides.is_null() { + for &s in std::slice::from_raw_parts(so.pBufferStrides, so.NumStrides as usize) { + fnv_feed(&mut h, &s.to_le_bytes()); + } + } + continue; + } + if ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING.0 as u32 + && payload.len() >= std::mem::size_of::() + { + let vi = std::ptr::read_unaligned(payload.as_ptr() as *const D3D12_VIEW_INSTANCING_DESC); + fnv_feed(&mut h, &vi.ViewInstanceCount.to_le_bytes()); + fnv_feed(&mut h, &vi.Flags.0.to_le_bytes()); + if vi.ViewInstanceCount > 0 && !vi.pViewInstanceLocations.is_null() { + for l in std::slice::from_raw_parts(vi.pViewInstanceLocations, vi.ViewInstanceCount as usize) { + fnv_feed(&mut h, &l.ViewportArrayIndex.to_le_bytes()); + fnv_feed(&mut h, &l.RenderTargetArrayIndex.to_le_bytes()); + } + } + continue; + } + fnv_feed(&mut h, payload); + } + } + format!("s-{h:016x}-{shader_bytes:x}") + } + + unsafe fn deliver_adopted(pso: ID3D12PipelineState, _riid: *const GUID, ppv: *mut *mut c_void) -> bool { + if ppv.is_null() { + return false; + } + // `pso` is already an `ID3D12PipelineState` matching `pc_iid(Kind::PipelineState)`; do not + // pass console IIDs through PC COM `QueryInterface`. + let out = pso.into_raw(); + adopt(out, Kind::PipelineState); + *ppv = out; + true + } + + fn note_hit() { + if let Some(s) = LIB_STATE.lock().unwrap().as_mut() { + s.hits += 1; + if s.hits == 1 || s.hits % 500 == 0 { + crate::xlog_info!("D3D12.X: memory-mapped pipeline library hits: {}", s.hits); + } + } + } + + pub(super) unsafe fn try_load_compute( + device: *mut c_void, + key: &str, + desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, + riid: *const GUID, + ppv: *mut *mut c_void, + ) -> bool { + let Some(lib) = library_for(device) else { return false }; + let Some(pso) = lib.load_compute(key, desc) else { return false }; + if deliver_adopted(pso, riid, ppv) { + note_hit(); + true + } else { + false + } + } + + pub(super) unsafe fn try_load_compute_raw( + device: *mut c_void, + key: &str, + rs: *mut c_void, + cs: &[u8], + ) -> Option<*mut c_void> { + let lib = library_for(device)?; + let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + cdesc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); + cdesc.CS = bytecode(cs); + let pso = lib.load_compute(key, &cdesc)?; + note_hit(); + Some(pso.into_raw()) + } + + pub(super) unsafe fn try_load_graphics( + device: *mut c_void, + key: &str, + desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + riid: *const GUID, + ppv: *mut *mut c_void, + ) -> bool { + let Some(lib) = library_for(device) else { return false }; + let Some(pso) = lib.load_graphics(key, desc) else { return false }; + if deliver_adopted(pso, riid, ppv) { + note_hit(); + true + } else { + false + } + } + + pub(super) unsafe fn try_load_stream( + device: *mut c_void, + key: &str, + stream_bytes: &[u8], + riid: *const GUID, + ppv: *mut *mut c_void, + ) -> bool { + let Some(lib) = library_for(device) else { return false }; + let sdesc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: stream_bytes.len(), + pPipelineStateSubobjectStream: stream_bytes.as_ptr() as *mut c_void, + }; + let Some(pso) = lib.load_stream(key, &sdesc) else { return false }; + if deliver_adopted(pso, riid, ppv) { + note_hit(); + true + } else { + false + } + } + + pub(super) unsafe fn store_pipeline(device: *mut c_void, key: &str, pso_raw: *mut c_void) { + if pso_raw.is_null() { + return; + } + let Some(lib) = library_for(device) else { return }; + { + let mut g = LIB_STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if !s.stored_keys.insert(key.to_string()) { + return; + } + } + let Some(pso) = ID3D12PipelineState::from_raw_borrowed(&pso_raw) else { return }; + if lib.store(key, pso) { + LAST_STORE_MS.store(now_ms(), Ordering::Release); + if let Some(s) = LIB_STATE.lock().unwrap().as_mut() { + s.stores += 1; + } + } + } + + #[cfg(test)] + mod tests { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::*; + + #[test] + fn pipeline_library_keys_are_deterministic_and_sensitive_to_effective_state() { + let s1 = [([1u32, 2, 3, 4], false)]; + let s2 = [([1u32, 2, 3, 4], true)]; + let ck1 = compute_key(b"dxil-cs", &s1, 0); + assert_eq!(ck1, compute_key(b"dxil-cs", &s1, 0)); + assert_ne!(ck1, compute_key(b"dxil-cs", &s2, 0), "sampler change must change key"); + assert_ne!(ck1, compute_key(b"dxil-cs", &s1, 1), "flags change must change key"); + assert_ne!(ck1, compute_key(b"dxil-c2", &s1, 0), "shader change must change key"); + + // Graphics key reflects pc_topology_type's normalized topology and PC target format. + unsafe { + let mut g1: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::mem::zeroed(); + g1.NumRenderTargets = 1; + g1.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let mut g2 = g1.clone(); + g2.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + assert_ne!( + graphics_key(&g1, b"vs", Some(b"ps"), None, &[]), + graphics_key(&g2, b"vs", Some(b"ps"), None, &[]) + ); + pc_topology_type(&mut g1); + pc_topology_type(&mut g2); + assert_eq!( + graphics_key(&g1, b"vs", Some(b"ps"), None, &[]), + graphics_key(&g2, b"vs", Some(b"ps"), None, &[]), + "normalized graphics PSOs must share the same library key" + ); + } + + // Stream key hashes shader content, not pointer addresses. + unsafe { + let ms_a = b"mesh-shader-dxil-payload".to_vec(); + let ms_b = ms_a.clone(); + assert_ne!(ms_a.as_ptr(), ms_b.as_ptr()); + let ps = b"pixel-shader-dxil".to_vec(); + let build = |ms: &[u8], rs_ptr: usize| { + let mut out = StreamOut::default(); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &rs_ptr); + out.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms); + out.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, &ps); + let rt = D3D12_RT_FORMAT_ARRAY { + RTFormats: [DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN], + NumRenderTargets: 1, + }; + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, &rt); + out + }; + let sa = build(&ms_a, 0x1000); + let sb = build(&ms_b, 0x2000); + assert_eq!( + stream_key(&sa.0, 0x1000, sa.shader_bytes()), + stream_key(&sb.0, 0x2000, sb.shader_bytes()), + "stream key must depend on shader content, not transient pointers" + ); + let ms_diff = b"mesh-shader-dxil-DIFF!!!".to_vec(); + let sc = build(&ms_diff, 0x1000); + assert_ne!( + stream_key(&sa.0, 0x1000, sa.shader_bytes()), + stream_key(&sc.0, 0x1000, sc.shader_bytes()), + ); + } + } + + #[test] + fn background_save_scheduler_batches_bursts_and_flushes_idle_tail() { + assert!(!should_background_save(0, 60_000, 10_000, 0)); + // Below batch threshold during active burst (< 5s idle) -> wait. + assert!(!should_background_save(10, 12_000, 10_000, 0)); + // At batch threshold (>= 32) but < 15s since last save -> wait. + assert!(!should_background_save(32, 20_000, 19_000, 10_000)); + // At batch threshold (>= 32) and >= 15s since last save -> save! + assert!(should_background_save(32, 25_000, 24_000, 10_000)); + // Small tail (1 dirty) after 5s idle since last store & save -> flush! + assert!(should_background_save(1, 30_000, 25_000, 20_000)); + } + } +} + enum StreamPipeline { Graphics(Box), Compute(Box),