diff --git a/README.md b/README.md index 2a957e95e..0ad65ee1e 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,7 @@ xcl inspect D:\Game\game.exe # the game's imports and what XCL has xcl run D:\Game [-- game arguments] # run xcl disasm [--hex] # RDNA2 disassembler (console containers too) xcl shaders D:\data\shaders.rpf --top 50 # pack statistics; --recomp / --compile N +xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines # build compute pipelines and save driver blobs for the next run xcl rpf D:\data\shaders.rpf --extract NAME --out folder ``` diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index aed907586..93d956482 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3435,7 +3435,7 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi /// its flags (`\driver\`) and read when a later run has none in memory; the /// driver refuses the blob of another driver, adapter or root signature (the file is dropped /// and the program compiled as before). `XCL_PSO_DISK_CACHE=0`: off. -mod driver_cache { +pub(crate) mod driver_cache { use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -3476,16 +3476,36 @@ mod driver_cache { } } + fn create_staging_file(p: &Path) -> std::io::Result<(PathBuf, std::fs::File)> { + static NEXT: AtomicU64 = AtomicU64::new(0); + create_staging_file_with(p, &NEXT) + } + + fn create_staging_file_with(p: &Path, next: &AtomicU64) -> std::io::Result<(PathBuf, std::fs::File)> { + loop { + let tmp = p.with_extension(format!("tmp{}-{}", std::process::id(), next.fetch_add(1, Ordering::Relaxed))); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp) { + Ok(file) => return Ok((tmp, file)), + // A prior process with this PID may have left a file behind. It is not ours. + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + } + } + /// `bytes` to `p`, under another name first: a run that is cut short leaves no half file. pub fn write(p: &Path, bytes: &[u8]) -> bool { + use std::io::Write; if bytes.is_empty() { return false; } if let Some(dir) = p.parent() { let _ = std::fs::create_dir_all(dir); } - let tmp = p.with_extension(format!("tmp{}", std::process::id())); - let ok = std::fs::write(&tmp, bytes).is_ok() && std::fs::rename(&tmp, p).is_ok(); + let Ok((tmp, mut file)) = create_staging_file(p) else { return false }; + let written = file.write_all(bytes).is_ok(); + drop(file); + let ok = written && std::fs::rename(&tmp, p).is_ok(); if !ok { let _ = std::fs::remove_file(&tmp); } @@ -3506,6 +3526,11 @@ mod driver_cache { mod tests { use super::*; + struct Directory(PathBuf); + impl Drop for Directory { + fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } + } + #[test] fn a_file_is_named_after_its_dxil_and_flags() { assert_eq!(name(b"abc", 0), name(b"abc", 0)); @@ -3534,6 +3559,44 @@ mod driver_cache { assert_eq!(load(&p), None); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn an_overlapping_writer_cannot_modify_the_published_blob() { + use std::io::Write; + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-overlap-{}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let p = dir.join("program.pso"); + // Another writer, paused after the production staging-file creation step. + let (_other_tmp, mut other) = create_staging_file(&p).unwrap(); + let complete = b"complete second blob"; + assert!(write(&p, complete)); + assert_eq!(load(&p).as_deref(), Some(complete.as_slice())); + // Resuming the older writer must not change a file already published by this + // invocation, even when the older payload is shorter than the newer one. + other.write_all(b"old").unwrap(); + assert_eq!(load(&p).as_deref(), Some(complete.as_slice()), "published bytes must not alias another writer's staging file"); + } + + #[test] + fn an_abandoned_staging_file_is_skipped_and_preserved() { + use std::io::Write; + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-stale-{}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let p = dir.join("program.pso"); + let occupied = p.with_extension(format!("tmp{}-0", std::process::id())); + std::fs::write(&occupied, b"not ours").unwrap(); + let next = AtomicU64::new(0); + let (tmp, mut file) = create_staging_file_with(&p, &next).unwrap(); + assert_eq!(next.load(Ordering::Relaxed), 2, "the occupied candidate was passed over"); + assert_ne!(tmp, occupied); + file.write_all(b"ours").unwrap(); + drop(file); + std::fs::rename(&tmp, &p).unwrap(); + assert_eq!(load(&p).as_deref(), Some(b"ours".as_slice())); + assert_eq!(std::fs::read(&occupied).unwrap(), b"not ours"); + } } } diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 5c3027d7b..db0c70049 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -734,14 +734,14 @@ pub fn run(path: &Path, args: &[String]) -> i32 { /// different at run time: a PS's static samplers after its VS's (sampler base 0 here) and the /// mesh pass-through, which the runtime builds for its pixel shader. /// `--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): the driver keeps what it compiled in its own -/// cache, which the title then finds – a retail game's 1 MB-DXIL programs kept its loading -/// waiting for the driver's compiler for minutes. Nothing runs on the GPU. +/// 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. struct Pipelines { dev: windows::Win32::Graphics::Direct3D12::ID3D12Device, signatures: Mutex, windows::Win32::Graphics::Direct3D12::ID3D12RootSignature>>, made: AtomicUsize, refused: AtomicUsize, + reused: 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), @@ -761,7 +761,7 @@ 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), running: (Mutex::new(0), std::sync::Condvar::new()), most }) + 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 }) } } @@ -785,7 +785,7 @@ impl Pipelines { }, } }; - let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::ManuallyDrop::new(Some(rs)), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: c.dxil.as_ptr() as *const _, BytecodeLength: c.dxil.len() }, ..Default::default() @@ -797,7 +797,30 @@ impl Pipelines { } *n += 1; } - let r: windows::core::Result = unsafe { self.dev.CreateComputePipelineState(&desc) }; + 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() + }); + 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(); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); @@ -934,6 +957,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)); } for e in errors.into_inner().unwrap() { println!(" {e}"); diff --git a/crates/xcl/tests/gpu_compute_e2e.rs b/crates/xcl/tests/gpu_compute_e2e.rs index 587c489ae..7b9a2490e 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -81,6 +81,49 @@ fn console_cs(code: &[u8], rsrc2: u32, threads: [u32; 3]) -> Vec { const V: u64 = 256; // VALU source code of v0 +#[test] +fn offline_compute_pipeline_is_reused_by_a_second_process() { + use std::{fs, process::Command}; + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + if xcl::gpu::recomp::dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + if runner::wave64_programs_supported() != Ok(true) { + runner::skip_test("no GPU with 32- or 64-lane waves"); + return; + } + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("xcl-offline-pso-{}-{nonce}", std::process::id())); + let input = dir.join("input"); + let cache = dir.join("cache"); + fs::create_dir_all(&input).unwrap(); + fs::write(input.join("kernel.bin"), console_cs(&program(), 2 << 1 | 1 << 7 | 1 << 8 | 1 << 11, [16, 8, 1])).unwrap(); + let run = |enabled: bool| { + let out = Command::new(env!("CARGO_BIN_EXE_xcl")).arg("shaders").arg(&input) + .args(["--precompile", "--pipelines"]).env("XCL_DXIL_CACHE", &cache) + .env("XCL_PSO_DISK_CACHE", if enabled { "1" } else { "0" }).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 + }; + run(false); + assert!(!cache.join("driver").exists()); + run(true); + let dxil_file = fs::read_dir(&cache).unwrap().flatten().map(|e| e.path()) + .find(|p| p.extension().is_some_and(|ext| ext == "dxil")).unwrap(); + let dxil = fs::read(dxil_file).unwrap(); + let name = format!("{:016x}-{:x}-0.pso", xcl::gpu::shader::fnv64(&dxil), dxil.len()); + let driver_file = cache.join("driver").join(name); + assert!(driver_file.metadata().unwrap().len() > 0); + let warm = run(true); + // A blob from an earlier driver can be refused. The normal build must still succeed. + fs::write(&driver_file, b"invalid cached pipeline").unwrap(); + run(true); + let _ = fs::remove_dir_all(&dir); + assert!(warm.contains("pipelines loaded from the driver cache 1"), "{warm}"); +} + /// 16×8 threads per group (two wave64s), s[0:1] = output base and row width, TGID_X/Y in /// s2/s3, thread ids in v0/v1: each thread writes its global (x, y), and through LDS + /// s_barrier the (x, y) of the thread at the mirrored index, which is in the other wave.