Skip to content
Closed
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
16 changes: 16 additions & 0 deletions crates/xcl/src/gpu/recomp/dxc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,15 @@ pub fn in_cached_only() -> bool {
CACHED_ONLY.with(|c| c.get())
}

/// The cached-only attempt found work that must not run on the title's thread: a shader
/// that is not compiled yet, or the driver's compile of a pipeline. `cached_only`'s
/// second return becomes true.
pub fn defer_to_worker() {
if CACHED_ONLY.with(|c| c.get()) {
MISSED.with(|m| m.set(true));
}
}

pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec<u8>, bool), String> {
compile_cached_in(&cache_dir(), src, entry, profile)
}
Expand Down Expand Up @@ -664,6 +673,13 @@ mod cache_tests {

let (r, missed) = cached_only(|| request(|| panic!("a cached-only miss must not compile")));
assert!(r.is_err() && missed);
let (n, missed) = cached_only(|| {
defer_to_worker();
7
});
assert_eq!(n, 7);
assert!(missed);
assert!(!cached_only(|| 1).1);
assert_eq!(
counters.snapshot(),
CacheStats {
Expand Down
90 changes: 85 additions & 5 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa
return compile_one();
}
static CACHE: OnceLock<Mutex<ShaderCache>> = OnceLock::new();
let cache = CACHE.get_or_init(|| Mutex::new(ShaderCache::new(64 << 20)));
let cache = CACHE.get_or_init(|| Mutex::new(ShaderCache::new(512 << 20)));
let key = ShaderKey {
hash: crate::gpu::shader::fnv64(blob),
stage,
Expand Down Expand Up @@ -229,7 +229,79 @@ mod translated {
}
}

fn blob_disk_key(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> u64 {
let mut h = crate::gpu::shader::fnv64(blob);
h ^= stage as u64;
h = h.wrapping_mul(0x100_0000_01b3);
for b in sampler_base.to_le_bytes().into_iter().chain(windows.to_le_bytes()).chain([split_wave64 as u8]) {
h ^= b as u64;
h = h.wrapping_mul(0x100_0000_01b3);
}
h
}

/// Translation plus DXC, remembered by the console blob. The DXIL cache is keyed by the
/// generated HLSL, so a later launch would otherwise translate every shader again just to
/// find the file it already wrote.
fn load_blob_compiled(key: u64) -> Option<Compiled> {
let bytes = std::fs::read(dxc::cache_dir().join(format!("blob-{key:016x}.xsh"))).ok()?;
if bytes.len() < 12 || &bytes[..4] != b"XSH1" {
return None;
}
let n = u32::from_le_bytes(bytes[4..8].try_into().ok()?) as usize;
if n > 64 {
return None;
}
let samplers_end = 8 + n * 17;
if bytes.len() < samplers_end + 32 {
return None;
}
let mut samplers = Vec::with_capacity(n);
for i in 0..n {
let at = 8 + i * 17;
let mut words = [0u32; 4];
for k in 0..4 {
words[k] = u32::from_le_bytes(bytes[at + k * 4..at + k * 4 + 4].try_into().ok()?);
}
samplers.push((words, bytes[at + 16] != 0));
}
let dxil = bytes[samplers_end..].to_vec();
(&dxil[..4] == b"DXBC").then_some(Compiled { dxil, samplers })
}

fn store_blob_compiled(key: u64, compiled: &Compiled) {
if compiled.samplers.len() > 64 || compiled.dxil.len() < 32 {
return;
}
let dir = dxc::cache_dir();
if std::fs::create_dir_all(&dir).is_err() {
return;
}
let mut body = Vec::with_capacity(8 + compiled.samplers.len() * 17 + compiled.dxil.len());
body.extend_from_slice(b"XSH1");
body.extend_from_slice(&(compiled.samplers.len() as u32).to_le_bytes());
for (words, comparison) in &compiled.samplers {
for word in words {
body.extend_from_slice(&word.to_le_bytes());
}
body.push(*comparison as u8);
}
body.extend_from_slice(&compiled.dxil);
let path = dir.join(format!("blob-{key:016x}.xsh"));
let tmp = path.with_extension(format!("tmp{}", std::process::id()));
if std::fs::write(&tmp, &body).is_ok() && std::fs::rename(&tmp, &path).is_err() {
let _ = std::fs::remove_file(&tmp);
}
}

fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<Compiled, String> {
let disk = cache_allowed(stage, |name| std::env::var_os(name).is_some());
let key = blob_disk_key(blob, stage, sampler_base, windows, split_wave64);
if disk {
if let Some(compiled) = load_blob_compiled(key) {
return Ok(compiled);
}
}
let (mut t, profile) = console_translation(blob, stage, sampler_base, windows, split_wave64)?;
if let Some([r, g, b]) = (stage == Stage::Pixel).then(|| debug_color(blob)).flatten() {
t.hlsl = t.hlsl.replacen(" return xo;\n}", &format!(" xo.t0 = float4({r:.3}, {g:.3}, {b:.3}, 1.0);\n return xo;\n}}"), 1);
Expand Down Expand Up @@ -261,7 +333,11 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows:
t.hlsl = t.hlsl.replacen(" if (!xcl_live) discard;\n return xo;\n}", &format!(" xo.t0 = {expr};\n return xo;\n}}"), 1);
}
let dxil = dxc::compile_cached(&t.hlsl, "main", profile)?.0;
Ok(Compiled { dxil, samplers: t.static_samplers })
let compiled = Compiled { dxil, samplers: t.static_samplers };
if disk {
store_blob_compiled(key, &compiled);
}
Ok(compiled)
}

/// Every `X_T.Sample(args)` of generated HLSL as `X_T.SampleLevel(args, 0.0f)`.
Expand Down Expand Up @@ -347,6 +423,10 @@ impl ShaderEntry {
}
}

/// Shared shaders kept in memory. 128 threw away a title's shaders while it was still
/// creating pipelines, so the same program was translated again and again.
const SHADER_CACHE_ENTRIES: usize = 8192;

struct ShaderCache {
entries: VecDeque<ShaderEntry>,
bytes: usize,
Expand Down Expand Up @@ -381,7 +461,7 @@ impl ShaderCache {
if bytes > self.limit {
return;
}
while self.bytes + bytes > self.limit || self.entries.len() >= 128 {
while self.bytes + bytes > self.limit || self.entries.len() >= SHADER_CACHE_ENTRIES {
let Some(old) = self.entries.pop_front() else {
break;
};
Expand Down Expand Up @@ -778,10 +858,10 @@ mod shader_cache_tests {
assert_eq!(cache.bytes, limit);
assert_eq!(cache.entries.len(), 2);
let mut cache = ShaderCache::new(1 << 20);
for i in 0..129 {
for i in 0..SHADER_CACHE_ENTRIES as u64 + 1 {
cache.insert(key(i), b"a", t.clone());
}
assert_eq!(cache.entries.len(), 128);
assert_eq!(cache.entries.len(), SHADER_CACHE_ENTRIES);
assert!(cache.get(&key(0), b"a").is_none());
}

Expand Down
28 changes: 21 additions & 7 deletions crates/xcl/src/gpu/shader.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
//! Shader capture and classification.
//!
//! Every shader blob a title hands to D3D12.X (pipeline state creation, root
//! signatures) is classified and – once per unique hash – written to
//! `<data>\shaders\`. Unknown formats are scanned for RDNA2 programs and a
//! disassembly is written next to the blob. This is how we learn, per title, whether
//! shaders still carry DXIL/DXBC or only console GPU microcode.
//! signatures) is classified once per unique hash. Writing the blob, the RDNA2
//! disassembly and a second translation to `<data>\shaders\` is `XCL_SHADER_DUMP=1`:
//! that work repeats the pipeline's own translation and is what a cold load spends
//! its time on.

use std::collections::{BTreeMap, HashSet};
use std::path::PathBuf;
Expand Down Expand Up @@ -201,6 +201,16 @@ fn dump_dir() -> PathBuf {
crate::state::data_dir().join("shaders")
}

/// Disk dumps and the extra translation that produces them. Off unless asked: the
/// pipeline path already translates each shader, and doing it again here serialises
/// the load on the title's thread.
fn dump_shaders() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| {
std::env::var("XCL_DUMP_SHADERS").is_ok_and(|v| v == "1") || std::env::var("XCL_SHADER_DUMP").is_ok_and(|v| v == "1")
})
}

/// Is `[p, p+len)` committed, readable memory? (Game-provided pointers may be garbage
/// when our guess of a console struct layout is wrong.)
pub fn readable(p: usize, len: usize) -> bool {
Expand All @@ -225,9 +235,11 @@ pub fn readable(p: usize, len: usize) -> bool {
}

/// Record a shader blob submitted by the title. Safe on garbage pointers.
/// Without `XCL_SHADER_DUMP=1` this returns immediately: copying, hashing and
/// translating every shader here runs on the title thread, ahead of the real pipeline.
pub fn capture(stage: &str, ptr: usize, len: usize) {
if ptr == 0 && len == 0 {
return; // unused stage
if !dump_shaders() || (ptr == 0 && len == 0) {
return;
}
let mut g = STATE.lock().unwrap();
let st = g.get_or_insert_with(|| State { seen: HashSet::new(), stats: ShaderStats::default(), insts: xbox::InstStats::default() });
Expand Down Expand Up @@ -284,7 +296,9 @@ pub fn capture(stage: &str, ptr: usize, len: usize) {
/// program at every start.
fn dumps_enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("XCL_DUMP_SHADERS").is_ok_and(|v| v == "1"))
*ON.get_or_init(|| {
std::env::var("XCL_DUMP_SHADERS").is_ok_and(|v| v == "1") || std::env::var("XCL_SHADER_DUMP").is_ok_and(|v| v == "1")
})
}

/// Console container without dumps: its FSSM variants and instructions accounted.
Expand Down
Loading