From 8044bedde5c82ca5d405a49986c904b32a38c0e9 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 25 Nov 2026 01:29:25 +1000 Subject: [PATCH 1/4] d3d12x: cap cumulative PSO bind waits per PresentX frame --- crates/xcl/src/hle/d3d12x/present.rs | 5 + crates/xcl/src/hle/d3d12x/pso_async.rs | 270 ++++++++++++++++++++++--- 2 files changed, 249 insertions(+), 26 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 01b3c92a4a..3faaae201a 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -141,6 +141,11 @@ pub fn counters() -> (u64, u64) { (PRESENTS.load(Ordering::Relaxed), BOUNDARIES.load(Ordering::Relaxed)) } +/// Monotonic count of presented frames (`PresentX` / fallback frame boundaries). +pub fn frame_generation() -> u64 { + BOUNDARIES.load(Ordering::Relaxed) +} + fn enabled() -> bool { !crate::state::config().present.eq_ignore_ascii_case("off") } diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 3bc4ad2d67..dc938139fd 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -507,6 +507,115 @@ mod used_tests { released(known); released(unknown); } + + #[test] + fn wait_caps_respect_env_and_title_boot_state() { + use std::time::Duration; + assert_eq!(resolve_caps(None, None, false), None); + assert_eq!( + resolve_caps(None, None, true), + Some(WaitCaps { per_pso: Duration::from_millis(DEFAULT_TITLE_WAIT_MS), per_frame: Some(Duration::from_millis(DEFAULT_FRAME_WAIT_MS)) }) + ); + assert_eq!(resolve_caps(Some(0), None, true), None); + assert_eq!( + resolve_caps(Some(500), None, false), + Some(WaitCaps { per_pso: Duration::from_millis(500), per_frame: Some(Duration::from_millis(DEFAULT_FRAME_WAIT_MS)) }) + ); + assert_eq!( + resolve_caps(Some(3_000), None, true), + Some(WaitCaps { per_pso: Duration::from_millis(3_000), per_frame: Some(Duration::from_millis(3_000)) }) + ); + assert_eq!( + resolve_caps(Some(250), Some(0), true), + Some(WaitCaps { per_pso: Duration::from_millis(250), per_frame: None }) + ); + assert_eq!( + resolve_caps(Some(1_000), Some(500), true), + Some(WaitCaps { per_pso: Duration::from_millis(500), per_frame: Some(Duration::from_millis(500)) }) + ); + assert_eq!( + resolve_caps(Some(0), Some(500), true), + Some(WaitCaps { per_pso: Duration::from_millis(500), per_frame: Some(Duration::from_millis(500)) }) + ); + } + + #[test] + fn frame_budget_caps_cumulative_wait_and_resets_on_new_frame() { + use std::time::Duration; + let mut fb = FrameBudget::default(); + let caps = WaitCaps { per_pso: Duration::from_millis(250), per_frame: Some(Duration::from_millis(600)) }; + + assert_eq!(fb.remaining(1, caps), (Duration::from_millis(250), false)); + fb.record(1, Duration::from_millis(250)); + assert_eq!(fb.remaining(1, caps), (Duration::from_millis(250), false)); + fb.record(1, Duration::from_millis(250)); + // 100 ms left in frame 1: truncated below per_pso (250 ms) + assert_eq!(fb.remaining(1, caps), (Duration::from_millis(100), true)); + fb.record(1, Duration::from_millis(100)); + // Exhausted for the rest of frame 1 + assert_eq!(fb.remaining(1, caps), (Duration::ZERO, true)); + + // Frame 2 resets the cumulative budget + assert_eq!(fb.remaining(2, caps), (Duration::from_millis(250), false)); + + // Uncapped frame leaves every wait at full per_pso + let uncapped = WaitCaps { per_pso: Duration::from_millis(250), per_frame: None }; + fb.record(2, Duration::from_secs(10)); + assert_eq!(fb.remaining(2, uncapped), (Duration::from_millis(250), false)); + } + + #[test] + fn a_frame_budget_caps_a_burst_of_slow_pipelines_and_resets_next_frame() { + use std::time::{Duration, Instant}; + let mut fb = FrameBudget::default(); + let caps = WaitCaps { per_pso: Duration::from_millis(35), per_frame: Some(Duration::from_millis(75)) }; + + let (tx1, rx1) = mpsc::channel(); + let (tx2, rx2) = mpsc::channel(); + let (tx3, rx3) = mpsc::channel(); + let (tx4, rx4) = mpsc::channel(); + let (p1, p2, p3, p4, ready) = (0x7E57_C001usize, 0x7E57_C002usize, 0x7E57_C003usize, 0x7E57_C004usize, 0x7E57_C005usize); + submit(p1, true, Box::new(move || { let _ = rx1.recv_timeout(Duration::from_secs(5)); 0xA1 })); + submit(p2, true, Box::new(move || { let _ = rx2.recv_timeout(Duration::from_secs(5)); 0xA2 })); + submit(p3, true, Box::new(move || { let _ = rx3.recv_timeout(Duration::from_secs(5)); 0xA3 })); + submit(p4, true, Box::new(move || { let _ = rx4.recv_timeout(Duration::from_secs(5)); 0xA4 })); + submit(ready, true, Box::new(|| 0xA5)); + let start = Instant::now(); + while is_pending(ready) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(1)); + } + + let (e1, e2, e3, e4, er) = (entry(p1).unwrap(), entry(p2).unwrap(), entry(p3).unwrap(), entry(p4).unwrap(), entry(ready).unwrap()); + let t0 = Instant::now(); + assert_eq!(resolve_within_in_frame(&e1, p1, caps, 1, &mut fb), p1); + assert!(e1.late.load(Ordering::Acquire), "full per-PSO timeout marks pipeline late"); + assert_eq!(resolve_within_in_frame(&e2, p2, caps, 1, &mut fb), p2); + let _ = resolve_within_in_frame(&e3, p3, caps, 1, &mut fb); + let t4 = Instant::now(); + assert_eq!(resolve_within_in_frame(&e4, p4, caps, 1, &mut fb), p4); + assert!(t4.elapsed() < Duration::from_millis(20), "exhausted frame budget skips wait ({:?})", t4.elapsed()); + assert!(t0.elapsed() < Duration::from_millis(250), "burst waited {:?}", t0.elapsed()); + assert!(!e4.late.load(Ordering::Acquire), "budget-skipped pipeline must not be marked late"); + assert_eq!(resolve_within_in_frame(&er, ready, caps, 1, &mut fb), 0xA5, "already-built pipeline still resolves when frame budget is exhausted"); + + // Advancing to frame 2 resets the budget so p4 gets a fresh wait window. + let t_next = Instant::now(); + assert_eq!(resolve_within_in_frame(&e4, p4, caps, 2, &mut fb), p4); + assert!(t_next.elapsed() >= Duration::from_millis(20), "new frame resets wait budget ({:?})", t_next.elapsed()); + assert!(e4.late.load(Ordering::Acquire), "timed-out pipeline in fresh frame becomes late"); + + for tx in [tx1, tx2, tx3, tx4] { + let _ = tx.send(()); + } + let start = Instant::now(); + for p in [p1, p2, p3, p4, ready] { + while is_pending(p) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(2)); + } + assert!(!is_pending(p)); + let _ = released(p); + } + } } fn entry(pso: usize) -> Option> { @@ -529,21 +638,118 @@ pub fn resolve(pso: usize) -> usize { } } -/// `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). +/// Default per-PSO bind wait when running a title (`XCL_PSO_WAIT_MS` unset). +const DEFAULT_TITLE_WAIT_MS: u64 = 250; +/// Default cumulative bind wait cap per `PresentX` frame (`XCL_PSO_FRAME_WAIT_MS` unset), +/// keeping `PresentX` advancing through bursts of cold pipeline builds. +const DEFAULT_FRAME_WAIT_MS: u64 = 2_000; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct WaitCaps { + /// Maximum wait for a single pipeline bind. + per_pso: std::time::Duration, + /// Optional cumulative wait cap per thread within one `PresentX` frame. + per_frame: Option, +} + +fn parse_env_ms(name: &str) -> Option { + std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()) +} + +fn resolve_caps(pso_env: Option, frame_env: Option, title_running: bool) -> Option { + let per_pso = match pso_env { + Some(0) => None, + Some(ms) => Some(std::time::Duration::from_millis(ms)), + None => title_running.then(|| std::time::Duration::from_millis(DEFAULT_TITLE_WAIT_MS)), + }; + match (per_pso, frame_env) { + (None, Some(ms)) if ms > 0 => { + let f = std::time::Duration::from_millis(ms); + Some(WaitCaps { per_pso: f, per_frame: Some(f) }) + } + (None, _) => None, + (Some(p), Some(0)) => Some(WaitCaps { per_pso: p, per_frame: None }), + (Some(p), Some(ms)) => { + let f = std::time::Duration::from_millis(ms); + Some(WaitCaps { per_pso: p.min(f), per_frame: Some(f) }) + } + (Some(p), None) => { + let f = std::time::Duration::from_millis(DEFAULT_FRAME_WAIT_MS).max(p); + Some(WaitCaps { per_pso: p, per_frame: Some(f) }) + } + } +} + +/// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS` per pipeline, +/// `XCL_PSO_FRAME_WAIT_MS` cumulative per `PresentX` frame; `XCL_PSO_WAIT_MS=0` waits until +/// built; unset defaults to 250 ms per pipeline / 2,000 ms per frame while a title runs and +/// unbounded otherwise). +fn wait_caps() -> Option { + static ENV: OnceLock<(Option, Option)> = OnceLock::new(); + let &(pso_env, frame_env) = ENV.get_or_init(|| (parse_env_ms("XCL_PSO_WAIT_MS"), parse_env_ms("XCL_PSO_FRAME_WAIT_MS"))); + resolve_caps(pso_env, frame_env, crate::state::boot().is_some()) +} + +#[derive(Default)] +struct FrameBudget { + frame: u64, + spent: std::time::Duration, +} + +impl FrameBudget { + /// Budget left for one bind in `frame`, returning `(effective_budget, truncated_by_frame)`. + fn remaining(&mut self, frame: u64, caps: WaitCaps) -> (std::time::Duration, bool) { + if self.frame != frame { + self.frame = frame; + self.spent = std::time::Duration::ZERO; + } + match caps.per_frame { + Some(limit) => { + let left = limit.saturating_sub(self.spent); + if left < caps.per_pso { + (left, true) + } else { + (caps.per_pso, false) + } + } + None => (caps.per_pso, false), + } + } + + fn record(&mut self, frame: u64, waited: std::time::Duration) { + if self.frame != frame { + self.frame = frame; + self.spent = std::time::Duration::ZERO; + } + self.spent = self.spent.saturating_add(waited); + } +} + +thread_local! { + static FRAME_BUDGET: std::cell::RefCell = std::cell::RefCell::new(FrameBudget::default()); +} + +/// `resolve`, waiting for a pipeline still being built – built here if unbounded and no worker +/// has started it yet, or waited on workers up to the per-PSO and per-frame budget. pub fn resolve_wait(pso: usize) -> usize { - resolve_wait_for(pso, wait_budget()) + resolve_wait_with_caps(pso, wait_caps()) } -/// `resolve_wait`, waiting at most `budget` (None: until the pipeline is built). +/// `resolve_wait`, waiting at most `budget` per pipeline (None: until the pipeline is built). +#[cfg(test)] fn resolve_wait_for(pso: usize, budget: Option) -> usize { + resolve_wait_with_caps(pso, budget.map(|per_pso| WaitCaps { per_pso, per_frame: None })) +} + +fn resolve_wait_with_caps(pso: usize, caps: Option) -> usize { let Some(p) = entry(pso) else { return pso }; p.note_use(); - // (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 let Some(caps) = caps { + let frame = super::present::frame_generation(); + return FRAME_BUDGET.with(|fb| resolve_within_in_frame(&p, pso, caps, frame, &mut fb.borrow_mut())); } + // (the title's thread is held from here until the pipeline is built) + let _held = (!*p.done.lock().unwrap()).then(Held::new); let job = p.job.lock().unwrap().take(); if let Some(job) = job { complete(&p, job()); @@ -559,19 +765,12 @@ 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)) -} - -/// `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` within `caps` for `frame`: the build goes to the workers (not this thread). +/// A pipeline that exhausts its full per-PSO budget is marked `late` – it and later binds of it +/// get the stand-in until a worker has built it. When the frame's cumulative wait cap runs out, +/// remaining pending binds go on with the stand-in without marking those pipelines `late`, so +/// they get a fresh wait window on the next `PresentX` frame. +fn resolve_within_in_frame(p: &Arc, pso: usize, caps: WaitCaps, frame: u64, fb: &mut FrameBudget) -> usize { let built = |p: &Pending| match p.real.load(Ordering::Acquire) { 0 => pso, r => r, @@ -585,17 +784,36 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> if p.late.load(Ordering::Acquire) { return pso; } + let (budget, truncated_by_frame) = fb.remaining(frame, caps); + if budget.is_zero() { + static SKIPPED: AtomicUsize = AtomicUsize::new(0); + let n = SKIPPED.fetch_add(1, Ordering::Relaxed); + if n < 16 || n.is_power_of_two() { + crate::xlog_warn!( + "D3D12.X: per-frame pipeline wait budget ({} ms) exhausted in frame {frame}: continuing with stand-in ({} so far)", + caps.per_frame.unwrap_or(caps.per_pso).as_millis(), + n + 1 + ); + } + return pso; + } + // (the title's thread is held while waiting for this pipeline) + let _held = Held::new(); p.want(); + let started = std::time::Instant::now(); let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), budget, |d| !*d).unwrap(); + fb.record(frame, started.elapsed()); if *done { return built(p); } 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); + if !truncated_by_frame { + 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); + } } pso } From 378a0775001770ee48f6d820a69f9da4a54017ad Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 25 Nov 2026 05:57:29 +1000 Subject: [PATCH 2/4] d3d12x: share frame PSO wait budget across threads and release wanted on timeout --- crates/xcl/src/hle/d3d12x/pso_async.rs | 180 ++++++++++++++++++++----- 1 file changed, 144 insertions(+), 36 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 9e4b580c48..d5cfb26fc9 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -36,6 +36,11 @@ struct Pending { #[derive(Default)] struct Demand { wanted: bool, + /// an unbounded bind (`want`) waits until the build finishes + unbounded_wanted: bool, + /// active bounded waits (`want_timed`); cleared when the wait exits so late builds return + /// to `real::big_compile_turn` and `dxc::wait_for_memory` commit throttling + timed_waiters: usize, /// thread id of the preload worker (lowest priority) building it, 0 = none preload_thread: u32, } @@ -85,22 +90,75 @@ fn build(p: &Arc, job: Job, preload: bool) { BUILDING.with(|b| *b.borrow_mut() = None); } +fn set_preload_priority(tid: u32, priority: i32) { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_SET_LIMITED_INFORMATION}; + unsafe { + let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, tid); + if !h.is_null() { + SetThreadPriority(h, priority); + CloseHandle(h); + } + } +} + +/// Raises `Demand::wanted` only while a bounded bind wait is actively blocked on `Pending`. +struct TimedWantGuard<'a>(&'a Pending); + +impl Drop for TimedWantGuard<'_> { + fn drop(&mut self) { + use windows_sys::Win32::System::Threading::THREAD_PRIORITY_LOWEST; + let restore_tid = { + let mut d = self.0.demand.lock().unwrap(); + d.timed_waiters = d.timed_waiters.saturating_sub(1); + if d.timed_waiters == 0 && !d.unbounded_wanted && std::mem::replace(&mut d.wanted, false) && d.preload_thread != 0 { + Some(d.preload_thread) + } else { + None + } + }; + if let Some(tid) = restore_tid { + set_preload_priority(tid, THREAD_PRIORITY_LOWEST); + } + } +} + impl Pending { - /// One of the title's threads is about to wait for it: the worker building it goes on now, - /// at a normal priority. + /// One of the title's threads is about to wait unconditionally for it: the worker building + /// it goes on now, at a normal priority. fn want(&self) { - 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 { - unsafe { - let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, d.preload_thread); - if !h.is_null() { - SetThreadPriority(h, THREAD_PRIORITY_NORMAL); - CloseHandle(h); - } + use windows_sys::Win32::System::Threading::THREAD_PRIORITY_NORMAL; + let raise_tid = { + let mut d = self.demand.lock().unwrap(); + d.unbounded_wanted = true; + if !std::mem::replace(&mut d.wanted, true) && d.preload_thread != 0 { + Some(d.preload_thread) + } else { + None + } + }; + if let Some(tid) = raise_tid { + set_preload_priority(tid, THREAD_PRIORITY_NORMAL); + } + } + + /// One of the title's threads waits for a bounded budget: keep `wanted` raised only while + /// the wait is active so a timed-out build returns to `big_compile_turn` / DXC memory gates. + fn want_timed(&self) -> TimedWantGuard<'_> { + use windows_sys::Win32::System::Threading::THREAD_PRIORITY_NORMAL; + let raise_tid = { + let mut d = self.demand.lock().unwrap(); + d.timed_waiters += 1; + if !std::mem::replace(&mut d.wanted, true) && d.preload_thread != 0 { + Some(d.preload_thread) + } else { + None } + }; + if let Some(tid) = raise_tid { + set_preload_priority(tid, THREAD_PRIORITY_NORMAL); } + TimedWantGuard(self) } fn note_use(&self) { @@ -573,7 +631,7 @@ mod used_tests { #[test] fn a_frame_budget_caps_a_burst_of_slow_pipelines_and_resets_next_frame() { use std::time::{Duration, Instant}; - let mut fb = FrameBudget::default(); + let fb = Arc::new(Mutex::new(FrameBudget::new())); let caps = WaitCaps { per_pso: Duration::from_millis(35), per_frame: Some(Duration::from_millis(75)) }; let (tx1, rx1) = mpsc::channel(); @@ -593,20 +651,28 @@ mod used_tests { let (e1, e2, e3, e4, er) = (entry(p1).unwrap(), entry(p2).unwrap(), entry(p3).unwrap(), entry(p4).unwrap(), entry(ready).unwrap()); let t0 = Instant::now(); - assert_eq!(resolve_within_in_frame(&e1, p1, caps, 1, &mut fb), p1); + assert_eq!(resolve_within_in_frame(&e1, p1, caps, 1, &fb), p1); assert!(e1.late.load(Ordering::Acquire), "full per-PSO timeout marks pipeline late"); - assert_eq!(resolve_within_in_frame(&e2, p2, caps, 1, &mut fb), p2); - let _ = resolve_within_in_frame(&e3, p3, caps, 1, &mut fb); - let t4 = Instant::now(); - assert_eq!(resolve_within_in_frame(&e4, p4, caps, 1, &mut fb), p4); - assert!(t4.elapsed() < Duration::from_millis(20), "exhausted frame budget skips wait ({:?})", t4.elapsed()); + assert_eq!(resolve_within_in_frame(&e2, p2, caps, 1, &fb), p2); + let _ = resolve_within_in_frame(&e3, p3, caps, 1, &fb); + // A second thread in the same frame sees the already-exhausted shared frame budget. + let (e4_t, fb_t) = (e4.clone(), fb.clone()); + let (res4, elapsed4) = std::thread::spawn(move || { + let t4 = Instant::now(); + let r = resolve_within_in_frame(&e4_t, p4, caps, 1, &fb_t); + (r, t4.elapsed()) + }) + .join() + .unwrap(); + assert_eq!(res4, p4); + assert!(elapsed4 < Duration::from_millis(20), "exhausted shared frame budget skips wait ({elapsed4:?})"); assert!(t0.elapsed() < Duration::from_millis(250), "burst waited {:?}", t0.elapsed()); assert!(!e4.late.load(Ordering::Acquire), "budget-skipped pipeline must not be marked late"); - assert_eq!(resolve_within_in_frame(&er, ready, caps, 1, &mut fb), 0xA5, "already-built pipeline still resolves when frame budget is exhausted"); + assert_eq!(resolve_within_in_frame(&er, ready, caps, 1, &fb), 0xA5, "already-built pipeline still resolves when frame budget is exhausted"); // Advancing to frame 2 resets the budget so p4 gets a fresh wait window. let t_next = Instant::now(); - assert_eq!(resolve_within_in_frame(&e4, p4, caps, 2, &mut fb), p4); + assert_eq!(resolve_within_in_frame(&e4, p4, caps, 2, &fb), p4); assert!(t_next.elapsed() >= Duration::from_millis(20), "new frame resets wait budget ({:?})", t_next.elapsed()); assert!(e4.late.load(Ordering::Acquire), "timed-out pipeline in fresh frame becomes late"); @@ -622,6 +688,40 @@ mod used_tests { let _ = released(p); } } + + #[test] + fn timed_out_bind_releases_wanted_so_late_builds_respect_throttling() { + use std::time::{Duration, Instant}; + let standin = 0x7E57_C010usize; + let (started_tx, started_rx) = mpsc::channel(); + let (done_tx, done_rx) = mpsc::channel(); + submit(standin, true, Box::new(move || { + started_tx.send(wanted_here()).unwrap(); + let _ = done_rx.recv_timeout(Duration::from_secs(5)); + 0xB1B1 + })); + let wanted = started_rx.recv().unwrap(); + let p = entry(standin).unwrap(); + assert!(!wanted(), "not wanted before a bind waits"); + { + let _guard = p.want_timed(); + assert!(wanted(), "wanted while a timed bind wait is active"); + } + assert!(!wanted(), "dropping TimedWantGuard clears wanted"); + + let fb = Mutex::new(FrameBudget::new()); + let caps = WaitCaps { per_pso: Duration::from_millis(25), per_frame: Some(Duration::from_millis(200)) }; + assert_eq!(resolve_within_in_frame(&p, standin, caps, 1, &fb), standin); + assert!(!wanted(), "timed-out bind releases wanted so big_compile_turn / DXC memory gates still apply"); + assert!(p.late.load(Ordering::Acquire)); + + let _ = done_tx.send(()); + let start = Instant::now(); + while is_pending(standin) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!(released(standin), 0xB1B1); + } } fn entry(pso: usize) -> Option> { @@ -654,7 +754,7 @@ const DEFAULT_FRAME_WAIT_MS: u64 = 2_000; struct WaitCaps { /// Maximum wait for a single pipeline bind. per_pso: std::time::Duration, - /// Optional cumulative wait cap per thread within one `PresentX` frame. + /// Optional process-wide cumulative wait cap within one `PresentX` frame. per_frame: Option, } @@ -686,10 +786,15 @@ fn resolve_caps(pso_env: Option, frame_env: Option, title_running: boo } } -/// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS` per pipeline, -/// `XCL_PSO_FRAME_WAIT_MS` cumulative per `PresentX` frame; `XCL_PSO_WAIT_MS=0` waits until -/// built; unset defaults to 250 ms per pipeline / 2,000 ms per frame while a title runs and -/// unbounded otherwise). +/// How long a bind waits for a pipeline still being built: +/// - `XCL_PSO_WAIT_MS`: per-pipeline cap in ms; `0` waits until built unless +/// `XCL_PSO_FRAME_WAIT_MS` is explicitly set to a positive value (in which case the explicit +/// frame cap wins and bounds both per-pipeline and per-frame waits). +/// - `XCL_PSO_FRAME_WAIT_MS`: process-wide cumulative cap per `PresentX` frame in ms; `0` +/// disables the per-frame cap while keeping `XCL_PSO_WAIT_MS`. +/// - When both are unset: defaults to 250 ms per pipeline / 2,000 ms cumulative per frame while +/// a title is running so cold bursts skip dispatches instead of stalling the watchdog +/// (unbounded in unit tests without a booted title). fn wait_caps() -> Option { static ENV: OnceLock<(Option, Option)> = OnceLock::new(); let &(pso_env, frame_env) = ENV.get_or_init(|| (parse_env_ms("XCL_PSO_WAIT_MS"), parse_env_ms("XCL_PSO_FRAME_WAIT_MS"))); @@ -703,6 +808,10 @@ struct FrameBudget { } impl FrameBudget { + const fn new() -> Self { + Self { frame: 0, spent: std::time::Duration::ZERO } + } + /// Budget left for one bind in `frame`, returning `(effective_budget, truncated_by_frame)`. fn remaining(&mut self, frame: u64, caps: WaitCaps) -> (std::time::Duration, bool) { if self.frame != frame { @@ -731,12 +840,10 @@ impl FrameBudget { } } -thread_local! { - static FRAME_BUDGET: std::cell::RefCell = std::cell::RefCell::new(FrameBudget::default()); -} +static FRAME_BUDGET: Mutex = Mutex::new(FrameBudget::new()); /// `resolve`, waiting for a pipeline still being built – built here if unbounded and no worker -/// has started it yet, or waited on workers up to the per-PSO and per-frame budget. +/// has started it yet, or waited on workers up to the per-PSO and process-wide per-frame budget. pub fn resolve_wait(pso: usize) -> usize { resolve_wait_with_caps(pso, wait_caps()) } @@ -752,7 +859,7 @@ fn resolve_wait_with_caps(pso: usize, caps: Option) -> usize { p.note_use(); if let Some(caps) = caps { let frame = super::present::frame_generation(); - return FRAME_BUDGET.with(|fb| resolve_within_in_frame(&p, pso, caps, frame, &mut fb.borrow_mut())); + return resolve_within_in_frame(&p, pso, caps, frame, &FRAME_BUDGET); } // (the title's thread is held from here until the pipeline is built) let _held = (!*p.done.lock().unwrap()).then(Held::new); @@ -776,7 +883,7 @@ fn resolve_wait_with_caps(pso: usize, caps: Option) -> usize { /// get the stand-in until a worker has built it. When the frame's cumulative wait cap runs out, /// remaining pending binds go on with the stand-in without marking those pipelines `late`, so /// they get a fresh wait window on the next `PresentX` frame. -fn resolve_within_in_frame(p: &Arc, pso: usize, caps: WaitCaps, frame: u64, fb: &mut FrameBudget) -> usize { +fn resolve_within_in_frame(p: &Arc, pso: usize, caps: WaitCaps, frame: u64, fb: &Mutex) -> usize { let built = |p: &Pending| match p.real.load(Ordering::Acquire) { 0 => pso, r => r, @@ -790,7 +897,7 @@ fn resolve_within_in_frame(p: &Arc, pso: usize, caps: WaitCaps, frame: if p.late.load(Ordering::Acquire) { return pso; } - let (budget, truncated_by_frame) = fb.remaining(frame, caps); + let (budget, truncated_by_frame) = fb.lock().unwrap().remaining(frame, caps); if budget.is_zero() { static SKIPPED: AtomicUsize = AtomicUsize::new(0); let n = SKIPPED.fetch_add(1, Ordering::Relaxed); @@ -803,12 +910,13 @@ fn resolve_within_in_frame(p: &Arc, pso: usize, caps: WaitCaps, frame: } return pso; } - // (the title's thread is held while waiting for this pipeline) + // (the title's thread is held while waiting for this pipeline; `wanted` drops when the wait + // ends so timed-out huge builds return to `big_compile_turn` and DXC commit throttling) let _held = Held::new(); - p.want(); + let _want = p.want_timed(); let started = std::time::Instant::now(); let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), budget, |d| !*d).unwrap(); - fb.record(frame, started.elapsed()); + fb.lock().unwrap().record(frame, started.elapsed()); if *done { return built(p); } From 5cb67796609ff17f20cd4bd5fbb7e1acdde4ba75 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 25 Nov 2026 10:19:01 +1000 Subject: [PATCH 3/4] d3d12x: reserve frame PSO wait budget across threads and guard cross-frame settlement --- crates/xcl/src/hle/d3d12x/pso_async.rs | 167 +++++++++++++++++++------ 1 file changed, 126 insertions(+), 41 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index d5cfb26fc9..e82ecac6d5 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -597,10 +597,9 @@ mod used_tests { resolve_caps(Some(1_000), Some(500), true), Some(WaitCaps { per_pso: Duration::from_millis(500), per_frame: Some(Duration::from_millis(500)) }) ); - assert_eq!( - resolve_caps(Some(0), Some(500), true), - Some(WaitCaps { per_pso: Duration::from_millis(500), per_frame: Some(Duration::from_millis(500)) }) - ); + assert_eq!(resolve_caps(Some(0), Some(500), true), Some(WaitCaps { per_pso: Duration::from_millis(500), per_frame: Some(Duration::from_millis(500)) })); + assert_eq!(resolve_caps(None, Some(0), true), Some(WaitCaps { per_pso: Duration::from_millis(DEFAULT_TITLE_WAIT_MS), per_frame: None })); + assert_eq!(resolve_caps(None, Some(0), false), None); } #[test] @@ -609,23 +608,35 @@ mod used_tests { let mut fb = FrameBudget::default(); let caps = WaitCaps { per_pso: Duration::from_millis(250), per_frame: Some(Duration::from_millis(600)) }; - assert_eq!(fb.remaining(1, caps), (Duration::from_millis(250), false)); - fb.record(1, Duration::from_millis(250)); - assert_eq!(fb.remaining(1, caps), (Duration::from_millis(250), false)); - fb.record(1, Duration::from_millis(250)); - // 100 ms left in frame 1: truncated below per_pso (250 ms) - assert_eq!(fb.remaining(1, caps), (Duration::from_millis(100), true)); - fb.record(1, Duration::from_millis(100)); + assert_eq!(fb.reserve(1, caps), (Duration::from_millis(250), false)); + fb.settle(1, Duration::from_millis(250), Duration::from_millis(250)); + assert_eq!(fb.reserve(1, caps), (Duration::from_millis(250), false)); + // Early wakeup returns unused reserved time to the frame + fb.settle(1, Duration::from_millis(250), Duration::from_millis(150)); + // 200 ms left in frame 1: truncated below per_pso (250 ms) + assert_eq!(fb.reserve(1, caps), (Duration::from_millis(200), true)); + fb.settle(1, Duration::from_millis(200), Duration::from_millis(200)); // Exhausted for the rest of frame 1 - assert_eq!(fb.remaining(1, caps), (Duration::ZERO, true)); - - // Frame 2 resets the cumulative budget - assert_eq!(fb.remaining(2, caps), (Duration::from_millis(250), false)); - - // Uncapped frame leaves every wait at full per_pso + assert_eq!(fb.reserve(1, caps), (Duration::ZERO, true)); + + // B1 regression: cross-frame settle from frame 1 must not wipe frame 2's spend + let b1_caps = WaitCaps { per_pso: Duration::from_millis(100), per_frame: Some(Duration::from_millis(100)) }; + let mut cross = FrameBudget::new(); + assert_eq!(cross.reserve(1, b1_caps), (Duration::from_millis(100), false)); + assert_eq!(cross.reserve(2, b1_caps), (Duration::from_millis(100), false)); + cross.settle(2, Duration::from_millis(100), Duration::from_millis(40)); + // Late settle & reserve for stale frame 1 leave frame 2 with 60 ms remaining (not 100 ms) + cross.settle(1, Duration::from_millis(100), Duration::from_millis(100)); + assert_eq!(cross.reserve(1, b1_caps), (Duration::ZERO, true)); + assert_eq!(cross.reserve(2, b1_caps), (Duration::from_millis(60), true)); + + // Frame 3 resets the cumulative budget cleanly + assert_eq!(fb.reserve(3, caps), (Duration::from_millis(250), false)); + + // Uncapped frame leaves every wait at full per_pso without reserving let uncapped = WaitCaps { per_pso: Duration::from_millis(250), per_frame: None }; - fb.record(2, Duration::from_secs(10)); - assert_eq!(fb.remaining(2, uncapped), (Duration::from_millis(250), false)); + fb.settle(3, Duration::from_millis(250), Duration::from_secs(10)); + assert_eq!(fb.reserve(3, uncapped), (Duration::from_millis(250), false)); } #[test] @@ -722,6 +733,52 @@ mod used_tests { } assert_eq!(released(standin), 0xB1B1); } + + #[test] + fn concurrent_binds_in_same_frame_share_reserved_budget() { + use std::sync::Barrier; + use std::time::{Duration, Instant}; + + let fb = Arc::new(Mutex::new(FrameBudget::new())); + let caps = WaitCaps { per_pso: Duration::from_millis(120), per_frame: Some(Duration::from_millis(120)) }; + let (tx1, rx1) = mpsc::channel(); + let (tx2, rx2) = mpsc::channel(); + let (p1, p2) = (0x7E57_D001usize, 0x7E57_D002usize); + submit(p1, true, Box::new(move || { let _ = rx1.recv_timeout(Duration::from_secs(5)); 0xD1 })); + submit(p2, true, Box::new(move || { let _ = rx2.recv_timeout(Duration::from_secs(5)); 0xD2 })); + let e1 = entry(p1).unwrap(); + let e2 = entry(p2).unwrap(); + + let barrier = Arc::new(Barrier::new(2)); + let run = |e: Arc, p: usize, fb: Arc>, b: Arc| { + std::thread::spawn(move || { + b.wait(); + let t = Instant::now(); + let res = resolve_within_in_frame(&e, p, caps, 1, &fb); + (res, t.elapsed()) + }) + }; + let t1 = run(e1.clone(), p1, fb.clone(), barrier.clone()); + let t2 = run(e2.clone(), p2, fb.clone(), barrier); + let (r1, d1) = t1.join().unwrap(); + let (r2, d2) = t2.join().unwrap(); + assert_eq!((r1, r2), (p1, p2)); + let (short, long) = if d1 <= d2 { (d1, d2) } else { (d2, d1) }; + assert!(long >= Duration::from_millis(90), "reserving thread waits near full cap ({long:?})"); + assert!(short < Duration::from_millis(40), "concurrent thread sees zero remaining budget ({short:?})"); + assert!(d1 + d2 < Duration::from_millis(200), "combined wait must not double frame cap ({d1:?} + {d2:?})"); + + let _ = tx1.send(()); + let _ = tx2.send(()); + let start = Instant::now(); + for p in [p1, p2] { + while is_pending(p) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(2)); + } + assert!(!is_pending(p)); + let _ = released(p); + } + } } fn entry(pso: usize) -> Option> { @@ -789,9 +846,11 @@ fn resolve_caps(pso_env: Option, frame_env: Option, title_running: boo /// How long a bind waits for a pipeline still being built: /// - `XCL_PSO_WAIT_MS`: per-pipeline cap in ms; `0` waits until built unless /// `XCL_PSO_FRAME_WAIT_MS` is explicitly set to a positive value (in which case the explicit -/// frame cap wins and bounds both per-pipeline and per-frame waits). +/// frame cap wins and bounds both per-pipeline and per-frame waits). When set while +/// `XCL_PSO_FRAME_WAIT_MS` is unset, the frame cap is `max(2,000 ms, XCL_PSO_WAIT_MS)`. /// - `XCL_PSO_FRAME_WAIT_MS`: process-wide cumulative cap per `PresentX` frame in ms; `0` -/// disables the per-frame cap while keeping `XCL_PSO_WAIT_MS`. +/// disables the per-frame cap while keeping `XCL_PSO_WAIT_MS` (or the 250 ms title default when +/// `XCL_PSO_WAIT_MS` is unset while a title runs; unbounded when no title is booted). /// - When both are unset: defaults to 250 ms per pipeline / 2,000 ms cumulative per frame while /// a title is running so cold bursts skip dispatches instead of stalling the watchdog /// (unbounded in unit tests without a booted title). @@ -805,38 +864,58 @@ fn wait_caps() -> Option { struct FrameBudget { frame: u64, spent: std::time::Duration, + reserved: std::time::Duration, } impl FrameBudget { const fn new() -> Self { - Self { frame: 0, spent: std::time::Duration::ZERO } + Self { frame: 0, spent: std::time::Duration::ZERO, reserved: std::time::Duration::ZERO } } - /// Budget left for one bind in `frame`, returning `(effective_budget, truncated_by_frame)`. - fn remaining(&mut self, frame: u64, caps: WaitCaps) -> (std::time::Duration, bool) { - if self.frame != frame { + /// Reserve budget for one bind in `frame`, returning `(effective_budget, truncated_by_frame)`. + /// Advancing `frame` clears the prior frame's accounting; stale frames never roll back or + /// consume a newer frame's budget. + fn reserve(&mut self, frame: u64, caps: WaitCaps) -> (std::time::Duration, bool) { + if frame > self.frame { self.frame = frame; self.spent = std::time::Duration::ZERO; + self.reserved = std::time::Duration::ZERO; + } else if frame < self.frame { + return (std::time::Duration::ZERO, true); } match caps.per_frame { Some(limit) => { - let left = limit.saturating_sub(self.spent); - if left < caps.per_pso { - (left, true) - } else { - (caps.per_pso, false) - } + let left = limit.saturating_sub(self.spent.saturating_add(self.reserved)); + let (grant, truncated) = if left < caps.per_pso { (left, true) } else { (caps.per_pso, false) }; + self.reserved = self.reserved.saturating_add(grant); + (grant, truncated) } None => (caps.per_pso, false), } } - fn record(&mut self, frame: u64, waited: std::time::Duration) { - if self.frame != frame { - self.frame = frame; - self.spent = std::time::Duration::ZERO; + /// Reconcile a reservation against the actual elapsed wait time, ignoring completions whose + /// originating frame has already been superseded by a newer `PresentX`. + fn settle(&mut self, frame: u64, reserved: std::time::Duration, waited: std::time::Duration) { + if self.frame == frame { + self.reserved = self.reserved.saturating_sub(reserved); + self.spent = self.spent.saturating_add(waited); + } + } +} + +struct FrameWaitGuard<'a> { + fb: &'a Mutex, + frame: u64, + reserved: std::time::Duration, + started: std::time::Instant, +} + +impl Drop for FrameWaitGuard<'_> { + fn drop(&mut self) { + if !self.reserved.is_zero() { + self.fb.lock().unwrap().settle(self.frame, self.reserved, self.started.elapsed()); } - self.spent = self.spent.saturating_add(waited); } } @@ -881,8 +960,9 @@ fn resolve_wait_with_caps(pso: usize, caps: Option) -> usize { /// `resolve_wait` within `caps` for `frame`: the build goes to the workers (not this thread). /// A pipeline that exhausts its full per-PSO budget is marked `late` – it and later binds of it /// get the stand-in until a worker has built it. When the frame's cumulative wait cap runs out, -/// remaining pending binds go on with the stand-in without marking those pipelines `late`, so -/// they get a fresh wait window on the next `PresentX` frame. +/// remaining pending binds in that `PresentX` generation continue immediately with the stand-in +/// without marking those pipelines `late`, keeping recording moving toward the next `PresentX` +/// where they receive a fresh wait window. fn resolve_within_in_frame(p: &Arc, pso: usize, caps: WaitCaps, frame: u64, fb: &Mutex) -> usize { let built = |p: &Pending| match p.real.load(Ordering::Acquire) { 0 => pso, @@ -897,7 +977,7 @@ fn resolve_within_in_frame(p: &Arc, pso: usize, caps: WaitCaps, frame: if p.late.load(Ordering::Acquire) { return pso; } - let (budget, truncated_by_frame) = fb.lock().unwrap().remaining(frame, caps); + let (budget, truncated_by_frame) = fb.lock().unwrap().reserve(frame, caps); if budget.is_zero() { static SKIPPED: AtomicUsize = AtomicUsize::new(0); let n = SKIPPED.fetch_add(1, Ordering::Relaxed); @@ -914,9 +994,14 @@ fn resolve_within_in_frame(p: &Arc, pso: usize, caps: WaitCaps, frame: // ends so timed-out huge builds return to `big_compile_turn` and DXC commit throttling) let _held = Held::new(); let _want = p.want_timed(); - let started = std::time::Instant::now(); + let budget_guard = FrameWaitGuard { + fb, + frame, + reserved: if caps.per_frame.is_some() { budget } else { std::time::Duration::ZERO }, + started: std::time::Instant::now(), + }; let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), budget, |d| !*d).unwrap(); - fb.lock().unwrap().record(frame, started.elapsed()); + drop(budget_guard); if *done { return built(p); } From 21c88bc26b60de5b7ef05b9a0fae5eb61fa6fc16 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 25 Nov 2026 16:29:12 +1000 Subject: [PATCH 4/4] d3d12x: keep per-PSO wait budget when per_frame is disabled on stale samples --- crates/xcl/src/hle/d3d12x/pso_async.rs | 41 +++++++++++++++++++------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 95738f9b27..454098a4c5 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -844,6 +844,25 @@ mod used_tests { assert_eq!(fb.reserve(3, uncapped), (Duration::from_millis(250), false)); } + #[test] + fn frame_budget_stale_frame_sample_keeps_full_wait_when_per_frame_disabled() { + use std::time::Duration; + let mut fb = FrameBudget::new(); + let capped = WaitCaps { per_pso: Duration::from_millis(250), per_frame: Some(Duration::from_millis(500)) }; + let uncapped = WaitCaps { per_pso: Duration::from_millis(250), per_frame: None }; + + // Caller B advances the shared budget to frame 2. + assert_eq!(fb.reserve(1, capped), (Duration::from_millis(250), false)); + assert_eq!(fb.reserve(2, capped), (Duration::from_millis(250), false)); + + // Caller A sampled frame 1 before B advanced: with per_frame == None it still gets full per_pso. + assert_eq!(fb.reserve(1, uncapped), (Duration::from_millis(250), false)); + + // With per_frame == Some(...), stale frame 1 is still rejected without disturbing frame 2. + assert_eq!(fb.reserve(1, capped), (Duration::ZERO, true)); + assert_eq!(fb.reserve(2, capped), (Duration::from_millis(250), false)); + } + #[test] fn a_frame_budget_caps_a_burst_of_slow_pipelines_and_resets_next_frame() { use std::time::{Duration, Instant}; @@ -1145,9 +1164,14 @@ impl FrameBudget { } /// Reserve budget for one bind in `frame`, returning `(effective_budget, truncated_by_frame)`. - /// Advancing `frame` clears the prior frame's accounting; stale frames never roll back or - /// consume a newer frame's budget. + /// When `per_frame` is `None`, returns full `per_pso` immediately before checking frame + /// generation so stale frame samples never zero out waits when the per-frame cap is disabled. + /// When `per_frame` is `Some(_)`, advancing `frame` clears the prior frame's accounting and + /// stale frames never roll back or consume a newer frame's budget. fn reserve(&mut self, frame: u64, caps: WaitCaps) -> (std::time::Duration, bool) { + let Some(limit) = caps.per_frame else { + return (caps.per_pso, false); + }; if frame > self.frame { self.frame = frame; self.spent = std::time::Duration::ZERO; @@ -1155,15 +1179,10 @@ impl FrameBudget { } else if frame < self.frame { return (std::time::Duration::ZERO, true); } - match caps.per_frame { - Some(limit) => { - let left = limit.saturating_sub(self.spent.saturating_add(self.reserved)); - let (grant, truncated) = if left < caps.per_pso { (left, true) } else { (caps.per_pso, false) }; - self.reserved = self.reserved.saturating_add(grant); - (grant, truncated) - } - None => (caps.per_pso, false), - } + let left = limit.saturating_sub(self.spent.saturating_add(self.reserved)); + let (grant, truncated) = if left < caps.per_pso { (left, true) } else { (caps.per_pso, false) }; + self.reserved = self.reserved.saturating_add(grant); + (grant, truncated) } /// Reconcile a reservation against the actual elapsed wait time, ignoring completions whose