Skip to content
Open
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
68 changes: 64 additions & 4 deletions crates/xcl/src/gpu/recomp/dxc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -816,13 +816,32 @@ fn cache_mutex_name(file: &Path) -> String {
format!(r"Local\XclDxilCache-{h:016x}")
}

fn normalized_cache_dir(dir: &Path) -> PathBuf {
if let Ok(canonical) = std::fs::canonicalize(dir) {
/// Canonicalize `dir` (or its deepest existing ancestor) for cache mutex/flight keys.
/// Keys the in-memory cache by `std::path::absolute(dir)` so relative `XCL_DXIL_CACHE` paths
/// still resolve cleanly if the process working directory changes. Mid-process symlink or
/// junction re-pointing of an already-cached directory is not handled.
fn normalized_cache_dir_in(
cache: &Mutex<HashMap<PathBuf, PathBuf>>,
dir: &Path,
canonicalize: impl Fn(&Path) -> std::io::Result<PathBuf>,
) -> PathBuf {
let absolute = std::path::absolute(dir).unwrap_or_else(|_| dir.to_path_buf());
if absolute.is_absolute() {
if let Some(hit) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(&absolute).cloned() {
return hit;
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking. The cache is keyed on dir as given, so a stale result can come back in two cases:

  • a relative XCL_DXIL_CACHE (e.g. .\dxil) keeps its first canonical result after the current directory changes;
  • a directory later replaced by a junction/symlink keeps its old target, while an alias of it canonicalizes to the new one.

In both cases cache_mutex_name and the flight key no longer match where the files are actually written. Unifying those is the reason normalized_cache_dir exists. At least key the cache on std::path::absolute(dir) (and only cache absolute inputs), and document that links swapped mid-process are not handled.

if let Ok(canonical) = canonicalize(&absolute) {
if absolute.is_absolute() {
let mut g = cache.lock().unwrap_or_else(|e| e.into_inner());
if g.len() < 64 {
g.insert(absolute, canonical.clone());
}
}
return canonical;
}
let absolute = std::path::absolute(dir).unwrap_or_else(|_| dir.to_path_buf());
for ancestor in absolute.ancestors().skip(1) {
if let Ok(canonical) = std::fs::canonicalize(ancestor) {
if let Ok(canonical) = canonicalize(ancestor) {
if let Ok(remainder) = absolute.strip_prefix(ancestor) {
return canonical.join(remainder);
}
Expand All @@ -831,6 +850,17 @@ fn normalized_cache_dir(dir: &Path) -> PathBuf {
absolute
}

pub(crate) fn normalized_cache_dir(dir: &Path) -> PathBuf {
static CACHE: OnceLock<Mutex<HashMap<PathBuf, PathBuf>>> = OnceLock::new();
normalized_cache_dir_in(CACHE.get_or_init(|| Mutex::new(HashMap::new())), dir, |p| std::fs::canonicalize(p))
}

/// Record a DXIL cache hit served from an upper in-memory layer (e.g. passthrough DXIL cache)
/// so `cache_counters()` / `XCL_ACTIVITY` stats remain accurate.
pub(crate) fn record_cache_hit() {
cache_counters().hits.fetch_add(1, Ordering::Relaxed);
}

fn process_cache_lock(file: &Path) -> Result<ProcessCacheLock, String> {
use windows_sys::Win32::Foundation::{CloseHandle, WAIT_ABANDONED, WAIT_OBJECT_0};
use windows_sys::Win32::System::Threading::{CreateMutexW, WaitForSingleObject, INFINITE};
Expand Down Expand Up @@ -1619,4 +1649,34 @@ mod accessor_library_tests {
assert!(!gate.open());
assert!(!gate.close());
}

#[test]
fn normalized_cache_dir_caches_existing_dir_and_retries_missing() {
let cache = Mutex::new(HashMap::new());
let dir = PathBuf::from(r"C:\fake\cache");
let calls = std::sync::atomic::AtomicUsize::new(0);
let first = normalized_cache_dir_in(&cache, &dir, |_| {
calls.fetch_add(1, Ordering::Relaxed);
Ok(PathBuf::from(r"\\?\C:\fake\cache"))
});
let second = normalized_cache_dir_in(&cache, &dir, |_| panic!("existing dir should hit normalized cache"));
assert_eq!(first, PathBuf::from(r"\\?\C:\fake\cache"));
assert_eq!(first, second);
assert_eq!(calls.load(Ordering::Relaxed), 1);

let missing = PathBuf::from(r"C:\fake\missing_dir_xyz");
let miss_calls = std::sync::atomic::AtomicUsize::new(0);
let _ = normalized_cache_dir_in(&cache, &missing, |_| {
miss_calls.fetch_add(1, Ordering::Relaxed);
Err(std::io::Error::new(std::io::ErrorKind::NotFound, "missing"))
});
let after_first = miss_calls.load(Ordering::Relaxed);
assert!(after_first >= 1);
let _ = normalized_cache_dir_in(&cache, &missing, |_| {
miss_calls.fetch_add(1, Ordering::Relaxed);
Err(std::io::Error::new(std::io::ErrorKind::NotFound, "missing"))
});
assert!(cache.lock().unwrap().get(&missing).is_none(), "non-existent dir must not be cached");
assert!(miss_calls.load(Ordering::Relaxed) > after_first, "missing dir must retry canonicalize on second lookup");
}
}
80 changes: 74 additions & 6 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1071,9 +1071,45 @@ pub struct TwoPass {
pub samplers: Vec<StaticSampler>,
}

type PassthroughKey = (PathBuf, &'static str, String);

fn compile_passthrough_cached_in(
cache: &Mutex<HashMap<PassthroughKey, Vec<u8>>>,
cache_dir: PathBuf,
hlsl: &str,
profile: &'static str,
on_hit: impl FnOnce(),
compile: impl FnOnce() -> Result<Vec<u8>, String>,
) -> Result<Vec<u8>, String> {
let key = (cache_dir, profile, hlsl.to_string());
if let Some(hit) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(&key).cloned() {
on_hit();
return Ok(hit);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking. A RAM hit returns before dxc::compile_cached runs, so after the first compile of a passthrough MS/GS shader:

  • the DXIL cache counters (cache_counters() hits/compilations, which feed XCL_ACTIVITY and the report stats) stop counting these shaders;
  • the key doesn't include cache_dir(). If XCL_DXIL_CACHE changes inside the process, the new directory never gets the ms_6_6/gs_6_6 passthrough .dxil. gpu_compute_e2e.rs and gpu_pso_e2e.rs both point XCL_DXIL_CACHE at a cold dir in-process, so a cold-cache test can miss shaders it expects to find written.

Please either key the RAM cache on the resolved cache dir as well (and count a RAM hit as a DXIL cache hit), or move this cache under compile_cached so the disk-cache bookkeeping still runs.

}
let dxil = compile()?;
let mut g = cache.lock().unwrap_or_else(|e| e.into_inner());
if g.len() < 256 {
g.insert(key, dxil.clone());
}
Ok(dxil)
}

fn compile_passthrough_cached(hlsl: &str, profile: &'static str) -> Result<Vec<u8>, String> {
static CACHE: std::sync::OnceLock<Mutex<HashMap<PassthroughKey, Vec<u8>>>> = std::sync::OnceLock::new();
let dir = dxc::normalized_cache_dir(&dxc::cache_dir());
compile_passthrough_cached_in(
CACHE.get_or_init(|| Mutex::new(HashMap::new())),
dir,
hlsl,
profile,
dxc::record_cache_hit,
|| dxc::compile_cached(hlsl, "main", profile).map(|(b, _)| b),
)
}

fn finish_two_pass_compiled(cs: Compiled, record: super::MsInterface, ps: Option<&[u8]>) -> Result<TwoPass, String> {
let ps_inputs = ps.map(|p| crate::gpu::dxbc::signatures(p).0);
let ms = dxc::compile_cached(&super::emit::mesh_passthrough_for(&record, ps_inputs.as_deref()), "main", "ms_6_6")?.0;
let ms = compile_passthrough_cached(&super::emit::mesh_passthrough_for(&record, ps_inputs.as_deref()), "ms_6_6")?;
let mesh_groups_per_record = super::emit::passthrough_split(&record, super::emit::passthrough_elements(&record, ps_inputs.as_deref()));
Ok(TwoPass { cs: cs.dxil, ms, record, mesh_groups_per_record, samplers: cs.samplers })
}
Expand Down Expand Up @@ -1226,10 +1262,7 @@ pub fn console_geometry(vs: &[u8], gs: &[u8], ps: Option<&[u8]>, split_wave64: b
match crate::gpu::dxil::kernel::translate_geometry(&code, o, &g) {
Ok(k) => {
crate::gpu::dxil::coverage::record_translated("GS");
let ps_inputs = ps.map(|p| crate::gpu::dxbc::signatures(p).0);
let msb = dxc::compile_cached(&super::emit::mesh_passthrough_for(&record, ps_inputs.as_deref()), "main", "ms_6_6")?.0;
let mesh_groups_per_record = super::emit::passthrough_split(&record, super::emit::passthrough_elements(&record, ps_inputs.as_deref()));
return Ok(TwoPass { cs: k.dxil, ms: msb, record, mesh_groups_per_record, samplers: k.static_samplers });
return finish_two_pass_compiled(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }, record, ps);
}
Err(e) => direct_fallback("GS", &e),
}
Expand All @@ -1246,7 +1279,7 @@ pub fn rect_list_gs(vs: &[u8]) -> Result<Vec<u8>, String> {
if outputs.is_empty() {
return Err("the VS has no output signature".into());
}
Ok(dxc::compile_cached(&super::emit::rect_list_gs(&outputs), "main", "gs_6_6")?.0)
compile_passthrough_cached(&super::emit::rect_list_gs(&outputs), "gs_6_6")
}

/// XCL shader ABI root signature (see the module docs); `graphics` allows an input layout.
Expand Down Expand Up @@ -2220,6 +2253,41 @@ mod shader_cache_tests {

let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn passthrough_ram_cache_reuses_compiled_dxil_and_does_not_cache_errors() {
let cache = Mutex::new(HashMap::new());
let dir_a = PathBuf::from(r"C:\cache_a");
let dir_b = PathBuf::from(r"C:\cache_b");
let src = "void main() {}";
let mut hits = 0usize;
// Errors (including cached_only deferred misses) must not be cached.
assert!(compile_passthrough_cached_in(&cache, dir_a.clone(), src, "ms_6_6", || hits += 1, || Err("DXIL not compiled yet".into())).is_err());
let mut calls = 0usize;
let first = compile_passthrough_cached_in(&cache, dir_a.clone(), src, "ms_6_6", || hits += 1, || {
calls += 1;
Ok(vec![0x44, 0x58, 0x42, 0x43])
})
.unwrap();
let second = compile_passthrough_cached_in(&cache, dir_a.clone(), src, "ms_6_6", || hits += 1, || {
panic!("second call with identical dir+HLSL+profile must hit RAM cache")
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(hits, 1, "RAM hit must invoke DXIL cache hit accounting");
assert_eq!(first, second);
// Changing cache_dir must miss so cold-cache tests populate the new directory.
let other_dir = compile_passthrough_cached_in(&cache, dir_b, src, "ms_6_6", || hits += 1, || {
calls += 1;
Ok(vec![0x44, 0x58, 0x42, 0x43])
})
.unwrap();
assert_eq!(calls, 2);
assert_eq!(other_dir, first);
// Different profile uses a distinct key.
let gs = compile_passthrough_cached_in(&cache, dir_a, src, "gs_6_6", || hits += 1, || Ok(vec![1, 2, 3, 4])).unwrap();
assert_eq!(gs, vec![1, 2, 3, 4]);
}
}

#[cfg(test)]
Expand Down
Loading