diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 3582764a6..c7c4a4ace 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3542,6 +3542,18 @@ fn huge_pso_concurrency() -> usize { *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_CONCURRENCY").ok().as_deref(), 1, 1, 64)) } +/// Hard cap on concurrent huge (`>= 256 KB`) driver compiles even when wanted by a title bind +/// (`XCL_HUGE_PSO_WANTED_CONCURRENCY`, default 2, always `>= huge_pso_concurrency()`). Prevents a +/// burst of lazy compute binds from launching 10+ huge driver compiles simultaneously and spiking +/// process commit into OOM, while still letting a wanted build overtake 1 background build. +fn huge_pso_wanted_concurrency() -> usize { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| { + let base = huge_pso_concurrency(); + env_count(std::env::var("XCL_HUGE_PSO_WANTED_CONCURRENCY").ok().as_deref(), base.max(2), base, 64) + }) +} + /// A count from the environment: `default` when unset or not a number, clamped to the /// inclusive range `min..=max`. fn env_count(v: Option<&str>, default: usize, min: usize, max: usize) -> usize { @@ -3549,17 +3561,22 @@ fn env_count(v: Option<&str>, default: usize, min: usize, max: usize) -> usize { } /// A counting semaphore: background driver compiles of big programs at once (`most` 0: the -/// `huge_pso_concurrency` of the environment). +/// `huge_pso_concurrency` of the environment; `wanted_most` 0: `huge_pso_wanted_concurrency`). struct Slots { n: Mutex, cv: std::sync::Condvar, most: usize, + wanted_most: usize, } impl Slots { fn most(&self) -> usize { if self.most == 0 { huge_pso_concurrency() } else { self.most } } + + fn wanted_most(&self) -> usize { + if self.wanted_most == 0 { huge_pso_wanted_concurrency() } else { self.wanted_most } + } } struct SlotGuard(&'static Slots); @@ -3567,13 +3584,13 @@ struct SlotGuard(&'static Slots); impl Drop for SlotGuard { fn drop(&mut self) { *self.0.n.lock().unwrap() -= 1; - self.0.cv.notify_one(); + self.0.cv.notify_all(); } } -static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 0 }; +static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 0, wanted_most: 0 }; const GIANT_DRIVER_COMPILE: usize = 4 << 20; -static GIANT_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1 }; +static GIANT_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 1 }; fn compile_slots(bytes: usize) -> &'static Slots { if bytes >= GIANT_DRIVER_COMPILE { &GIANT_COMPILES } else { &BIG_COMPILES } @@ -3598,7 +3615,7 @@ fn pso_trace() -> bool { fn driver_compile_identified(kind: &str, bytes: usize, gate: bool, record: Option<(u64, bool)>, build: impl FnOnce() -> R) -> (R, std::time::Duration) { let huge = gate && bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); let waited = std::time::Instant::now(); - let slot = huge.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)).flatten(); + let _slot = huge.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)); let waited = waited.elapsed(); static SEQUENCE: AtomicU64 = AtomicU64::new(0); let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1; @@ -3613,18 +3630,17 @@ fn driver_compile_identified(kind: &str, bytes: usize, gate: bool, record: Op let r = build(); let took = started.elapsed(); if log { - crate::xlog_info!("D3D12.X: driver compile finish #{sequence}: {kind} PSO, {bytes} B DXIL, {} ms{}", took.as_millis(), gate_note(bytes >= huge_pso_bytes(), huge, slot.is_some(), waited)); + crate::xlog_info!("D3D12.X: driver compile finish #{sequence}: {kind} PSO, {bytes} B DXIL, {} ms{}", took.as_millis(), gate_note(bytes >= huge_pso_bytes(), huge, waited)); } (r, took) } /// How a logged driver compile went through the huge-pipeline gate. -fn gate_note(huge_size: bool, gated: bool, had_slot: bool, waited: std::time::Duration) -> String { - match (huge_size, gated, had_slot) { - (false, _, _) => String::new(), - (true, true, true) => format!(", gated (waited {} ms)", waited.as_millis()), - (true, true, false) => ", huge, wanted at once (no slot)".to_string(), - (true, false, _) => ", huge, ungated here (a title thread's, cached, or gated by its caller)".to_string(), +fn gate_note(huge_size: bool, gated: bool, waited: std::time::Duration) -> String { + match (huge_size, gated) { + (false, _) => String::new(), + (true, true) => format!(", gated (waited {} ms)", waited.as_millis()), + (true, false) => ", huge, ungated here (a title thread's, cached, or gated by its caller)".to_string(), } } @@ -3634,36 +3650,25 @@ fn gate_compute_driver_compile(has_cached_blob: bool) -> bool { !has_cached_blob } -/// Before a big driver compile in the background: its turn – at most the configured number at -/// once, and the commit headroom it asks for (`commit_free`, from `big_compile_headroom`; the -/// title loading next to it must not run out). Unless one of the title's threads waits for the -/// pipeline (`wanted`): then at once and without a slot (None), as when that thread builds it -/// itself. Holding such a build back holds the title back: on a machine with less than the -/// headroom free throughout a retail title's world loading, the first one would not go on and -/// keeps the slot, until the title's watchdog ends it. -fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wanted: impl Fn() -> bool) -> Option { +/// Before a big driver compile in the background: its turn – unwanted builds wait for both +/// `slots.most()` and commit headroom (`commit_free`, from `big_compile_headroom`) before taking a +/// slot so an unwanted commit-blocked compile never starves a wanted build. When a title thread +/// waits for the pipeline (`wanted`), it bypasses the commit wait and can use up to +/// `slots.wanted_most()` (default 2 for `>= 256 KB`, 1 for `>= 4 MiB` giant shaders) so a wanted +/// build is not stuck behind 1 background build while a burst of lazy binds still cannot spike +/// driver compiler commit into OOM. +fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wanted: impl Fn() -> bool) -> SlotGuard { const LOOK: std::time::Duration = std::time::Duration::from_millis(50); - let slot = { - let mut n = slots.n.lock().unwrap(); - loop { - if wanted() { - return None; - } - if *n < slots.most() { - break; - } - n = slots.cv.wait_timeout(n, LOOK).unwrap().0; + let mut n = slots.n.lock().unwrap(); + loop { + let is_wanted = wanted(); + let cap = if is_wanted { slots.wanted_most() } else { slots.most() }; + if *n < cap && (is_wanted || commit_free()) { + *n += 1; + return SlotGuard(slots); } - *n += 1; - SlotGuard(slots) - }; - while !commit_free() { - if wanted() { - return None; - } - std::thread::sleep(LOOK); + n = slots.cv.wait_timeout(n, LOOK).unwrap().0; } - Some(slot) } /// Commit headroom a big driver compile waits for: 3 GB for the class that starts at @@ -3690,32 +3695,85 @@ mod big_compile_tests { use std::time::{Duration, Instant}; #[test] - fn a_wanted_build_waits_for_neither_the_slot_nor_the_commit() { - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1 }; - let held = big_compile_turn(&S, || true, || false).expect("a free slot"); + fn wanted_builds_bypass_commit_and_unwanted_slot_but_respect_hard_cap() { + static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 2 }; + let held = big_compile_turn(&S, || true, || false); assert_eq!(*S.n.lock().unwrap(), 1); - // the slot is taken: a wanted build goes on without one, at once - assert!(big_compile_turn(&S, || true, || true).is_none()); - // … and one that becomes wanted while it waits for the slot goes on then - static WANTED: AtomicBool = AtomicBool::new(false); - let t = std::thread::spawn(|| big_compile_turn(&S, || true, || WANTED.load(Ordering::Acquire)).is_none()); + // Unwanted slot is full, but a wanted build immediately takes the 2nd (wanted) slot and + // bypasses the commit-free check. + let held_wanted = big_compile_turn(&S, || false, || true); + assert_eq!(*S.n.lock().unwrap(), 2); + // A 3rd wanted build MUST wait while both slots are occupied (hard cap = 2). + let t = std::thread::spawn(|| { + let _g = big_compile_turn(&S, || false, || true); + }); std::thread::sleep(Duration::from_millis(120)); - assert!(!t.is_finished(), "not wanted yet: it waits for its turn"); - WANTED.store(true, Ordering::Release); - assert!(t.join().unwrap()); + assert!(!t.is_finished(), "3rd concurrent wanted huge compile must wait for hard cap"); + drop(held_wanted); + t.join().unwrap(); drop(held); assert_eq!(*S.n.lock().unwrap(), 0); - // without the commit: not wanted, it waits; wanted, it goes on and gives the slot back + // Without commit free: an unwanted build waits without holding a slot until it becomes + // wanted, then acquires a slot and proceeds. static WANTED2: AtomicBool = AtomicBool::new(false); let t0 = Instant::now(); - let t = std::thread::spawn(|| big_compile_turn(&S, || false, || WANTED2.load(Ordering::Acquire)).is_none()); + let t = std::thread::spawn(|| { + let _g = big_compile_turn(&S, || false, || WANTED2.load(Ordering::Acquire)); + }); std::thread::sleep(Duration::from_millis(120)); - assert!(!t.is_finished(), "no commit free: it waits"); + assert!(!t.is_finished(), "no commit free: unwanted build waits"); + assert_eq!(*S.n.lock().unwrap(), 0, "unwanted commit-blocked build must not hold a slot"); WANTED2.store(true, Ordering::Release); - assert!(t.join().unwrap() && t0.elapsed() < Duration::from_secs(5)); + t.join().unwrap(); + assert!(t0.elapsed() < Duration::from_secs(5)); assert_eq!(*S.n.lock().unwrap(), 0, "the slot went back"); } + #[test] + fn unwanted_commit_waiter_does_not_starve_wanted_compile() { + // Mirrors GIANT_COMPILES (`most == 1, wanted_most == 1`) under low commit (< 3 GiB): + // an unwanted compile waiting on commit headroom must never hold the slot and deadlock a + // wanted compile. + static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 1 }; + static FREE: AtomicBool = AtomicBool::new(false); + let bg = std::thread::spawn(|| { + let _g = big_compile_turn(&S, || FREE.load(Ordering::Acquire), || false); + }); + std::thread::sleep(Duration::from_millis(120)); + assert!(!bg.is_finished(), "unwanted compile waits for commit"); + assert_eq!(*S.n.lock().unwrap(), 0, "unwanted compile must not hold slot while commit-blocked"); + let t0 = Instant::now(); + let wanted = big_compile_turn(&S, || false, || true); + assert!(t0.elapsed() < Duration::from_secs(1), "wanted compile must acquire slot immediately"); + assert_eq!(*S.n.lock().unwrap(), 1); + drop(wanted); + FREE.store(true, Ordering::Release); + bg.join().unwrap(); + assert_eq!(*S.n.lock().unwrap(), 0); + } + + #[test] + fn wanted_burst_is_hard_capped_to_wanted_most() { + use std::sync::atomic::AtomicUsize; + static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 2 }; + static IN: AtomicUsize = AtomicUsize::new(0); + static PEAK: AtomicUsize = AtomicUsize::new(0); + let t: Vec<_> = (0..12) + .map(|_| { + std::thread::spawn(|| { + let _g = big_compile_turn(&S, || false, || true); + let now = IN.fetch_add(1, Ordering::SeqCst) + 1; + PEAK.fetch_max(now, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(15)); + IN.fetch_sub(1, Ordering::SeqCst); + }) + }) + .collect(); + t.into_iter().for_each(|h| h.join().unwrap()); + assert_eq!(PEAK.load(Ordering::SeqCst), 2, "12 concurrent wanted huge compiles must cap at 2"); + assert_eq!(*S.n.lock().unwrap(), 0); + } + #[test] fn env_counts_parse() { assert_eq!(env_count(None, 2, 1, 64), 2); @@ -3729,10 +3787,9 @@ mod big_compile_tests { #[test] fn only_huge_compiles_get_a_gate_note() { let ms = Duration::from_millis(5); - assert_eq!(gate_note(false, false, false, ms), "", "a small compile (XCL_PSO_TRACE) is not called huge"); - assert_eq!(gate_note(true, true, true, ms), ", gated (waited 5 ms)"); - assert!(gate_note(true, true, false, ms).contains("wanted at once")); - assert!(gate_note(true, false, false, ms).contains("ungated here")); + assert_eq!(gate_note(false, false, ms), "", "a small compile (XCL_PSO_TRACE) is not called huge"); + assert_eq!(gate_note(true, true, ms), ", gated (waited 5 ms)"); + assert!(gate_note(true, false, ms).contains("ungated here")); } #[test] @@ -3750,7 +3807,7 @@ mod big_compile_tests { #[test] fn the_concurrency_limit_holds_and_all_finish() { use std::sync::atomic::AtomicUsize; - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 2 }; + static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 2, wanted_most: 2 }; static IN: AtomicUsize = AtomicUsize::new(0); static PEAK: AtomicUsize = AtomicUsize::new(0); // the two holders of the slots meet here: both are inside at once, deterministically @@ -3758,7 +3815,7 @@ mod big_compile_tests { let t: Vec<_> = (0..8) .map(|_| { std::thread::spawn(|| { - let _g = big_compile_turn(&S, || true, || false).expect("a turn"); + let _g = big_compile_turn(&S, || true, || false); let now = IN.fetch_add(1, Ordering::SeqCst) + 1; PEAK.fetch_max(now, Ordering::SeqCst); BOTH.wait(); @@ -3779,8 +3836,8 @@ mod big_compile_tests { // every slot taken: a small compile on a worker, and a huge one on an unnamed (title) // thread, both go on at once // (both lanes: a huge compile of any size would block on a gate it should bypass) - let mut held: Vec<_> = (0..huge_pso_concurrency()).map(|_| big_compile_turn(&BIG_COMPILES, || true, || false).unwrap()).collect(); - held.push(big_compile_turn(&GIANT_COMPILES, || true, || false).unwrap()); + let mut held: Vec<_> = (0..huge_pso_concurrency()).map(|_| big_compile_turn(&BIG_COMPILES, || true, || false)).collect(); + held.push(big_compile_turn(&GIANT_COMPILES, || true, || false)); let small = std::thread::Builder::new() .name("xcl-pso-test".into()) .spawn(|| driver_compile("test", huge_pso_bytes() - 1, true, || 7)) @@ -3807,13 +3864,15 @@ mod big_compile_tests { #[test] fn unwanted_builds_go_one_at_a_time_when_the_commit_is_there() { - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1 }; - let first = big_compile_turn(&S, || true, || false).expect("its turn"); - let t = std::thread::spawn(|| big_compile_turn(&S, || true, || false).is_some()); + static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 2 }; + let first = big_compile_turn(&S, || true, || false); + let t = std::thread::spawn(|| { + let _g = big_compile_turn(&S, || true, || false); + }); std::thread::sleep(Duration::from_millis(120)); assert!(!t.is_finished(), "one at a time"); drop(first); - assert!(t.join().unwrap(), "the next one's turn"); + t.join().unwrap(); assert_eq!(*S.n.lock().unwrap(), 0); } } @@ -5142,9 +5201,9 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: 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")); let waited = std::time::Instant::now(); - let _slot = gate.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)).flatten(); + let _slot = gate.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)); if gate { - crate::xlog_info!("D3D12.X: two-pass {kind} PSO ({bytes} B DXIL) gated: {}, waited {} ms", _slot.is_some(), waited.elapsed().as_millis()); + 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)); if hr < 0 {