Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
44 changes: 32 additions & 12 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3598,7 +3598,7 @@ fn pso_trace() -> bool {
fn driver_compile_identified<R>(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;
Expand Down Expand Up @@ -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<SlotGuard> {
const LOOK: std::time::Duration = std::time::Duration::from_millis(50);
let slot = {
Expand All @@ -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::<MEMORYSTATUSEX>() as u32;
unsafe { GlobalMemoryStatusEx(&mut m) == 0 || m.ullAvailPageFile >= 3 << 30 }
unsafe { GlobalMemoryStatusEx(&mut m) == 0 || m.ullAvailPageFile >= need }
}

#[cfg(test)]
Expand Down Expand Up @@ -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 };
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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());
}
Expand Down
118 changes: 113 additions & 5 deletions crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1116,16 +1116,88 @@ 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<std::collections::HashMap<Vec<u32>, 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<usize>, 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);
}

#[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
Expand All @@ -1141,12 +1213,17 @@ 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 })
}
}

/// 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<PathBuf>) {
use windows::Win32::Graphics::Direct3D12::*;
let key: Vec<u32> = c.samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect();
let rs = {
Expand All @@ -1170,20 +1247,47 @@ 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 = 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() && 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));
return;
}
{
let mut n = self.running.0.lock().unwrap();
while *n >= self.most {
n = self.running.1.wait(n).unwrap();
}
*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::<ID3D12PipelineState>(&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::<ID3D12PipelineState>(&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)
Expand Down Expand Up @@ -1340,6 +1444,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, 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}");
Expand Down
Loading