From 40a14da3716bc28d0c34c86928de987a473192bb Mon Sep 17 00:00:00 2001 From: throny <11830644+throny@users.noreply.github.com> Date: Fri, 27 Nov 2026 03:45:56 +0100 Subject: [PATCH] Shaders: the preparation trusts the driver blobs it checked before At every launch the preparation workers created each used compute pipeline from its stored driver blob only to run its check (the driver makes a pipeline from the blob and returns a blob of the same size), and dropped it. Creating a pipeline from a blob is not free: on an RTX 4080 (driver 621.40) it was measured to cost as much as compiling it, and the preparation took 7-8 minutes at every launch, also right after a launch that had completed it (186 of 192 slow creations in two launches were such hits). A blob that passed that check, or that was just written, now gets a marker beside it (`.ok`: the driver's identity, the blob's length and a digest of its bytes). A later pass counts a record whose blob still matches its marker as prepared without creating the pipeline. This is the same check as before, so it changes when the check runs, not what it proves (it does not show that the driver used the blob). A blob that changed, also at the same length, is checked the old way and repaired; a blob the driver refuses is removed together with its marker. XCL_PREPARE_VERIFY=1 checks every blob again. Assisted-by: Claude Code (Claude Fable 5.2; first version written by a Claude Sonnet 5.5 sub-agent, reviewed by a Claude Opus 5.5 sub-agent) Co-Authored-By: Claude Fable 5.2 --- README.md | 6 ++ crates/xcl/src/hle/d3d12x/real.rs | 79 ++++++++++++++++++++++++- crates/xcl/src/shaders.rs | 92 ++++++++++++++++++++++++++++- crates/xcl/tests/gpu_compute_e2e.rs | 36 +++++++++-- 4 files changed, 203 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 973a027e86..46843b466a 100644 --- a/README.md +++ b/README.md @@ -260,6 +260,12 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. 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). +- **Verified compute blobs**: a driver blob that passed the preparation's check (the driver made a + pipeline from it and returned a blob of the same size) is marked (`.ok`, with the driver's + identity, the blob's length and a digest of its bytes), and later launches do not create its + pipeline again (creating one is not free and on some driver setups has been measured to cost as + much as compiling it). It is the check every launch applied before, so this changes when it + runs, not what it proves. `XCL_PREPARE_VERIFY=1` checks every blob again. - **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/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 570ef64a10..6d473a7f01 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5275,7 +5275,7 @@ pub(crate) mod driver_cache { } } else { if let Some(p) = p { - let _ = std::fs::remove_file(p); + remove(p); } if STALE.fetch_add(1, Ordering::Relaxed) == 0 { crate::xlog_info!("D3D12.X: a driver blob kept on disk was refused (another driver or adapter?) – such pipelines are compiled again"); @@ -5319,6 +5319,49 @@ pub(crate) mod driver_cache { ok } + /// The marker of the blob `p`: the same name with `.ok` after it. + fn marker(p: &Path) -> PathBuf { + let mut m = p.as_os_str().to_owned(); + m.push(".ok"); + PathBuf::from(m) + } + + /// `{identity} {len} {digest}`: the driver, and the blob's length and `fnv64` digest. + fn marker_text(identity: u64, len: u64, digest: u64) -> String { + format!("{identity:016x} {len} {digest:016x}\n") + } + + /// The blob `p` and its marker, gone (the driver refused it). + pub fn remove(p: &Path) { + let _ = std::fs::remove_file(p); + let _ = std::fs::remove_file(marker(p)); + } + + /// The blob `p` (its content is `bytes`) passed the preparation's check for the driver of + /// `identity`: the driver made a pipeline from it and returned a blob of the same size. A later + /// pass need not create that pipeline again (creating one from its blob is not free and on some + /// driver setups has been measured to cost as much as compiling it); it is the check every + /// launch applied before, so this changes when it runs, not what it proves. The marker records + /// the bytes' length and digest. + pub fn mark_verified(p: &Path, identity: u64, bytes: &[u8]) { + write(&marker(p), marker_text(identity, bytes.len() as u64, crate::gpu::shader::fnv64(bytes)).as_bytes()); + } + + /// The blob `p` passed the preparation's check for the driver of `identity` (see + /// `mark_verified`) and is still the file it was: the + /// marker's identity matches, the file's length is the marker's, and the bytes read from the + /// file have the marker's digest. The marker covers the adapter and driver version and the + /// blob's bytes, not a D3D12 runtime or OS update; a blob the driver later refuses in the + /// title is removed with its marker there, and `XCL_PREPARE_VERIFY=1` checks all again. + pub fn verified(p: &Path, identity: u64) -> bool { + let Ok(text) = std::fs::read_to_string(marker(p)) else { return false }; + let Ok(meta) = std::fs::metadata(p) else { return false }; + let Some(rest) = text.strip_prefix(&format!("{identity:016x} {} ", meta.len())) else { return false }; + let Ok(digest) = u64::from_str_radix(rest.trim(), 16) else { return false }; + let Ok(bytes) = std::fs::read(p) else { return false }; + text == marker_text(identity, bytes.len() as u64, digest) && crate::gpu::shader::fnv64(&bytes) == digest + } + /// Keep `blob`, of a compute pipeline's build that took `took`, for the next run /// (`compute_keep_threshold`). pub fn keep(p: &Path, blob: &[u8], took: std::time::Duration) { @@ -5389,6 +5432,38 @@ pub(crate) mod driver_cache { let _ = std::fs::remove_dir_all(&dir); } + /// A blob that passed the check is marked; the marker counts for that driver and that file only, + /// and goes with the blob when the driver refuses it. + #[test] + fn a_verified_blob_is_trusted_until_it_changes_or_is_refused() { + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-verified-{}", std::process::id())); + let _directory = Directory(dir.clone()); + let p = dir.join(name(b"program", 0)); + assert!(!verified(&p, 7), "no blob, no marker"); + assert!(write(&p, &[1, 2, 3])); + assert!(!verified(&p, 7), "a blob nobody verified"); + mark_verified(&p, 7, &[1, 2, 3]); + assert!(verified(&p, 7)); + assert!(!verified(&p, 8), "another adapter or driver"); + assert!(write(&p, &[1, 2, 3, 4])); + assert!(!verified(&p, 7), "the blob's length is not the marker's"); + mark_verified(&p, 7, &[1, 2, 3, 4]); + assert!(verified(&p, 7)); + assert!(write(&p, &[0, 0, 0, 0])); + assert!(!verified(&p, 7), "same length, other bytes"); + mark_verified(&p, 7, &[0, 0, 0, 0]); + assert!(verified(&p, 7)); + assert!(write(&p, &[1, 2, 3, 4])); + mark_verified(&p, 7, &[1, 2, 3, 4]); + std::fs::remove_file(&p).unwrap(); + assert!(!verified(&p, 7), "the blob is missing"); + assert!(write(&p, &[1, 2, 3, 4])); + assert!(verified(&p, 7)); + note(false, Some(&p)); + assert!(!p.exists() && !marker(&p).exists(), "the refused blob's marker goes with it"); + assert!(!verified(&p, 7)); + } + /// A compute build of 20 ms or more keeps its file (it was 250 ms, as for the others, and /// `XCL_PSO_DISK_CACHE_MIN_MS` did not reach it); the switch chooses for both. #[test] @@ -7208,7 +7283,7 @@ pub fn driver_cache_stats() -> (u64, u64, u64) { /// one's blob (it is compiled again), and two adapters sharing the cache (a GPU and the /// software one) would take turns overwriting each other's files. None: not known (no blob of /// its pipelines is kept on disk). -fn driver_identity(device: *mut c_void) -> Option { +pub(crate) fn driver_identity(device: *mut c_void) -> Option { use windows::Win32::Graphics::Dxgi::*; let dev = unsafe { ID3D12Device::from_raw_borrowed(&device) }?; let luid = unsafe { dev.GetAdapterLuid() }; diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 67fb3e0dcb..f7cfe02a7d 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1226,6 +1226,12 @@ struct Pipelines { made: AtomicUsize, refused: AtomicUsize, reused: AtomicUsize, + /// blobs that passed the check in an earlier pass (`driver_cache::verified`): not created again + trusted: AtomicUsize, + /// the adapter's and driver's identity for the markers (None: not known, none is trusted) + identity: Option, + /// `XCL_PREPARE_VERIFY=1`: create the pipeline of every blob again, markers or not + verify: bool, /// pipelines another process of the same preparation was building (`Claim`): left to it elsewhere: AtomicUsize, split_programs: AtomicUsize, @@ -1305,6 +1311,58 @@ mod pipeline_cap_tests { assert!(!path.exists(), "rejected blob should not be retried next run"); } + /// The pass that made a blob marks it; the next pass counts it as trusted and creates nothing, + /// and with `verify` it creates the pipeline from the blob again. + #[test] + fn a_second_pass_trusts_the_blobs_the_first_verified() { + use super::{Pipelines, recomp, Ordering}; + use crate::hle::d3d12x::real::driver_cache; + + 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 Some(identity) = pipelines.identity else { + recomp::runner::skip_test("no adapter identity"); + return; + }; + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let scratch = Scratch(std::env::temp_dir().join(format!("xcl-trusted-pso-{}-{nonce}", std::process::id()))); + std::fs::create_dir(&scratch.0).expect("scratch cache directory"); + pipelines.cache_dir = Some(scratch.0.clone()); + pipelines.verify = false; + let dxil = recomp::dxc::compile( + "RWByteAddressBuffer mem : register(u2); [numthreads(1,1,1)] void main() { mem.Store(0, 5); }", + "main", + "cs_6_6", + &[], + ) + .expect("DXC compile"); + let compiled = recomp::pso::Compiled { dispatch_chain: None, dxil: dxil.clone(), samplers: vec![] }; + let path = scratch.0.join(driver_cache::name_for(&dxil, 0, false)); + pipelines.make(&compiled); + assert_eq!(pipelines.made.load(Ordering::Relaxed), 1); + assert!(driver_cache::verified(&path, identity), "a blob the driver just made is marked"); + pipelines.make(&compiled); + assert_eq!(pipelines.trusted.load(Ordering::Relaxed), 1); + assert_eq!((pipelines.made.load(Ordering::Relaxed), pipelines.reused.load(Ordering::Relaxed)), (1, 0), "nothing created"); + pipelines.verify = true; + pipelines.make(&compiled); + assert_eq!((pipelines.made.load(Ordering::Relaxed), pipelines.reused.load(Ordering::Relaxed)), (2, 1), "created from the blob again"); + assert_eq!(pipelines.trusted.load(Ordering::Relaxed), 1); + } + #[test] fn split_compute_program_prebuilds_and_caches_chain_pieces() { use super::{Pipelines, recomp, Ordering}; @@ -1391,7 +1449,9 @@ mod pipeline_cap_tests { assert!(p1_path.is_file() && p1_path.metadata().unwrap().len() > 0, "piece 1 .chain.pso missing"); assert!(!whole_path.exists(), "unsplit whole .pso should not be written for a split compute program"); - // Second pass reuses both cached piece blobs. + // Second pass reuses both cached piece blobs (the markers would skip them: see + // `a_second_pass_trusts_the_blobs_the_first_verified`). + pipelines.verify = true; pipelines.make(&compiled); assert_eq!(pipelines.reused.load(Ordering::Relaxed), 2); assert_eq!(pipelines.made.load(Ordering::Relaxed), 4); @@ -1448,12 +1508,19 @@ impl Pipelines { }; let most = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4usize).max(1); let max_dxil = pipeline_cap_kb(std::env::var("XCL_PIPELINE_MAX_KB").ok().as_deref()).saturating_mul(1024); + let identity = { + use windows::core::Interface; + crate::hle::d3d12x::real::driver_identity(dev.as_raw()) + }; Ok(Pipelines { dev, signatures: Mutex::new(Default::default()), made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), + trusted: AtomicUsize::new(0), + identity, + verify: std::env::var("XCL_PREPARE_VERIFY").is_ok_and(|v| v.trim() == "1"), elsewhere: AtomicUsize::new(0), split_programs: AtomicUsize::new(0), split_pieces: AtomicUsize::new(0), @@ -1543,6 +1610,16 @@ impl Pipelines { } driver_cache::path_for(dxil, desc.Flags.0, chained) }); + // a blob that passed the check in an earlier pass (a pipeline made from it, a blob of the same + // size returned; the check every launch applied before): creating its pipeline again is not + // free (on some driver setups it has been measured to cost as much as a compile) + if let (Some(path), Some(identity), false) = (path.as_deref(), self.identity, self.verify) { + if driver_cache::verified(path, identity) { + self.trusted.fetch_add(1, Ordering::Relaxed); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + return; + } + } let mut cached = path.as_deref().and_then(driver_cache::load); let over_cap = self.max_dxil != 0 && dxil.len() > self.max_dxil; // over the cap and no blob from an earlier run: the driver's compile of this one takes @@ -1593,7 +1670,7 @@ impl Pipelines { // 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); + driver_cache::remove(path); } *self.running.0.lock().unwrap() -= 1; self.running.1.notify_one(); @@ -1604,6 +1681,9 @@ impl Pipelines { } let r = if let Some(pso) = from_cache { self.reused.fetch_add(1, Ordering::Relaxed); + if let (Some(path), Some(identity), Some(bytes)) = (path.as_deref(), self.identity, &cached) { + driver_cache::mark_verified(path, identity, bytes); + } Ok(pso) } else { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); @@ -1613,7 +1693,12 @@ impl Pipelines { 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) }); + let written = unsafe { std::slice::from_raw_parts(bytes, len) }; + if driver_cache::write(path, written) { + if let Some(identity) = self.identity { + driver_cache::mark_verified(path, identity, written); + } + } } } } @@ -2254,6 +2339,7 @@ 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)); + println!("pipelines whose blob an earlier pass verified, not created again {} (XCL_PREPARE_VERIFY=1: create them)", p.trusted.load(Ordering::Relaxed)); println!("pipelines left to another process that was building them {}", p.elsewhere.load(Ordering::Relaxed)); let split_programs = p.split_programs.load(Ordering::Relaxed); if split_programs != 0 { diff --git a/crates/xcl/tests/gpu_compute_e2e.rs b/crates/xcl/tests/gpu_compute_e2e.rs index 5ffa519a96..c92ec245f5 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -155,8 +155,9 @@ fn split_compute_prefers_the_offline_whole_pipeline() { // Seed the ordinary whole PSO offline, then force the runtime to choose between it and a split chain. run(Command::new(env!("CARGO_BIN_EXE_xcl")).arg("shaders").arg(&input).args(["--precompile","--pipelines"]) .env("XCL_DIRECT_SPLIT_INSTRUCTIONS","12500")); - let mut files = fs::read_dir(cache.join("driver")).unwrap(); - let blob = files.next().unwrap().unwrap().path(); + let mut files = fs::read_dir(cache.join("driver")).unwrap().flatten().map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|ext| ext == "pso")); + let blob = files.next().unwrap(); assert!(files.next().is_none() && blob.metadata().unwrap().len() > 0); for case in ["hit","stale","miss"] { if case == "stale" { fs::write(&blob, b"rejected driver cache fixture").unwrap(); } @@ -189,7 +190,8 @@ fn offline_compute_pipeline_is_reused_by_a_second_process() { let out = Command::new(env!("CARGO_BIN_EXE_xcl")).arg("shaders").arg(&input) .args(["--precompile", "--pipelines"]).env("XCL_DXIL_CACHE", &cache) .env("TMP", &dir).env("TEMP", &dir).env("XCL_DXIL_DUMP", "all") - .env("XCL_PSO_DISK_CACHE", if enabled { "1" } else { "0" }).output().unwrap(); + .env("XCL_PSO_DISK_CACHE", if enabled { "1" } else { "0" }) + .env("XCL_PREPARE_VERIFY", "1").output().unwrap(); let text = String::from_utf8_lossy(&out.stdout).into_owned(); assert!(out.status.success() && text.contains("pipelines made on the GPU 1, refused 0"), "{text}\n{}", String::from_utf8_lossy(&out.stderr)); text @@ -212,8 +214,30 @@ fn offline_compute_pipeline_is_reused_by_a_second_process() { assert!(stale.contains("pipelines loaded from the driver cache 0"), "{stale}"); let repaired = run(true); assert!(repaired.contains("pipelines loaded from the driver cache 1"), "{repaired}"); - let _ = fs::remove_dir_all(&dir); assert!(warm.contains("pipelines loaded from the driver cache 1"), "{warm}"); + // Without the switch the blob the last pass verified is trusted: its pipeline is not created again. + let run_trusting = || { + let out = Command::new(env!("CARGO_BIN_EXE_xcl")).arg("shaders").arg(&input) + .args(["--precompile", "--pipelines"]).env("XCL_DXIL_CACHE", &cache) + .env("TMP", &dir).env("TEMP", &dir).env("XCL_PSO_DISK_CACHE", "1") + .env_remove("XCL_PREPARE_VERIFY").output().unwrap(); + let text = String::from_utf8_lossy(&out.stdout).into_owned(); + assert!(out.status.success(), "{text}\n{}", String::from_utf8_lossy(&out.stderr)); + text + }; + let trusted_text = run_trusting(); + assert!(trusted_text.contains("pipelines whose blob an earlier pass verified, not created again 1"), "{trusted_text}"); + assert!(trusted_text.contains("pipelines made on the GPU 0, refused 0"), "{trusted_text}"); + // A blob overwritten with other bytes of the same length is not trusted: the pipeline is made again. + let len = driver_file.metadata().unwrap().len() as usize; + fs::write(&driver_file, vec![0u8; len]).unwrap(); + let overwritten = run_trusting(); + assert!(overwritten.contains("pipelines whose blob an earlier pass verified, not created again 0"), "{overwritten}"); + assert!(overwritten.contains("pipelines made on the GPU 1,"), "{overwritten}"); + assert!(fs::read(&driver_file).unwrap().iter().any(|b| *b != 0), "the blob was written again"); + let again = run_trusting(); + assert!(again.contains("pipelines whose blob an earlier pass verified, not created again 1"), "{again}"); + let _ = fs::remove_dir_all(&dir); } /// Wave32 compute program with conditional branches across distinct basic blocks so direct @@ -275,6 +299,7 @@ fn offline_split_compute_pipeline_is_reused_by_a_second_process() { .env("XCL_DIRECT_DXIL", "1") .env("XCL_DIRECT_SPLIT_INSTRUCTIONS", "12") .env("XCL_PSO_DISK_CACHE", "1") + .env("XCL_PREPARE_VERIFY", "1") .output() .unwrap(); let text = String::from_utf8_lossy(&out.stdout).into_owned(); @@ -282,7 +307,8 @@ fn offline_split_compute_pipeline_is_reused_by_a_second_process() { text }; let cold = run(); - let mut files: Vec<_> = fs::read_dir(cache.join("driver")).unwrap().flatten().map(|e| e.path()).collect(); + let mut files: Vec<_> = fs::read_dir(cache.join("driver")).unwrap().flatten().map(|e| e.path()) + .filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.ends_with(".chain.pso"))).collect(); files.sort(); let pieces = files.len(); assert!(pieces >= 2, "expected >= 2 split piece blobs in driver cache, got {files:?}\n{cold}");