Skip to content
Draft
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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`<blob>.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.
Expand Down
79 changes: 77 additions & 2 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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<u64> {
pub(crate) fn driver_identity(device: *mut c_void) -> Option<u64> {
use windows::Win32::Graphics::Dxgi::*;
let dev = unsafe { ID3D12Device::from_raw_borrowed(&device) }?;
let luid = unsafe { dev.GetAdapterLuid() };
Expand Down
92 changes: 89 additions & 3 deletions crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u64>,
/// `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,
Expand Down Expand Up @@ -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};
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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();
Expand All @@ -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();
Expand All @@ -1613,7 +1693,12 @@ impl Pipelines {
let bytes = unsafe { blob.GetBufferPointer() }.cast::<u8>();
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);
}
}
}
}
}
Expand Down Expand Up @@ -2254,6 +2339,7 @@ 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));
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 {
Expand Down
Loading
Loading