From 4b4c08cfe7c8ca21477c03d1958e6b1ba647dd8c Mon Sep 17 00:00:00 2001 From: Jerkin42 <66524771+Jerkin42@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:31:52 +0000 Subject: [PATCH] d3d12: look up cached shaders without scanning the cache directory Wine matches file names without regard to case, so opening a name that is absent reads the whole directory to look for another spelling of it. Every program request asked for several absent names: its session reply (twice), the cache's .sha256 or .unsupported file, and the destination of the rename that published a copy of a cached program to the session directory. With 39,463 files in the ProjectScarlett cache and 13,812 copies in the session directory, the loader threads spent most of their time in those scans: up to 80% busy each, three quarters of it in the kernel, with almost no disk reads. In user space perf showed utf8_mbstowcs, hash_short_file_name and readdir64. List both directories once and open only names they hold. Use the cache's own file instead of a session copy. A translation the host adds after the listing still works: it is requested, and the host answers from its cache. Measured on our tree, an older main with the same change, one run each: from leaving the first screen to the start of streaming, 3 min 45 s became 1 min 16 s, and kernel time over the busy part fell from about 360% to 170% of a core. The second run also had a larger Mesa shader cache limit and the first run's driver cache, so not all of the difference need be this change. Co-Authored-By: Claude Opus 5.5 --- .../d3d12/src/device/shader_cache/compile.rs | 82 ++++++++++++++++--- 1 file changed, 71 insertions(+), 11 deletions(-) diff --git a/runtime/d3d12/src/device/shader_cache/compile.rs b/runtime/d3d12/src/device/shader_cache/compile.rs index c02766db..be73d949 100644 --- a/runtime/d3d12/src/device/shader_cache/compile.rs +++ b/runtime/d3d12/src/device/shader_cache/compile.rs @@ -1,11 +1,12 @@ //! Submit unprofiled console shaders to the running launcher's compiler. use super::{Stage, read_portable_file, source_digest}; use crate::progress::{self, Shader}; +use std::collections::HashSet; use std::fs; use std::io::{self, Read}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{LazyLock, OnceLock}; +use std::sync::{LazyLock, Mutex, MutexGuard, OnceLock}; mod request_locks; use request_locks::RequestLocks; @@ -28,6 +29,36 @@ fn session() -> Option<&'static PathBuf> { .as_ref() } +/// The names in a directory, listed once and then extended by this process. +/// +/// Wine matches names without regard to case. Opening an absent one therefore +/// reads the whole directory to look for another spelling of it, and the cache +/// holds tens of thousands of files. A name the host added after the listing +/// only costs a request, which the host answers from its cache. +struct Names(OnceLock>>); + +impl Names { + const fn new() -> Self { + Self(OnceLock::new()) + } + + fn of(&self, directory: &Path) -> MutexGuard<'_, HashSet> { + self.0 + .get_or_init(|| { + let entries = fs::read_dir(directory).into_iter().flatten().flatten(); + let names = entries.filter_map(|entry| entry.file_name().into_string().ok()); + Mutex::new(names.collect()) + }) + .lock() + .unwrap_or_else(|error| error.into_inner()) + } +} + +/// Files of the compiler's cache. +static CACHED: Names = Names::new(); +/// Replies published in this session. +static REPLIES: Names = Names::new(); + fn read_digest(path: &Path) -> Option<[u8; 64]> { let mut file = fs::File::open(path).ok()?; if file.metadata().ok()?.len() != 64 { @@ -61,6 +92,9 @@ fn compiler_cache(session: &Path) -> Option<&'static PathBuf> { } fn cached_translation(cache: &Path, key: &str, stage: Stage) -> Option> { + if !CACHED.of(cache).contains(&format!("{key}.sha256")) { + return None; + } let file = cache.join(format!("{key}.cso")); let expected = read_digest(&file.with_extension("sha256"))?; let bytes = read_portable_file(&file, stage)?; @@ -70,6 +104,9 @@ fn cached_translation(cache: &Path, key: &str, stage: Stage) -> Option> } fn cached_refusal(cache: &Path, key: &str) -> bool { + if !CACHED.of(cache).contains(&format!("{key}.unsupported")) { + return false; + } let Ok(file) = fs::File::open(cache.join(format!("{key}.unsupported"))) else { return false; }; @@ -134,8 +171,13 @@ fn request( submit: impl FnOnce(&Path, &Path) -> io::Result<()>, ) -> Option> { let dir = session()?; - let result = dir.join(format!("{key}.cso")); - if let Some(bytes) = read_portable_file(&result, stage) { + let name = format!("{key}.cso"); + let result = dir.join(&name); + let reply = || { + let known = REPLIES.of(dir).contains(&name); + if known { read_portable_file(&result, stage) } else { None } + }; + if let Some(bytes) = reply() { progress::record(key, Shader::Cached); return Some(bytes); } @@ -144,7 +186,7 @@ fn request( static LOCKS: LazyLock = LazyLock::new(RequestLocks::default); let lock = LOCKS.for_key(key); let _guard = lock.lock().unwrap_or_else(|error| error.into_inner()); - if let Some(bytes) = read_portable_file(&result, stage) { + if let Some(bytes) = reply() { progress::record(key, Shader::Cached); return Some(bytes); } @@ -152,13 +194,6 @@ fn request( let pending = dir.join(format!("{key}.{}.tmp", std::process::id())); if let Some(cache) = compiler_cache(dir) { if let Some(bytes) = cached_translation(cache, key, stage) { - // Later PSOs in this session can use the verified reply directly. - if fs::write(&pending, &bytes) - .and_then(|()| fs::rename(&pending, &result)) - .is_err() - { - let _ = fs::remove_file(&pending); - } progress::record(key, Shader::Cached); return Some(bytes); } @@ -177,6 +212,7 @@ fn request( // A successful worker may have completed between the first read // and the existence check. Avoid compiling that request twice. if let Some(bytes) = read_portable_file(&result, stage) { + REPLIES.of(dir).insert(name); progress::record(key, Shader::Translated); return Some(bytes); } @@ -192,10 +228,15 @@ fn request( let start = Instant::now(); loop { if let Some(bytes) = read_portable_file(&result, stage) { + REPLIES.of(dir).insert(name); progress::record(key, Shader::Translated); return Some(bytes); } if failed.exists() { + // The host records a refusal in its cache before it reports the failure. + if let Some(cache) = compiler_cache(dir) { + CACHED.of(cache).insert(format!("{key}.unsupported")); + } progress::record(key, Shader::Unsupported); return None; } @@ -206,3 +247,22 @@ fn request( std::thread::sleep(Duration::from_millis(25)); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_directory_is_listed_once_and_extended() { + let dir = std::env::temp_dir().join(format!("tuxbox-names-{}", std::process::id())); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join("a.sha256"), b"").unwrap(); + let names = Names::new(); + assert!(names.of(&dir).contains("a.sha256")); + fs::write(dir.join("b.sha256"), b"").unwrap(); + assert!(!names.of(&dir).contains("b.sha256")); + names.of(&dir).insert("b.sha256".into()); + assert!(names.of(&dir).contains("b.sha256")); + fs::remove_dir_all(&dir).unwrap(); + } +}