diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 76f31d4daf..15d861adc7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3962,13 +3962,13 @@ unsafe fn abi_rs_raw(this: *mut c_void) -> Option<*mut c_void> { /// for one of the `XCL_HUGE_PSO_CONCURRENCY` slots. NVIDIA's compiler (nvgpucomp64) takes /// minutes and ~1 GB for a 1 – 2 MB program; ~20 of them at once (one per worker) were slower /// in total than 1 – 2 at a time. Small programs (ms each) never wait. -fn huge_pso_bytes() -> usize { +pub(crate) fn huge_pso_bytes() -> usize { static V: std::sync::OnceLock = std::sync::OnceLock::new(); *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_BYTES").ok().as_deref(), 256 << 10, 1, usize::MAX)) } /// Huge driver compiles at once on the workers (default 1, `XCL_HUGE_PSO_CONCURRENCY`). -fn huge_pso_concurrency() -> usize { +pub(crate) fn huge_pso_concurrency() -> usize { static V: std::sync::OnceLock = std::sync::OnceLock::new(); *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_CONCURRENCY").ok().as_deref(), 1, 1, 64)) } @@ -4020,7 +4020,7 @@ impl Drop for SlotGuard { } 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; +pub(crate) const GIANT_DRIVER_COMPILE: usize = 4 << 20; 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 { @@ -4107,12 +4107,12 @@ fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wante /// of it — the driver's compile of a 29.8 MB program grew past 14 GB free before it was stopped /// (#1269), and programs of ~1 MB took several GB each on an 8 GB card (same issue). The floor /// leaves every program up to 6 MiB of DXIL waiting for exactly what it waited for before. -fn big_compile_headroom(dxil_len: usize) -> u64 { +pub(crate) fn big_compile_headroom(dxil_len: usize) -> u64 { (3u64 << 30).max(dxil_len as u64 * 512) } /// That much commit is free (true when that is not known). -fn big_compile_commit_free(need: u64) -> bool { +pub(crate) fn big_compile_commit_free(need: u64) -> bool { use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; m.dwLength = std::mem::size_of::() as u32; diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 0cd2ed7b3a..ef3dafc949 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1217,12 +1217,145 @@ struct Pipelines { /// biggest takes ~1.5 GB in the driver – fifteen at once took 24 GB running: (Mutex, std::sync::Condvar), most: usize, + /// concurrency and commit-headroom gate for uncached large DXIL driver compiles + gate: OfflineGate, /// DXIL bytes a pipeline is still handed to the driver (`XCL_PIPELINE_MAX_KB`, 8 MiB; 0: off) max_dxil: usize, #[cfg(test)] cache_dir: Option, } +#[derive(Default)] +struct OfflineGateState { + active_cold: usize, + active_huge: usize, + active_giant: usize, +} + +/// Concurrency and commit-headroom gate for uncached offline `--pipelines` builds. +/// Serializes giant compiles (`>= giant_bytes`), caps huge compiles (`>= huge_bytes`) to +/// `huge_most`, and waits for `big_compile_headroom` free commit while any other cold +/// compile is active. When `active_cold == 0`, a sole huge/giant compile proceeds so low +/// host commit never deadlocks progress. +struct OfflineGate { + state: Mutex, + cv: std::sync::Condvar, + huge_bytes: usize, + huge_most: usize, + giant_bytes: usize, +} + +struct OfflineGateGuard<'a> { + gate: &'a OfflineGate, + is_huge: bool, + is_giant: bool, +} + +impl Drop for OfflineGateGuard<'_> { + fn drop(&mut self) { + let mut s = self.gate.state.lock().unwrap(); + s.active_cold -= 1; + if self.is_huge { + s.active_huge -= 1; + } + if self.is_giant { + s.active_giant -= 1; + } + self.gate.cv.notify_all(); + } +} + +impl OfflineGate { + fn from_env() -> Self { + use crate::hle::d3d12x::real; + Self::new(real::huge_pso_bytes(), real::huge_pso_concurrency(), real::GIANT_DRIVER_COMPILE) + } + + fn new(huge_bytes: usize, huge_most: usize, giant_bytes: usize) -> Self { + Self { + state: Mutex::new(OfflineGateState::default()), + cv: std::sync::Condvar::new(), + huge_bytes, + huge_most: huge_most.max(1), + giant_bytes, + } + } + + fn enter(&self, dxil_len: usize, commit_free: impl Fn(u64) -> bool) -> OfflineGateGuard<'_> { + let is_giant = dxil_len >= self.giant_bytes; + let is_huge = dxil_len >= self.huge_bytes; + let need = crate::hle::d3d12x::real::big_compile_headroom(dxil_len); + let mut s = self.state.lock().unwrap(); + loop { + let blocked_by_size = if is_giant { + s.active_giant >= 1 || s.active_huge > 0 + } else if is_huge { + s.active_giant > 0 || s.active_huge >= self.huge_most + } else { + false + }; + let blocked_by_commit = is_huge && s.active_cold > 0 && !commit_free(need); + if !blocked_by_size && !blocked_by_commit { + s.active_cold += 1; + if is_huge { + s.active_huge += 1; + } + if is_giant { + s.active_giant += 1; + } + return OfflineGateGuard { gate: self, is_huge, is_giant }; + } + s = self.cv.wait_timeout(s, std::time::Duration::from_millis(50)).unwrap().0; + } + } +} + +struct RunningSlot<'a>(&'a (Mutex, std::sync::Condvar)); + +impl Drop for RunningSlot<'_> { + fn drop(&mut self) { + *self.0 .0.lock().unwrap() -= 1; + self.0 .1.notify_one(); + } +} + +fn acquire_running(running: &(Mutex, std::sync::Condvar), most: usize) -> RunningSlot<'_> { + let mut n = running.0.lock().unwrap(); + while *n >= most { + n = running.1.wait(n).unwrap(); + } + *n += 1; + RunningSlot(running) +} + +#[allow(clippy::too_many_arguments)] +fn build_with_gate( + gate: &OfflineGate, + running: &(Mutex, std::sync::Condvar), + most: usize, + dxil_len: usize, + over_cap: bool, + cached: Option<&[u8]>, + ctx: &mut C, + commit_free: impl Fn(u64) -> bool, + mut try_cached: impl FnMut(&mut C, &[u8]) -> Option

, + mut on_stale: impl FnMut(), + mut cold_build: impl FnMut(&mut C) -> Result, +) -> Option<(Result, bool)> { + let _gate = gate.enter(dxil_len, commit_free); + let _slot = acquire_running(running, most); + if let Some(bytes) = cached { + if let Some(pso) = try_cached(ctx, bytes) { + return Some((Ok(pso), true)); + } + on_stale(); + if over_cap { + return None; + } + } + Some((cold_build(ctx), false)) +} + /// `XCL_PIPELINE_MAX_KB`: the KiB of DXIL `--pipelines` still compiles (default 8 MiB; 0: no /// cap). Above it sit the programs whose driver compile takes tens of minutes and gigabytes — /// the > 8 MB HLSL programs DXC compiles at `-O0` (#1269) — and they hang the pass. @@ -1407,6 +1540,152 @@ mod pipeline_cap_tests { } } +#[cfg(test)] +mod offline_gate_tests { + use super::OfflineGate; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{mpsc, Arc}; + use std::time::{Duration, Instant}; + + #[test] + fn offline_gate_serializes_huge_compiles_while_small_compiles_proceed() { + let gate = Arc::new(OfflineGate::new(256 << 10, 1, 4 << 20)); + let first = gate.enter(512 << 10, |_| true); + // Small DXIL builds proceed immediately alongside an active huge build. + let small = gate.enter(64 << 10, |_| false); + drop(small); + + let (tx, rx) = mpsc::channel(); + let gate2 = gate.clone(); + let second = std::thread::spawn(move || { + let _g = gate2.enter(512 << 10, |_| true); + let _ = tx.send(()); + }); + std::thread::sleep(Duration::from_millis(120)); + assert!(rx.try_recv().is_err(), "second huge compile should wait for the first"); + drop(first); + rx.recv_timeout(Duration::from_secs(5)).expect("second huge compile proceeds"); + second.join().unwrap(); + } + + #[test] + fn offline_gate_waits_for_headroom_while_another_compile_is_active_and_avoids_deadlock_when_alone() { + let gate = Arc::new(OfflineGate::new(256 << 10, 2, 4 << 20)); + let active_small = gate.enter(64 << 10, |_| true); + let commit_ok = Arc::new(AtomicBool::new(false)); + let commit_ok2 = commit_ok.clone(); + let (tx, rx) = mpsc::channel(); + let gate2 = gate.clone(); + let huge = std::thread::spawn(move || { + let _g = gate2.enter(1 << 20, |_| commit_ok2.load(Ordering::Acquire)); + let _ = tx.send(()); + }); + std::thread::sleep(Duration::from_millis(120)); + assert!(rx.try_recv().is_err(), "huge compile should wait for commit headroom while another compile is active"); + drop(active_small); + // With no other cold compile in flight, the sole huge compile must proceed despite commit_free == false. + rx.recv_timeout(Duration::from_secs(5)).expect("sole huge compile should not deadlock on low commit"); + huge.join().unwrap(); + let _ = commit_ok; + } + + #[test] + fn offline_gate_runs_giant_compile_alone_even_with_higher_huge_concurrency() { + let gate = Arc::new(OfflineGate::new(256 << 10, 2, 4 << 20)); + let huge = gate.enter(1 << 20, |_| true); + let (tx_giant, rx_giant) = mpsc::channel(); + let gate2 = gate.clone(); + let t0 = Instant::now(); + let giant_thread = std::thread::spawn(move || { + let _g = gate2.enter(4 << 20, |_| true); + let _ = tx_giant.send(()); + std::thread::sleep(Duration::from_millis(120)); + }); + std::thread::sleep(Duration::from_millis(120)); + assert!(rx_giant.try_recv().is_err(), "giant compile should wait until active huge compiles finish"); + drop(huge); + rx_giant.recv_timeout(Duration::from_secs(5)).expect("giant compile proceeds once alone"); + // While giant is running, another huge compile must also wait. + let (tx_huge2, rx_huge2) = mpsc::channel(); + let gate3 = gate.clone(); + let huge2_thread = std::thread::spawn(move || { + let _g = gate3.enter(1 << 20, |_| true); + let _ = tx_huge2.send(()); + }); + std::thread::sleep(Duration::from_millis(50)); + assert!(rx_huge2.try_recv().is_err(), "huge compile should wait for active giant compile"); + giant_thread.join().unwrap(); + rx_huge2.recv_timeout(Duration::from_secs(5)).expect("huge compile proceeds after giant"); + huge2_thread.join().unwrap(); + assert!(t0.elapsed() < Duration::from_secs(5)); + } + + #[test] + fn offline_gate_serializes_giant_cached_probe_fallback() { + use super::{build_with_gate, OfflineGate}; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::{Arc, Condvar, Mutex}; + use std::time::Duration; + + let gate = Arc::new(OfflineGate::new(256 << 10, 2, 4 << 20)); + let running = Arc::new((Mutex::new(0usize), Condvar::new())); + let active = Arc::new(AtomicUsize::new(0)); + let peak_concurrent = Arc::new(AtomicUsize::new(0)); + let stale_calls = Arc::new(AtomicUsize::new(0)); + let cold_calls = Arc::new(AtomicUsize::new(0)); + + let mut threads = Vec::new(); + for _ in 0..2 { + let g = gate.clone(); + let r = running.clone(); + let a = active.clone(); + let p = peak_concurrent.clone(); + let s = stale_calls.clone(); + let c = cold_calls.clone(); + threads.push(std::thread::spawn(move || { + let mut seen = AtomicBool::new(false); + let out = build_with_gate::<(), u32, ()>( + &g, + &r, + 4, + 4 << 20, + false, + Some(b"stale-blob"), + &mut (), + |_| true, + |_, _| { + let cur = a.fetch_add(1, Ordering::SeqCst) + 1; + p.fetch_max(cur, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(80)); + a.fetch_sub(1, Ordering::SeqCst); + *seen.get_mut() = true; + None + }, + || { + s.fetch_add(1, Ordering::SeqCst); + }, + |_| { + let cur = a.fetch_add(1, Ordering::SeqCst) + 1; + p.fetch_max(cur, Ordering::SeqCst); + c.fetch_add(1, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(30)); + a.fetch_sub(1, Ordering::SeqCst); + Ok(7) + }, + ); + assert!(seen.into_inner()); + assert_eq!(out, Some((Ok(7), false))); + })); + } + for t in threads { + t.join().unwrap(); + } + assert_eq!(peak_concurrent.load(Ordering::SeqCst), 1, "giant cached probes and their cold fallbacks must serialize under OfflineGate"); + assert_eq!(stale_calls.load(Ordering::SeqCst), 2); + assert_eq!(cold_calls.load(Ordering::SeqCst), 2); + } +} + // D3D12 devices and root signatures are free-threaded unsafe impl Sync for Pipelines {} @@ -1433,6 +1712,7 @@ impl Pipelines { capped_bytes: AtomicUsize::new(0), running: (Mutex::new(0), std::sync::Condvar::new()), most, + gate: OfflineGate::from_env(), max_dxil, #[cfg(test)] cache_dir: None, @@ -1526,53 +1806,51 @@ impl Pipelines { drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); return; } - { - let mut n = self.running.0.lock().unwrap(); - while *n >= self.most { - n = self.running.1.wait(n).unwrap(); - } - *n += 1; - } - let from_cache = cached.as_ref().and_then(|bytes| { - desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: bytes.as_ptr().cast(), CachedBlobSizeInBytes: bytes.len() }; - // a driver that cannot use the blob may compile from the DXIL itself and still - // return Ok: only the pipeline carrying a blob of the size we handed over is a hit - unsafe { self.dev.CreateComputePipelineState::(&desc) } - .ok() - .filter(|pso| unsafe { pso.GetCachedBlob() }.is_ok_and(|b| unsafe { b.GetBufferSize() } == bytes.len())) - }); - // A stale blob is not a usable cache hit. Do not let its presence bypass the offline - // size cap and start the expensive uncached driver compile. - if cached.is_some() && from_cache.is_none() && over_cap { - if let Some(path) = path.as_deref() { - let _ = std::fs::remove_file(path); - } - *self.running.0.lock().unwrap() -= 1; - self.running.1.notify_one(); + let Some((r, from_cache)) = build_with_gate( + &self.gate, + &self.running, + self.most, + dxil.len(), + over_cap, + cached.as_deref(), + &mut desc, + crate::hle::d3d12x::real::big_compile_commit_free, + |d, bytes| { + d.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: bytes.as_ptr().cast(), CachedBlobSizeInBytes: bytes.len() }; + // a driver that cannot use the blob may compile from the DXIL itself and still + // return Ok: only the pipeline carrying a blob of the size we handed over is a hit + unsafe { self.dev.CreateComputePipelineState::(d) } + .ok() + .filter(|pso| unsafe { pso.GetCachedBlob() }.is_ok_and(|b| unsafe { b.GetBufferSize() } == bytes.len())) + }, + || { + if let Some(path) = path.as_deref() { + let _ = std::fs::remove_file(path); + } + }, + |d| { + d.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + let pso = unsafe { self.dev.CreateComputePipelineState::(d) }; + if let (Some(path), Ok(pso)) = (path.as_deref(), &pso) { + if let Ok(blob) = unsafe { pso.GetCachedBlob() } { + let bytes = unsafe { blob.GetBufferPointer() }.cast::(); + let len = unsafe { blob.GetBufferSize() }; + if !bytes.is_null() && len != 0 { + driver_cache::write(path, unsafe { std::slice::from_raw_parts(bytes, len) }); + } + } + } + pso + }, + ) else { self.capped.fetch_add(1, Ordering::Relaxed); self.capped_bytes.fetch_add(dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); return; - } - let r = if let Some(pso) = from_cache { - self.reused.fetch_add(1, Ordering::Relaxed); - Ok(pso) - } else { - desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); - let pso = unsafe { self.dev.CreateComputePipelineState::(&desc) }; - if let (Some(path), Ok(pso)) = (path.as_deref(), &pso) { - if let Ok(blob) = unsafe { pso.GetCachedBlob() } { - let bytes = unsafe { blob.GetBufferPointer() }.cast::(); - let len = unsafe { blob.GetBufferSize() }; - if !bytes.is_null() && len != 0 { - driver_cache::write(path, unsafe { std::slice::from_raw_parts(bytes, len) }); - } - } - } - pso }; - *self.running.0.lock().unwrap() -= 1; - self.running.1.notify_one(); + if from_cache { + self.reused.fetch_add(1, Ordering::Relaxed); + } drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); let done = match r { Ok(_) => self.made.fetch_add(1, Ordering::Relaxed) + 1,