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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <shader.bin> [--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
```

Expand Down
69 changes: 66 additions & 3 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3435,7 +3435,7 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi
/// its flags (`<DXIL cache>\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};

Expand Down Expand Up @@ -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);
}
Expand All @@ -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));
Expand Down Expand Up @@ -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");
}
}
}

Expand Down
36 changes: 30 additions & 6 deletions crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::collections::HashMap<Vec<u32>, 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<usize>, std::sync::Condvar),
Expand All @@ -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 })
}
}

Expand All @@ -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()
Expand All @@ -797,7 +797,30 @@ impl Pipelines {
}
*n += 1;
}
let r: windows::core::Result<ID3D12PipelineState> = 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::<ID3D12PipelineState>(&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::<ID3D12PipelineState>(&desc) };
if let (Some(path), Ok(pso)) = (path.as_deref(), &pso) {
if let Ok(blob) = unsafe { pso.GetCachedBlob() } {
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) });
}
}
}
pso
};
*self.running.0.lock().unwrap() -= 1;
self.running.1.notify_one();
drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature));
Expand Down Expand Up @@ -934,6 +957,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));
}
for e in errors.into_inner().unwrap() {
println!(" {e}");
Expand Down
43 changes: 43 additions & 0 deletions crates/xcl/tests/gpu_compute_e2e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,49 @@ fn console_cs(code: &[u8], rsrc2: u32, threads: [u32; 3]) -> Vec<u8> {

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.
Expand Down
Loading