diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 2958aa0e9b..4957af9d33 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 b1fd4c2255..454098a4c5 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -38,6 +38,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, } @@ -87,22 +92,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) { @@ -719,6 +777,233 @@ mod used_tests { 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)) })); + 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] + 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.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.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.settle(3, Duration::from_millis(250), Duration::from_secs(10)); + 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}; + 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(); + 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(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)); + } + submit_lazy(p1, true, Box::new(move || { let _ = rx1.recv_timeout(Duration::from_secs(30)); 0xA1 }), 0); + submit_lazy(p2, true, Box::new(move || { let _ = rx2.recv_timeout(Duration::from_secs(30)); 0xA2 }), 0); + submit_lazy(p3, true, Box::new(move || { let _ = rx3.recv_timeout(Duration::from_secs(30)); 0xA3 }), 0); + submit_lazy(p4, true, Box::new(move || { let _ = rx4.recv_timeout(Duration::from_secs(30)); 0xA4 }), 0); + + 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, &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, &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(40), "exhausted shared frame budget skips wait ({elapsed4:?})"); + assert!(t0.elapsed() < Duration::from_millis(350), "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, &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, &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); + } + } + + #[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(30)); + 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); + } + + #[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(200), per_frame: Some(Duration::from_millis(200)) }; + 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(30)); 0xD1 })); + submit(p2, true, Box::new(move || { let _ = rx2.recv_timeout(Duration::from_secs(30)); 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(160), "reserving thread waits near full cap ({long:?})"); + assert!(short < Duration::from_millis(80), "concurrent thread sees zero remaining budget ({short:?})"); + assert!(d1 + d2 < Duration::from_millis(320), "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); + } + } + /// A queued normal worker job whose stand-in was released before a worker starts it is /// skipped as orphaned instead of entering the compiler. #[test] @@ -807,24 +1092,150 @@ 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 process-wide cumulative wait cap 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 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). 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` (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). +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, + reserved: std::time::Duration, +} + +impl FrameBudget { + const fn new() -> Self { + Self { frame: 0, spent: std::time::Duration::ZERO, reserved: std::time::Duration::ZERO } + } + + /// Reserve budget for one bind in `frame`, returning `(effective_budget, truncated_by_frame)`. + /// 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; + self.reserved = std::time::Duration::ZERO; + } else if frame < self.frame { + return (std::time::Duration::ZERO, true); + } + 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 + /// 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()); + } + } +} + +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 process-wide 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(); if p.spared.load(Ordering::Acquire) { return resolve_spared(&p, pso); } - // (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 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); let job = p.job.lock().unwrap().take(); if let Some(job) = job { complete(&p, job()); @@ -840,19 +1251,13 @@ 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 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, r => r, @@ -866,17 +1271,42 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> if p.late.load(Ordering::Acquire) { return pso; } - p.want(); + 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); + 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; `wanted` drops when the wait + // 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 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(); + drop(budget_guard); 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 }