From 28946bb1276baffcee7483f6ba19fb0753c4d2ec Mon Sep 17 00:00:00 2001 From: Brandon Strong Date: Tue, 24 Nov 2026 11:35:58 -0800 Subject: [PATCH 1/3] D3D12.X: big driver compiles wait for commit headroom sized by their DXIL The 3 GB floor was measured on the 256 KiB class (~1.5 GB each in the driver). The programs at the other end are a different order: the driver compile of a 29.8 MB program grew past 14 GB of free commit before it was stopped, and ~1 MB programs took several GB each on an 8 GB card (xcl-dev/xcl#1269). Ask for max(3 GB, 512x DXIL size), so a giant program waits for headroom instead of exhausting commit next to a loading title. Programs up to 6 MiB of DXIL wait for exactly what they waited for before. Part of xcl-dev/xcl#1269 (A19). Co-Authored-By: Claude Code --- crates/xcl/src/hle/d3d12x/real.rs | 44 ++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index fed31e6224..9e38009a3f 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3598,7 +3598,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, 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)).flatten(); let waited = waited.elapsed(); static SEQUENCE: AtomicU64 = AtomicU64::new(0); let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1; @@ -3635,12 +3635,12 @@ fn gate_compute_driver_compile(has_cached_blob: bool) -> bool { } /// Before a big driver compile in the background: its turn – at most the configured number at -/// once, and 3 GB of commit -/// free (each takes ~1.5 GB; 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 3 GB of commit 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. +/// 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 { const LOOK: std::time::Duration = std::time::Duration::from_millis(50); let slot = { @@ -3666,12 +3666,21 @@ fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wante Some(slot) } -/// 3 GB of commit are free (true when that is not known). -fn big_compile_commit_free() -> bool { +/// Commit headroom a big driver compile waits for: 3 GB for the class that starts at +/// `huge_pso_bytes()` (each takes ~1.5 GB in the driver), and ~512× the DXIL size above 6 MiB +/// 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 { + (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 { use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; m.dwLength = std::mem::size_of::() as u32; - unsafe { GlobalMemoryStatusEx(&mut m) == 0 || m.ullAvailPageFile >= 3 << 30 } + unsafe { GlobalMemoryStatusEx(&mut m) == 0 || m.ullAvailPageFile >= need } } #[cfg(test)] @@ -3785,6 +3794,17 @@ mod big_compile_tests { drop(held); } + #[test] + fn headroom_is_the_3_gb_floor_until_512_times_the_dxil_exceeds_it() { + // the class from huge_pso_bytes() up to 6 MiB of DXIL: the floor, unchanged + assert_eq!(big_compile_headroom(huge_pso_bytes()), 3 << 30); + assert_eq!(big_compile_headroom(6 << 20), 3 << 30); + // above it the wait scales with the program: the 29.8 MB one that grew past 14 GB of + // free commit (#1269) waits for 15 GB + assert_eq!(big_compile_headroom(8 << 20), 4 << 30); + assert_eq!(big_compile_headroom(29_800_000), 29_800_000u64 * 512); + } + #[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 }; @@ -3850,7 +3870,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const if let Some(b) = &cached { copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; } - // in the background, a few at a time and within the commit left (each ~1.5 GB in the driver) + // in the background, a few at a time and within the commit headroom the program asks for let record = crate::gpu::shader::fnv64(cs); let (mut hr, mut in_driver) = driver_compile_identified( "compute", @@ -4766,7 +4786,7 @@ 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, 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)).flatten(); if gate { crate::xlog_info!("D3D12.X: two-pass {kind} PSO ({bytes} B DXIL) gated: {}, waited {} ms", _slot.is_some(), waited.elapsed().as_millis()); } From cbff0b8c09e240f33acb86db4b7e213966392641 Mon Sep 17 00:00:00 2001 From: Brandon Strong Date: Tue, 24 Nov 2026 11:35:59 -0800 Subject: [PATCH 2/3] Shaders: --pipelines leaves compute programs over the DXIL cap to the runtime The precompile pass stopped advancing on the biggest compute programs: their driver compile takes tens of minutes and gigabytes (three of 29-30 MB DXIL hung --precompile --only cs --pipelines for 33+ minutes on three machines, xcl-dev/xcl#744). Skip programs whose DXIL is over XCL_PIPELINE_MAX_KB (8 MiB by default; 0 turns the cap off) when no blob exists yet, count them, and report the total; the runtime still builds one when a title needs the pipeline. 8 MiB sits above the largest program that ever completes (~2.2 MB, the optimized class) and below the smallest that hangs (14.1 MB), so the pass now finishes. Part of xcl-dev/xcl#1269 (A19). Co-Authored-By: Claude Code --- README.md | 4 +++ crates/xcl/src/shaders.rs | 52 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e35903a1cf..a8649600e5 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,10 @@ xcl shaders D:\data\shaders.rpf --measure-pso HEX --repeat 3 # cold driv xcl rpf D:\data\shaders.rpf --extract NAME --out folder ``` +- **`--pipelines` size cap**: a compute program whose DXIL is over 8 MiB and that has no saved + blob is left to the runtime instead of being compiled in the pass — those compiles take tens + of minutes and gigabytes and stopped the pass on the biggest programs. `XCL_PIPELINE_MAX_KB` + sets the cap in KiB (0 turns it off). - **Without a command line** (xcl.exe opened from Explorer) XCL shows a small menu: *Choose a game…* (pick its exe or `MicrosoftGame.config`) or *Run again* (the last one). On an error the window stays open until Enter. diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 92c04341d4..c51926341b 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1116,16 +1116,46 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl /// `--pipelines`: each compute program's pipeline made on the GPU as a title's would be (XCL's /// ABI root signature with its static samplers). Save the driver's compiled blob in the same /// cache the runtime reads at startup. Nothing runs on the GPU. +/// Programs whose DXIL is over `XCL_PIPELINE_MAX_KB` (8 MiB by default; 0 turns the cap off) +/// and that have no blob yet are counted as capped and left to the runtime: their driver +/// compile takes tens of minutes and gigabytes, and stopped the pass on the biggest programs +/// (the > 8 MB HLSL programs DXC compiles at `-O0`, #1269). struct Pipelines { dev: windows::Win32::Graphics::Direct3D12::ID3D12Device, signatures: Mutex, windows::Win32::Graphics::Direct3D12::ID3D12RootSignature>>, made: AtomicUsize, refused: AtomicUsize, reused: AtomicUsize, + /// programs over `max_dxil` with no blob yet, and their DXIL bytes + capped: AtomicUsize, + capped_bytes: AtomicUsize, /// driver compiles running and the most at once (`XCL_PIPELINE_THREADS`, 4): each of the /// biggest takes ~1.5 GB in the driver – fifteen at once took 24 GB running: (Mutex, std::sync::Condvar), most: usize, + /// DXIL bytes a pipeline is still handed to the driver (`XCL_PIPELINE_MAX_KB`, 8 MiB; 0: off) + max_dxil: usize, +} + +/// `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. +fn pipeline_cap_kb(set: Option<&str>) -> usize { + set.and_then(|v| v.parse().ok()).unwrap_or(8192) +} + +#[cfg(test)] +mod pipeline_cap_tests { + use super::pipeline_cap_kb; + + #[test] + fn the_cap_is_8_mib_unless_set_and_off_at_zero() { + assert_eq!(pipeline_cap_kb(None), 8192); + assert_eq!(pipeline_cap_kb(Some("512")), 512); + assert_eq!(pipeline_cap_kb(Some("0")), 0); + // not a number: the default, not a crash + assert_eq!(pipeline_cap_kb(Some("off")), 8192); + } } // D3D12 devices and root signatures are free-threaded @@ -1141,7 +1171,8 @@ impl Pipelines { let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?; let most = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4usize).max(1); - Ok(Pipelines { dev, signatures: Mutex::new(Default::default()), made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), running: (Mutex::new(0), std::sync::Condvar::new()), most }) + let max_dxil = pipeline_cap_kb(std::env::var("XCL_PIPELINE_MAX_KB").ok().as_deref()).saturating_mul(1024); + Ok(Pipelines { dev, signatures: Mutex::new(Default::default()), made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), capped: AtomicUsize::new(0), capped_bytes: AtomicUsize::new(0), running: (Mutex::new(0), std::sync::Condvar::new()), most, max_dxil }) } } @@ -1170,6 +1201,18 @@ impl Pipelines { CS: D3D12_SHADER_BYTECODE { pShaderBytecode: c.dxil.as_ptr() as *const _, BytecodeLength: c.dxil.len() }, ..Default::default() }; + use crate::hle::d3d12x::real::driver_cache; + let path = driver_cache::path(&c.dxil, desc.Flags.0); + let cached = path.as_deref().and_then(driver_cache::load); + // over the cap and no blob from an earlier run: the driver's compile of this one takes + // tens of minutes and gigabytes; the pass finishes without it, and the runtime builds it + // when a title needs the pipeline. `XCL_PIPELINE_MAX_KB` 0 turns the cap off. + if cached.is_none() && self.max_dxil != 0 && c.dxil.len() > self.max_dxil { + self.capped.fetch_add(1, Ordering::Relaxed); + self.capped_bytes.fetch_add(c.dxil.len(), Ordering::Relaxed); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + return; + } { let mut n = self.running.0.lock().unwrap(); while *n >= self.most { @@ -1177,9 +1220,6 @@ impl Pipelines { } *n += 1; } - use crate::hle::d3d12x::real::driver_cache; - let path = driver_cache::path(&c.dxil, desc.Flags.0); - let cached = path.as_deref().and_then(driver_cache::load); let from_cache = cached.as_ref().and_then(|bytes| { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: bytes.as_ptr().cast(), CachedBlobSizeInBytes: bytes.len() }; unsafe { self.dev.CreateComputePipelineState::(&desc) }.ok() @@ -1340,6 +1380,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on if let Some(p) = pipelines { println!("pipelines made on the GPU {}, refused {}", p.made.load(Ordering::Relaxed), p.refused.load(Ordering::Relaxed)); println!("pipelines loaded from the driver cache {}", p.reused.load(Ordering::Relaxed)); + let capped = p.capped.load(Ordering::Relaxed); + if capped != 0 { + println!("pipelines over the {} MiB DXIL cap, left to the runtime: {} ({} MiB of DXIL; XCL_PIPELINE_MAX_KB)", p.max_dxil >> 20, capped, p.capped_bytes.load(Ordering::Relaxed) >> 20); + } } for e in errors.into_inner().unwrap() { println!(" {e}"); From 6b9b14fd636ae26152c02eeb8c0f34c51bbd55f7 Mon Sep 17 00:00:00 2001 From: Brandon Strong Date: Tue, 24 Nov 2026 13:46:57 -0800 Subject: [PATCH 3/3] Shaders: a stale driver blob cannot let an over-cap program past the cap The --pipelines cap only gated programs with no saved blob: a blob the driver rejects (after an adapter or driver change) fell through to the uncached compile, recompiling exactly the giant programs the cap exists to skip. NVIDIA drivers showed both faces: a hard reject (Err) when cold, and an Ok with an internal recompile when their own cache had the result - the latter looked like a blob hit and bypassed the cap too. A blob attempt now counts as a hit only when the pipeline carries a blob of the size handed to it; a miss over the cap removes the stale file, counts the program as capped, and returns before the uncached compile. Diagnosis, regression test and the first version of the fix from WebIdentity1 in #1774 (tested on an RTX 3090); the hit-detection filter and the Ok-with-internal-fallback case added here (RTX 4090). Co-Authored-By: Claude Code --- crates/xcl/src/shaders.rs | 70 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 67 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index c51926341b..35f3e95a8d 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1156,6 +1156,48 @@ mod pipeline_cap_tests { // not a number: the default, not a crash assert_eq!(pipeline_cap_kb(Some("off")), 8192); } + + #[test] + fn stale_blob_cannot_bypass_the_offline_pipeline_cap() { + use super::{Pipelines, recomp, Ordering}; + use std::time::{Instant, SystemTime, UNIX_EPOCH}; + + struct Scratch(std::path::PathBuf); + impl Drop for Scratch { + fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } + } + if let Err(reason) = recomp::dxc::location() { + recomp::runner::skip_test(&format!("no DXC: {reason}")); + return; + } + let mut pipelines = match Pipelines::new() { + Ok(pipelines) => pipelines, + Err(reason) => { + recomp::runner::skip_test(&format!("no D3D12 device: {reason}")); + return; + } + }; + let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let scratch = Scratch(std::env::temp_dir().join(format!("xcl-stale-pso-{}-{nonce}", std::process::id()))); + std::fs::create_dir(&scratch.0).expect("scratch cache directory"); + let hlsl = "RWByteAddressBuffer mem : register(u2); [numthreads(1,1,1)] void main() { mem.Store(0, 42); }"; + let dxil = recomp::dxc::compile(hlsl, "main", "cs_6_6", &[]).expect("DXC compile"); + let path = scratch.0.join("stale.pso"); + std::fs::write(&path, b"deliberately invalid cached PSO").expect("stale blob"); + + pipelines.max_dxil = dxil.len() - 1; + let start = Instant::now(); + pipelines.make_with_cache_path(&recomp::pso::Compiled { dxil: dxil.clone(), samplers: vec![] }, Some(path.clone())); + let elapsed = start.elapsed(); + let capped = pipelines.capped.load(Ordering::Relaxed); + let made = pipelines.made.load(Ordering::Relaxed); + let refused = pipelines.refused.load(Ordering::Relaxed); + let output = recomp::runner::dispatch(&dxil, [1, 1, 1], &[], &[0; 64]).expect("runtime GPU dispatch"); + println!("adapter={} dxil_bytes={} offline_ms={} capped={} made={} refused={} gpu_word0={}", recomp::runner::adapter().unwrap_or_default(), dxil.len(), elapsed.as_millis(), capped, made, refused, output[0]); + assert_eq!(output[0], 42); + assert_eq!((capped, made, refused), (1, 0, 0)); + assert!(!path.exists(), "rejected blob should not be retried next run"); + } } // D3D12 devices and root signatures are free-threaded @@ -1178,6 +1220,10 @@ impl Pipelines { /// The compute pipeline of `c` (made and released). fn make(&self, c: &recomp::pso::Compiled) { + self.make_with_cache_path(c, None); + } + + fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option) { use windows::Win32::Graphics::Direct3D12::*; let key: Vec = c.samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect(); let rs = { @@ -1202,12 +1248,13 @@ impl Pipelines { ..Default::default() }; use crate::hle::d3d12x::real::driver_cache; - let path = driver_cache::path(&c.dxil, desc.Flags.0); + let path = path_override.or_else(|| driver_cache::path(&c.dxil, desc.Flags.0)); let cached = path.as_deref().and_then(driver_cache::load); + let over_cap = self.max_dxil != 0 && c.dxil.len() > self.max_dxil; // over the cap and no blob from an earlier run: the driver's compile of this one takes // tens of minutes and gigabytes; the pass finishes without it, and the runtime builds it // when a title needs the pipeline. `XCL_PIPELINE_MAX_KB` 0 turns the cap off. - if cached.is_none() && self.max_dxil != 0 && c.dxil.len() > self.max_dxil { + if cached.is_none() && over_cap { self.capped.fetch_add(1, Ordering::Relaxed); self.capped_bytes.fetch_add(c.dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); @@ -1222,8 +1269,25 @@ impl Pipelines { } let from_cache = cached.as_ref().and_then(|bytes| { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: bytes.as_ptr().cast(), CachedBlobSizeInBytes: bytes.len() }; - unsafe { self.dev.CreateComputePipelineState::(&desc) }.ok() + // 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(); + self.capped.fetch_add(1, Ordering::Relaxed); + self.capped_bytes.fetch_add(c.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)